Subversion Repositories SmartDukaan

Rev

Rev 15234 | Rev 15240 | 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
633
            agent = session.query(Agents).filter_by(agent_id=self.agentId).first()
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()
643
        finally:
644
            session.close()
15081 amit.gupta 645
 
646
        if retailer is None:
15157 amit.gupta 647
            resp.body = "{}"
15081 amit.gupta 648
        else:
649
            resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
650
 
651
    def on_post(self, req, resp, agentId, callType):
15112 amit.gupta 652
        returned = False
15081 amit.gupta 653
        self.agentId = int(agentId)
654
        self.callType = callType
655
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15169 amit.gupta 656
        lgr.info( "Request ----\n"  + str(jsonReq))
15091 amit.gupta 657
        self.jsonReq = jsonReq
658
        invalidNumber = self.invalidNumber
659
        callLater = self.callLater
15096 amit.gupta 660
        alreadyUser = self.alReadyUser
15091 amit.gupta 661
        verifiedLinkSent = self.verifiedLinkSent
15109 amit.gupta 662
 
15096 amit.gupta 663
        self.retailerId = int(jsonReq.get('retailerid'))
15112 amit.gupta 664
        try:
665
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
666
            self.callDisposition = jsonReq.get('calldispositiontype')
667
            self.callHistory = CallHistory()
668
            self.callHistory.agent_id=self.agentId
669
            self.callHistory.call_disposition = self.callDisposition
670
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 671
            self.callHistory.call_type=self.callType
15112 amit.gupta 672
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
673
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 674
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
675
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 676
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
677
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 678
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 679
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
680
            if lastFetchData is None:
681
                raise
682
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 683
 
684
            dispositionMap = {  'call_later':callLater,
685
                        'ringing_no_answer':callLater,
686
                        'not_reachable':callLater,
687
                        'switch_off':callLater,
15202 manas 688
                        'not_retailer':invalidNumber,
15112 amit.gupta 689
                        'invalid_no':invalidNumber,
690
                        'wrong_no':invalidNumber,
691
                        'hang_up':invalidNumber,
692
                        'retailer_not_interested':invalidNumber,
15200 manas 693
                        'recharge_retailer':invalidNumber,
694
                        'accessory_retailer':invalidNumber,
695
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 696
                        'alreadyuser':alreadyUser,
697
                        'verified_link_sent':verifiedLinkSent
698
                      }
699
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
700
        finally:
701
            session.close()
15096 amit.gupta 702
 
15112 amit.gupta 703
        if returned:
704
            resp.body = "{\"result\":\"success\"}"
705
        else:
706
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 707
 
15091 amit.gupta 708
    def invalidNumber(self,):
15108 manas 709
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
710
        if self.callDisposition == 'invalid_no':
711
            self.retailer.status='failed'
712
            self.callHistory.disposition_description = 'Invalid Number'
713
        elif self.callDisposition == 'wrong_no':
15111 manas 714
            self.retailer.status='failed'
715
            self.callHistory.disposition_description = 'Wrong Number'
716
        elif self.callDisposition == 'hang_up':
717
            self.retailer.status='failed'
718
            self.callHistory.disposition_description = 'Hang Up'
719
        elif self.callDisposition == 'retailer_not_interested':
720
            self.retailer.status='failed'
721
            if self.callHistory.disposition_description is None:
722
                self.callHistory.disposition_description = 'NA'
15200 manas 723
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
724
        elif self.callDisposition == 'recharge_retailer':
725
            self.retailer.status='failed'
726
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
727
        elif self.callDisposition == 'accessory_retailer':
728
            self.retailer.status='failed'
729
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
730
        elif self.callDisposition == 'service_center_retailer':
731
            self.retailer.status='failed'
732
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 733
        elif self.callDisposition == 'not_retailer':
734
            self.retailer.status='failed'
735
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 736
        session.commit()
737
        return True   
738
 
15132 amit.gupta 739
    def getCode(self,):
15207 amit.gupta 740
        newCode = None
741
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
742
        if lastLink is not None:
743
            if len(lastLink.code)==len(codesys):
744
                newCode=lastLink.code
745
        return getNextCode(codesys, newCode)
15108 manas 746
 
15091 amit.gupta 747
    def callLater(self,):
15100 amit.gupta 748
        self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
749
        self.retailer.call_priority = None
15096 amit.gupta 750
        if self.callDisposition == 'call_later':
15100 amit.gupta 751
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 752
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 753
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
754
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
755
            else:
15102 amit.gupta 756
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 757
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 758
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
759
        else: 
760
            if self.callDisposition == 'ringing_no_answer':
761
                if self.retailer.disposition == 'ringing_no_answer':
762
                    self.retailer.retry_count += 1
763
                else:
764
                    self.retailer.disposition = 'ringing_no_answer'
765
                    self.retailer.retry_count = 1
766
            else:
767
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 768
                    pass
15112 amit.gupta 769
                else:
15119 amit.gupta 770
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 771
                self.retailer.retry_count += 1
772
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 773
 
15122 amit.gupta 774
            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 775
            if retryConfig is not None:
776
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 777
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 778
            else:
779
                self.retailer.status = 'failed'
780
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 781
 
15101 amit.gupta 782
        session.commit()
783
        return True
15096 amit.gupta 784
 
15100 amit.gupta 785
 
15091 amit.gupta 786
    def alReadyUser(self,):
15112 amit.gupta 787
        self.retailer.status = self.callDisposition
15117 amit.gupta 788
        if self.callHistory.disposition_description is None:
789
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 790
        session.commit()
791
        return True
15091 amit.gupta 792
    def verifiedLinkSent(self,):
15147 amit.gupta 793
        if self.callType == 'fresh':
794
            self.retailer.status = 'followup'
795
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
796
            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') 
797
        else:
15224 amit.gupta 798
            self.retailer.status = 'followup'
15147 amit.gupta 799
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
800
            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 801
        session.commit()
802
        return True
15189 manas 803
 
804
class Login():
805
 
806
    def on_get(self, req, resp, agentId, role):
807
        try:
15198 manas 808
            self.agentId = int(agentId)
809
            self.role = role
810
            print str(self.agentId) + self.role;
15199 manas 811
            agents=AgentLoginTimings()
812
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
813
            print 'lastLogintime' + str(lastLoginTime)
814
            agents.loginTime=lastLoginTime.last_login
815
            agents.logoutTime=datetime.now()
816
            agents.role =self.role
817
            agents.agent_id = 2
818
            session.add(agents)    
819
            session.commit()
820
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 821
        finally:
822
            session.close()        
15112 amit.gupta 823
 
15189 manas 824
    def on_post(self,req,resp):
825
        try:
826
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
827
            lgr.info( "Request ----\n"  + str(jsonReq))
828
            email=jsonReq.get('email')
829
            password = jsonReq.get('password')
830
            role=jsonReq.get('role')    
831
            checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
832
            if checkUser is None:
833
                print checkUser
834
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
835
            else:
836
                print checkUser[0]
837
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
838
                if checkRole is None:
839
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
840
                else:
15196 manas 841
                    session.query(Agents).filter_by(id = checkUser[0]).update({"last_login":datetime.now()})
15195 manas 842
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":checkUser[0]}}, encoding='utf-8')
843
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 844
                    session.commit()
845
        finally:
846
            session.close()    
847
 
15195 manas 848
    def test(self,email,password,role):
15189 manas 849
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
850
        if checkUser is None:
851
            print checkUser
15195 manas 852
 
15189 manas 853
        else:
854
            print checkUser[0]
855
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
856
            if checkRole is None:
15195 manas 857
                pass
15189 manas 858
            else:
15195 manas 859
                agents=AgentLoginTimings()
860
                agents.loginTime=datetime.now()
861
                agents.logoutTime=datetime.now()
862
                agents.role =role
863
                agents.agent_id = 2
864
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
865
                session.add(agents)    
866
                session.commit()
867
                session.close()
868
 
869
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15189 manas 870
 
15081 amit.gupta 871
def todict(obj, classkey=None):
872
    if isinstance(obj, dict):
873
        data = {}
874
        for (k, v) in obj.items():
875
            data[k] = todict(v, classkey)
876
        return data
877
    elif hasattr(obj, "_ast"):
878
        return todict(obj._ast())
879
    elif hasattr(obj, "__iter__"):
880
        return [todict(v, classkey) for v in obj]
881
    elif hasattr(obj, "__dict__"):
882
        data = dict([(key, todict(value, classkey)) 
883
            for key, value in obj.__dict__.iteritems() 
884
            if not callable(value) and not key.startswith('_')])
885
        if classkey is not None and hasattr(obj, "__class__"):
886
            data[classkey] = obj.__class__.__name__
887
        return data
888
    else:
889
        return obj
890
 
891
def getRetailerObj(retailer):
892
    obj = Mock()
893
    obj.title = retailer.title
894
    obj.contact1 = retailer.contact1
895
    obj.contact2 = retailer.contact2
896
    obj.address = retailer.address
897
    obj.id = retailer.id
15096 amit.gupta 898
    obj.scheduled = (retailer.call_priority is not None)
15081 amit.gupta 899
    return obj
15091 amit.gupta 900
 
15132 amit.gupta 901
def make_tiny(code):
902
    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
903
    request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
904
    filehandle = urllib2.Request(request_url)
905
    x= urllib2.urlopen(filehandle)
906
    return str(x.read())
15171 amit.gupta 907
 
908
 
909
#def update_pin():
15081 amit.gupta 910
 
15132 amit.gupta 911
 
15081 amit.gupta 912
class Mock(object):
913
    pass
15189 manas 914
 
15081 amit.gupta 915
def main():
15207 amit.gupta 916
    print getNextCode(codesys, 'ZZ999')
15195 manas 917
 
15081 amit.gupta 918
if __name__ == '__main__':
15207 amit.gupta 919
    main()
15091 amit.gupta 920