Subversion Repositories SmartDukaan

Rev

Rev 15420 | Rev 15454 | 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
13582 amit.gupta 4
from dtr import main
15081 amit.gupta 5
from dtr.config import PythonPropertyReader
13629 kshitij.so 6
from dtr.storage import Mongo
15132 amit.gupta 7
from dtr.storage.DataService import Retailers, Users, CallHistory, RetryConfig, \
15254 amit.gupta 8
    RetailerLinks, Activation_Codes, Agents, Agent_Roles, AgentLoginTimings, \
15368 amit.gupta 9
    FetchDataHistory, RetailerContacts, Orders, OnboardedRetailerChecklists
15358 amit.gupta 10
from dtr.storage.Mongo import get_mongo_connection
11
from dtr.storage.Mysql import fetchResult
15081 amit.gupta 12
from dtr.utils import FetchLivePrices, DealSheet as X_DealSheet, \
13
    UserSpecificDeals
15168 amit.gupta 14
from dtr.utils.utils import getLogger
15081 amit.gupta 15
from elixir import *
15254 amit.gupta 16
from operator import and_
15303 amit.gupta 17
from sqlalchemy.sql.expression import func, func, or_
15132 amit.gupta 18
from urllib import urlencode
19
import contextlib
13827 kshitij.so 20
import falcon
15081 amit.gupta 21
import json
15358 amit.gupta 22
import re
15254 amit.gupta 23
import string
15081 amit.gupta 24
import traceback
15132 amit.gupta 25
import urllib
26
import urllib2
27
import uuid
15207 amit.gupta 28
alphalist = list(string.uppercase)
29
alphalist.remove('O')
30
numList = ['1','2','3','4','5','6','7','8','9']
31
codesys = [alphalist, alphalist, numList, numList, numList]
15312 amit.gupta 32
CONTACT_PRIORITY = ['sms', 'called', 'ringing']
15368 amit.gupta 33
RETRY_MAP = {'fresh':'retry', 'followup':'fretry', 'onboarding':'oretry'}
15358 amit.gupta 34
ASSIGN_MAP = {'retry':'assigned', 'fretry':'fassigned', 'oretry':'oassigned'}
15207 amit.gupta 35
 
36
def getNextCode(codesys, code=None):
37
    if code is None:
38
        code = []
39
        for charcode in codesys:
40
            code.append(charcode[0])
41
        return string.join(code, '')
42
    carry = True
43
    code = list(code)
44
    lastindex = len(codesys) - 1
45
    while carry:
46
        listChar = codesys[lastindex]
47
        newIndex = (listChar.index(code[lastindex])+1)%len(listChar)
48
        print newIndex
49
        code[lastindex] = listChar[newIndex]
50
        if newIndex != 0:
51
            carry = False
52
        lastindex -= 1
53
        if lastindex ==-1:
54
            raise BaseException("All codes are exhausted")
55
 
56
    return string.join(code, '')
57
 
58
 
59
 
60
 
15081 amit.gupta 61
global RETAILER_DETAIL_CALL_COUNTER
62
RETAILER_DETAIL_CALL_COUNTER = 0
13572 kshitij.so 63
 
15168 amit.gupta 64
lgr = getLogger('/var/log/retailer-acquisition-api.log')
15081 amit.gupta 65
DEALER_RETRY_FACTOR = int(PythonPropertyReader.getConfig('DEALER_RETRY_FACTOR'))
13572 kshitij.so 66
class CategoryDiscountInfo(object):
67
 
68
    def on_get(self, req, resp):
69
 
13629 kshitij.so 70
        result = Mongo.getAllCategoryDiscount()
71
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
72
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 73
 
74
    def on_post(self, req, resp):
75
        try:
76
            result_json = json.loads(req.stream.read(), encoding='utf-8')
77
        except ValueError:
78
            raise falcon.HTTPError(falcon.HTTP_400,
79
                'Malformed JSON',
80
                'Could not decode the request body. The '
81
                'JSON was incorrect.')
82
 
83
        result = Mongo.addCategoryDiscount(result_json)
84
        resp.body = json.dumps(result, encoding='utf-8')
13969 kshitij.so 85
 
86
    def on_put(self, req, resp, _id):
13970 kshitij.so 87
        try:
88
            result_json = json.loads(req.stream.read(), encoding='utf-8')
89
        except ValueError:
90
            raise falcon.HTTPError(falcon.HTTP_400,
91
                'Malformed JSON',
92
                'Could not decode the request body. The '
93
                'JSON was incorrect.')
94
 
95
        result = Mongo.updateCategoryDiscount(result_json, _id)
96
        resp.body = json.dumps(result, encoding='utf-8')
97
 
13966 kshitij.so 98
 
13969 kshitij.so 99
 
13572 kshitij.so 100
class SkuSchemeDetails(object):
101
 
102
    def on_get(self, req, resp):
13629 kshitij.so 103
 
14070 kshitij.so 104
        offset = req.get_param_as_int("offset")
105
        limit = req.get_param_as_int("limit")
106
 
107
        result = Mongo.getAllSkuWiseSchemeDetails(offset, limit)
13629 kshitij.so 108
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
109
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 110
 
111
 
112
    def on_post(self, req, resp):
113
 
14552 kshitij.so 114
        multi = req.get_param_as_int("multi")
115
 
13572 kshitij.so 116
        try:
117
            result_json = json.loads(req.stream.read(), encoding='utf-8')
118
        except ValueError:
119
            raise falcon.HTTPError(falcon.HTTP_400,
120
                'Malformed JSON',
121
                'Could not decode the request body. The '
122
                'JSON was incorrect.')
123
 
14552 kshitij.so 124
        result = Mongo.addSchemeDetailsForSku(result_json, multi)
13572 kshitij.so 125
        resp.body = json.dumps(result, encoding='utf-8')
126
 
127
class SkuDiscountInfo():
128
 
129
    def on_get(self, req, resp):
13629 kshitij.so 130
 
13970 kshitij.so 131
        offset = req.get_param_as_int("offset")
132
        limit = req.get_param_as_int("limit")
133
        result = Mongo.getallSkuDiscountInfo(offset,limit)
13629 kshitij.so 134
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
135
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 136
 
137
 
138
    def on_post(self, req, resp):
139
 
14552 kshitij.so 140
        multi = req.get_param_as_int("multi")
141
 
13572 kshitij.so 142
        try:
143
            result_json = json.loads(req.stream.read(), encoding='utf-8')
144
        except ValueError:
145
            raise falcon.HTTPError(falcon.HTTP_400,
146
                'Malformed JSON',
147
                'Could not decode the request body. The '
148
                'JSON was incorrect.')
149
 
14552 kshitij.so 150
        result = Mongo.addSkuDiscountInfo(result_json, multi)
13572 kshitij.so 151
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 152
 
153
    def on_put(self, req, resp, _id):
154
        try:
155
            result_json = json.loads(req.stream.read(), encoding='utf-8')
156
        except ValueError:
157
            raise falcon.HTTPError(falcon.HTTP_400,
158
                'Malformed JSON',
159
                'Could not decode the request body. The '
160
                'JSON was incorrect.')
161
 
162
        result = Mongo.updateSkuDiscount(result_json, _id)
163
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 164
 
165
class ExceptionalNlc():
166
 
167
    def on_get(self, req, resp):
13629 kshitij.so 168
 
13970 kshitij.so 169
        offset = req.get_param_as_int("offset")
170
        limit = req.get_param_as_int("limit")
171
 
172
        result = Mongo.getAllExceptionlNlcItems(offset, limit)
13629 kshitij.so 173
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
174
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 175
 
176
    def on_post(self, req, resp):
177
 
14552 kshitij.so 178
        multi = req.get_param_as_int("multi")
179
 
13572 kshitij.so 180
        try:
181
            result_json = json.loads(req.stream.read(), encoding='utf-8')
182
        except ValueError:
183
            raise falcon.HTTPError(falcon.HTTP_400,
184
                'Malformed JSON',
185
                'Could not decode the request body. The '
186
                'JSON was incorrect.')
187
 
14552 kshitij.so 188
        result = Mongo.addExceptionalNlc(result_json, multi)
13572 kshitij.so 189
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 190
 
191
    def on_put(self, req, resp, _id):
192
        try:
193
            result_json = json.loads(req.stream.read(), encoding='utf-8')
194
        except ValueError:
195
            raise falcon.HTTPError(falcon.HTTP_400,
196
                'Malformed JSON',
197
                'Could not decode the request body. The '
198
                'JSON was incorrect.')
199
 
200
        result = Mongo.updateExceptionalNlc(result_json, _id)
201
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 202
 
13772 kshitij.so 203
class Deals():
13779 kshitij.so 204
    def on_get(self,req, resp, userId):
205
        categoryId = req.get_param_as_int("categoryId")
206
        offset = req.get_param_as_int("offset")
207
        limit = req.get_param_as_int("limit")
13798 kshitij.so 208
        sort = req.get_param("sort")
13802 kshitij.so 209
        direction = req.get_param_as_int("direction")
14853 kshitij.so 210
        filterData = req.get_param('filterData')
211
        result = Mongo.getNewDeals(int(userId), categoryId, offset, limit, sort, direction, filterData)
13772 kshitij.so 212
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 213
        resp.body = json.dumps(json_docs, encoding='utf-8')
13790 kshitij.so 214
 
215
class MasterData():
216
    def on_get(self,req, resp, skuId):
217
        result = Mongo.getItem(skuId)
13798 kshitij.so 218
        try:
219
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 220
            resp.body = json.dumps(json_docs, encoding='utf-8')
13798 kshitij.so 221
        except:
222
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 223
            resp.body = json.dumps(json_docs, encoding='utf-8')
13790 kshitij.so 224
 
14586 kshitij.so 225
    def on_post(self,req, resp):
226
 
227
        addNew = req.get_param_as_int("addNew")
228
        update = req.get_param_as_int("update")
229
        addToExisting = req.get_param_as_int("addToExisting")
230
        multi = req.get_param_as_int("multi")
231
 
14589 kshitij.so 232
        try:
14592 kshitij.so 233
            result_json = json.loads(req.stream.read(), encoding='utf-8')
234
        except ValueError:
235
            raise falcon.HTTPError(falcon.HTTP_400,
236
                'Malformed JSON',
237
                'Could not decode the request body. The '
238
                'JSON was incorrect.')
239
 
240
        if addNew == 1:
241
            result = Mongo.addNewItem(result_json)
242
        elif update == 1:
243
            result = Mongo.updateMaster(result_json, multi)
244
        elif addToExisting == 1:
245
            result = Mongo.addItemToExistingBundle(result_json)
246
        else:
247
            raise
248
        resp.body = dumps(result)
14586 kshitij.so 249
 
13827 kshitij.so 250
class LiveData():
251
    def on_get(self,req, resp):
13865 kshitij.so 252
        if req.get_param_as_int("id") is not None:
253
            print "****getting only for id"
254
            id = req.get_param_as_int("id")
255
            try:
256
                result = FetchLivePrices.getLatestPriceById(id)
13867 kshitij.so 257
                json_docs = json.dumps(result, default=json_util.default)
13966 kshitij.so 258
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 259
            except:
260
                json_docs = json.dumps({}, default=json_util.default)
13966 kshitij.so 261
                resp.body = json.dumps(json_docs, encoding='utf-8')
13834 kshitij.so 262
 
13865 kshitij.so 263
        else:
264
            print "****getting only for skuId"
265
            skuBundleId = req.get_param_as_int("skuBundleId")
266
            source_id = req.get_param_as_int("source_id")
267
            try:
268
                result = FetchLivePrices.getLatestPrice(skuBundleId, source_id)
269
                json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 270
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 271
            except:
272
                json_docs = [json.dumps(doc, default=json_util.default) for doc in [{}]]
13966 kshitij.so 273
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 274
 
13834 kshitij.so 275
class CashBack():
276
    def on_get(self,req, resp):
277
        identifier = req.get_param("identifier")
278
        source_id = req.get_param_as_int("source_id")
279
        try:
13838 kshitij.so 280
            result = Mongo.getCashBackDetails(identifier, source_id)
13837 kshitij.so 281
            json_docs = json.dumps(result, default=json_util.default)
13964 kshitij.so 282
            resp.body = json_docs
13834 kshitij.so 283
        except:
13837 kshitij.so 284
            json_docs = json.dumps({}, default=json_util.default)
13963 kshitij.so 285
            resp.body = json_docs
13892 kshitij.so 286
 
14398 amit.gupta 287
class ImgSrc():
288
    def on_get(self,req, resp):
289
        identifier = req.get_param("identifier")
290
        source_id = req.get_param_as_int("source_id")
291
        try:
292
            result = Mongo.getImgSrc(identifier, source_id)
293
            json_docs = json.dumps(result, default=json_util.default)
294
            resp.body = json_docs
295
        except:
296
            json_docs = json.dumps({}, default=json_util.default)
297
            resp.body = json_docs
298
 
13892 kshitij.so 299
class DealSheet():
300
    def on_get(self,req, resp):
13895 kshitij.so 301
        X_DealSheet.sendMail()
13897 kshitij.so 302
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
13966 kshitij.so 303
        resp.body = json.dumps(json_docs, encoding='utf-8')
13892 kshitij.so 304
 
13970 kshitij.so 305
class DealerPrice():
306
 
307
    def on_get(self, req, resp):
308
 
309
        offset = req.get_param_as_int("offset")
310
        limit = req.get_param_as_int("limit")
311
        result = Mongo.getAllDealerPrices(offset,limit)
312
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
313
        resp.body = json.dumps(json_docs, encoding='utf-8')
314
 
315
    def on_post(self, req, resp):
316
 
14552 kshitij.so 317
        multi = req.get_param_as_int("multi")
318
 
13970 kshitij.so 319
        try:
320
            result_json = json.loads(req.stream.read(), encoding='utf-8')
321
        except ValueError:
322
            raise falcon.HTTPError(falcon.HTTP_400,
323
                'Malformed JSON',
324
                'Could not decode the request body. The '
325
                'JSON was incorrect.')
326
 
14552 kshitij.so 327
        result = Mongo.addSkuDealerPrice(result_json, multi)
13970 kshitij.so 328
        resp.body = json.dumps(result, encoding='utf-8')
329
 
330
    def on_put(self, req, resp, _id):
331
        try:
332
            result_json = json.loads(req.stream.read(), encoding='utf-8')
333
        except ValueError:
334
            raise falcon.HTTPError(falcon.HTTP_400,
335
                'Malformed JSON',
336
                'Could not decode the request body. The '
337
                'JSON was incorrect.')
338
 
339
        result = Mongo.updateSkuDealerPrice(result_json, _id)
340
        resp.body = json.dumps(result, encoding='utf-8')
341
 
342
 
14041 kshitij.so 343
class ResetCache():
344
 
345
    def on_get(self,req, resp, userId):
14044 kshitij.so 346
        result = Mongo.resetCache(userId)
14046 kshitij.so 347
        resp.body = json.dumps(result, encoding='utf-8')
348
 
349
class UserDeals():
350
    def on_get(self,req,resp,userId):
351
        UserSpecificDeals.generateSheet(userId)
352
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
353
        resp.body = json.dumps(json_docs, encoding='utf-8')
14075 kshitij.so 354
 
355
class CommonUpdate():
356
 
357
    def on_post(self,req,resp):
14575 kshitij.so 358
 
359
        multi = req.get_param_as_int("multi")
360
 
14075 kshitij.so 361
        try:
362
            result_json = json.loads(req.stream.read(), encoding='utf-8')
363
        except ValueError:
364
            raise falcon.HTTPError(falcon.HTTP_400,
365
                'Malformed JSON',
366
                'Could not decode the request body. The '
367
                'JSON was incorrect.')
368
 
14575 kshitij.so 369
        result = Mongo.updateCollection(result_json, multi)
14075 kshitij.so 370
        resp.body = json.dumps(result, encoding='utf-8')
14106 kshitij.so 371
        resp.content_type = "application/json; charset=utf-8"
14481 kshitij.so 372
 
373
class NegativeDeals():
374
 
375
    def on_get(self, req, resp):
376
 
377
        offset = req.get_param_as_int("offset")
378
        limit = req.get_param_as_int("limit")
379
 
380
        result = Mongo.getAllNegativeDeals(offset, limit)
14483 kshitij.so 381
        resp.body = dumps(result) 
14481 kshitij.so 382
 
383
 
384
    def on_post(self, req, resp):
385
 
14552 kshitij.so 386
        multi = req.get_param_as_int("multi")
387
 
14481 kshitij.so 388
        try:
389
            result_json = json.loads(req.stream.read(), encoding='utf-8')
390
        except ValueError:
391
            raise falcon.HTTPError(falcon.HTTP_400,
392
                'Malformed JSON',
393
                'Could not decode the request body. The '
394
                'JSON was incorrect.')
395
 
14552 kshitij.so 396
        result = Mongo.addNegativeDeals(result_json, multi)
14481 kshitij.so 397
        resp.body = json.dumps(result, encoding='utf-8')
398
 
399
class ManualDeals():
400
 
401
    def on_get(self, req, resp):
402
 
403
        offset = req.get_param_as_int("offset")
404
        limit = req.get_param_as_int("limit")
405
 
406
        result = Mongo.getAllManualDeals(offset, limit)
14483 kshitij.so 407
        resp.body = dumps(result)
14481 kshitij.so 408
 
409
 
410
    def on_post(self, req, resp):
411
 
14552 kshitij.so 412
        multi = req.get_param_as_int("multi")
413
 
14481 kshitij.so 414
        try:
415
            result_json = json.loads(req.stream.read(), encoding='utf-8')
416
        except ValueError:
417
            raise falcon.HTTPError(falcon.HTTP_400,
418
                'Malformed JSON',
419
                'Could not decode the request body. The '
420
                'JSON was incorrect.')
421
 
14552 kshitij.so 422
        result = Mongo.addManualDeal(result_json, multi)
14481 kshitij.so 423
        resp.body = json.dumps(result, encoding='utf-8')
424
 
425
class CommonDelete():
14482 kshitij.so 426
 
14481 kshitij.so 427
    def on_post(self,req,resp):
428
        try:
429
            result_json = json.loads(req.stream.read(), encoding='utf-8')
430
        except ValueError:
431
            raise falcon.HTTPError(falcon.HTTP_400,
432
                'Malformed JSON',
433
                'Could not decode the request body. The '
434
                'JSON was incorrect.')
435
 
436
        result = Mongo.deleteDocument(result_json)
437
        resp.body = json.dumps(result, encoding='utf-8')
438
        resp.content_type = "application/json; charset=utf-8"
14482 kshitij.so 439
 
440
class SearchProduct():
441
 
442
    def on_get(self,req,resp):
443
        offset = req.get_param_as_int("offset")
444
        limit = req.get_param_as_int("limit")
445
        search_term = req.get_param("search")
446
 
447
        result = Mongo.searchMaster(offset, limit, search_term)
14483 kshitij.so 448
        resp.body = dumps(result) 
14482 kshitij.so 449
 
450
 
14495 kshitij.so 451
class FeaturedDeals():
14482 kshitij.so 452
 
14495 kshitij.so 453
    def on_get(self, req, resp):
454
 
455
        offset = req.get_param_as_int("offset")
456
        limit = req.get_param_as_int("limit")
457
 
458
        result = Mongo.getAllFeaturedDeals(offset, limit)
459
        resp.body = dumps(result)
460
 
461
 
462
    def on_post(self, req, resp):
463
 
14552 kshitij.so 464
        multi = req.get_param_as_int("multi")
465
 
14495 kshitij.so 466
        try:
467
            result_json = json.loads(req.stream.read(), encoding='utf-8')
468
        except ValueError:
469
            raise falcon.HTTPError(falcon.HTTP_400,
470
                'Malformed JSON',
471
                'Could not decode the request body. The '
472
                'JSON was incorrect.')
473
 
14552 kshitij.so 474
        result = Mongo.addFeaturedDeal(result_json, multi)
14495 kshitij.so 475
        resp.body = json.dumps(result, encoding='utf-8')
476
 
14497 kshitij.so 477
 
478
class CommonSearch():
14495 kshitij.so 479
 
14497 kshitij.so 480
    def on_get(self,req,resp):
481
        class_name = req.get_param("class")
482
        sku = req.get_param_as_int("sku")
483
        skuBundleId = req.get_param_as_int("skuBundleId")
14499 kshitij.so 484
 
485
        result = Mongo.searchCollection(class_name, sku, skuBundleId)
14497 kshitij.so 486
        resp.body = dumps(result)
14619 kshitij.so 487
 
488
class CricScore():
489
 
490
    def on_get(self,req,resp):
491
 
492
        result = Mongo.getLiveCricScore()
14853 kshitij.so 493
        resp.body = dumps(result)
494
 
495
class Notification():
496
 
497
    def on_post(self, req, resp):
498
 
499
        try:
500
            result_json = json.loads(req.stream.read(), encoding='utf-8')
501
        except ValueError:
502
            raise falcon.HTTPError(falcon.HTTP_400,
503
                'Malformed JSON',
504
                'Could not decode the request body. The '
505
                'JSON was incorrect.')
506
 
507
        result = Mongo.addBundleToNotification(result_json)
508
        resp.body = json.dumps(result, encoding='utf-8')
509
 
510
    def on_get(self, req, resp):
511
 
512
        offset = req.get_param_as_int("offset")
513
        limit = req.get_param_as_int("limit")
514
 
515
        result = Mongo.getAllNotifications(offset, limit)
516
        resp.body = dumps(result)
517
 
14998 kshitij.so 518
class DealBrands():
14853 kshitij.so 519
 
14998 kshitij.so 520
    def on_get(self, req, resp):
521
 
522
        category_id = req.get_param_as_int("category_id")
523
        result = Mongo.getBrandsForFilter(category_id)
14999 kshitij.so 524
        resp.body = dumps(result)
15161 kshitij.so 525
 
526
class DealRank():
14998 kshitij.so 527
 
15161 kshitij.so 528
    def on_get(self, req, resp):
529
        identifier = req.get_param("identifier")
530
        source_id = req.get_param_as_int("source_id")
531
        user_id = req.get_param_as_int("user_id")
532
        result = Mongo.getDealRank(identifier, source_id, user_id)
533
        json_docs = json.dumps(result, default=json_util.default)
534
        resp.body = json_docs
535
 
536
 
15081 amit.gupta 537
 
538
class RetailerDetail():
539
    global RETAILER_DETAIL_CALL_COUNTER
15105 amit.gupta 540
    def getRetryRetailer(self,failback=True):
15358 amit.gupta 541
        status = RETRY_MAP.get(self.callType)
15239 amit.gupta 542
        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()
543
        if retailer is not None:
544
            lgr.info( "getRetryRetailer " + str(retailer.id))
545
        else:
546
            if failback:
547
                retailer = self.getNewRetailer(False)
548
                return retailer
15358 amit.gupta 549
        retailer.status = ASSIGN_MAP.get(status)
15239 amit.gupta 550
        lgr.info( "getRetryRetailer " + str(retailer.id))
15081 amit.gupta 551
        return retailer
552
 
553
    def getNewRetailer(self,failback=True):
554
        retry = True
555
        retailer = None 
556
        try:
557
            while(retry):
15168 amit.gupta 558
                lgr.info( "Calltype " + self.callType)
15081 amit.gupta 559
                status=self.callType
560
                query = session.query(Retailers).filter(Retailers.status==status)
561
                if status=='fresh':
15172 amit.gupta 562
                    query = query.filter_by(is_or=False, is_std=False).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None)).order_by(Retailers.is_elavated.desc(), -Retailers.agent_id)
15358 amit.gupta 563
                elif status=='followup':
564
                    query = query.filter(Retailers.next_call_time<=datetime.now()).order_by(Retailers.next_call_time)
15162 amit.gupta 565
                else:
15358 amit.gupta 566
                    query = query.filter(Retailers.modified<=datetime.now()).order_by(Retailers.modified)
567
 
15081 amit.gupta 568
                retailer = query.with_lockmode("update").first()
569
                if retailer is not None:
15168 amit.gupta 570
                    lgr.info( "retailer " +str(retailer.id))
15081 amit.gupta 571
                    if status=="fresh":
572
                        userquery = session.query(Users)
573
                        if retailer.contact2 is not None:
574
                            userquery = userquery.filter(Users.mobile_number.in_([retailer.contact1,retailer.contact2]))
575
                        else:
576
                            userquery = userquery.filter_by(mobile_number=retailer.contact1)
577
                        user = userquery.first()
578
                        if user is not None:
579
                            retailer.status = 'alreadyuser'
15168 amit.gupta 580
                            lgr.info( "retailer.status " + retailer.status)
15081 amit.gupta 581
                            session.commit()
582
                            continue
583
                        retailer.status = 'assigned'
15358 amit.gupta 584
                    elif status=='followup':
15276 amit.gupta 585
                        if isActivated(retailer.id):
586
                            print "Retailer Already %d activated and marked onboarded"%(retailer.id)
587
                            continue
15081 amit.gupta 588
                        retailer.status = 'fassigned'
15358 amit.gupta 589
                    else:
590
                        retailer.status = 'oassigned'
15081 amit.gupta 591
                    retailer.retry_count = 0
15123 amit.gupta 592
                    retailer.invalid_retry_count = 0
15168 amit.gupta 593
                    lgr.info( "Found Retailer " +  str(retailer.id) + " with status " + status + " assigned to " + str(self.agentId))
15081 amit.gupta 594
 
595
                else:
15168 amit.gupta 596
                    lgr.info( "No fresh/followup retailers found")
15081 amit.gupta 597
                    if failback:
598
                        retailer = self.getRetryRetailer(False)
15104 amit.gupta 599
                        return retailer
15148 amit.gupta 600
                retry=False
15081 amit.gupta 601
        except:
602
            print traceback.print_exc()
603
        return retailer
604
 
15132 amit.gupta 605
    def on_get(self, req, resp, agentId, callType=None, retailerId=None):
15081 amit.gupta 606
        global RETAILER_DETAIL_CALL_COUNTER
607
        RETAILER_DETAIL_CALL_COUNTER += 1
15168 amit.gupta 608
        lgr.info( "RETAILER_DETAIL_CALL_COUNTER " +  str(RETAILER_DETAIL_CALL_COUNTER))
15081 amit.gupta 609
        self.agentId = int(agentId)
610
        self.callType = callType
15139 amit.gupta 611
        if retailerId is not None:
612
            self.retailerId = int(retailerId)
15208 amit.gupta 613
            retailerLink = session.query(RetailerLinks).filter_by(retailer_id=self.retailerId).first()
15132 amit.gupta 614
            if retailerLink is not None:
615
                code = retailerLink.code
616
            else: 
617
                code = self.getCode()
618
                retailerLink = RetailerLinks()
619
                retailerLink.code = code
15139 amit.gupta 620
                retailerLink.agent_id = self.agentId
621
                retailerLink.retailer_id = self.retailerId
15135 amit.gupta 622
 
623
                activationCode=Activation_Codes()
624
                activationCode.code = code
15132 amit.gupta 625
                session.commit()
626
            session.close()
15142 amit.gupta 627
            resp.body =  json.dumps({"result":{"code":code,"link":make_tiny(code)}}, encoding='utf-8')
15132 amit.gupta 628
            return 
15081 amit.gupta 629
        retryFlag = False 
630
        if RETAILER_DETAIL_CALL_COUNTER % DEALER_RETRY_FACTOR ==0:
631
            retryFlag=True
15239 amit.gupta 632
        try:
633
            if retryFlag:
634
                retailer = self.getRetryRetailer()
635
            else:
636
                retailer = self.getNewRetailer()
15343 amit.gupta 637
            if retailer is None:
638
                resp.body = "{}"
639
                return
15239 amit.gupta 640
            fetchInfo = FetchDataHistory()
641
            fetchInfo.agent_id = self.agentId
642
            fetchInfo.call_type = self.callType
15240 amit.gupta 643
            agent = session.query(Agents).filter_by(id=self.agentId).first()
15239 amit.gupta 644
            last_disposition = session.query(CallHistory).filter_by(agent_id=self.agentId).order_by(CallHistory.id.desc()).first()
645
            if last_disposition is None or last_disposition.created < agent.last_login:
646
                fetchInfo.last_action = 'login'
647
                fetchInfo.last_action_time = agent.last_login 
648
            else:
649
                fetchInfo.last_action = 'disposition'
650
                fetchInfo.last_action_time = last_disposition.created
651
            fetchInfo.retailer_id = retailer.id
652
            session.commit()
15241 amit.gupta 653
 
15358 amit.gupta 654
            otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
655
            resp.body = json.dumps(todict(getRetailerObj(retailer, otherContacts, self.callType)), encoding='utf-8')
15241 amit.gupta 656
 
657
            return
658
 
15239 amit.gupta 659
        finally:
660
            session.close()
15241 amit.gupta 661
 
15081 amit.gupta 662
        if retailer is None:
15157 amit.gupta 663
            resp.body = "{}"
15081 amit.gupta 664
        else:
15358 amit.gupta 665
            print "It should never come here"
15081 amit.gupta 666
            resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
667
 
15241 amit.gupta 668
 
15081 amit.gupta 669
    def on_post(self, req, resp, agentId, callType):
15112 amit.gupta 670
        returned = False
15081 amit.gupta 671
        self.agentId = int(agentId)
672
        self.callType = callType
673
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15169 amit.gupta 674
        lgr.info( "Request ----\n"  + str(jsonReq))
15091 amit.gupta 675
        self.jsonReq = jsonReq
676
        invalidNumber = self.invalidNumber
677
        callLater = self.callLater
15096 amit.gupta 678
        alreadyUser = self.alReadyUser
15091 amit.gupta 679
        verifiedLinkSent = self.verifiedLinkSent
15368 amit.gupta 680
        onboarded = self.onboarded
15278 amit.gupta 681
        self.address = jsonReq.get('address')
15096 amit.gupta 682
        self.retailerId = int(jsonReq.get('retailerid'))
15254 amit.gupta 683
        self.smsNumber = jsonReq.get('smsnumber') 
15112 amit.gupta 684
        try:
685
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
15281 amit.gupta 686
            if self.address:
15278 amit.gupta 687
                self.retailer.address_new = self.address
15112 amit.gupta 688
            self.callDisposition = jsonReq.get('calldispositiontype')
689
            self.callHistory = CallHistory()
690
            self.callHistory.agent_id=self.agentId
691
            self.callHistory.call_disposition = self.callDisposition
692
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 693
            self.callHistory.call_type=self.callType
15112 amit.gupta 694
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
695
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 696
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
697
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 698
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
699
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 700
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 701
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
15368 amit.gupta 702
            if self.callDisposition == 'onboarded':
703
                self.checkList = jsonReq.get('checklist')
704
 
15234 amit.gupta 705
            if lastFetchData is None:
706
                raise
707
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 708
 
709
            dispositionMap = {  'call_later':callLater,
710
                        'ringing_no_answer':callLater,
711
                        'not_reachable':callLater,
712
                        'switch_off':callLater,
15202 manas 713
                        'not_retailer':invalidNumber,
15112 amit.gupta 714
                        'invalid_no':invalidNumber,
715
                        'wrong_no':invalidNumber,
716
                        'hang_up':invalidNumber,
717
                        'retailer_not_interested':invalidNumber,
15200 manas 718
                        'recharge_retailer':invalidNumber,
719
                        'accessory_retailer':invalidNumber,
720
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 721
                        'alreadyuser':alreadyUser,
15368 amit.gupta 722
                        'verified_link_sent':verifiedLinkSent,
723
                        'onboarded':onboarded
15112 amit.gupta 724
                      }
725
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
726
        finally:
727
            session.close()
15096 amit.gupta 728
 
15112 amit.gupta 729
        if returned:
730
            resp.body = "{\"result\":\"success\"}"
731
        else:
732
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 733
 
15091 amit.gupta 734
    def invalidNumber(self,):
15108 manas 735
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
736
        if self.callDisposition == 'invalid_no':
737
            self.retailer.status='failed'
738
            self.callHistory.disposition_description = 'Invalid Number'
739
        elif self.callDisposition == 'wrong_no':
15111 manas 740
            self.retailer.status='failed'
741
            self.callHistory.disposition_description = 'Wrong Number'
742
        elif self.callDisposition == 'hang_up':
743
            self.retailer.status='failed'
744
            self.callHistory.disposition_description = 'Hang Up'
745
        elif self.callDisposition == 'retailer_not_interested':
746
            self.retailer.status='failed'
747
            if self.callHistory.disposition_description is None:
748
                self.callHistory.disposition_description = 'NA'
15200 manas 749
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
750
        elif self.callDisposition == 'recharge_retailer':
751
            self.retailer.status='failed'
752
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
753
        elif self.callDisposition == 'accessory_retailer':
754
            self.retailer.status='failed'
755
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
756
        elif self.callDisposition == 'service_center_retailer':
757
            self.retailer.status='failed'
758
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 759
        elif self.callDisposition == 'not_retailer':
760
            self.retailer.status='failed'
761
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 762
        session.commit()
763
        return True   
764
 
15132 amit.gupta 765
    def getCode(self,):
15207 amit.gupta 766
        newCode = None
767
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
768
        if lastLink is not None:
769
            if len(lastLink.code)==len(codesys):
770
                newCode=lastLink.code
771
        return getNextCode(codesys, newCode)
15108 manas 772
 
15254 amit.gupta 773
 
15091 amit.gupta 774
    def callLater(self,):
15368 amit.gupta 775
        self.retailer.status = RETRY_MAP.get(self.callType)
15100 amit.gupta 776
        self.retailer.call_priority = None
15096 amit.gupta 777
        if self.callDisposition == 'call_later':
15100 amit.gupta 778
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 779
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 780
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
781
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
782
            else:
15102 amit.gupta 783
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 784
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 785
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
786
        else: 
787
            if self.callDisposition == 'ringing_no_answer':
788
                if self.retailer.disposition == 'ringing_no_answer':
789
                    self.retailer.retry_count += 1
790
                else:
791
                    self.retailer.disposition = 'ringing_no_answer'
792
                    self.retailer.retry_count = 1
793
            else:
794
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 795
                    pass
15112 amit.gupta 796
                else:
15119 amit.gupta 797
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 798
                self.retailer.retry_count += 1
799
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 800
 
15122 amit.gupta 801
            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 802
            if retryConfig is not None:
803
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 804
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 805
            else:
806
                self.retailer.status = 'failed'
807
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 808
 
15101 amit.gupta 809
        session.commit()
810
        return True
15096 amit.gupta 811
 
15100 amit.gupta 812
 
15091 amit.gupta 813
    def alReadyUser(self,):
15112 amit.gupta 814
        self.retailer.status = self.callDisposition
15117 amit.gupta 815
        if self.callHistory.disposition_description is None:
816
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 817
        session.commit()
818
        return True
15091 amit.gupta 819
    def verifiedLinkSent(self,):
15147 amit.gupta 820
        if self.callType == 'fresh':
821
            self.retailer.status = 'followup'
822
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
823
            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') 
824
        else:
15224 amit.gupta 825
            self.retailer.status = 'followup'
15147 amit.gupta 826
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
15254 amit.gupta 827
            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 828
        addContactToRetailer(self.agentId, self.retailerId, self.smsNumber, self.callType, 'sms')     
15146 amit.gupta 829
        session.commit()
830
        return True
15368 amit.gupta 831
    def onboarded(self,):
832
        self.retailer.status = self.callDisposition
833
        checkList = OnboardedRetailerChecklists()
834
        checkList.contact_us = self.checkList.get('contactus')
15390 amit.gupta 835
        checkList.doa_return_policy = self.checkList.get('doareturnpolicy')
15368 amit.gupta 836
        checkList.number_verification = self.checkList.get('numberverification')
837
        checkList.payment_option = self.checkList.get('paymentoption')
838
        checkList.preferences = self.checkList.get('preferences')
839
        checkList.product_info = self.checkList.get('productinfo')
15372 amit.gupta 840
        checkList.redeem = self.checkList.get('redeem')
15368 amit.gupta 841
        checkList.retailer_id = self.retailerId
842
        session.commit()
843
        return True
844
 
845
 
15254 amit.gupta 846
def isActivated(retailerId):
15276 amit.gupta 847
    retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailerId).first()
15448 amit.gupta 848
    user = session.query(Users).filter(or_(func.lower(Users.referrer)==retailerLink.code.lower(), Users.utm_campaign==retailerLink.code)).first()
15276 amit.gupta 849
    if user is None:
850
        mobileNumbers = list(session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailerId).all())
851
        user = session.query(Users).filter(Users.mobile_number.in_(mobileNumbers)).first()
15254 amit.gupta 852
        if user is None:
15332 amit.gupta 853
            if retailerLink.created < datetime(2015,5,26):
15333 amit.gupta 854
                historyNumbers = [number for number, in session.query(CallHistory.mobile_number).filter_by(retailer_id = retailerId).all()]
15391 amit.gupta 855
                user = session.query(Users).filter_by(activated=1).filter(Users.mobile_number.in_(historyNumbers)).first()
15332 amit.gupta 856
                if user is None:
857
                    return False
15334 amit.gupta 858
                else:
859
                    mapped_with = 'contact'
15332 amit.gupta 860
            else:
861
                return False
15276 amit.gupta 862
        else:
863
            mapped_with = 'contact'
864
    else:
865
        mapped_with = 'code'
866
    retailerLink.mapped_with = mapped_with
15388 amit.gupta 867
    if user.activation_time is not None:
15448 amit.gupta 868
        retailerLink.activated = user.activation_time
869
    retailerLink.activated = user.created
15276 amit.gupta 870
    retailerLink.user_id = user.id
15291 amit.gupta 871
    retailer = session.query(Retailers).filter_by(id=retailerId).first()
15389 amit.gupta 872
    if retailer.status != 'onboarded':
873
        retailer.status = 'onboarding'
15391 amit.gupta 874
        retailer.call_priority = None
875
        retailer.next_call_time = None
876
        retailer.retry_count = 0
877
        retailer.invalid_retry_count = 0
15276 amit.gupta 878
    session.commit()
15287 amit.gupta 879
    print "retailerLink.retailer_id", retailerLink.retailer_id
15276 amit.gupta 880
    session.close()
881
    return True
15254 amit.gupta 882
 
883
class AddContactToRetailer():
884
    def on_post(self,req,resp, agentId):
885
        agentId = int(agentId)
886
        try:
887
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
888
            retailerId = int(jsonReq.get("retailerid"))
889
            mobile = jsonReq.get("mobile")
890
            callType = jsonReq.get("calltype")
891
            contactType = jsonReq.get("contacttype")
892
            addContactToRetailer(agentId, retailerId, mobile, callType, contactType)
893
            session.commit()
894
        finally:
895
            session.close()
896
 
897
def addContactToRetailer(agentId, retailerId, mobile, callType, contactType):
15312 amit.gupta 898
    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=retailerId).filter_by(mobile_number=mobile).first()
899
    if retailerContact is None:
15254 amit.gupta 900
        retailerContact = RetailerContacts()
15256 amit.gupta 901
        retailerContact.retailer_id = retailerId
15254 amit.gupta 902
        retailerContact.agent_id = agentId
903
        retailerContact.call_type = callType
904
        retailerContact.contact_type = contactType
905
        retailerContact.mobile_number = mobile
15312 amit.gupta 906
    else:
15327 amit.gupta 907
        if CONTACT_PRIORITY.index(retailerContact.contact_type) > CONTACT_PRIORITY.index(contactType):
15358 amit.gupta 908
            retailerContact.contact_type = contactType
15312 amit.gupta 909
 
15254 amit.gupta 910
 
15312 amit.gupta 911
 
15189 manas 912
class Login():
913
 
914
    def on_get(self, req, resp, agentId, role):
915
        try:
15198 manas 916
            self.agentId = int(agentId)
917
            self.role = role
918
            print str(self.agentId) + self.role;
15199 manas 919
            agents=AgentLoginTimings()
920
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
921
            print 'lastLogintime' + str(lastLoginTime)
922
            agents.loginTime=lastLoginTime.last_login
923
            agents.logoutTime=datetime.now()
924
            agents.role =self.role
15282 amit.gupta 925
            agents.agent_id = self.agentId
15199 manas 926
            session.add(agents)    
927
            session.commit()
928
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 929
        finally:
930
            session.close()        
15112 amit.gupta 931
 
15189 manas 932
    def on_post(self,req,resp):
933
        try:
934
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
935
            lgr.info( "Request ----\n"  + str(jsonReq))
936
            email=jsonReq.get('email')
937
            password = jsonReq.get('password')
938
            role=jsonReq.get('role')    
939
            checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
940
            if checkUser is None:
941
                print checkUser
942
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
943
            else:
944
                print checkUser[0]
945
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
946
                if checkRole is None:
947
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
948
                else:
15196 manas 949
                    session.query(Agents).filter_by(id = checkUser[0]).update({"last_login":datetime.now()})
15195 manas 950
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":checkUser[0]}}, encoding='utf-8')
951
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 952
                    session.commit()
953
        finally:
954
            session.close()    
955
 
15195 manas 956
    def test(self,email,password,role):
15189 manas 957
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
958
        if checkUser is None:
959
            print checkUser
15195 manas 960
 
15189 manas 961
        else:
962
            print checkUser[0]
963
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
964
            if checkRole is None:
15195 manas 965
                pass
15189 manas 966
            else:
15195 manas 967
                agents=AgentLoginTimings()
968
                agents.loginTime=datetime.now()
969
                agents.logoutTime=datetime.now()
970
                agents.role =role
971
                agents.agent_id = 2
972
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
973
                session.add(agents)    
974
                session.commit()
975
                session.close()
976
 
977
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15275 amit.gupta 978
 
979
class RetailerActivation():
980
    def on_get(self, req, resp, userId):
15351 amit.gupta 981
        res =  markDealerActivation(int(userId))
982
        if res:
983
            resp.body = "{\"activated\":true}"
984
        else:
985
            resp.body = "{\"activated\":false}"
986
 
15275 amit.gupta 987
 
988
def markDealerActivation(userId):
989
    try:
15343 amit.gupta 990
        user = session.query(Users).filter_by(id=userId).first()
15275 amit.gupta 991
        result = False                
992
        mappedWith = 'contact'
993
        if user is not None:
15448 amit.gupta 994
            retailerLink = session.query(RetailerLinks).filter(or_(RetailerLinks.code==user.referrer.upper(), RetailerLinks.code==user.utm_campaign)).first()
15275 amit.gupta 995
            if retailerLink is None:
996
                retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
997
                if retailerContact is None:
998
                    retailer = session.query(Retailers).filter(Retailers.status.in_(['followup', 'fretry'])).filter(or_(Retailers.contact1==user.mobile_number,Retailers.contact2==user.mobile_number)).first()
999
                else:
1000
                    retailer = session.query(Retailers).filter_by(id = retailerContact.retailer_id).first()
1001
            else:
1002
                retailer = session.query(Retailers).filter_by(id = retailerLink.retailer_id).first()
1003
                mappedWith='code'
1004
            if retailer is not None:
1005
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailer.id).first()
1006
                if retailerLink is not None:
1007
                    retailerLink.user_id = user.id
1008
                    retailerLink.mapped_with=mappedWith
15358 amit.gupta 1009
                    retailer.status = 'onboarding'
15275 amit.gupta 1010
                    result = True
1011
                    session.commit()
1012
            return result
1013
    finally:
1014
        session.close()
1015
 
15189 manas 1016
 
15081 amit.gupta 1017
def todict(obj, classkey=None):
1018
    if isinstance(obj, dict):
1019
        data = {}
1020
        for (k, v) in obj.items():
1021
            data[k] = todict(v, classkey)
1022
        return data
1023
    elif hasattr(obj, "_ast"):
1024
        return todict(obj._ast())
1025
    elif hasattr(obj, "__iter__"):
1026
        return [todict(v, classkey) for v in obj]
1027
    elif hasattr(obj, "__dict__"):
1028
        data = dict([(key, todict(value, classkey)) 
1029
            for key, value in obj.__dict__.iteritems() 
1030
            if not callable(value) and not key.startswith('_')])
1031
        if classkey is not None and hasattr(obj, "__class__"):
1032
            data[classkey] = obj.__class__.__name__
1033
        return data
1034
    else:
1035
        return obj
1036
 
15358 amit.gupta 1037
def getRetailerObj(retailer, otherContacts1=None, callType=None):
15324 amit.gupta 1038
    print "before otherContacts1",otherContacts1
1039
    otherContacts = [] if otherContacts1 is None else otherContacts1
15315 amit.gupta 1040
    print "afotherContacts1",otherContacts
15081 amit.gupta 1041
    obj = Mock()
1042
    obj.title = retailer.title
15280 amit.gupta 1043
    obj.id = retailer.id
15314 amit.gupta 1044
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts:
15315 amit.gupta 1045
        otherContacts.append(retailer.contact1)
15314 amit.gupta 1046
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts:
15315 amit.gupta 1047
        otherContacts.append(retailer.contact2)
15276 amit.gupta 1048
    obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
15323 amit.gupta 1049
    obj.contact1 = None if len(otherContacts)==0 else otherContacts[0]
15325 amit.gupta 1050
    if obj.contact1 is not None:
1051
        obj.contact2 = None if len(otherContacts)==1 else otherContacts[1]
15096 amit.gupta 1052
    obj.scheduled = (retailer.call_priority is not None)
15312 amit.gupta 1053
    obj.status = retailer.status
15358 amit.gupta 1054
    if callType == 'onboarding':
1055
        try:
15364 amit.gupta 1056
            userId, activatedTime = session.query(RetailerLinks.user_id, RetailerLinks.activated).filter(RetailerLinks.retailer_id==retailer.id).first()
15366 amit.gupta 1057
            activated, = session.query(Users.activation_time).filter(Users.id==userId).first()
15364 amit.gupta 1058
            if activated is not None:
15366 amit.gupta 1059
                activatedTime = activated
15362 amit.gupta 1060
            obj.user_id = userId
15364 amit.gupta 1061
            obj.created = datetime.strftime(activatedTime, '%d/%m/%Y %H:%M:%S')
15358 amit.gupta 1062
            result = fetchResult("select * from useractive where user_id=%d"%(userId))
1063
            if result == ():
1064
                obj.last_active = None
1065
            else:
15360 amit.gupta 1066
                obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
15361 amit.gupta 1067
            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 1068
            obj.orders = ordersCount
1069
        finally:
1070
            session.close()
15081 amit.gupta 1071
    return obj
15091 amit.gupta 1072
 
15132 amit.gupta 1073
def make_tiny(code):
1074
    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
1075
    request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1076
    filehandle = urllib2.Request(request_url)
1077
    x= urllib2.urlopen(filehandle)
1078
    return str(x.read())
15171 amit.gupta 1079
 
15285 manas 1080
class SearchUser():
1081
 
1082
    def on_post(self, req, resp, agentId, searchType):
15314 amit.gupta 1083
        retailersJsonArray = []
15285 manas 1084
        try:
1085
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1086
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1087
            contact=jsonReq.get('searchTerm')
15285 manas 1088
            if(searchType=="number"):
15312 amit.gupta 1089
                retailer_ids = session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all()
1090
                retailer_ids = [r for r, in retailer_ids]    
1091
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact, Retailers.id.in_(retailer_ids))
1092
            else:
1093
                m = re.match("(.*?)(\d{6})(.*?)", contact)
1094
                if m is not None:
1095
                    pin = m.group(2)
1096
                    contact = m.group(1) if m.group(1) != '' else m.group(3)
15313 amit.gupta 1097
                    anotherCondition = and_(Retailers.title.ilike('%%%s%%'%(contact)), Retailers.pin==pin)
15312 amit.gupta 1098
                else:
1099
                    anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1100
 
15326 amit.gupta 1101
            retailers = session.query(Retailers).filter(anotherCondition).limit(20).all()
15312 amit.gupta 1102
            if retailers is None:
15285 manas 1103
                resp.body = json.dumps("{}")
15312 amit.gupta 1104
            else:
1105
                for retailer in retailers:
15326 amit.gupta 1106
                    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 1107
                    retailersJsonArray.append(todict(getRetailerObj(retailer, otherContacts)))    
1108
            resp.body = json.dumps({"Retailers":retailersJsonArray}, encoding='utf-8')
15312 amit.gupta 1109
            return
15285 manas 1110
        finally:
1111
            session.close()
15171 amit.gupta 1112
 
15081 amit.gupta 1113
 
1114
class Mock(object):
1115
    pass
15189 manas 1116
 
15312 amit.gupta 1117
def tagActivatedReatilers():
1118
    retailerIds = [r for  r, in session.query(RetailerLinks.retailer_id).all()]
1119
    session.close()
15288 amit.gupta 1120
    for retailerId in retailerIds:
1121
        isActivated(retailerId)
15312 amit.gupta 1122
    session.close()
15374 kshitij.so 1123
 
1124
class StaticDeals():
1125
 
1126
    def on_get(self, req, resp):
1127
 
1128
        offset = req.get_param_as_int("offset")
1129
        limit = req.get_param_as_int("limit")
1130
        categoryId = req.get_param_as_int("categoryId")
1131
 
1132
        result = Mongo.getStaticDeals(offset, limit, categoryId)
1133
        resp.body = dumps(result)
1134
 
1135
 
1136
 
15312 amit.gupta 1137
def main():
1138
    tagActivatedReatilers()
15195 manas 1139
 
15081 amit.gupta 1140
if __name__ == '__main__':
15207 amit.gupta 1141
    main()
15091 amit.gupta 1142