Subversion Repositories SmartDukaan

Rev

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