Subversion Repositories SmartDukaan

Rev

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