Subversion Repositories SmartDukaan

Rev

Rev 15099 | Rev 15101 | 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
15096 amit.gupta 7
from dtr.storage.DataService import Retailers, Users, CallHistory
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
482
    def getRetryRetailer(self,failback=False):
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)
492
            if status=='fresh':
493
                retailer.status = 'assigned'
494
            else:
495
                retailer.status = 'fassigned'
496
            retailer.retry_count += 1
497
            session.commit()
498
        finally:
499
            session.close()
500
        return retailer
501
 
502
    def getNewRetailer(self,failback=True):
503
        retry = True
504
        retailer = None 
505
        try:
506
            while(retry):
507
                print "Calltype", self.callType
508
                status=self.callType
509
                query = session.query(Retailers).filter(Retailers.status==status)
510
                if status=='fresh':
511
                    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)
512
                retailer = query.with_lockmode("update").first()
513
                if retailer is not None:
514
                    print "retailer", retailer.id
515
                    if status=="fresh":
516
                        userquery = session.query(Users)
517
                        if retailer.contact2 is not None:
518
                            userquery = userquery.filter(Users.mobile_number.in_([retailer.contact1,retailer.contact2]))
519
                        else:
520
                            userquery = userquery.filter_by(mobile_number=retailer.contact1)
521
                        user = userquery.first()
522
                        if user is not None:
523
                            retailer.status = 'alreadyuser'
524
                            print "retailer.status", retailer.status
525
                            session.commit()
526
                            continue
527
                        retailer.status = 'assigned'
528
                    else:
529
                        retailer.status = 'fassigned'
530
                    print "Found Retailer", retailer.id, "with status", status,"assigned to", self.agentId
531
                    retailer.retry_count = 0
532
                    session.commit()
533
                    print "-"*50
534
                    print "Found Retailer", retailer.id, "with status", status,"assigned to", self.agentId
535
                    retry=False
536
 
537
                else:
538
                    print "No fresh/followup retailers found"
539
                    if failback:
540
                        retailer = self.getRetryRetailer(False)
541
                    retry=False
542
        except:
543
            print traceback.print_exc()
544
        finally:
545
            session.close()
546
        return retailer
547
 
548
    def on_get(self, req, resp, agentId, callType):
549
        global RETAILER_DETAIL_CALL_COUNTER
550
        RETAILER_DETAIL_CALL_COUNTER += 1
551
        print "RETAILER_DETAIL_CALL_COUNTER", RETAILER_DETAIL_CALL_COUNTER
552
        print "I am here"
553
        self.agentId = int(agentId)
554
        self.callType = callType
555
        retryFlag = False 
556
        agentId = int(agentId)
557
        if RETAILER_DETAIL_CALL_COUNTER % DEALER_RETRY_FACTOR ==0:
558
            retryFlag=True
559
 
560
        if retryFlag:
561
            retailer = self.getRetryRetailer()
562
        else:
563
            retailer = self.getNewRetailer()
564
 
565
        if retailer is None:
566
            resp.body = "{\"result\":\"{}\"}"
567
        else:
568
            resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
569
 
570
    def on_post(self, req, resp, agentId, callType):
571
        self.agentId = int(agentId)
572
        self.callType = callType
573
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15099 amit.gupta 574
        print jsonReq
15091 amit.gupta 575
        self.jsonReq = jsonReq
576
        invalidNumber = self.invalidNumber
577
        callLater = self.callLater
15096 amit.gupta 578
        alreadyUser = self.alReadyUser
15091 amit.gupta 579
        verifiedLinkSent = self.verifiedLinkSent
15096 amit.gupta 580
        self.retailerId = int(jsonReq.get('retailerid'))
581
        self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
582
        self.callDisposition = jsonReq.get('calldispositiontype')
583
        self.mobile = jsonReq.get('number')
584
 
585
        self.callHistory = CallHistory()
586
        self.callHistory.agent_id=self.agentId
587
        self.callHistory.duration_sec = int(jsonReq.get("callduration"))
588
        self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
589
        self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
590
        self.callHistory.mobile_number = self.mobile
591
        self.callHistory.sms_verified = 0
592
 
15091 amit.gupta 593
        dispositionMap = {  'call_later':callLater,
594
                    'ringing_no_answer':callLater,
595
                    'not_reachable':callLater,
596
                    'switch_off':callLater,
597
                    'invalid_no':invalidNumber,
598
                    'wrong_no':invalidNumber,
599
                    'not_interested':invalidNumber,
600
                    'retailer_not_interested':invalidNumber,
601
                    'alreadyuser':alreadyUser,
602
                    'verified_link_sent':verifiedLinkSent
603
                  }
604
        dispositionMap[jsonReq.get('calldispositiontype')]()
605
 
606
 
15081 amit.gupta 607
        resp.body = json.dumps(jsonReq, encoding='utf-8')
608
 
15091 amit.gupta 609
    def invalidNumber(self,):
15096 amit.gupta 610
        pass
15091 amit.gupta 611
    def callLater(self,):
15100 amit.gupta 612
        self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
613
        self.retailer.call_priority = None
15096 amit.gupta 614
        if self.callDisposition == 'call_later':
15100 amit.gupta 615
            if self.callHistory.disposition_description is not None:
15096 amit.gupta 616
                self.retailer.call_priority = 'system_initiated'
617
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
618
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
619
            else:
620
                self.retailer.call_priority = 'user_initiated'
621
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
622
                self.callHistory.disposition_description = 'User to be called next day'
15100 amit.gupta 623
        elif self.callDisposition == 'ringing_no_answer':
15096 amit.gupta 624
            session.commit()
625
            return True
626
 
15100 amit.gupta 627
 
15091 amit.gupta 628
    def alReadyUser(self,):
629
        print self.jsonReq
630
        callDisposition = self.jsonReq.get('calldispositiontype')
631
        dispositionDesc = self.jsonReq.get('calldispositiondescritption')
632
        retailerId = self.jsonReq.get('retailerid')
633
        mobile = self.jsonReq.get('number')
634
        callTime = self.jsonReq.get("calltime")
635
        callDuration = self.jsonReq.get("callduration") 
636
    def verifiedLinkSent(self,):
637
        print self.jsonReq
638
        callDisposition = self.jsonReq.get('calldispositiontype')
639
        dispositionDesc = self.jsonReq.get('calldispositiondescritption')
640
        retailerId = self.jsonReq.get('retailerid')
641
        mobile = self.jsonReq.get('number')
642
        callTime = self.jsonReq.get("calltime")
643
        callDuration = self.jsonReq.get("callduration") 
15081 amit.gupta 644
 
645
def todict(obj, classkey=None):
646
    if isinstance(obj, dict):
647
        data = {}
648
        for (k, v) in obj.items():
649
            data[k] = todict(v, classkey)
650
        return data
651
    elif hasattr(obj, "_ast"):
652
        return todict(obj._ast())
653
    elif hasattr(obj, "__iter__"):
654
        return [todict(v, classkey) for v in obj]
655
    elif hasattr(obj, "__dict__"):
656
        data = dict([(key, todict(value, classkey)) 
657
            for key, value in obj.__dict__.iteritems() 
658
            if not callable(value) and not key.startswith('_')])
659
        if classkey is not None and hasattr(obj, "__class__"):
660
            data[classkey] = obj.__class__.__name__
661
        return data
662
    else:
663
        return obj
664
 
665
def getRetailerObj(retailer):
666
    obj = Mock()
667
    obj.title = retailer.title
668
    obj.contact1 = retailer.contact1
669
    obj.contact2 = retailer.contact2
670
    obj.address = retailer.address
671
    obj.id = retailer.id
15096 amit.gupta 672
    obj.scheduled = (retailer.call_priority is not None)
15081 amit.gupta 673
    return obj
15091 amit.gupta 674
 
15081 amit.gupta 675
 
676
class Mock(object):
677
    pass
678
 
679
def main():
680
    ret = RetailerDetail()
681
    resp = Mock()
682
    ret.on_get(None, resp, 1, 'fresh')
683
 
684
if __name__ == '__main__':
15091 amit.gupta 685
        main()
686