Subversion Repositories SmartDukaan

Rev

Rev 15852 | Rev 16221 | 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, \
15676 amit.gupta 10
    FetchDataHistory, RetailerContacts, Orders, OnboardedRetailerChecklists,\
15710 amit.gupta 11
    RetailerAddresses, Pincodeavailability
15358 amit.gupta 12
from dtr.storage.Mongo import get_mongo_connection
13
from dtr.storage.Mysql import fetchResult
15081 amit.gupta 14
from dtr.utils import FetchLivePrices, DealSheet as X_DealSheet, \
15
    UserSpecificDeals
15168 amit.gupta 16
from dtr.utils.utils import getLogger
15081 amit.gupta 17
from elixir import *
15254 amit.gupta 18
from operator import and_
15303 amit.gupta 19
from sqlalchemy.sql.expression import func, func, or_
15132 amit.gupta 20
from urllib import urlencode
21
import contextlib
13827 kshitij.so 22
import falcon
15081 amit.gupta 23
import json
15358 amit.gupta 24
import re
15254 amit.gupta 25
import string
15081 amit.gupta 26
import traceback
15132 amit.gupta 27
import urllib
28
import urllib2
29
import uuid
15465 amit.gupta 30
import gdshortener
15207 amit.gupta 31
alphalist = list(string.uppercase)
32
alphalist.remove('O')
33
numList = ['1','2','3','4','5','6','7','8','9']
34
codesys = [alphalist, alphalist, numList, numList, numList]
15312 amit.gupta 35
CONTACT_PRIORITY = ['sms', 'called', 'ringing']
15368 amit.gupta 36
RETRY_MAP = {'fresh':'retry', 'followup':'fretry', 'onboarding':'oretry'}
15358 amit.gupta 37
ASSIGN_MAP = {'retry':'assigned', 'fretry':'fassigned', 'oretry':'oassigned'}
15207 amit.gupta 38
 
39
def getNextCode(codesys, code=None):
40
    if code is None:
41
        code = []
42
        for charcode in codesys:
43
            code.append(charcode[0])
44
        return string.join(code, '')
45
    carry = True
46
    code = list(code)
47
    lastindex = len(codesys) - 1
48
    while carry:
49
        listChar = codesys[lastindex]
50
        newIndex = (listChar.index(code[lastindex])+1)%len(listChar)
51
        print newIndex
52
        code[lastindex] = listChar[newIndex]
53
        if newIndex != 0:
54
            carry = False
55
        lastindex -= 1
56
        if lastindex ==-1:
57
            raise BaseException("All codes are exhausted")
58
 
59
    return string.join(code, '')
60
 
61
 
62
 
63
 
15081 amit.gupta 64
global RETAILER_DETAIL_CALL_COUNTER
65
RETAILER_DETAIL_CALL_COUNTER = 0
13572 kshitij.so 66
 
15168 amit.gupta 67
lgr = getLogger('/var/log/retailer-acquisition-api.log')
15081 amit.gupta 68
DEALER_RETRY_FACTOR = int(PythonPropertyReader.getConfig('DEALER_RETRY_FACTOR'))
13572 kshitij.so 69
class CategoryDiscountInfo(object):
70
 
71
    def on_get(self, req, resp):
72
 
13629 kshitij.so 73
        result = Mongo.getAllCategoryDiscount()
74
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
75
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 76
 
77
    def on_post(self, req, resp):
78
        try:
79
            result_json = json.loads(req.stream.read(), encoding='utf-8')
80
        except ValueError:
81
            raise falcon.HTTPError(falcon.HTTP_400,
82
                'Malformed JSON',
83
                'Could not decode the request body. The '
84
                'JSON was incorrect.')
85
 
86
        result = Mongo.addCategoryDiscount(result_json)
87
        resp.body = json.dumps(result, encoding='utf-8')
13969 kshitij.so 88
 
89
    def on_put(self, req, resp, _id):
13970 kshitij.so 90
        try:
91
            result_json = json.loads(req.stream.read(), encoding='utf-8')
92
        except ValueError:
93
            raise falcon.HTTPError(falcon.HTTP_400,
94
                'Malformed JSON',
95
                'Could not decode the request body. The '
96
                'JSON was incorrect.')
97
 
98
        result = Mongo.updateCategoryDiscount(result_json, _id)
99
        resp.body = json.dumps(result, encoding='utf-8')
100
 
13966 kshitij.so 101
 
13969 kshitij.so 102
 
13572 kshitij.so 103
class SkuSchemeDetails(object):
104
 
105
    def on_get(self, req, resp):
13629 kshitij.so 106
 
14070 kshitij.so 107
        offset = req.get_param_as_int("offset")
108
        limit = req.get_param_as_int("limit")
109
 
110
        result = Mongo.getAllSkuWiseSchemeDetails(offset, limit)
13629 kshitij.so 111
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
112
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 113
 
114
 
115
    def on_post(self, req, resp):
116
 
14552 kshitij.so 117
        multi = req.get_param_as_int("multi")
118
 
13572 kshitij.so 119
        try:
120
            result_json = json.loads(req.stream.read(), encoding='utf-8')
121
        except ValueError:
122
            raise falcon.HTTPError(falcon.HTTP_400,
123
                'Malformed JSON',
124
                'Could not decode the request body. The '
125
                'JSON was incorrect.')
126
 
15852 kshitij.so 127
        result = Mongo.addSchemeDetailsForSku(result_json)
13572 kshitij.so 128
        resp.body = json.dumps(result, encoding='utf-8')
129
 
130
class SkuDiscountInfo():
131
 
132
    def on_get(self, req, resp):
13629 kshitij.so 133
 
13970 kshitij.so 134
        offset = req.get_param_as_int("offset")
135
        limit = req.get_param_as_int("limit")
136
        result = Mongo.getallSkuDiscountInfo(offset,limit)
13629 kshitij.so 137
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
138
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 139
 
140
 
141
    def on_post(self, req, resp):
142
 
14552 kshitij.so 143
        multi = req.get_param_as_int("multi")
144
 
13572 kshitij.so 145
        try:
146
            result_json = json.loads(req.stream.read(), encoding='utf-8')
147
        except ValueError:
148
            raise falcon.HTTPError(falcon.HTTP_400,
149
                'Malformed JSON',
150
                'Could not decode the request body. The '
151
                'JSON was incorrect.')
152
 
15852 kshitij.so 153
        result = Mongo.addSkuDiscountInfo(result_json)
13572 kshitij.so 154
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 155
 
156
    def on_put(self, req, resp, _id):
157
        try:
158
            result_json = json.loads(req.stream.read(), encoding='utf-8')
159
        except ValueError:
160
            raise falcon.HTTPError(falcon.HTTP_400,
161
                'Malformed JSON',
162
                'Could not decode the request body. The '
163
                'JSON was incorrect.')
164
 
165
        result = Mongo.updateSkuDiscount(result_json, _id)
166
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 167
 
168
class ExceptionalNlc():
169
 
170
    def on_get(self, req, resp):
13629 kshitij.so 171
 
13970 kshitij.so 172
        offset = req.get_param_as_int("offset")
173
        limit = req.get_param_as_int("limit")
174
 
175
        result = Mongo.getAllExceptionlNlcItems(offset, limit)
13629 kshitij.so 176
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
177
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 178
 
179
    def on_post(self, req, resp):
180
 
14552 kshitij.so 181
        multi = req.get_param_as_int("multi")
182
 
13572 kshitij.so 183
        try:
184
            result_json = json.loads(req.stream.read(), encoding='utf-8')
185
        except ValueError:
186
            raise falcon.HTTPError(falcon.HTTP_400,
187
                'Malformed JSON',
188
                'Could not decode the request body. The '
189
                'JSON was incorrect.')
190
 
15852 kshitij.so 191
        result = Mongo.addExceptionalNlc(result_json)
13572 kshitij.so 192
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 193
 
194
    def on_put(self, req, resp, _id):
195
        try:
196
            result_json = json.loads(req.stream.read(), encoding='utf-8')
197
        except ValueError:
198
            raise falcon.HTTPError(falcon.HTTP_400,
199
                'Malformed JSON',
200
                'Could not decode the request body. The '
201
                'JSON was incorrect.')
202
 
203
        result = Mongo.updateExceptionalNlc(result_json, _id)
204
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 205
 
13772 kshitij.so 206
class Deals():
13779 kshitij.so 207
    def on_get(self,req, resp, userId):
208
        categoryId = req.get_param_as_int("categoryId")
209
        offset = req.get_param_as_int("offset")
210
        limit = req.get_param_as_int("limit")
13798 kshitij.so 211
        sort = req.get_param("sort")
13802 kshitij.so 212
        direction = req.get_param_as_int("direction")
14853 kshitij.so 213
        filterData = req.get_param('filterData')
214
        result = Mongo.getNewDeals(int(userId), categoryId, offset, limit, sort, direction, filterData)
16078 kshitij.so 215
        resp.body = dumps(result) 
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
 
15852 kshitij.so 329
        result = Mongo.addSkuDealerPrice(result_json)
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
 
15852 kshitij.so 371
        result = Mongo.updateCollection(result_json)
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:
15716 amit.gupta 557
            user = session.query(Users).filter_by(activated=0).filter_by(status=1).filter(Users.mobile_number != None).filter(~Users.mobile_number.like("0%")).filter(Users.created>datetime(2015,06,29)).order_by(Users.created.desc()).with_lockmode("update").first()
15662 amit.gupta 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'
15672 amit.gupta 572
                            retailer.retry_count = 0
15673 amit.gupta 573
                            retailer.invalid_retry_count = 0
15699 amit.gupta 574
                            retailer.is_elavated=1
15662 amit.gupta 575
                user.status = 2
576
                session.commit()
577
                print "retailer id", retailer.id
578
                retailer.contact = user.mobile_number
579
                return retailer
580
        finally:
581
            session.close()
582
 
15081 amit.gupta 583
    def getNewRetailer(self,failback=True):
15663 amit.gupta 584
        if self.callType == 'fresh':
585
            retailer = self.getNotActiveRetailer()
586
            if retailer is not None:
587
                return retailer
15081 amit.gupta 588
        retry = True
589
        retailer = None 
590
        try:
591
            while(retry):
15168 amit.gupta 592
                lgr.info( "Calltype " + self.callType)
15081 amit.gupta 593
                status=self.callType
15545 amit.gupta 594
                query = session.query(Retailers).filter(Retailers.status==status).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None))
15081 amit.gupta 595
                if status=='fresh':
15710 amit.gupta 596
                    query = query.filter_by(is_or=False, is_std=False).filter(Retailers.pin==Pincodeavailability.code).filter(Pincodeavailability.amount > 19999).order_by(Retailers.is_elavated.desc(), Retailers.agent_id.desc())
15358 amit.gupta 597
                elif status=='followup':
15546 amit.gupta 598
                    query = query.filter(Retailers.next_call_time<=datetime.now()).order_by(Retailers.agent_id.desc(),Retailers.next_call_time)
15162 amit.gupta 599
                else:
15546 amit.gupta 600
                    query = query.filter(Retailers.modified<=datetime.now()).order_by(Retailers.agent_id.desc(), Retailers.modified)
15358 amit.gupta 601
 
15081 amit.gupta 602
                retailer = query.with_lockmode("update").first()
603
                if retailer is not None:
15168 amit.gupta 604
                    lgr.info( "retailer " +str(retailer.id))
15081 amit.gupta 605
                    if status=="fresh":
606
                        userquery = session.query(Users)
607
                        if retailer.contact2 is not None:
608
                            userquery = userquery.filter(Users.mobile_number.in_([retailer.contact1,retailer.contact2]))
609
                        else:
610
                            userquery = userquery.filter_by(mobile_number=retailer.contact1)
611
                        user = userquery.first()
612
                        if user is not None:
613
                            retailer.status = 'alreadyuser'
15168 amit.gupta 614
                            lgr.info( "retailer.status " + retailer.status)
15081 amit.gupta 615
                            session.commit()
616
                            continue
617
                        retailer.status = 'assigned'
15358 amit.gupta 618
                    elif status=='followup':
15276 amit.gupta 619
                        if isActivated(retailer.id):
620
                            print "Retailer Already %d activated and marked onboarded"%(retailer.id)
621
                            continue
15081 amit.gupta 622
                        retailer.status = 'fassigned'
15358 amit.gupta 623
                    else:
624
                        retailer.status = 'oassigned'
15081 amit.gupta 625
                    retailer.retry_count = 0
15123 amit.gupta 626
                    retailer.invalid_retry_count = 0
15168 amit.gupta 627
                    lgr.info( "Found Retailer " +  str(retailer.id) + " with status " + status + " assigned to " + str(self.agentId))
15081 amit.gupta 628
 
629
                else:
15168 amit.gupta 630
                    lgr.info( "No fresh/followup retailers found")
15081 amit.gupta 631
                    if failback:
632
                        retailer = self.getRetryRetailer(False)
15104 amit.gupta 633
                        return retailer
15148 amit.gupta 634
                retry=False
15081 amit.gupta 635
        except:
636
            print traceback.print_exc()
637
        return retailer
638
 
15132 amit.gupta 639
    def on_get(self, req, resp, agentId, callType=None, retailerId=None):
15081 amit.gupta 640
        global RETAILER_DETAIL_CALL_COUNTER
641
        RETAILER_DETAIL_CALL_COUNTER += 1
15168 amit.gupta 642
        lgr.info( "RETAILER_DETAIL_CALL_COUNTER " +  str(RETAILER_DETAIL_CALL_COUNTER))
15081 amit.gupta 643
        self.agentId = int(agentId)
644
        self.callType = callType
15139 amit.gupta 645
        if retailerId is not None:
646
            self.retailerId = int(retailerId)
15208 amit.gupta 647
            retailerLink = session.query(RetailerLinks).filter_by(retailer_id=self.retailerId).first()
15132 amit.gupta 648
            if retailerLink is not None:
649
                code = retailerLink.code
650
            else: 
651
                code = self.getCode()
652
                retailerLink = RetailerLinks()
653
                retailerLink.code = code
15139 amit.gupta 654
                retailerLink.agent_id = self.agentId
655
                retailerLink.retailer_id = self.retailerId
15135 amit.gupta 656
 
657
                activationCode=Activation_Codes()
658
                activationCode.code = code
15132 amit.gupta 659
                session.commit()
660
            session.close()
15142 amit.gupta 661
            resp.body =  json.dumps({"result":{"code":code,"link":make_tiny(code)}}, encoding='utf-8')
15132 amit.gupta 662
            return 
15081 amit.gupta 663
        retryFlag = False 
664
        if RETAILER_DETAIL_CALL_COUNTER % DEALER_RETRY_FACTOR ==0:
665
            retryFlag=True
15239 amit.gupta 666
        try:
667
            if retryFlag:
668
                retailer = self.getRetryRetailer()
669
            else:
670
                retailer = self.getNewRetailer()
15343 amit.gupta 671
            if retailer is None:
672
                resp.body = "{}"
673
                return
15239 amit.gupta 674
            fetchInfo = FetchDataHistory()
675
            fetchInfo.agent_id = self.agentId
676
            fetchInfo.call_type = self.callType
15240 amit.gupta 677
            agent = session.query(Agents).filter_by(id=self.agentId).first()
15239 amit.gupta 678
            last_disposition = session.query(CallHistory).filter_by(agent_id=self.agentId).order_by(CallHistory.id.desc()).first()
679
            if last_disposition is None or last_disposition.created < agent.last_login:
680
                fetchInfo.last_action = 'login'
681
                fetchInfo.last_action_time = agent.last_login 
682
            else:
683
                fetchInfo.last_action = 'disposition'
684
                fetchInfo.last_action_time = last_disposition.created
685
            fetchInfo.retailer_id = retailer.id
686
            session.commit()
15241 amit.gupta 687
 
15358 amit.gupta 688
            otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
689
            resp.body = json.dumps(todict(getRetailerObj(retailer, otherContacts, self.callType)), encoding='utf-8')
15241 amit.gupta 690
 
691
            return
692
 
15239 amit.gupta 693
        finally:
694
            session.close()
15241 amit.gupta 695
 
15081 amit.gupta 696
        if retailer is None:
15157 amit.gupta 697
            resp.body = "{}"
15081 amit.gupta 698
        else:
15358 amit.gupta 699
            print "It should never come here"
15081 amit.gupta 700
            resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
701
 
15241 amit.gupta 702
 
15081 amit.gupta 703
    def on_post(self, req, resp, agentId, callType):
15112 amit.gupta 704
        returned = False
15081 amit.gupta 705
        self.agentId = int(agentId)
706
        self.callType = callType
707
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15169 amit.gupta 708
        lgr.info( "Request ----\n"  + str(jsonReq))
15091 amit.gupta 709
        self.jsonReq = jsonReq
710
        invalidNumber = self.invalidNumber
711
        callLater = self.callLater
15096 amit.gupta 712
        alreadyUser = self.alReadyUser
15091 amit.gupta 713
        verifiedLinkSent = self.verifiedLinkSent
15368 amit.gupta 714
        onboarded = self.onboarded
15278 amit.gupta 715
        self.address = jsonReq.get('address')
15096 amit.gupta 716
        self.retailerId = int(jsonReq.get('retailerid'))
15671 amit.gupta 717
        self.smsNumber = jsonReq.get('smsnumber')
718
        if self.smsNumber is not None:
719
            self.smsNumber = self.smsNumber.strip().lstrip("0") 
15112 amit.gupta 720
        try:
721
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
15281 amit.gupta 722
            if self.address:
15278 amit.gupta 723
                self.retailer.address_new = self.address
15112 amit.gupta 724
            self.callDisposition = jsonReq.get('calldispositiontype')
725
            self.callHistory = CallHistory()
726
            self.callHistory.agent_id=self.agentId
727
            self.callHistory.call_disposition = self.callDisposition
728
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 729
            self.callHistory.call_type=self.callType
15112 amit.gupta 730
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
731
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 732
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
733
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 734
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
735
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 736
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 737
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
15368 amit.gupta 738
            if self.callDisposition == 'onboarded':
739
                self.checkList = jsonReq.get('checklist')
740
 
15234 amit.gupta 741
            if lastFetchData is None:
742
                raise
743
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 744
 
745
            dispositionMap = {  'call_later':callLater,
746
                        'ringing_no_answer':callLater,
747
                        'not_reachable':callLater,
748
                        'switch_off':callLater,
15202 manas 749
                        'not_retailer':invalidNumber,
15112 amit.gupta 750
                        'invalid_no':invalidNumber,
751
                        'wrong_no':invalidNumber,
752
                        'hang_up':invalidNumber,
753
                        'retailer_not_interested':invalidNumber,
15200 manas 754
                        'recharge_retailer':invalidNumber,
755
                        'accessory_retailer':invalidNumber,
756
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 757
                        'alreadyuser':alreadyUser,
15368 amit.gupta 758
                        'verified_link_sent':verifiedLinkSent,
759
                        'onboarded':onboarded
15112 amit.gupta 760
                      }
761
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
762
        finally:
763
            session.close()
15096 amit.gupta 764
 
15112 amit.gupta 765
        if returned:
766
            resp.body = "{\"result\":\"success\"}"
767
        else:
768
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 769
 
15091 amit.gupta 770
    def invalidNumber(self,):
15108 manas 771
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
772
        if self.callDisposition == 'invalid_no':
773
            self.retailer.status='failed'
774
            self.callHistory.disposition_description = 'Invalid Number'
775
        elif self.callDisposition == 'wrong_no':
15111 manas 776
            self.retailer.status='failed'
777
            self.callHistory.disposition_description = 'Wrong Number'
778
        elif self.callDisposition == 'hang_up':
779
            self.retailer.status='failed'
780
            self.callHistory.disposition_description = 'Hang Up'
781
        elif self.callDisposition == 'retailer_not_interested':
782
            self.retailer.status='failed'
783
            if self.callHistory.disposition_description is None:
784
                self.callHistory.disposition_description = 'NA'
15200 manas 785
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
786
        elif self.callDisposition == 'recharge_retailer':
787
            self.retailer.status='failed'
788
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
789
        elif self.callDisposition == 'accessory_retailer':
790
            self.retailer.status='failed'
791
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
792
        elif self.callDisposition == 'service_center_retailer':
793
            self.retailer.status='failed'
794
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 795
        elif self.callDisposition == 'not_retailer':
796
            self.retailer.status='failed'
797
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 798
        session.commit()
799
        return True   
800
 
15132 amit.gupta 801
    def getCode(self,):
15207 amit.gupta 802
        newCode = None
803
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
804
        if lastLink is not None:
805
            if len(lastLink.code)==len(codesys):
806
                newCode=lastLink.code
807
        return getNextCode(codesys, newCode)
15108 manas 808
 
15254 amit.gupta 809
 
15091 amit.gupta 810
    def callLater(self,):
15368 amit.gupta 811
        self.retailer.status = RETRY_MAP.get(self.callType)
15100 amit.gupta 812
        self.retailer.call_priority = None
15096 amit.gupta 813
        if self.callDisposition == 'call_later':
15100 amit.gupta 814
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 815
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 816
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
817
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
818
            else:
15102 amit.gupta 819
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 820
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 821
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
822
        else: 
823
            if self.callDisposition == 'ringing_no_answer':
824
                if self.retailer.disposition == 'ringing_no_answer':
825
                    self.retailer.retry_count += 1
826
                else:
827
                    self.retailer.disposition = 'ringing_no_answer'
828
                    self.retailer.retry_count = 1
829
            else:
830
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 831
                    pass
15112 amit.gupta 832
                else:
15119 amit.gupta 833
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 834
                self.retailer.retry_count += 1
835
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 836
 
15122 amit.gupta 837
            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 838
            if retryConfig is not None:
839
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 840
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 841
            else:
842
                self.retailer.status = 'failed'
843
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 844
 
15101 amit.gupta 845
        session.commit()
846
        return True
15096 amit.gupta 847
 
15100 amit.gupta 848
 
15091 amit.gupta 849
    def alReadyUser(self,):
15112 amit.gupta 850
        self.retailer.status = self.callDisposition
15117 amit.gupta 851
        if self.callHistory.disposition_description is None:
852
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 853
        session.commit()
854
        return True
15091 amit.gupta 855
    def verifiedLinkSent(self,):
15147 amit.gupta 856
        if self.callType == 'fresh':
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=1)
860
            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') 
861
        else:
15224 amit.gupta 862
            self.retailer.status = 'followup'
15548 amit.gupta 863
            self.retailer.agent_id = None
15147 amit.gupta 864
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
15254 amit.gupta 865
            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 866
        addContactToRetailer(self.agentId, self.retailerId, self.smsNumber, self.callType, 'sms')     
15146 amit.gupta 867
        session.commit()
868
        return True
15368 amit.gupta 869
    def onboarded(self,):
870
        self.retailer.status = self.callDisposition
871
        checkList = OnboardedRetailerChecklists()
872
        checkList.contact_us = self.checkList.get('contactus')
15390 amit.gupta 873
        checkList.doa_return_policy = self.checkList.get('doareturnpolicy')
15368 amit.gupta 874
        checkList.number_verification = self.checkList.get('numberverification')
875
        checkList.payment_option = self.checkList.get('paymentoption')
876
        checkList.preferences = self.checkList.get('preferences')
877
        checkList.product_info = self.checkList.get('productinfo')
15372 amit.gupta 878
        checkList.redeem = self.checkList.get('redeem')
15368 amit.gupta 879
        checkList.retailer_id = self.retailerId
880
        session.commit()
881
        return True
882
 
883
 
15254 amit.gupta 884
def isActivated(retailerId):
15276 amit.gupta 885
    retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailerId).first()
15448 amit.gupta 886
    user = session.query(Users).filter(or_(func.lower(Users.referrer)==retailerLink.code.lower(), Users.utm_campaign==retailerLink.code)).first()
15276 amit.gupta 887
    if user is None:
888
        mobileNumbers = list(session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailerId).all())
889
        user = session.query(Users).filter(Users.mobile_number.in_(mobileNumbers)).first()
15254 amit.gupta 890
        if user is None:
15332 amit.gupta 891
            if retailerLink.created < datetime(2015,5,26):
15333 amit.gupta 892
                historyNumbers = [number for number, in session.query(CallHistory.mobile_number).filter_by(retailer_id = retailerId).all()]
15476 amit.gupta 893
                user = session.query(Users).filter(Users.mobile_number.in_(historyNumbers)).first()
15332 amit.gupta 894
                if user is None:
895
                    return False
15334 amit.gupta 896
                else:
897
                    mapped_with = 'contact'
15332 amit.gupta 898
            else:
899
                return False
15276 amit.gupta 900
        else:
901
            mapped_with = 'contact'
902
    else:
903
        mapped_with = 'code'
904
    retailerLink.mapped_with = mapped_with
15388 amit.gupta 905
    if user.activation_time is not None:
15448 amit.gupta 906
        retailerLink.activated = user.activation_time
907
    retailerLink.activated = user.created
15276 amit.gupta 908
    retailerLink.user_id = user.id
15291 amit.gupta 909
    retailer = session.query(Retailers).filter_by(id=retailerId).first()
15574 amit.gupta 910
    if retailer.status == 'followup' or retailer.status == 'fretry':
15389 amit.gupta 911
        retailer.status = 'onboarding'
15548 amit.gupta 912
        retailer.agent_id = None
15391 amit.gupta 913
        retailer.call_priority = None
914
        retailer.next_call_time = None
915
        retailer.retry_count = 0
916
        retailer.invalid_retry_count = 0
15276 amit.gupta 917
    session.commit()
15287 amit.gupta 918
    print "retailerLink.retailer_id", retailerLink.retailer_id
15700 amit.gupta 919
    print "retailer", retailer.id
15276 amit.gupta 920
    session.close()
921
    return True
15254 amit.gupta 922
 
923
class AddContactToRetailer():
924
    def on_post(self,req,resp, agentId):
925
        agentId = int(agentId)
926
        try:
927
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
928
            retailerId = int(jsonReq.get("retailerid"))
929
            mobile = jsonReq.get("mobile")
930
            callType = jsonReq.get("calltype")
931
            contactType = jsonReq.get("contacttype")
932
            addContactToRetailer(agentId, retailerId, mobile, callType, contactType)
933
            session.commit()
934
        finally:
935
            session.close()
15676 amit.gupta 936
 
15677 amit.gupta 937
class AddAddressToRetailer():
15676 amit.gupta 938
    def on_post(self,req,resp, agentId):
939
        agentId = int(agentId)
15678 amit.gupta 940
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
941
        retailerId = int(jsonReq.get("retailerid"))
15684 amit.gupta 942
        address = str(jsonReq.get("address"))
943
        storeName = str(jsonReq.get("storename"))
944
        pin = str(jsonReq.get("pin"))
945
        city = str(jsonReq.get("city"))
946
        state = str(jsonReq.get("state"))
947
        updateType = str(jsonReq.get("updatetype"))
15678 amit.gupta 948
        addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType)
15254 amit.gupta 949
 
950
def addContactToRetailer(agentId, retailerId, mobile, callType, contactType):
15312 amit.gupta 951
    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=retailerId).filter_by(mobile_number=mobile).first()
952
    if retailerContact is None:
15254 amit.gupta 953
        retailerContact = RetailerContacts()
15256 amit.gupta 954
        retailerContact.retailer_id = retailerId
15254 amit.gupta 955
        retailerContact.agent_id = agentId
956
        retailerContact.call_type = callType
957
        retailerContact.contact_type = contactType
958
        retailerContact.mobile_number = mobile
15312 amit.gupta 959
    else:
15327 amit.gupta 960
        if CONTACT_PRIORITY.index(retailerContact.contact_type) > CONTACT_PRIORITY.index(contactType):
15358 amit.gupta 961
            retailerContact.contact_type = contactType
15676 amit.gupta 962
 
963
def addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType):
15679 amit.gupta 964
    print "I am in addAddress"
15682 amit.gupta 965
    print agentId, retailerId, address, storeName, pin, city, state, updateType
15679 amit.gupta 966
    try:
967
        if updateType=='new':
15685 amit.gupta 968
            retailer = session.query(Retailers).filter_by(id=retailerId).first()
15679 amit.gupta 969
            retailer.address = address
970
            retailer.title = storeName
971
            retailer.city = city
972
            retailer.state = state
973
            retailer.pin = pin
974
        raddress = RetailerAddresses()
975
        raddress.address = address
15682 amit.gupta 976
        raddress.title = storeName
15679 amit.gupta 977
        raddress.agent_id = agentId
978
        raddress.city = city
979
        raddress.pin = pin
980
        raddress.retailer_id = retailerId
981
        raddress.state = state
982
        session.commit()
983
    finally:
984
        session.close() 
15254 amit.gupta 985
 
15312 amit.gupta 986
 
15189 manas 987
class Login():
988
 
989
    def on_get(self, req, resp, agentId, role):
990
        try:
15198 manas 991
            self.agentId = int(agentId)
992
            self.role = role
993
            print str(self.agentId) + self.role;
15199 manas 994
            agents=AgentLoginTimings()
995
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
996
            print 'lastLogintime' + str(lastLoginTime)
997
            agents.loginTime=lastLoginTime.last_login
998
            agents.logoutTime=datetime.now()
999
            agents.role =self.role
15282 amit.gupta 1000
            agents.agent_id = self.agentId
15199 manas 1001
            session.add(agents)    
1002
            session.commit()
1003
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 1004
        finally:
1005
            session.close()        
15112 amit.gupta 1006
 
15189 manas 1007
    def on_post(self,req,resp):
1008
        try:
1009
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1010
            lgr.info( "Request ----\n"  + str(jsonReq))
1011
            email=jsonReq.get('email')
1012
            password = jsonReq.get('password')
1013
            role=jsonReq.get('role')    
15531 amit.gupta 1014
            agent = session.query(Agents).filter(and_(Agents.email==email,Agents.password==password)).first()
1015
            if agent is None:
15189 manas 1016
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
1017
            else:
15531 amit.gupta 1018
                print agent.id
1019
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==agent.id,Agent_Roles.role==role)).first()
15189 manas 1020
                if checkRole is None:
1021
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
1022
                else:
15531 amit.gupta 1023
                    agent.last_login = datetime.now()
1024
                    agent.login_type = role
1025
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":agent.id}}, encoding='utf-8')
1026
                    session.commit()
15195 manas 1027
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 1028
        finally:
1029
            session.close()    
1030
 
15195 manas 1031
    def test(self,email,password,role):
15189 manas 1032
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
1033
        if checkUser is None:
1034
            print checkUser
15195 manas 1035
 
15189 manas 1036
        else:
1037
            print checkUser[0]
1038
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
1039
            if checkRole is None:
15195 manas 1040
                pass
15189 manas 1041
            else:
15195 manas 1042
                agents=AgentLoginTimings()
1043
                agents.loginTime=datetime.now()
1044
                agents.logoutTime=datetime.now()
1045
                agents.role =role
1046
                agents.agent_id = 2
1047
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
1048
                session.add(agents)    
1049
                session.commit()
1050
                session.close()
1051
 
1052
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15275 amit.gupta 1053
 
1054
class RetailerActivation():
1055
    def on_get(self, req, resp, userId):
15351 amit.gupta 1056
        res =  markDealerActivation(int(userId))
1057
        if res:
1058
            resp.body = "{\"activated\":true}"
1059
        else:
1060
            resp.body = "{\"activated\":false}"
1061
 
15275 amit.gupta 1062
 
1063
def markDealerActivation(userId):
1064
    try:
15343 amit.gupta 1065
        user = session.query(Users).filter_by(id=userId).first()
15275 amit.gupta 1066
        result = False                
1067
        mappedWith = 'contact'
15534 amit.gupta 1068
        retailer = None
15275 amit.gupta 1069
        if user is not None:
15454 amit.gupta 1070
            referrer = None if user.referrer is None else user.referrer.upper()
1071
            retailerLink = session.query(RetailerLinks).filter(or_(RetailerLinks.code==referrer, RetailerLinks.code==user.utm_campaign)).first()
15275 amit.gupta 1072
            if retailerLink is None:
15501 amit.gupta 1073
                if user.mobile_number is not None:
1074
                    retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
1075
                    if retailerContact is None:
15613 amit.gupta 1076
                        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 1077
                    else:
1078
                        retailer = session.query(Retailers).filter_by(id = retailerContact.retailer_id).first()
15275 amit.gupta 1079
            else:
1080
                retailer = session.query(Retailers).filter_by(id = retailerLink.retailer_id).first()
1081
                mappedWith='code'
1082
            if retailer is not None:
1083
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailer.id).first()
1084
                if retailerLink is not None:
1085
                    retailerLink.user_id = user.id
1086
                    retailerLink.mapped_with=mappedWith
15358 amit.gupta 1087
                    retailer.status = 'onboarding'
15275 amit.gupta 1088
                    result = True
1089
                    session.commit()
15574 amit.gupta 1090
        return result
15275 amit.gupta 1091
    finally:
1092
        session.close()
1093
 
15189 manas 1094
 
15081 amit.gupta 1095
def todict(obj, classkey=None):
1096
    if isinstance(obj, dict):
1097
        data = {}
1098
        for (k, v) in obj.items():
1099
            data[k] = todict(v, classkey)
1100
        return data
1101
    elif hasattr(obj, "_ast"):
1102
        return todict(obj._ast())
1103
    elif hasattr(obj, "__iter__"):
1104
        return [todict(v, classkey) for v in obj]
1105
    elif hasattr(obj, "__dict__"):
1106
        data = dict([(key, todict(value, classkey)) 
1107
            for key, value in obj.__dict__.iteritems() 
1108
            if not callable(value) and not key.startswith('_')])
1109
        if classkey is not None and hasattr(obj, "__class__"):
1110
            data[classkey] = obj.__class__.__name__
1111
        return data
1112
    else:
1113
        return obj
1114
 
15358 amit.gupta 1115
def getRetailerObj(retailer, otherContacts1=None, callType=None):
15324 amit.gupta 1116
    print "before otherContacts1",otherContacts1
1117
    otherContacts = [] if otherContacts1 is None else otherContacts1
15662 amit.gupta 1118
    print "after otherContacts1",otherContacts
15081 amit.gupta 1119
    obj = Mock()
15280 amit.gupta 1120
    obj.id = retailer.id
15686 amit.gupta 1121
 
1122
 
15314 amit.gupta 1123
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts:
15315 amit.gupta 1124
        otherContacts.append(retailer.contact1)
15314 amit.gupta 1125
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts:
15315 amit.gupta 1126
        otherContacts.append(retailer.contact2)
15323 amit.gupta 1127
    obj.contact1 = None if len(otherContacts)==0 else otherContacts[0]
15325 amit.gupta 1128
    if obj.contact1 is not None:
1129
        obj.contact2 = None if len(otherContacts)==1 else otherContacts[1]
15096 amit.gupta 1130
    obj.scheduled = (retailer.call_priority is not None)
15686 amit.gupta 1131
    address = None
1132
    try:
1133
        address = session.query(RetailerAddresses).filter_by(retailer_id=retailer.id).order_by(RetailerAddresses.created.desc()).first()
1134
    finally:
1135
        session.close()
1136
    if address is not None:
1137
        obj.address = address.address
1138
        obj.title = address.title
1139
        obj.city = address.city
1140
        obj.state = address.state
1141
        obj.pin = address.pin 
1142
    else:
1143
        obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
1144
        obj.title = retailer.title
1145
        obj.city = retailer.city
1146
        obj.state = retailer.state
1147
        obj.pin = retailer.pin 
15699 amit.gupta 1148
    obj.status = retailer.status
15686 amit.gupta 1149
 
15662 amit.gupta 1150
    if hasattr(retailer, 'contact'):
1151
        obj.contact = retailer.contact
15358 amit.gupta 1152
    if callType == 'onboarding':
1153
        try:
15364 amit.gupta 1154
            userId, activatedTime = session.query(RetailerLinks.user_id, RetailerLinks.activated).filter(RetailerLinks.retailer_id==retailer.id).first()
15366 amit.gupta 1155
            activated, = session.query(Users.activation_time).filter(Users.id==userId).first()
15364 amit.gupta 1156
            if activated is not None:
15366 amit.gupta 1157
                activatedTime = activated
15362 amit.gupta 1158
            obj.user_id = userId
15364 amit.gupta 1159
            obj.created = datetime.strftime(activatedTime, '%d/%m/%Y %H:%M:%S')
15358 amit.gupta 1160
            result = fetchResult("select * from useractive where user_id=%d"%(userId))
1161
            if result == ():
1162
                obj.last_active = None
1163
            else:
15360 amit.gupta 1164
                obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
15361 amit.gupta 1165
            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 1166
            obj.orders = ordersCount
1167
        finally:
1168
            session.close()
15081 amit.gupta 1169
    return obj
15091 amit.gupta 1170
 
15132 amit.gupta 1171
def make_tiny(code):
1172
    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 1173
    #request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1174
    #filehandle = urllib2.Request(request_url)
1175
    #x= urllib2.urlopen(filehandle)
15546 amit.gupta 1176
    try:
1177
        shortener = Shortener('TinyurlShortener')
1178
        returnUrl =  shortener.short(url)
1179
    except:
1180
        shortener = Shortener('SentalaShortener')
1181
        returnlUrl =  shortener.short(url)
1182
    return returnUrl
15171 amit.gupta 1183
 
15285 manas 1184
class SearchUser():
1185
 
1186
    def on_post(self, req, resp, agentId, searchType):
15314 amit.gupta 1187
        retailersJsonArray = []
15285 manas 1188
        try:
1189
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1190
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1191
            contact=jsonReq.get('searchTerm')
15285 manas 1192
            if(searchType=="number"):
15312 amit.gupta 1193
                retailer_ids = session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all()
1194
                retailer_ids = [r for r, in retailer_ids]    
1195
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact, Retailers.id.in_(retailer_ids))
1196
            else:
1197
                m = re.match("(.*?)(\d{6})(.*?)", contact)
1198
                if m is not None:
1199
                    pin = m.group(2)
1200
                    contact = m.group(1) if m.group(1) != '' else m.group(3)
15313 amit.gupta 1201
                    anotherCondition = and_(Retailers.title.ilike('%%%s%%'%(contact)), Retailers.pin==pin)
15312 amit.gupta 1202
                else:
1203
                    anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1204
 
15326 amit.gupta 1205
            retailers = session.query(Retailers).filter(anotherCondition).limit(20).all()
15312 amit.gupta 1206
            if retailers is None:
15285 manas 1207
                resp.body = json.dumps("{}")
15312 amit.gupta 1208
            else:
1209
                for retailer in retailers:
15326 amit.gupta 1210
                    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 1211
                    retailersJsonArray.append(todict(getRetailerObj(retailer, otherContacts)))    
1212
            resp.body = json.dumps({"Retailers":retailersJsonArray}, encoding='utf-8')
15312 amit.gupta 1213
            return
15285 manas 1214
        finally:
1215
            session.close()
15171 amit.gupta 1216
 
15081 amit.gupta 1217
 
1218
class Mock(object):
1219
    pass
15189 manas 1220
 
15312 amit.gupta 1221
def tagActivatedReatilers():
15613 amit.gupta 1222
    retailerIds = [r for  r, in session.query(RetailerLinks.retailer_id).filter_by(user_id = None).all()]
15312 amit.gupta 1223
    session.close()
15288 amit.gupta 1224
    for retailerId in retailerIds:
1225
        isActivated(retailerId)
15312 amit.gupta 1226
    session.close()
15374 kshitij.so 1227
 
1228
class StaticDeals():
1229
 
1230
    def on_get(self, req, resp):
1231
 
1232
        offset = req.get_param_as_int("offset")
1233
        limit = req.get_param_as_int("limit")
1234
        categoryId = req.get_param_as_int("categoryId")
15458 kshitij.so 1235
        direction = req.get_param_as_int("direction")
15374 kshitij.so 1236
 
15458 kshitij.so 1237
        result = Mongo.getStaticDeals(offset, limit, categoryId, direction)
15374 kshitij.so 1238
        resp.body = dumps(result)
1239
 
1240
 
1241
 
15312 amit.gupta 1242
def main():
15662 amit.gupta 1243
    #tagActivatedReatilers()
1244
    a = RetailerDetail()
1245
    retailer = a.getNotActiveRetailer()
1246
    otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
1247
    print json.dumps(todict(getRetailerObj(retailer, otherContacts, 'fresh')), encoding='utf-8')
15465 amit.gupta 1248
    #print make_tiny("AA")
15195 manas 1249
 
15081 amit.gupta 1250
if __name__ == '__main__':
15207 amit.gupta 1251
    main()
15091 amit.gupta 1252