Subversion Repositories SmartDukaan

Rev

Rev 15662 | Rev 15671 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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