Subversion Repositories SmartDukaan

Rev

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