Subversion Repositories SmartDukaan

Rev

Rev 15307 | Rev 15309 | 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, \
15254 amit.gupta 8
    RetailerLinks, Activation_Codes, Agents, Agent_Roles, AgentLoginTimings, \
9
    FetchDataHistory, RetailerContacts
15081 amit.gupta 10
from dtr.utils import FetchLivePrices, DealSheet as X_DealSheet, \
11
    UserSpecificDeals
15168 amit.gupta 12
from dtr.utils.utils import getLogger
15081 amit.gupta 13
from elixir import *
15254 amit.gupta 14
from operator import and_
15303 amit.gupta 15
from sqlalchemy.sql.expression import func, func, or_
15132 amit.gupta 16
from urllib import urlencode
17
import contextlib
13827 kshitij.so 18
import falcon
15081 amit.gupta 19
import json
15254 amit.gupta 20
import string
15081 amit.gupta 21
import traceback
15132 amit.gupta 22
import urllib
23
import urllib2
24
import uuid
15207 amit.gupta 25
alphalist = list(string.uppercase)
26
alphalist.remove('O')
27
numList = ['1','2','3','4','5','6','7','8','9']
28
codesys = [alphalist, alphalist, numList, numList, numList]
29
 
30
 
31
def getNextCode(codesys, code=None):
32
    if code is None:
33
        code = []
34
        for charcode in codesys:
35
            code.append(charcode[0])
36
        return string.join(code, '')
37
    carry = True
38
    code = list(code)
39
    lastindex = len(codesys) - 1
40
    while carry:
41
        listChar = codesys[lastindex]
42
        newIndex = (listChar.index(code[lastindex])+1)%len(listChar)
43
        print newIndex
44
        code[lastindex] = listChar[newIndex]
45
        if newIndex != 0:
46
            carry = False
47
        lastindex -= 1
48
        if lastindex ==-1:
49
            raise BaseException("All codes are exhausted")
50
 
51
    return string.join(code, '')
52
 
53
 
54
 
55
 
15081 amit.gupta 56
global RETAILER_DETAIL_CALL_COUNTER
57
RETAILER_DETAIL_CALL_COUNTER = 0
13572 kshitij.so 58
 
15168 amit.gupta 59
lgr = getLogger('/var/log/retailer-acquisition-api.log')
15081 amit.gupta 60
DEALER_RETRY_FACTOR = int(PythonPropertyReader.getConfig('DEALER_RETRY_FACTOR'))
13572 kshitij.so 61
class CategoryDiscountInfo(object):
62
 
63
    def on_get(self, req, resp):
64
 
13629 kshitij.so 65
        result = Mongo.getAllCategoryDiscount()
66
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
67
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 68
 
69
    def on_post(self, req, resp):
70
        try:
71
            result_json = json.loads(req.stream.read(), encoding='utf-8')
72
        except ValueError:
73
            raise falcon.HTTPError(falcon.HTTP_400,
74
                'Malformed JSON',
75
                'Could not decode the request body. The '
76
                'JSON was incorrect.')
77
 
78
        result = Mongo.addCategoryDiscount(result_json)
79
        resp.body = json.dumps(result, encoding='utf-8')
13969 kshitij.so 80
 
81
    def on_put(self, req, resp, _id):
13970 kshitij.so 82
        try:
83
            result_json = json.loads(req.stream.read(), encoding='utf-8')
84
        except ValueError:
85
            raise falcon.HTTPError(falcon.HTTP_400,
86
                'Malformed JSON',
87
                'Could not decode the request body. The '
88
                'JSON was incorrect.')
89
 
90
        result = Mongo.updateCategoryDiscount(result_json, _id)
91
        resp.body = json.dumps(result, encoding='utf-8')
92
 
13966 kshitij.so 93
 
13969 kshitij.so 94
 
13572 kshitij.so 95
class SkuSchemeDetails(object):
96
 
97
    def on_get(self, req, resp):
13629 kshitij.so 98
 
14070 kshitij.so 99
        offset = req.get_param_as_int("offset")
100
        limit = req.get_param_as_int("limit")
101
 
102
        result = Mongo.getAllSkuWiseSchemeDetails(offset, limit)
13629 kshitij.so 103
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
104
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 105
 
106
 
107
    def on_post(self, req, resp):
108
 
14552 kshitij.so 109
        multi = req.get_param_as_int("multi")
110
 
13572 kshitij.so 111
        try:
112
            result_json = json.loads(req.stream.read(), encoding='utf-8')
113
        except ValueError:
114
            raise falcon.HTTPError(falcon.HTTP_400,
115
                'Malformed JSON',
116
                'Could not decode the request body. The '
117
                'JSON was incorrect.')
118
 
14552 kshitij.so 119
        result = Mongo.addSchemeDetailsForSku(result_json, multi)
13572 kshitij.so 120
        resp.body = json.dumps(result, encoding='utf-8')
121
 
122
class SkuDiscountInfo():
123
 
124
    def on_get(self, req, resp):
13629 kshitij.so 125
 
13970 kshitij.so 126
        offset = req.get_param_as_int("offset")
127
        limit = req.get_param_as_int("limit")
128
        result = Mongo.getallSkuDiscountInfo(offset,limit)
13629 kshitij.so 129
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
130
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 131
 
132
 
133
    def on_post(self, req, resp):
134
 
14552 kshitij.so 135
        multi = req.get_param_as_int("multi")
136
 
13572 kshitij.so 137
        try:
138
            result_json = json.loads(req.stream.read(), encoding='utf-8')
139
        except ValueError:
140
            raise falcon.HTTPError(falcon.HTTP_400,
141
                'Malformed JSON',
142
                'Could not decode the request body. The '
143
                'JSON was incorrect.')
144
 
14552 kshitij.so 145
        result = Mongo.addSkuDiscountInfo(result_json, multi)
13572 kshitij.so 146
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 147
 
148
    def on_put(self, req, resp, _id):
149
        try:
150
            result_json = json.loads(req.stream.read(), encoding='utf-8')
151
        except ValueError:
152
            raise falcon.HTTPError(falcon.HTTP_400,
153
                'Malformed JSON',
154
                'Could not decode the request body. The '
155
                'JSON was incorrect.')
156
 
157
        result = Mongo.updateSkuDiscount(result_json, _id)
158
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 159
 
160
class ExceptionalNlc():
161
 
162
    def on_get(self, req, resp):
13629 kshitij.so 163
 
13970 kshitij.so 164
        offset = req.get_param_as_int("offset")
165
        limit = req.get_param_as_int("limit")
166
 
167
        result = Mongo.getAllExceptionlNlcItems(offset, limit)
13629 kshitij.so 168
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
169
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 170
 
171
    def on_post(self, req, resp):
172
 
14552 kshitij.so 173
        multi = req.get_param_as_int("multi")
174
 
13572 kshitij.so 175
        try:
176
            result_json = json.loads(req.stream.read(), encoding='utf-8')
177
        except ValueError:
178
            raise falcon.HTTPError(falcon.HTTP_400,
179
                'Malformed JSON',
180
                'Could not decode the request body. The '
181
                'JSON was incorrect.')
182
 
14552 kshitij.so 183
        result = Mongo.addExceptionalNlc(result_json, multi)
13572 kshitij.so 184
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 185
 
186
    def on_put(self, req, resp, _id):
187
        try:
188
            result_json = json.loads(req.stream.read(), encoding='utf-8')
189
        except ValueError:
190
            raise falcon.HTTPError(falcon.HTTP_400,
191
                'Malformed JSON',
192
                'Could not decode the request body. The '
193
                'JSON was incorrect.')
194
 
195
        result = Mongo.updateExceptionalNlc(result_json, _id)
196
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 197
 
13772 kshitij.so 198
class Deals():
13779 kshitij.so 199
    def on_get(self,req, resp, userId):
200
        categoryId = req.get_param_as_int("categoryId")
201
        offset = req.get_param_as_int("offset")
202
        limit = req.get_param_as_int("limit")
13798 kshitij.so 203
        sort = req.get_param("sort")
13802 kshitij.so 204
        direction = req.get_param_as_int("direction")
14853 kshitij.so 205
        filterData = req.get_param('filterData')
206
        result = Mongo.getNewDeals(int(userId), categoryId, offset, limit, sort, direction, filterData)
13772 kshitij.so 207
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 208
        resp.body = json.dumps(json_docs, encoding='utf-8')
13790 kshitij.so 209
 
210
class MasterData():
211
    def on_get(self,req, resp, skuId):
212
        result = Mongo.getItem(skuId)
13798 kshitij.so 213
        try:
214
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 215
            resp.body = json.dumps(json_docs, encoding='utf-8')
13798 kshitij.so 216
        except:
217
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 218
            resp.body = json.dumps(json_docs, encoding='utf-8')
13790 kshitij.so 219
 
14586 kshitij.so 220
    def on_post(self,req, resp):
221
 
222
        addNew = req.get_param_as_int("addNew")
223
        update = req.get_param_as_int("update")
224
        addToExisting = req.get_param_as_int("addToExisting")
225
        multi = req.get_param_as_int("multi")
226
 
14589 kshitij.so 227
        try:
14592 kshitij.so 228
            result_json = json.loads(req.stream.read(), encoding='utf-8')
229
        except ValueError:
230
            raise falcon.HTTPError(falcon.HTTP_400,
231
                'Malformed JSON',
232
                'Could not decode the request body. The '
233
                'JSON was incorrect.')
234
 
235
        if addNew == 1:
236
            result = Mongo.addNewItem(result_json)
237
        elif update == 1:
238
            result = Mongo.updateMaster(result_json, multi)
239
        elif addToExisting == 1:
240
            result = Mongo.addItemToExistingBundle(result_json)
241
        else:
242
            raise
243
        resp.body = dumps(result)
14586 kshitij.so 244
 
13827 kshitij.so 245
class LiveData():
246
    def on_get(self,req, resp):
13865 kshitij.so 247
        if req.get_param_as_int("id") is not None:
248
            print "****getting only for id"
249
            id = req.get_param_as_int("id")
250
            try:
251
                result = FetchLivePrices.getLatestPriceById(id)
13867 kshitij.so 252
                json_docs = json.dumps(result, default=json_util.default)
13966 kshitij.so 253
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 254
            except:
255
                json_docs = json.dumps({}, default=json_util.default)
13966 kshitij.so 256
                resp.body = json.dumps(json_docs, encoding='utf-8')
13834 kshitij.so 257
 
13865 kshitij.so 258
        else:
259
            print "****getting only for skuId"
260
            skuBundleId = req.get_param_as_int("skuBundleId")
261
            source_id = req.get_param_as_int("source_id")
262
            try:
263
                result = FetchLivePrices.getLatestPrice(skuBundleId, source_id)
264
                json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 265
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 266
            except:
267
                json_docs = [json.dumps(doc, default=json_util.default) for doc in [{}]]
13966 kshitij.so 268
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 269
 
13834 kshitij.so 270
class CashBack():
271
    def on_get(self,req, resp):
272
        identifier = req.get_param("identifier")
273
        source_id = req.get_param_as_int("source_id")
274
        try:
13838 kshitij.so 275
            result = Mongo.getCashBackDetails(identifier, source_id)
13837 kshitij.so 276
            json_docs = json.dumps(result, default=json_util.default)
13964 kshitij.so 277
            resp.body = json_docs
13834 kshitij.so 278
        except:
13837 kshitij.so 279
            json_docs = json.dumps({}, default=json_util.default)
13963 kshitij.so 280
            resp.body = json_docs
13892 kshitij.so 281
 
14398 amit.gupta 282
class ImgSrc():
283
    def on_get(self,req, resp):
284
        identifier = req.get_param("identifier")
285
        source_id = req.get_param_as_int("source_id")
286
        try:
287
            result = Mongo.getImgSrc(identifier, source_id)
288
            json_docs = json.dumps(result, default=json_util.default)
289
            resp.body = json_docs
290
        except:
291
            json_docs = json.dumps({}, default=json_util.default)
292
            resp.body = json_docs
293
 
13892 kshitij.so 294
class DealSheet():
295
    def on_get(self,req, resp):
13895 kshitij.so 296
        X_DealSheet.sendMail()
13897 kshitij.so 297
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
13966 kshitij.so 298
        resp.body = json.dumps(json_docs, encoding='utf-8')
13892 kshitij.so 299
 
13970 kshitij.so 300
class DealerPrice():
301
 
302
    def on_get(self, req, resp):
303
 
304
        offset = req.get_param_as_int("offset")
305
        limit = req.get_param_as_int("limit")
306
        result = Mongo.getAllDealerPrices(offset,limit)
307
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
308
        resp.body = json.dumps(json_docs, encoding='utf-8')
309
 
310
    def on_post(self, req, resp):
311
 
14552 kshitij.so 312
        multi = req.get_param_as_int("multi")
313
 
13970 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
 
14552 kshitij.so 322
        result = Mongo.addSkuDealerPrice(result_json, multi)
13970 kshitij.so 323
        resp.body = json.dumps(result, encoding='utf-8')
324
 
325
    def on_put(self, req, resp, _id):
326
        try:
327
            result_json = json.loads(req.stream.read(), encoding='utf-8')
328
        except ValueError:
329
            raise falcon.HTTPError(falcon.HTTP_400,
330
                'Malformed JSON',
331
                'Could not decode the request body. The '
332
                'JSON was incorrect.')
333
 
334
        result = Mongo.updateSkuDealerPrice(result_json, _id)
335
        resp.body = json.dumps(result, encoding='utf-8')
336
 
337
 
14041 kshitij.so 338
class ResetCache():
339
 
340
    def on_get(self,req, resp, userId):
14044 kshitij.so 341
        result = Mongo.resetCache(userId)
14046 kshitij.so 342
        resp.body = json.dumps(result, encoding='utf-8')
343
 
344
class UserDeals():
345
    def on_get(self,req,resp,userId):
346
        UserSpecificDeals.generateSheet(userId)
347
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
348
        resp.body = json.dumps(json_docs, encoding='utf-8')
14075 kshitij.so 349
 
350
class CommonUpdate():
351
 
352
    def on_post(self,req,resp):
14575 kshitij.so 353
 
354
        multi = req.get_param_as_int("multi")
355
 
14075 kshitij.so 356
        try:
357
            result_json = json.loads(req.stream.read(), encoding='utf-8')
358
        except ValueError:
359
            raise falcon.HTTPError(falcon.HTTP_400,
360
                'Malformed JSON',
361
                'Could not decode the request body. The '
362
                'JSON was incorrect.')
363
 
14575 kshitij.so 364
        result = Mongo.updateCollection(result_json, multi)
14075 kshitij.so 365
        resp.body = json.dumps(result, encoding='utf-8')
14106 kshitij.so 366
        resp.content_type = "application/json; charset=utf-8"
14481 kshitij.so 367
 
368
class NegativeDeals():
369
 
370
    def on_get(self, req, resp):
371
 
372
        offset = req.get_param_as_int("offset")
373
        limit = req.get_param_as_int("limit")
374
 
375
        result = Mongo.getAllNegativeDeals(offset, limit)
14483 kshitij.so 376
        resp.body = dumps(result) 
14481 kshitij.so 377
 
378
 
379
    def on_post(self, req, resp):
380
 
14552 kshitij.so 381
        multi = req.get_param_as_int("multi")
382
 
14481 kshitij.so 383
        try:
384
            result_json = json.loads(req.stream.read(), encoding='utf-8')
385
        except ValueError:
386
            raise falcon.HTTPError(falcon.HTTP_400,
387
                'Malformed JSON',
388
                'Could not decode the request body. The '
389
                'JSON was incorrect.')
390
 
14552 kshitij.so 391
        result = Mongo.addNegativeDeals(result_json, multi)
14481 kshitij.so 392
        resp.body = json.dumps(result, encoding='utf-8')
393
 
394
class ManualDeals():
395
 
396
    def on_get(self, req, resp):
397
 
398
        offset = req.get_param_as_int("offset")
399
        limit = req.get_param_as_int("limit")
400
 
401
        result = Mongo.getAllManualDeals(offset, limit)
14483 kshitij.so 402
        resp.body = dumps(result)
14481 kshitij.so 403
 
404
 
405
    def on_post(self, req, resp):
406
 
14552 kshitij.so 407
        multi = req.get_param_as_int("multi")
408
 
14481 kshitij.so 409
        try:
410
            result_json = json.loads(req.stream.read(), encoding='utf-8')
411
        except ValueError:
412
            raise falcon.HTTPError(falcon.HTTP_400,
413
                'Malformed JSON',
414
                'Could not decode the request body. The '
415
                'JSON was incorrect.')
416
 
14552 kshitij.so 417
        result = Mongo.addManualDeal(result_json, multi)
14481 kshitij.so 418
        resp.body = json.dumps(result, encoding='utf-8')
419
 
420
class CommonDelete():
14482 kshitij.so 421
 
14481 kshitij.so 422
    def on_post(self,req,resp):
423
        try:
424
            result_json = json.loads(req.stream.read(), encoding='utf-8')
425
        except ValueError:
426
            raise falcon.HTTPError(falcon.HTTP_400,
427
                'Malformed JSON',
428
                'Could not decode the request body. The '
429
                'JSON was incorrect.')
430
 
431
        result = Mongo.deleteDocument(result_json)
432
        resp.body = json.dumps(result, encoding='utf-8')
433
        resp.content_type = "application/json; charset=utf-8"
14482 kshitij.so 434
 
435
class SearchProduct():
436
 
437
    def on_get(self,req,resp):
438
        offset = req.get_param_as_int("offset")
439
        limit = req.get_param_as_int("limit")
440
        search_term = req.get_param("search")
441
 
442
        result = Mongo.searchMaster(offset, limit, search_term)
14483 kshitij.so 443
        resp.body = dumps(result) 
14482 kshitij.so 444
 
445
 
14495 kshitij.so 446
class FeaturedDeals():
14482 kshitij.so 447
 
14495 kshitij.so 448
    def on_get(self, req, resp):
449
 
450
        offset = req.get_param_as_int("offset")
451
        limit = req.get_param_as_int("limit")
452
 
453
        result = Mongo.getAllFeaturedDeals(offset, limit)
454
        resp.body = dumps(result)
455
 
456
 
457
    def on_post(self, req, resp):
458
 
14552 kshitij.so 459
        multi = req.get_param_as_int("multi")
460
 
14495 kshitij.so 461
        try:
462
            result_json = json.loads(req.stream.read(), encoding='utf-8')
463
        except ValueError:
464
            raise falcon.HTTPError(falcon.HTTP_400,
465
                'Malformed JSON',
466
                'Could not decode the request body. The '
467
                'JSON was incorrect.')
468
 
14552 kshitij.so 469
        result = Mongo.addFeaturedDeal(result_json, multi)
14495 kshitij.so 470
        resp.body = json.dumps(result, encoding='utf-8')
471
 
14497 kshitij.so 472
 
473
class CommonSearch():
14495 kshitij.so 474
 
14497 kshitij.so 475
    def on_get(self,req,resp):
476
        class_name = req.get_param("class")
477
        sku = req.get_param_as_int("sku")
478
        skuBundleId = req.get_param_as_int("skuBundleId")
14499 kshitij.so 479
 
480
        result = Mongo.searchCollection(class_name, sku, skuBundleId)
14497 kshitij.so 481
        resp.body = dumps(result)
14619 kshitij.so 482
 
483
class CricScore():
484
 
485
    def on_get(self,req,resp):
486
 
487
        result = Mongo.getLiveCricScore()
14853 kshitij.so 488
        resp.body = dumps(result)
489
 
490
class Notification():
491
 
492
    def on_post(self, req, resp):
493
 
494
        try:
495
            result_json = json.loads(req.stream.read(), encoding='utf-8')
496
        except ValueError:
497
            raise falcon.HTTPError(falcon.HTTP_400,
498
                'Malformed JSON',
499
                'Could not decode the request body. The '
500
                'JSON was incorrect.')
501
 
502
        result = Mongo.addBundleToNotification(result_json)
503
        resp.body = json.dumps(result, encoding='utf-8')
504
 
505
    def on_get(self, req, resp):
506
 
507
        offset = req.get_param_as_int("offset")
508
        limit = req.get_param_as_int("limit")
509
 
510
        result = Mongo.getAllNotifications(offset, limit)
511
        resp.body = dumps(result)
512
 
14998 kshitij.so 513
class DealBrands():
14853 kshitij.so 514
 
14998 kshitij.so 515
    def on_get(self, req, resp):
516
 
517
        category_id = req.get_param_as_int("category_id")
518
        result = Mongo.getBrandsForFilter(category_id)
14999 kshitij.so 519
        resp.body = dumps(result)
15161 kshitij.so 520
 
521
class DealRank():
14998 kshitij.so 522
 
15161 kshitij.so 523
    def on_get(self, req, resp):
524
        identifier = req.get_param("identifier")
525
        source_id = req.get_param_as_int("source_id")
526
        user_id = req.get_param_as_int("user_id")
527
        result = Mongo.getDealRank(identifier, source_id, user_id)
528
        json_docs = json.dumps(result, default=json_util.default)
529
        resp.body = json_docs
530
 
531
 
15081 amit.gupta 532
 
533
class RetailerDetail():
534
    global RETAILER_DETAIL_CALL_COUNTER
15105 amit.gupta 535
    def getRetryRetailer(self,failback=True):
15081 amit.gupta 536
        retailer = None
537
        status = 'fretry' if self.callType == 'followup' else 'retry'
15239 amit.gupta 538
        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()
539
        if retailer is not None:
540
            lgr.info( "getRetryRetailer " + str(retailer.id))
541
        else:
542
            if failback:
543
                retailer = self.getNewRetailer(False)
544
                return retailer
545
        if status=='retry':
546
            retailer.status = 'assigned'
547
        else:
548
            retailer.status = 'fassigned'
549
        lgr.info( "getRetryRetailer " + str(retailer.id))
15081 amit.gupta 550
        return retailer
551
 
552
    def getNewRetailer(self,failback=True):
553
        retry = True
554
        retailer = None 
555
        try:
556
            while(retry):
15168 amit.gupta 557
                lgr.info( "Calltype " + self.callType)
15081 amit.gupta 558
                status=self.callType
559
                query = session.query(Retailers).filter(Retailers.status==status)
560
                if status=='fresh':
15172 amit.gupta 561
                    query = query.filter_by(is_or=False, is_std=False).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None)).order_by(Retailers.is_elavated.desc(), -Retailers.agent_id)
15162 amit.gupta 562
                else:
15171 amit.gupta 563
                    query = query.filter(Retailers.next_call_time<=datetime.now())
15081 amit.gupta 564
                retailer = query.with_lockmode("update").first()
565
                if retailer is not None:
15168 amit.gupta 566
                    lgr.info( "retailer " +str(retailer.id))
15081 amit.gupta 567
                    if status=="fresh":
568
                        userquery = session.query(Users)
569
                        if retailer.contact2 is not None:
570
                            userquery = userquery.filter(Users.mobile_number.in_([retailer.contact1,retailer.contact2]))
571
                        else:
572
                            userquery = userquery.filter_by(mobile_number=retailer.contact1)
573
                        user = userquery.first()
574
                        if user is not None:
575
                            retailer.status = 'alreadyuser'
15168 amit.gupta 576
                            lgr.info( "retailer.status " + retailer.status)
15081 amit.gupta 577
                            session.commit()
578
                            continue
579
                        retailer.status = 'assigned'
580
                    else:
15276 amit.gupta 581
                        if isActivated(retailer.id):
582
                            print "Retailer Already %d activated and marked onboarded"%(retailer.id)
583
                            continue
15081 amit.gupta 584
                        retailer.status = 'fassigned'
585
                    retailer.retry_count = 0
15123 amit.gupta 586
                    retailer.invalid_retry_count = 0
15168 amit.gupta 587
                    lgr.info( "Found Retailer " +  str(retailer.id) + " with status " + status + " assigned to " + str(self.agentId))
15081 amit.gupta 588
 
589
                else:
15168 amit.gupta 590
                    lgr.info( "No fresh/followup retailers found")
15081 amit.gupta 591
                    if failback:
592
                        retailer = self.getRetryRetailer(False)
15104 amit.gupta 593
                        return retailer
15148 amit.gupta 594
                retry=False
15081 amit.gupta 595
        except:
596
            print traceback.print_exc()
597
        return retailer
598
 
15132 amit.gupta 599
    def on_get(self, req, resp, agentId, callType=None, retailerId=None):
15081 amit.gupta 600
        global RETAILER_DETAIL_CALL_COUNTER
601
        RETAILER_DETAIL_CALL_COUNTER += 1
15168 amit.gupta 602
        lgr.info( "RETAILER_DETAIL_CALL_COUNTER " +  str(RETAILER_DETAIL_CALL_COUNTER))
15081 amit.gupta 603
        self.agentId = int(agentId)
604
        self.callType = callType
15139 amit.gupta 605
        if retailerId is not None:
606
            self.retailerId = int(retailerId)
15208 amit.gupta 607
            retailerLink = session.query(RetailerLinks).filter_by(retailer_id=self.retailerId).first()
15132 amit.gupta 608
            if retailerLink is not None:
609
                code = retailerLink.code
610
            else: 
611
                code = self.getCode()
612
                retailerLink = RetailerLinks()
613
                retailerLink.code = code
15139 amit.gupta 614
                retailerLink.agent_id = self.agentId
615
                retailerLink.retailer_id = self.retailerId
15135 amit.gupta 616
 
617
                activationCode=Activation_Codes()
618
                activationCode.code = code
15132 amit.gupta 619
                session.commit()
620
            session.close()
15142 amit.gupta 621
            resp.body =  json.dumps({"result":{"code":code,"link":make_tiny(code)}}, encoding='utf-8')
15132 amit.gupta 622
            return 
15081 amit.gupta 623
        retryFlag = False 
624
        if RETAILER_DETAIL_CALL_COUNTER % DEALER_RETRY_FACTOR ==0:
625
            retryFlag=True
15239 amit.gupta 626
        try:
627
            if retryFlag:
628
                retailer = self.getRetryRetailer()
629
            else:
630
                retailer = self.getNewRetailer()
631
            fetchInfo = FetchDataHistory()
632
            fetchInfo.agent_id = self.agentId
633
            fetchInfo.call_type = self.callType
15240 amit.gupta 634
            agent = session.query(Agents).filter_by(id=self.agentId).first()
15239 amit.gupta 635
            last_disposition = session.query(CallHistory).filter_by(agent_id=self.agentId).order_by(CallHistory.id.desc()).first()
636
            if last_disposition is None or last_disposition.created < agent.last_login:
637
                fetchInfo.last_action = 'login'
638
                fetchInfo.last_action_time = agent.last_login 
639
            else:
640
                fetchInfo.last_action = 'disposition'
641
                fetchInfo.last_action_time = last_disposition.created
642
            fetchInfo.retailer_id = retailer.id
643
            session.commit()
15241 amit.gupta 644
 
15286 amit.gupta 645
            otherContacts = session.query(RetailerContacts).filter_by(retailer_id=retailer.id).all() 
15241 amit.gupta 646
            if retailer is None:
647
                resp.body = "{}"
648
            else:
15286 amit.gupta 649
                resp.body = json.dumps(todict(getRetailerObj(retailer, otherContacts)), encoding='utf-8')
15241 amit.gupta 650
 
651
            return
652
 
15239 amit.gupta 653
        finally:
654
            session.close()
15241 amit.gupta 655
 
15081 amit.gupta 656
        if retailer is None:
15157 amit.gupta 657
            resp.body = "{}"
15081 amit.gupta 658
        else:
659
            resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
660
 
15241 amit.gupta 661
 
15081 amit.gupta 662
    def on_post(self, req, resp, agentId, callType):
15112 amit.gupta 663
        returned = False
15081 amit.gupta 664
        self.agentId = int(agentId)
665
        self.callType = callType
666
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15169 amit.gupta 667
        lgr.info( "Request ----\n"  + str(jsonReq))
15091 amit.gupta 668
        self.jsonReq = jsonReq
669
        invalidNumber = self.invalidNumber
670
        callLater = self.callLater
15096 amit.gupta 671
        alreadyUser = self.alReadyUser
15091 amit.gupta 672
        verifiedLinkSent = self.verifiedLinkSent
15278 amit.gupta 673
        self.address = jsonReq.get('address')
15096 amit.gupta 674
        self.retailerId = int(jsonReq.get('retailerid'))
15254 amit.gupta 675
        self.smsNumber = jsonReq.get('smsnumber') 
15112 amit.gupta 676
        try:
677
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
15281 amit.gupta 678
            if self.address:
15278 amit.gupta 679
                self.retailer.address_new = self.address
15112 amit.gupta 680
            self.callDisposition = jsonReq.get('calldispositiontype')
681
            self.callHistory = CallHistory()
682
            self.callHistory.agent_id=self.agentId
683
            self.callHistory.call_disposition = self.callDisposition
684
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 685
            self.callHistory.call_type=self.callType
15112 amit.gupta 686
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
687
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 688
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
689
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 690
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
691
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 692
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 693
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
694
            if lastFetchData is None:
695
                raise
696
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 697
 
698
            dispositionMap = {  'call_later':callLater,
699
                        'ringing_no_answer':callLater,
700
                        'not_reachable':callLater,
701
                        'switch_off':callLater,
15202 manas 702
                        'not_retailer':invalidNumber,
15112 amit.gupta 703
                        'invalid_no':invalidNumber,
704
                        'wrong_no':invalidNumber,
705
                        'hang_up':invalidNumber,
706
                        'retailer_not_interested':invalidNumber,
15200 manas 707
                        'recharge_retailer':invalidNumber,
708
                        'accessory_retailer':invalidNumber,
709
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 710
                        'alreadyuser':alreadyUser,
711
                        'verified_link_sent':verifiedLinkSent
712
                      }
713
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
714
        finally:
715
            session.close()
15096 amit.gupta 716
 
15112 amit.gupta 717
        if returned:
718
            resp.body = "{\"result\":\"success\"}"
719
        else:
720
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 721
 
15091 amit.gupta 722
    def invalidNumber(self,):
15108 manas 723
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
724
        if self.callDisposition == 'invalid_no':
725
            self.retailer.status='failed'
726
            self.callHistory.disposition_description = 'Invalid Number'
727
        elif self.callDisposition == 'wrong_no':
15111 manas 728
            self.retailer.status='failed'
729
            self.callHistory.disposition_description = 'Wrong Number'
730
        elif self.callDisposition == 'hang_up':
731
            self.retailer.status='failed'
732
            self.callHistory.disposition_description = 'Hang Up'
733
        elif self.callDisposition == 'retailer_not_interested':
734
            self.retailer.status='failed'
735
            if self.callHistory.disposition_description is None:
736
                self.callHistory.disposition_description = 'NA'
15200 manas 737
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
738
        elif self.callDisposition == 'recharge_retailer':
739
            self.retailer.status='failed'
740
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
741
        elif self.callDisposition == 'accessory_retailer':
742
            self.retailer.status='failed'
743
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
744
        elif self.callDisposition == 'service_center_retailer':
745
            self.retailer.status='failed'
746
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 747
        elif self.callDisposition == 'not_retailer':
748
            self.retailer.status='failed'
749
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 750
        session.commit()
751
        return True   
752
 
15132 amit.gupta 753
    def getCode(self,):
15207 amit.gupta 754
        newCode = None
755
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
756
        if lastLink is not None:
757
            if len(lastLink.code)==len(codesys):
758
                newCode=lastLink.code
759
        return getNextCode(codesys, newCode)
15108 manas 760
 
15254 amit.gupta 761
 
15091 amit.gupta 762
    def callLater(self,):
15100 amit.gupta 763
        self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
764
        self.retailer.call_priority = None
15096 amit.gupta 765
        if self.callDisposition == 'call_later':
15100 amit.gupta 766
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 767
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 768
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
769
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
770
            else:
15102 amit.gupta 771
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 772
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 773
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
774
        else: 
775
            if self.callDisposition == 'ringing_no_answer':
776
                if self.retailer.disposition == 'ringing_no_answer':
777
                    self.retailer.retry_count += 1
778
                else:
779
                    self.retailer.disposition = 'ringing_no_answer'
780
                    self.retailer.retry_count = 1
781
            else:
782
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 783
                    pass
15112 amit.gupta 784
                else:
15119 amit.gupta 785
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 786
                self.retailer.retry_count += 1
787
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 788
 
15122 amit.gupta 789
            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 790
            if retryConfig is not None:
791
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 792
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 793
            else:
794
                self.retailer.status = 'failed'
795
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 796
 
15101 amit.gupta 797
        session.commit()
798
        return True
15096 amit.gupta 799
 
15100 amit.gupta 800
 
15091 amit.gupta 801
    def alReadyUser(self,):
15112 amit.gupta 802
        self.retailer.status = self.callDisposition
15117 amit.gupta 803
        if self.callHistory.disposition_description is None:
804
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 805
        session.commit()
806
        return True
15091 amit.gupta 807
    def verifiedLinkSent(self,):
15147 amit.gupta 808
        if self.callType == 'fresh':
809
            self.retailer.status = 'followup'
810
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
811
            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') 
812
        else:
15224 amit.gupta 813
            self.retailer.status = 'followup'
15147 amit.gupta 814
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
15254 amit.gupta 815
            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')
816
        addContactToRetailer(self.agentId, self.retailerId, self.smsNumber, self.callLater(), 'sms')     
15146 amit.gupta 817
        session.commit()
818
        return True
15254 amit.gupta 819
def isActivated(retailerId):
15276 amit.gupta 820
    retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailerId).first()
821
    user = session.query(Users).filter_by(referrer=retailerLink.code).first()
822
    if user is None:
823
        mobileNumbers = list(session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailerId).all())
824
        user = session.query(Users).filter(Users.mobile_number.in_(mobileNumbers)).first()
15254 amit.gupta 825
        if user is None:
15276 amit.gupta 826
            return False
827
        else:
828
            mapped_with = 'contact'
829
    else:
830
        mapped_with = 'code'
831
    retailerLink.mapped_with = mapped_with
832
    retailerLink.user_id = user.id
15291 amit.gupta 833
    retailer = session.query(Retailers).filter_by(id=retailerId).first()
15276 amit.gupta 834
    retailer.status = 'onboarded'
835
    session.commit()
15287 amit.gupta 836
    print "retailerLink.retailer_id", retailerLink.retailer_id
15276 amit.gupta 837
    session.close()
838
    return True
15254 amit.gupta 839
 
840
class AddContactToRetailer():
841
    def on_post(self,req,resp, agentId):
842
        agentId = int(agentId)
843
        try:
844
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
845
            retailerId = int(jsonReq.get("retailerid"))
846
            mobile = jsonReq.get("mobile")
847
            callType = jsonReq.get("calltype")
848
            contactType = jsonReq.get("contacttype")
849
            addContactToRetailer(agentId, retailerId, mobile, callType, contactType)
850
            session.commit()
851
        finally:
852
            session.close()
853
 
854
def addContactToRetailer(agentId, retailerId, mobile, callType, contactType):
855
    retailerContacts = session.query(RetailerContacts).filter_by(retailer_id=retailerId).filter_by(mobile_number=mobile).first()
856
    if retailerContacts is None:
857
        retailerContact = RetailerContacts()
15256 amit.gupta 858
        retailerContact.retailer_id = retailerId
15254 amit.gupta 859
        retailerContact.agent_id = agentId
860
        retailerContact.call_type = callType
861
        retailerContact.contact_type = contactType
862
        retailerContact.mobile_number = mobile
863
 
15189 manas 864
class Login():
865
 
866
    def on_get(self, req, resp, agentId, role):
867
        try:
15198 manas 868
            self.agentId = int(agentId)
869
            self.role = role
870
            print str(self.agentId) + self.role;
15199 manas 871
            agents=AgentLoginTimings()
872
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
873
            print 'lastLogintime' + str(lastLoginTime)
874
            agents.loginTime=lastLoginTime.last_login
875
            agents.logoutTime=datetime.now()
876
            agents.role =self.role
15282 amit.gupta 877
            agents.agent_id = self.agentId
15199 manas 878
            session.add(agents)    
879
            session.commit()
880
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 881
        finally:
882
            session.close()        
15112 amit.gupta 883
 
15189 manas 884
    def on_post(self,req,resp):
885
        try:
886
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
887
            lgr.info( "Request ----\n"  + str(jsonReq))
888
            email=jsonReq.get('email')
889
            password = jsonReq.get('password')
890
            role=jsonReq.get('role')    
891
            checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
892
            if checkUser is None:
893
                print checkUser
894
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
895
            else:
896
                print checkUser[0]
897
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
898
                if checkRole is None:
899
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
900
                else:
15196 manas 901
                    session.query(Agents).filter_by(id = checkUser[0]).update({"last_login":datetime.now()})
15195 manas 902
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":checkUser[0]}}, encoding='utf-8')
903
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 904
                    session.commit()
905
        finally:
906
            session.close()    
907
 
15195 manas 908
    def test(self,email,password,role):
15189 manas 909
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
910
        if checkUser is None:
911
            print checkUser
15195 manas 912
 
15189 manas 913
        else:
914
            print checkUser[0]
915
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
916
            if checkRole is None:
15195 manas 917
                pass
15189 manas 918
            else:
15195 manas 919
                agents=AgentLoginTimings()
920
                agents.loginTime=datetime.now()
921
                agents.logoutTime=datetime.now()
922
                agents.role =role
923
                agents.agent_id = 2
924
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
925
                session.add(agents)    
926
                session.commit()
927
                session.close()
928
 
929
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15275 amit.gupta 930
 
931
class RetailerActivation():
932
    def on_get(self, req, resp, userId):
933
        return markDealerActivation(int(userId))
934
 
935
def markDealerActivation(userId):
936
    try:
937
        user = session.query(Users).filter_by(id=userId)
938
        result = False                
939
        mappedWith = 'contact'
940
        if user is not None:
941
            retailerLink = session.query(RetailerLinks).filter_by(code=user.referrer).first()
942
            if retailerLink is None:
943
                retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
944
                if retailerContact is None:
945
                    retailer = session.query(Retailers).filter(Retailers.status.in_(['followup', 'fretry'])).filter(or_(Retailers.contact1==user.mobile_number,Retailers.contact2==user.mobile_number)).first()
946
                else:
947
                    retailer = session.query(Retailers).filter_by(id = retailerContact.retailer_id).first()
948
            else:
949
                retailer = session.query(Retailers).filter_by(id = retailerLink.retailer_id).first()
950
                mappedWith='code'
951
            if retailer is not None:
952
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailer.id).first()
953
                if retailerLink is not None:
954
                    retailerLink.user_id = user.id
955
                    retailerLink.mapped_with=mappedWith
956
                    retailer.status = 'onboarded'
957
                    result = True
958
                    session.commit()
959
            return result
960
    finally:
961
        session.close()
962
 
15189 manas 963
 
15081 amit.gupta 964
def todict(obj, classkey=None):
965
    if isinstance(obj, dict):
966
        data = {}
967
        for (k, v) in obj.items():
968
            data[k] = todict(v, classkey)
969
        return data
970
    elif hasattr(obj, "_ast"):
971
        return todict(obj._ast())
972
    elif hasattr(obj, "__iter__"):
973
        return [todict(v, classkey) for v in obj]
974
    elif hasattr(obj, "__dict__"):
975
        data = dict([(key, todict(value, classkey)) 
976
            for key, value in obj.__dict__.iteritems() 
977
            if not callable(value) and not key.startswith('_')])
978
        if classkey is not None and hasattr(obj, "__class__"):
979
            data[classkey] = obj.__class__.__name__
980
        return data
981
    else:
982
        return obj
983
 
15307 amit.gupta 984
def getRetailerObj(retailer, otherContacts1=[]):
15308 amit.gupta 985
    print "before otherContacts1",otherContacts1
15307 amit.gupta 986
    otherContacts1 = [] if otherContacts1 is None else otherContacts1
15308 amit.gupta 987
    print "after otherContacts1",otherContacts1
15081 amit.gupta 988
    obj = Mock()
989
    obj.title = retailer.title
15280 amit.gupta 990
    obj.id = retailer.id
15307 amit.gupta 991
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts1:
992
        otherContacts1.append(retailer.contact1)
993
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts1:
994
        otherContacts1.append(retailer.contact2)
15276 amit.gupta 995
    obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
15307 amit.gupta 996
    obj.contact1 = otherContacts1[0]
997
    obj.contact2 = None if len(otherContacts1)==1 else otherContacts1[1]
15096 amit.gupta 998
    obj.scheduled = (retailer.call_priority is not None)
15081 amit.gupta 999
    return obj
15091 amit.gupta 1000
 
15132 amit.gupta 1001
def make_tiny(code):
1002
    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
1003
    request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1004
    filehandle = urllib2.Request(request_url)
1005
    x= urllib2.urlopen(filehandle)
1006
    return str(x.read())
15171 amit.gupta 1007
 
15285 manas 1008
class SearchUser():
1009
 
1010
    def on_post(self, req, resp, agentId, searchType):
1011
        try:
1012
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1013
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1014
            contact=jsonReq.get('searchTerm')
15285 manas 1015
            if(searchType=="number"):
15297 amit.gupta 1016
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact)
15305 amit.gupta 1017
            elif(searchType=="counter"):
15306 amit.gupta 1018
                #retailer_ids = list(session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all())    
15303 amit.gupta 1019
                anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1020
 
15300 amit.gupta 1021
            searchUser = session.query(Retailers).filter(Retailers.modified != None).filter(anotherCondition).all()
15285 manas 1022
            if searchUser is None:
1023
                resp.body = json.dumps("{}")
1024
            else:    
1025
                resp.body = json.dumps({"Retailers":[todict(getRetailerObj(user)) for user in searchUser]}, encoding='utf-8')
1026
        finally:
1027
            session.close()
15171 amit.gupta 1028
 
15285 manas 1029
 
15171 amit.gupta 1030
#def update_pin():
15081 amit.gupta 1031
 
15132 amit.gupta 1032
 
15081 amit.gupta 1033
class Mock(object):
1034
    pass
15189 manas 1035
 
15081 amit.gupta 1036
def main():
15288 amit.gupta 1037
    retailerIds = session.query(RetailerLinks.retailer_id).all()
1038
    for retailerId in retailerIds:
15292 amit.gupta 1039
        (retailerId,) = retailerId
15288 amit.gupta 1040
        isActivated(retailerId)
15195 manas 1041
 
15081 amit.gupta 1042
if __name__ == '__main__':
15207 amit.gupta 1043
    main()
15091 amit.gupta 1044