Subversion Repositories SmartDukaan

Rev

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