Subversion Repositories SmartDukaan

Rev

Rev 15300 | Rev 15302 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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