Subversion Repositories SmartDukaan

Rev

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