Subversion Repositories SmartDukaan

Rev

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