Subversion Repositories SmartDukaan

Rev

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