Subversion Repositories SmartDukaan

Rev

Rev 15358 | Rev 15361 | 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, \
15358 amit.gupta 9
    FetchDataHistory, RetailerContacts, Orders
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']
15358 amit.gupta 33
RETRY_MAP = {'fresh':'retry', 'folluwpup':'fretry', 'onboarding':'oretry'}
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
15278 amit.gupta 680
        self.address = jsonReq.get('address')
15096 amit.gupta 681
        self.retailerId = int(jsonReq.get('retailerid'))
15254 amit.gupta 682
        self.smsNumber = jsonReq.get('smsnumber') 
15112 amit.gupta 683
        try:
684
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
15281 amit.gupta 685
            if self.address:
15278 amit.gupta 686
                self.retailer.address_new = self.address
15112 amit.gupta 687
            self.callDisposition = jsonReq.get('calldispositiontype')
688
            self.callHistory = CallHistory()
689
            self.callHistory.agent_id=self.agentId
690
            self.callHistory.call_disposition = self.callDisposition
691
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 692
            self.callHistory.call_type=self.callType
15112 amit.gupta 693
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
694
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 695
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
696
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 697
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
698
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 699
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 700
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
701
            if lastFetchData is None:
702
                raise
703
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 704
 
705
            dispositionMap = {  'call_later':callLater,
706
                        'ringing_no_answer':callLater,
707
                        'not_reachable':callLater,
708
                        'switch_off':callLater,
15202 manas 709
                        'not_retailer':invalidNumber,
15112 amit.gupta 710
                        'invalid_no':invalidNumber,
711
                        'wrong_no':invalidNumber,
712
                        'hang_up':invalidNumber,
713
                        'retailer_not_interested':invalidNumber,
15200 manas 714
                        'recharge_retailer':invalidNumber,
715
                        'accessory_retailer':invalidNumber,
716
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 717
                        'alreadyuser':alreadyUser,
718
                        'verified_link_sent':verifiedLinkSent
719
                      }
720
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
721
        finally:
722
            session.close()
15096 amit.gupta 723
 
15112 amit.gupta 724
        if returned:
725
            resp.body = "{\"result\":\"success\"}"
726
        else:
727
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 728
 
15091 amit.gupta 729
    def invalidNumber(self,):
15108 manas 730
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
731
        if self.callDisposition == 'invalid_no':
732
            self.retailer.status='failed'
733
            self.callHistory.disposition_description = 'Invalid Number'
734
        elif self.callDisposition == 'wrong_no':
15111 manas 735
            self.retailer.status='failed'
736
            self.callHistory.disposition_description = 'Wrong Number'
737
        elif self.callDisposition == 'hang_up':
738
            self.retailer.status='failed'
739
            self.callHistory.disposition_description = 'Hang Up'
740
        elif self.callDisposition == 'retailer_not_interested':
741
            self.retailer.status='failed'
742
            if self.callHistory.disposition_description is None:
743
                self.callHistory.disposition_description = 'NA'
15200 manas 744
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
745
        elif self.callDisposition == 'recharge_retailer':
746
            self.retailer.status='failed'
747
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
748
        elif self.callDisposition == 'accessory_retailer':
749
            self.retailer.status='failed'
750
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
751
        elif self.callDisposition == 'service_center_retailer':
752
            self.retailer.status='failed'
753
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 754
        elif self.callDisposition == 'not_retailer':
755
            self.retailer.status='failed'
756
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 757
        session.commit()
758
        return True   
759
 
15132 amit.gupta 760
    def getCode(self,):
15207 amit.gupta 761
        newCode = None
762
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
763
        if lastLink is not None:
764
            if len(lastLink.code)==len(codesys):
765
                newCode=lastLink.code
766
        return getNextCode(codesys, newCode)
15108 manas 767
 
15254 amit.gupta 768
 
15091 amit.gupta 769
    def callLater(self,):
15100 amit.gupta 770
        self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
771
        self.retailer.call_priority = None
15096 amit.gupta 772
        if self.callDisposition == 'call_later':
15100 amit.gupta 773
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 774
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 775
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
776
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
777
            else:
15102 amit.gupta 778
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 779
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 780
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
781
        else: 
782
            if self.callDisposition == 'ringing_no_answer':
783
                if self.retailer.disposition == 'ringing_no_answer':
784
                    self.retailer.retry_count += 1
785
                else:
786
                    self.retailer.disposition = 'ringing_no_answer'
787
                    self.retailer.retry_count = 1
788
            else:
789
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 790
                    pass
15112 amit.gupta 791
                else:
15119 amit.gupta 792
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 793
                self.retailer.retry_count += 1
794
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 795
 
15122 amit.gupta 796
            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 797
            if retryConfig is not None:
798
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 799
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 800
            else:
801
                self.retailer.status = 'failed'
802
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 803
 
15101 amit.gupta 804
        session.commit()
805
        return True
15096 amit.gupta 806
 
15100 amit.gupta 807
 
15091 amit.gupta 808
    def alReadyUser(self,):
15112 amit.gupta 809
        self.retailer.status = self.callDisposition
15117 amit.gupta 810
        if self.callHistory.disposition_description is None:
811
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 812
        session.commit()
813
        return True
15091 amit.gupta 814
    def verifiedLinkSent(self,):
15147 amit.gupta 815
        if self.callType == 'fresh':
816
            self.retailer.status = 'followup'
817
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
818
            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') 
819
        else:
15224 amit.gupta 820
            self.retailer.status = 'followup'
15147 amit.gupta 821
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
15254 amit.gupta 822
            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 823
        addContactToRetailer(self.agentId, self.retailerId, self.smsNumber, self.callType, 'sms')     
15146 amit.gupta 824
        session.commit()
825
        return True
15254 amit.gupta 826
def isActivated(retailerId):
15276 amit.gupta 827
    retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailerId).first()
828
    user = session.query(Users).filter_by(referrer=retailerLink.code).first()
829
    if user is None:
830
        mobileNumbers = list(session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailerId).all())
831
        user = session.query(Users).filter(Users.mobile_number.in_(mobileNumbers)).first()
15254 amit.gupta 832
        if user is None:
15332 amit.gupta 833
            if retailerLink.created < datetime(2015,5,26):
15333 amit.gupta 834
                historyNumbers = [number for number, in session.query(CallHistory.mobile_number).filter_by(retailer_id = retailerId).all()]
15332 amit.gupta 835
                user = session.query(Users).filter(Users.mobile_number.in_(historyNumbers)).first()
836
                if user is None:
837
                    return False
15334 amit.gupta 838
                else:
839
                    mapped_with = 'contact'
15332 amit.gupta 840
            else:
841
                return False
15276 amit.gupta 842
        else:
843
            mapped_with = 'contact'
844
    else:
845
        mapped_with = 'code'
846
    retailerLink.mapped_with = mapped_with
847
    retailerLink.user_id = user.id
15291 amit.gupta 848
    retailer = session.query(Retailers).filter_by(id=retailerId).first()
15358 amit.gupta 849
    retailer.status = 'onboarding'
15276 amit.gupta 850
    session.commit()
15287 amit.gupta 851
    print "retailerLink.retailer_id", retailerLink.retailer_id
15276 amit.gupta 852
    session.close()
853
    return True
15254 amit.gupta 854
 
855
class AddContactToRetailer():
856
    def on_post(self,req,resp, agentId):
857
        agentId = int(agentId)
858
        try:
859
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
860
            retailerId = int(jsonReq.get("retailerid"))
861
            mobile = jsonReq.get("mobile")
862
            callType = jsonReq.get("calltype")
863
            contactType = jsonReq.get("contacttype")
864
            addContactToRetailer(agentId, retailerId, mobile, callType, contactType)
865
            session.commit()
866
        finally:
867
            session.close()
868
 
869
def addContactToRetailer(agentId, retailerId, mobile, callType, contactType):
15312 amit.gupta 870
    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=retailerId).filter_by(mobile_number=mobile).first()
871
    if retailerContact is None:
15254 amit.gupta 872
        retailerContact = RetailerContacts()
15256 amit.gupta 873
        retailerContact.retailer_id = retailerId
15254 amit.gupta 874
        retailerContact.agent_id = agentId
875
        retailerContact.call_type = callType
876
        retailerContact.contact_type = contactType
877
        retailerContact.mobile_number = mobile
15312 amit.gupta 878
    else:
15327 amit.gupta 879
        if CONTACT_PRIORITY.index(retailerContact.contact_type) > CONTACT_PRIORITY.index(contactType):
15358 amit.gupta 880
            retailerContact.contact_type = contactType
15312 amit.gupta 881
 
15254 amit.gupta 882
 
15312 amit.gupta 883
 
15189 manas 884
class Login():
885
 
886
    def on_get(self, req, resp, agentId, role):
887
        try:
15198 manas 888
            self.agentId = int(agentId)
889
            self.role = role
890
            print str(self.agentId) + self.role;
15199 manas 891
            agents=AgentLoginTimings()
892
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
893
            print 'lastLogintime' + str(lastLoginTime)
894
            agents.loginTime=lastLoginTime.last_login
895
            agents.logoutTime=datetime.now()
896
            agents.role =self.role
15282 amit.gupta 897
            agents.agent_id = self.agentId
15199 manas 898
            session.add(agents)    
899
            session.commit()
900
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 901
        finally:
902
            session.close()        
15112 amit.gupta 903
 
15189 manas 904
    def on_post(self,req,resp):
905
        try:
906
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
907
            lgr.info( "Request ----\n"  + str(jsonReq))
908
            email=jsonReq.get('email')
909
            password = jsonReq.get('password')
910
            role=jsonReq.get('role')    
911
            checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
912
            if checkUser is None:
913
                print checkUser
914
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
915
            else:
916
                print checkUser[0]
917
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
918
                if checkRole is None:
919
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
920
                else:
15196 manas 921
                    session.query(Agents).filter_by(id = checkUser[0]).update({"last_login":datetime.now()})
15195 manas 922
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":checkUser[0]}}, encoding='utf-8')
923
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 924
                    session.commit()
925
        finally:
926
            session.close()    
927
 
15195 manas 928
    def test(self,email,password,role):
15189 manas 929
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
930
        if checkUser is None:
931
            print checkUser
15195 manas 932
 
15189 manas 933
        else:
934
            print checkUser[0]
935
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
936
            if checkRole is None:
15195 manas 937
                pass
15189 manas 938
            else:
15195 manas 939
                agents=AgentLoginTimings()
940
                agents.loginTime=datetime.now()
941
                agents.logoutTime=datetime.now()
942
                agents.role =role
943
                agents.agent_id = 2
944
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
945
                session.add(agents)    
946
                session.commit()
947
                session.close()
948
 
949
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15275 amit.gupta 950
 
951
class RetailerActivation():
952
    def on_get(self, req, resp, userId):
15351 amit.gupta 953
        res =  markDealerActivation(int(userId))
954
        if res:
955
            resp.body = "{\"activated\":true}"
956
        else:
957
            resp.body = "{\"activated\":false}"
958
 
15275 amit.gupta 959
 
960
def markDealerActivation(userId):
961
    try:
15343 amit.gupta 962
        user = session.query(Users).filter_by(id=userId).first()
15275 amit.gupta 963
        result = False                
964
        mappedWith = 'contact'
965
        if user is not None:
966
            retailerLink = session.query(RetailerLinks).filter_by(code=user.referrer).first()
967
            if retailerLink is None:
968
                retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
969
                if retailerContact is None:
970
                    retailer = session.query(Retailers).filter(Retailers.status.in_(['followup', 'fretry'])).filter(or_(Retailers.contact1==user.mobile_number,Retailers.contact2==user.mobile_number)).first()
971
                else:
972
                    retailer = session.query(Retailers).filter_by(id = retailerContact.retailer_id).first()
973
            else:
974
                retailer = session.query(Retailers).filter_by(id = retailerLink.retailer_id).first()
975
                mappedWith='code'
976
            if retailer is not None:
977
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailer.id).first()
978
                if retailerLink is not None:
979
                    retailerLink.user_id = user.id
980
                    retailerLink.mapped_with=mappedWith
15358 amit.gupta 981
                    retailer.status = 'onboarding'
15275 amit.gupta 982
                    result = True
983
                    session.commit()
984
            return result
985
    finally:
986
        session.close()
987
 
15189 manas 988
 
15081 amit.gupta 989
def todict(obj, classkey=None):
990
    if isinstance(obj, dict):
991
        data = {}
992
        for (k, v) in obj.items():
993
            data[k] = todict(v, classkey)
994
        return data
995
    elif hasattr(obj, "_ast"):
996
        return todict(obj._ast())
997
    elif hasattr(obj, "__iter__"):
998
        return [todict(v, classkey) for v in obj]
999
    elif hasattr(obj, "__dict__"):
1000
        data = dict([(key, todict(value, classkey)) 
1001
            for key, value in obj.__dict__.iteritems() 
1002
            if not callable(value) and not key.startswith('_')])
1003
        if classkey is not None and hasattr(obj, "__class__"):
1004
            data[classkey] = obj.__class__.__name__
1005
        return data
1006
    else:
1007
        return obj
1008
 
15358 amit.gupta 1009
def getRetailerObj(retailer, otherContacts1=None, callType=None):
15324 amit.gupta 1010
    print "before otherContacts1",otherContacts1
1011
    otherContacts = [] if otherContacts1 is None else otherContacts1
15315 amit.gupta 1012
    print "afotherContacts1",otherContacts
15081 amit.gupta 1013
    obj = Mock()
1014
    obj.title = retailer.title
15280 amit.gupta 1015
    obj.id = retailer.id
15314 amit.gupta 1016
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts:
15315 amit.gupta 1017
        otherContacts.append(retailer.contact1)
15314 amit.gupta 1018
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts:
15315 amit.gupta 1019
        otherContacts.append(retailer.contact2)
15276 amit.gupta 1020
    obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
15323 amit.gupta 1021
    obj.contact1 = None if len(otherContacts)==0 else otherContacts[0]
15325 amit.gupta 1022
    if obj.contact1 is not None:
1023
        obj.contact2 = None if len(otherContacts)==1 else otherContacts[1]
15096 amit.gupta 1024
    obj.scheduled = (retailer.call_priority is not None)
15312 amit.gupta 1025
    obj.status = retailer.status
15358 amit.gupta 1026
    if callType == 'onboarding':
1027
        try:
1028
            userId, = session.query(RetailerLinks.user_id).filter(RetailerLinks.retailer_id==retailer.id).first()
1029
            obj.userId = userId
1030
            result = fetchResult("select * from useractive where user_id=%d"%(userId))
1031
            if result == ():
1032
                obj.last_active = None
1033
            else:
15360 amit.gupta 1034
                obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
15358 amit.gupta 1035
            ordersCount = session.query(Orders).filter_by(user_id = userId).filter(~Orders.status.in_('ORDER_NOT_CREATED_KNOWN', 'ORDER_ALREADY_CREATED_IGNORED')).count()
1036
            obj.orders = ordersCount
1037
        finally:
1038
            session.close()
15081 amit.gupta 1039
    return obj
15091 amit.gupta 1040
 
15132 amit.gupta 1041
def make_tiny(code):
1042
    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
1043
    request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1044
    filehandle = urllib2.Request(request_url)
1045
    x= urllib2.urlopen(filehandle)
1046
    return str(x.read())
15171 amit.gupta 1047
 
15285 manas 1048
class SearchUser():
1049
 
1050
    def on_post(self, req, resp, agentId, searchType):
15314 amit.gupta 1051
        retailersJsonArray = []
15285 manas 1052
        try:
1053
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1054
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1055
            contact=jsonReq.get('searchTerm')
15285 manas 1056
            if(searchType=="number"):
15312 amit.gupta 1057
                retailer_ids = session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all()
1058
                retailer_ids = [r for r, in retailer_ids]    
1059
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact, Retailers.id.in_(retailer_ids))
1060
            else:
1061
                m = re.match("(.*?)(\d{6})(.*?)", contact)
1062
                if m is not None:
1063
                    pin = m.group(2)
1064
                    contact = m.group(1) if m.group(1) != '' else m.group(3)
15313 amit.gupta 1065
                    anotherCondition = and_(Retailers.title.ilike('%%%s%%'%(contact)), Retailers.pin==pin)
15312 amit.gupta 1066
                else:
1067
                    anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1068
 
15326 amit.gupta 1069
            retailers = session.query(Retailers).filter(anotherCondition).limit(20).all()
15312 amit.gupta 1070
            if retailers is None:
15285 manas 1071
                resp.body = json.dumps("{}")
15312 amit.gupta 1072
            else:
1073
                for retailer in retailers:
15326 amit.gupta 1074
                    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 1075
                    retailersJsonArray.append(todict(getRetailerObj(retailer, otherContacts)))    
1076
            resp.body = json.dumps({"Retailers":retailersJsonArray}, encoding='utf-8')
15312 amit.gupta 1077
            return
15285 manas 1078
        finally:
1079
            session.close()
15171 amit.gupta 1080
 
15081 amit.gupta 1081
 
1082
class Mock(object):
1083
    pass
15189 manas 1084
 
15312 amit.gupta 1085
def tagActivatedReatilers():
1086
    retailerIds = [r for  r, in session.query(RetailerLinks.retailer_id).all()]
1087
    session.close()
15288 amit.gupta 1088
    for retailerId in retailerIds:
1089
        isActivated(retailerId)
15312 amit.gupta 1090
    session.close()
1091
def main():
1092
    tagActivatedReatilers()
15195 manas 1093
 
15081 amit.gupta 1094
if __name__ == '__main__':
15207 amit.gupta 1095
    main()
15091 amit.gupta 1096