Subversion Repositories SmartDukaan

Rev

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