Subversion Repositories SmartDukaan

Rev

Rev 16560 | Rev 16581 | 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):
16223 kshitij.so 219
        showDp = req.get_param_as_int("showDp")
16221 kshitij.so 220
        result = Mongo.getItem(skuId, showDp)
13798 kshitij.so 221
        try:
222
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 223
            resp.body = json.dumps(json_docs, encoding='utf-8')
13798 kshitij.so 224
        except:
225
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 226
            resp.body = json.dumps(json_docs, encoding='utf-8')
13790 kshitij.so 227
 
14586 kshitij.so 228
    def on_post(self,req, resp):
229
 
230
        addNew = req.get_param_as_int("addNew")
231
        update = req.get_param_as_int("update")
232
        addToExisting = req.get_param_as_int("addToExisting")
233
        multi = req.get_param_as_int("multi")
234
 
14589 kshitij.so 235
        try:
14592 kshitij.so 236
            result_json = json.loads(req.stream.read(), encoding='utf-8')
237
        except ValueError:
238
            raise falcon.HTTPError(falcon.HTTP_400,
239
                'Malformed JSON',
240
                'Could not decode the request body. The '
241
                'JSON was incorrect.')
242
 
243
        if addNew == 1:
244
            result = Mongo.addNewItem(result_json)
245
        elif update == 1:
246
            result = Mongo.updateMaster(result_json, multi)
247
        elif addToExisting == 1:
248
            result = Mongo.addItemToExistingBundle(result_json)
249
        else:
250
            raise
251
        resp.body = dumps(result)
14586 kshitij.so 252
 
13827 kshitij.so 253
class LiveData():
254
    def on_get(self,req, resp):
13865 kshitij.so 255
        if req.get_param_as_int("id") is not None:
256
            print "****getting only for id"
257
            id = req.get_param_as_int("id")
258
            try:
259
                result = FetchLivePrices.getLatestPriceById(id)
13867 kshitij.so 260
                json_docs = json.dumps(result, default=json_util.default)
13966 kshitij.so 261
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 262
            except:
263
                json_docs = json.dumps({}, default=json_util.default)
13966 kshitij.so 264
                resp.body = json.dumps(json_docs, encoding='utf-8')
13834 kshitij.so 265
 
13865 kshitij.so 266
        else:
267
            print "****getting only for skuId"
268
            skuBundleId = req.get_param_as_int("skuBundleId")
269
            source_id = req.get_param_as_int("source_id")
270
            try:
271
                result = FetchLivePrices.getLatestPrice(skuBundleId, source_id)
272
                json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 273
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 274
            except:
275
                json_docs = [json.dumps(doc, default=json_util.default) for doc in [{}]]
13966 kshitij.so 276
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 277
 
13834 kshitij.so 278
class CashBack():
279
    def on_get(self,req, resp):
280
        identifier = req.get_param("identifier")
281
        source_id = req.get_param_as_int("source_id")
282
        try:
13838 kshitij.so 283
            result = Mongo.getCashBackDetails(identifier, source_id)
13837 kshitij.so 284
            json_docs = json.dumps(result, default=json_util.default)
13964 kshitij.so 285
            resp.body = json_docs
13834 kshitij.so 286
        except:
13837 kshitij.so 287
            json_docs = json.dumps({}, default=json_util.default)
13963 kshitij.so 288
            resp.body = json_docs
13892 kshitij.so 289
 
14398 amit.gupta 290
class ImgSrc():
291
    def on_get(self,req, resp):
292
        identifier = req.get_param("identifier")
293
        source_id = req.get_param_as_int("source_id")
294
        try:
295
            result = Mongo.getImgSrc(identifier, source_id)
296
            json_docs = json.dumps(result, default=json_util.default)
297
            resp.body = json_docs
298
        except:
299
            json_docs = json.dumps({}, default=json_util.default)
300
            resp.body = json_docs
301
 
13892 kshitij.so 302
class DealSheet():
303
    def on_get(self,req, resp):
13895 kshitij.so 304
        X_DealSheet.sendMail()
13897 kshitij.so 305
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
13966 kshitij.so 306
        resp.body = json.dumps(json_docs, encoding='utf-8')
13892 kshitij.so 307
 
13970 kshitij.so 308
class DealerPrice():
309
 
310
    def on_get(self, req, resp):
311
 
312
        offset = req.get_param_as_int("offset")
313
        limit = req.get_param_as_int("limit")
314
        result = Mongo.getAllDealerPrices(offset,limit)
315
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
316
        resp.body = json.dumps(json_docs, encoding='utf-8')
317
 
318
    def on_post(self, req, resp):
319
 
14552 kshitij.so 320
        multi = req.get_param_as_int("multi")
321
 
13970 kshitij.so 322
        try:
323
            result_json = json.loads(req.stream.read(), encoding='utf-8')
324
        except ValueError:
325
            raise falcon.HTTPError(falcon.HTTP_400,
326
                'Malformed JSON',
327
                'Could not decode the request body. The '
328
                'JSON was incorrect.')
329
 
15852 kshitij.so 330
        result = Mongo.addSkuDealerPrice(result_json)
13970 kshitij.so 331
        resp.body = json.dumps(result, encoding='utf-8')
332
 
333
    def on_put(self, req, resp, _id):
334
        try:
335
            result_json = json.loads(req.stream.read(), encoding='utf-8')
336
        except ValueError:
337
            raise falcon.HTTPError(falcon.HTTP_400,
338
                'Malformed JSON',
339
                'Could not decode the request body. The '
340
                'JSON was incorrect.')
341
 
342
        result = Mongo.updateSkuDealerPrice(result_json, _id)
343
        resp.body = json.dumps(result, encoding='utf-8')
344
 
345
 
14041 kshitij.so 346
class ResetCache():
347
 
348
    def on_get(self,req, resp, userId):
14044 kshitij.so 349
        result = Mongo.resetCache(userId)
14046 kshitij.so 350
        resp.body = json.dumps(result, encoding='utf-8')
351
 
352
class UserDeals():
353
    def on_get(self,req,resp,userId):
354
        UserSpecificDeals.generateSheet(userId)
355
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
356
        resp.body = json.dumps(json_docs, encoding='utf-8')
14075 kshitij.so 357
 
358
class CommonUpdate():
359
 
360
    def on_post(self,req,resp):
14575 kshitij.so 361
 
362
        multi = req.get_param_as_int("multi")
363
 
14075 kshitij.so 364
        try:
365
            result_json = json.loads(req.stream.read(), encoding='utf-8')
366
        except ValueError:
367
            raise falcon.HTTPError(falcon.HTTP_400,
368
                'Malformed JSON',
369
                'Could not decode the request body. The '
370
                'JSON was incorrect.')
371
 
15852 kshitij.so 372
        result = Mongo.updateCollection(result_json)
14075 kshitij.so 373
        resp.body = json.dumps(result, encoding='utf-8')
14106 kshitij.so 374
        resp.content_type = "application/json; charset=utf-8"
14481 kshitij.so 375
 
376
class NegativeDeals():
377
 
378
    def on_get(self, req, resp):
379
 
380
        offset = req.get_param_as_int("offset")
381
        limit = req.get_param_as_int("limit")
382
 
383
        result = Mongo.getAllNegativeDeals(offset, limit)
14483 kshitij.so 384
        resp.body = dumps(result) 
14481 kshitij.so 385
 
386
 
387
    def on_post(self, req, resp):
388
 
14552 kshitij.so 389
        multi = req.get_param_as_int("multi")
390
 
14481 kshitij.so 391
        try:
392
            result_json = json.loads(req.stream.read(), encoding='utf-8')
393
        except ValueError:
394
            raise falcon.HTTPError(falcon.HTTP_400,
395
                'Malformed JSON',
396
                'Could not decode the request body. The '
397
                'JSON was incorrect.')
398
 
14552 kshitij.so 399
        result = Mongo.addNegativeDeals(result_json, multi)
14481 kshitij.so 400
        resp.body = json.dumps(result, encoding='utf-8')
401
 
402
class ManualDeals():
403
 
404
    def on_get(self, req, resp):
405
 
406
        offset = req.get_param_as_int("offset")
407
        limit = req.get_param_as_int("limit")
408
 
409
        result = Mongo.getAllManualDeals(offset, limit)
14483 kshitij.so 410
        resp.body = dumps(result)
14481 kshitij.so 411
 
412
 
413
    def on_post(self, req, resp):
414
 
14552 kshitij.so 415
        multi = req.get_param_as_int("multi")
416
 
14481 kshitij.so 417
        try:
418
            result_json = json.loads(req.stream.read(), encoding='utf-8')
419
        except ValueError:
420
            raise falcon.HTTPError(falcon.HTTP_400,
421
                'Malformed JSON',
422
                'Could not decode the request body. The '
423
                'JSON was incorrect.')
424
 
14552 kshitij.so 425
        result = Mongo.addManualDeal(result_json, multi)
14481 kshitij.so 426
        resp.body = json.dumps(result, encoding='utf-8')
427
 
428
class CommonDelete():
14482 kshitij.so 429
 
14481 kshitij.so 430
    def on_post(self,req,resp):
431
        try:
432
            result_json = json.loads(req.stream.read(), encoding='utf-8')
433
        except ValueError:
434
            raise falcon.HTTPError(falcon.HTTP_400,
435
                'Malformed JSON',
436
                'Could not decode the request body. The '
437
                'JSON was incorrect.')
438
 
439
        result = Mongo.deleteDocument(result_json)
440
        resp.body = json.dumps(result, encoding='utf-8')
441
        resp.content_type = "application/json; charset=utf-8"
14482 kshitij.so 442
 
443
class SearchProduct():
444
 
445
    def on_get(self,req,resp):
446
        offset = req.get_param_as_int("offset")
447
        limit = req.get_param_as_int("limit")
448
        search_term = req.get_param("search")
449
 
450
        result = Mongo.searchMaster(offset, limit, search_term)
14483 kshitij.so 451
        resp.body = dumps(result) 
14482 kshitij.so 452
 
453
 
14495 kshitij.so 454
class FeaturedDeals():
14482 kshitij.so 455
 
14495 kshitij.so 456
    def on_get(self, req, resp):
457
 
458
        offset = req.get_param_as_int("offset")
459
        limit = req.get_param_as_int("limit")
460
 
461
        result = Mongo.getAllFeaturedDeals(offset, limit)
462
        resp.body = dumps(result)
463
 
464
 
465
    def on_post(self, req, resp):
466
 
14552 kshitij.so 467
        multi = req.get_param_as_int("multi")
468
 
14495 kshitij.so 469
        try:
470
            result_json = json.loads(req.stream.read(), encoding='utf-8')
471
        except ValueError:
472
            raise falcon.HTTPError(falcon.HTTP_400,
473
                'Malformed JSON',
474
                'Could not decode the request body. The '
475
                'JSON was incorrect.')
476
 
14552 kshitij.so 477
        result = Mongo.addFeaturedDeal(result_json, multi)
14495 kshitij.so 478
        resp.body = json.dumps(result, encoding='utf-8')
479
 
14497 kshitij.so 480
 
481
class CommonSearch():
14495 kshitij.so 482
 
14497 kshitij.so 483
    def on_get(self,req,resp):
484
        class_name = req.get_param("class")
485
        sku = req.get_param_as_int("sku")
486
        skuBundleId = req.get_param_as_int("skuBundleId")
14499 kshitij.so 487
 
488
        result = Mongo.searchCollection(class_name, sku, skuBundleId)
14497 kshitij.so 489
        resp.body = dumps(result)
14619 kshitij.so 490
 
491
class CricScore():
492
 
493
    def on_get(self,req,resp):
494
 
495
        result = Mongo.getLiveCricScore()
14853 kshitij.so 496
        resp.body = dumps(result)
497
 
498
class Notification():
499
 
500
    def on_post(self, req, resp):
501
 
502
        try:
503
            result_json = json.loads(req.stream.read(), encoding='utf-8')
504
        except ValueError:
505
            raise falcon.HTTPError(falcon.HTTP_400,
506
                'Malformed JSON',
507
                'Could not decode the request body. The '
508
                'JSON was incorrect.')
509
 
510
        result = Mongo.addBundleToNotification(result_json)
511
        resp.body = json.dumps(result, encoding='utf-8')
512
 
513
    def on_get(self, req, resp):
514
 
515
        offset = req.get_param_as_int("offset")
516
        limit = req.get_param_as_int("limit")
517
 
518
        result = Mongo.getAllNotifications(offset, limit)
519
        resp.body = dumps(result)
520
 
14998 kshitij.so 521
class DealBrands():
14853 kshitij.so 522
 
14998 kshitij.so 523
    def on_get(self, req, resp):
524
 
525
        category_id = req.get_param_as_int("category_id")
526
        result = Mongo.getBrandsForFilter(category_id)
14999 kshitij.so 527
        resp.body = dumps(result)
15161 kshitij.so 528
 
529
class DealRank():
14998 kshitij.so 530
 
15161 kshitij.so 531
    def on_get(self, req, resp):
532
        identifier = req.get_param("identifier")
533
        source_id = req.get_param_as_int("source_id")
534
        user_id = req.get_param_as_int("user_id")
535
        result = Mongo.getDealRank(identifier, source_id, user_id)
536
        json_docs = json.dumps(result, default=json_util.default)
537
        resp.body = json_docs
538
 
539
 
16560 amit.gupta 540
class OrderedOffers():
541
    def on_get(self, req, resp, storeId, storeSku):
542
        storeId = int(storeId)
16563 amit.gupta 543
        result = Mongo.getBundleBySourceSku(storeId, storeSku)
544
        json_docs = json.dumps(result, default=json_util.default)
545
        resp.body = json_docs
546
 
15081 amit.gupta 547
class RetailerDetail():
548
    global RETAILER_DETAIL_CALL_COUNTER
15105 amit.gupta 549
    def getRetryRetailer(self,failback=True):
15358 amit.gupta 550
        status = RETRY_MAP.get(self.callType)
15239 amit.gupta 551
        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()
552
        if retailer is not None:
553
            lgr.info( "getRetryRetailer " + str(retailer.id))
554
        else:
555
            if failback:
556
                retailer = self.getNewRetailer(False)
557
                return retailer
16371 amit.gupta 558
            else:
559
                #No further calls for now
560
                return None
15358 amit.gupta 561
        retailer.status = ASSIGN_MAP.get(status)
16371 amit.gupta 562
        retailer.next_call_time = None
15239 amit.gupta 563
        lgr.info( "getRetryRetailer " + str(retailer.id))
15081 amit.gupta 564
        return retailer
565
 
15662 amit.gupta 566
    def getNotActiveRetailer(self):
567
        try:
15716 amit.gupta 568
            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 569
            if user is None: 
570
                return None
571
            else:
572
                retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
573
                if retailerContact is not None:
574
                    retailer = session.query(Retailers).filter_by(id=retailerContact.retailer_id).first()
575
                else:
576
                    retailer = session.query(Retailers).filter_by(contact1=user.mobile_number).first()
577
                    if retailer is None:
578
                        retailer = session.query(Retailers).filter_by(contact2=user.mobile_number).first()
579
                        if retailer is None:
580
                            retailer = Retailers()
581
                            retailer.contact1 = user.mobile_number
582
                            retailer.status = 'assigned'
15672 amit.gupta 583
                            retailer.retry_count = 0
15673 amit.gupta 584
                            retailer.invalid_retry_count = 0
15699 amit.gupta 585
                            retailer.is_elavated=1
15662 amit.gupta 586
                user.status = 2
587
                session.commit()
588
                print "retailer id", retailer.id
589
                retailer.contact = user.mobile_number
590
                return retailer
591
        finally:
592
            session.close()
593
 
15081 amit.gupta 594
    def getNewRetailer(self,failback=True):
15663 amit.gupta 595
        if self.callType == 'fresh':
596
            retailer = self.getNotActiveRetailer()
597
            if retailer is not None:
598
                return retailer
15081 amit.gupta 599
        retry = True
600
        retailer = None 
601
        try:
602
            while(retry):
15168 amit.gupta 603
                lgr.info( "Calltype " + self.callType)
15081 amit.gupta 604
                status=self.callType
15545 amit.gupta 605
                query = session.query(Retailers).filter(Retailers.status==status).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None))
15081 amit.gupta 606
                if status=='fresh':
15710 amit.gupta 607
                    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 608
                elif status=='followup':
15546 amit.gupta 609
                    query = query.filter(Retailers.next_call_time<=datetime.now()).order_by(Retailers.agent_id.desc(),Retailers.next_call_time)
15162 amit.gupta 610
                else:
15546 amit.gupta 611
                    query = query.filter(Retailers.modified<=datetime.now()).order_by(Retailers.agent_id.desc(), Retailers.modified)
15358 amit.gupta 612
 
15081 amit.gupta 613
                retailer = query.with_lockmode("update").first()
614
                if retailer is not None:
15168 amit.gupta 615
                    lgr.info( "retailer " +str(retailer.id))
15081 amit.gupta 616
                    if status=="fresh":
617
                        userquery = session.query(Users)
618
                        if retailer.contact2 is not None:
619
                            userquery = userquery.filter(Users.mobile_number.in_([retailer.contact1,retailer.contact2]))
620
                        else:
621
                            userquery = userquery.filter_by(mobile_number=retailer.contact1)
622
                        user = userquery.first()
623
                        if user is not None:
624
                            retailer.status = 'alreadyuser'
15168 amit.gupta 625
                            lgr.info( "retailer.status " + retailer.status)
15081 amit.gupta 626
                            session.commit()
627
                            continue
628
                        retailer.status = 'assigned'
15358 amit.gupta 629
                    elif status=='followup':
15276 amit.gupta 630
                        if isActivated(retailer.id):
631
                            print "Retailer Already %d activated and marked onboarded"%(retailer.id)
632
                            continue
15081 amit.gupta 633
                        retailer.status = 'fassigned'
15358 amit.gupta 634
                    else:
635
                        retailer.status = 'oassigned'
15081 amit.gupta 636
                    retailer.retry_count = 0
15123 amit.gupta 637
                    retailer.invalid_retry_count = 0
15168 amit.gupta 638
                    lgr.info( "Found Retailer " +  str(retailer.id) + " with status " + status + " assigned to " + str(self.agentId))
15081 amit.gupta 639
 
640
                else:
15168 amit.gupta 641
                    lgr.info( "No fresh/followup retailers found")
15081 amit.gupta 642
                    if failback:
643
                        retailer = self.getRetryRetailer(False)
15104 amit.gupta 644
                        return retailer
15148 amit.gupta 645
                retry=False
15081 amit.gupta 646
        except:
647
            print traceback.print_exc()
648
        return retailer
649
 
15132 amit.gupta 650
    def on_get(self, req, resp, agentId, callType=None, retailerId=None):
15081 amit.gupta 651
        global RETAILER_DETAIL_CALL_COUNTER
652
        RETAILER_DETAIL_CALL_COUNTER += 1
15168 amit.gupta 653
        lgr.info( "RETAILER_DETAIL_CALL_COUNTER " +  str(RETAILER_DETAIL_CALL_COUNTER))
15081 amit.gupta 654
        self.agentId = int(agentId)
655
        self.callType = callType
15139 amit.gupta 656
        if retailerId is not None:
657
            self.retailerId = int(retailerId)
15208 amit.gupta 658
            retailerLink = session.query(RetailerLinks).filter_by(retailer_id=self.retailerId).first()
15132 amit.gupta 659
            if retailerLink is not None:
660
                code = retailerLink.code
661
            else: 
662
                code = self.getCode()
663
                retailerLink = RetailerLinks()
664
                retailerLink.code = code
15139 amit.gupta 665
                retailerLink.agent_id = self.agentId
666
                retailerLink.retailer_id = self.retailerId
15135 amit.gupta 667
 
668
                activationCode=Activation_Codes()
669
                activationCode.code = code
15132 amit.gupta 670
                session.commit()
671
            session.close()
15142 amit.gupta 672
            resp.body =  json.dumps({"result":{"code":code,"link":make_tiny(code)}}, encoding='utf-8')
15132 amit.gupta 673
            return 
15081 amit.gupta 674
        retryFlag = False 
675
        if RETAILER_DETAIL_CALL_COUNTER % DEALER_RETRY_FACTOR ==0:
676
            retryFlag=True
15239 amit.gupta 677
        try:
678
            if retryFlag:
679
                retailer = self.getRetryRetailer()
680
            else:
681
                retailer = self.getNewRetailer()
15343 amit.gupta 682
            if retailer is None:
683
                resp.body = "{}"
684
                return
15239 amit.gupta 685
            fetchInfo = FetchDataHistory()
686
            fetchInfo.agent_id = self.agentId
687
            fetchInfo.call_type = self.callType
15240 amit.gupta 688
            agent = session.query(Agents).filter_by(id=self.agentId).first()
15239 amit.gupta 689
            last_disposition = session.query(CallHistory).filter_by(agent_id=self.agentId).order_by(CallHistory.id.desc()).first()
690
            if last_disposition is None or last_disposition.created < agent.last_login:
691
                fetchInfo.last_action = 'login'
692
                fetchInfo.last_action_time = agent.last_login 
693
            else:
694
                fetchInfo.last_action = 'disposition'
695
                fetchInfo.last_action_time = last_disposition.created
696
            fetchInfo.retailer_id = retailer.id
697
            session.commit()
15241 amit.gupta 698
 
15358 amit.gupta 699
            otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
700
            resp.body = json.dumps(todict(getRetailerObj(retailer, otherContacts, self.callType)), encoding='utf-8')
15241 amit.gupta 701
 
702
            return
703
 
15239 amit.gupta 704
        finally:
705
            session.close()
15241 amit.gupta 706
 
15081 amit.gupta 707
        if retailer is None:
15157 amit.gupta 708
            resp.body = "{}"
15081 amit.gupta 709
        else:
15358 amit.gupta 710
            print "It should never come here"
15081 amit.gupta 711
            resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
712
 
15241 amit.gupta 713
 
15081 amit.gupta 714
    def on_post(self, req, resp, agentId, callType):
15112 amit.gupta 715
        returned = False
15081 amit.gupta 716
        self.agentId = int(agentId)
717
        self.callType = callType
718
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15169 amit.gupta 719
        lgr.info( "Request ----\n"  + str(jsonReq))
15091 amit.gupta 720
        self.jsonReq = jsonReq
721
        invalidNumber = self.invalidNumber
722
        callLater = self.callLater
15096 amit.gupta 723
        alreadyUser = self.alReadyUser
15091 amit.gupta 724
        verifiedLinkSent = self.verifiedLinkSent
15368 amit.gupta 725
        onboarded = self.onboarded
15278 amit.gupta 726
        self.address = jsonReq.get('address')
15096 amit.gupta 727
        self.retailerId = int(jsonReq.get('retailerid'))
15671 amit.gupta 728
        self.smsNumber = jsonReq.get('smsnumber')
729
        if self.smsNumber is not None:
730
            self.smsNumber = self.smsNumber.strip().lstrip("0") 
15112 amit.gupta 731
        try:
732
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
15281 amit.gupta 733
            if self.address:
15278 amit.gupta 734
                self.retailer.address_new = self.address
15112 amit.gupta 735
            self.callDisposition = jsonReq.get('calldispositiontype')
736
            self.callHistory = CallHistory()
737
            self.callHistory.agent_id=self.agentId
738
            self.callHistory.call_disposition = self.callDisposition
739
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 740
            self.callHistory.call_type=self.callType
15112 amit.gupta 741
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
742
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 743
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
744
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 745
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
746
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 747
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 748
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
15368 amit.gupta 749
            if self.callDisposition == 'onboarded':
750
                self.checkList = jsonReq.get('checklist')
751
 
15234 amit.gupta 752
            if lastFetchData is None:
753
                raise
754
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 755
 
756
            dispositionMap = {  'call_later':callLater,
757
                        'ringing_no_answer':callLater,
758
                        'not_reachable':callLater,
759
                        'switch_off':callLater,
15202 manas 760
                        'not_retailer':invalidNumber,
15112 amit.gupta 761
                        'invalid_no':invalidNumber,
762
                        'wrong_no':invalidNumber,
763
                        'hang_up':invalidNumber,
764
                        'retailer_not_interested':invalidNumber,
15200 manas 765
                        'recharge_retailer':invalidNumber,
766
                        'accessory_retailer':invalidNumber,
767
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 768
                        'alreadyuser':alreadyUser,
15368 amit.gupta 769
                        'verified_link_sent':verifiedLinkSent,
770
                        'onboarded':onboarded
15112 amit.gupta 771
                      }
772
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
773
        finally:
774
            session.close()
15096 amit.gupta 775
 
15112 amit.gupta 776
        if returned:
777
            resp.body = "{\"result\":\"success\"}"
778
        else:
779
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 780
 
15091 amit.gupta 781
    def invalidNumber(self,):
15108 manas 782
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
783
        if self.callDisposition == 'invalid_no':
784
            self.retailer.status='failed'
785
            self.callHistory.disposition_description = 'Invalid Number'
786
        elif self.callDisposition == 'wrong_no':
15111 manas 787
            self.retailer.status='failed'
788
            self.callHistory.disposition_description = 'Wrong Number'
789
        elif self.callDisposition == 'hang_up':
790
            self.retailer.status='failed'
791
            self.callHistory.disposition_description = 'Hang Up'
792
        elif self.callDisposition == 'retailer_not_interested':
793
            self.retailer.status='failed'
794
            if self.callHistory.disposition_description is None:
795
                self.callHistory.disposition_description = 'NA'
15200 manas 796
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
797
        elif self.callDisposition == 'recharge_retailer':
798
            self.retailer.status='failed'
799
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
800
        elif self.callDisposition == 'accessory_retailer':
801
            self.retailer.status='failed'
802
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
803
        elif self.callDisposition == 'service_center_retailer':
804
            self.retailer.status='failed'
805
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 806
        elif self.callDisposition == 'not_retailer':
807
            self.retailer.status='failed'
808
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 809
        session.commit()
810
        return True   
811
 
15132 amit.gupta 812
    def getCode(self,):
15207 amit.gupta 813
        newCode = None
814
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
815
        if lastLink is not None:
816
            if len(lastLink.code)==len(codesys):
817
                newCode=lastLink.code
818
        return getNextCode(codesys, newCode)
15108 manas 819
 
15254 amit.gupta 820
 
15091 amit.gupta 821
    def callLater(self,):
15368 amit.gupta 822
        self.retailer.status = RETRY_MAP.get(self.callType)
15100 amit.gupta 823
        self.retailer.call_priority = None
15096 amit.gupta 824
        if self.callDisposition == 'call_later':
15100 amit.gupta 825
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 826
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 827
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
828
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
829
            else:
15102 amit.gupta 830
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 831
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 832
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
833
        else: 
834
            if self.callDisposition == 'ringing_no_answer':
835
                if self.retailer.disposition == 'ringing_no_answer':
836
                    self.retailer.retry_count += 1
837
                else:
838
                    self.retailer.disposition = 'ringing_no_answer'
839
                    self.retailer.retry_count = 1
840
            else:
841
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 842
                    pass
15112 amit.gupta 843
                else:
15119 amit.gupta 844
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 845
                self.retailer.retry_count += 1
846
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 847
 
15122 amit.gupta 848
            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 849
            if retryConfig is not None:
850
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 851
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 852
            else:
853
                self.retailer.status = 'failed'
854
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 855
 
15101 amit.gupta 856
        session.commit()
857
        return True
15096 amit.gupta 858
 
15100 amit.gupta 859
 
15091 amit.gupta 860
    def alReadyUser(self,):
15112 amit.gupta 861
        self.retailer.status = self.callDisposition
15117 amit.gupta 862
        if self.callHistory.disposition_description is None:
863
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 864
        session.commit()
865
        return True
15091 amit.gupta 866
    def verifiedLinkSent(self,):
15147 amit.gupta 867
        if self.callType == 'fresh':
868
            self.retailer.status = 'followup'
15548 amit.gupta 869
            self.retailer.agent_id = None
15147 amit.gupta 870
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
871
            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') 
872
        else:
15224 amit.gupta 873
            self.retailer.status = 'followup'
15548 amit.gupta 874
            self.retailer.agent_id = None
15147 amit.gupta 875
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
15254 amit.gupta 876
            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 877
        addContactToRetailer(self.agentId, self.retailerId, self.smsNumber, self.callType, 'sms')     
15146 amit.gupta 878
        session.commit()
879
        return True
15368 amit.gupta 880
    def onboarded(self,):
881
        self.retailer.status = self.callDisposition
882
        checkList = OnboardedRetailerChecklists()
883
        checkList.contact_us = self.checkList.get('contactus')
15390 amit.gupta 884
        checkList.doa_return_policy = self.checkList.get('doareturnpolicy')
15368 amit.gupta 885
        checkList.number_verification = self.checkList.get('numberverification')
886
        checkList.payment_option = self.checkList.get('paymentoption')
887
        checkList.preferences = self.checkList.get('preferences')
888
        checkList.product_info = self.checkList.get('productinfo')
15372 amit.gupta 889
        checkList.redeem = self.checkList.get('redeem')
15368 amit.gupta 890
        checkList.retailer_id = self.retailerId
891
        session.commit()
892
        return True
893
 
894
 
15254 amit.gupta 895
def isActivated(retailerId):
15276 amit.gupta 896
    retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailerId).first()
15448 amit.gupta 897
    user = session.query(Users).filter(or_(func.lower(Users.referrer)==retailerLink.code.lower(), Users.utm_campaign==retailerLink.code)).first()
15276 amit.gupta 898
    if user is None:
899
        mobileNumbers = list(session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailerId).all())
900
        user = session.query(Users).filter(Users.mobile_number.in_(mobileNumbers)).first()
15254 amit.gupta 901
        if user is None:
15332 amit.gupta 902
            if retailerLink.created < datetime(2015,5,26):
15333 amit.gupta 903
                historyNumbers = [number for number, in session.query(CallHistory.mobile_number).filter_by(retailer_id = retailerId).all()]
15476 amit.gupta 904
                user = session.query(Users).filter(Users.mobile_number.in_(historyNumbers)).first()
15332 amit.gupta 905
                if user is None:
906
                    return False
15334 amit.gupta 907
                else:
908
                    mapped_with = 'contact'
15332 amit.gupta 909
            else:
910
                return False
15276 amit.gupta 911
        else:
912
            mapped_with = 'contact'
913
    else:
914
        mapped_with = 'code'
915
    retailerLink.mapped_with = mapped_with
15388 amit.gupta 916
    if user.activation_time is not None:
15448 amit.gupta 917
        retailerLink.activated = user.activation_time
918
    retailerLink.activated = user.created
15276 amit.gupta 919
    retailerLink.user_id = user.id
15291 amit.gupta 920
    retailer = session.query(Retailers).filter_by(id=retailerId).first()
15574 amit.gupta 921
    if retailer.status == 'followup' or retailer.status == 'fretry':
15389 amit.gupta 922
        retailer.status = 'onboarding'
15548 amit.gupta 923
        retailer.agent_id = None
15391 amit.gupta 924
        retailer.call_priority = None
925
        retailer.next_call_time = None
926
        retailer.retry_count = 0
927
        retailer.invalid_retry_count = 0
15276 amit.gupta 928
    session.commit()
15287 amit.gupta 929
    print "retailerLink.retailer_id", retailerLink.retailer_id
15700 amit.gupta 930
    print "retailer", retailer.id
15276 amit.gupta 931
    session.close()
932
    return True
15254 amit.gupta 933
 
934
class AddContactToRetailer():
935
    def on_post(self,req,resp, agentId):
936
        agentId = int(agentId)
937
        try:
938
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
939
            retailerId = int(jsonReq.get("retailerid"))
940
            mobile = jsonReq.get("mobile")
941
            callType = jsonReq.get("calltype")
942
            contactType = jsonReq.get("contacttype")
943
            addContactToRetailer(agentId, retailerId, mobile, callType, contactType)
944
            session.commit()
945
        finally:
946
            session.close()
15676 amit.gupta 947
 
15677 amit.gupta 948
class AddAddressToRetailer():
15676 amit.gupta 949
    def on_post(self,req,resp, agentId):
950
        agentId = int(agentId)
15678 amit.gupta 951
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
952
        retailerId = int(jsonReq.get("retailerid"))
15684 amit.gupta 953
        address = str(jsonReq.get("address"))
954
        storeName = str(jsonReq.get("storename"))
955
        pin = str(jsonReq.get("pin"))
956
        city = str(jsonReq.get("city"))
957
        state = str(jsonReq.get("state"))
958
        updateType = str(jsonReq.get("updatetype"))
15678 amit.gupta 959
        addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType)
15254 amit.gupta 960
 
961
def addContactToRetailer(agentId, retailerId, mobile, callType, contactType):
15312 amit.gupta 962
    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=retailerId).filter_by(mobile_number=mobile).first()
963
    if retailerContact is None:
15254 amit.gupta 964
        retailerContact = RetailerContacts()
15256 amit.gupta 965
        retailerContact.retailer_id = retailerId
15254 amit.gupta 966
        retailerContact.agent_id = agentId
967
        retailerContact.call_type = callType
968
        retailerContact.contact_type = contactType
969
        retailerContact.mobile_number = mobile
15312 amit.gupta 970
    else:
15327 amit.gupta 971
        if CONTACT_PRIORITY.index(retailerContact.contact_type) > CONTACT_PRIORITY.index(contactType):
15358 amit.gupta 972
            retailerContact.contact_type = contactType
15676 amit.gupta 973
 
974
def addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType):
15679 amit.gupta 975
    print "I am in addAddress"
15682 amit.gupta 976
    print agentId, retailerId, address, storeName, pin, city, state, updateType
15679 amit.gupta 977
    try:
978
        if updateType=='new':
15685 amit.gupta 979
            retailer = session.query(Retailers).filter_by(id=retailerId).first()
15679 amit.gupta 980
            retailer.address = address
981
            retailer.title = storeName
982
            retailer.city = city
983
            retailer.state = state
984
            retailer.pin = pin
985
        raddress = RetailerAddresses()
986
        raddress.address = address
15682 amit.gupta 987
        raddress.title = storeName
15679 amit.gupta 988
        raddress.agent_id = agentId
989
        raddress.city = city
990
        raddress.pin = pin
991
        raddress.retailer_id = retailerId
992
        raddress.state = state
993
        session.commit()
994
    finally:
995
        session.close() 
15254 amit.gupta 996
 
15312 amit.gupta 997
 
15189 manas 998
class Login():
999
 
1000
    def on_get(self, req, resp, agentId, role):
1001
        try:
15198 manas 1002
            self.agentId = int(agentId)
1003
            self.role = role
1004
            print str(self.agentId) + self.role;
15199 manas 1005
            agents=AgentLoginTimings()
1006
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
1007
            print 'lastLogintime' + str(lastLoginTime)
1008
            agents.loginTime=lastLoginTime.last_login
1009
            agents.logoutTime=datetime.now()
1010
            agents.role =self.role
15282 amit.gupta 1011
            agents.agent_id = self.agentId
15199 manas 1012
            session.add(agents)    
1013
            session.commit()
1014
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 1015
        finally:
1016
            session.close()        
15112 amit.gupta 1017
 
15189 manas 1018
    def on_post(self,req,resp):
1019
        try:
1020
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1021
            lgr.info( "Request ----\n"  + str(jsonReq))
1022
            email=jsonReq.get('email')
1023
            password = jsonReq.get('password')
1024
            role=jsonReq.get('role')    
15531 amit.gupta 1025
            agent = session.query(Agents).filter(and_(Agents.email==email,Agents.password==password)).first()
1026
            if agent is None:
15189 manas 1027
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
1028
            else:
15531 amit.gupta 1029
                print agent.id
1030
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==agent.id,Agent_Roles.role==role)).first()
15189 manas 1031
                if checkRole is None:
1032
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
1033
                else:
15531 amit.gupta 1034
                    agent.last_login = datetime.now()
1035
                    agent.login_type = role
1036
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":agent.id}}, encoding='utf-8')
1037
                    session.commit()
15195 manas 1038
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 1039
        finally:
1040
            session.close()    
1041
 
15195 manas 1042
    def test(self,email,password,role):
15189 manas 1043
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
1044
        if checkUser is None:
1045
            print checkUser
15195 manas 1046
 
15189 manas 1047
        else:
1048
            print checkUser[0]
1049
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
1050
            if checkRole is None:
15195 manas 1051
                pass
15189 manas 1052
            else:
15195 manas 1053
                agents=AgentLoginTimings()
1054
                agents.loginTime=datetime.now()
1055
                agents.logoutTime=datetime.now()
1056
                agents.role =role
1057
                agents.agent_id = 2
1058
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
1059
                session.add(agents)    
1060
                session.commit()
1061
                session.close()
1062
 
1063
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15275 amit.gupta 1064
 
1065
class RetailerActivation():
1066
    def on_get(self, req, resp, userId):
15351 amit.gupta 1067
        res =  markDealerActivation(int(userId))
1068
        if res:
1069
            resp.body = "{\"activated\":true}"
1070
        else:
1071
            resp.body = "{\"activated\":false}"
1072
 
15275 amit.gupta 1073
 
1074
def markDealerActivation(userId):
1075
    try:
15343 amit.gupta 1076
        user = session.query(Users).filter_by(id=userId).first()
15275 amit.gupta 1077
        result = False                
1078
        mappedWith = 'contact'
15534 amit.gupta 1079
        retailer = None
15275 amit.gupta 1080
        if user is not None:
15454 amit.gupta 1081
            referrer = None if user.referrer is None else user.referrer.upper()
1082
            retailerLink = session.query(RetailerLinks).filter(or_(RetailerLinks.code==referrer, RetailerLinks.code==user.utm_campaign)).first()
15275 amit.gupta 1083
            if retailerLink is None:
15501 amit.gupta 1084
                if user.mobile_number is not None:
1085
                    retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
1086
                    if retailerContact is None:
15613 amit.gupta 1087
                        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 1088
                    else:
1089
                        retailer = session.query(Retailers).filter_by(id = retailerContact.retailer_id).first()
15275 amit.gupta 1090
            else:
1091
                retailer = session.query(Retailers).filter_by(id = retailerLink.retailer_id).first()
1092
                mappedWith='code'
1093
            if retailer is not None:
1094
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailer.id).first()
1095
                if retailerLink is not None:
1096
                    retailerLink.user_id = user.id
1097
                    retailerLink.mapped_with=mappedWith
15358 amit.gupta 1098
                    retailer.status = 'onboarding'
15275 amit.gupta 1099
                    result = True
1100
                    session.commit()
15574 amit.gupta 1101
        return result
15275 amit.gupta 1102
    finally:
1103
        session.close()
1104
 
15189 manas 1105
 
15081 amit.gupta 1106
def todict(obj, classkey=None):
1107
    if isinstance(obj, dict):
1108
        data = {}
1109
        for (k, v) in obj.items():
1110
            data[k] = todict(v, classkey)
1111
        return data
1112
    elif hasattr(obj, "_ast"):
1113
        return todict(obj._ast())
1114
    elif hasattr(obj, "__iter__"):
1115
        return [todict(v, classkey) for v in obj]
1116
    elif hasattr(obj, "__dict__"):
1117
        data = dict([(key, todict(value, classkey)) 
1118
            for key, value in obj.__dict__.iteritems() 
1119
            if not callable(value) and not key.startswith('_')])
1120
        if classkey is not None and hasattr(obj, "__class__"):
1121
            data[classkey] = obj.__class__.__name__
1122
        return data
1123
    else:
1124
        return obj
1125
 
15358 amit.gupta 1126
def getRetailerObj(retailer, otherContacts1=None, callType=None):
15324 amit.gupta 1127
    print "before otherContacts1",otherContacts1
1128
    otherContacts = [] if otherContacts1 is None else otherContacts1
15662 amit.gupta 1129
    print "after otherContacts1",otherContacts
15081 amit.gupta 1130
    obj = Mock()
15280 amit.gupta 1131
    obj.id = retailer.id
15686 amit.gupta 1132
 
1133
 
15314 amit.gupta 1134
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts:
15315 amit.gupta 1135
        otherContacts.append(retailer.contact1)
15314 amit.gupta 1136
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts:
15315 amit.gupta 1137
        otherContacts.append(retailer.contact2)
15323 amit.gupta 1138
    obj.contact1 = None if len(otherContacts)==0 else otherContacts[0]
15325 amit.gupta 1139
    if obj.contact1 is not None:
1140
        obj.contact2 = None if len(otherContacts)==1 else otherContacts[1]
15096 amit.gupta 1141
    obj.scheduled = (retailer.call_priority is not None)
15686 amit.gupta 1142
    address = None
1143
    try:
1144
        address = session.query(RetailerAddresses).filter_by(retailer_id=retailer.id).order_by(RetailerAddresses.created.desc()).first()
1145
    finally:
1146
        session.close()
1147
    if address is not None:
1148
        obj.address = address.address
1149
        obj.title = address.title
1150
        obj.city = address.city
1151
        obj.state = address.state
1152
        obj.pin = address.pin 
1153
    else:
1154
        obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
1155
        obj.title = retailer.title
1156
        obj.city = retailer.city
1157
        obj.state = retailer.state
1158
        obj.pin = retailer.pin 
15699 amit.gupta 1159
    obj.status = retailer.status
15686 amit.gupta 1160
 
15662 amit.gupta 1161
    if hasattr(retailer, 'contact'):
1162
        obj.contact = retailer.contact
15358 amit.gupta 1163
    if callType == 'onboarding':
1164
        try:
15364 amit.gupta 1165
            userId, activatedTime = session.query(RetailerLinks.user_id, RetailerLinks.activated).filter(RetailerLinks.retailer_id==retailer.id).first()
15366 amit.gupta 1166
            activated, = session.query(Users.activation_time).filter(Users.id==userId).first()
15364 amit.gupta 1167
            if activated is not None:
15366 amit.gupta 1168
                activatedTime = activated
15362 amit.gupta 1169
            obj.user_id = userId
15364 amit.gupta 1170
            obj.created = datetime.strftime(activatedTime, '%d/%m/%Y %H:%M:%S')
15358 amit.gupta 1171
            result = fetchResult("select * from useractive where user_id=%d"%(userId))
1172
            if result == ():
1173
                obj.last_active = None
1174
            else:
15360 amit.gupta 1175
                obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
15361 amit.gupta 1176
            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 1177
            obj.orders = ordersCount
1178
        finally:
1179
            session.close()
15081 amit.gupta 1180
    return obj
15091 amit.gupta 1181
 
15132 amit.gupta 1182
def make_tiny(code):
1183
    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 1184
    #request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1185
    #filehandle = urllib2.Request(request_url)
1186
    #x= urllib2.urlopen(filehandle)
15546 amit.gupta 1187
    try:
1188
        shortener = Shortener('TinyurlShortener')
1189
        returnUrl =  shortener.short(url)
1190
    except:
1191
        shortener = Shortener('SentalaShortener')
1192
        returnlUrl =  shortener.short(url)
1193
    return returnUrl
15171 amit.gupta 1194
 
15285 manas 1195
class SearchUser():
1196
 
1197
    def on_post(self, req, resp, agentId, searchType):
15314 amit.gupta 1198
        retailersJsonArray = []
15285 manas 1199
        try:
1200
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1201
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1202
            contact=jsonReq.get('searchTerm')
15285 manas 1203
            if(searchType=="number"):
15312 amit.gupta 1204
                retailer_ids = session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all()
1205
                retailer_ids = [r for r, in retailer_ids]    
1206
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact, Retailers.id.in_(retailer_ids))
1207
            else:
1208
                m = re.match("(.*?)(\d{6})(.*?)", contact)
1209
                if m is not None:
1210
                    pin = m.group(2)
1211
                    contact = m.group(1) if m.group(1) != '' else m.group(3)
15313 amit.gupta 1212
                    anotherCondition = and_(Retailers.title.ilike('%%%s%%'%(contact)), Retailers.pin==pin)
15312 amit.gupta 1213
                else:
1214
                    anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1215
 
15326 amit.gupta 1216
            retailers = session.query(Retailers).filter(anotherCondition).limit(20).all()
15312 amit.gupta 1217
            if retailers is None:
15285 manas 1218
                resp.body = json.dumps("{}")
15312 amit.gupta 1219
            else:
1220
                for retailer in retailers:
15326 amit.gupta 1221
                    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 1222
                    retailersJsonArray.append(todict(getRetailerObj(retailer, otherContacts)))    
1223
            resp.body = json.dumps({"Retailers":retailersJsonArray}, encoding='utf-8')
15312 amit.gupta 1224
            return
15285 manas 1225
        finally:
1226
            session.close()
15171 amit.gupta 1227
 
15081 amit.gupta 1228
 
1229
class Mock(object):
1230
    pass
15189 manas 1231
 
15312 amit.gupta 1232
def tagActivatedReatilers():
15613 amit.gupta 1233
    retailerIds = [r for  r, in session.query(RetailerLinks.retailer_id).filter_by(user_id = None).all()]
15312 amit.gupta 1234
    session.close()
15288 amit.gupta 1235
    for retailerId in retailerIds:
1236
        isActivated(retailerId)
15312 amit.gupta 1237
    session.close()
15374 kshitij.so 1238
 
1239
class StaticDeals():
1240
 
1241
    def on_get(self, req, resp):
1242
 
1243
        offset = req.get_param_as_int("offset")
1244
        limit = req.get_param_as_int("limit")
1245
        categoryId = req.get_param_as_int("categoryId")
15458 kshitij.so 1246
        direction = req.get_param_as_int("direction")
15374 kshitij.so 1247
 
15458 kshitij.so 1248
        result = Mongo.getStaticDeals(offset, limit, categoryId, direction)
15374 kshitij.so 1249
        resp.body = dumps(result)
1250
 
16366 kshitij.so 1251
class DealNotification():
1252
 
1253
    def on_get(self,req,resp,skuBundleIds):
1254
        result = Mongo.getDealsForNotification(skuBundleIds)
1255
        resp.body = dumps(result)
16487 kshitij.so 1256
 
1257
class DealPoints():
1258
 
1259
    def on_get(self, req, resp):
16366 kshitij.so 1260
 
16487 kshitij.so 1261
        offset = req.get_param_as_int("offset")
1262
        limit = req.get_param_as_int("limit")
1263
 
1264
        result = Mongo.getAllBundlesWithDealPoints(offset, limit)
1265
        resp.body = dumps(result)
15374 kshitij.so 1266
 
16487 kshitij.so 1267
 
1268
    def on_post(self, req, resp):
1269
 
1270
 
1271
        try:
1272
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1273
        except ValueError:
1274
            raise falcon.HTTPError(falcon.HTTP_400,
1275
                'Malformed JSON',
1276
                'Could not decode the request body. The '
1277
                'JSON was incorrect.')
1278
 
1279
        result = Mongo.addDealPoints(result_json)
1280
        resp.body = json.dumps(result, encoding='utf-8')
15374 kshitij.so 1281
 
16545 kshitij.so 1282
class AppAffiliates():
1283
 
1284
    def on_get(self, req, resp, retailerId, appId):
1285
        retailerId = int(retailerId)
1286
        appId = int(appId)
16554 kshitij.so 1287
        call_back = req.get_param("callback")
16545 kshitij.so 1288
        result = Mongo.generateRedirectUrl(retailerId, appId)
16555 kshitij.so 1289
        resp.body = call_back+'('+str(result)+')'
16557 kshitij.so 1290
 
1291
class AffiliatePayout():
1292
    def on_get(self, req, resp):
1293
        payout = req.get_param("payout")
1294
        transaction_id = req.get_param("transaction_id")
1295
        result = Mongo.addPayout(payout, transaction_id)
1296
        resp.body = str(result)
1297
 
16545 kshitij.so 1298
 
1299
 
15312 amit.gupta 1300
def main():
15662 amit.gupta 1301
    #tagActivatedReatilers()
1302
    a = RetailerDetail()
1303
    retailer = a.getNotActiveRetailer()
1304
    otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
1305
    print json.dumps(todict(getRetailerObj(retailer, otherContacts, 'fresh')), encoding='utf-8')
15465 amit.gupta 1306
    #print make_tiny("AA")
15195 manas 1307
 
15081 amit.gupta 1308
if __name__ == '__main__':
15207 amit.gupta 1309
    main()
15091 amit.gupta 1310