Subversion Repositories SmartDukaan

Rev

Rev 18096 | Rev 18098 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
15081 amit.gupta 1
from bson import json_util
2
from bson.json_util import dumps
15096 amit.gupta 3
from datetime import datetime, timedelta
15534 amit.gupta 4
from pyshorteners.shorteners  import Shortener
13582 amit.gupta 5
from dtr import main
15081 amit.gupta 6
from dtr.config import PythonPropertyReader
13629 kshitij.so 7
from dtr.storage import Mongo
15132 amit.gupta 8
from dtr.storage.DataService import Retailers, Users, CallHistory, RetryConfig, \
15254 amit.gupta 9
    RetailerLinks, Activation_Codes, Agents, Agent_Roles, AgentLoginTimings, \
15676 amit.gupta 10
    FetchDataHistory, RetailerContacts, Orders, OnboardedRetailerChecklists,\
17467 manas 11
    RetailerAddresses, Pincodeavailability, app_offers, appmasters, user_app_cashbacks, user_app_installs,\
12
    Postoffices
15358 amit.gupta 13
from dtr.storage.Mongo import get_mongo_connection
14
from dtr.storage.Mysql import fetchResult
15081 amit.gupta 15
from dtr.utils import FetchLivePrices, DealSheet as X_DealSheet, \
16
    UserSpecificDeals
18090 manas 17
from dtr.utils.utils import getLogger,encryptMessage,decryptMessage
15081 amit.gupta 18
from elixir import *
15254 amit.gupta 19
from operator import and_
16714 manish.sha 20
from sqlalchemy.sql.expression import func, func, or_, desc, asc, case
15132 amit.gupta 21
from urllib import urlencode
22
import contextlib
13827 kshitij.so 23
import falcon
15081 amit.gupta 24
import json
15358 amit.gupta 25
import re
15254 amit.gupta 26
import string
15081 amit.gupta 27
import traceback
15132 amit.gupta 28
import urllib
29
import urllib2
30
import uuid
15465 amit.gupta 31
import gdshortener
16727 manish.sha 32
from dtr.dao import AppOfferObj, UserAppBatchDrillDown, UserAppBatchDateDrillDown
18097 manas 33
import base64
34
from falcon.util.uri import decode
16631 manish.sha 35
 
15207 amit.gupta 36
alphalist = list(string.uppercase)
37
alphalist.remove('O')
38
numList = ['1','2','3','4','5','6','7','8','9']
39
codesys = [alphalist, alphalist, numList, numList, numList]
15312 amit.gupta 40
CONTACT_PRIORITY = ['sms', 'called', 'ringing']
15368 amit.gupta 41
RETRY_MAP = {'fresh':'retry', 'followup':'fretry', 'onboarding':'oretry'}
15358 amit.gupta 42
ASSIGN_MAP = {'retry':'assigned', 'fretry':'fassigned', 'oretry':'oassigned'}
15207 amit.gupta 43
 
16882 amit.gupta 44
sticky_agents = [17]
45
 
15207 amit.gupta 46
def getNextCode(codesys, code=None):
47
    if code is None:
48
        code = []
49
        for charcode in codesys:
50
            code.append(charcode[0])
51
        return string.join(code, '')
52
    carry = True
53
    code = list(code)
54
    lastindex = len(codesys) - 1
55
    while carry:
56
        listChar = codesys[lastindex]
57
        newIndex = (listChar.index(code[lastindex])+1)%len(listChar)
58
        print newIndex
59
        code[lastindex] = listChar[newIndex]
60
        if newIndex != 0:
61
            carry = False
62
        lastindex -= 1
63
        if lastindex ==-1:
64
            raise BaseException("All codes are exhausted")
65
 
66
    return string.join(code, '')
67
 
68
 
69
 
70
 
15081 amit.gupta 71
global RETAILER_DETAIL_CALL_COUNTER
72
RETAILER_DETAIL_CALL_COUNTER = 0
13572 kshitij.so 73
 
15168 amit.gupta 74
lgr = getLogger('/var/log/retailer-acquisition-api.log')
15081 amit.gupta 75
DEALER_RETRY_FACTOR = int(PythonPropertyReader.getConfig('DEALER_RETRY_FACTOR'))
16886 amit.gupta 76
DEALER_FRESH_FACTOR = int(PythonPropertyReader.getConfig('DEALER_FRESH_FACTOR'))
77
TOTAL = DEALER_RETRY_FACTOR + DEALER_FRESH_FACTOR  
13572 kshitij.so 78
class CategoryDiscountInfo(object):
79
 
80
    def on_get(self, req, resp):
81
 
13629 kshitij.so 82
        result = Mongo.getAllCategoryDiscount()
83
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
84
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 85
 
86
    def on_post(self, req, resp):
87
        try:
88
            result_json = json.loads(req.stream.read(), encoding='utf-8')
89
        except ValueError:
90
            raise falcon.HTTPError(falcon.HTTP_400,
91
                'Malformed JSON',
92
                'Could not decode the request body. The '
93
                'JSON was incorrect.')
94
 
95
        result = Mongo.addCategoryDiscount(result_json)
96
        resp.body = json.dumps(result, encoding='utf-8')
13969 kshitij.so 97
 
98
    def on_put(self, req, resp, _id):
13970 kshitij.so 99
        try:
100
            result_json = json.loads(req.stream.read(), encoding='utf-8')
101
        except ValueError:
102
            raise falcon.HTTPError(falcon.HTTP_400,
103
                'Malformed JSON',
104
                'Could not decode the request body. The '
105
                'JSON was incorrect.')
106
 
107
        result = Mongo.updateCategoryDiscount(result_json, _id)
108
        resp.body = json.dumps(result, encoding='utf-8')
109
 
13966 kshitij.so 110
 
13969 kshitij.so 111
 
13572 kshitij.so 112
class SkuSchemeDetails(object):
113
 
114
    def on_get(self, req, resp):
13629 kshitij.so 115
 
14070 kshitij.so 116
        offset = req.get_param_as_int("offset")
117
        limit = req.get_param_as_int("limit")
118
 
119
        result = Mongo.getAllSkuWiseSchemeDetails(offset, limit)
13629 kshitij.so 120
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
121
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 122
 
123
 
124
    def on_post(self, req, resp):
125
 
14552 kshitij.so 126
        multi = req.get_param_as_int("multi")
127
 
13572 kshitij.so 128
        try:
129
            result_json = json.loads(req.stream.read(), encoding='utf-8')
130
        except ValueError:
131
            raise falcon.HTTPError(falcon.HTTP_400,
132
                'Malformed JSON',
133
                'Could not decode the request body. The '
134
                'JSON was incorrect.')
135
 
15852 kshitij.so 136
        result = Mongo.addSchemeDetailsForSku(result_json)
13572 kshitij.so 137
        resp.body = json.dumps(result, encoding='utf-8')
138
 
139
class SkuDiscountInfo():
140
 
141
    def on_get(self, req, resp):
13629 kshitij.so 142
 
13970 kshitij.so 143
        offset = req.get_param_as_int("offset")
144
        limit = req.get_param_as_int("limit")
145
        result = Mongo.getallSkuDiscountInfo(offset,limit)
13629 kshitij.so 146
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
147
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 148
 
149
 
150
    def on_post(self, req, resp):
151
 
14552 kshitij.so 152
        multi = req.get_param_as_int("multi")
153
 
13572 kshitij.so 154
        try:
155
            result_json = json.loads(req.stream.read(), encoding='utf-8')
156
        except ValueError:
157
            raise falcon.HTTPError(falcon.HTTP_400,
158
                'Malformed JSON',
159
                'Could not decode the request body. The '
160
                'JSON was incorrect.')
161
 
15852 kshitij.so 162
        result = Mongo.addSkuDiscountInfo(result_json)
13572 kshitij.so 163
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 164
 
165
    def on_put(self, req, resp, _id):
166
        try:
167
            result_json = json.loads(req.stream.read(), encoding='utf-8')
168
        except ValueError:
169
            raise falcon.HTTPError(falcon.HTTP_400,
170
                'Malformed JSON',
171
                'Could not decode the request body. The '
172
                'JSON was incorrect.')
173
 
174
        result = Mongo.updateSkuDiscount(result_json, _id)
175
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 176
 
177
class ExceptionalNlc():
178
 
179
    def on_get(self, req, resp):
13629 kshitij.so 180
 
13970 kshitij.so 181
        offset = req.get_param_as_int("offset")
182
        limit = req.get_param_as_int("limit")
183
 
184
        result = Mongo.getAllExceptionlNlcItems(offset, limit)
13629 kshitij.so 185
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
186
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 187
 
188
    def on_post(self, req, resp):
189
 
14552 kshitij.so 190
        multi = req.get_param_as_int("multi")
191
 
13572 kshitij.so 192
        try:
193
            result_json = json.loads(req.stream.read(), encoding='utf-8')
194
        except ValueError:
195
            raise falcon.HTTPError(falcon.HTTP_400,
196
                'Malformed JSON',
197
                'Could not decode the request body. The '
198
                'JSON was incorrect.')
199
 
15852 kshitij.so 200
        result = Mongo.addExceptionalNlc(result_json)
13572 kshitij.so 201
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 202
 
203
    def on_put(self, req, resp, _id):
204
        try:
205
            result_json = json.loads(req.stream.read(), encoding='utf-8')
206
        except ValueError:
207
            raise falcon.HTTPError(falcon.HTTP_400,
208
                'Malformed JSON',
209
                'Could not decode the request body. The '
210
                'JSON was incorrect.')
211
 
212
        result = Mongo.updateExceptionalNlc(result_json, _id)
213
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 214
 
13772 kshitij.so 215
class Deals():
13779 kshitij.so 216
    def on_get(self,req, resp, userId):
217
        categoryId = req.get_param_as_int("categoryId")
218
        offset = req.get_param_as_int("offset")
219
        limit = req.get_param_as_int("limit")
13798 kshitij.so 220
        sort = req.get_param("sort")
13802 kshitij.so 221
        direction = req.get_param_as_int("direction")
14853 kshitij.so 222
        filterData = req.get_param('filterData')
223
        result = Mongo.getNewDeals(int(userId), categoryId, offset, limit, sort, direction, filterData)
16078 kshitij.so 224
        resp.body = dumps(result) 
13790 kshitij.so 225
 
226
class MasterData():
227
    def on_get(self,req, resp, skuId):
16223 kshitij.so 228
        showDp = req.get_param_as_int("showDp")
16221 kshitij.so 229
        result = Mongo.getItem(skuId, showDp)
13798 kshitij.so 230
        try:
231
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 232
            resp.body = json.dumps(json_docs, encoding='utf-8')
13798 kshitij.so 233
        except:
234
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 235
            resp.body = json.dumps(json_docs, encoding='utf-8')
13790 kshitij.so 236
 
14586 kshitij.so 237
    def on_post(self,req, resp):
238
 
239
        addNew = req.get_param_as_int("addNew")
240
        update = req.get_param_as_int("update")
241
        addToExisting = req.get_param_as_int("addToExisting")
242
        multi = req.get_param_as_int("multi")
243
 
14589 kshitij.so 244
        try:
14592 kshitij.so 245
            result_json = json.loads(req.stream.read(), encoding='utf-8')
246
        except ValueError:
247
            raise falcon.HTTPError(falcon.HTTP_400,
248
                'Malformed JSON',
249
                'Could not decode the request body. The '
250
                'JSON was incorrect.')
251
 
252
        if addNew == 1:
253
            result = Mongo.addNewItem(result_json)
254
        elif update == 1:
255
            result = Mongo.updateMaster(result_json, multi)
256
        elif addToExisting == 1:
257
            result = Mongo.addItemToExistingBundle(result_json)
258
        else:
259
            raise
260
        resp.body = dumps(result)
14586 kshitij.so 261
 
13827 kshitij.so 262
class LiveData():
263
    def on_get(self,req, resp):
13865 kshitij.so 264
        if req.get_param_as_int("id") is not None:
265
            print "****getting only for id"
266
            id = req.get_param_as_int("id")
267
            try:
268
                result = FetchLivePrices.getLatestPriceById(id)
13867 kshitij.so 269
                json_docs = json.dumps(result, default=json_util.default)
13966 kshitij.so 270
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 271
            except:
272
                json_docs = json.dumps({}, default=json_util.default)
13966 kshitij.so 273
                resp.body = json.dumps(json_docs, encoding='utf-8')
13834 kshitij.so 274
 
13865 kshitij.so 275
        else:
276
            print "****getting only for skuId"
277
            skuBundleId = req.get_param_as_int("skuBundleId")
278
            source_id = req.get_param_as_int("source_id")
279
            try:
280
                result = FetchLivePrices.getLatestPrice(skuBundleId, source_id)
281
                json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 282
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 283
            except:
284
                json_docs = [json.dumps(doc, default=json_util.default) for doc in [{}]]
13966 kshitij.so 285
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 286
 
13834 kshitij.so 287
class CashBack():
288
    def on_get(self,req, resp):
289
        identifier = req.get_param("identifier")
290
        source_id = req.get_param_as_int("source_id")
291
        try:
13838 kshitij.so 292
            result = Mongo.getCashBackDetails(identifier, source_id)
13837 kshitij.so 293
            json_docs = json.dumps(result, default=json_util.default)
13964 kshitij.so 294
            resp.body = json_docs
13834 kshitij.so 295
        except:
13837 kshitij.so 296
            json_docs = json.dumps({}, default=json_util.default)
13963 kshitij.so 297
            resp.body = json_docs
13892 kshitij.so 298
 
14398 amit.gupta 299
class ImgSrc():
300
    def on_get(self,req, resp):
301
        identifier = req.get_param("identifier")
302
        source_id = req.get_param_as_int("source_id")
303
        try:
304
            result = Mongo.getImgSrc(identifier, source_id)
305
            json_docs = json.dumps(result, default=json_util.default)
306
            resp.body = json_docs
307
        except:
308
            json_docs = json.dumps({}, default=json_util.default)
309
            resp.body = json_docs
310
 
13892 kshitij.so 311
class DealSheet():
312
    def on_get(self,req, resp):
13895 kshitij.so 313
        X_DealSheet.sendMail()
13897 kshitij.so 314
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
13966 kshitij.so 315
        resp.body = json.dumps(json_docs, encoding='utf-8')
13892 kshitij.so 316
 
13970 kshitij.so 317
class DealerPrice():
318
 
319
    def on_get(self, req, resp):
320
 
321
        offset = req.get_param_as_int("offset")
322
        limit = req.get_param_as_int("limit")
323
        result = Mongo.getAllDealerPrices(offset,limit)
324
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
325
        resp.body = json.dumps(json_docs, encoding='utf-8')
326
 
327
    def on_post(self, req, resp):
328
 
14552 kshitij.so 329
        multi = req.get_param_as_int("multi")
330
 
13970 kshitij.so 331
        try:
332
            result_json = json.loads(req.stream.read(), encoding='utf-8')
333
        except ValueError:
334
            raise falcon.HTTPError(falcon.HTTP_400,
335
                'Malformed JSON',
336
                'Could not decode the request body. The '
337
                'JSON was incorrect.')
338
 
15852 kshitij.so 339
        result = Mongo.addSkuDealerPrice(result_json)
13970 kshitij.so 340
        resp.body = json.dumps(result, encoding='utf-8')
341
 
342
    def on_put(self, req, resp, _id):
343
        try:
344
            result_json = json.loads(req.stream.read(), encoding='utf-8')
345
        except ValueError:
346
            raise falcon.HTTPError(falcon.HTTP_400,
347
                'Malformed JSON',
348
                'Could not decode the request body. The '
349
                'JSON was incorrect.')
350
 
351
        result = Mongo.updateSkuDealerPrice(result_json, _id)
352
        resp.body = json.dumps(result, encoding='utf-8')
353
 
354
 
14041 kshitij.so 355
class ResetCache():
356
 
357
    def on_get(self,req, resp, userId):
14044 kshitij.so 358
        result = Mongo.resetCache(userId)
14046 kshitij.so 359
        resp.body = json.dumps(result, encoding='utf-8')
360
 
361
class UserDeals():
362
    def on_get(self,req,resp,userId):
363
        UserSpecificDeals.generateSheet(userId)
364
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
365
        resp.body = json.dumps(json_docs, encoding='utf-8')
14075 kshitij.so 366
 
367
class CommonUpdate():
368
 
369
    def on_post(self,req,resp):
14575 kshitij.so 370
 
371
        multi = req.get_param_as_int("multi")
372
 
14075 kshitij.so 373
        try:
374
            result_json = json.loads(req.stream.read(), encoding='utf-8')
375
        except ValueError:
376
            raise falcon.HTTPError(falcon.HTTP_400,
377
                'Malformed JSON',
378
                'Could not decode the request body. The '
379
                'JSON was incorrect.')
380
 
15852 kshitij.so 381
        result = Mongo.updateCollection(result_json)
14075 kshitij.so 382
        resp.body = json.dumps(result, encoding='utf-8')
14106 kshitij.so 383
        resp.content_type = "application/json; charset=utf-8"
14481 kshitij.so 384
 
385
class NegativeDeals():
386
 
387
    def on_get(self, req, resp):
388
 
389
        offset = req.get_param_as_int("offset")
390
        limit = req.get_param_as_int("limit")
391
 
392
        result = Mongo.getAllNegativeDeals(offset, limit)
14483 kshitij.so 393
        resp.body = dumps(result) 
14481 kshitij.so 394
 
395
 
396
    def on_post(self, req, resp):
397
 
14552 kshitij.so 398
        multi = req.get_param_as_int("multi")
399
 
14481 kshitij.so 400
        try:
401
            result_json = json.loads(req.stream.read(), encoding='utf-8')
402
        except ValueError:
403
            raise falcon.HTTPError(falcon.HTTP_400,
404
                'Malformed JSON',
405
                'Could not decode the request body. The '
406
                'JSON was incorrect.')
407
 
14552 kshitij.so 408
        result = Mongo.addNegativeDeals(result_json, multi)
14481 kshitij.so 409
        resp.body = json.dumps(result, encoding='utf-8')
410
 
411
class ManualDeals():
412
 
413
    def on_get(self, req, resp):
414
 
415
        offset = req.get_param_as_int("offset")
416
        limit = req.get_param_as_int("limit")
417
 
418
        result = Mongo.getAllManualDeals(offset, limit)
14483 kshitij.so 419
        resp.body = dumps(result)
14481 kshitij.so 420
 
421
 
422
    def on_post(self, req, resp):
423
 
14552 kshitij.so 424
        multi = req.get_param_as_int("multi")
425
 
14481 kshitij.so 426
        try:
427
            result_json = json.loads(req.stream.read(), encoding='utf-8')
428
        except ValueError:
429
            raise falcon.HTTPError(falcon.HTTP_400,
430
                'Malformed JSON',
431
                'Could not decode the request body. The '
432
                'JSON was incorrect.')
433
 
14552 kshitij.so 434
        result = Mongo.addManualDeal(result_json, multi)
14481 kshitij.so 435
        resp.body = json.dumps(result, encoding='utf-8')
436
 
437
class CommonDelete():
14482 kshitij.so 438
 
14481 kshitij.so 439
    def on_post(self,req,resp):
440
        try:
441
            result_json = json.loads(req.stream.read(), encoding='utf-8')
442
        except ValueError:
443
            raise falcon.HTTPError(falcon.HTTP_400,
444
                'Malformed JSON',
445
                'Could not decode the request body. The '
446
                'JSON was incorrect.')
447
 
448
        result = Mongo.deleteDocument(result_json)
449
        resp.body = json.dumps(result, encoding='utf-8')
450
        resp.content_type = "application/json; charset=utf-8"
14482 kshitij.so 451
 
452
class SearchProduct():
453
 
454
    def on_get(self,req,resp):
455
        offset = req.get_param_as_int("offset")
456
        limit = req.get_param_as_int("limit")
457
        search_term = req.get_param("search")
458
 
459
        result = Mongo.searchMaster(offset, limit, search_term)
14483 kshitij.so 460
        resp.body = dumps(result) 
14482 kshitij.so 461
 
462
 
14495 kshitij.so 463
class FeaturedDeals():
14482 kshitij.so 464
 
14495 kshitij.so 465
    def on_get(self, req, resp):
466
 
467
        offset = req.get_param_as_int("offset")
468
        limit = req.get_param_as_int("limit")
469
 
470
        result = Mongo.getAllFeaturedDeals(offset, limit)
471
        resp.body = dumps(result)
472
 
473
 
474
    def on_post(self, req, resp):
475
 
14552 kshitij.so 476
        multi = req.get_param_as_int("multi")
477
 
14495 kshitij.so 478
        try:
479
            result_json = json.loads(req.stream.read(), encoding='utf-8')
480
        except ValueError:
481
            raise falcon.HTTPError(falcon.HTTP_400,
482
                'Malformed JSON',
483
                'Could not decode the request body. The '
484
                'JSON was incorrect.')
485
 
14552 kshitij.so 486
        result = Mongo.addFeaturedDeal(result_json, multi)
14495 kshitij.so 487
        resp.body = json.dumps(result, encoding='utf-8')
488
 
14497 kshitij.so 489
 
490
class CommonSearch():
14495 kshitij.so 491
 
14497 kshitij.so 492
    def on_get(self,req,resp):
493
        class_name = req.get_param("class")
494
        sku = req.get_param_as_int("sku")
495
        skuBundleId = req.get_param_as_int("skuBundleId")
14499 kshitij.so 496
 
497
        result = Mongo.searchCollection(class_name, sku, skuBundleId)
14497 kshitij.so 498
        resp.body = dumps(result)
14619 kshitij.so 499
 
500
class CricScore():
501
 
502
    def on_get(self,req,resp):
503
 
504
        result = Mongo.getLiveCricScore()
14853 kshitij.so 505
        resp.body = dumps(result)
506
 
507
class Notification():
508
 
509
    def on_post(self, req, resp):
510
 
511
        try:
512
            result_json = json.loads(req.stream.read(), encoding='utf-8')
513
        except ValueError:
514
            raise falcon.HTTPError(falcon.HTTP_400,
515
                'Malformed JSON',
516
                'Could not decode the request body. The '
517
                'JSON was incorrect.')
518
 
519
        result = Mongo.addBundleToNotification(result_json)
520
        resp.body = json.dumps(result, encoding='utf-8')
521
 
522
    def on_get(self, req, resp):
523
 
524
        offset = req.get_param_as_int("offset")
525
        limit = req.get_param_as_int("limit")
526
 
527
        result = Mongo.getAllNotifications(offset, limit)
528
        resp.body = dumps(result)
529
 
14998 kshitij.so 530
class DealBrands():
14853 kshitij.so 531
 
14998 kshitij.so 532
    def on_get(self, req, resp):
533
 
534
        category_id = req.get_param_as_int("category_id")
535
        result = Mongo.getBrandsForFilter(category_id)
14999 kshitij.so 536
        resp.body = dumps(result)
15161 kshitij.so 537
 
538
class DealRank():
14998 kshitij.so 539
 
15161 kshitij.so 540
    def on_get(self, req, resp):
541
        identifier = req.get_param("identifier")
542
        source_id = req.get_param_as_int("source_id")
543
        user_id = req.get_param_as_int("user_id")
544
        result = Mongo.getDealRank(identifier, source_id, user_id)
545
        json_docs = json.dumps(result, default=json_util.default)
546
        resp.body = json_docs
547
 
548
 
16560 amit.gupta 549
class OrderedOffers():
550
    def on_get(self, req, resp, storeId, storeSku):
551
        storeId = int(storeId)
16563 amit.gupta 552
        result = Mongo.getBundleBySourceSku(storeId, storeSku)
553
        json_docs = json.dumps(result, default=json_util.default)
554
        resp.body = json_docs
555
 
15081 amit.gupta 556
class RetailerDetail():
557
    global RETAILER_DETAIL_CALL_COUNTER
15105 amit.gupta 558
    def getRetryRetailer(self,failback=True):
15358 amit.gupta 559
        status = RETRY_MAP.get(self.callType)
17089 amit.gupta 560
        retailer = session.query(Retailers).filter_by(status=status).filter(Retailers.next_call_time<=datetime.now()).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None)).order_by(Retailers.agent_id.desc(),Retailers.call_priority).order_by(Retailers.next_call_time).with_lockmode("update").first()
17029 amit.gupta 561
 
15239 amit.gupta 562
        if retailer is not None:
563
            lgr.info( "getRetryRetailer " + str(retailer.id))
564
        else:
565
            if failback:
566
                retailer = self.getNewRetailer(False)
567
                return retailer
16371 amit.gupta 568
            else:
569
                #No further calls for now
570
                return None
15358 amit.gupta 571
        retailer.status = ASSIGN_MAP.get(status)
16371 amit.gupta 572
        retailer.next_call_time = None
15239 amit.gupta 573
        lgr.info( "getRetryRetailer " + str(retailer.id))
15081 amit.gupta 574
        return retailer
575
 
15662 amit.gupta 576
    def getNotActiveRetailer(self):
577
        try:
15716 amit.gupta 578
            user = session.query(Users).filter_by(activated=0).filter_by(status=1).filter(Users.mobile_number != None).filter(~Users.mobile_number.like("0%")).filter(Users.created>datetime(2015,06,29)).order_by(Users.created.desc()).with_lockmode("update").first()
15662 amit.gupta 579
            if user is None: 
580
                return None
581
            else:
582
                retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
583
                if retailerContact is not None:
584
                    retailer = session.query(Retailers).filter_by(id=retailerContact.retailer_id).first()
585
                else:
586
                    retailer = session.query(Retailers).filter_by(contact1=user.mobile_number).first()
587
                    if retailer is None:
588
                        retailer = session.query(Retailers).filter_by(contact2=user.mobile_number).first()
589
                        if retailer is None:
590
                            retailer = Retailers()
591
                            retailer.contact1 = user.mobile_number
592
                            retailer.status = 'assigned'
15672 amit.gupta 593
                            retailer.retry_count = 0
15673 amit.gupta 594
                            retailer.invalid_retry_count = 0
15699 amit.gupta 595
                            retailer.is_elavated=1
15662 amit.gupta 596
                user.status = 2
597
                session.commit()
598
                print "retailer id", retailer.id
599
                retailer.contact = user.mobile_number
600
                return retailer
601
        finally:
602
            session.close()
603
 
15081 amit.gupta 604
    def getNewRetailer(self,failback=True):
15663 amit.gupta 605
        if self.callType == 'fresh':
606
            retailer = self.getNotActiveRetailer()
607
            if retailer is not None:
608
                return retailer
15081 amit.gupta 609
        retry = True
610
        retailer = None 
611
        try:
612
            while(retry):
15168 amit.gupta 613
                lgr.info( "Calltype " + self.callType)
15081 amit.gupta 614
                status=self.callType
15545 amit.gupta 615
                query = session.query(Retailers).filter(Retailers.status==status).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None))
15081 amit.gupta 616
                if status=='fresh':
17030 amit.gupta 617
                    query = query.filter_by(is_or=False, is_std=False).filter(Retailers.pin==Pincodeavailability.code).filter(Pincodeavailability.amount > 19999).order_by(Retailers.is_elavated.desc(), Retailers.agent_id.desc())
15358 amit.gupta 618
                elif status=='followup':
15546 amit.gupta 619
                    query = query.filter(Retailers.next_call_time<=datetime.now()).order_by(Retailers.agent_id.desc(),Retailers.next_call_time)
15162 amit.gupta 620
                else:
15546 amit.gupta 621
                    query = query.filter(Retailers.modified<=datetime.now()).order_by(Retailers.agent_id.desc(), Retailers.modified)
15358 amit.gupta 622
 
15081 amit.gupta 623
                retailer = query.with_lockmode("update").first()
624
                if retailer is not None:
15168 amit.gupta 625
                    lgr.info( "retailer " +str(retailer.id))
15081 amit.gupta 626
                    if status=="fresh":
627
                        userquery = session.query(Users)
628
                        if retailer.contact2 is not None:
629
                            userquery = userquery.filter(Users.mobile_number.in_([retailer.contact1,retailer.contact2]))
630
                        else:
631
                            userquery = userquery.filter_by(mobile_number=retailer.contact1)
632
                        user = userquery.first()
633
                        if user is not None:
634
                            retailer.status = 'alreadyuser'
15168 amit.gupta 635
                            lgr.info( "retailer.status " + retailer.status)
15081 amit.gupta 636
                            session.commit()
637
                            continue
638
                        retailer.status = 'assigned'
15358 amit.gupta 639
                    elif status=='followup':
15276 amit.gupta 640
                        if isActivated(retailer.id):
641
                            print "Retailer Already %d activated and marked onboarded"%(retailer.id)
642
                            continue
15081 amit.gupta 643
                        retailer.status = 'fassigned'
15358 amit.gupta 644
                    else:
645
                        retailer.status = 'oassigned'
15081 amit.gupta 646
                    retailer.retry_count = 0
15123 amit.gupta 647
                    retailer.invalid_retry_count = 0
15168 amit.gupta 648
                    lgr.info( "Found Retailer " +  str(retailer.id) + " with status " + status + " assigned to " + str(self.agentId))
15081 amit.gupta 649
 
650
                else:
15168 amit.gupta 651
                    lgr.info( "No fresh/followup retailers found")
15081 amit.gupta 652
                    if failback:
653
                        retailer = self.getRetryRetailer(False)
15104 amit.gupta 654
                        return retailer
15148 amit.gupta 655
                retry=False
15081 amit.gupta 656
        except:
657
            print traceback.print_exc()
658
        return retailer
659
 
15132 amit.gupta 660
    def on_get(self, req, resp, agentId, callType=None, retailerId=None):
16927 amit.gupta 661
        try:
662
            global RETAILER_DETAIL_CALL_COUNTER
663
            RETAILER_DETAIL_CALL_COUNTER += 1
664
            lgr.info( "RETAILER_DETAIL_CALL_COUNTER " +  str(RETAILER_DETAIL_CALL_COUNTER))
665
            self.agentId = int(agentId)
666
            self.callType = callType
667
            if retailerId is not None:
668
                self.retailerId = int(retailerId)
669
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=self.retailerId).first()
670
                if retailerLink is not None:
671
                    code = retailerLink.code
672
                else: 
673
                    code = self.getCode()
674
                    retailerLink = RetailerLinks()
675
                    retailerLink.code = code
676
                    retailerLink.agent_id = self.agentId
677
                    retailerLink.retailer_id = self.retailerId
678
 
679
                    activationCode=Activation_Codes()
680
                    activationCode.code = code
681
                    session.commit()
682
                session.close()
683
                resp.body =  json.dumps({"result":{"code":code,"link":make_tiny(code)}}, encoding='utf-8')
684
                return 
685
            retryFlag = False 
686
            if RETAILER_DETAIL_CALL_COUNTER % TOTAL >= DEALER_FRESH_FACTOR:
687
                retryFlag=True
688
            try:
689
                if retryFlag:
690
                    retailer = self.getRetryRetailer()
691
                else:
692
                    retailer = self.getNewRetailer()
693
                if retailer is None:
694
                    resp.body = "{}"
695
                    return
696
                fetchInfo = FetchDataHistory()
697
                fetchInfo.agent_id = self.agentId
698
                fetchInfo.call_type = self.callType
699
                agent = session.query(Agents).filter_by(id=self.agentId).first()
700
                last_disposition = session.query(CallHistory).filter_by(agent_id=self.agentId).order_by(CallHistory.id.desc()).first()
701
                if last_disposition is None or last_disposition.created < agent.last_login:
702
                    fetchInfo.last_action = 'login'
703
                    fetchInfo.last_action_time = agent.last_login 
704
                else:
705
                    fetchInfo.last_action = 'disposition'
706
                    fetchInfo.last_action_time = last_disposition.created
707
                fetchInfo.retailer_id = retailer.id
708
                session.commit()
15135 amit.gupta 709
 
16927 amit.gupta 710
                otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
711
                resp.body = json.dumps(todict(getRetailerObj(retailer, otherContacts, self.callType)), encoding='utf-8')
712
 
713
                return
714
 
715
            finally:
716
                session.close()
717
 
15343 amit.gupta 718
            if retailer is None:
719
                resp.body = "{}"
15239 amit.gupta 720
            else:
16927 amit.gupta 721
                print "It should never come here"
722
                resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
15239 amit.gupta 723
        finally:
724
            session.close()
15081 amit.gupta 725
 
726
    def on_post(self, req, resp, agentId, callType):
15112 amit.gupta 727
        returned = False
15081 amit.gupta 728
        self.agentId = int(agentId)
729
        self.callType = callType
730
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15169 amit.gupta 731
        lgr.info( "Request ----\n"  + str(jsonReq))
15091 amit.gupta 732
        self.jsonReq = jsonReq
733
        invalidNumber = self.invalidNumber
734
        callLater = self.callLater
15096 amit.gupta 735
        alreadyUser = self.alReadyUser
15091 amit.gupta 736
        verifiedLinkSent = self.verifiedLinkSent
15368 amit.gupta 737
        onboarded = self.onboarded
15278 amit.gupta 738
        self.address = jsonReq.get('address')
15096 amit.gupta 739
        self.retailerId = int(jsonReq.get('retailerid'))
15671 amit.gupta 740
        self.smsNumber = jsonReq.get('smsnumber')
741
        if self.smsNumber is not None:
742
            self.smsNumber = self.smsNumber.strip().lstrip("0") 
15112 amit.gupta 743
        try:
744
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
15281 amit.gupta 745
            if self.address:
15278 amit.gupta 746
                self.retailer.address_new = self.address
15112 amit.gupta 747
            self.callDisposition = jsonReq.get('calldispositiontype')
748
            self.callHistory = CallHistory()
749
            self.callHistory.agent_id=self.agentId
750
            self.callHistory.call_disposition = self.callDisposition
751
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 752
            self.callHistory.call_type=self.callType
15112 amit.gupta 753
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
754
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 755
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
756
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 757
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
758
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 759
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 760
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
15368 amit.gupta 761
            if self.callDisposition == 'onboarded':
762
                self.checkList = jsonReq.get('checklist')
763
 
15234 amit.gupta 764
            if lastFetchData is None:
765
                raise
766
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 767
 
768
            dispositionMap = {  'call_later':callLater,
769
                        'ringing_no_answer':callLater,
770
                        'not_reachable':callLater,
771
                        'switch_off':callLater,
15202 manas 772
                        'not_retailer':invalidNumber,
15112 amit.gupta 773
                        'invalid_no':invalidNumber,
774
                        'wrong_no':invalidNumber,
775
                        'hang_up':invalidNumber,
776
                        'retailer_not_interested':invalidNumber,
15200 manas 777
                        'recharge_retailer':invalidNumber,
778
                        'accessory_retailer':invalidNumber,
779
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 780
                        'alreadyuser':alreadyUser,
15368 amit.gupta 781
                        'verified_link_sent':verifiedLinkSent,
782
                        'onboarded':onboarded
15112 amit.gupta 783
                      }
784
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
785
        finally:
786
            session.close()
15096 amit.gupta 787
 
15112 amit.gupta 788
        if returned:
789
            resp.body = "{\"result\":\"success\"}"
790
        else:
791
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 792
 
15091 amit.gupta 793
    def invalidNumber(self,):
15108 manas 794
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
795
        if self.callDisposition == 'invalid_no':
796
            self.retailer.status='failed'
797
            self.callHistory.disposition_description = 'Invalid Number'
798
        elif self.callDisposition == 'wrong_no':
15111 manas 799
            self.retailer.status='failed'
800
            self.callHistory.disposition_description = 'Wrong Number'
801
        elif self.callDisposition == 'hang_up':
802
            self.retailer.status='failed'
803
            self.callHistory.disposition_description = 'Hang Up'
804
        elif self.callDisposition == 'retailer_not_interested':
805
            self.retailer.status='failed'
806
            if self.callHistory.disposition_description is None:
807
                self.callHistory.disposition_description = 'NA'
15200 manas 808
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
809
        elif self.callDisposition == 'recharge_retailer':
810
            self.retailer.status='failed'
811
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
812
        elif self.callDisposition == 'accessory_retailer':
813
            self.retailer.status='failed'
814
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
815
        elif self.callDisposition == 'service_center_retailer':
816
            self.retailer.status='failed'
817
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 818
        elif self.callDisposition == 'not_retailer':
819
            self.retailer.status='failed'
820
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 821
        session.commit()
822
        return True   
823
 
15132 amit.gupta 824
    def getCode(self,):
15207 amit.gupta 825
        newCode = None
826
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
827
        if lastLink is not None:
828
            if len(lastLink.code)==len(codesys):
829
                newCode=lastLink.code
830
        return getNextCode(codesys, newCode)
15108 manas 831
 
15254 amit.gupta 832
 
15091 amit.gupta 833
    def callLater(self,):
15368 amit.gupta 834
        self.retailer.status = RETRY_MAP.get(self.callType)
15100 amit.gupta 835
        self.retailer.call_priority = None
15096 amit.gupta 836
        if self.callDisposition == 'call_later':
15100 amit.gupta 837
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 838
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 839
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
840
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
841
            else:
15102 amit.gupta 842
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 843
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 844
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
845
        else: 
846
            if self.callDisposition == 'ringing_no_answer':
847
                if self.retailer.disposition == 'ringing_no_answer':
848
                    self.retailer.retry_count += 1
849
                else:
850
                    self.retailer.disposition = 'ringing_no_answer'
851
                    self.retailer.retry_count = 1
852
            else:
853
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 854
                    pass
15112 amit.gupta 855
                else:
15119 amit.gupta 856
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 857
                self.retailer.retry_count += 1
858
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 859
 
15122 amit.gupta 860
            retryConfig = session.query(RetryConfig).filter_by(call_type=self.callType, disposition_type=self.retailer.disposition, retry_count=self.retailer.retry_count).first()
15112 amit.gupta 861
            if retryConfig is not None:
862
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 863
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 864
            else:
865
                self.retailer.status = 'failed'
866
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 867
 
15101 amit.gupta 868
        session.commit()
869
        return True
15096 amit.gupta 870
 
15100 amit.gupta 871
 
15091 amit.gupta 872
    def alReadyUser(self,):
15112 amit.gupta 873
        self.retailer.status = self.callDisposition
15117 amit.gupta 874
        if self.callHistory.disposition_description is None:
875
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 876
        session.commit()
877
        return True
15091 amit.gupta 878
    def verifiedLinkSent(self,):
15147 amit.gupta 879
        if self.callType == 'fresh':
880
            self.retailer.status = 'followup'
16882 amit.gupta 881
            if self.retailer.agent_id not in sticky_agents:
882
                self.retailer.agent_id = None
15147 amit.gupta 883
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
884
            self.callHistory.disposition_description = 'App link sent via ' + self.callHistory.disposition_description+ '. followup on' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S') 
885
        else:
15224 amit.gupta 886
            self.retailer.status = 'followup'
16882 amit.gupta 887
            if self.retailer.agent_id not in sticky_agents:
888
                self.retailer.agent_id = None
15147 amit.gupta 889
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
15254 amit.gupta 890
            self.callHistory.disposition_description = 'App link sent via' + self.callHistory.disposition_description + '. Followup again on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15328 amit.gupta 891
        addContactToRetailer(self.agentId, self.retailerId, self.smsNumber, self.callType, 'sms')     
15146 amit.gupta 892
        session.commit()
893
        return True
15368 amit.gupta 894
    def onboarded(self,):
895
        self.retailer.status = self.callDisposition
896
        checkList = OnboardedRetailerChecklists()
897
        checkList.contact_us = self.checkList.get('contactus')
15390 amit.gupta 898
        checkList.doa_return_policy = self.checkList.get('doareturnpolicy')
15368 amit.gupta 899
        checkList.number_verification = self.checkList.get('numberverification')
900
        checkList.payment_option = self.checkList.get('paymentoption')
901
        checkList.preferences = self.checkList.get('preferences')
902
        checkList.product_info = self.checkList.get('productinfo')
15372 amit.gupta 903
        checkList.redeem = self.checkList.get('redeem')
15368 amit.gupta 904
        checkList.retailer_id = self.retailerId
905
        session.commit()
906
        return True
907
 
908
 
15254 amit.gupta 909
def isActivated(retailerId):
15276 amit.gupta 910
    retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailerId).first()
15448 amit.gupta 911
    user = session.query(Users).filter(or_(func.lower(Users.referrer)==retailerLink.code.lower(), Users.utm_campaign==retailerLink.code)).first()
15276 amit.gupta 912
    if user is None:
913
        mobileNumbers = list(session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailerId).all())
914
        user = session.query(Users).filter(Users.mobile_number.in_(mobileNumbers)).first()
15254 amit.gupta 915
        if user is None:
15332 amit.gupta 916
            if retailerLink.created < datetime(2015,5,26):
15333 amit.gupta 917
                historyNumbers = [number for number, in session.query(CallHistory.mobile_number).filter_by(retailer_id = retailerId).all()]
15476 amit.gupta 918
                user = session.query(Users).filter(Users.mobile_number.in_(historyNumbers)).first()
15332 amit.gupta 919
                if user is None:
920
                    return False
15334 amit.gupta 921
                else:
922
                    mapped_with = 'contact'
15332 amit.gupta 923
            else:
924
                return False
15276 amit.gupta 925
        else:
926
            mapped_with = 'contact'
927
    else:
928
        mapped_with = 'code'
929
    retailerLink.mapped_with = mapped_with
15388 amit.gupta 930
    if user.activation_time is not None:
15448 amit.gupta 931
        retailerLink.activated = user.activation_time
932
    retailerLink.activated = user.created
15276 amit.gupta 933
    retailerLink.user_id = user.id
15291 amit.gupta 934
    retailer = session.query(Retailers).filter_by(id=retailerId).first()
15574 amit.gupta 935
    if retailer.status == 'followup' or retailer.status == 'fretry':
15389 amit.gupta 936
        retailer.status = 'onboarding'
16882 amit.gupta 937
        if retailer.agent_id not in sticky_agents:
938
                retailer.agent_id = None
15391 amit.gupta 939
        retailer.call_priority = None
940
        retailer.next_call_time = None
941
        retailer.retry_count = 0
942
        retailer.invalid_retry_count = 0
15276 amit.gupta 943
    session.commit()
15287 amit.gupta 944
    print "retailerLink.retailer_id", retailerLink.retailer_id
15700 amit.gupta 945
    print "retailer", retailer.id
15276 amit.gupta 946
    session.close()
947
    return True
15254 amit.gupta 948
 
949
class AddContactToRetailer():
950
    def on_post(self,req,resp, agentId):
951
        agentId = int(agentId)
952
        try:
953
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
954
            retailerId = int(jsonReq.get("retailerid"))
955
            mobile = jsonReq.get("mobile")
956
            callType = jsonReq.get("calltype")
957
            contactType = jsonReq.get("contacttype")
958
            addContactToRetailer(agentId, retailerId, mobile, callType, contactType)
959
            session.commit()
960
        finally:
961
            session.close()
15676 amit.gupta 962
 
15677 amit.gupta 963
class AddAddressToRetailer():
15676 amit.gupta 964
    def on_post(self,req,resp, agentId):
965
        agentId = int(agentId)
15678 amit.gupta 966
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
967
        retailerId = int(jsonReq.get("retailerid"))
15684 amit.gupta 968
        address = str(jsonReq.get("address"))
969
        storeName = str(jsonReq.get("storename"))
970
        pin = str(jsonReq.get("pin"))
971
        city = str(jsonReq.get("city"))
972
        state = str(jsonReq.get("state"))
973
        updateType = str(jsonReq.get("updatetype"))
15678 amit.gupta 974
        addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType)
15254 amit.gupta 975
 
976
def addContactToRetailer(agentId, retailerId, mobile, callType, contactType):
15312 amit.gupta 977
    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=retailerId).filter_by(mobile_number=mobile).first()
978
    if retailerContact is None:
15254 amit.gupta 979
        retailerContact = RetailerContacts()
15256 amit.gupta 980
        retailerContact.retailer_id = retailerId
15254 amit.gupta 981
        retailerContact.agent_id = agentId
982
        retailerContact.call_type = callType
983
        retailerContact.contact_type = contactType
984
        retailerContact.mobile_number = mobile
15312 amit.gupta 985
    else:
15327 amit.gupta 986
        if CONTACT_PRIORITY.index(retailerContact.contact_type) > CONTACT_PRIORITY.index(contactType):
15358 amit.gupta 987
            retailerContact.contact_type = contactType
15676 amit.gupta 988
 
989
def addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType):
15679 amit.gupta 990
    print "I am in addAddress"
15682 amit.gupta 991
    print agentId, retailerId, address, storeName, pin, city, state, updateType
15679 amit.gupta 992
    try:
993
        if updateType=='new':
15685 amit.gupta 994
            retailer = session.query(Retailers).filter_by(id=retailerId).first()
15679 amit.gupta 995
            retailer.address = address
996
            retailer.title = storeName
997
            retailer.city = city
998
            retailer.state = state
999
            retailer.pin = pin
1000
        raddress = RetailerAddresses()
1001
        raddress.address = address
15682 amit.gupta 1002
        raddress.title = storeName
15679 amit.gupta 1003
        raddress.agent_id = agentId
1004
        raddress.city = city
1005
        raddress.pin = pin
1006
        raddress.retailer_id = retailerId
1007
        raddress.state = state
1008
        session.commit()
1009
    finally:
1010
        session.close() 
15254 amit.gupta 1011
 
15312 amit.gupta 1012
 
15189 manas 1013
class Login():
1014
 
1015
    def on_get(self, req, resp, agentId, role):
1016
        try:
15198 manas 1017
            self.agentId = int(agentId)
1018
            self.role = role
1019
            print str(self.agentId) + self.role;
15199 manas 1020
            agents=AgentLoginTimings()
1021
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
1022
            print 'lastLogintime' + str(lastLoginTime)
1023
            agents.loginTime=lastLoginTime.last_login
1024
            agents.logoutTime=datetime.now()
1025
            agents.role =self.role
15282 amit.gupta 1026
            agents.agent_id = self.agentId
15199 manas 1027
            session.add(agents)    
1028
            session.commit()
1029
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 1030
        finally:
1031
            session.close()        
15112 amit.gupta 1032
 
15189 manas 1033
    def on_post(self,req,resp):
1034
        try:
1035
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1036
            lgr.info( "Request ----\n"  + str(jsonReq))
1037
            email=jsonReq.get('email')
1038
            password = jsonReq.get('password')
1039
            role=jsonReq.get('role')    
15531 amit.gupta 1040
            agent = session.query(Agents).filter(and_(Agents.email==email,Agents.password==password)).first()
1041
            if agent is None:
15189 manas 1042
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
1043
            else:
15531 amit.gupta 1044
                print agent.id
1045
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==agent.id,Agent_Roles.role==role)).first()
15189 manas 1046
                if checkRole is None:
1047
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
1048
                else:
15531 amit.gupta 1049
                    agent.last_login = datetime.now()
1050
                    agent.login_type = role
1051
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":agent.id}}, encoding='utf-8')
1052
                    session.commit()
15195 manas 1053
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 1054
        finally:
1055
            session.close()    
1056
 
15195 manas 1057
    def test(self,email,password,role):
15189 manas 1058
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
1059
        if checkUser is None:
1060
            print checkUser
15195 manas 1061
 
15189 manas 1062
        else:
1063
            print checkUser[0]
1064
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
1065
            if checkRole is None:
15195 manas 1066
                pass
15189 manas 1067
            else:
15195 manas 1068
                agents=AgentLoginTimings()
1069
                agents.loginTime=datetime.now()
1070
                agents.logoutTime=datetime.now()
1071
                agents.role =role
1072
                agents.agent_id = 2
1073
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
1074
                session.add(agents)    
1075
                session.commit()
1076
                session.close()
1077
 
1078
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15275 amit.gupta 1079
 
1080
class RetailerActivation():
1081
    def on_get(self, req, resp, userId):
15351 amit.gupta 1082
        res =  markDealerActivation(int(userId))
1083
        if res:
1084
            resp.body = "{\"activated\":true}"
1085
        else:
1086
            resp.body = "{\"activated\":false}"
1087
 
15275 amit.gupta 1088
 
1089
def markDealerActivation(userId):
1090
    try:
15343 amit.gupta 1091
        user = session.query(Users).filter_by(id=userId).first()
15275 amit.gupta 1092
        result = False                
1093
        mappedWith = 'contact'
15534 amit.gupta 1094
        retailer = None
15275 amit.gupta 1095
        if user is not None:
15454 amit.gupta 1096
            referrer = None if user.referrer is None else user.referrer.upper()
1097
            retailerLink = session.query(RetailerLinks).filter(or_(RetailerLinks.code==referrer, RetailerLinks.code==user.utm_campaign)).first()
15275 amit.gupta 1098
            if retailerLink is None:
15501 amit.gupta 1099
                if user.mobile_number is not None:
1100
                    retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
1101
                    if retailerContact is None:
15613 amit.gupta 1102
                        retailer = session.query(Retailers).filter(Retailers.status.in_(['followup', 'fretry', 'fdone'])).filter(or_(Retailers.contact1==user.mobile_number,Retailers.contact2==user.mobile_number)).first()
15501 amit.gupta 1103
                    else:
1104
                        retailer = session.query(Retailers).filter_by(id = retailerContact.retailer_id).first()
15275 amit.gupta 1105
            else:
1106
                retailer = session.query(Retailers).filter_by(id = retailerLink.retailer_id).first()
1107
                mappedWith='code'
1108
            if retailer is not None:
1109
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailer.id).first()
1110
                if retailerLink is not None:
1111
                    retailerLink.user_id = user.id
1112
                    retailerLink.mapped_with=mappedWith
15358 amit.gupta 1113
                    retailer.status = 'onboarding'
15275 amit.gupta 1114
                    result = True
1115
                    session.commit()
15574 amit.gupta 1116
        return result
15275 amit.gupta 1117
    finally:
1118
        session.close()
1119
 
15189 manas 1120
 
15081 amit.gupta 1121
def todict(obj, classkey=None):
1122
    if isinstance(obj, dict):
1123
        data = {}
1124
        for (k, v) in obj.items():
1125
            data[k] = todict(v, classkey)
1126
        return data
1127
    elif hasattr(obj, "_ast"):
1128
        return todict(obj._ast())
1129
    elif hasattr(obj, "__iter__"):
1130
        return [todict(v, classkey) for v in obj]
1131
    elif hasattr(obj, "__dict__"):
1132
        data = dict([(key, todict(value, classkey)) 
1133
            for key, value in obj.__dict__.iteritems() 
1134
            if not callable(value) and not key.startswith('_')])
1135
        if classkey is not None and hasattr(obj, "__class__"):
1136
            data[classkey] = obj.__class__.__name__
1137
        return data
1138
    else:
1139
        return obj
1140
 
15358 amit.gupta 1141
def getRetailerObj(retailer, otherContacts1=None, callType=None):
15324 amit.gupta 1142
    print "before otherContacts1",otherContacts1
1143
    otherContacts = [] if otherContacts1 is None else otherContacts1
15662 amit.gupta 1144
    print "after otherContacts1",otherContacts
15081 amit.gupta 1145
    obj = Mock()
15280 amit.gupta 1146
    obj.id = retailer.id
15686 amit.gupta 1147
 
1148
 
15314 amit.gupta 1149
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts:
15315 amit.gupta 1150
        otherContacts.append(retailer.contact1)
15314 amit.gupta 1151
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts:
15315 amit.gupta 1152
        otherContacts.append(retailer.contact2)
15323 amit.gupta 1153
    obj.contact1 = None if len(otherContacts)==0 else otherContacts[0]
15325 amit.gupta 1154
    if obj.contact1 is not None:
1155
        obj.contact2 = None if len(otherContacts)==1 else otherContacts[1]
15096 amit.gupta 1156
    obj.scheduled = (retailer.call_priority is not None)
15686 amit.gupta 1157
    address = None
1158
    try:
1159
        address = session.query(RetailerAddresses).filter_by(retailer_id=retailer.id).order_by(RetailerAddresses.created.desc()).first()
1160
    finally:
1161
        session.close()
1162
    if address is not None:
1163
        obj.address = address.address
1164
        obj.title = address.title
1165
        obj.city = address.city
1166
        obj.state = address.state
1167
        obj.pin = address.pin 
1168
    else:
1169
        obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
1170
        obj.title = retailer.title
1171
        obj.city = retailer.city
1172
        obj.state = retailer.state
1173
        obj.pin = retailer.pin 
15699 amit.gupta 1174
    obj.status = retailer.status
15686 amit.gupta 1175
 
15662 amit.gupta 1176
    if hasattr(retailer, 'contact'):
1177
        obj.contact = retailer.contact
15358 amit.gupta 1178
    if callType == 'onboarding':
1179
        try:
15364 amit.gupta 1180
            userId, activatedTime = session.query(RetailerLinks.user_id, RetailerLinks.activated).filter(RetailerLinks.retailer_id==retailer.id).first()
15366 amit.gupta 1181
            activated, = session.query(Users.activation_time).filter(Users.id==userId).first()
15364 amit.gupta 1182
            if activated is not None:
15366 amit.gupta 1183
                activatedTime = activated
15362 amit.gupta 1184
            obj.user_id = userId
15364 amit.gupta 1185
            obj.created = datetime.strftime(activatedTime, '%d/%m/%Y %H:%M:%S')
15358 amit.gupta 1186
            result = fetchResult("select * from useractive where user_id=%d"%(userId))
1187
            if result == ():
1188
                obj.last_active = None
1189
            else:
15360 amit.gupta 1190
                obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
15361 amit.gupta 1191
            ordersCount = session.query(Orders).filter_by(user_id = userId).filter(~Orders.status.in_(['ORDER_NOT_CREATED_KNOWN', 'ORDER_ALREADY_CREATED_IGNORED'])).count()
15358 amit.gupta 1192
            obj.orders = ordersCount
1193
        finally:
1194
            session.close()
15081 amit.gupta 1195
    return obj
15091 amit.gupta 1196
 
15132 amit.gupta 1197
def make_tiny(code):
16939 manish.sha 1198
    url = 'https://play.google.com/store/apps/details?id=com.saholic.profittill&referrer=utm_source%3D0%26utm_medium%3DCRM%26utm_term%3D001%26utm_campaign%3D' + code
16881 manas 1199
    #url='https://play.google.com/store/apps/details?id=com.saholic.profittill&referrer=utm_source=0&utm_medium=CRM&utm_term=001&utm_campaign='+code
16939 manish.sha 1200
    #marketUrl='market://details?id=com.saholic.profittill&referrer=utm_source=0&utm_medium=CRM&utm_term=001&utm_campaign='+code
1201
    #url = urllib.quote(marketUrl)
15465 amit.gupta 1202
    #request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1203
    #filehandle = urllib2.Request(request_url)
1204
    #x= urllib2.urlopen(filehandle)
15546 amit.gupta 1205
    try:
1206
        shortener = Shortener('TinyurlShortener')
1207
        returnUrl =  shortener.short(url)
1208
    except:
1209
        shortener = Shortener('SentalaShortener')
1210
        returnlUrl =  shortener.short(url)
1211
    return returnUrl
15171 amit.gupta 1212
 
15285 manas 1213
class SearchUser():
1214
 
1215
    def on_post(self, req, resp, agentId, searchType):
15314 amit.gupta 1216
        retailersJsonArray = []
15285 manas 1217
        try:
1218
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1219
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1220
            contact=jsonReq.get('searchTerm')
15285 manas 1221
            if(searchType=="number"):
15312 amit.gupta 1222
                retailer_ids = session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all()
1223
                retailer_ids = [r for r, in retailer_ids]    
1224
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact, Retailers.id.in_(retailer_ids))
1225
            else:
1226
                m = re.match("(.*?)(\d{6})(.*?)", contact)
1227
                if m is not None:
1228
                    pin = m.group(2)
1229
                    contact = m.group(1) if m.group(1) != '' else m.group(3)
15313 amit.gupta 1230
                    anotherCondition = and_(Retailers.title.ilike('%%%s%%'%(contact)), Retailers.pin==pin)
15312 amit.gupta 1231
                else:
1232
                    anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1233
 
15326 amit.gupta 1234
            retailers = session.query(Retailers).filter(anotherCondition).limit(20).all()
15312 amit.gupta 1235
            if retailers is None:
15285 manas 1236
                resp.body = json.dumps("{}")
15312 amit.gupta 1237
            else:
1238
                for retailer in retailers:
15326 amit.gupta 1239
                    otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
15314 amit.gupta 1240
                    retailersJsonArray.append(todict(getRetailerObj(retailer, otherContacts)))    
1241
            resp.body = json.dumps({"Retailers":retailersJsonArray}, encoding='utf-8')
15312 amit.gupta 1242
            return
15285 manas 1243
        finally:
1244
            session.close()
15171 amit.gupta 1245
 
15081 amit.gupta 1246
 
1247
class Mock(object):
1248
    pass
15189 manas 1249
 
15312 amit.gupta 1250
def tagActivatedReatilers():
15613 amit.gupta 1251
    retailerIds = [r for  r, in session.query(RetailerLinks.retailer_id).filter_by(user_id = None).all()]
15312 amit.gupta 1252
    session.close()
15288 amit.gupta 1253
    for retailerId in retailerIds:
1254
        isActivated(retailerId)
15312 amit.gupta 1255
    session.close()
15374 kshitij.so 1256
 
1257
class StaticDeals():
1258
 
1259
    def on_get(self, req, resp):
1260
 
1261
        offset = req.get_param_as_int("offset")
1262
        limit = req.get_param_as_int("limit")
1263
        categoryId = req.get_param_as_int("categoryId")
15458 kshitij.so 1264
        direction = req.get_param_as_int("direction")
15374 kshitij.so 1265
 
15458 kshitij.so 1266
        result = Mongo.getStaticDeals(offset, limit, categoryId, direction)
15374 kshitij.so 1267
        resp.body = dumps(result)
1268
 
16366 kshitij.so 1269
class DealNotification():
1270
 
1271
    def on_get(self,req,resp,skuBundleIds):
1272
        result = Mongo.getDealsForNotification(skuBundleIds)
1273
        resp.body = dumps(result)
16487 kshitij.so 1274
 
1275
class DealPoints():
1276
 
1277
    def on_get(self, req, resp):
16366 kshitij.so 1278
 
16487 kshitij.so 1279
        offset = req.get_param_as_int("offset")
1280
        limit = req.get_param_as_int("limit")
1281
 
1282
        result = Mongo.getAllBundlesWithDealPoints(offset, limit)
1283
        resp.body = dumps(result)
15374 kshitij.so 1284
 
16487 kshitij.so 1285
 
1286
    def on_post(self, req, resp):
1287
 
1288
 
1289
        try:
1290
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1291
        except ValueError:
1292
            raise falcon.HTTPError(falcon.HTTP_400,
1293
                'Malformed JSON',
1294
                'Could not decode the request body. The '
1295
                'JSON was incorrect.')
1296
 
1297
        result = Mongo.addDealPoints(result_json)
1298
        resp.body = json.dumps(result, encoding='utf-8')
15374 kshitij.so 1299
 
16545 kshitij.so 1300
class AppAffiliates():
1301
 
1302
    def on_get(self, req, resp, retailerId, appId):
1303
        retailerId = int(retailerId)
1304
        appId = int(appId)
16554 kshitij.so 1305
        call_back = req.get_param("callback")
16545 kshitij.so 1306
        result = Mongo.generateRedirectUrl(retailerId, appId)
16555 kshitij.so 1307
        resp.body = call_back+'('+str(result)+')'
16557 kshitij.so 1308
 
1309
class AffiliatePayout():
1310
    def on_get(self, req, resp):
1311
        payout = req.get_param("payout")
1312
        transaction_id = req.get_param("transaction_id")
1313
        result = Mongo.addPayout(payout, transaction_id)
1314
        resp.body = str(result)
1315
 
16581 manish.sha 1316
class AppOffers():
1317
    def on_get(self, req, resp, retailerId):
16895 manish.sha 1318
        try:            
1319
            result = Mongo.getAppOffers(retailerId)
1320
            offerids = result.values()
1321
            if offerids is None or len(offerids)==0:
16887 kshitij.so 1322
                resp.body = json.dumps("{}")
1323
            else:
16941 manish.sha 1324
                appOffers = session.query(app_offers.id,app_offers.appmaster_id, app_offers.app_name, app_offers.affiliate_offer_id, app_offers.image_url, app_offers.downloads, app_offers.link, app_offers.offer_price, app_offers.offerCategory, app_offers.package_name, app_offers.promoImage, app_offers.ratings, case([(app_offers.override_payout == True, app_offers.overriden_payout)], else_=app_offers.user_payout).label('user_payout'), case([(appmasters.shortDescription != None, appmasters.shortDescription)], else_=None).label('shortDescription'), case([(appmasters.longDescription != None, appmasters.longDescription)], else_=None).label('longDescription'), appmasters.customerOneLiner, appmasters.retailerOneLiner,appmasters.rank, app_offers.offerCondition, app_offers.location).join((appmasters,appmasters.id==app_offers.appmaster_id)).filter(app_offers.id.in_(tuple(offerids))).all()
16895 manish.sha 1325
                appOffersMap = {}
1326
                jsonOffersArray=[]
1327
                for offer in appOffers:
1328
                    appOffersMap[long(offer[0])]= AppOfferObj(offer[0], offer[1], offer[2], offer[3], offer[4], offer[5], offer[6], offer[7], offer[8], offer[9], offer[10], offer[11], offer[12], offer[13], offer[14], offer[15], offer[16], offer[17], offer[18], offer[19]).__dict__
1329
                for rank in sorted(result):
1330
                    print 'Rank', rank, 'Data', appOffersMap[result[rank]]
1331
                    jsonOffersArray.append(appOffersMap[result[rank]])
1332
 
1333
            resp.body = json.dumps({"AppOffers":jsonOffersArray}, encoding='latin1')
16887 kshitij.so 1334
        finally:
1335
            session.close()
1336
 
16727 manish.sha 1337
 
1338
class AppUserBatchRefund():
1339
    def on_get(self, req, resp, batchId, userId):
16887 kshitij.so 1340
        try:
1341
            batchId = long(batchId)
1342
            userId = long(userId)
1343
            userBatchCashback = user_app_cashbacks.get_by(user_id=userId, batchCreditId=batchId)
1344
            if userBatchCashback is None:
1345
                resp.body = json.dumps("{}")
1346
            else:
16905 manish.sha 1347
                if userBatchCashback.creditedDate is not None:
1348
                    userBatchCashback.creditedDate = str(userBatchCashback.creditedDate)
16887 kshitij.so 1349
                resp.body = json.dumps(todict(userBatchCashback), encoding='utf-8')
1350
        finally:
1351
            session.close()
16727 manish.sha 1352
 
1353
class AppUserBatchDrillDown():
16777 manish.sha 1354
    def on_get(self, req, resp, fortNightOfYear, userId, yearVal):
16887 kshitij.so 1355
        try:
1356
            fortNightOfYear = long(fortNightOfYear)
1357
            userId = long(userId)
1358
            yearVal = long(yearVal)
1359
            appUserBatchDrillDown = session.query(user_app_installs.transaction_date, func.sum(user_app_installs.installCount).label('downloads'), func.sum(user_app_installs.payoutAmount).label('amount')).join((user_app_cashbacks,user_app_cashbacks.user_id==user_app_installs.user_id)).filter(user_app_cashbacks.fortnightOfYear==user_app_installs.fortnightOfYear).filter(user_app_cashbacks.user_id==userId).filter(user_app_cashbacks.yearVal==yearVal).filter(user_app_cashbacks.fortnightOfYear==fortNightOfYear).group_by(user_app_installs.transaction_date).all()
1360
            cashbackArray = []
1361
            if appUserBatchDrillDown is None or len(appUserBatchDrillDown)==0:
1362
                resp.body = json.dumps("{}")
1363
            else:
1364
                for appcashBack in appUserBatchDrillDown:
1365
                    userAppBatchDrillDown = UserAppBatchDrillDown(str(appcashBack[0]),long(appcashBack[1]), long(appcashBack[2]))
1366
                    cashbackArray.append(todict(userAppBatchDrillDown))
1367
                resp.body = json.dumps({"UserAppCashBackInBatch":cashbackArray}, encoding='utf-8')
1368
        finally:
1369
            session.close()
16727 manish.sha 1370
 
1371
class AppUserBatchDateDrillDown():
1372
    def on_get(self, req, resp, userId, date):
16887 kshitij.so 1373
        try:
1374
            userId = long(userId)
1375
            date = str(date)
1376
            date = datetime.strptime(date, '%Y-%m-%d')
1377
            appUserBatchDateDrillDown = session.query(user_app_installs.app_name, func.sum(user_app_installs.installCount).label('downloads'), func.sum(user_app_installs.payoutAmount).label('amount')).filter(user_app_installs.user_id==userId).filter(user_app_installs.transaction_date==date).group_by(user_app_installs.app_name).all()
1378
            cashbackArray = []
1379
            if appUserBatchDateDrillDown is None or len(appUserBatchDateDrillDown)==0:
1380
                resp.body = json.dumps("{}")
1381
            else:
1382
                for appcashBack in appUserBatchDateDrillDown:
1383
                    userAppBatchDateDrillDown = UserAppBatchDateDrillDown(str(appcashBack[0]),long(appcashBack[1]),long(appcashBack[2]))
1384
                    cashbackArray.append(todict(userAppBatchDateDrillDown))
1385
                resp.body = json.dumps({"UserAppCashBackDateWise":cashbackArray}, encoding='utf-8')
1386
        finally:
1387
            session.close()
16739 manish.sha 1388
 
16748 manish.sha 1389
class AppUserCashBack():
1390
    def on_get(self, req, resp, userId, status):
16887 kshitij.so 1391
        try:
1392
            userId = long(userId)
1393
            status = str(status)
1394
            appUserApprovedCashBacks = user_app_cashbacks.query.filter(user_app_cashbacks.user_id==userId).filter(user_app_cashbacks.status==status).all()
1395
            cashbackArray = []
1396
            if appUserApprovedCashBacks is None or len(appUserApprovedCashBacks)==0:
1397
                resp.body = json.dumps("{}")
1398
            else:
1399
                totalAmount = 0                
1400
                for appUserApprovedCashBack in appUserApprovedCashBacks:
1401
                    totalAmount = totalAmount + appUserApprovedCashBack.amount
16895 manish.sha 1402
                    if appUserApprovedCashBack.creditedDate is not None:
1403
                        appUserApprovedCashBack.creditedDate = str(appUserApprovedCashBack.creditedDate)  
16905 manish.sha 1404
                    cashbackArray.append(todict(appUserApprovedCashBack)) 
1405
 
16887 kshitij.so 1406
                resp.body = json.dumps({"UserAppCashBack":cashbackArray,"TotalAmount":totalAmount}, encoding='utf-8')
1407
        finally:
1408
            session.close()
17278 naman 1409
 
1410
class GetSaleDetail():
1411
    def on_get(self,req,res,date_val):
1412
        try:
1413
                db = get_mongo_connection()
1414
                sum=0
1415
                count=0
1416
                #print date_val, type(date_val)
1417
                #cursor = db.Dtr.merchantOrder.find({'createdOnInt':{'$lt':long(date_val)},'subOrders':{'$exists':True}})
17315 naman 1418
                cursor = db.Dtr.merchantOrder.find({"$and": [ { "createdOnInt":{"$gt":long(date_val)} }, {"createdOnInt":{"$lt":long(date_val)+86401} } ],"subOrders":{"$exists":True}})
17278 naman 1419
 
1420
                for document in cursor:
1421
                    for doc in document['subOrders']:
1422
                        sum = sum + float(doc['amountPaid'])
1423
                        count = count + int(doc['quantity'])
1424
 
1425
                data = {"amount":sum , "quantity":count}
1426
 
1427
                res.body= json.dumps(data,encoding='utf-8')
1428
        finally:
1429
                session.close()
1430
 
17301 kshitij.so 1431
class DummyDeals():
17304 kshitij.so 1432
    def on_get(self,req, resp):
17301 kshitij.so 1433
        categoryId = req.get_param_as_int("categoryId")
1434
        offset = req.get_param_as_int("offset")
1435
        limit = req.get_param_as_int("limit")
1436
        result = Mongo.getDummyDeals(categoryId, offset, limit)
17556 kshitij.so 1437
        resp.body = dumps(result)
17301 kshitij.so 1438
 
17467 manas 1439
class PincodeValidation():
17498 amit.gupta 1440
    def on_get(self,req,resp,pincode):
17467 manas 1441
        json_data={}
1442
        cities=[]
1443
        print pincode
1444
        if len(str(pincode)) ==6:
17499 amit.gupta 1445
            listCities = list(session.query(Postoffices.taluk,Postoffices.state).distinct().filter(Postoffices.pincode==pincode).filter(Postoffices.taluk!='NA').all())
17467 manas 1446
            if len(listCities)>0:
1447
                for j in listCities:
1448
                    cities.append(j.taluk)
1449
                json_data['cities'] = cities
1450
                json_data['state'] = listCities[0][1]
1451
                resp.body =  json.dumps(json_data)
1452
            else:
1453
                resp.body = json.dumps("{}")       
1454
        else:
1455
            resp.body = json.dumps("{}")
1456
        session.close()
17301 kshitij.so 1457
 
17556 kshitij.so 1458
class SearchDummyDeals():
1459
    def on_get(self,req,resp):
1460
        offset = req.get_param_as_int("offset")
1461
        limit = req.get_param_as_int("limit")
1462
        searchTerm = req.get_param("searchTerm")
1463
        result = Mongo.searchDummyDeals(searchTerm, limit, offset)
1464
        resp.body = dumps(result)
1465
 
1466
class DummyPricing:
17560 kshitij.so 1467
    def on_get(self, req, resp):
17556 kshitij.so 1468
        skuBundleId = req.get_param_as_int("skuBundleId")
1469
        result = Mongo.getDummyPricing(skuBundleId)
1470
        resp.body = dumps(result)
1471
 
1472
class DealObject:
17560 kshitij.so 1473
    def on_post(self, req, resp):
17569 kshitij.so 1474
        update = req.get_param_as_int("update")
17556 kshitij.so 1475
        try:
1476
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1477
        except ValueError:
1478
            raise falcon.HTTPError(falcon.HTTP_400,
1479
                'Malformed JSON',
1480
                'Could not decode the request body. The '
1481
                'JSON was incorrect.')
17569 kshitij.so 1482
        if update is None:    
1483
            result = Mongo.addDealObject(result_json)
1484
        else:
1485
            result = Mongo.updateDealObject(result_json)
1486
 
17556 kshitij.so 1487
        resp.body = dumps(result)
17569 kshitij.so 1488
 
17556 kshitij.so 1489
 
17560 kshitij.so 1490
    def on_get(self, req, resp):
17567 kshitij.so 1491
        edit = req.get_param_as_int("edit")
1492
        if edit is None:
1493
            offset = req.get_param_as_int("offset")
1494
            limit = req.get_param_as_int("limit")
17560 kshitij.so 1495
 
17567 kshitij.so 1496
            result = Mongo.getAllDealObjects(offset, limit)
1497
            resp.body = dumps(result)
1498
        else:
1499
            id = req.get_param_as_int("id")
1500
            result = Mongo.getDealObjectById(id)
1501
            resp.body = dumps(result)
17560 kshitij.so 1502
 
17563 kshitij.so 1503
class DeleteDealObject:
1504
    def on_get(self, req, resp, id):
1505
        result = Mongo.deleteDealObject(int(id))
1506
        resp.body = dumps(result)
1507
 
17611 kshitij.so 1508
class FeaturedDealObject:
1509
    def on_get(self, req, resp):
1510
 
1511
        offset = req.get_param_as_int("offset")
1512
        limit = req.get_param_as_int("limit")
1513
 
1514
        result = Mongo.getAllFeaturedDealsForDealObject(offset, limit)
1515
        resp.body = dumps(result)
1516
 
17556 kshitij.so 1517
 
17611 kshitij.so 1518
    def on_post(self, req, resp):
1519
 
1520
 
1521
        try:
1522
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1523
        except ValueError:
1524
            raise falcon.HTTPError(falcon.HTTP_400,
1525
                'Malformed JSON',
1526
                'Could not decode the request body. The '
1527
                'JSON was incorrect.')
1528
 
17613 kshitij.so 1529
        result = Mongo.addFeaturedDealForDealObject(result_json)
17611 kshitij.so 1530
        resp.body = json.dumps(result, encoding='utf-8')
1531
 
17615 kshitij.so 1532
class DeleteFeaturedDealObject:
1533
    def on_get(self, req, resp, id):
1534
        result = Mongo.deleteFeaturedDealObject(int(id))
1535
        resp.body = dumps(result)
17611 kshitij.so 1536
 
17653 kshitij.so 1537
class SubCategoryFilter:
1538
    def on_get(self, req, resp):
1539
        category_id = req.get_param_as_int("category_id")
1540
        result = Mongo.getSubCategoryForFilter(category_id)
1541
        resp.body = dumps(result)
1542
 
17726 kshitij.so 1543
class DummyLogin:
1544
    def on_post(self,req,resp):
1545
        try:
1546
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1547
        except ValueError:
1548
            raise falcon.HTTPError(falcon.HTTP_400,
1549
                'Malformed JSON',
1550
                'Could not decode the request body. The '
1551
                'JSON was incorrect.')
1552
 
1553
        result = Mongo.dummyLogin(result_json)
1554
        resp.body = json.dumps(result, encoding='utf-8')
17653 kshitij.so 1555
 
17726 kshitij.so 1556
class DummyRegister:
1557
    def on_post(self,req,resp):
1558
        try:
1559
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1560
        except ValueError:
1561
            raise falcon.HTTPError(falcon.HTTP_400,
1562
                'Malformed JSON',
1563
                'Could not decode the request body. The '
1564
                'JSON was incorrect.')
1565
 
1566
        result = Mongo.dummyRegister(result_json)
1567
        resp.body = json.dumps(result, encoding='utf-8')
1568
 
17730 kshitij.so 1569
class UpdateUser:
1570
    def on_post(self,req,resp):
1571
        try:
1572
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1573
        except ValueError:
1574
            raise falcon.HTTPError(falcon.HTTP_400,
1575
                'Malformed JSON',
1576
                'Could not decode the request body. The '
1577
                'JSON was incorrect.')
1578
 
1579
        result = Mongo.updateDummyUser(result_json)
1580
        resp.body = json.dumps(result, encoding='utf-8')
1581
 
1582
class FetchUser:
1583
    def on_get(self,req,resp):
1584
        user_id = req.get_param_as_int("user_id")
1585
        result = Mongo.getDummyUser(user_id)
1586
        resp.body = json.dumps(result, encoding='utf-8')
17928 kshitij.so 1587
 
1588
class SearchSubCategory:
1589
    def on_get(self,req, resp):
18088 kshitij.so 1590
        subCategoryIds = req.get_param("subCategoryId")
17928 kshitij.so 1591
        searchTerm = req.get_param("searchTerm")
1592
        offset = req.get_param_as_int("offset")
1593
        limit = req.get_param_as_int("limit")
17730 kshitij.so 1594
 
18088 kshitij.so 1595
        result = Mongo.getDealsForSearchText(subCategoryIds, searchTerm,offset, limit)
17928 kshitij.so 1596
        resp.body = json.dumps(result, encoding='utf-8')
1597
 
1598
class SearchSubCategoryCount:
1599
    def on_get(self,req, resp):
18088 kshitij.so 1600
        subCategoryIds = req.get_param("subCategoryId")
17928 kshitij.so 1601
        searchTerm = req.get_param("searchTerm")
18088 kshitij.so 1602
        result = Mongo.getCountForSearchText(subCategoryIds, searchTerm)
17928 kshitij.so 1603
        resp.body = json.dumps(result, encoding='utf-8')
18090 manas 1604
 
1605
class MessageEncryption:
1606
 
1607
    def on_get(self,req,resp):
1608
        message_type = req.get_param("type")
18096 manas 1609
        print 'type', message_type
18093 manas 1610
        if message_type == 'encrypt':
18090 manas 1611
            encryption_data = req.get_param("data")
18097 manas 1612
            print 'encryption data ',decode(encryption_data)
1613
            encrypted_data = encryptMessage(decode(encryption_data))
18096 manas 1614
            print 'encrypted data ', encrypted_data
18090 manas 1615
            resp.body =  json.dumps({"result":{"value":encrypted_data}}, encoding='utf-8')
1616
 
18093 manas 1617
        elif message_type == 'decrypt':
18090 manas 1618
            decryption_data = req.get_param("data")
1619
            decrypted_data = decryptMessage(decryption_data)
1620
            print 'In on get of message encryption decrypted', decrypted_data
1621
            resp.body =  json.dumps({"result":{"value":decrypted_data}}, encoding='utf-8')
1622
 
1623
        else:
1624
            resp.body = json.dumps({}, encoding='utf-8')
17556 kshitij.so 1625
 
15312 amit.gupta 1626
def main():
15662 amit.gupta 1627
    #tagActivatedReatilers()
1628
    a = RetailerDetail()
1629
    retailer = a.getNotActiveRetailer()
1630
    otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
1631
    print json.dumps(todict(getRetailerObj(retailer, otherContacts, 'fresh')), encoding='utf-8')
15465 amit.gupta 1632
    #print make_tiny("AA")
15195 manas 1633
 
15081 amit.gupta 1634
if __name__ == '__main__':
15207 amit.gupta 1635
    main()
15091 amit.gupta 1636