Subversion Repositories SmartDukaan

Rev

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

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