Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
18272 kshitij.so 1
from bson import json_util
15081 amit.gupta 2
from bson.json_util import dumps
19666 amit.gupta 3
from datetime import datetime, timedelta, date
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,\
19666 amit.gupta 12
    Postoffices, UserCrmCallingData, CallHistoryCrm, ProductPricingInputs,\
19761 manas 13
    tinxys_stats, profitmandi_sms
15358 amit.gupta 14
from dtr.storage.Mongo import get_mongo_connection
15
from dtr.storage.Mysql import fetchResult
19651 manas 16
from dtr.utils import DealSheet as X_DealSheet, \
17
    UserSpecificDeals, utils, ThriftUtils
18256 manas 18
from dtr.utils.utils import getLogger,encryptMessage,decryptMessage,\
19
    get_mongo_connection_dtr_data, to_java_date
15081 amit.gupta 20
from elixir import *
15254 amit.gupta 21
from operator import and_
16714 manish.sha 22
from sqlalchemy.sql.expression import func, func, or_, desc, asc, case
15132 amit.gupta 23
from urllib import urlencode
24
import contextlib
13827 kshitij.so 25
import falcon
15081 amit.gupta 26
import json
15358 amit.gupta 27
import re
15254 amit.gupta 28
import string
15081 amit.gupta 29
import traceback
15132 amit.gupta 30
import urllib
31
import urllib2
32
import uuid
15465 amit.gupta 33
import gdshortener
16727 manish.sha 34
from dtr.dao import AppOfferObj, UserAppBatchDrillDown, UserAppBatchDateDrillDown
18097 manas 35
import base64
18272 kshitij.so 36
from falcon.util.uri import decode
18266 manas 37
import MySQLdb
18792 manas 38
from shop2020.clients.CatalogClient import CatalogClient  
18896 amit.gupta 39
from pyquery import PyQuery as pq
19463 manas 40
import time
19475 manas 41
from dtr.main import refundToWallet
19732 manas 42
import random
20170 kshitij.so 43
from dtr.utils.AutoSuggest import getSuggestions
15207 amit.gupta 44
alphalist = list(string.uppercase)
45
alphalist.remove('O')
19850 manas 46
alphalist.remove('I')
47
alphalist.remove('L')
48
numList = ['2','3','4','5','6','7','8','9']
15207 amit.gupta 49
codesys = [alphalist, alphalist, numList, numList, numList]
19732 manas 50
newcodesys = alphalist + numList
15312 amit.gupta 51
CONTACT_PRIORITY = ['sms', 'called', 'ringing']
15368 amit.gupta 52
RETRY_MAP = {'fresh':'retry', 'followup':'fretry', 'onboarding':'oretry'}
15358 amit.gupta 53
ASSIGN_MAP = {'retry':'assigned', 'fretry':'fassigned', 'oretry':'oassigned'}
20133 rajender 54
CRM_PROJECTS_USER_AVAILABILITY = {1:{'cooldown':30, 'isrepeat':True}, 2:{'cooldown':15,'isrepeat': False}, 3:{'cooldown':2,'isrepeat': True}, 5:{'cooldown':15,'isrepeat': True}}
15207 amit.gupta 55
 
20082 rajender 56
sticky_agents = [17,29]
16882 amit.gupta 57
 
19732 manas 58
def getNextRandomCode(newcodesys,size=6):
59
    return ''.join(random.choice(newcodesys) for _ in range(size))
15207 amit.gupta 60
def getNextCode(codesys, code=None):
61
    if code is None:
62
        code = []
63
        for charcode in codesys:
64
            code.append(charcode[0])
65
        return string.join(code, '')
66
    carry = True
67
    code = list(code)
68
    lastindex = len(codesys) - 1
69
    while carry:
70
        listChar = codesys[lastindex]
71
        newIndex = (listChar.index(code[lastindex])+1)%len(listChar)
72
        print newIndex
73
        code[lastindex] = listChar[newIndex]
74
        if newIndex != 0:
75
            carry = False
76
        lastindex -= 1
77
        if lastindex ==-1:
78
            raise BaseException("All codes are exhausted")
79
 
80
    return string.join(code, '')
81
 
18397 manas 82
 
15081 amit.gupta 83
global RETAILER_DETAIL_CALL_COUNTER
84
RETAILER_DETAIL_CALL_COUNTER = 0
18329 manas 85
global USER_DETAIL_MAP
18332 manas 86
USER_DETAIL_MAP={} 
18329 manas 87
USER_DETAIL_MAP['accs_cart']=0
88
USER_DETAIL_MAP['accs_active']=0
89
USER_DETAIL_MAP['accs_order']=0
19442 manas 90
USER_DETAIL_MAP['accs_cashback_scheme']=0
20133 rajender 91
# change 1
92
USER_DETAIL_MAP['inactive_users']=0
15168 amit.gupta 93
lgr = getLogger('/var/log/retailer-acquisition-api.log')
15081 amit.gupta 94
DEALER_RETRY_FACTOR = int(PythonPropertyReader.getConfig('DEALER_RETRY_FACTOR'))
16886 amit.gupta 95
DEALER_FRESH_FACTOR = int(PythonPropertyReader.getConfig('DEALER_FRESH_FACTOR'))
18329 manas 96
USER_CRM_DEFAULT_RETRY_FACTOR = int(PythonPropertyReader.getConfig('USER_CRM_DEFAULT_RETRY_FACTOR'))
97
USER_CRM_DEFAULT_FRESH_FACTOR = int(PythonPropertyReader.getConfig('USER_CRM_DEFAULT_FRESH_FACTOR'))
98
TOTAL = DEALER_RETRY_FACTOR + DEALER_FRESH_FACTOR
19761 manas 99
TOTAL_USER = USER_CRM_DEFAULT_FRESH_FACTOR + USER_CRM_DEFAULT_RETRY_FACTOR
100
TRANSACTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/SMSGateway/sendingSMS?"
19764 manas 101
 
13572 kshitij.so 102
class CategoryDiscountInfo(object):
103
 
104
    def on_get(self, req, resp):
105
 
13629 kshitij.so 106
        result = Mongo.getAllCategoryDiscount()
107
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
108
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 109
 
110
    def on_post(self, req, resp):
111
        try:
112
            result_json = json.loads(req.stream.read(), encoding='utf-8')
113
        except ValueError:
114
            raise falcon.HTTPError(falcon.HTTP_400,
115
                'Malformed JSON',
116
                'Could not decode the request body. The '
117
                'JSON was incorrect.')
118
 
119
        result = Mongo.addCategoryDiscount(result_json)
120
        resp.body = json.dumps(result, encoding='utf-8')
13969 kshitij.so 121
 
122
    def on_put(self, req, resp, _id):
13970 kshitij.so 123
        try:
124
            result_json = json.loads(req.stream.read(), encoding='utf-8')
125
        except ValueError:
126
            raise falcon.HTTPError(falcon.HTTP_400,
127
                'Malformed JSON',
128
                'Could not decode the request body. The '
129
                'JSON was incorrect.')
130
 
131
        result = Mongo.updateCategoryDiscount(result_json, _id)
132
        resp.body = json.dumps(result, encoding='utf-8')
133
 
13966 kshitij.so 134
 
13969 kshitij.so 135
 
13572 kshitij.so 136
class SkuSchemeDetails(object):
137
 
138
    def on_get(self, req, resp):
13629 kshitij.so 139
 
14070 kshitij.so 140
        offset = req.get_param_as_int("offset")
141
        limit = req.get_param_as_int("limit")
142
 
143
        result = Mongo.getAllSkuWiseSchemeDetails(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.addSchemeDetailsForSku(result_json)
13572 kshitij.so 161
        resp.body = json.dumps(result, encoding='utf-8')
162
 
163
class SkuDiscountInfo():
164
 
165
    def on_get(self, req, resp):
13629 kshitij.so 166
 
13970 kshitij.so 167
        offset = req.get_param_as_int("offset")
168
        limit = req.get_param_as_int("limit")
169
        result = Mongo.getallSkuDiscountInfo(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
 
174
    def on_post(self, req, resp):
175
 
14552 kshitij.so 176
        multi = req.get_param_as_int("multi")
177
 
13572 kshitij.so 178
        try:
179
            result_json = json.loads(req.stream.read(), encoding='utf-8')
180
        except ValueError:
181
            raise falcon.HTTPError(falcon.HTTP_400,
182
                'Malformed JSON',
183
                'Could not decode the request body. The '
184
                'JSON was incorrect.')
185
 
15852 kshitij.so 186
        result = Mongo.addSkuDiscountInfo(result_json)
13572 kshitij.so 187
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 188
 
189
    def on_put(self, req, resp, _id):
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
 
198
        result = Mongo.updateSkuDiscount(result_json, _id)
199
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 200
 
201
class ExceptionalNlc():
202
 
203
    def on_get(self, req, resp):
13629 kshitij.so 204
 
13970 kshitij.so 205
        offset = req.get_param_as_int("offset")
206
        limit = req.get_param_as_int("limit")
207
 
208
        result = Mongo.getAllExceptionlNlcItems(offset, limit)
13629 kshitij.so 209
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
210
        resp.body = json.dumps(json_docs, encoding='utf-8')
13572 kshitij.so 211
 
212
    def on_post(self, req, resp):
213
 
14552 kshitij.so 214
        multi = req.get_param_as_int("multi")
215
 
13572 kshitij.so 216
        try:
217
            result_json = json.loads(req.stream.read(), encoding='utf-8')
218
        except ValueError:
219
            raise falcon.HTTPError(falcon.HTTP_400,
220
                'Malformed JSON',
221
                'Could not decode the request body. The '
222
                'JSON was incorrect.')
223
 
15852 kshitij.so 224
        result = Mongo.addExceptionalNlc(result_json)
13572 kshitij.so 225
        resp.body = json.dumps(result, encoding='utf-8')
13970 kshitij.so 226
 
227
    def on_put(self, req, resp, _id):
228
        try:
229
            result_json = json.loads(req.stream.read(), encoding='utf-8')
230
        except ValueError:
231
            raise falcon.HTTPError(falcon.HTTP_400,
232
                'Malformed JSON',
233
                'Could not decode the request body. The '
234
                'JSON was incorrect.')
235
 
236
        result = Mongo.updateExceptionalNlc(result_json, _id)
237
        resp.body = json.dumps(result, encoding='utf-8')
13572 kshitij.so 238
 
13772 kshitij.so 239
class Deals():
13779 kshitij.so 240
    def on_get(self,req, resp, userId):
241
        categoryId = req.get_param_as_int("categoryId")
242
        offset = req.get_param_as_int("offset")
243
        limit = req.get_param_as_int("limit")
13798 kshitij.so 244
        sort = req.get_param("sort")
13802 kshitij.so 245
        direction = req.get_param_as_int("direction")
14853 kshitij.so 246
        filterData = req.get_param('filterData')
19558 kshitij.so 247
        if categoryId!=6:
248
            result = Mongo.getNewDeals(int(userId), categoryId, offset, limit, sort, direction, filterData)
249
        else:
250
            result = Mongo.getAccesoryDeals(int(userId), categoryId, offset, limit, sort, direction, filterData)
16078 kshitij.so 251
        resp.body = dumps(result) 
19440 kshitij.so 252
 
13790 kshitij.so 253
class MasterData():
254
    def on_get(self,req, resp, skuId):
16223 kshitij.so 255
        showDp = req.get_param_as_int("showDp")
16221 kshitij.so 256
        result = Mongo.getItem(skuId, showDp)
13798 kshitij.so 257
        try:
258
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 259
            resp.body = json.dumps(json_docs, encoding='utf-8')
13798 kshitij.so 260
        except:
261
            json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
13966 kshitij.so 262
            resp.body = json.dumps(json_docs, encoding='utf-8')
13790 kshitij.so 263
 
14586 kshitij.so 264
    def on_post(self,req, resp):
265
 
266
        addNew = req.get_param_as_int("addNew")
267
        update = req.get_param_as_int("update")
268
        addToExisting = req.get_param_as_int("addToExisting")
269
        multi = req.get_param_as_int("multi")
270
 
14589 kshitij.so 271
        try:
14592 kshitij.so 272
            result_json = json.loads(req.stream.read(), encoding='utf-8')
273
        except ValueError:
274
            raise falcon.HTTPError(falcon.HTTP_400,
275
                'Malformed JSON',
276
                'Could not decode the request body. The '
277
                'JSON was incorrect.')
278
 
279
        if addNew == 1:
280
            result = Mongo.addNewItem(result_json)
281
        elif update == 1:
282
            result = Mongo.updateMaster(result_json, multi)
283
        elif addToExisting == 1:
284
            result = Mongo.addItemToExistingBundle(result_json)
285
        else:
286
            raise
287
        resp.body = dumps(result)
13865 kshitij.so 288
 
13834 kshitij.so 289
class CashBack():
290
    def on_get(self,req, resp):
291
        identifier = req.get_param("identifier")
292
        source_id = req.get_param_as_int("source_id")
293
        try:
13838 kshitij.so 294
            result = Mongo.getCashBackDetails(identifier, source_id)
13837 kshitij.so 295
            json_docs = json.dumps(result, default=json_util.default)
13964 kshitij.so 296
            resp.body = json_docs
13834 kshitij.so 297
        except:
13837 kshitij.so 298
            json_docs = json.dumps({}, default=json_util.default)
13963 kshitij.so 299
            resp.body = json_docs
13892 kshitij.so 300
 
14398 amit.gupta 301
class ImgSrc():
302
    def on_get(self,req, resp):
303
        identifier = req.get_param("identifier")
304
        source_id = req.get_param_as_int("source_id")
305
        try:
306
            result = Mongo.getImgSrc(identifier, source_id)
307
            json_docs = json.dumps(result, default=json_util.default)
308
            resp.body = json_docs
309
        except:
310
            json_docs = json.dumps({}, default=json_util.default)
311
            resp.body = json_docs
312
 
13892 kshitij.so 313
class DealSheet():
314
    def on_get(self,req, resp):
13895 kshitij.so 315
        X_DealSheet.sendMail()
13897 kshitij.so 316
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
13966 kshitij.so 317
        resp.body = json.dumps(json_docs, encoding='utf-8')
13892 kshitij.so 318
 
13970 kshitij.so 319
class DealerPrice():
320
 
321
    def on_get(self, req, resp):
322
 
323
        offset = req.get_param_as_int("offset")
324
        limit = req.get_param_as_int("limit")
325
        result = Mongo.getAllDealerPrices(offset,limit)
326
        json_docs = [json.dumps(doc, default=json_util.default) for doc in result]
327
        resp.body = json.dumps(json_docs, encoding='utf-8')
328
 
329
    def on_post(self, req, resp):
330
 
14552 kshitij.so 331
        multi = req.get_param_as_int("multi")
332
 
13970 kshitij.so 333
        try:
334
            result_json = json.loads(req.stream.read(), encoding='utf-8')
335
        except ValueError:
336
            raise falcon.HTTPError(falcon.HTTP_400,
337
                'Malformed JSON',
338
                'Could not decode the request body. The '
339
                'JSON was incorrect.')
340
 
15852 kshitij.so 341
        result = Mongo.addSkuDealerPrice(result_json)
13970 kshitij.so 342
        resp.body = json.dumps(result, encoding='utf-8')
343
 
344
    def on_put(self, req, resp, _id):
345
        try:
346
            result_json = json.loads(req.stream.read(), encoding='utf-8')
347
        except ValueError:
348
            raise falcon.HTTPError(falcon.HTTP_400,
349
                'Malformed JSON',
350
                'Could not decode the request body. The '
351
                'JSON was incorrect.')
352
 
353
        result = Mongo.updateSkuDealerPrice(result_json, _id)
354
        resp.body = json.dumps(result, encoding='utf-8')
355
 
356
 
14041 kshitij.so 357
class ResetCache():
358
 
20441 kshitij.so 359
    def on_get(self,req, resp):
360
        cache_type = req.get_param("type")
361
        users = req.get_param("users")
362
        result = Mongo.resetCache(cache_type, users)
14046 kshitij.so 363
        resp.body = json.dumps(result, encoding='utf-8')
364
 
365
class UserDeals():
366
    def on_get(self,req,resp,userId):
367
        UserSpecificDeals.generateSheet(userId)
368
        json_docs = json.dumps({'True':'Sheet generated, mail sent.'}, default=json_util.default)
369
        resp.body = json.dumps(json_docs, encoding='utf-8')
14075 kshitij.so 370
 
371
class CommonUpdate():
372
 
373
    def on_post(self,req,resp):
14575 kshitij.so 374
 
375
        multi = req.get_param_as_int("multi")
376
 
14075 kshitij.so 377
        try:
378
            result_json = json.loads(req.stream.read(), encoding='utf-8')
379
        except ValueError:
380
            raise falcon.HTTPError(falcon.HTTP_400,
381
                'Malformed JSON',
382
                'Could not decode the request body. The '
383
                'JSON was incorrect.')
384
 
15852 kshitij.so 385
        result = Mongo.updateCollection(result_json)
14075 kshitij.so 386
        resp.body = json.dumps(result, encoding='utf-8')
14106 kshitij.so 387
        resp.content_type = "application/json; charset=utf-8"
14481 kshitij.so 388
 
389
class NegativeDeals():
390
 
391
    def on_get(self, req, resp):
392
 
393
        offset = req.get_param_as_int("offset")
394
        limit = req.get_param_as_int("limit")
395
 
396
        result = Mongo.getAllNegativeDeals(offset, limit)
14483 kshitij.so 397
        resp.body = dumps(result) 
14481 kshitij.so 398
 
399
 
400
    def on_post(self, req, resp):
401
 
14552 kshitij.so 402
        multi = req.get_param_as_int("multi")
403
 
14481 kshitij.so 404
        try:
405
            result_json = json.loads(req.stream.read(), encoding='utf-8')
406
        except ValueError:
407
            raise falcon.HTTPError(falcon.HTTP_400,
408
                'Malformed JSON',
409
                'Could not decode the request body. The '
410
                'JSON was incorrect.')
411
 
14552 kshitij.so 412
        result = Mongo.addNegativeDeals(result_json, multi)
14481 kshitij.so 413
        resp.body = json.dumps(result, encoding='utf-8')
414
 
415
class ManualDeals():
416
 
417
    def on_get(self, req, resp):
418
 
419
        offset = req.get_param_as_int("offset")
420
        limit = req.get_param_as_int("limit")
421
 
422
        result = Mongo.getAllManualDeals(offset, limit)
14483 kshitij.so 423
        resp.body = dumps(result)
14481 kshitij.so 424
 
425
 
426
    def on_post(self, req, resp):
427
 
14552 kshitij.so 428
        multi = req.get_param_as_int("multi")
429
 
14481 kshitij.so 430
        try:
431
            result_json = json.loads(req.stream.read(), encoding='utf-8')
432
        except ValueError:
433
            raise falcon.HTTPError(falcon.HTTP_400,
434
                'Malformed JSON',
435
                'Could not decode the request body. The '
436
                'JSON was incorrect.')
437
 
14552 kshitij.so 438
        result = Mongo.addManualDeal(result_json, multi)
14481 kshitij.so 439
        resp.body = json.dumps(result, encoding='utf-8')
440
 
441
class CommonDelete():
14482 kshitij.so 442
 
14481 kshitij.so 443
    def on_post(self,req,resp):
444
        try:
445
            result_json = json.loads(req.stream.read(), encoding='utf-8')
446
        except ValueError:
447
            raise falcon.HTTPError(falcon.HTTP_400,
448
                'Malformed JSON',
449
                'Could not decode the request body. The '
450
                'JSON was incorrect.')
451
 
452
        result = Mongo.deleteDocument(result_json)
453
        resp.body = json.dumps(result, encoding='utf-8')
454
        resp.content_type = "application/json; charset=utf-8"
14482 kshitij.so 455
 
456
class SearchProduct():
457
 
458
    def on_get(self,req,resp):
459
        offset = req.get_param_as_int("offset")
460
        limit = req.get_param_as_int("limit")
461
        search_term = req.get_param("search")
462
 
463
        result = Mongo.searchMaster(offset, limit, search_term)
14483 kshitij.so 464
        resp.body = dumps(result) 
14482 kshitij.so 465
 
466
 
14495 kshitij.so 467
class FeaturedDeals():
14482 kshitij.so 468
 
14495 kshitij.so 469
    def on_get(self, req, resp):
470
 
471
        offset = req.get_param_as_int("offset")
472
        limit = req.get_param_as_int("limit")
473
 
474
        result = Mongo.getAllFeaturedDeals(offset, limit)
475
        resp.body = dumps(result)
476
 
477
 
478
    def on_post(self, req, resp):
479
 
14552 kshitij.so 480
        multi = req.get_param_as_int("multi")
481
 
14495 kshitij.so 482
        try:
483
            result_json = json.loads(req.stream.read(), encoding='utf-8')
484
        except ValueError:
485
            raise falcon.HTTPError(falcon.HTTP_400,
486
                'Malformed JSON',
487
                'Could not decode the request body. The '
488
                'JSON was incorrect.')
489
 
14552 kshitij.so 490
        result = Mongo.addFeaturedDeal(result_json, multi)
14495 kshitij.so 491
        resp.body = json.dumps(result, encoding='utf-8')
492
 
14497 kshitij.so 493
 
494
class CommonSearch():
14495 kshitij.so 495
 
14497 kshitij.so 496
    def on_get(self,req,resp):
497
        class_name = req.get_param("class")
498
        sku = req.get_param_as_int("sku")
499
        skuBundleId = req.get_param_as_int("skuBundleId")
14499 kshitij.so 500
 
501
        result = Mongo.searchCollection(class_name, sku, skuBundleId)
14497 kshitij.so 502
        resp.body = dumps(result)
14619 kshitij.so 503
 
504
class CricScore():
505
 
506
    def on_get(self,req,resp):
507
 
508
        result = Mongo.getLiveCricScore()
14853 kshitij.so 509
        resp.body = dumps(result)
510
 
511
class Notification():
512
 
513
    def on_post(self, req, resp):
514
 
515
        try:
516
            result_json = json.loads(req.stream.read(), encoding='utf-8')
517
        except ValueError:
518
            raise falcon.HTTPError(falcon.HTTP_400,
519
                'Malformed JSON',
520
                'Could not decode the request body. The '
521
                'JSON was incorrect.')
522
 
523
        result = Mongo.addBundleToNotification(result_json)
524
        resp.body = json.dumps(result, encoding='utf-8')
525
 
526
    def on_get(self, req, resp):
527
 
528
        offset = req.get_param_as_int("offset")
529
        limit = req.get_param_as_int("limit")
530
 
531
        result = Mongo.getAllNotifications(offset, limit)
532
        resp.body = dumps(result)
533
 
14998 kshitij.so 534
class DealBrands():
14853 kshitij.so 535
 
14998 kshitij.so 536
    def on_get(self, req, resp):
537
 
538
        category_id = req.get_param_as_int("category_id")
539
        result = Mongo.getBrandsForFilter(category_id)
14999 kshitij.so 540
        resp.body = dumps(result)
15161 kshitij.so 541
 
542
class DealRank():
14998 kshitij.so 543
 
15161 kshitij.so 544
    def on_get(self, req, resp):
545
        identifier = req.get_param("identifier")
546
        source_id = req.get_param_as_int("source_id")
547
        user_id = req.get_param_as_int("user_id")
548
        result = Mongo.getDealRank(identifier, source_id, user_id)
549
        json_docs = json.dumps(result, default=json_util.default)
550
        resp.body = json_docs
551
 
552
 
16560 amit.gupta 553
class OrderedOffers():
554
    def on_get(self, req, resp, storeId, storeSku):
555
        storeId = int(storeId)
16563 amit.gupta 556
        result = Mongo.getBundleBySourceSku(storeId, storeSku)
557
        json_docs = json.dumps(result, default=json_util.default)
558
        resp.body = json_docs
20147 rajender 559
 
560
class GetDtrLinks():
561
 
562
    def on_get(self, req, resp, agentId, callType, userId):
563
        try:
564
            self.agentId = int(agentId)
565
            self.callType = callType
566
            if userId is not None:
567
                self.userId = int(userId)
568
                users_referrer, = session.query(Users.referrer).filter_by(id=self.userId).first()
569
                retailerLink = session.query(RetailerLinks).filter_by(code=users_referrer).first()
570
                if retailerLink is not None:
571
                    code = retailerLink.code
20161 rajender 572
                elif users_referrer.lower()=='fos01':
573
                    code = 'fos01'
20147 rajender 574
                else:
20149 rajender 575
                    resp.body =  json.dumps({"success":"false"}, encoding='utf-8')
576
                    return
20147 rajender 577
                session.close()
578
                resp.body =  json.dumps({"result":{"code":code,"link":make_tiny(code)}}, encoding='utf-8')
579
                return 
580
        finally:
581
            session.close
582
 
583
    def getNewRandomCode(self,):
584
        newCode = None
585
        while True:
586
            newCode = getNextRandomCode(newcodesys, 6)
587
            print 'NewCode',newCode
588
            isCodePresent = session.query(Activation_Codes).filter_by(code=newCode).first()
589
            if isCodePresent is not None:
590
                continue
591
            else:
592
                break
593
        return newCode
594
 
15081 amit.gupta 595
class RetailerDetail():
596
    global RETAILER_DETAIL_CALL_COUNTER
15105 amit.gupta 597
    def getRetryRetailer(self,failback=True):
15358 amit.gupta 598
        status = RETRY_MAP.get(self.callType)
17089 amit.gupta 599
        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 600
 
15239 amit.gupta 601
        if retailer is not None:
602
            lgr.info( "getRetryRetailer " + str(retailer.id))
603
        else:
604
            if failback:
605
                retailer = self.getNewRetailer(False)
606
                return retailer
16371 amit.gupta 607
            else:
608
                #No further calls for now
609
                return None
15358 amit.gupta 610
        retailer.status = ASSIGN_MAP.get(status)
16371 amit.gupta 611
        retailer.next_call_time = None
15239 amit.gupta 612
        lgr.info( "getRetryRetailer " + str(retailer.id))
15081 amit.gupta 613
        return retailer
614
 
15662 amit.gupta 615
    def getNotActiveRetailer(self):
616
        try:
15716 amit.gupta 617
            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 618
            if user is None: 
619
                return None
620
            else:
621
                retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
622
                if retailerContact is not None:
623
                    retailer = session.query(Retailers).filter_by(id=retailerContact.retailer_id).first()
624
                else:
625
                    retailer = session.query(Retailers).filter_by(contact1=user.mobile_number).first()
626
                    if retailer is None:
627
                        retailer = session.query(Retailers).filter_by(contact2=user.mobile_number).first()
628
                        if retailer is None:
629
                            retailer = Retailers()
630
                            retailer.contact1 = user.mobile_number
631
                            retailer.status = 'assigned'
15672 amit.gupta 632
                            retailer.retry_count = 0
15673 amit.gupta 633
                            retailer.invalid_retry_count = 0
15699 amit.gupta 634
                            retailer.is_elavated=1
19767 manas 635
                            retailer.isvalidated = 0
636
                            retailer.source = 'outbound' 
15662 amit.gupta 637
                user.status = 2
638
                session.commit()
639
                print "retailer id", retailer.id
640
                retailer.contact = user.mobile_number
641
                return retailer
642
        finally:
643
            session.close()
644
 
15081 amit.gupta 645
    def getNewRetailer(self,failback=True):
15663 amit.gupta 646
        if self.callType == 'fresh':
647
            retailer = self.getNotActiveRetailer()
648
            if retailer is not None:
649
                return retailer
20326 aman.kumar 650
            else:
651
                return None
652
            '''
653
            As of 26 august 2016, this is temporary change should be rolled back when required
654
            Hint remove above else statement
655
            '''
15081 amit.gupta 656
        retry = True
657
        retailer = None 
658
        try:
659
            while(retry):
15168 amit.gupta 660
                lgr.info( "Calltype " + self.callType)
15081 amit.gupta 661
                status=self.callType
15545 amit.gupta 662
                query = session.query(Retailers).filter(Retailers.status==status).filter(or_(Retailers.agent_id==self.agentId, Retailers.agent_id==None))
15081 amit.gupta 663
                if status=='fresh':
19850 manas 664
                    query = query.filter_by(is_or=False, is_std=False).filter(Retailers.cod_limit > 4998).order_by(Retailers.is_elavated.desc(), Retailers.agent_id.desc())
15358 amit.gupta 665
                elif status=='followup':
15546 amit.gupta 666
                    query = query.filter(Retailers.next_call_time<=datetime.now()).order_by(Retailers.agent_id.desc(),Retailers.next_call_time)
15162 amit.gupta 667
                else:
15546 amit.gupta 668
                    query = query.filter(Retailers.modified<=datetime.now()).order_by(Retailers.agent_id.desc(), Retailers.modified)
15358 amit.gupta 669
 
15081 amit.gupta 670
                retailer = query.with_lockmode("update").first()
671
                if retailer is not None:
15168 amit.gupta 672
                    lgr.info( "retailer " +str(retailer.id))
15081 amit.gupta 673
                    if status=="fresh":
674
                        userquery = session.query(Users)
675
                        if retailer.contact2 is not None:
676
                            userquery = userquery.filter(Users.mobile_number.in_([retailer.contact1,retailer.contact2]))
677
                        else:
678
                            userquery = userquery.filter_by(mobile_number=retailer.contact1)
679
                        user = userquery.first()
680
                        if user is not None:
681
                            retailer.status = 'alreadyuser'
15168 amit.gupta 682
                            lgr.info( "retailer.status " + retailer.status)
15081 amit.gupta 683
                            session.commit()
684
                            continue
685
                        retailer.status = 'assigned'
15358 amit.gupta 686
                    elif status=='followup':
15276 amit.gupta 687
                        if isActivated(retailer.id):
688
                            print "Retailer Already %d activated and marked onboarded"%(retailer.id)
689
                            continue
15081 amit.gupta 690
                        retailer.status = 'fassigned'
15358 amit.gupta 691
                    else:
692
                        retailer.status = 'oassigned'
15081 amit.gupta 693
                    retailer.retry_count = 0
15123 amit.gupta 694
                    retailer.invalid_retry_count = 0
15168 amit.gupta 695
                    lgr.info( "Found Retailer " +  str(retailer.id) + " with status " + status + " assigned to " + str(self.agentId))
15081 amit.gupta 696
 
697
                else:
15168 amit.gupta 698
                    lgr.info( "No fresh/followup retailers found")
15081 amit.gupta 699
                    if failback:
700
                        retailer = self.getRetryRetailer(False)
15104 amit.gupta 701
                        return retailer
15148 amit.gupta 702
                retry=False
15081 amit.gupta 703
        except:
704
            print traceback.print_exc()
705
        return retailer
706
 
15132 amit.gupta 707
    def on_get(self, req, resp, agentId, callType=None, retailerId=None):
16927 amit.gupta 708
        try:
709
            global RETAILER_DETAIL_CALL_COUNTER
710
            RETAILER_DETAIL_CALL_COUNTER += 1
711
            lgr.info( "RETAILER_DETAIL_CALL_COUNTER " +  str(RETAILER_DETAIL_CALL_COUNTER))
712
            self.agentId = int(agentId)
713
            self.callType = callType
714
            if retailerId is not None:
715
                self.retailerId = int(retailerId)
716
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=self.retailerId).first()
717
                if retailerLink is not None:
718
                    code = retailerLink.code
19734 manas 719
                    retailerLink.agent_id = self.agentId
720
                    session.commit()
16927 amit.gupta 721
                else: 
19732 manas 722
                    code = self.getNewRandomCode()
16927 amit.gupta 723
                    retailerLink = RetailerLinks()
724
                    retailerLink.code = code
725
                    retailerLink.agent_id = self.agentId
726
                    retailerLink.retailer_id = self.retailerId
727
                    activationCode=Activation_Codes()
728
                    activationCode.code = code
19777 manas 729
                    activationCode.status = False
16927 amit.gupta 730
                    session.commit()
731
                session.close()
732
                resp.body =  json.dumps({"result":{"code":code,"link":make_tiny(code)}}, encoding='utf-8')
733
                return 
734
            retryFlag = False 
735
            if RETAILER_DETAIL_CALL_COUNTER % TOTAL >= DEALER_FRESH_FACTOR:
736
                retryFlag=True
737
            try:
738
                if retryFlag:
739
                    retailer = self.getRetryRetailer()
740
                else:
741
                    retailer = self.getNewRetailer()
742
                if retailer is None:
743
                    resp.body = "{}"
744
                    return
745
                fetchInfo = FetchDataHistory()
746
                fetchInfo.agent_id = self.agentId
747
                fetchInfo.call_type = self.callType
748
                agent = session.query(Agents).filter_by(id=self.agentId).first()
749
                last_disposition = session.query(CallHistory).filter_by(agent_id=self.agentId).order_by(CallHistory.id.desc()).first()
750
                if last_disposition is None or last_disposition.created < agent.last_login:
751
                    fetchInfo.last_action = 'login'
752
                    fetchInfo.last_action_time = agent.last_login 
753
                else:
754
                    fetchInfo.last_action = 'disposition'
755
                    fetchInfo.last_action_time = last_disposition.created
756
                fetchInfo.retailer_id = retailer.id
757
                session.commit()
15135 amit.gupta 758
 
16927 amit.gupta 759
                otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
760
                resp.body = json.dumps(todict(getRetailerObj(retailer, otherContacts, self.callType)), encoding='utf-8')
761
 
762
                return
763
 
764
            finally:
765
                session.close()
766
 
15343 amit.gupta 767
            if retailer is None:
768
                resp.body = "{}"
15239 amit.gupta 769
            else:
16927 amit.gupta 770
                print "It should never come here"
771
                resp.body = json.dumps(todict(getRetailerObj(retailer)), encoding='utf-8')
15239 amit.gupta 772
        finally:
773
            session.close()
15081 amit.gupta 774
 
775
    def on_post(self, req, resp, agentId, callType):
15112 amit.gupta 776
        returned = False
15081 amit.gupta 777
        self.agentId = int(agentId)
778
        self.callType = callType
779
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
15169 amit.gupta 780
        lgr.info( "Request ----\n"  + str(jsonReq))
15091 amit.gupta 781
        self.jsonReq = jsonReq
782
        invalidNumber = self.invalidNumber
783
        callLater = self.callLater
15096 amit.gupta 784
        alreadyUser = self.alReadyUser
15091 amit.gupta 785
        verifiedLinkSent = self.verifiedLinkSent
15368 amit.gupta 786
        onboarded = self.onboarded
15278 amit.gupta 787
        self.address = jsonReq.get('address')
15096 amit.gupta 788
        self.retailerId = int(jsonReq.get('retailerid'))
15671 amit.gupta 789
        self.smsNumber = jsonReq.get('smsnumber')
790
        if self.smsNumber is not None:
791
            self.smsNumber = self.smsNumber.strip().lstrip("0") 
15112 amit.gupta 792
        try:
793
            self.retailer = session.query(Retailers).filter_by(id=self.retailerId).first()
15281 amit.gupta 794
            if self.address:
15278 amit.gupta 795
                self.retailer.address_new = self.address
15112 amit.gupta 796
            self.callDisposition = jsonReq.get('calldispositiontype')
797
            self.callHistory = CallHistory()
798
            self.callHistory.agent_id=self.agentId
799
            self.callHistory.call_disposition = self.callDisposition
800
            self.callHistory.retailer_id=self.retailerId
15115 amit.gupta 801
            self.callHistory.call_type=self.callType
15112 amit.gupta 802
            self.callHistory.duration_sec = int(jsonReq.get("callduration"))
803
            self.callHistory.disposition_description = jsonReq.get('calldispositiondescritption')
15200 manas 804
            self.callHistory.disposition_comments = jsonReq.get('calldispositioncomments')
805
            lgr.info(self.callHistory.disposition_comments)
15112 amit.gupta 806
            self.callHistory.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
807
            self.callHistory.mobile_number = jsonReq.get('number')
15145 amit.gupta 808
            self.callHistory.sms_verified = int(jsonReq.get("verified"))
15234 amit.gupta 809
            lastFetchData = session.query(FetchDataHistory).filter_by(agent_id=self.agentId).order_by(FetchDataHistory.id.desc()).first()
15368 amit.gupta 810
            if self.callDisposition == 'onboarded':
811
                self.checkList = jsonReq.get('checklist')
812
 
15234 amit.gupta 813
            if lastFetchData is None:
814
                raise
815
            self.callHistory.last_fetch_time= lastFetchData.created  
15112 amit.gupta 816
 
817
            dispositionMap = {  'call_later':callLater,
818
                        'ringing_no_answer':callLater,
819
                        'not_reachable':callLater,
820
                        'switch_off':callLater,
15202 manas 821
                        'not_retailer':invalidNumber,
15112 amit.gupta 822
                        'invalid_no':invalidNumber,
823
                        'wrong_no':invalidNumber,
824
                        'hang_up':invalidNumber,
825
                        'retailer_not_interested':invalidNumber,
15200 manas 826
                        'recharge_retailer':invalidNumber,
827
                        'accessory_retailer':invalidNumber,
828
                        'service_center_retailer':invalidNumber,
15112 amit.gupta 829
                        'alreadyuser':alreadyUser,
15368 amit.gupta 830
                        'verified_link_sent':verifiedLinkSent,
831
                        'onboarded':onboarded
15112 amit.gupta 832
                      }
833
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
834
        finally:
835
            session.close()
15096 amit.gupta 836
 
15112 amit.gupta 837
        if returned:
838
            resp.body = "{\"result\":\"success\"}"
839
        else:
840
            resp.body = "{\"result\":\"failed\"}"
15081 amit.gupta 841
 
15091 amit.gupta 842
    def invalidNumber(self,):
15108 manas 843
        #self.retailer.status = 'retry' if self.callType == 'fresh' else 'fretry'
844
        if self.callDisposition == 'invalid_no':
845
            self.retailer.status='failed'
846
            self.callHistory.disposition_description = 'Invalid Number'
847
        elif self.callDisposition == 'wrong_no':
15111 manas 848
            self.retailer.status='failed'
849
            self.callHistory.disposition_description = 'Wrong Number'
850
        elif self.callDisposition == 'hang_up':
851
            self.retailer.status='failed'
852
            self.callHistory.disposition_description = 'Hang Up'
853
        elif self.callDisposition == 'retailer_not_interested':
854
            self.retailer.status='failed'
855
            if self.callHistory.disposition_description is None:
856
                self.callHistory.disposition_description = 'NA'
15200 manas 857
            self.callHistory.disposition_description = 'Reason Retailer Not Interested ' + self.callHistory.disposition_description
858
        elif self.callDisposition == 'recharge_retailer':
859
            self.retailer.status='failed'
860
            self.callHistory.disposition_description = 'Recharge related. Not a retailer '
861
        elif self.callDisposition == 'accessory_retailer':
862
            self.retailer.status='failed'
863
            self.callHistory.disposition_description = 'Accessory related. Not a retailer'
864
        elif self.callDisposition == 'service_center_retailer':
865
            self.retailer.status='failed'
866
            self.callHistory.disposition_description = 'Service Center related. Not a retailer'
15202 manas 867
        elif self.callDisposition == 'not_retailer':
868
            self.retailer.status='failed'
869
            self.callHistory.disposition_description = 'Not a retailer'    
15108 manas 870
        session.commit()
871
        return True   
872
 
15132 amit.gupta 873
    def getCode(self,):
15207 amit.gupta 874
        newCode = None
875
        lastLink = session.query(RetailerLinks).order_by(RetailerLinks.id.desc()).with_lockmode("update").first()
876
        if lastLink is not None:
877
            if len(lastLink.code)==len(codesys):
878
                newCode=lastLink.code
879
        return getNextCode(codesys, newCode)
15108 manas 880
 
19732 manas 881
    def getNewRandomCode(self,):
882
        newCode = None
883
        while True:
884
            newCode = getNextRandomCode(newcodesys, 6)
885
            print 'NewCode',newCode
886
            isCodePresent = session.query(Activation_Codes).filter_by(code=newCode).first()
887
            if isCodePresent is not None:
888
                continue
889
            else:
890
                break
891
        return newCode
15254 amit.gupta 892
 
15091 amit.gupta 893
    def callLater(self,):
15368 amit.gupta 894
        self.retailer.status = RETRY_MAP.get(self.callType)
15100 amit.gupta 895
        self.retailer.call_priority = None
15096 amit.gupta 896
        if self.callDisposition == 'call_later':
15100 amit.gupta 897
            if self.callHistory.disposition_description is not None:
15102 amit.gupta 898
                self.retailer.call_priority = 'user_initiated'
15096 amit.gupta 899
                self.retailer.next_call_time = datetime.strptime(self.callHistory.disposition_description, '%d/%m/%Y %H:%M:%S')
900
                self.callHistory.disposition_description = 'User requested to call on ' + self.callHistory.disposition_description
901
            else:
15102 amit.gupta 902
                self.retailer.call_priority = 'system_initiated'
15096 amit.gupta 903
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
15112 amit.gupta 904
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
905
        else: 
906
            if self.callDisposition == 'ringing_no_answer':
907
                if self.retailer.disposition == 'ringing_no_answer':
908
                    self.retailer.retry_count += 1
909
                else:
910
                    self.retailer.disposition = 'ringing_no_answer'
911
                    self.retailer.retry_count = 1
912
            else:
913
                if self.retailer.disposition == 'ringing_no_answer':
15122 amit.gupta 914
                    pass
15112 amit.gupta 915
                else:
15119 amit.gupta 916
                    self.retailer.disposition = 'not_reachable'
15122 amit.gupta 917
                self.retailer.retry_count += 1
918
                self.retailer.invalid_retry_count += 1
15119 amit.gupta 919
 
15122 amit.gupta 920
            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 921
            if retryConfig is not None:
922
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(minutes = retryConfig.minutes_ahead)
15119 amit.gupta 923
                self.callHistory.disposition_description = 'Call scheduled on ' + datetime.strftime(self.retailer.next_call_time, '%d/%m/%Y %H:%M:%S')
15112 amit.gupta 924
            else:
925
                self.retailer.status = 'failed'
926
                self.callHistory.disposition_description = 'Call failed as all attempts exhausted'
15119 amit.gupta 927
 
15101 amit.gupta 928
        session.commit()
929
        return True
15096 amit.gupta 930
 
15100 amit.gupta 931
 
15091 amit.gupta 932
    def alReadyUser(self,):
15112 amit.gupta 933
        self.retailer.status = self.callDisposition
15117 amit.gupta 934
        if self.callHistory.disposition_description is None:
935
            self.callHistory.disposition_description = 'Retailer already user' 
15112 amit.gupta 936
        session.commit()
937
        return True
15091 amit.gupta 938
    def verifiedLinkSent(self,):
15147 amit.gupta 939
        if self.callType == 'fresh':
19734 manas 940
            if self.retailer.isvalidated:
941
                self.retailer.status = 'followup'
942
                if self.retailer.agent_id not in sticky_agents:
943
                    self.retailer.agent_id = None
944
                self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=1)
945
                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') 
946
            else:
947
                self.retailer.status = 'pending_verification'
948
                if self.retailer.agent_id not in sticky_agents:
949
                    self.retailer.agent_id = None
950
                self.callHistory.disposition_description = "Retailer is pending for verification" 
15147 amit.gupta 951
        else:
15224 amit.gupta 952
            self.retailer.status = 'followup'
16882 amit.gupta 953
            if self.retailer.agent_id not in sticky_agents:
954
                self.retailer.agent_id = None
15147 amit.gupta 955
            self.retailer.next_call_time = self.callHistory.call_time + timedelta(days=7)
15254 amit.gupta 956
            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 957
        addContactToRetailer(self.agentId, self.retailerId, self.smsNumber, self.callType, 'sms')     
15146 amit.gupta 958
        session.commit()
959
        return True
15368 amit.gupta 960
    def onboarded(self,):
961
        self.retailer.status = self.callDisposition
962
        checkList = OnboardedRetailerChecklists()
963
        checkList.contact_us = self.checkList.get('contactus')
15390 amit.gupta 964
        checkList.doa_return_policy = self.checkList.get('doareturnpolicy')
15368 amit.gupta 965
        checkList.number_verification = self.checkList.get('numberverification')
966
        checkList.payment_option = self.checkList.get('paymentoption')
967
        checkList.preferences = self.checkList.get('preferences')
968
        checkList.product_info = self.checkList.get('productinfo')
15372 amit.gupta 969
        checkList.redeem = self.checkList.get('redeem')
15368 amit.gupta 970
        checkList.retailer_id = self.retailerId
971
        session.commit()
972
        return True
973
 
974
 
15254 amit.gupta 975
def isActivated(retailerId):
15276 amit.gupta 976
    retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailerId).first()
15448 amit.gupta 977
    user = session.query(Users).filter(or_(func.lower(Users.referrer)==retailerLink.code.lower(), Users.utm_campaign==retailerLink.code)).first()
15276 amit.gupta 978
    if user is None:
979
        mobileNumbers = list(session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailerId).all())
980
        user = session.query(Users).filter(Users.mobile_number.in_(mobileNumbers)).first()
15254 amit.gupta 981
        if user is None:
15332 amit.gupta 982
            if retailerLink.created < datetime(2015,5,26):
15333 amit.gupta 983
                historyNumbers = [number for number, in session.query(CallHistory.mobile_number).filter_by(retailer_id = retailerId).all()]
15476 amit.gupta 984
                user = session.query(Users).filter(Users.mobile_number.in_(historyNumbers)).first()
15332 amit.gupta 985
                if user is None:
986
                    return False
15334 amit.gupta 987
                else:
988
                    mapped_with = 'contact'
15332 amit.gupta 989
            else:
990
                return False
15276 amit.gupta 991
        else:
992
            mapped_with = 'contact'
993
    else:
994
        mapped_with = 'code'
995
    retailerLink.mapped_with = mapped_with
15388 amit.gupta 996
    if user.activation_time is not None:
15448 amit.gupta 997
        retailerLink.activated = user.activation_time
998
    retailerLink.activated = user.created
15276 amit.gupta 999
    retailerLink.user_id = user.id
15291 amit.gupta 1000
    retailer = session.query(Retailers).filter_by(id=retailerId).first()
15574 amit.gupta 1001
    if retailer.status == 'followup' or retailer.status == 'fretry':
15389 amit.gupta 1002
        retailer.status = 'onboarding'
16882 amit.gupta 1003
        if retailer.agent_id not in sticky_agents:
1004
                retailer.agent_id = None
15391 amit.gupta 1005
        retailer.call_priority = None
1006
        retailer.next_call_time = None
1007
        retailer.retry_count = 0
1008
        retailer.invalid_retry_count = 0
15276 amit.gupta 1009
    session.commit()
15287 amit.gupta 1010
    print "retailerLink.retailer_id", retailerLink.retailer_id
15700 amit.gupta 1011
    print "retailer", retailer.id
15276 amit.gupta 1012
    session.close()
1013
    return True
15254 amit.gupta 1014
 
1015
class AddContactToRetailer():
1016
    def on_post(self,req,resp, agentId):
1017
        agentId = int(agentId)
1018
        try:
1019
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1020
            retailerId = int(jsonReq.get("retailerid"))
1021
            mobile = jsonReq.get("mobile")
1022
            callType = jsonReq.get("calltype")
1023
            contactType = jsonReq.get("contacttype")
1024
            addContactToRetailer(agentId, retailerId, mobile, callType, contactType)
1025
            session.commit()
1026
        finally:
1027
            session.close()
15676 amit.gupta 1028
 
15677 amit.gupta 1029
class AddAddressToRetailer():
15676 amit.gupta 1030
    def on_post(self,req,resp, agentId):
1031
        agentId = int(agentId)
15678 amit.gupta 1032
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1033
        retailerId = int(jsonReq.get("retailerid"))
15684 amit.gupta 1034
        address = str(jsonReq.get("address"))
1035
        storeName = str(jsonReq.get("storename"))
1036
        pin = str(jsonReq.get("pin"))
1037
        city = str(jsonReq.get("city"))
1038
        state = str(jsonReq.get("state"))
1039
        updateType = str(jsonReq.get("updatetype"))
19732 manas 1040
        tinnumber = str(jsonReq.get("tinnumber"))
1041
        addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType,tinnumber)
15254 amit.gupta 1042
 
1043
def addContactToRetailer(agentId, retailerId, mobile, callType, contactType):
15312 amit.gupta 1044
    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=retailerId).filter_by(mobile_number=mobile).first()
1045
    if retailerContact is None:
15254 amit.gupta 1046
        retailerContact = RetailerContacts()
15256 amit.gupta 1047
        retailerContact.retailer_id = retailerId
15254 amit.gupta 1048
        retailerContact.agent_id = agentId
1049
        retailerContact.call_type = callType
1050
        retailerContact.contact_type = contactType
1051
        retailerContact.mobile_number = mobile
15312 amit.gupta 1052
    else:
15327 amit.gupta 1053
        if CONTACT_PRIORITY.index(retailerContact.contact_type) > CONTACT_PRIORITY.index(contactType):
15358 amit.gupta 1054
            retailerContact.contact_type = contactType
15676 amit.gupta 1055
 
19732 manas 1056
def addAddressToRetailer(agentId, retailerId, address, storeName, pin, city,state, updateType,tinnumber):
15679 amit.gupta 1057
    print "I am in addAddress"
15682 amit.gupta 1058
    print agentId, retailerId, address, storeName, pin, city, state, updateType
15679 amit.gupta 1059
    try:
19734 manas 1060
        retailer = session.query(Retailers).filter_by(id=retailerId).first()
1061
        retailer.tinnumber = tinnumber
15679 amit.gupta 1062
        if updateType=='new':
1063
            retailer.address = address
1064
            retailer.title = storeName
1065
            retailer.city = city
1066
            retailer.state = state
1067
            retailer.pin = pin
1068
        raddress = RetailerAddresses()
1069
        raddress.address = address
15682 amit.gupta 1070
        raddress.title = storeName
15679 amit.gupta 1071
        raddress.agent_id = agentId
1072
        raddress.city = city
1073
        raddress.pin = pin
1074
        raddress.retailer_id = retailerId
1075
        raddress.state = state
1076
        session.commit()
1077
    finally:
1078
        session.close() 
15254 amit.gupta 1079
 
15312 amit.gupta 1080
 
15189 manas 1081
class Login():
1082
 
1083
    def on_get(self, req, resp, agentId, role):
1084
        try:
15198 manas 1085
            self.agentId = int(agentId)
1086
            self.role = role
1087
            print str(self.agentId) + self.role;
15199 manas 1088
            agents=AgentLoginTimings()
1089
            lastLoginTime = session.query(Agents).filter(Agents.id==self.agentId).first()
1090
            print 'lastLogintime' + str(lastLoginTime)
1091
            agents.loginTime=lastLoginTime.last_login
1092
            agents.logoutTime=datetime.now()
1093
            agents.role =self.role
15282 amit.gupta 1094
            agents.agent_id = self.agentId
15199 manas 1095
            session.add(agents)    
1096
            session.commit()
1097
            resp.body =  json.dumps({"result":{"success":"true","message":"Success"}}, encoding='utf-8')
15189 manas 1098
        finally:
1099
            session.close()        
15112 amit.gupta 1100
 
15189 manas 1101
    def on_post(self,req,resp):
1102
        try:
1103
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1104
            lgr.info( "Request ----\n"  + str(jsonReq))
1105
            email=jsonReq.get('email')
1106
            password = jsonReq.get('password')
1107
            role=jsonReq.get('role')    
15531 amit.gupta 1108
            agent = session.query(Agents).filter(and_(Agents.email==email,Agents.password==password)).first()
1109
            if agent is None:
15189 manas 1110
                resp.body =  json.dumps({"result":{"success":"false","message":"Invalid User"}}, encoding='utf-8')
1111
            else:
15531 amit.gupta 1112
                print agent.id
1113
                checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==agent.id,Agent_Roles.role==role)).first()
15189 manas 1114
                if checkRole is None:
1115
                    resp.body =  json.dumps({"result":{"success":"false","message":"Invalid Role"}}, encoding='utf-8')
1116
                else:
15531 amit.gupta 1117
                    agent.last_login = datetime.now()
1118
                    agent.login_type = role
1119
                    resp.body =  json.dumps({"result":{"success":"true","message":"Valid User","id":agent.id}}, encoding='utf-8')
1120
                    session.commit()
15195 manas 1121
                    #session.query(Agents).filter_by(id = checkUser[0]).    
15189 manas 1122
        finally:
1123
            session.close()    
1124
 
15195 manas 1125
    def test(self,email,password,role):
15189 manas 1126
        checkUser = session.query(Agents.id).filter(and_(Agents.email==email,Agents.password==password)).first()
1127
        if checkUser is None:
1128
            print checkUser
15195 manas 1129
 
15189 manas 1130
        else:
1131
            print checkUser[0]
1132
            checkRole = session.query(Agent_Roles.id).filter(and_(Agent_Roles.agent_id==checkUser[0],Agent_Roles.role==role)).first()
1133
            if checkRole is None:
15195 manas 1134
                pass
15189 manas 1135
            else:
15195 manas 1136
                agents=AgentLoginTimings()
1137
                agents.loginTime=datetime.now()
1138
                agents.logoutTime=datetime.now()
1139
                agents.role =role
1140
                agents.agent_id = 2
1141
                #session.query(AgentLoginTimings).filter_by(id = checkUser[0]).update({"last_login":datetime.now()}, synchronize_session=False)
1142
                session.add(agents)    
1143
                session.commit()
1144
                session.close()
1145
 
1146
                #session.query(Agents).filter(Agents.id==checkUser[0]).update({"last_login":Agents.last_login})
15275 amit.gupta 1147
 
1148
class RetailerActivation():
1149
    def on_get(self, req, resp, userId):
15351 amit.gupta 1150
        res =  markDealerActivation(int(userId))
1151
        if res:
1152
            resp.body = "{\"activated\":true}"
1153
        else:
1154
            resp.body = "{\"activated\":false}"
1155
 
15275 amit.gupta 1156
 
1157
def markDealerActivation(userId):
1158
    try:
15343 amit.gupta 1159
        user = session.query(Users).filter_by(id=userId).first()
15275 amit.gupta 1160
        result = False                
1161
        mappedWith = 'contact'
15534 amit.gupta 1162
        retailer = None
15275 amit.gupta 1163
        if user is not None:
15454 amit.gupta 1164
            referrer = None if user.referrer is None else user.referrer.upper()
1165
            retailerLink = session.query(RetailerLinks).filter(or_(RetailerLinks.code==referrer, RetailerLinks.code==user.utm_campaign)).first()
15275 amit.gupta 1166
            if retailerLink is None:
15501 amit.gupta 1167
                if user.mobile_number is not None:
1168
                    retailerContact = session.query(RetailerContacts).filter_by(mobile_number=user.mobile_number).first()
1169
                    if retailerContact is None:
15613 amit.gupta 1170
                        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 1171
                    else:
1172
                        retailer = session.query(Retailers).filter_by(id = retailerContact.retailer_id).first()
15275 amit.gupta 1173
            else:
1174
                retailer = session.query(Retailers).filter_by(id = retailerLink.retailer_id).first()
1175
                mappedWith='code'
1176
            if retailer is not None:
1177
                retailerLink = session.query(RetailerLinks).filter_by(retailer_id=retailer.id).first()
1178
                if retailerLink is not None:
1179
                    retailerLink.user_id = user.id
1180
                    retailerLink.mapped_with=mappedWith
15358 amit.gupta 1181
                    retailer.status = 'onboarding'
15275 amit.gupta 1182
                    result = True
1183
                    session.commit()
15574 amit.gupta 1184
        return result
15275 amit.gupta 1185
    finally:
1186
        session.close()
1187
 
15189 manas 1188
 
15081 amit.gupta 1189
def todict(obj, classkey=None):
1190
    if isinstance(obj, dict):
1191
        data = {}
1192
        for (k, v) in obj.items():
1193
            data[k] = todict(v, classkey)
1194
        return data
1195
    elif hasattr(obj, "_ast"):
1196
        return todict(obj._ast())
1197
    elif hasattr(obj, "__iter__"):
1198
        return [todict(v, classkey) for v in obj]
1199
    elif hasattr(obj, "__dict__"):
1200
        data = dict([(key, todict(value, classkey)) 
1201
            for key, value in obj.__dict__.iteritems() 
1202
            if not callable(value) and not key.startswith('_')])
1203
        if classkey is not None and hasattr(obj, "__class__"):
1204
            data[classkey] = obj.__class__.__name__
1205
        return data
1206
    else:
1207
        return obj
18256 manas 1208
 
15358 amit.gupta 1209
def getRetailerObj(retailer, otherContacts1=None, callType=None):
15324 amit.gupta 1210
    print "before otherContacts1",otherContacts1
1211
    otherContacts = [] if otherContacts1 is None else otherContacts1
15662 amit.gupta 1212
    print "after otherContacts1",otherContacts
15081 amit.gupta 1213
    obj = Mock()
15280 amit.gupta 1214
    obj.id = retailer.id
15686 amit.gupta 1215
 
1216
 
15314 amit.gupta 1217
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts:
15315 amit.gupta 1218
        otherContacts.append(retailer.contact1)
15314 amit.gupta 1219
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts:
15315 amit.gupta 1220
        otherContacts.append(retailer.contact2)
15323 amit.gupta 1221
    obj.contact1 = None if len(otherContacts)==0 else otherContacts[0]
15325 amit.gupta 1222
    if obj.contact1 is not None:
1223
        obj.contact2 = None if len(otherContacts)==1 else otherContacts[1]
15096 amit.gupta 1224
    obj.scheduled = (retailer.call_priority is not None)
15686 amit.gupta 1225
    address = None
1226
    try:
1227
        address = session.query(RetailerAddresses).filter_by(retailer_id=retailer.id).order_by(RetailerAddresses.created.desc()).first()
1228
    finally:
1229
        session.close()
1230
    if address is not None:
1231
        obj.address = address.address
1232
        obj.title = address.title
1233
        obj.city = address.city
1234
        obj.state = address.state
1235
        obj.pin = address.pin 
1236
    else:
1237
        obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
1238
        obj.title = retailer.title
1239
        obj.city = retailer.city
1240
        obj.state = retailer.state
1241
        obj.pin = retailer.pin 
15699 amit.gupta 1242
    obj.status = retailer.status
19791 manas 1243
    obj.tinnumber = retailer.tinnumber
1244
    obj.isvalidated = retailer.isvalidated    
15662 amit.gupta 1245
    if hasattr(retailer, 'contact'):
1246
        obj.contact = retailer.contact
19732 manas 1247
    if callType == 'followup':
1248
        obj.last_call_time = datetime.strftime(retailer.modified, "%B %Y")
15358 amit.gupta 1249
    if callType == 'onboarding':
1250
        try:
15364 amit.gupta 1251
            userId, activatedTime = session.query(RetailerLinks.user_id, RetailerLinks.activated).filter(RetailerLinks.retailer_id==retailer.id).first()
15366 amit.gupta 1252
            activated, = session.query(Users.activation_time).filter(Users.id==userId).first()
15364 amit.gupta 1253
            if activated is not None:
15366 amit.gupta 1254
                activatedTime = activated
15362 amit.gupta 1255
            obj.user_id = userId
15364 amit.gupta 1256
            obj.created = datetime.strftime(activatedTime, '%d/%m/%Y %H:%M:%S')
15358 amit.gupta 1257
            result = fetchResult("select * from useractive where user_id=%d"%(userId))
1258
            if result == ():
1259
                obj.last_active = None
1260
            else:
15360 amit.gupta 1261
                obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
15361 amit.gupta 1262
            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 1263
            obj.orders = ordersCount
1264
        finally:
1265
            session.close()
15081 amit.gupta 1266
    return obj
15091 amit.gupta 1267
 
15132 amit.gupta 1268
def make_tiny(code):
16939 manish.sha 1269
    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 1270
    #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 1271
    #marketUrl='market://details?id=com.saholic.profittill&referrer=utm_source=0&utm_medium=CRM&utm_term=001&utm_campaign='+code
1272
    #url = urllib.quote(marketUrl)
15465 amit.gupta 1273
    #request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1274
    #filehandle = urllib2.Request(request_url)
1275
    #x= urllib2.urlopen(filehandle)
15546 amit.gupta 1276
    try:
1277
        shortener = Shortener('TinyurlShortener')
1278
        returnUrl =  shortener.short(url)
1279
    except:
1280
        shortener = Shortener('SentalaShortener')
19678 amit.gupta 1281
        returnUrl =  shortener.short(url)
15546 amit.gupta 1282
    return returnUrl
15171 amit.gupta 1283
 
15285 manas 1284
class SearchUser():
1285
 
1286
    def on_post(self, req, resp, agentId, searchType):
15314 amit.gupta 1287
        retailersJsonArray = []
15285 manas 1288
        try:
1289
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1290
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1291
            contact=jsonReq.get('searchTerm')
15285 manas 1292
            if(searchType=="number"):
15312 amit.gupta 1293
                retailer_ids = session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all()
1294
                retailer_ids = [r for r, in retailer_ids]    
1295
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact, Retailers.id.in_(retailer_ids))
1296
            else:
1297
                m = re.match("(.*?)(\d{6})(.*?)", contact)
1298
                if m is not None:
1299
                    pin = m.group(2)
1300
                    contact = m.group(1) if m.group(1) != '' else m.group(3)
15313 amit.gupta 1301
                    anotherCondition = and_(Retailers.title.ilike('%%%s%%'%(contact)), Retailers.pin==pin)
15312 amit.gupta 1302
                else:
1303
                    anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1304
 
19928 kshitij.so 1305
            retailers = session.query(Retailers).filter(anotherCondition).filter(Retailers.isvalidated==1).limit(20).all()
15312 amit.gupta 1306
            if retailers is None:
15285 manas 1307
                resp.body = json.dumps("{}")
15312 amit.gupta 1308
            else:
1309
                for retailer in retailers:
15326 amit.gupta 1310
                    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 1311
                    retailersJsonArray.append(todict(getRetailerObj(retailer, otherContacts)))    
1312
            resp.body = json.dumps({"Retailers":retailersJsonArray}, encoding='utf-8')
15285 manas 1313
        finally:
1314
            session.close()
15171 amit.gupta 1315
 
15081 amit.gupta 1316
 
1317
class Mock(object):
1318
    pass
15189 manas 1319
 
15312 amit.gupta 1320
def tagActivatedReatilers():
15613 amit.gupta 1321
    retailerIds = [r for  r, in session.query(RetailerLinks.retailer_id).filter_by(user_id = None).all()]
15312 amit.gupta 1322
    session.close()
15288 amit.gupta 1323
    for retailerId in retailerIds:
1324
        isActivated(retailerId)
15312 amit.gupta 1325
    session.close()
15374 kshitij.so 1326
 
1327
class StaticDeals():
1328
 
1329
    def on_get(self, req, resp):
1330
 
1331
        offset = req.get_param_as_int("offset")
1332
        limit = req.get_param_as_int("limit")
1333
        categoryId = req.get_param_as_int("categoryId")
15458 kshitij.so 1334
        direction = req.get_param_as_int("direction")
15374 kshitij.so 1335
 
15458 kshitij.so 1336
        result = Mongo.getStaticDeals(offset, limit, categoryId, direction)
15374 kshitij.so 1337
        resp.body = dumps(result)
1338
 
16366 kshitij.so 1339
class DealNotification():
1340
 
1341
    def on_get(self,req,resp,skuBundleIds):
1342
        result = Mongo.getDealsForNotification(skuBundleIds)
1343
        resp.body = dumps(result)
16487 kshitij.so 1344
 
1345
class DealPoints():
1346
 
1347
    def on_get(self, req, resp):
16366 kshitij.so 1348
 
16487 kshitij.so 1349
        offset = req.get_param_as_int("offset")
1350
        limit = req.get_param_as_int("limit")
1351
 
1352
        result = Mongo.getAllBundlesWithDealPoints(offset, limit)
1353
        resp.body = dumps(result)
15374 kshitij.so 1354
 
16487 kshitij.so 1355
 
1356
    def on_post(self, req, resp):
1357
 
1358
 
1359
        try:
1360
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1361
        except ValueError:
1362
            raise falcon.HTTPError(falcon.HTTP_400,
1363
                'Malformed JSON',
1364
                'Could not decode the request body. The '
1365
                'JSON was incorrect.')
1366
 
1367
        result = Mongo.addDealPoints(result_json)
1368
        resp.body = json.dumps(result, encoding='utf-8')
15374 kshitij.so 1369
 
16545 kshitij.so 1370
class AppAffiliates():
1371
 
1372
    def on_get(self, req, resp, retailerId, appId):
1373
        retailerId = int(retailerId)
1374
        appId = int(appId)
16554 kshitij.so 1375
        call_back = req.get_param("callback")
16545 kshitij.so 1376
        result = Mongo.generateRedirectUrl(retailerId, appId)
16555 kshitij.so 1377
        resp.body = call_back+'('+str(result)+')'
16557 kshitij.so 1378
 
1379
class AffiliatePayout():
1380
    def on_get(self, req, resp):
1381
        payout = req.get_param("payout")
1382
        transaction_id = req.get_param("transaction_id")
1383
        result = Mongo.addPayout(payout, transaction_id)
1384
        resp.body = str(result)
1385
 
16581 manish.sha 1386
class AppOffers():
1387
    def on_get(self, req, resp, retailerId):
16895 manish.sha 1388
        try:            
1389
            result = Mongo.getAppOffers(retailerId)
1390
            offerids = result.values()
1391
            if offerids is None or len(offerids)==0:
16887 kshitij.so 1392
                resp.body = json.dumps("{}")
1393
            else:
16941 manish.sha 1394
                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 1395
                appOffersMap = {}
1396
                jsonOffersArray=[]
1397
                for offer in appOffers:
1398
                    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__
1399
                for rank in sorted(result):
1400
                    print 'Rank', rank, 'Data', appOffersMap[result[rank]]
1401
                    jsonOffersArray.append(appOffersMap[result[rank]])
1402
 
1403
            resp.body = json.dumps({"AppOffers":jsonOffersArray}, encoding='latin1')
16887 kshitij.so 1404
        finally:
1405
            session.close()
1406
 
16727 manish.sha 1407
 
1408
class AppUserBatchRefund():
1409
    def on_get(self, req, resp, batchId, userId):
16887 kshitij.so 1410
        try:
1411
            batchId = long(batchId)
1412
            userId = long(userId)
1413
            userBatchCashback = user_app_cashbacks.get_by(user_id=userId, batchCreditId=batchId)
1414
            if userBatchCashback is None:
1415
                resp.body = json.dumps("{}")
1416
            else:
16905 manish.sha 1417
                if userBatchCashback.creditedDate is not None:
1418
                    userBatchCashback.creditedDate = str(userBatchCashback.creditedDate)
16887 kshitij.so 1419
                resp.body = json.dumps(todict(userBatchCashback), encoding='utf-8')
1420
        finally:
1421
            session.close()
16727 manish.sha 1422
 
1423
class AppUserBatchDrillDown():
16777 manish.sha 1424
    def on_get(self, req, resp, fortNightOfYear, userId, yearVal):
16887 kshitij.so 1425
        try:
1426
            fortNightOfYear = long(fortNightOfYear)
1427
            userId = long(userId)
1428
            yearVal = long(yearVal)
1429
            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()
1430
            cashbackArray = []
1431
            if appUserBatchDrillDown is None or len(appUserBatchDrillDown)==0:
1432
                resp.body = json.dumps("{}")
1433
            else:
1434
                for appcashBack in appUserBatchDrillDown:
1435
                    userAppBatchDrillDown = UserAppBatchDrillDown(str(appcashBack[0]),long(appcashBack[1]), long(appcashBack[2]))
1436
                    cashbackArray.append(todict(userAppBatchDrillDown))
1437
                resp.body = json.dumps({"UserAppCashBackInBatch":cashbackArray}, encoding='utf-8')
1438
        finally:
1439
            session.close()
16727 manish.sha 1440
 
1441
class AppUserBatchDateDrillDown():
1442
    def on_get(self, req, resp, userId, date):
16887 kshitij.so 1443
        try:
1444
            userId = long(userId)
1445
            date = str(date)
1446
            date = datetime.strptime(date, '%Y-%m-%d')
1447
            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()
1448
            cashbackArray = []
1449
            if appUserBatchDateDrillDown is None or len(appUserBatchDateDrillDown)==0:
1450
                resp.body = json.dumps("{}")
1451
            else:
1452
                for appcashBack in appUserBatchDateDrillDown:
1453
                    userAppBatchDateDrillDown = UserAppBatchDateDrillDown(str(appcashBack[0]),long(appcashBack[1]),long(appcashBack[2]))
1454
                    cashbackArray.append(todict(userAppBatchDateDrillDown))
1455
                resp.body = json.dumps({"UserAppCashBackDateWise":cashbackArray}, encoding='utf-8')
1456
        finally:
1457
            session.close()
16739 manish.sha 1458
 
16748 manish.sha 1459
class AppUserCashBack():
1460
    def on_get(self, req, resp, userId, status):
16887 kshitij.so 1461
        try:
1462
            userId = long(userId)
1463
            status = str(status)
1464
            appUserApprovedCashBacks = user_app_cashbacks.query.filter(user_app_cashbacks.user_id==userId).filter(user_app_cashbacks.status==status).all()
1465
            cashbackArray = []
1466
            if appUserApprovedCashBacks is None or len(appUserApprovedCashBacks)==0:
1467
                resp.body = json.dumps("{}")
1468
            else:
1469
                totalAmount = 0                
1470
                for appUserApprovedCashBack in appUserApprovedCashBacks:
1471
                    totalAmount = totalAmount + appUserApprovedCashBack.amount
16895 manish.sha 1472
                    if appUserApprovedCashBack.creditedDate is not None:
1473
                        appUserApprovedCashBack.creditedDate = str(appUserApprovedCashBack.creditedDate)  
16905 manish.sha 1474
                    cashbackArray.append(todict(appUserApprovedCashBack)) 
1475
 
16887 kshitij.so 1476
                resp.body = json.dumps({"UserAppCashBack":cashbackArray,"TotalAmount":totalAmount}, encoding='utf-8')
1477
        finally:
1478
            session.close()
17278 naman 1479
 
1480
class GetSaleDetail():
1481
    def on_get(self,req,res,date_val):
1482
        try:
1483
                db = get_mongo_connection()
1484
                sum=0
1485
                count=0
1486
                #print date_val, type(date_val)
1487
                #cursor = db.Dtr.merchantOrder.find({'createdOnInt':{'$lt':long(date_val)},'subOrders':{'$exists':True}})
17315 naman 1488
                cursor = db.Dtr.merchantOrder.find({"$and": [ { "createdOnInt":{"$gt":long(date_val)} }, {"createdOnInt":{"$lt":long(date_val)+86401} } ],"subOrders":{"$exists":True}})
17278 naman 1489
 
1490
                for document in cursor:
1491
                    for doc in document['subOrders']:
1492
                        sum = sum + float(doc['amountPaid'])
1493
                        count = count + int(doc['quantity'])
1494
 
1495
                data = {"amount":sum , "quantity":count}
1496
 
1497
                res.body= json.dumps(data,encoding='utf-8')
1498
        finally:
1499
                session.close()
1500
 
17301 kshitij.so 1501
class DummyDeals():
17304 kshitij.so 1502
    def on_get(self,req, resp):
17301 kshitij.so 1503
        categoryId = req.get_param_as_int("categoryId")
1504
        offset = req.get_param_as_int("offset")
1505
        limit = req.get_param_as_int("limit")
1506
        result = Mongo.getDummyDeals(categoryId, offset, limit)
17556 kshitij.so 1507
        resp.body = dumps(result)
17301 kshitij.so 1508
 
17467 manas 1509
class PincodeValidation():
17498 amit.gupta 1510
    def on_get(self,req,resp,pincode):
17467 manas 1511
        json_data={}
1512
        cities=[]
1513
        print pincode
1514
        if len(str(pincode)) ==6:
19391 amit.gupta 1515
            listCities = list(session.query(Postoffices.taluk,Postoffices.state).distinct().filter(Postoffices.pincode==pincode).all())
17467 manas 1516
            if len(listCities)>0:
1517
                for j in listCities:
19391 amit.gupta 1518
                    if j.taluk != 'NA':
1519
                        cities.append(j.taluk)
17467 manas 1520
                json_data['cities'] = cities
1521
                json_data['state'] = listCities[0][1]
1522
                resp.body =  json.dumps(json_data)
1523
            else:
1524
                resp.body = json.dumps("{}")       
1525
        else:
1526
            resp.body = json.dumps("{}")
1527
        session.close()
17301 kshitij.so 1528
 
17556 kshitij.so 1529
class SearchDummyDeals():
1530
    def on_get(self,req,resp):
1531
        offset = req.get_param_as_int("offset")
1532
        limit = req.get_param_as_int("limit")
1533
        searchTerm = req.get_param("searchTerm")
1534
        result = Mongo.searchDummyDeals(searchTerm, limit, offset)
1535
        resp.body = dumps(result)
1536
 
1537
class DummyPricing:
17560 kshitij.so 1538
    def on_get(self, req, resp):
17556 kshitij.so 1539
        skuBundleId = req.get_param_as_int("skuBundleId")
1540
        result = Mongo.getDummyPricing(skuBundleId)
1541
        resp.body = dumps(result)
1542
 
1543
class DealObject:
17560 kshitij.so 1544
    def on_post(self, req, resp):
17569 kshitij.so 1545
        update = req.get_param_as_int("update")
17556 kshitij.so 1546
        try:
1547
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1548
        except ValueError:
1549
            raise falcon.HTTPError(falcon.HTTP_400,
1550
                'Malformed JSON',
1551
                'Could not decode the request body. The '
1552
                'JSON was incorrect.')
17569 kshitij.so 1553
        if update is None:    
1554
            result = Mongo.addDealObject(result_json)
1555
        else:
1556
            result = Mongo.updateDealObject(result_json)
1557
 
17556 kshitij.so 1558
        resp.body = dumps(result)
17569 kshitij.so 1559
 
17556 kshitij.so 1560
 
17560 kshitij.so 1561
    def on_get(self, req, resp):
17567 kshitij.so 1562
        edit = req.get_param_as_int("edit")
1563
        if edit is None:
1564
            offset = req.get_param_as_int("offset")
1565
            limit = req.get_param_as_int("limit")
17560 kshitij.so 1566
 
17567 kshitij.so 1567
            result = Mongo.getAllDealObjects(offset, limit)
1568
            resp.body = dumps(result)
1569
        else:
1570
            id = req.get_param_as_int("id")
1571
            result = Mongo.getDealObjectById(id)
1572
            resp.body = dumps(result)
17560 kshitij.so 1573
 
17563 kshitij.so 1574
class DeleteDealObject:
1575
    def on_get(self, req, resp, id):
1576
        result = Mongo.deleteDealObject(int(id))
1577
        resp.body = dumps(result)
1578
 
17611 kshitij.so 1579
class FeaturedDealObject:
1580
    def on_get(self, req, resp):
1581
 
1582
        offset = req.get_param_as_int("offset")
1583
        limit = req.get_param_as_int("limit")
1584
 
1585
        result = Mongo.getAllFeaturedDealsForDealObject(offset, limit)
1586
        resp.body = dumps(result)
1587
 
17556 kshitij.so 1588
 
17611 kshitij.so 1589
    def on_post(self, req, resp):
1590
 
1591
 
1592
        try:
1593
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1594
        except ValueError:
1595
            raise falcon.HTTPError(falcon.HTTP_400,
1596
                'Malformed JSON',
1597
                'Could not decode the request body. The '
1598
                'JSON was incorrect.')
1599
 
17613 kshitij.so 1600
        result = Mongo.addFeaturedDealForDealObject(result_json)
17611 kshitij.so 1601
        resp.body = json.dumps(result, encoding='utf-8')
1602
 
17615 kshitij.so 1603
class DeleteFeaturedDealObject:
1604
    def on_get(self, req, resp, id):
1605
        result = Mongo.deleteFeaturedDealObject(int(id))
1606
        resp.body = dumps(result)
17611 kshitij.so 1607
 
17653 kshitij.so 1608
class SubCategoryFilter:
1609
    def on_get(self, req, resp):
1610
        category_id = req.get_param_as_int("category_id")
1611
        result = Mongo.getSubCategoryForFilter(category_id)
1612
        resp.body = dumps(result)
1613
 
17726 kshitij.so 1614
class DummyLogin:
1615
    def on_post(self,req,resp):
1616
        try:
1617
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1618
        except ValueError:
1619
            raise falcon.HTTPError(falcon.HTTP_400,
1620
                'Malformed JSON',
1621
                'Could not decode the request body. The '
1622
                'JSON was incorrect.')
1623
 
1624
        result = Mongo.dummyLogin(result_json)
1625
        resp.body = json.dumps(result, encoding='utf-8')
17653 kshitij.so 1626
 
17726 kshitij.so 1627
class DummyRegister:
1628
    def on_post(self,req,resp):
1629
        try:
1630
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1631
        except ValueError:
1632
            raise falcon.HTTPError(falcon.HTTP_400,
1633
                'Malformed JSON',
1634
                'Could not decode the request body. The '
1635
                'JSON was incorrect.')
1636
 
1637
        result = Mongo.dummyRegister(result_json)
1638
        resp.body = json.dumps(result, encoding='utf-8')
1639
 
18896 amit.gupta 1640
class TinSearch:
1641
    def on_get(self,req,resp):
1642
        tin = req.get_param("tin")
1643
        result = getTinInfo(tin)
1644
        resp.body = json.dumps(result, encoding='utf-8')
1645
 
1646
 
1647
def getTinInfo(tin):
1648
    try:
19718 amit.gupta 1649
        curData = session.query(tinxys_stats).filter_by(req_date=date.today()).first()
19666 amit.gupta 1650
        if not curData:
1651
            curData = tinxys_stats()
19718 amit.gupta 1652
            curData.total = 0
1653
            curData.request_failed = 0
1654
            curData.invalid_tin = 0
19666 amit.gupta 1655
        curData.total += 1
1656
        tinInfo = {"isError":False}
18995 amit.gupta 1657
        try:
19666 amit.gupta 1658
            params = ['tin','cst','counter_name','counter_address','state','pan','registered_on','cst_status','valid_since']
1659
            url  = "http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber=" + tin + "&searchBy=TIN"
1660
            req = urllib2.Request(url)
1661
            try:
1662
                connection = urllib2.urlopen(req, timeout=10)
1663
            except:
1664
                curData.request_failed += 1
1665
                tinInfo = {"isError":True,
1666
                        "errorMsg": "Some problem occurred. Try again after some time"
1667
                }
1668
                return tinInfo
1669
            pageHtml = connection.read()
1670
            connection.close()        
1671
            doc = pq(pageHtml)
1672
            index=-1
1673
            for ele in pq(doc.find('table')[2])('tr td:nth-child(2)'):
1674
                index += 1
1675
                text = pq(ele).text().strip()
1676
                if not text:
1677
                    text = pq(ele)('div').text().strip()
1678
                tinInfo[params[index]] = text
1679
            print index, "index"
1680
            if index != 8:
1681
                raise
1682
            if not get_mongo_connection().Dtr.tin.find({"tin":tinInfo['tin']}):
1683
                get_mongo_connection().Dtr.tin.insert(tinInfo)
1684
            address = tinInfo['counter_address']
1685
            m = re.match(".*?(\d{6}).*?", address)
1686
            if m:
1687
                tinInfo['pin'] = m.group(1)
1688
                tinInfo['pin_required'] = False
1689
            else:
1690
                tinInfo['pin_required'] = True
1691
 
1692
            print "TinNumber: Successfully fetched details", tin
18995 amit.gupta 1693
        except:
19666 amit.gupta 1694
            curData.invalid_tin = 1
1695
            traceback.print_exc()
18995 amit.gupta 1696
            tinInfo = {"isError":True,
19666 amit.gupta 1697
                        "errorMsg": "Could not find tin"
18995 amit.gupta 1698
            }
19666 amit.gupta 1699
            print "TinNumber: Problem fetching details", tin
1700
        session.commit()
1701
        return tinInfo
1702
    finally:
1703
        session.close()
18896 amit.gupta 1704
 
1705
 
17730 kshitij.so 1706
class UpdateUser:
1707
    def on_post(self,req,resp):
1708
        try:
1709
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1710
        except ValueError:
1711
            raise falcon.HTTPError(falcon.HTTP_400,
1712
                'Malformed JSON',
1713
                'Could not decode the request body. The '
1714
                'JSON was incorrect.')
1715
 
1716
        result = Mongo.updateDummyUser(result_json)
1717
        resp.body = json.dumps(result, encoding='utf-8')
1718
 
1719
class FetchUser:
1720
    def on_get(self,req,resp):
1721
        user_id = req.get_param_as_int("user_id")
1722
        result = Mongo.getDummyUser(user_id)
1723
        resp.body = json.dumps(result, encoding='utf-8')
17928 kshitij.so 1724
 
1725
class SearchSubCategory:
1726
    def on_get(self,req, resp):
18088 kshitij.so 1727
        subCategoryIds = req.get_param("subCategoryId")
17928 kshitij.so 1728
        searchTerm = req.get_param("searchTerm")
1729
        offset = req.get_param_as_int("offset")
1730
        limit = req.get_param_as_int("limit")
17730 kshitij.so 1731
 
18088 kshitij.so 1732
        result = Mongo.getDealsForSearchText(subCategoryIds, searchTerm,offset, limit)
17928 kshitij.so 1733
        resp.body = json.dumps(result, encoding='utf-8')
1734
 
1735
class SearchSubCategoryCount:
1736
    def on_get(self,req, resp):
18088 kshitij.so 1737
        subCategoryIds = req.get_param("subCategoryId")
17928 kshitij.so 1738
        searchTerm = req.get_param("searchTerm")
18088 kshitij.so 1739
        result = Mongo.getCountForSearchText(subCategoryIds, searchTerm)
17928 kshitij.so 1740
        resp.body = json.dumps(result, encoding='utf-8')
18090 manas 1741
 
1742
class MessageEncryption:
1743
 
1744
    def on_get(self,req,resp):
1745
        message_type = req.get_param("type")
18093 manas 1746
        if message_type == 'encrypt':
18090 manas 1747
            encryption_data = req.get_param("data")
18101 manas 1748
            encrypted_data = encryptMessage(base64.decodestring(encryption_data))
18090 manas 1749
            resp.body =  json.dumps({"result":{"value":encrypted_data}}, encoding='utf-8')
1750
 
18093 manas 1751
        elif message_type == 'decrypt':
18090 manas 1752
            decryption_data = req.get_param("data")
1753
            decrypted_data = decryptMessage(decryption_data)
1754
            resp.body =  json.dumps({"result":{"value":decrypted_data}}, encoding='utf-8')
1755
 
1756
        else:
1757
            resp.body = json.dumps({}, encoding='utf-8')
18256 manas 1758
 
1759
class GetUserCrmApplication:
19442 manas 1760
 
18256 manas 1761
    def on_get(self,req,resp):
18329 manas 1762
        global USER_DETAIL_MAP
18256 manas 1763
        project_name = req.get_param("project_name")
18329 manas 1764
        USER_DETAIL_MAP[project_name]+=1
18386 manas 1765
        lgr.info( "USER_DETAIL_CALL_COUNTER " +  str(USER_DETAIL_MAP[project_name]))
18329 manas 1766
        retryFlag=False
1767
        if USER_DETAIL_MAP[project_name] % TOTAL_USER >= USER_CRM_DEFAULT_FRESH_FACTOR:
1768
                retryFlag=True
1769
        if project_name == 'accs_cart':
18792 manas 1770
            project_id=1
1771
        elif project_name == 'accs_active':
1772
            project_id=2
1773
        elif project_name == 'accs_order':
1774
            project_id=3
19442 manas 1775
        elif project_name == 'accs_cashback_scheme':
1776
            project_id=4
20133 rajender 1777
        elif project_name == 'inactive_users':
1778
            project_id=5
18792 manas 1779
        if retryFlag:
1780
            user = self.getRetryUser(project_id)
1781
        else:
1782
            user = self.getNewUser(project_id)
1783
 
1784
        if user is None:
1785
            resp.body ={}
1786
        else:        
1787
            user.status =  'assigned'
1788
            user.agent_id = req.get_param("agent_id")
1789
            user.counter=1
1790
            user.modified = datetime.now()
1791
            session.commit()
1792
            resp.body = json.dumps(todict(getUserObject(user)), encoding='utf-8')
1793
            session.close()
18620 manas 1794
 
18329 manas 1795
    def getRetryUser(self,projectId,failback=True):
1796
        status = "retry"
18367 manas 1797
        user = session.query(UserCrmCallingData).filter_by(status=status,project_id=projectId).filter(UserCrmCallingData.next_call_time<=datetime.now()).filter(~(UserCrmCallingData.contact1).like('')).order_by(UserCrmCallingData.next_call_time).with_lockmode("update").first()
18329 manas 1798
 
1799
        if user is not None:
18334 manas 1800
            lgr.info( "getRetryUser " + str(user.id))
18329 manas 1801
        else:
1802
            if failback:
18334 manas 1803
                user = self.getNewUser(projectId,False)
18329 manas 1804
                return user
1805
            else:
1806
                return None
1807
        return user
18291 manas 1808
 
18329 manas 1809
 
18331 manas 1810
    def getNewUser(self,projectId,failback=True):
18329 manas 1811
            user = None 
1812
            try:
18416 manas 1813
                user = session.query(UserCrmCallingData).filter_by(project_id=projectId).filter(UserCrmCallingData.status=='new').filter(UserCrmCallingData.pincode_servicable==True).filter(UserCrmCallingData.user_available==0).filter(UserCrmCallingData.contact1!=None).filter(~(UserCrmCallingData.contact1).like('')).order_by(UserCrmCallingData.next_call_time).order_by(UserCrmCallingData.id).with_lockmode("update").first()
18334 manas 1814
                if user is None:
1815
                    insertUserCrmData(projectId)
18416 manas 1816
                    user = session.query(UserCrmCallingData).filter_by(project_id=projectId).filter(UserCrmCallingData.status=='new').filter(UserCrmCallingData.pincode_servicable==True).filter(~(UserCrmCallingData.contact1).like('')).filter(UserCrmCallingData.user_available==0).filter(UserCrmCallingData.contact1!=None).order_by(UserCrmCallingData.next_call_time).order_by(UserCrmCallingData.id).with_lockmode("update").first()
18334 manas 1817
                    if user is not None:
1818
                        lgr.info( "getNewUser " + str(user.id))
1819
                    else:
1820
                        if failback:
1821
                            user = self.getRetryUser(projectId,False)
1822
                            return user
1823
                        else:
1824
                            return None
18329 manas 1825
            except:
1826
                print traceback.print_exc()
1827
            return user    
18386 manas 1828
 
18291 manas 1829
    def on_post(self, req, resp):
1830
        returned = False
1831
        self.agentId = req.get_param("agent_id")
1832
        project_name = req.get_param("project_name")
18637 manas 1833
 
18329 manas 1834
        if project_name == 'accs_cart':
18637 manas 1835
            project_id=1
1836
        elif project_name == 'accs_active':
1837
            project_id=2            
1838
        elif project_name == 'accs_order':
1839
            project_id=3            
19442 manas 1840
        elif project_name == 'accs_cashback_scheme':
1841
            project_id=4
20133 rajender 1842
        elif project_name == 'inactive_users':
1843
            project_id=5
19442 manas 1844
 
18637 manas 1845
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1846
        lgr.info( "Request ----\n"  + str(jsonReq))
1847
        self.jsonReq = jsonReq
1848
        self.callType="default"
1849
        callLaterAccs = self.callLaterAccs
20133 rajender 1850
        invalidNumber = self.invalidNumber
18637 manas 1851
        accsDisposition = self.accsDisposition
1852
        accsOrderDisposition=self.accsOrderDisposition
20133 rajender 1853
        otherreason = self.otherreason
1854
        willplaceorder = self.willplaceorder
20147 rajender 1855
        verifiedLinkSent = self.verifiedLinkSent
20133 rajender 1856
        orderdiffaccount = self.orderdiffaccount
1857
        businessclosed = self.businessclosed
1858
        appuninstalled = self.appuninstalled
18637 manas 1859
        self.userId = int(jsonReq.get('user_id'))
1860
        try:
1861
            self.user = session.query(UserCrmCallingData).filter_by(user_id=self.userId).filter(UserCrmCallingData.project_id==project_id).first()
1862
            self.callDisposition = jsonReq.get('calldispositiontype')
1863
            self.callHistoryCrm = CallHistoryCrm()
1864
            self.callHistoryCrm.agent_id=self.agentId
1865
            self.callHistoryCrm.project_id = project_id
1866
            self.callHistoryCrm.call_disposition = self.callDisposition
1867
            self.callHistoryCrm.user_id=self.userId
1868
            self.callHistoryCrm.duration_sec = int(jsonReq.get("callduration"))
1869
            self.callHistoryCrm.disposition_comments = jsonReq.get('calldispositioncomments')
1870
            self.callHistoryCrm.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
1871
            self.callHistoryCrm.mobile_number = jsonReq.get('number')
1872
            self.inputs = jsonReq.get("inputs")
1873
            dispositionMap = {  'call_later':callLaterAccs,
1874
                        'ringing_no_answer':callLaterAccs,
1875
                        'not_reachable':callLaterAccs,
1876
                        'switch_off':callLaterAccs,
1877
                        'technical_issue':accsDisposition,
1878
                        'pricing_issue':accsDisposition,
1879
                        'shipping_issue':accsDisposition,
1880
                        'internet_issue':accsDisposition,
1881
                        'checking_price':accsDisposition,
1882
                        'order_process':accsDisposition,
1883
                        'placed_order':accsDisposition,
1884
                        'place_order':accsDisposition,
1885
                        'product_availability':accsOrderDisposition,
1886
                        'return_replacement':accsOrderDisposition,
1887
                        'already_purchased':accsOrderDisposition,
1888
                        'product_quality_issue':accsOrderDisposition,
1889
                        'delayed_delivery':accsOrderDisposition,
18671 manas 1890
                        'other_complaint':accsOrderDisposition,
19442 manas 1891
                        'scheme_not_clear':accsOrderDisposition,
20133 rajender 1892
                        'not_dealing_accessories':accsOrderDisposition,
1893
                        'other_reason':otherreason,
1894
                        'app_uninstalled':appuninstalled,
1895
                        'will_place_order':willplaceorder,
1896
                        'order_diff_acc':orderdiffaccount,
1897
                        'not_retailer':invalidNumber,
1898
                        'business_closed':businessclosed,
1899
                        'invalid_no':invalidNumber,
1900
                        'wrong_no':invalidNumber,
1901
                        'hang_up':invalidNumber,
1902
                        'service_center_retailer':invalidNumber,
20147 rajender 1903
                        'recharge_retailer':invalidNumber,
1904
                        'verified_link_sent':verifiedLinkSent
20133 rajender 1905
 
1906
 
18637 manas 1907
                      }
1908
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
1909
        finally:
1910
            session.close()
1911
 
1912
        if returned:
1913
            resp.body = "{\"result\":\"success\"}"
1914
        else:
1915
            resp.body = "{\"result\":\"failed\"}"
1916
 
20147 rajender 1917
    def verifiedLinkSent(self,):
1918
        users_referrer, = session.query(Users.referrer).filter_by(id=self.userId).first()
1919
        if users_referrer is not None:
1920
            activationCode=session.query(Activation_Codes).filter_by(code=users_referrer).first()
1921
            if activationCode is not None:
1922
                activationCode.status = False
1923
        self.user.status='done'
1924
        self.user.modified = datetime.now()
1925
        self.user.disposition=self.callDisposition
1926
        if self.callHistoryCrm.disposition_description is not None:
1927
            self.callHistoryCrm.disposition_description = 'App link sent via ' + self.callHistoryCrm.disposition_description
1928
        else: 
1929
            self.callHistoryCrm.disposition_description = 'App link sent'
1930
        session.commit()
1931
        return True
1932
 
1933
 
18628 manas 1934
    def accsOrderDisposition(self):
1935
        self.user.status='done'
1936
        self.user.user_available = 1
1937
        self.user.disposition=self.callDisposition
1938
        self.user.modified = datetime.now()
18712 manas 1939
        a = CrmTicketDtr()
18628 manas 1940
        if self.callDisposition == 'product_availability':
1941
            self.callHistoryCrm.disposition_description='Product Not available'
1942
        elif self.callDisposition == 'return_replacement':
1943
            self.callHistoryCrm.disposition_description='Return or replacement pending'
18923 manas 1944
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18713 manas 1945
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)
18628 manas 1946
        elif self.callDisposition == 'already_purchased':
1947
            self.callHistoryCrm.disposition_description='Already purchased required stock'
19442 manas 1948
        elif self.callDisposition == 'scheme_not_clear':
1949
            self.callHistoryCrm.disposition_description='Scheme Not Clear to the User'
18628 manas 1950
        elif self.callDisposition == 'product_quality_issue':
1951
            self.callHistoryCrm.disposition_description='Product Quality issue'
18923 manas 1952
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18713 manas 1953
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)            
18628 manas 1954
        elif self.callDisposition == 'delayed_delivery':
18637 manas 1955
            self.callHistoryCrm.disposition_description='Delayed Delivery' 
18923 manas 1956
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18713 manas 1957
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)   
18628 manas 1958
        elif self.callDisposition == 'other_complaint':
18637 manas 1959
            self.callHistoryCrm.disposition_description='Other complaint with profitmandi'
18923 manas 1960
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18713 manas 1961
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)
18671 manas 1962
        elif self.callDisposition == 'not_dealing_accessories':
1963
            self.callHistoryCrm.disposition_description='Not Dealing in Accessories/Not Interested'        
18628 manas 1964
        session.commit()
1965
        jdata = self.inputs
1966
        jdata = json.loads(jdata)
1967
        if jdata:
1968
            for d in jdata:
1969
                for key, value in d.iteritems():
1970
                    productpricingInputs = ProductPricingInputs()
1971
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
1972
                    productpricingInputs.agent_id = self.callHistoryCrm.agent_id
1973
                    productpricingInputs.disposition_id = self.callHistoryCrm.id
1974
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
1975
                    productpricingInputs.call_disposition = self.callHistoryCrm.call_disposition
1976
                    productpricingInputs.project_id = self.callHistoryCrm.project_id
1977
                    productpricingInputs.product_input = key
1978
                    productpricingInputs.pricing_input = value
1979
            session.commit()        
1980
        return True
1981
 
20133 rajender 1982
    def willplaceorder(self,):
20136 rajender 1983
        self.user.status='done'
1984
        self.user.modified = datetime.now()
1985
        self.user.disposition=self.callDisposition
1986
        if self.callHistoryCrm.disposition_description is None:
1987
            self.callHistoryCrm.disposition_description = 'User will place order from now' 
20133 rajender 1988
        session.commit()
1989
        return True
20136 rajender 1990
 
20133 rajender 1991
    def orderdiffaccount(self,):
20136 rajender 1992
        self.user.status='done'
1993
        self.user.modified = datetime.now()
1994
        self.user.disposition=self.callDisposition
1995
        if self.callHistoryCrm.disposition_description is None:
1996
            self.callHistoryCrm.disposition_description = 'Placing Order from Different Account' 
20133 rajender 1997
        session.commit()
1998
        return True
20136 rajender 1999
 
20133 rajender 2000
 
2001
    def businessclosed(self,):
20136 rajender 2002
        self.user.status='done'
2003
        self.user.modified = datetime.now()
2004
        self.user.disposition=self.callDisposition
2005
        if self.callHistoryCrm.disposition_description is None:
2006
            self.callHistoryCrm.disposition_description = 'Business Closed' 
20133 rajender 2007
        session.commit()
2008
        return True
20136 rajender 2009
 
20133 rajender 2010
 
2011
    def appuninstalled(self,):
20136 rajender 2012
        self.user.status='done'
2013
        self.user.modified = datetime.now()
2014
        self.user.disposition=self.callDisposition
2015
        if self.callHistoryCrm.disposition_description is None:
2016
            self.callHistoryCrm.disposition_description = 'User uninstalled application' 
2017
        a = CrmTicketDtr()
2018
        a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)
20133 rajender 2019
        session.commit()
2020
        return True
20136 rajender 2021
 
2022
 
20133 rajender 2023
    def invalidNumber(self,):
20136 rajender 2024
 
20133 rajender 2025
        self.user.modified = datetime.now()
2026
        if self.callDisposition == 'invalid_no':
20136 rajender 2027
 
20133 rajender 2028
            self.user.disposition=self.callDisposition
2029
            self.callHistoryCrm.disposition_description = 'Invalid Number'
2030
        elif self.callDisposition == 'wrong_no':
20136 rajender 2031
 
20133 rajender 2032
            self.user.disposition=self.callDisposition
2033
            self.callHistoryCrm.disposition_description = 'Wrong Number'
2034
        elif self.callDisposition == 'hang_up':
20136 rajender 2035
 
20133 rajender 2036
            self.user.disposition=self.callDisposition
2037
            self.callHistoryCrm.disposition_description = 'Hang Up'
2038
        elif self.callDisposition == 'retailer_not_interested':
20136 rajender 2039
 
20133 rajender 2040
            self.user.disposition=self.callDisposition
2041
            if self.callHistoryCrm.disposition_description is None:
2042
                self.callHistoryCrm.disposition_description = 'NA'
2043
            self.callHistoryCrm.disposition_description = 'Reason Retailer Not Interested ' + self.callHistoryCrm.disposition_description
2044
        elif self.callDisposition == 'recharge_retailer':
20136 rajender 2045
 
20133 rajender 2046
            self.user.disposition=self.callDisposition
2047
            self.callHistoryCrm.disposition_description = 'Recharge related. Not a retailer '
2048
        elif self.callDisposition == 'service_center_retailer':
20136 rajender 2049
 
20133 rajender 2050
            self.user.disposition=self.callDisposition
2051
            self.callHistoryCrm.disposition_description = 'Service Center related. Not a retailer'
2052
        elif self.callDisposition == 'not_retailer':
20136 rajender 2053
 
20133 rajender 2054
            self.user.disposition=self.callDisposition
2055
            self.callHistoryCrm.disposition_description = 'Not a retailer'    
2056
        session.commit()
2057
        return True  
2058
 
2059
    def otherreason(self,):
20136 rajender 2060
        self.user.status='done'
20133 rajender 2061
        self.user.modified = datetime.now()
2062
        self.user.disposition=self.callDisposition
2063
        if self.callHistoryCrm.disposition_description is None:
2064
            self.callHistoryCrm.disposition_description = 'Other Reasons' 
2065
        session.commit()
2066
        return True
2067
 
2068
 
18291 manas 2069
    def accsDisposition(self):
2070
        self.user.status='done'
2071
        self.user.user_available = 1
2072
        self.user.disposition=self.callDisposition
2073
        self.user.modified = datetime.now()
2074
        if self.callDisposition == 'technical_issue':
2075
            self.callHistoryCrm.disposition_description='Technical issue at Profitmandi'
18923 manas 2076
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18716 manas 2077
            a = CrmTicketDtr()
2078
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)
18291 manas 2079
        elif self.callDisposition == 'pricing_issue':
2080
            self.callHistoryCrm.disposition_description='Pricing Issue(High)'
2081
        elif self.callDisposition == 'shipping_issue':
2082
            self.callHistoryCrm.disposition_description='Shipping charges related issue'
2083
        elif self.callDisposition == 'internet_issue':
2084
            self.callHistoryCrm.disposition_description='Internet issue at user end'
2085
        elif self.callDisposition == 'checking_price':
2086
            self.callHistoryCrm.disposition_description='Checking price'    
2087
        elif self.callDisposition == 'order_process':
2088
            self.callHistoryCrm.disposition_description='Order Process inquery'    
2089
        elif self.callDisposition == 'placed_order':
2090
            self.callHistoryCrm.disposition_description='Placed Order from Different Account'    
2091
        elif self.callDisposition == 'place_order':
2092
            self.callHistoryCrm.disposition_description='Will Place Order'            
2093
        session.commit()
18360 manas 2094
        jdata = self.inputs
18361 manas 2095
        jdata = json.loads(jdata)
18350 manas 2096
        if jdata:
2097
            for d in jdata:
18360 manas 2098
                for key, value in d.iteritems():
18350 manas 2099
                    productpricingInputs = ProductPricingInputs()
2100
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
2101
                    productpricingInputs.agent_id = self.callHistoryCrm.agent_id
2102
                    productpricingInputs.disposition_id = self.callHistoryCrm.id
2103
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
2104
                    productpricingInputs.call_disposition = self.callHistoryCrm.call_disposition
2105
                    productpricingInputs.project_id = self.callHistoryCrm.project_id
2106
                    productpricingInputs.product_input = key
2107
                    productpricingInputs.pricing_input = value
2108
            session.commit()        
18291 manas 2109
        return True
2110
 
2111
    def callLaterAccs(self):
18329 manas 2112
        self.user.status='retry'
2113
        self.user.modified = datetime.now()
18291 manas 2114
        if self.callDisposition == 'call_later':
18310 manas 2115
            if self.callHistoryCrm.disposition_comments is not None:
18321 manas 2116
                self.user.next_call_time = datetime.strptime(self.callHistoryCrm.disposition_comments, '%d/%m/%Y %H:%M:%S')
18310 manas 2117
                self.callHistoryCrm.disposition_description = 'User requested to call'
2118
                self.callHistoryCrm.disposition_comments = self.callHistoryCrm.disposition_comments
18291 manas 2119
            else:
2120
                self.user.next_call_time = self.callHistoryCrm.call_time + timedelta(days=1)
18310 manas 2121
                self.callHistoryCrm.disposition_description = 'Call Scheduled'
2122
                self.callHistoryCrm.disposition_comments = datetime.strftime(self.user.next_call_time, '%d/%m/%Y %H:%M:%S')
18291 manas 2123
        else: 
18310 manas 2124
            self.callHistoryCrm.disposition_description = 'User was not contactable'
18291 manas 2125
            if self.callDisposition == 'ringing_no_answer':
2126
                if self.user.disposition == 'ringing_no_answer':
2127
                    self.user.retry_count += 1
2128
                else:
2129
                    self.user.disposition = 'ringing_no_answer'
2130
                    self.user.retry_count = 1
2131
            else:
2132
                if self.user.disposition == 'ringing_no_answer':
2133
                    pass
2134
                else:
2135
                    self.user.disposition = 'not_reachable'
2136
                self.user.retry_count += 1
2137
                self.user.invalid_retry_count += 1
2138
 
18306 manas 2139
            retryConfig = session.query(RetryConfig).filter_by(call_type=self.callType, disposition_type=self.user.disposition, retry_count=self.user.retry_count).first()
2140
            if retryConfig is not None:
2141
                self.user.next_call_time = self.callHistoryCrm.call_time + timedelta(minutes = retryConfig.minutes_ahead)
2142
                self.callHistoryCrm.disposition_description = 'Call scheduled on ' + datetime.strftime(self.user.next_call_time, '%d/%m/%Y %H:%M:%S')
2143
            else:
2144
                self.user.status = 'failed'
18335 manas 2145
                self.user.user_available=1
18306 manas 2146
                self.callHistoryCrm.disposition_description = 'Call failed as all attempts exhausted'
18329 manas 2147
        self.user.disposition=self.callDisposition        
18291 manas 2148
        session.commit()
18347 manas 2149
        jdata =self.inputs
18361 manas 2150
        jdata = json.loads(jdata)
18350 manas 2151
        if jdata: 
2152
            for d in jdata:
18360 manas 2153
                for key, value in d.iteritems():
18350 manas 2154
                    productpricingInputs = ProductPricingInputs()
2155
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
2156
                    productpricingInputs.agent_id = self.callHistoryCrm.agent_id
2157
                    productpricingInputs.disposition_id = self.callHistoryCrm.id
2158
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
2159
                    productpricingInputs.call_disposition = self.callHistoryCrm.call_disposition
2160
                    productpricingInputs.project_id = self.callHistoryCrm.project_id
2161
                    productpricingInputs.product_input = key
2162
                    productpricingInputs.pricing_input = value
2163
            session.commit()        
18291 manas 2164
        return True
2165
 
18266 manas 2166
def insertUserCrmData(project_id):
2167
    if project_id==1:  
2168
        getCartDetailsUser()
18386 manas 2169
    if project_id==2:  
2170
        getCartTabsUser()
18620 manas 2171
    if project_id==3:
2172
        getAccsRepeatUsers(project_id)
19442 manas 2173
    if project_id==4:
2174
        getAccsSchemeCashback(project_id)
20133 rajender 2175
    if project_id==5:
2176
        getInactiveUsers(project_id)
19442 manas 2177
 
20133 rajender 2178
def getInactiveUsers(project_id):
2179
    PRIOPRITIZING_USER_QUERY = "select d.user_id, count(d.user_id),x.totalorder from daily_visitors d join users u on d.user_id=u.id left join (select user_id,count(*) as totalorder from allorder group by user_id order by totalorder desc) as x on d.user_id=x.user_id where lower(u.referrer) not like 'emp%' and d.user_id not in (select user_id from daily_visitors where visited > '2016-03-01') group by d.user_id having count(*) >=5 order by x.totalorder desc, count(d.user_id) desc;"
2180
    userFinalList=[]
2181
    result = fetchResult(PRIOPRITIZING_USER_QUERY)
2182
    for r in result:
2183
        userFinalList.append(r[0])
2184
    for i in userFinalList:
2185
        try:
2186
            userId=i
2187
            userPresent = session.query(UserCrmCallingData).filter_by(user_id=userId).order_by(desc(UserCrmCallingData.modified)).first()
2188
            if userPresent is not None:
2189
                if userPresent.user_available==1:
2190
                    if userPresent.project_id==project_id:
2191
                        continue
2192
                    elif userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
2193
                        continue
2194
                else:
2195
                    continue         
2196
            userMasterData = UserCrmCallingData()
2197
            userMasterData.user_id = userId 
2198
            userMasterData.name =getUsername(userId) 
2199
            userMasterData.project_id = project_id
2200
            userMasterData.user_available=0
2201
            userMasterData.contact1 = getUserContactDetails(userId)
2202
            userMasterData.counter = 0
2203
            userMasterData.retry_count=0
2204
            userMasterData.invalid_retry_count=0
2205
            userMasterData.created = datetime.now()
2206
            userMasterData.modified = datetime.now()
2207
            userMasterData.status = 'new'
2208
            userMasterData.pincode_servicable = checkPincodeServicable(userId)
2209
            session.commit()
2210
        except:
2211
            print traceback.print_exc()
2212
        finally:
2213
            session.close()
2214
 
2215
 
19442 manas 2216
def getAccsSchemeCashback(project_id):
2217
    userMasterMap={}
2218
    skipUserList=[]
19444 manas 2219
    query = "select id from users where lower(referrer) in ('emp01','emp99','emp88')"
19442 manas 2220
    skipUsersresult = fetchResult(query)
2221
    for skipUser in skipUsersresult:
2222
        skipUserList.append(skipUser[0])
2223
    queryFilter = {"user_id":{"$nin":skipUserList}}
2224
    result = get_mongo_connection().Catalog.PromoOffer.find(queryFilter)
2225
    userMasterList =[]
2226
    for r in result:
2227
        userMasterList.append(r.get('user_id'))
2228
    queryfilter ={"url":{"$regex" : "http://api.profittill.com/categories/target"}}
2229
    result = get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilter).distinct('user_id')
2230
    userSeenList=[]
2231
    for r in result:
2232
        userSeenList.append(r)
2233
    finalUserList  = list(set(userMasterList) - set(userSeenList))
2234
    queryFilter = {"user_id":{"$in":finalUserList}}
2235
    result = get_mongo_connection().Catalog.PromoOffer.find(queryFilter)
2236
    for r in result:
2237
        userMasterMap[r.get('user_id')] = r.get('target2')
2238
    d_sorted = sorted(zip(userMasterMap.values(), userMasterMap.keys()),reverse=True)
2239
    counter=0
2240
    for i in d_sorted:
2241
        try:
2242
            userId=i[1]
2243
            if counter==20:
2244
                break
20133 rajender 2245
 
2246
#             userPresent = isUserAvailable(CRM_PROJECTS_USER_AVAILABILITY.get(project_id))
19442 manas 2247
            userPresent = session.query(UserCrmCallingData).filter_by(user_id=userId).order_by(desc(UserCrmCallingData.modified)).first()
2248
            if userPresent is not None:
2249
                if userPresent.user_available==1:
2250
                    if userPresent.project_id==project_id:
2251
                        continue                        
2252
                    elif userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
2253
                        continue
2254
                else:
2255
                    continue               
2256
            counter=counter+1
2257
            userMasterData = UserCrmCallingData()
2258
            userMasterData.user_id = userId 
2259
            userMasterData.name =getUsername(userId) 
2260
            userMasterData.project_id = project_id
2261
            userMasterData.user_available=0
2262
            userMasterData.contact1 = getUserContactDetails(userId)
2263
            userMasterData.counter = 0
2264
            userMasterData.retry_count=0
2265
            userMasterData.invalid_retry_count=0
2266
            userMasterData.created = datetime.now()
2267
            userMasterData.modified = datetime.now()
2268
            userMasterData.status = 'new'
2269
            userMasterData.pincode_servicable = checkPincodeServicable(userId)
2270
            session.commit()
2271
        except:
2272
            print traceback.print_exc()
2273
        finally:
2274
            session.close()
2275
 
18620 manas 2276
def getAccsRepeatUsers(project_id):
2277
 
2278
    usersMasterList=[]
2279
    ACCS_ALL_ORDERS = "select distinct user_id from allorder where category in ('Accs','Accessories') and store_id='spice';"
2280
    result = fetchResult(ACCS_ALL_ORDERS)
2281
    for r in result:
2282
        usersMasterList.append(r[0])
2283
 
2284
    ACCS_LAST_FIFTEEN_DAYS = "select distinct user_id from allorder where category in ('Accs','Accessories') and store_id='spice' and (date(created_on) between date(curdate() - interval 15 day) and date(curdate())) order by user_id;"
2285
    result = fetchResult(ACCS_LAST_FIFTEEN_DAYS)
2286
    for r in result:
2287
        if r[0] in usersMasterList:
2288
            usersMasterList.remove(r[0])        
2289
 
2290
    PRIOPRITIZING_USER_QUERY = "select user_id from allorder where category in ('Accs','Accessories')and store_id ='spice' and user_id in (%s)" % ",".join(map(str,usersMasterList)) + "group by user_id order by sum(amount_paid) desc;"
2291
    userFinalList=[]
2292
    result = fetchResult(PRIOPRITIZING_USER_QUERY)
2293
    for r in result:
2294
        userFinalList.append(r[0])
2295
 
2296
    counter=0
2297
    for i in userFinalList:
2298
        try:
2299
            userId=i
18628 manas 2300
            if counter==20:
18620 manas 2301
                break
2302
            userPresent = session.query(UserCrmCallingData).filter_by(user_id=userId).order_by(desc(UserCrmCallingData.modified)).first()
2303
            if userPresent is not None:
2304
                if userPresent.user_available==1:
2305
                    if userPresent.project_id==project_id:
2306
                        if userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
2307
                            continue
2308
                        else:
2309
                            pass    
18792 manas 2310
                    elif userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
18620 manas 2311
                        continue
2312
                else:
2313
                    continue     
2314
            counter=counter+1
2315
            userMasterData = UserCrmCallingData()
2316
            userMasterData.user_id = userId 
2317
            userMasterData.name =getUsername(userId) 
2318
            userMasterData.project_id = project_id
2319
            userMasterData.user_available=0
2320
            userMasterData.contact1 = getUserContactDetails(userId)
2321
            userMasterData.counter = 0
2322
            userMasterData.retry_count=0
2323
            userMasterData.invalid_retry_count=0
2324
            userMasterData.created = datetime.now()
2325
            userMasterData.modified = datetime.now()
2326
            userMasterData.status = 'new'
2327
            userMasterData.pincode_servicable = checkPincodeServicable(userId)
2328
            session.commit()
2329
        except:
2330
            print traceback.print_exc()
2331
        finally:
2332
            session.close()
2333
 
18256 manas 2334
def getCartDetailsUser():
2335
    userList=[]
2336
    orderUserList=[]
18818 manas 2337
    #userMasterMap={}
18256 manas 2338
    queryfilter = {"$and":
2339
                   [
18792 manas 2340
                    {'created':{"$gte":(to_java_date(datetime.now())-3*86400000)}},
18256 manas 2341
                    {'created':{"$lte":(to_java_date(datetime.now())- 43200000)}},
2342
                    {"url":{"$regex" : "http://api.profittill.com/cartdetails"}}
2343
                    ]
2344
                   }
2345
    result = get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilter).distinct('user_id')
2346
 
2347
    for r in result:
2348
        userList.append(r)
2349
 
18301 manas 2350
    myquery = "select a.user_id from allorder a join users u on a.user_id=u.id where a.store_id='spice' and (a.category='Accs' or a.category='Accessories') and u.referrer not like 'emp%%' and u.mobile_number IS NOT NULL and a.user_id in (%s)" % ",".join(map(str,userList)) + " UNION select id from users where lower(referrer) like 'emp%'"
2351
 
18256 manas 2352
    result = fetchResult(myquery)
2353
    for r in result:
18301 manas 2354
        orderUserList.append(r[0])
18256 manas 2355
    finalUserList  = list(set(userList) - set(orderUserList))
2356
 
18792 manas 2357
    userCartIdMap={}
2358
    fetchCartId = "select user_id,account_key from user_accounts where account_type='cartId' and user_id in (%s)" % ",".join(map(str,finalUserList))
2359
    result = fetchResult(fetchCartId)
2360
    for r in result:
18818 manas 2361
        userCartIdMap[long(r[1])] = long(r[0])
18843 manas 2362
    client = CatalogClient("catalog_service_server_host_prod","catalog_service_server_port").get_client()
18792 manas 2363
    userMapReturned = client.getCartByValue(userCartIdMap.keys())
18818 manas 2364
    userFinalList=[]
2365
    for i in userMapReturned:
2366
        userFinalList.append(userCartIdMap.get(i))
18792 manas 2367
#     queryfilternew = {"$and":
2368
#                    [
2369
#                     {'user_id':{"$in":finalUserList}},
2370
#                     {'created':{"$gte":(to_java_date(datetime.now())-2*86400000)}},
2371
#                     {'created':{"$lte":(to_java_date(datetime.now())- 43200000)}},
2372
#                     {"url":{"$regex" : "http://api.profittill.com/cartdetails"}}
2373
#                     ]
2374
#                    }
2375
#     itemIds = list(get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilternew))
2376
#      
2377
#     for i in itemIds:
2378
#         if(userMasterMap.has_key(i.get('user_id'))):
2379
#             if userMasterMap.get(i.get('user_id')) > i.get('created'):
2380
#                 userMasterMap[i.get('user_id')]=i.get('created')
2381
#         else:
2382
#             userMasterMap[i.get('user_id')]=i.get('created')
2383
#             
2384
#     d_sorted = sorted(zip(userMasterMap.values(), userMasterMap.keys()))
18818 manas 2385
    addUserToTable(userFinalList,1)
18256 manas 2386
 
18301 manas 2387
def addUserToTable(userList,projectId):
18266 manas 2388
    counter=0
18301 manas 2389
    for i in userList:
2390
        try:
18792 manas 2391
            userId=i
18412 manas 2392
            if counter==20:
18301 manas 2393
                break
2394
            userPresent = session.query(UserCrmCallingData).filter_by(user_id=userId).order_by(desc(UserCrmCallingData.modified)).first()
2395
            if userPresent is not None:
2396
                if userPresent.user_available==1:
2397
                    if userPresent.project_id==projectId:
2398
                        continue
18792 manas 2399
                    elif userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
18301 manas 2400
                        continue
18306 manas 2401
                else:
2402
                    continue     
18266 manas 2403
            counter=counter+1
2404
            userMasterData = UserCrmCallingData()
2405
            userMasterData.user_id = userId 
2406
            userMasterData.name =getUsername(userId) 
18301 manas 2407
            userMasterData.project_id = projectId
18277 manas 2408
            userMasterData.user_available=0
18266 manas 2409
            userMasterData.contact1 = getUserContactDetails(userId)
2410
            userMasterData.counter = 0
18318 manas 2411
            userMasterData.retry_count=0
2412
            userMasterData.invalid_retry_count=0
18266 manas 2413
            userMasterData.created = datetime.now()
2414
            userMasterData.modified = datetime.now()
2415
            userMasterData.status = 'new'
2416
            userMasterData.pincode_servicable = checkPincodeServicable(userId)
2417
            session.commit()
18301 manas 2418
        except:
2419
            print traceback.print_exc()
2420
        finally:
2421
            session.close()    
2422
 
18256 manas 2423
def getCartTabsUser():
18346 manas 2424
    userMasterList=[]
2425
    userList = []
18256 manas 2426
    userMasterMap={}
2427
    queryfilter = {"$and":
2428
                   [
2429
                    {'created':{"$gte":(to_java_date(datetime.now())-2*86400000)}},
2430
                    {'created':{"$lte":(to_java_date(datetime.now())- 43200000)}},
2431
                    {"url":{"$regex" : "http://api.profittill.com/category/6"}}
2432
                    ]
2433
                   }
2434
    result = get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilter).distinct('user_id')
2435
 
2436
    for r in result:
18346 manas 2437
        userMasterList.append(r)
2438
 
2439
    queryfilterVisistedCart = {"$and":
2440
                   [
18386 manas 2441
                    {'user_id':{"$in":userMasterList}},
18346 manas 2442
                    {"url":{"$regex" : "http://api.profittill.com/cartdetails"}}
2443
                    ]
2444
                  }
18386 manas 2445
    result = get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilterVisistedCart).distinct('user_id')   
18346 manas 2446
    for r in result:
18256 manas 2447
        userList.append(r)
2448
 
18416 manas 2449
    myquery = "select user_id from allorder where store_id='spice' and (category='Accs' or category='Accessories') and user_id in (%s)" % ",".join(map(str,userMasterList)) + " UNION select id from users where lower(referrer) like 'emp%'"
18256 manas 2450
 
2451
    result = fetchResult(myquery)
2452
    for r in result:
18346 manas 2453
        if r[0] in userList:
2454
            continue
2455
        userList.append(r[0])
18386 manas 2456
 
18346 manas 2457
    finalUserList  = list(set(userMasterList) - set(userList))
18386 manas 2458
 
18256 manas 2459
    queryfilternew = {"$and":
2460
                   [
2461
                    {'user_id':{"$in":finalUserList}},
2462
                    {'created':{"$gte":(to_java_date(datetime.now())-2*86400000)}},
2463
                    {'created':{"$lte":(to_java_date(datetime.now())- 43200000)}},
2464
                    {"url":{"$regex" : "http://api.profittill.com/category/6"}}
2465
                    ]
2466
                   }
2467
    itemIds = list(get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilternew))
2468
 
2469
    for i in itemIds:
2470
        if(userMasterMap.has_key(i.get('user_id'))):
2471
            if userMasterMap.get(i.get('user_id')) > i.get('created'):
2472
                userMasterMap[i.get('user_id')]=i.get('created')
2473
        else:
2474
            userMasterMap[i.get('user_id')]=i.get('created')
2475
 
2476
    d_sorted = sorted(zip(userMasterMap.values(), userMasterMap.keys()))
18792 manas 2477
    userFinalList=[]
2478
    for i in d_sorted:
2479
        userFinalList.append(i[1])
2480
    addUserToTable(userFinalList,2)
18346 manas 2481
 
18266 manas 2482
def getUserContactDetails(userId):
18792 manas 2483
    r = session.query(Users.mobile_number).filter_by(id=userId).first()
2484
    if r is None:
2485
        return None
2486
    else:
2487
        return r[0]
18712 manas 2488
 
18266 manas 2489
def getUsername(userId):
18792 manas 2490
    r = session.query(Users.first_name).filter_by(id=userId).first()
2491
    if r is None:
2492
        return None
2493
    else:
2494
        return r[0]
2495
 
18266 manas 2496
def checkPincodeServicable(userId):
2497
    checkAddressUser = "select distinct pincode from all_user_addresses where user_id= (%s)"
2498
    result = fetchResult(checkAddressUser,userId)
2499
    if len(result)==0:
2500
        return True
2501
    else:
2502
        myquery = "select count(*) from (select distinct pincode from all_user_addresses where user_id= (%s))a join pincodeavailability p on a.pincode=p.code"
2503
        result = fetchResult(myquery,userId)
2504
        if result[0][0]==0:
2505
            return False
2506
        else:
2507
            return True
2508
 
2509
def getUserObject(user):
2510
    obj = Mock()
2511
    obj.user_id = user.user_id
2512
    result = fetchResult("select * from useractive where user_id=%d"%(user.user_id))
2513
    if result == ():
2514
        obj.last_active = None
2515
    else:
2516
        obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
18269 manas 2517
    obj.name = user.name    
18266 manas 2518
    obj.contact = user.contact1
18275 manas 2519
    obj.lastOrderTimestamp=None
18256 manas 2520
 
18275 manas 2521
    details = session.query(Orders).filter_by(user_id = user.user_id).filter(~Orders.status.in_(['ORDER_NOT_CREATED_KNOWN','ORDER_NOT_CREATED_UNKNOWN', 'ORDER_ALREADY_CREATED_IGNORED'])).order_by(desc(Orders.created)).first()
18266 manas 2522
    if details is None:
18275 manas 2523
        obj.lastOrderTimestamp =None
18266 manas 2524
    else:
18366 manas 2525
        obj.lastOrderTimestamp =datetime.strftime(details.created, '%d/%m/%Y %H:%M:%S')
18275 manas 2526
    obj.totalOrders = session.query(Orders).filter_by(user_id = user.user_id).filter(~Orders.status.in_(['ORDER_NOT_CREATED_KNOWN','ORDER_NOT_CREATED_UNKNOWN', 'ORDER_ALREADY_CREATED_IGNORED'])).count()
18266 manas 2527
 
18275 manas 2528
    cartResult = fetchResult("select account_key from user_accounts where account_type ='cartId' and user_id=%d"%(user.user_id))
18266 manas 2529
    if cartResult == ():
18268 manas 2530
        obj.lastActiveCartTime = None
18266 manas 2531
    else:
2532
        conn = MySQLdb.connect("192.168.190.114", "root","shop2020", "user")
2533
        cursor = conn.cursor()
18275 manas 2534
        cursor.execute("select updated_on from cart where id=%s",(cartResult[0][0]))
18266 manas 2535
        result = cursor.fetchall()
2536
        if result ==():
18268 manas 2537
            obj.lastActiveCartTime = None
18266 manas 2538
        else:
2539
            print result
18275 manas 2540
            obj.lastActiveCartTime =datetime.strftime(result[0][0], '%d/%m/%Y %H:%M:%S')
18712 manas 2541
        conn.close()
2542
 
2543
    session.close()                
18266 manas 2544
    return obj
2545
 
18709 manas 2546
class CrmTicketDtr():
2547
    def on_post(self,req,resp):
18712 manas 2548
        try:
2549
            customerFeedbackBackMap = {}
2550
            customerFeedbackBackMap['user_id']=req.get_param("user_id")
2551
            user = session.query(Users).filter_by(id=customerFeedbackBackMap.get('user_id')).first()
2552
            if user is not None:
2553
                customerFeedbackBackMap['email']=user.email
2554
                customerFeedbackBackMap['mobile_number']=user.mobile_number
2555
                customerFeedbackBackMap['customer_name']=user.first_name + ' ' + user.last_name
2556
                customerFeedbackBackMap['subject'] = req.get_param("subject")
2557
                customerFeedbackBackMap['message'] = req.get_param("message")
2558
                customerFeedbackBackMap['created'] = datetime.now()
19761 manas 2559
                if ThriftUtils.generateCrmTicket(customerFeedbackBackMap):
18712 manas 2560
                    resp.body={"result":"success"}
2561
                else:
2562
                    resp.body={"result":"failure"}    
18709 manas 2563
            else:
18712 manas 2564
                resp.body={"result":"failure"}
2565
        except:
2566
            print traceback.print_exc()
2567
        finally:
2568
            session.close()            
18709 manas 2569
    def addTicket(self,user_id,subject,message):
18712 manas 2570
        try:
2571
            customerFeedbackBackMap = {}
2572
            customerFeedbackBackMap['user_id']=user_id
2573
            user = session.query(Users).filter_by(id=user_id).first()
2574
            if user is not None:
2575
                customerFeedbackBackMap['email']=user.email
2576
                customerFeedbackBackMap['mobile_number']=user.mobile_number
2577
                customerFeedbackBackMap['customer_name']=user.first_name + ' ' + user.last_name
2578
                customerFeedbackBackMap['subject'] = subject
2579
                customerFeedbackBackMap['message'] = message
2580
                customerFeedbackBackMap['created'] = datetime.now()
19651 manas 2581
                ThriftUtils.generateCrmTicket(customerFeedbackBackMap)
18712 manas 2582
            else:
2583
                print 'User is not present'
2584
        except:
18926 manas 2585
            print traceback.print_exc()                
2586
 
18272 kshitij.so 2587
class UnitDeal():
2588
    def on_get(self,req,resp, id):
2589
        result = Mongo.getDealById(id)
2590
        resp.body = dumps(result)
19290 kshitij.so 2591
 
2592
class SpecialOffer():
2593
    def on_get(self,req,resp):
2594
        user_id = req.get_param_as_int('user_id')
2595
        result = Mongo.getOfferForUser(user_id)
2596
        resp.body = dumps(result)
19388 kshitij.so 2597
 
2598
class BrandSubCatFilter():
2599
    def on_get(self, req, resp):
2600
        category_id = req.get_param_as_int('category_id')
2601
        id_list = req.get_param('id_list')
2602
        type = req.get_param('type')
2603
        result = Mongo.getBrandSubCategoryInfo(category_id, id_list, type)
2604
        resp.body = dumps(result)
19444 manas 2605
 
19451 manas 2606
class RefundAmountWallet():
2607
    def on_post(self,req,resp):
2608
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
2609
        if Mongo.refundAmountInWallet(jsonReq):
2610
            resp.body = "{\"result\":\"success\"}"
2611
        else:
2612
            resp.body = "{\"result\":\"failed\"}"
2613
 
2614
    def on_get(self,req,resp):
2615
        offset = req.get_param_as_int("offset")
2616
        limit = req.get_param_as_int("limit")
2617
        status = req.get_param("status")
19529 manas 2618
        if status: 
2619
            userRefundDetails = Mongo.fetchCrmRefundUsers(status,offset,limit)
2620
        else:
2621
            userRefundDetails = Mongo.fetchCrmRefundUsers(None,offset,limit)
19454 manas 2622
        if userRefundDetails is not None:
19457 manas 2623
            resp.body = dumps(userRefundDetails)
19454 manas 2624
        else:
2625
            resp.body ="{}"
19463 manas 2626
 
2627
class RefundWalletStatus():
2628
    def on_post(self,req,resp):
2629
        status = req.get_param('status')
2630
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
19479 manas 2631
        user_id = int(jsonReq.get('user_id'))
19463 manas 2632
        _id = jsonReq.get('_id')
2633
        if status == utils.REFUND_ADJUSTMENT_MAP.get(1):
19475 manas 2634
            value = int(jsonReq.get('amount'))
2635
            userAmountMap = {}
19469 manas 2636
            datetimeNow = datetime.now()
2637
            batchId = int(time.mktime(datetimeNow.timetuple()))
19475 manas 2638
            userAmountMap[user_id] = value
19497 manas 2639
            Mongo.updateCrmWalletStatus(status, _id,user_id,None,None)
19475 manas 2640
            if refundToWallet(batchId,userAmountMap):
2641
                refundType = jsonReq.get('type')
19497 manas 2642
                approved_by = jsonReq.get('approved_by')
19475 manas 2643
                get_mongo_connection().Dtr.refund.insert({"userId": user_id, "batch":batchId, "userAmount":value, "timestamp":datetime.strftime(datetimeNow,"%Y-%m-%d %H:%M:%S"), "type":refundType})
2644
                get_mongo_connection().Dtr.user.update({"userId":user_id}, {"$inc": { "credited": value, refundType:value}}, upsert=True)
19497 manas 2645
                Mongo.updateCrmWalletStatus(utils.REFUND_ADJUSTMENT_MAP.get(3), _id,user_id,batchId,approved_by)
19475 manas 2646
                print user_id,value                
19556 manas 2647
                Mongo.sendNotification([user_id], 'Batch Credit', 'Cashback Credited for %ss'%(str(refundType)), 'Rs.%s has been added to your wallet'%(value),'url', 'http://api.profittill.com/cashbacks/mine?user_id=%s'%(user_id), '2999-01-01', True, "TRAN_SMS Dear Customer, Cashback Credited for %ss. Rs.%s has been added to your wallet"%(refundType,value))
19475 manas 2648
                resp.body = "{\"result\":\"success\"}"
2649
            else:
2650
                resp.body = "{\"result\":\"failed\"}"
19463 manas 2651
        elif status == utils.REFUND_ADJUSTMENT_MAP.get(2):
19497 manas 2652
            Mongo.updateCrmWalletStatus(status, _id,user_id,None,None)
19469 manas 2653
            resp.body = "{\"result\":\"success\"}"
2654
        else:
2655
            resp.body = "{\"result\":\"failed\"}"
19485 manas 2656
 
2657
class DetailsBatchId():
2658
    def on_get(self,req,resp):
2659
        batchId = req.get_param('batchId')
2660
        userRefundDetails = Mongo.fetchCrmRefundByBatchId(batchId)        
2661
        if userRefundDetails is not None:
19493 manas 2662
            resp.body = dumps(list(userRefundDetails))
19485 manas 2663
        else:
2664
            resp.body ="{}"
19654 kshitij.so 2665
 
2666
class HeaderLinks():
2667
    def on_get(self, req, resp):
2668
        category_id = req.get_param_as_int('category_id')
2669
        result = Mongo.getHeaderLinks(category_id)
2670
        resp.body = dumps(result)
19761 manas 2671
 
2672
class SendTransactionalSms():
2673
    def on_post(self,req,resp,sms_type,identifier,agentId):
19767 manas 2674
        try:
2675
            if sms_type =='code':
2676
                otherMobileNumber = req.get_param('mobile_number')
2677
                if otherMobileNumber is None or str(otherMobileNumber).strip() is '':
2678
                    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=identifier).filter(RetailerContacts.contact_type=='sms').order_by(RetailerContacts.created.desc()).first()
2679
                    if retailerContact is not None:
2680
                        if retailerContact.mobile_number is not None and len(retailerContact.mobile_number)==10:
19776 manas 2681
                            smsStatus = generateSms(identifier,retailerContact.mobile_number,agentId)
19767 manas 2682
                            if smsStatus:
2683
                                resp.body = "{\"result\":\"success\"}"
2684
                            else:
2685
                                resp.body = "{\"result\":\"failed\"}"
19761 manas 2686
                        else:
19767 manas 2687
                            print 'Not a valid number to send the message to '+str(retailerContact.mobile_number)
19761 manas 2688
                            resp.body = "{\"result\":\"failed\"}"
2689
                    else:
19767 manas 2690
                        print 'No number to send the message for retailer id '+str(identifier)
19761 manas 2691
                        resp.body = "{\"result\":\"failed\"}"
2692
                else:
19767 manas 2693
                    if len(str(otherMobileNumber).strip())==10:
19776 manas 2694
                        smsStatus = generateSms(identifier,str(otherMobileNumber).strip(),agentId)
19767 manas 2695
                        if smsStatus:
2696
                            retailerContact = RetailerContacts()
2697
                            retailerContact.retailer_id = identifier
2698
                            retailerContact.agent_id = agentId
2699
                            retailerContact.call_type = 'inbound'
2700
                            retailerContact.contact_type = 'sms'
2701
                            retailerContact.mobile_number = str(otherMobileNumber).strip()
2702
                            session.commit()
2703
                            resp.body = "{\"result\":\"success\"}"
2704
 
2705
                        else:
2706
                            resp.body = "{\"result\":\"failed\"}"
19761 manas 2707
                    else:
19767 manas 2708
                        print 'Not a valid number to send the message to '+str(otherMobileNumber)
19761 manas 2709
                        resp.body = "{\"result\":\"failed\"}"
19767 manas 2710
        except:
2711
            print traceback.print_exc()
2712
        finally:
2713
            session.close()
19761 manas 2714
 
19776 manas 2715
def generateSms(identifier,mobile_number,agentId):
19761 manas 2716
    try:
2717
        retailerLink = session.query(RetailerLinks).filter_by(retailer_id=identifier).first()
2718
        retailer = session.query(Retailers).filter_by(id=identifier).first()
2719
        if retailer is not None:
2720
            if retailerLink is not None:
2721
                code = retailerLink.code
2722
                retailerLink.agent_id = agentId
2723
            else: 
19776 manas 2724
                c = RetailerDetail()
2725
                code = c.getNewRandomCode()
19761 manas 2726
                retailerLink = RetailerLinks()
2727
                retailerLink.code = code
19776 manas 2728
                retailerLink.agent_id = agentId
2729
                retailerLink.retailer_id = identifier
19761 manas 2730
                activationCode=Activation_Codes()
2731
                activationCode.code = code
19777 manas 2732
                activationCode.status = False
19761 manas 2733
            profitmandiUrl = make_tiny(code)
19784 manas 2734
            smsText = "Dear Customer,Download ProfitMandi app now. Get best deals on mobiles & accessories.Invite Code-" + code + " Click to download " + profitmandiUrl
19761 manas 2735
            url_params = { 'ani' : '91'+mobile_number,  'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'cli' : 'PROFTM', 'message' : smsText.strip() }
2736
            encoded_url_params = urllib.urlencode(url_params)
2737
            print 'Mobile Number :- '+str(mobile_number) +' Url Params:- '+str(encoded_url_params)
2738
            url = TRANSACTIONAL_SMS_SEND_URL + encoded_url_params
2739
            response_str = None
2740
            try:
2741
                req = urllib2.Request(url)
2742
                response = urllib2.urlopen(req)
2743
                response_str = response.read()
2744
            except:
2745
                print 'Error while getting response for user id:- Mobile Number:- '+str(mobile_number)
2746
                traceback.print_exc()
2747
                return False
2748
            print 'Mobile Number:- '+str(mobile_number) +' Sent Response:- '+ str(response_str)
2749
            try:
2750
                sms = profitmandi_sms()
2751
                sms.mobile_number = mobile_number
2752
                sms.sms_type = 'code'
2753
                sms.identifier = identifier 
2754
                if "Message sent successfully to " in response_str:
2755
                    response_str_vals = response_str.split('#')
2756
                    sms.status = "smsprocessed"
2757
                    sms.sms_id = response_str_vals[0]
2758
                else:
2759
                    sms.status = "smsrejected"
2760
                    sms.sms_id = None
2761
            except:
2762
                print 'Error while getting response for user id:- Mobile Number:- '+str(mobile_number)
2763
                traceback.print_exc()
2764
                return False
2765
            retailer.status='followup'
2766
            retailer.disposition = 'auto_text_sent'
2767
            retailer.next_call_time = datetime.now() + timedelta(days=1)
2768
            session.commit()
2769
            return True
2770
        else:
2771
            return False
2772
    except:
2773
        print traceback.print_exc()
2774
        return False
2775
    finally:
2776
        session.close()
19897 kshitij.so 2777
 
2778
class FilterDealsByType():
2779
    def on_get(self, req, resp):
2780
        categoryId = req.get_param_as_int("categoryId")
2781
        offset = req.get_param_as_int("offset")
2782
        limit = req.get_param_as_int("limit")
2783
        type = req.get_param("type")
2784
        result = Mongo.getDealsByType(categoryId, offset, limit, type)
2785
        resp.body = dumps(result) 
2786
 
19761 manas 2787
 
19879 naman 2788
 
2789
class GetItemCashback():
2790
    def on_get(self ,req,res):
2791
        itemcashback_id = req.get_param('id')
2792
        offsetval = req.get_param_as_int('offset')
2793
        limitval = req.get_param_as_int('limit')
2794
        allitemcashback = Mongo.getAllItemCasback(itemcashback_id,offsetval,limitval)
2795
        try: 
2796
            if allitemcashback:
2797
                res.body = dumps(allitemcashback)
2798
        except:
2799
                res.body = dumps({})
2800
 
2801
 
2802
    def on_post(self,req,res):
2803
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
2804
        item_skuId = jsonReq.get('sku')
2805
        cb = jsonReq.get('cash_back')
2806
        cb_description = jsonReq.get('cash_back_description')
2807
        cb_type = jsonReq.get('cash_back_type')
2808
        cb_status = jsonReq.get('cash_back_status')
2809
        response = Mongo.itemCashbackAdd(item_skuId,cb,cb_description,cb_type,cb_status)
2810
        try:
2811
            if response:
2812
                res.body = dumps({"result":"success"})
2813
        except:
2814
            res.body = dumps({"result":"failed"})
20079 kshitij.so 2815
 
2816
class AutoComplete():
2817
    def on_get(self, req, resp):
2818
        search_term = req.get_param('searchString')
2819
        try:
20170 kshitij.so 2820
            resp.body = dumps(getSuggestions(search_term))
20079 kshitij.so 2821
        except:
2822
            resp.body = dumps([])
15312 amit.gupta 2823
def main():
18386 manas 2824
    a = RetailerDetail()
2825
    retailer = a.getNotActiveRetailer()
2826
    otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
2827
    print json.dumps(todict(getRetailerObj(retailer, otherContacts, 'fresh')), encoding='utf-8')
15195 manas 2828
 
15081 amit.gupta 2829
if __name__ == '__main__':
19879 naman 2830
    main()
2831