Subversion Repositories SmartDukaan

Rev

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