Subversion Repositories SmartDukaan

Rev

Rev 17611 | Rev 17615 | 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
15534 amit.gupta 4
from pyshorteners.shorteners  import Shortener
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, \
15676 amit.gupta 10
    FetchDataHistory, RetailerContacts, Orders, OnboardedRetailerChecklists,\
17467 manas 11
    RetailerAddresses, Pincodeavailability, app_offers, appmasters, user_app_cashbacks, user_app_installs,\
12
    Postoffices
15358 amit.gupta 13
from dtr.storage.Mongo import get_mongo_connection
14
from dtr.storage.Mysql import fetchResult
15081 amit.gupta 15
from dtr.utils import FetchLivePrices, DealSheet as X_DealSheet, \
16
    UserSpecificDeals
15168 amit.gupta 17
from dtr.utils.utils import getLogger
15081 amit.gupta 18
from elixir import *
15254 amit.gupta 19
from operator import and_
16714 manish.sha 20
from sqlalchemy.sql.expression import func, func, or_, desc, asc, case
15132 amit.gupta 21
from urllib import urlencode
22
import contextlib
13827 kshitij.so 23
import falcon
15081 amit.gupta 24
import json
15358 amit.gupta 25
import re
15254 amit.gupta 26
import string
15081 amit.gupta 27
import traceback
15132 amit.gupta 28
import urllib
29
import urllib2
30
import uuid
15465 amit.gupta 31
import gdshortener
16727 manish.sha 32
from dtr.dao import AppOfferObj, UserAppBatchDrillDown, UserAppBatchDateDrillDown
16631 manish.sha 33
 
15207 amit.gupta 34
alphalist = list(string.uppercase)
35
alphalist.remove('O')
36
numList = ['1','2','3','4','5','6','7','8','9']
37
codesys = [alphalist, alphalist, numList, numList, numList]
15312 amit.gupta 38
CONTACT_PRIORITY = ['sms', 'called', 'ringing']
15368 amit.gupta 39
RETRY_MAP = {'fresh':'retry', 'followup':'fretry', 'onboarding':'oretry'}
15358 amit.gupta 40
ASSIGN_MAP = {'retry':'assigned', 'fretry':'fassigned', 'oretry':'oassigned'}
15207 amit.gupta 41
 
16882 amit.gupta 42
sticky_agents = [17]
43
 
15207 amit.gupta 44
def getNextCode(codesys, code=None):
45
    if code is None:
46
        code = []
47
        for charcode in codesys:
48
            code.append(charcode[0])
49
        return string.join(code, '')
50
    carry = True
51
    code = list(code)
52
    lastindex = len(codesys) - 1
53
    while carry:
54
        listChar = codesys[lastindex]
55
        newIndex = (listChar.index(code[lastindex])+1)%len(listChar)
56
        print newIndex
57
        code[lastindex] = listChar[newIndex]
58
        if newIndex != 0:
59
            carry = False
60
        lastindex -= 1
61
        if lastindex ==-1:
62
            raise BaseException("All codes are exhausted")
63
 
64
    return string.join(code, '')
65
 
66
 
67
 
68
 
15081 amit.gupta 69
global RETAILER_DETAIL_CALL_COUNTER
70
RETAILER_DETAIL_CALL_COUNTER = 0
13572 kshitij.so 71
 
15168 amit.gupta 72
lgr = getLogger('/var/log/retailer-acquisition-api.log')
15081 amit.gupta 73
DEALER_RETRY_FACTOR = int(PythonPropertyReader.getConfig('DEALER_RETRY_FACTOR'))
16886 amit.gupta 74
DEALER_FRESH_FACTOR = int(PythonPropertyReader.getConfig('DEALER_FRESH_FACTOR'))
75
TOTAL = DEALER_RETRY_FACTOR + DEALER_FRESH_FACTOR  
13572 kshitij.so 76
class CategoryDiscountInfo(object):
77
 
78
    def on_get(self, req, resp):
79
 
13629 kshitij.so 80
        result = Mongo.getAllCategoryDiscount()
81
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
82
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 83
 
84
    def on_post(self, req, resp):
85
        try:
86
            result_json = json.loads(req.stream.read(), encoding='utf-8')
87
        except ValueError:
88
            raise falcon.HTTPError(falcon.HTTP_400,
89
                'Malformed JSON',
90
                'Could not decode the request body. The '
91
                'JSON was incorrect.')
92
 
93
        result = Mongo.addCategoryDiscount(result_json)
94
        resp.body = json.dumps(result, encoding='utf-8')
13969 kshitij.so 95
 
96
    def on_put(self, req, resp, _id):
13970 kshitij.so 97
        try:
98
            result_json = json.loads(req.stream.read(), encoding='utf-8')
99
        except ValueError:
100
            raise falcon.HTTPError(falcon.HTTP_400,
101
                'Malformed JSON',
102
                'Could not decode the request body. The '
103
                'JSON was incorrect.')
104
 
105
        result = Mongo.updateCategoryDiscount(result_json, _id)
106
        resp.body = json.dumps(result, encoding='utf-8')
107
 
13966 kshitij.so 108
 
13969 kshitij.so 109
 
13572 kshitij.so 110
class SkuSchemeDetails(object):
111
 
112
    def on_get(self, req, resp):
13629 kshitij.so 113
 
14070 kshitij.so 114
        offset = req.get_param_as_int("offset")
115
        limit = req.get_param_as_int("limit")
116
 
117
        result = Mongo.getAllSkuWiseSchemeDetails(offset, limit)
13629 kshitij.so 118
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
119
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 120
 
121
 
122
    def on_post(self, req, resp):
123
 
14552 kshitij.so 124
        multi = req.get_param_as_int("multi")
125
 
13572 kshitij.so 126
        try:
127
            result_json = json.loads(req.stream.read(), encoding='utf-8')
128
        except ValueError:
129
            raise falcon.HTTPError(falcon.HTTP_400,
130
                'Malformed JSON',
131
                'Could not decode the request body. The '
132
                'JSON was incorrect.')
133
 
15852 kshitij.so 134
        result = Mongo.addSchemeDetailsForSku(result_json)
13572 kshitij.so 135
        resp.body = json.dumps(result, encoding='utf-8')
136
 
137
class SkuDiscountInfo():
138
 
139
    def on_get(self, req, resp):
13629 kshitij.so 140
 
13970 kshitij.so 141
        offset = req.get_param_as_int("offset")
142
        limit = req.get_param_as_int("limit")
143
        result = Mongo.getallSkuDiscountInfo(offset,limit)
13629 kshitij.so 144
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
145
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 146
 
147
 
148
    def on_post(self, req, resp):
149
 
14552 kshitij.so 150
        multi = req.get_param_as_int("multi")
151
 
13572 kshitij.so 152
        try:
153
            result_json = json.loads(req.stream.read(), encoding='utf-8')
154
        except ValueError:
155
            raise falcon.HTTPError(falcon.HTTP_400,
156
                'Malformed JSON',
157
                'Could not decode the request body. The '
158
                'JSON was incorrect.')
159
 
15852 kshitij.so 160
        result = Mongo.addSkuDiscountInfo(result_json)
13572 kshitij.so 161
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 162
 
163
    def on_put(self, req, resp, _id):
164
        try:
165
            result_json = json.loads(req.stream.read(), encoding='utf-8')
166
        except ValueError:
167
            raise falcon.HTTPError(falcon.HTTP_400,
168
                'Malformed JSON',
169
                'Could not decode the request body. The '
170
                'JSON was incorrect.')
171
 
172
        result = Mongo.updateSkuDiscount(result_json, _id)
173
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 174
 
175
class ExceptionalNlc():
176
 
177
    def on_get(self, req, resp):
13629 kshitij.so 178
 
13970 kshitij.so 179
        offset = req.get_param_as_int("offset")
180
        limit = req.get_param_as_int("limit")
181
 
182
        result = Mongo.getAllExceptionlNlcItems(offset, limit)
13629 kshitij.so 183
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
184
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 185
 
186
    def on_post(self, req, resp):
187
 
14552 kshitij.so 188
        multi = req.get_param_as_int("multi")
189
 
13572 kshitij.so 190
        try:
191
            result_json = json.loads(req.stream.read(), encoding='utf-8')
192
        except ValueError:
193
            raise falcon.HTTPError(falcon.HTTP_400,
194
                'Malformed JSON',
195
                'Could not decode the request body. The '
196
                'JSON was incorrect.')
197
 
15852 kshitij.so 198
        result = Mongo.addExceptionalNlc(result_json)
13572 kshitij.so 199
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 200
 
201
    def on_put(self, req, resp, _id):
202
        try:
203
            result_json = json.loads(req.stream.read(), encoding='utf-8')
204
        except ValueError:
205
            raise falcon.HTTPError(falcon.HTTP_400,
206
                'Malformed JSON',
207
                'Could not decode the request body. The '
208
                'JSON was incorrect.')
209
 
210
        result = Mongo.updateExceptionalNlc(result_json, _id)
211
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 212
 
13772 kshitij.so 213
class Deals():
13779 kshitij.so 214
    def on_get(self,req, resp, userId):
215
        categoryId = req.get_param_as_int("categoryId")
216
        offset = req.get_param_as_int("offset")
217
        limit = req.get_param_as_int("limit")
13798 kshitij.so 218
        sort = req.get_param("sort")
13802 kshitij.so 219
        direction = req.get_param_as_int("direction")
14853 kshitij.so 220
        filterData = req.get_param('filterData')
221
        result = Mongo.getNewDeals(int(userId), categoryId, offset, limit, sort, direction, filterData)
16078 kshitij.so 222
        resp.body = dumps(result) 
13790 kshitij.so 223
 
224
class MasterData():
225
    def on_get(self,req, resp, skuId):
16223 kshitij.so 226
        showDp = req.get_param_as_int("showDp")
16221 kshitij.so 227
        result = Mongo.getItem(skuId, showDp)
13798 kshitij.so 228
        try:
229
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 230
            resp.body = json.dumps(json_docs, encoding='utf-8')
13798 kshitij.so 231
        except:
232
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 233
            resp.body = json.dumps(json_docs, encoding='utf-8')
13790 kshitij.so 234
 
14586 kshitij.so 235
    def on_post(self,req, resp):
236
 
237
        addNew = req.get_param_as_int("addNew")
238
        update = req.get_param_as_int("update")
239
        addToExisting = req.get_param_as_int("addToExisting")
240
        multi = req.get_param_as_int("multi")
241
 
14589 kshitij.so 242
        try:
14592 kshitij.so 243
            result_json = json.loads(req.stream.read(), encoding='utf-8')
244
        except ValueError:
245
            raise falcon.HTTPError(falcon.HTTP_400,
246
                'Malformed JSON',
247
                'Could not decode the request body. The '
248
                'JSON was incorrect.')
249
 
250
        if addNew == 1:
251
            result = Mongo.addNewItem(result_json)
252
        elif update == 1:
253
            result = Mongo.updateMaster(result_json, multi)
254
        elif addToExisting == 1:
255
            result = Mongo.addItemToExistingBundle(result_json)
256
        else:
257
            raise
258
        resp.body = dumps(result)
14586 kshitij.so 259
 
13827 kshitij.so 260
class LiveData():
261
    def on_get(self,req, resp):
13865 kshitij.so 262
        if req.get_param_as_int("id") is not None:
263
            print "****getting only for id"
264
            id = req.get_param_as_int("id")
265
            try:
266
                result = FetchLivePrices.getLatestPriceById(id)
13867 kshitij.so 267
                json_docs = json.dumps(result, default=json_util.default)
13966 kshitij.so 268
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 269
            except:
270
                json_docs = json.dumps({}, default=json_util.default)
13966 kshitij.so 271
                resp.body = json.dumps(json_docs, encoding='utf-8')
13834 kshitij.so 272
 
13865 kshitij.so 273
        else:
274
            print "****getting only for skuId"
275
            skuBundleId = req.get_param_as_int("skuBundleId")
276
            source_id = req.get_param_as_int("source_id")
277
            try:
278
                result = FetchLivePrices.getLatestPrice(skuBundleId, source_id)
279
                json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 280
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 281
            except:
282
                json_docs = [json.dumps(doc, default=json_util.default) for doc in [{}]]
13966 kshitij.so 283
                resp.body = json.dumps(json_docs, encoding='utf-8')
13865 kshitij.so 284
 
13834 kshitij.so 285
class CashBack():
286
    def on_get(self,req, resp):
287
        identifier = req.get_param("identifier")
288
        source_id = req.get_param_as_int("source_id")
289
        try:
13838 kshitij.so 290
            result = Mongo.getCashBackDetails(identifier, source_id)
13837 kshitij.so 291
            json_docs = json.dumps(result, default=json_util.default)
13964 kshitij.so 292
            resp.body = json_docs
13834 kshitij.so 293
        except:
13837 kshitij.so 294
            json_docs = json.dumps({}, default=json_util.default)
13963 kshitij.so 295
            resp.body = json_docs
13892 kshitij.so 296
 
14398 amit.gupta 297
class ImgSrc():
298
    def on_get(self,req, resp):
299
        identifier = req.get_param("identifier")
300
        source_id = req.get_param_as_int("source_id")
301
        try:
302
            result = Mongo.getImgSrc(identifier, source_id)
303
            json_docs = json.dumps(result, default=json_util.default)
304
            resp.body = json_docs
305
        except:
306
            json_docs = json.dumps({}, default=json_util.default)
307
            resp.body = json_docs
308
 
13892 kshitij.so 309
class DealSheet():
310
    def on_get(self,req, resp):
13895 kshitij.so 311
        X_DealSheet.sendMail()
13897 kshitij.so 312
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
13966 kshitij.so 313
        resp.body = json.dumps(json_docs, encoding='utf-8')
13892 kshitij.so 314
 
13970 kshitij.so 315
class DealerPrice():
316
 
317
    def on_get(self, req, resp):
318
 
319
        offset = req.get_param_as_int("offset")
320
        limit = req.get_param_as_int("limit")
321
        result = Mongo.getAllDealerPrices(offset,limit)
322
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
323
        resp.body = json.dumps(json_docs, encoding='utf-8')
324
 
325
    def on_post(self, req, resp):
326
 
14552 kshitij.so 327
        multi = req.get_param_as_int("multi")
328
 
13970 kshitij.so 329
        try:
330
            result_json = json.loads(req.stream.read(), encoding='utf-8')
331
        except ValueError:
332
            raise falcon.HTTPError(falcon.HTTP_400,
333
                'Malformed JSON',
334
                'Could not decode the request body. The '
335
                'JSON was incorrect.')
336
 
15852 kshitij.so 337
        result = Mongo.addSkuDealerPrice(result_json)
13970 kshitij.so 338
        resp.body = json.dumps(result, encoding='utf-8')
339
 
340
    def on_put(self, req, resp, _id):
341
        try:
342
            result_json = json.loads(req.stream.read(), encoding='utf-8')
343
        except ValueError:
344
            raise falcon.HTTPError(falcon.HTTP_400,
345
                'Malformed JSON',
346
                'Could not decode the request body. The '
347
                'JSON was incorrect.')
348
 
349
        result = Mongo.updateSkuDealerPrice(result_json, _id)
350
        resp.body = json.dumps(result, encoding='utf-8')
351
 
352
 
14041 kshitij.so 353
class ResetCache():
354
 
355
    def on_get(self,req, resp, userId):
14044 kshitij.so 356
        result = Mongo.resetCache(userId)
14046 kshitij.so 357
        resp.body = json.dumps(result, encoding='utf-8')
358
 
359
class UserDeals():
360
    def on_get(self,req,resp,userId):
361
        UserSpecificDeals.generateSheet(userId)
362
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
363
        resp.body = json.dumps(json_docs, encoding='utf-8')
14075 kshitij.so 364
 
365
class CommonUpdate():
366
 
367
    def on_post(self,req,resp):
14575 kshitij.so 368
 
369
        multi = req.get_param_as_int("multi")
370
 
14075 kshitij.so 371
        try:
372
            result_json = json.loads(req.stream.read(), encoding='utf-8')
373
        except ValueError:
374
            raise falcon.HTTPError(falcon.HTTP_400,
375
                'Malformed JSON',
376
                'Could not decode the request body. The '
377
                'JSON was incorrect.')
378
 
15852 kshitij.so 379
        result = Mongo.updateCollection(result_json)
14075 kshitij.so 380
        resp.body = json.dumps(result, encoding='utf-8')
14106 kshitij.so 381
        resp.content_type = "application/json; charset=utf-8"
14481 kshitij.so 382
 
383
class NegativeDeals():
384
 
385
    def on_get(self, req, resp):
386
 
387
        offset = req.get_param_as_int("offset")
388
        limit = req.get_param_as_int("limit")
389
 
390
        result = Mongo.getAllNegativeDeals(offset, limit)
14483 kshitij.so 391
        resp.body = dumps(result) 
14481 kshitij.so 392
 
393
 
394
    def on_post(self, req, resp):
395
 
14552 kshitij.so 396
        multi = req.get_param_as_int("multi")
397
 
14481 kshitij.so 398
        try:
399
            result_json = json.loads(req.stream.read(), encoding='utf-8')
400
        except ValueError:
401
            raise falcon.HTTPError(falcon.HTTP_400,
402
                'Malformed JSON',
403
                'Could not decode the request body. The '
404
                'JSON was incorrect.')
405
 
14552 kshitij.so 406
        result = Mongo.addNegativeDeals(result_json, multi)
14481 kshitij.so 407
        resp.body = json.dumps(result, encoding='utf-8')
408
 
409
class ManualDeals():
410
 
411
    def on_get(self, req, resp):
412
 
413
        offset = req.get_param_as_int("offset")
414
        limit = req.get_param_as_int("limit")
415
 
416
        result = Mongo.getAllManualDeals(offset, limit)
14483 kshitij.so 417
        resp.body = dumps(result)
14481 kshitij.so 418
 
419
 
420
    def on_post(self, req, resp):
421
 
14552 kshitij.so 422
        multi = req.get_param_as_int("multi")
423
 
14481 kshitij.so 424
        try:
425
            result_json = json.loads(req.stream.read(), encoding='utf-8')
426
        except ValueError:
427
            raise falcon.HTTPError(falcon.HTTP_400,
428
                'Malformed JSON',
429
                'Could not decode the request body. The '
430
                'JSON was incorrect.')
431
 
14552 kshitij.so 432
        result = Mongo.addManualDeal(result_json, multi)
14481 kshitij.so 433
        resp.body = json.dumps(result, encoding='utf-8')
434
 
435
class CommonDelete():
14482 kshitij.so 436
 
14481 kshitij.so 437
    def on_post(self,req,resp):
438
        try:
439
            result_json = json.loads(req.stream.read(), encoding='utf-8')
440
        except ValueError:
441
            raise falcon.HTTPError(falcon.HTTP_400,
442
                'Malformed JSON',
443
                'Could not decode the request body. The '
444
                'JSON was incorrect.')
445
 
446
        result = Mongo.deleteDocument(result_json)
447
        resp.body = json.dumps(result, encoding='utf-8')
448
        resp.content_type = "application/json; charset=utf-8"
14482 kshitij.so 449
 
450
class SearchProduct():
451
 
452
    def on_get(self,req,resp):
453
        offset = req.get_param_as_int("offset")
454
        limit = req.get_param_as_int("limit")
455
        search_term = req.get_param("search")
456
 
457
        result = Mongo.searchMaster(offset, limit, search_term)
14483 kshitij.so 458
        resp.body = dumps(result) 
14482 kshitij.so 459
 
460
 
14495 kshitij.so 461
class FeaturedDeals():
14482 kshitij.so 462
 
14495 kshitij.so 463
    def on_get(self, req, resp):
464
 
465
        offset = req.get_param_as_int("offset")
466
        limit = req.get_param_as_int("limit")
467
 
468
        result = Mongo.getAllFeaturedDeals(offset, limit)
469
        resp.body = dumps(result)
470
 
471
 
472
    def on_post(self, req, resp):
473
 
14552 kshitij.so 474
        multi = req.get_param_as_int("multi")
475
 
14495 kshitij.so 476
        try:
477
            result_json = json.loads(req.stream.read(), encoding='utf-8')
478
        except ValueError:
479
            raise falcon.HTTPError(falcon.HTTP_400,
480
                'Malformed JSON',
481
                'Could not decode the request body. The '
482
                'JSON was incorrect.')
483
 
14552 kshitij.so 484
        result = Mongo.addFeaturedDeal(result_json, multi)
14495 kshitij.so 485
        resp.body = json.dumps(result, encoding='utf-8')
486
 
14497 kshitij.so 487
 
488
class CommonSearch():
14495 kshitij.so 489
 
14497 kshitij.so 490
    def on_get(self,req,resp):
491
        class_name = req.get_param("class")
492
        sku = req.get_param_as_int("sku")
493
        skuBundleId = req.get_param_as_int("skuBundleId")
14499 kshitij.so 494
 
495
        result = Mongo.searchCollection(class_name, sku, skuBundleId)
14497 kshitij.so 496
        resp.body = dumps(result)
14619 kshitij.so 497
 
498
class CricScore():
499
 
500
    def on_get(self,req,resp):
501
 
502
        result = Mongo.getLiveCricScore()
14853 kshitij.so 503
        resp.body = dumps(result)
504
 
505
class Notification():
506
 
507
    def on_post(self, req, resp):
508
 
509
        try:
510
            result_json = json.loads(req.stream.read(), encoding='utf-8')
511
        except ValueError:
512
            raise falcon.HTTPError(falcon.HTTP_400,
513
                'Malformed JSON',
514
                'Could not decode the request body. The '
515
                'JSON was incorrect.')
516
 
517
        result = Mongo.addBundleToNotification(result_json)
518
        resp.body = json.dumps(result, encoding='utf-8')
519
 
520
    def on_get(self, req, resp):
521
 
522
        offset = req.get_param_as_int("offset")
523
        limit = req.get_param_as_int("limit")
524
 
525
        result = Mongo.getAllNotifications(offset, limit)
526
        resp.body = dumps(result)
527
 
14998 kshitij.so 528
class DealBrands():
14853 kshitij.so 529
 
14998 kshitij.so 530
    def on_get(self, req, resp):
531
 
532
        category_id = req.get_param_as_int("category_id")
533
        result = Mongo.getBrandsForFilter(category_id)
14999 kshitij.so 534
        resp.body = dumps(result)
15161 kshitij.so 535
 
536
class DealRank():
14998 kshitij.so 537
 
15161 kshitij.so 538
    def on_get(self, req, resp):
539
        identifier = req.get_param("identifier")
540
        source_id = req.get_param_as_int("source_id")
541
        user_id = req.get_param_as_int("user_id")
542
        result = Mongo.getDealRank(identifier, source_id, user_id)
543
        json_docs = json.dumps(result, default=json_util.default)
544
        resp.body = json_docs
545
 
546
 
16560 amit.gupta 547
class OrderedOffers():
548
    def on_get(self, req, resp, storeId, storeSku):
549
        storeId = int(storeId)
16563 amit.gupta 550
        result = Mongo.getBundleBySourceSku(storeId, storeSku)
551
        json_docs = json.dumps(result, default=json_util.default)
552
        resp.body = json_docs
553
 
15081 amit.gupta 554
class RetailerDetail():
555
    global RETAILER_DETAIL_CALL_COUNTER
15105 amit.gupta 556
    def getRetryRetailer(self,failback=True):
15358 amit.gupta 557
        status = RETRY_MAP.get(self.callType)
17089 amit.gupta 558
        retailer = session.query(Retailers).filter_by(status=status).filter(Retailers.next_call_time<=datetime.now()).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None)).order_by(Retailers.agent_id.desc(),Retailers.call_priority).order_by(Retailers.next_call_time).with_lockmode("update").first()
17029 amit.gupta 559
 
15239 amit.gupta 560
        if retailer is not None:
561
            lgr.info( "getRetryRetailer " + str(retailer.id))
562
        else:
563
            if failback:
564
                retailer = self.getNewRetailer(False)
565
                return retailer
16371 amit.gupta 566
            else:
567
                #No further calls for now
568
                return None
15358 amit.gupta 569
        retailer.status = ASSIGN_MAP.get(status)
16371 amit.gupta 570
        retailer.next_call_time = None
15239 amit.gupta 571
        lgr.info( "getRetryRetailer " + str(retailer.id))
15081 amit.gupta 572
        return retailer
573
 
15662 amit.gupta 574
    def getNotActiveRetailer(self):
575
        try:
15716 amit.gupta 576
            user = session.query(Users).filter_by(activated=0).filter_by(status=1).filter(Users.mobile_number != None).filter(~Users.mobile_number.like("0%")).filter(Users.created>datetime(2015,06,29)).order_by(Users.created.desc()).with_lockmode("update").first()
15662 amit.gupta 577
            if user is None: 
578
                return None
579
            else:
580
                retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
581
                if retailerContact is not None:
582
                    retailer = session.query(Retailers).filter_by(id=retailerContact.retailer_id).first()
583
                else:
584
                    retailer = session.query(Retailers).filter_by(contact1=user.mobile_number).first()
585
                    if retailer is None:
586
                        retailer = session.query(Retailers).filter_by(contact2=user.mobile_number).first()
587
                        if retailer is None:
588
                            retailer = Retailers()
589
                            retailer.contact1 = user.mobile_number
590
                            retailer.status = 'assigned'
15672 amit.gupta 591
                            retailer.retry_count = 0
15673 amit.gupta 592
                            retailer.invalid_retry_count = 0
15699 amit.gupta 593
                            retailer.is_elavated=1
15662 amit.gupta 594
                user.status = 2
595
                session.commit()
596
                print "retailer id", retailer.id
597
                retailer.contact = user.mobile_number
598
                return retailer
599
        finally:
600
            session.close()
601
 
15081 amit.gupta 602
    def getNewRetailer(self,failback=True):
15663 amit.gupta 603
        if self.callType == 'fresh':
604
            retailer = self.getNotActiveRetailer()
605
            if retailer is not None:
606
                return retailer
15081 amit.gupta 607
        retry = True
608
        retailer = None 
609
        try:
610
            while(retry):
15168 amit.gupta 611
                lgr.info( "Calltype " + self.callType)
15081 amit.gupta 612
                status=self.callType
15545 amit.gupta 613
                query = session.query(Retailers).filter(Retailers.status==status).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None))
15081 amit.gupta 614
                if status=='fresh':
17030 amit.gupta 615
                    query = query.filter_by(is_or=False, is_std=False).filter(Retailers.pin==Pincodeavailability.code).filter(Pincodeavailability.amount > 19999).order_by(Retailers.is_elavated.desc(), Retailers.agent_id.desc())
15358 amit.gupta 616
                elif status=='followup':
15546 amit.gupta 617
                    query = query.filter(Retailers.next_call_time<=datetime.now()).order_by(Retailers.agent_id.desc(),Retailers.next_call_time)
15162 amit.gupta 618
                else:
15546 amit.gupta 619
                    query = query.filter(Retailers.modified<=datetime.now()).order_by(Retailers.agent_id.desc(), Retailers.modified)
15358 amit.gupta 620
 
15081 amit.gupta 621
                retailer = query.with_lockmode("update").first()
622
                if retailer is not None:
15168 amit.gupta 623
                    lgr.info( "retailer " +str(retailer.id))
15081 amit.gupta 624
                    if status=="fresh":
625
                        userquery = session.query(Users)
626
                        if retailer.contact2 is not None:
627
                            userquery = userquery.filter(Users.mobile_number.in_([retailer.contact1,retailer.contact2]))
628
                        else:
629
                            userquery = userquery.filter_by(mobile_number=retailer.contact1)
630
                        user = userquery.first()
631
                        if user is not None:
632
                            retailer.status = 'alreadyuser'
15168 amit.gupta 633
                            lgr.info( "retailer.status " + retailer.status)
15081 amit.gupta 634
                            session.commit()
635
                            continue
636
                        retailer.status = 'assigned'
15358 amit.gupta 637
                    elif status=='followup':
15276 amit.gupta 638
                        if isActivated(retailer.id):
639
                            print "Retailer Already %d activated and marked onboarded"%(retailer.id)
640
                            continue
15081 amit.gupta 641
                        retailer.status = 'fassigned'
15358 amit.gupta 642
                    else:
643
                        retailer.status = 'oassigned'
15081 amit.gupta 644
                    retailer.retry_count = 0
15123 amit.gupta 645
                    retailer.invalid_retry_count = 0
15168 amit.gupta 646
                    lgr.info( "Found Retailer " +  str(retailer.id) + " with status " + status + " assigned to " + str(self.agentId))
15081 amit.gupta 647
 
648
                else:
15168 amit.gupta 649
                    lgr.info( "No fresh/followup retailers found")
15081 amit.gupta 650
                    if failback:
651
                        retailer = self.getRetryRetailer(False)
15104 amit.gupta 652
                        return retailer
15148 amit.gupta 653
                retry=False
15081 amit.gupta 654
        except:
655
            print traceback.print_exc()
656
        return retailer
657
 
15132 amit.gupta 658
    def on_get(self, req, resp, agentId, callType=None, retailerId=None):
16927 amit.gupta 659
        try:
660
            global RETAILER_DETAIL_CALL_COUNTER
661
            RETAILER_DETAIL_CALL_COUNTER += 1
662
            lgr.info( "RETAILER_DETAIL_CALL_COUNTER " +  str(RETAILER_DETAIL_CALL_COUNTER))
663
            self.agentId = int(agentId)
664
            self.callType = callType
665
            if retailerId is not None:
666
                self.retailerId = int(retailerId)
667
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=self.retailerId).first()
668
                if retailerLink is not None:
669
                    code = retailerLink.code
670
                else: 
671
                    code = self.getCode()
672
                    retailerLink = RetailerLinks()
673
                    retailerLink.code = code
674
                    retailerLink.agent_id = self.agentId
675
                    retailerLink.retailer_id = self.retailerId
676
 
677
                    activationCode=Activation_Codes()
678
                    activationCode.code = code
679
                    session.commit()
680
                session.close()
681
                resp.body =  json.dumps({"result":{"code":code,"link":make_tiny(code)}}, encoding='utf-8')
682
                return 
683
            retryFlag = False 
684
            if RETAILER_DETAIL_CALL_COUNTER % TOTAL >= DEALER_FRESH_FACTOR:
685
                retryFlag=True
686
            try:
687
                if retryFlag:
688
                    retailer = self.getRetryRetailer()
689
                else:
690
                    retailer = self.getNewRetailer()
691
                if retailer is None:
692
                    resp.body = "{}"
693
                    return
694
                fetchInfo = FetchDataHistory()
695
                fetchInfo.agent_id = self.agentId
696
                fetchInfo.call_type = self.callType
697
                agent = session.query(Agents).filter_by(id=self.agentId).first()
698
                last_disposition = session.query(CallHistory).filter_by(agent_id=self.agentId).order_by(CallHistory.id.desc()).first()
699
                if last_disposition is None or last_disposition.created < agent.last_login:
700
                    fetchInfo.last_action = 'login'
701
                    fetchInfo.last_action_time = agent.last_login 
702
                else:
703
                    fetchInfo.last_action = 'disposition'
704
                    fetchInfo.last_action_time = last_disposition.created
705
                fetchInfo.retailer_id = retailer.id
706
                session.commit()
15135 amit.gupta 707
 
16927 amit.gupta 708
                otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
709
                resp.body = json.dumps(todict(getRetailerObj(retailer, otherContacts, self.callType)), encoding='utf-8')
710
 
711
                return
712
 
713
            finally:
714
                session.close()
715
 
15343 amit.gupta 716
            if retailer is None:
717
                resp.body = "{}"
15239 amit.gupta 718
            else:
16927 amit.gupta 719
                print "It should never come here"
720
                resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
15239 amit.gupta 721
        finally:
722
            session.close()
15081 amit.gupta 723
 
724
    def on_post(self, req, resp, agentId, callType):
15112 amit.gupta 725
        returned = False
15081 amit.gupta 726
        self.agentId = int(agentId)
727
        self.callType = callType
728
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15169 amit.gupta 729
        lgr.info( "Request ----\n"  + str(jsonReq))
15091 amit.gupta 730
        self.jsonReq = jsonReq
731
        invalidNumber = self.invalidNumber
732
        callLater = self.callLater
15096 amit.gupta 733
        alreadyUser = self.alReadyUser
15091 amit.gupta 734
        verifiedLinkSent = self.verifiedLinkSent
15368 amit.gupta 735
        onboarded = self.onboarded
15278 amit.gupta 736
        self.address = jsonReq.get('address')
15096 amit.gupta 737
        self.retailerId = int(jsonReq.get('retailerid'))
15671 amit.gupta 738
        self.smsNumber = jsonReq.get('smsnumber')
739
        if self.smsNumber is not None:
740
            self.smsNumber = self.smsNumber.strip().lstrip("0") 
15112 amit.gupta 741
        try:
742
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
15281 amit.gupta 743
            if self.address:
15278 amit.gupta 744
                self.retailer.address_new = self.address
15112 amit.gupta 745
            self.callDisposition = jsonReq.get('calldispositiontype')
746
            self.callHistory = CallHistory()
747
            self.callHistory.agent_id=self.agentId
748
            self.callHistory.call_disposition = self.callDisposition
749
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 750
            self.callHistory.call_type=self.callType
15112 amit.gupta 751
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
752
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 753
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
754
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 755
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
756
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 757
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 758
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
15368 amit.gupta 759
            if self.callDisposition == 'onboarded':
760
                self.checkList = jsonReq.get('checklist')
761
 
15234 amit.gupta 762
            if lastFetchData is None:
763
                raise
764
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 765
 
766
            dispositionMap = {  'call_later':callLater,
767
                        'ringing_no_answer':callLater,
768
                        'not_reachable':callLater,
769
                        'switch_off':callLater,
15202 manas 770
                        'not_retailer':invalidNumber,
15112 amit.gupta 771
                        'invalid_no':invalidNumber,
772
                        'wrong_no':invalidNumber,
773
                        'hang_up':invalidNumber,
774
                        'retailer_not_interested':invalidNumber,
15200 manas 775
                        'recharge_retailer':invalidNumber,
776
                        'accessory_retailer':invalidNumber,
777
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 778
                        'alreadyuser':alreadyUser,
15368 amit.gupta 779
                        'verified_link_sent':verifiedLinkSent,
780
                        'onboarded':onboarded
15112 amit.gupta 781
                      }
782
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
783
        finally:
784
            session.close()
15096 amit.gupta 785
 
15112 amit.gupta 786
        if returned:
787
            resp.body = "{\"result\":\"success\"}"
788
        else:
789
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 790
 
15091 amit.gupta 791
    def invalidNumber(self,):
15108 manas 792
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
793
        if self.callDisposition == 'invalid_no':
794
            self.retailer.status='failed'
795
            self.callHistory.disposition_description = 'Invalid Number'
796
        elif self.callDisposition == 'wrong_no':
15111 manas 797
            self.retailer.status='failed'
798
            self.callHistory.disposition_description = 'Wrong Number'
799
        elif self.callDisposition == 'hang_up':
800
            self.retailer.status='failed'
801
            self.callHistory.disposition_description = 'Hang Up'
802
        elif self.callDisposition == 'retailer_not_interested':
803
            self.retailer.status='failed'
804
            if self.callHistory.disposition_description is None:
805
                self.callHistory.disposition_description = 'NA'
15200 manas 806
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
807
        elif self.callDisposition == 'recharge_retailer':
808
            self.retailer.status='failed'
809
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
810
        elif self.callDisposition == 'accessory_retailer':
811
            self.retailer.status='failed'
812
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
813
        elif self.callDisposition == 'service_center_retailer':
814
            self.retailer.status='failed'
815
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 816
        elif self.callDisposition == 'not_retailer':
817
            self.retailer.status='failed'
818
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 819
        session.commit()
820
        return True   
821
 
15132 amit.gupta 822
    def getCode(self,):
15207 amit.gupta 823
        newCode = None
824
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
825
        if lastLink is not None:
826
            if len(lastLink.code)==len(codesys):
827
                newCode=lastLink.code
828
        return getNextCode(codesys, newCode)
15108 manas 829
 
15254 amit.gupta 830
 
15091 amit.gupta 831
    def callLater(self,):
15368 amit.gupta 832
        self.retailer.status = RETRY_MAP.get(self.callType)
15100 amit.gupta 833
        self.retailer.call_priority = None
15096 amit.gupta 834
        if self.callDisposition == 'call_later':
15100 amit.gupta 835
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 836
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 837
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
838
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
839
            else:
15102 amit.gupta 840
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 841
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 842
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
843
        else: 
844
            if self.callDisposition == 'ringing_no_answer':
845
                if self.retailer.disposition == 'ringing_no_answer':
846
                    self.retailer.retry_count += 1
847
                else:
848
                    self.retailer.disposition = 'ringing_no_answer'
849
                    self.retailer.retry_count = 1
850
            else:
851
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 852
                    pass
15112 amit.gupta 853
                else:
15119 amit.gupta 854
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 855
                self.retailer.retry_count += 1
856
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 857
 
15122 amit.gupta 858
            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 859
            if retryConfig is not None:
860
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 861
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 862
            else:
863
                self.retailer.status = 'failed'
864
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 865
 
15101 amit.gupta 866
        session.commit()
867
        return True
15096 amit.gupta 868
 
15100 amit.gupta 869
 
15091 amit.gupta 870
    def alReadyUser(self,):
15112 amit.gupta 871
        self.retailer.status = self.callDisposition
15117 amit.gupta 872
        if self.callHistory.disposition_description is None:
873
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 874
        session.commit()
875
        return True
15091 amit.gupta 876
    def verifiedLinkSent(self,):
15147 amit.gupta 877
        if self.callType == 'fresh':
878
            self.retailer.status = 'followup'
16882 amit.gupta 879
            if self.retailer.agent_id not in sticky_agents:
880
                self.retailer.agent_id = None
15147 amit.gupta 881
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
882
            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') 
883
        else:
15224 amit.gupta 884
            self.retailer.status = 'followup'
16882 amit.gupta 885
            if self.retailer.agent_id not in sticky_agents:
886
                self.retailer.agent_id = None
15147 amit.gupta 887
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
15254 amit.gupta 888
            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')
15328 amit.gupta 889
        addContactToRetailer(self.agentId, self.retailerId, self.smsNumber, self.callType, 'sms')     
15146 amit.gupta 890
        session.commit()
891
        return True
15368 amit.gupta 892
    def onboarded(self,):
893
        self.retailer.status = self.callDisposition
894
        checkList = OnboardedRetailerChecklists()
895
        checkList.contact_us = self.checkList.get('contactus')
15390 amit.gupta 896
        checkList.doa_return_policy = self.checkList.get('doareturnpolicy')
15368 amit.gupta 897
        checkList.number_verification = self.checkList.get('numberverification')
898
        checkList.payment_option = self.checkList.get('paymentoption')
899
        checkList.preferences = self.checkList.get('preferences')
900
        checkList.product_info = self.checkList.get('productinfo')
15372 amit.gupta 901
        checkList.redeem = self.checkList.get('redeem')
15368 amit.gupta 902
        checkList.retailer_id = self.retailerId
903
        session.commit()
904
        return True
905
 
906
 
15254 amit.gupta 907
def isActivated(retailerId):
15276 amit.gupta 908
    retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailerId).first()
15448 amit.gupta 909
    user = session.query(Users).filter(or_(func.lower(Users.referrer)==retailerLink.code.lower(), Users.utm_campaign==retailerLink.code)).first()
15276 amit.gupta 910
    if user is None:
911
        mobileNumbers = list(session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailerId).all())
912
        user = session.query(Users).filter(Users.mobile_number.in_(mobileNumbers)).first()
15254 amit.gupta 913
        if user is None:
15332 amit.gupta 914
            if retailerLink.created < datetime(2015,5,26):
15333 amit.gupta 915
                historyNumbers = [number for number, in session.query(CallHistory.mobile_number).filter_by(retailer_id = retailerId).all()]
15476 amit.gupta 916
                user = session.query(Users).filter(Users.mobile_number.in_(historyNumbers)).first()
15332 amit.gupta 917
                if user is None:
918
                    return False
15334 amit.gupta 919
                else:
920
                    mapped_with = 'contact'
15332 amit.gupta 921
            else:
922
                return False
15276 amit.gupta 923
        else:
924
            mapped_with = 'contact'
925
    else:
926
        mapped_with = 'code'
927
    retailerLink.mapped_with = mapped_with
15388 amit.gupta 928
    if user.activation_time is not None:
15448 amit.gupta 929
        retailerLink.activated = user.activation_time
930
    retailerLink.activated = user.created
15276 amit.gupta 931
    retailerLink.user_id = user.id
15291 amit.gupta 932
    retailer = session.query(Retailers).filter_by(id=retailerId).first()
15574 amit.gupta 933
    if retailer.status == 'followup' or retailer.status == 'fretry':
15389 amit.gupta 934
        retailer.status = 'onboarding'
16882 amit.gupta 935
        if retailer.agent_id not in sticky_agents:
936
                retailer.agent_id = None
15391 amit.gupta 937
        retailer.call_priority = None
938
        retailer.next_call_time = None
939
        retailer.retry_count = 0
940
        retailer.invalid_retry_count = 0
15276 amit.gupta 941
    session.commit()
15287 amit.gupta 942
    print "retailerLink.retailer_id", retailerLink.retailer_id
15700 amit.gupta 943
    print "retailer", retailer.id
15276 amit.gupta 944
    session.close()
945
    return True
15254 amit.gupta 946
 
947
class AddContactToRetailer():
948
    def on_post(self,req,resp, agentId):
949
        agentId = int(agentId)
950
        try:
951
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
952
            retailerId = int(jsonReq.get("retailerid"))
953
            mobile = jsonReq.get("mobile")
954
            callType = jsonReq.get("calltype")
955
            contactType = jsonReq.get("contacttype")
956
            addContactToRetailer(agentId, retailerId, mobile, callType, contactType)
957
            session.commit()
958
        finally:
959
            session.close()
15676 amit.gupta 960
 
15677 amit.gupta 961
class AddAddressToRetailer():
15676 amit.gupta 962
    def on_post(self,req,resp, agentId):
963
        agentId = int(agentId)
15678 amit.gupta 964
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
965
        retailerId = int(jsonReq.get("retailerid"))
15684 amit.gupta 966
        address = str(jsonReq.get("address"))
967
        storeName = str(jsonReq.get("storename"))
968
        pin = str(jsonReq.get("pin"))
969
        city = str(jsonReq.get("city"))
970
        state = str(jsonReq.get("state"))
971
        updateType = str(jsonReq.get("updatetype"))
15678 amit.gupta 972
        addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType)
15254 amit.gupta 973
 
974
def addContactToRetailer(agentId, retailerId, mobile, callType, contactType):
15312 amit.gupta 975
    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=retailerId).filter_by(mobile_number=mobile).first()
976
    if retailerContact is None:
15254 amit.gupta 977
        retailerContact = RetailerContacts()
15256 amit.gupta 978
        retailerContact.retailer_id = retailerId
15254 amit.gupta 979
        retailerContact.agent_id = agentId
980
        retailerContact.call_type = callType
981
        retailerContact.contact_type = contactType
982
        retailerContact.mobile_number = mobile
15312 amit.gupta 983
    else:
15327 amit.gupta 984
        if CONTACT_PRIORITY.index(retailerContact.contact_type) > CONTACT_PRIORITY.index(contactType):
15358 amit.gupta 985
            retailerContact.contact_type = contactType
15676 amit.gupta 986
 
987
def addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType):
15679 amit.gupta 988
    print "I am in addAddress"
15682 amit.gupta 989
    print agentId, retailerId, address, storeName, pin, city, state, updateType
15679 amit.gupta 990
    try:
991
        if updateType=='new':
15685 amit.gupta 992
            retailer = session.query(Retailers).filter_by(id=retailerId).first()
15679 amit.gupta 993
            retailer.address = address
994
            retailer.title = storeName
995
            retailer.city = city
996
            retailer.state = state
997
            retailer.pin = pin
998
        raddress = RetailerAddresses()
999
        raddress.address = address
15682 amit.gupta 1000
        raddress.title = storeName
15679 amit.gupta 1001
        raddress.agent_id = agentId
1002
        raddress.city = city
1003
        raddress.pin = pin
1004
        raddress.retailer_id = retailerId
1005
        raddress.state = state
1006
        session.commit()
1007
    finally:
1008
        session.close() 
15254 amit.gupta 1009
 
15312 amit.gupta 1010
 
15189 manas 1011
class Login():
1012
 
1013
    def on_get(self, req, resp, agentId, role):
1014
        try:
15198 manas 1015
            self.agentId = int(agentId)
1016
            self.role = role
1017
            print str(self.agentId) + self.role;
15199 manas 1018
            agents=AgentLoginTimings()
1019
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
1020
            print 'lastLogintime' + str(lastLoginTime)
1021
            agents.loginTime=lastLoginTime.last_login
1022
            agents.logoutTime=datetime.now()
1023
            agents.role =self.role
15282 amit.gupta 1024
            agents.agent_id = self.agentId
15199 manas 1025
            session.add(agents)    
1026
            session.commit()
1027
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 1028
        finally:
1029
            session.close()        
15112 amit.gupta 1030
 
15189 manas 1031
    def on_post(self,req,resp):
1032
        try:
1033
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1034
            lgr.info( "Request ----\n"  + str(jsonReq))
1035
            email=jsonReq.get('email')
1036
            password = jsonReq.get('password')
1037
            role=jsonReq.get('role')    
15531 amit.gupta 1038
            agent = session.query(Agents).filter(and_(Agents.email==email,Agents.password==password)).first()
1039
            if agent is None:
15189 manas 1040
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
1041
            else:
15531 amit.gupta 1042
                print agent.id
1043
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==agent.id,Agent_Roles.role==role)).first()
15189 manas 1044
                if checkRole is None:
1045
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
1046
                else:
15531 amit.gupta 1047
                    agent.last_login = datetime.now()
1048
                    agent.login_type = role
1049
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":agent.id}}, encoding='utf-8')
1050
                    session.commit()
15195 manas 1051
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 1052
        finally:
1053
            session.close()    
1054
 
15195 manas 1055
    def test(self,email,password,role):
15189 manas 1056
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
1057
        if checkUser is None:
1058
            print checkUser
15195 manas 1059
 
15189 manas 1060
        else:
1061
            print checkUser[0]
1062
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
1063
            if checkRole is None:
15195 manas 1064
                pass
15189 manas 1065
            else:
15195 manas 1066
                agents=AgentLoginTimings()
1067
                agents.loginTime=datetime.now()
1068
                agents.logoutTime=datetime.now()
1069
                agents.role =role
1070
                agents.agent_id = 2
1071
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
1072
                session.add(agents)    
1073
                session.commit()
1074
                session.close()
1075
 
1076
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15275 amit.gupta 1077
 
1078
class RetailerActivation():
1079
    def on_get(self, req, resp, userId):
15351 amit.gupta 1080
        res =  markDealerActivation(int(userId))
1081
        if res:
1082
            resp.body = "{\"activated\":true}"
1083
        else:
1084
            resp.body = "{\"activated\":false}"
1085
 
15275 amit.gupta 1086
 
1087
def markDealerActivation(userId):
1088
    try:
15343 amit.gupta 1089
        user = session.query(Users).filter_by(id=userId).first()
15275 amit.gupta 1090
        result = False                
1091
        mappedWith = 'contact'
15534 amit.gupta 1092
        retailer = None
15275 amit.gupta 1093
        if user is not None:
15454 amit.gupta 1094
            referrer = None if user.referrer is None else user.referrer.upper()
1095
            retailerLink = session.query(RetailerLinks).filter(or_(RetailerLinks.code==referrer, RetailerLinks.code==user.utm_campaign)).first()
15275 amit.gupta 1096
            if retailerLink is None:
15501 amit.gupta 1097
                if user.mobile_number is not None:
1098
                    retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
1099
                    if retailerContact is None:
15613 amit.gupta 1100
                        retailer = session.query(Retailers).filter(Retailers.status.in_(['followup', 'fretry', 'fdone'])).filter(or_(Retailers.contact1==user.mobile_number,Retailers.contact2==user.mobile_number)).first()
15501 amit.gupta 1101
                    else:
1102
                        retailer = session.query(Retailers).filter_by(id = retailerContact.retailer_id).first()
15275 amit.gupta 1103
            else:
1104
                retailer = session.query(Retailers).filter_by(id = retailerLink.retailer_id).first()
1105
                mappedWith='code'
1106
            if retailer is not None:
1107
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailer.id).first()
1108
                if retailerLink is not None:
1109
                    retailerLink.user_id = user.id
1110
                    retailerLink.mapped_with=mappedWith
15358 amit.gupta 1111
                    retailer.status = 'onboarding'
15275 amit.gupta 1112
                    result = True
1113
                    session.commit()
15574 amit.gupta 1114
        return result
15275 amit.gupta 1115
    finally:
1116
        session.close()
1117
 
15189 manas 1118
 
15081 amit.gupta 1119
def todict(obj, classkey=None):
1120
    if isinstance(obj, dict):
1121
        data = {}
1122
        for (k, v) in obj.items():
1123
            data[k] = todict(v, classkey)
1124
        return data
1125
    elif hasattr(obj, "_ast"):
1126
        return todict(obj._ast())
1127
    elif hasattr(obj, "__iter__"):
1128
        return [todict(v, classkey) for v in obj]
1129
    elif hasattr(obj, "__dict__"):
1130
        data = dict([(key, todict(value, classkey)) 
1131
            for key, value in obj.__dict__.iteritems() 
1132
            if not callable(value) and not key.startswith('_')])
1133
        if classkey is not None and hasattr(obj, "__class__"):
1134
            data[classkey] = obj.__class__.__name__
1135
        return data
1136
    else:
1137
        return obj
1138
 
15358 amit.gupta 1139
def getRetailerObj(retailer, otherContacts1=None, callType=None):
15324 amit.gupta 1140
    print "before otherContacts1",otherContacts1
1141
    otherContacts = [] if otherContacts1 is None else otherContacts1
15662 amit.gupta 1142
    print "after otherContacts1",otherContacts
15081 amit.gupta 1143
    obj = Mock()
15280 amit.gupta 1144
    obj.id = retailer.id
15686 amit.gupta 1145
 
1146
 
15314 amit.gupta 1147
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts:
15315 amit.gupta 1148
        otherContacts.append(retailer.contact1)
15314 amit.gupta 1149
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts:
15315 amit.gupta 1150
        otherContacts.append(retailer.contact2)
15323 amit.gupta 1151
    obj.contact1 = None if len(otherContacts)==0 else otherContacts[0]
15325 amit.gupta 1152
    if obj.contact1 is not None:
1153
        obj.contact2 = None if len(otherContacts)==1 else otherContacts[1]
15096 amit.gupta 1154
    obj.scheduled = (retailer.call_priority is not None)
15686 amit.gupta 1155
    address = None
1156
    try:
1157
        address = session.query(RetailerAddresses).filter_by(retailer_id=retailer.id).order_by(RetailerAddresses.created.desc()).first()
1158
    finally:
1159
        session.close()
1160
    if address is not None:
1161
        obj.address = address.address
1162
        obj.title = address.title
1163
        obj.city = address.city
1164
        obj.state = address.state
1165
        obj.pin = address.pin 
1166
    else:
1167
        obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
1168
        obj.title = retailer.title
1169
        obj.city = retailer.city
1170
        obj.state = retailer.state
1171
        obj.pin = retailer.pin 
15699 amit.gupta 1172
    obj.status = retailer.status
15686 amit.gupta 1173
 
15662 amit.gupta 1174
    if hasattr(retailer, 'contact'):
1175
        obj.contact = retailer.contact
15358 amit.gupta 1176
    if callType == 'onboarding':
1177
        try:
15364 amit.gupta 1178
            userId, activatedTime = session.query(RetailerLinks.user_id, RetailerLinks.activated).filter(RetailerLinks.retailer_id==retailer.id).first()
15366 amit.gupta 1179
            activated, = session.query(Users.activation_time).filter(Users.id==userId).first()
15364 amit.gupta 1180
            if activated is not None:
15366 amit.gupta 1181
                activatedTime = activated
15362 amit.gupta 1182
            obj.user_id = userId
15364 amit.gupta 1183
            obj.created = datetime.strftime(activatedTime, '%d/%m/%Y %H:%M:%S')
15358 amit.gupta 1184
            result = fetchResult("select * from useractive where user_id=%d"%(userId))
1185
            if result == ():
1186
                obj.last_active = None
1187
            else:
15360 amit.gupta 1188
                obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
15361 amit.gupta 1189
            ordersCount = session.query(Orders).filter_by(user_id = userId).filter(~Orders.status.in_(['ORDER_NOT_CREATED_KNOWN', 'ORDER_ALREADY_CREATED_IGNORED'])).count()
15358 amit.gupta 1190
            obj.orders = ordersCount
1191
        finally:
1192
            session.close()
15081 amit.gupta 1193
    return obj
15091 amit.gupta 1194
 
15132 amit.gupta 1195
def make_tiny(code):
16939 manish.sha 1196
    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
16881 manas 1197
    #url='https://play.google.com/store/apps/details?id=com.saholic.profittill&referrer=utm_source=0&utm_medium=CRM&utm_term=001&utm_campaign='+code
16939 manish.sha 1198
    #marketUrl='market://details?id=com.saholic.profittill&referrer=utm_source=0&utm_medium=CRM&utm_term=001&utm_campaign='+code
1199
    #url = urllib.quote(marketUrl)
15465 amit.gupta 1200
    #request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1201
    #filehandle = urllib2.Request(request_url)
1202
    #x= urllib2.urlopen(filehandle)
15546 amit.gupta 1203
    try:
1204
        shortener = Shortener('TinyurlShortener')
1205
        returnUrl =  shortener.short(url)
1206
    except:
1207
        shortener = Shortener('SentalaShortener')
1208
        returnlUrl =  shortener.short(url)
1209
    return returnUrl
15171 amit.gupta 1210
 
15285 manas 1211
class SearchUser():
1212
 
1213
    def on_post(self, req, resp, agentId, searchType):
15314 amit.gupta 1214
        retailersJsonArray = []
15285 manas 1215
        try:
1216
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1217
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1218
            contact=jsonReq.get('searchTerm')
15285 manas 1219
            if(searchType=="number"):
15312 amit.gupta 1220
                retailer_ids = session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all()
1221
                retailer_ids = [r for r, in retailer_ids]    
1222
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact, Retailers.id.in_(retailer_ids))
1223
            else:
1224
                m = re.match("(.*?)(\d{6})(.*?)", contact)
1225
                if m is not None:
1226
                    pin = m.group(2)
1227
                    contact = m.group(1) if m.group(1) != '' else m.group(3)
15313 amit.gupta 1228
                    anotherCondition = and_(Retailers.title.ilike('%%%s%%'%(contact)), Retailers.pin==pin)
15312 amit.gupta 1229
                else:
1230
                    anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1231
 
15326 amit.gupta 1232
            retailers = session.query(Retailers).filter(anotherCondition).limit(20).all()
15312 amit.gupta 1233
            if retailers is None:
15285 manas 1234
                resp.body = json.dumps("{}")
15312 amit.gupta 1235
            else:
1236
                for retailer in retailers:
15326 amit.gupta 1237
                    otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
15314 amit.gupta 1238
                    retailersJsonArray.append(todict(getRetailerObj(retailer, otherContacts)))    
1239
            resp.body = json.dumps({"Retailers":retailersJsonArray}, encoding='utf-8')
15312 amit.gupta 1240
            return
15285 manas 1241
        finally:
1242
            session.close()
15171 amit.gupta 1243
 
15081 amit.gupta 1244
 
1245
class Mock(object):
1246
    pass
15189 manas 1247
 
15312 amit.gupta 1248
def tagActivatedReatilers():
15613 amit.gupta 1249
    retailerIds = [r for  r, in session.query(RetailerLinks.retailer_id).filter_by(user_id = None).all()]
15312 amit.gupta 1250
    session.close()
15288 amit.gupta 1251
    for retailerId in retailerIds:
1252
        isActivated(retailerId)
15312 amit.gupta 1253
    session.close()
15374 kshitij.so 1254
 
1255
class StaticDeals():
1256
 
1257
    def on_get(self, req, resp):
1258
 
1259
        offset = req.get_param_as_int("offset")
1260
        limit = req.get_param_as_int("limit")
1261
        categoryId = req.get_param_as_int("categoryId")
15458 kshitij.so 1262
        direction = req.get_param_as_int("direction")
15374 kshitij.so 1263
 
15458 kshitij.so 1264
        result = Mongo.getStaticDeals(offset, limit, categoryId, direction)
15374 kshitij.so 1265
        resp.body = dumps(result)
1266
 
16366 kshitij.so 1267
class DealNotification():
1268
 
1269
    def on_get(self,req,resp,skuBundleIds):
1270
        result = Mongo.getDealsForNotification(skuBundleIds)
1271
        resp.body = dumps(result)
16487 kshitij.so 1272
 
1273
class DealPoints():
1274
 
1275
    def on_get(self, req, resp):
16366 kshitij.so 1276
 
16487 kshitij.so 1277
        offset = req.get_param_as_int("offset")
1278
        limit = req.get_param_as_int("limit")
1279
 
1280
        result = Mongo.getAllBundlesWithDealPoints(offset, limit)
1281
        resp.body = dumps(result)
15374 kshitij.so 1282
 
16487 kshitij.so 1283
 
1284
    def on_post(self, req, resp):
1285
 
1286
 
1287
        try:
1288
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1289
        except ValueError:
1290
            raise falcon.HTTPError(falcon.HTTP_400,
1291
                'Malformed JSON',
1292
                'Could not decode the request body. The '
1293
                'JSON was incorrect.')
1294
 
1295
        result = Mongo.addDealPoints(result_json)
1296
        resp.body = json.dumps(result, encoding='utf-8')
15374 kshitij.so 1297
 
16545 kshitij.so 1298
class AppAffiliates():
1299
 
1300
    def on_get(self, req, resp, retailerId, appId):
1301
        retailerId = int(retailerId)
1302
        appId = int(appId)
16554 kshitij.so 1303
        call_back = req.get_param("callback")
16545 kshitij.so 1304
        result = Mongo.generateRedirectUrl(retailerId, appId)
16555 kshitij.so 1305
        resp.body = call_back+'('+str(result)+')'
16557 kshitij.so 1306
 
1307
class AffiliatePayout():
1308
    def on_get(self, req, resp):
1309
        payout = req.get_param("payout")
1310
        transaction_id = req.get_param("transaction_id")
1311
        result = Mongo.addPayout(payout, transaction_id)
1312
        resp.body = str(result)
1313
 
16581 manish.sha 1314
class AppOffers():
1315
    def on_get(self, req, resp, retailerId):
16895 manish.sha 1316
        try:            
1317
            result = Mongo.getAppOffers(retailerId)
1318
            offerids = result.values()
1319
            if offerids is None or len(offerids)==0:
16887 kshitij.so 1320
                resp.body = json.dumps("{}")
1321
            else:
16941 manish.sha 1322
                appOffers = session.query(app_offers.id,app_offers.appmaster_id, app_offers.app_name, app_offers.affiliate_offer_id, app_offers.image_url, app_offers.downloads, app_offers.link, app_offers.offer_price, app_offers.offerCategory, app_offers.package_name, app_offers.promoImage, app_offers.ratings, case([(app_offers.override_payout == True, app_offers.overriden_payout)], else_=app_offers.user_payout).label('user_payout'), case([(appmasters.shortDescription != None, appmasters.shortDescription)], else_=None).label('shortDescription'), case([(appmasters.longDescription != None, appmasters.longDescription)], else_=None).label('longDescription'), appmasters.customerOneLiner, appmasters.retailerOneLiner,appmasters.rank, app_offers.offerCondition, app_offers.location).join((appmasters,appmasters.id==app_offers.appmaster_id)).filter(app_offers.id.in_(tuple(offerids))).all()
16895 manish.sha 1323
                appOffersMap = {}
1324
                jsonOffersArray=[]
1325
                for offer in appOffers:
1326
                    appOffersMap[long(offer[0])]= AppOfferObj(offer[0], offer[1], offer[2], offer[3], offer[4], offer[5], offer[6], offer[7], offer[8], offer[9], offer[10], offer[11], offer[12], offer[13], offer[14], offer[15], offer[16], offer[17], offer[18], offer[19]).__dict__
1327
                for rank in sorted(result):
1328
                    print 'Rank', rank, 'Data', appOffersMap[result[rank]]
1329
                    jsonOffersArray.append(appOffersMap[result[rank]])
1330
 
1331
            resp.body = json.dumps({"AppOffers":jsonOffersArray}, encoding='latin1')
16887 kshitij.so 1332
        finally:
1333
            session.close()
1334
 
16727 manish.sha 1335
 
1336
class AppUserBatchRefund():
1337
    def on_get(self, req, resp, batchId, userId):
16887 kshitij.so 1338
        try:
1339
            batchId = long(batchId)
1340
            userId = long(userId)
1341
            userBatchCashback = user_app_cashbacks.get_by(user_id=userId, batchCreditId=batchId)
1342
            if userBatchCashback is None:
1343
                resp.body = json.dumps("{}")
1344
            else:
16905 manish.sha 1345
                if userBatchCashback.creditedDate is not None:
1346
                    userBatchCashback.creditedDate = str(userBatchCashback.creditedDate)
16887 kshitij.so 1347
                resp.body = json.dumps(todict(userBatchCashback), encoding='utf-8')
1348
        finally:
1349
            session.close()
16727 manish.sha 1350
 
1351
class AppUserBatchDrillDown():
16777 manish.sha 1352
    def on_get(self, req, resp, fortNightOfYear, userId, yearVal):
16887 kshitij.so 1353
        try:
1354
            fortNightOfYear = long(fortNightOfYear)
1355
            userId = long(userId)
1356
            yearVal = long(yearVal)
1357
            appUserBatchDrillDown = session.query(user_app_installs.transaction_date, func.sum(user_app_installs.installCount).label('downloads'), func.sum(user_app_installs.payoutAmount).label('amount')).join((user_app_cashbacks,user_app_cashbacks.user_id==user_app_installs.user_id)).filter(user_app_cashbacks.fortnightOfYear==user_app_installs.fortnightOfYear).filter(user_app_cashbacks.user_id==userId).filter(user_app_cashbacks.yearVal==yearVal).filter(user_app_cashbacks.fortnightOfYear==fortNightOfYear).group_by(user_app_installs.transaction_date).all()
1358
            cashbackArray = []
1359
            if appUserBatchDrillDown is None or len(appUserBatchDrillDown)==0:
1360
                resp.body = json.dumps("{}")
1361
            else:
1362
                for appcashBack in appUserBatchDrillDown:
1363
                    userAppBatchDrillDown = UserAppBatchDrillDown(str(appcashBack[0]),long(appcashBack[1]), long(appcashBack[2]))
1364
                    cashbackArray.append(todict(userAppBatchDrillDown))
1365
                resp.body = json.dumps({"UserAppCashBackInBatch":cashbackArray}, encoding='utf-8')
1366
        finally:
1367
            session.close()
16727 manish.sha 1368
 
1369
class AppUserBatchDateDrillDown():
1370
    def on_get(self, req, resp, userId, date):
16887 kshitij.so 1371
        try:
1372
            userId = long(userId)
1373
            date = str(date)
1374
            date = datetime.strptime(date, '%Y-%m-%d')
1375
            appUserBatchDateDrillDown = session.query(user_app_installs.app_name, func.sum(user_app_installs.installCount).label('downloads'), func.sum(user_app_installs.payoutAmount).label('amount')).filter(user_app_installs.user_id==userId).filter(user_app_installs.transaction_date==date).group_by(user_app_installs.app_name).all()
1376
            cashbackArray = []
1377
            if appUserBatchDateDrillDown is None or len(appUserBatchDateDrillDown)==0:
1378
                resp.body = json.dumps("{}")
1379
            else:
1380
                for appcashBack in appUserBatchDateDrillDown:
1381
                    userAppBatchDateDrillDown = UserAppBatchDateDrillDown(str(appcashBack[0]),long(appcashBack[1]),long(appcashBack[2]))
1382
                    cashbackArray.append(todict(userAppBatchDateDrillDown))
1383
                resp.body = json.dumps({"UserAppCashBackDateWise":cashbackArray}, encoding='utf-8')
1384
        finally:
1385
            session.close()
16739 manish.sha 1386
 
16748 manish.sha 1387
class AppUserCashBack():
1388
    def on_get(self, req, resp, userId, status):
16887 kshitij.so 1389
        try:
1390
            userId = long(userId)
1391
            status = str(status)
1392
            appUserApprovedCashBacks = user_app_cashbacks.query.filter(user_app_cashbacks.user_id==userId).filter(user_app_cashbacks.status==status).all()
1393
            cashbackArray = []
1394
            if appUserApprovedCashBacks is None or len(appUserApprovedCashBacks)==0:
1395
                resp.body = json.dumps("{}")
1396
            else:
1397
                totalAmount = 0                
1398
                for appUserApprovedCashBack in appUserApprovedCashBacks:
1399
                    totalAmount = totalAmount + appUserApprovedCashBack.amount
16895 manish.sha 1400
                    if appUserApprovedCashBack.creditedDate is not None:
1401
                        appUserApprovedCashBack.creditedDate = str(appUserApprovedCashBack.creditedDate)  
16905 manish.sha 1402
                    cashbackArray.append(todict(appUserApprovedCashBack)) 
1403
 
16887 kshitij.so 1404
                resp.body = json.dumps({"UserAppCashBack":cashbackArray,"TotalAmount":totalAmount}, encoding='utf-8')
1405
        finally:
1406
            session.close()
17278 naman 1407
 
1408
class GetSaleDetail():
1409
    def on_get(self,req,res,date_val):
1410
        try:
1411
                db = get_mongo_connection()
1412
                sum=0
1413
                count=0
1414
                #print date_val, type(date_val)
1415
                #cursor = db.Dtr.merchantOrder.find({'createdOnInt':{'$lt':long(date_val)},'subOrders':{'$exists':True}})
17315 naman 1416
                cursor = db.Dtr.merchantOrder.find({"$and": [ { "createdOnInt":{"$gt":long(date_val)} }, {"createdOnInt":{"$lt":long(date_val)+86401} } ],"subOrders":{"$exists":True}})
17278 naman 1417
 
1418
                for document in cursor:
1419
                    for doc in document['subOrders']:
1420
                        sum = sum + float(doc['amountPaid'])
1421
                        count = count + int(doc['quantity'])
1422
 
1423
                data = {"amount":sum , "quantity":count}
1424
 
1425
                res.body= json.dumps(data,encoding='utf-8')
1426
        finally:
1427
                session.close()
1428
 
17301 kshitij.so 1429
class DummyDeals():
17304 kshitij.so 1430
    def on_get(self,req, resp):
17301 kshitij.so 1431
        categoryId = req.get_param_as_int("categoryId")
1432
        offset = req.get_param_as_int("offset")
1433
        limit = req.get_param_as_int("limit")
1434
        result = Mongo.getDummyDeals(categoryId, offset, limit)
17556 kshitij.so 1435
        resp.body = dumps(result)
17301 kshitij.so 1436
 
17467 manas 1437
class PincodeValidation():
17498 amit.gupta 1438
    def on_get(self,req,resp,pincode):
17467 manas 1439
        json_data={}
1440
        cities=[]
1441
        print pincode
1442
        if len(str(pincode)) ==6:
17499 amit.gupta 1443
            listCities = list(session.query(Postoffices.taluk,Postoffices.state).distinct().filter(Postoffices.pincode==pincode).filter(Postoffices.taluk!='NA').all())
17467 manas 1444
            if len(listCities)>0:
1445
                for j in listCities:
1446
                    cities.append(j.taluk)
1447
                json_data['cities'] = cities
1448
                json_data['state'] = listCities[0][1]
1449
                resp.body =  json.dumps(json_data)
1450
            else:
1451
                resp.body = json.dumps("{}")       
1452
        else:
1453
            resp.body = json.dumps("{}")
1454
        session.close()
17301 kshitij.so 1455
 
17556 kshitij.so 1456
class SearchDummyDeals():
1457
    def on_get(self,req,resp):
1458
        offset = req.get_param_as_int("offset")
1459
        limit = req.get_param_as_int("limit")
1460
        searchTerm = req.get_param("searchTerm")
1461
        result = Mongo.searchDummyDeals(searchTerm, limit, offset)
1462
        resp.body = dumps(result)
1463
 
1464
class DummyPricing:
17560 kshitij.so 1465
    def on_get(self, req, resp):
17556 kshitij.so 1466
        skuBundleId = req.get_param_as_int("skuBundleId")
1467
        result = Mongo.getDummyPricing(skuBundleId)
1468
        resp.body = dumps(result)
1469
 
1470
class DealObject:
17560 kshitij.so 1471
    def on_post(self, req, resp):
17569 kshitij.so 1472
        update = req.get_param_as_int("update")
17556 kshitij.so 1473
        try:
1474
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1475
        except ValueError:
1476
            raise falcon.HTTPError(falcon.HTTP_400,
1477
                'Malformed JSON',
1478
                'Could not decode the request body. The '
1479
                'JSON was incorrect.')
17569 kshitij.so 1480
        if update is None:    
1481
            result = Mongo.addDealObject(result_json)
1482
        else:
1483
            result = Mongo.updateDealObject(result_json)
1484
 
17556 kshitij.so 1485
        resp.body = dumps(result)
17569 kshitij.so 1486
 
17556 kshitij.so 1487
 
17560 kshitij.so 1488
    def on_get(self, req, resp):
17567 kshitij.so 1489
        edit = req.get_param_as_int("edit")
1490
        if edit is None:
1491
            offset = req.get_param_as_int("offset")
1492
            limit = req.get_param_as_int("limit")
17560 kshitij.so 1493
 
17567 kshitij.so 1494
            result = Mongo.getAllDealObjects(offset, limit)
1495
            resp.body = dumps(result)
1496
        else:
1497
            id = req.get_param_as_int("id")
1498
            result = Mongo.getDealObjectById(id)
1499
            resp.body = dumps(result)
17560 kshitij.so 1500
 
17563 kshitij.so 1501
class DeleteDealObject:
1502
    def on_get(self, req, resp, id):
1503
        result = Mongo.deleteDealObject(int(id))
1504
        resp.body = dumps(result)
1505
 
17611 kshitij.so 1506
class FeaturedDealObject:
1507
    def on_get(self, req, resp):
1508
 
1509
        offset = req.get_param_as_int("offset")
1510
        limit = req.get_param_as_int("limit")
1511
 
1512
        result = Mongo.getAllFeaturedDealsForDealObject(offset, limit)
1513
        resp.body = dumps(result)
1514
 
17556 kshitij.so 1515
 
17611 kshitij.so 1516
    def on_post(self, req, resp):
1517
 
1518
 
1519
        try:
1520
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1521
        except ValueError:
1522
            raise falcon.HTTPError(falcon.HTTP_400,
1523
                'Malformed JSON',
1524
                'Could not decode the request body. The '
1525
                'JSON was incorrect.')
1526
 
17613 kshitij.so 1527
        result = Mongo.addFeaturedDealForDealObject(result_json)
17611 kshitij.so 1528
        resp.body = json.dumps(result, encoding='utf-8')
1529
 
1530
 
17556 kshitij.so 1531
 
17560 kshitij.so 1532
 
17611 kshitij.so 1533
 
15312 amit.gupta 1534
def main():
15662 amit.gupta 1535
    #tagActivatedReatilers()
1536
    a = RetailerDetail()
1537
    retailer = a.getNotActiveRetailer()
1538
    otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
1539
    print json.dumps(todict(getRetailerObj(retailer, otherContacts, 'fresh')), encoding='utf-8')
15465 amit.gupta 1540
    #print make_tiny("AA")
15195 manas 1541
 
15081 amit.gupta 1542
if __name__ == '__main__':
15207 amit.gupta 1543
    main()
15091 amit.gupta 1544