Subversion Repositories SmartDukaan

Rev

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