Subversion Repositories SmartDukaan

Rev

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