Subversion Repositories SmartDukaan

Rev

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