Subversion Repositories SmartDukaan

Rev

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