Subversion Repositories SmartDukaan

Rev

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