Subversion Repositories SmartDukaan

Rev

Rev 21157 | Rev 21161 | 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,\
21157 kshitij.so 13
    tinxys_stats, profitmandi_sms, user_accounts
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:
21031 amit.gupta 1159
        retailerLink = session.query(RetailerLinks).filter_by(user_id = userId).first()
21028 amit.gupta 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
21030 amit.gupta 1194
    except:
1195
        traceback.print_exc()
15275 amit.gupta 1196
    finally:
1197
        session.close()
1198
 
15189 manas 1199
 
15081 amit.gupta 1200
def todict(obj, classkey=None):
1201
    if isinstance(obj, dict):
1202
        data = {}
1203
        for (k, v) in obj.items():
1204
            data[k] = todict(v, classkey)
1205
        return data
1206
    elif hasattr(obj, "_ast"):
1207
        return todict(obj._ast())
1208
    elif hasattr(obj, "__iter__"):
1209
        return [todict(v, classkey) for v in obj]
1210
    elif hasattr(obj, "__dict__"):
1211
        data = dict([(key, todict(value, classkey)) 
1212
            for key, value in obj.__dict__.iteritems() 
1213
            if not callable(value) and not key.startswith('_')])
1214
        if classkey is not None and hasattr(obj, "__class__"):
1215
            data[classkey] = obj.__class__.__name__
1216
        return data
1217
    else:
1218
        return obj
18256 manas 1219
 
15358 amit.gupta 1220
def getRetailerObj(retailer, otherContacts1=None, callType=None):
15324 amit.gupta 1221
    print "before otherContacts1",otherContacts1
1222
    otherContacts = [] if otherContacts1 is None else otherContacts1
15662 amit.gupta 1223
    print "after otherContacts1",otherContacts
15081 amit.gupta 1224
    obj = Mock()
15280 amit.gupta 1225
    obj.id = retailer.id
15686 amit.gupta 1226
 
1227
 
15314 amit.gupta 1228
    if retailer.contact1 is not None and retailer.contact1 not in otherContacts:
15315 amit.gupta 1229
        otherContacts.append(retailer.contact1)
15314 amit.gupta 1230
    if retailer.contact2 is not None and retailer.contact2 not in otherContacts:
15315 amit.gupta 1231
        otherContacts.append(retailer.contact2)
15323 amit.gupta 1232
    obj.contact1 = None if len(otherContacts)==0 else otherContacts[0]
15325 amit.gupta 1233
    if obj.contact1 is not None:
1234
        obj.contact2 = None if len(otherContacts)==1 else otherContacts[1]
15096 amit.gupta 1235
    obj.scheduled = (retailer.call_priority is not None)
15686 amit.gupta 1236
    address = None
1237
    try:
1238
        address = session.query(RetailerAddresses).filter_by(retailer_id=retailer.id).order_by(RetailerAddresses.created.desc()).first()
1239
    finally:
1240
        session.close()
1241
    if address is not None:
1242
        obj.address = address.address
1243
        obj.title = address.title
1244
        obj.city = address.city
1245
        obj.state = address.state
1246
        obj.pin = address.pin 
1247
    else:
1248
        obj.address = retailer.address_new if retailer.address_new is not None else retailer.address
1249
        obj.title = retailer.title
1250
        obj.city = retailer.city
1251
        obj.state = retailer.state
1252
        obj.pin = retailer.pin 
15699 amit.gupta 1253
    obj.status = retailer.status
19791 manas 1254
    obj.tinnumber = retailer.tinnumber
1255
    obj.isvalidated = retailer.isvalidated    
15662 amit.gupta 1256
    if hasattr(retailer, 'contact'):
1257
        obj.contact = retailer.contact
19732 manas 1258
    if callType == 'followup':
1259
        obj.last_call_time = datetime.strftime(retailer.modified, "%B %Y")
15358 amit.gupta 1260
    if callType == 'onboarding':
1261
        try:
15364 amit.gupta 1262
            userId, activatedTime = session.query(RetailerLinks.user_id, RetailerLinks.activated).filter(RetailerLinks.retailer_id==retailer.id).first()
15366 amit.gupta 1263
            activated, = session.query(Users.activation_time).filter(Users.id==userId).first()
15364 amit.gupta 1264
            if activated is not None:
15366 amit.gupta 1265
                activatedTime = activated
15362 amit.gupta 1266
            obj.user_id = userId
15364 amit.gupta 1267
            obj.created = datetime.strftime(activatedTime, '%d/%m/%Y %H:%M:%S')
15358 amit.gupta 1268
            result = fetchResult("select * from useractive where user_id=%d"%(userId))
1269
            if result == ():
1270
                obj.last_active = None
1271
            else:
15360 amit.gupta 1272
                obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
15361 amit.gupta 1273
            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 1274
            obj.orders = ordersCount
1275
        finally:
1276
            session.close()
15081 amit.gupta 1277
    return obj
15091 amit.gupta 1278
 
15132 amit.gupta 1279
def make_tiny(code):
16939 manish.sha 1280
    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 1281
    #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 1282
    #marketUrl='market://details?id=com.saholic.profittill&referrer=utm_source=0&utm_medium=CRM&utm_term=001&utm_campaign='+code
1283
    #url = urllib.quote(marketUrl)
15465 amit.gupta 1284
    #request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))
1285
    #filehandle = urllib2.Request(request_url)
1286
    #x= urllib2.urlopen(filehandle)
15546 amit.gupta 1287
    try:
1288
        shortener = Shortener('TinyurlShortener')
1289
        returnUrl =  shortener.short(url)
1290
    except:
1291
        shortener = Shortener('SentalaShortener')
19678 amit.gupta 1292
        returnUrl =  shortener.short(url)
15546 amit.gupta 1293
    return returnUrl
15171 amit.gupta 1294
 
15285 manas 1295
class SearchUser():
1296
 
1297
    def on_post(self, req, resp, agentId, searchType):
15314 amit.gupta 1298
        retailersJsonArray = []
15285 manas 1299
        try:
1300
            jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1301
            lgr.info( "Request in Search----\n"  + str(jsonReq))
15302 amit.gupta 1302
            contact=jsonReq.get('searchTerm')
15285 manas 1303
            if(searchType=="number"):
15312 amit.gupta 1304
                retailer_ids = session.query(RetailerContacts.retailer_id).filter_by(mobile_number=contact).all()
1305
                retailer_ids = [r for r, in retailer_ids]    
1306
                anotherCondition = or_(Retailers.contact1==contact,Retailers.contact2==contact, Retailers.id.in_(retailer_ids))
1307
            else:
1308
                m = re.match("(.*?)(\d{6})(.*?)", contact)
1309
                if m is not None:
1310
                    pin = m.group(2)
1311
                    contact = m.group(1) if m.group(1) != '' else m.group(3)
15313 amit.gupta 1312
                    anotherCondition = and_(Retailers.title.ilike('%%%s%%'%(contact)), Retailers.pin==pin)
15312 amit.gupta 1313
                else:
1314
                    anotherCondition = Retailers.title.ilike('%%%s%%'%(contact))
15297 amit.gupta 1315
 
19928 kshitij.so 1316
            retailers = session.query(Retailers).filter(anotherCondition).filter(Retailers.isvalidated==1).limit(20).all()
15312 amit.gupta 1317
            if retailers is None:
15285 manas 1318
                resp.body = json.dumps("{}")
15312 amit.gupta 1319
            else:
1320
                for retailer in retailers:
15326 amit.gupta 1321
                    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 1322
                    retailersJsonArray.append(todict(getRetailerObj(retailer, otherContacts)))    
1323
            resp.body = json.dumps({"Retailers":retailersJsonArray}, encoding='utf-8')
15285 manas 1324
        finally:
1325
            session.close()
15171 amit.gupta 1326
 
15081 amit.gupta 1327
 
1328
class Mock(object):
1329
    pass
15189 manas 1330
 
15312 amit.gupta 1331
def tagActivatedReatilers():
15613 amit.gupta 1332
    retailerIds = [r for  r, in session.query(RetailerLinks.retailer_id).filter_by(user_id = None).all()]
15312 amit.gupta 1333
    session.close()
15288 amit.gupta 1334
    for retailerId in retailerIds:
1335
        isActivated(retailerId)
15312 amit.gupta 1336
    session.close()
15374 kshitij.so 1337
 
1338
class StaticDeals():
1339
 
1340
    def on_get(self, req, resp):
1341
 
1342
        offset = req.get_param_as_int("offset")
1343
        limit = req.get_param_as_int("limit")
1344
        categoryId = req.get_param_as_int("categoryId")
15458 kshitij.so 1345
        direction = req.get_param_as_int("direction")
15374 kshitij.so 1346
 
15458 kshitij.so 1347
        result = Mongo.getStaticDeals(offset, limit, categoryId, direction)
15374 kshitij.so 1348
        resp.body = dumps(result)
1349
 
16366 kshitij.so 1350
class DealNotification():
1351
 
1352
    def on_get(self,req,resp,skuBundleIds):
1353
        result = Mongo.getDealsForNotification(skuBundleIds)
1354
        resp.body = dumps(result)
16487 kshitij.so 1355
 
1356
class DealPoints():
1357
 
1358
    def on_get(self, req, resp):
16366 kshitij.so 1359
 
16487 kshitij.so 1360
        offset = req.get_param_as_int("offset")
1361
        limit = req.get_param_as_int("limit")
1362
 
1363
        result = Mongo.getAllBundlesWithDealPoints(offset, limit)
1364
        resp.body = dumps(result)
15374 kshitij.so 1365
 
16487 kshitij.so 1366
 
1367
    def on_post(self, req, resp):
1368
 
1369
 
1370
        try:
1371
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1372
        except ValueError:
1373
            raise falcon.HTTPError(falcon.HTTP_400,
1374
                'Malformed JSON',
1375
                'Could not decode the request body. The '
1376
                'JSON was incorrect.')
1377
 
1378
        result = Mongo.addDealPoints(result_json)
1379
        resp.body = json.dumps(result, encoding='utf-8')
15374 kshitij.so 1380
 
16545 kshitij.so 1381
class AppAffiliates():
1382
 
1383
    def on_get(self, req, resp, retailerId, appId):
1384
        retailerId = int(retailerId)
1385
        appId = int(appId)
16554 kshitij.so 1386
        call_back = req.get_param("callback")
16545 kshitij.so 1387
        result = Mongo.generateRedirectUrl(retailerId, appId)
16555 kshitij.so 1388
        resp.body = call_back+'('+str(result)+')'
16557 kshitij.so 1389
 
1390
class AffiliatePayout():
1391
    def on_get(self, req, resp):
1392
        payout = req.get_param("payout")
1393
        transaction_id = req.get_param("transaction_id")
1394
        result = Mongo.addPayout(payout, transaction_id)
1395
        resp.body = str(result)
1396
 
16581 manish.sha 1397
class AppOffers():
1398
    def on_get(self, req, resp, retailerId):
16895 manish.sha 1399
        try:            
1400
            result = Mongo.getAppOffers(retailerId)
1401
            offerids = result.values()
1402
            if offerids is None or len(offerids)==0:
16887 kshitij.so 1403
                resp.body = json.dumps("{}")
1404
            else:
16941 manish.sha 1405
                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 1406
                appOffersMap = {}
1407
                jsonOffersArray=[]
1408
                for offer in appOffers:
1409
                    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__
1410
                for rank in sorted(result):
1411
                    print 'Rank', rank, 'Data', appOffersMap[result[rank]]
1412
                    jsonOffersArray.append(appOffersMap[result[rank]])
1413
 
1414
            resp.body = json.dumps({"AppOffers":jsonOffersArray}, encoding='latin1')
16887 kshitij.so 1415
        finally:
1416
            session.close()
1417
 
16727 manish.sha 1418
 
1419
class AppUserBatchRefund():
1420
    def on_get(self, req, resp, batchId, userId):
16887 kshitij.so 1421
        try:
1422
            batchId = long(batchId)
1423
            userId = long(userId)
1424
            userBatchCashback = user_app_cashbacks.get_by(user_id=userId, batchCreditId=batchId)
1425
            if userBatchCashback is None:
1426
                resp.body = json.dumps("{}")
1427
            else:
16905 manish.sha 1428
                if userBatchCashback.creditedDate is not None:
1429
                    userBatchCashback.creditedDate = str(userBatchCashback.creditedDate)
16887 kshitij.so 1430
                resp.body = json.dumps(todict(userBatchCashback), encoding='utf-8')
1431
        finally:
1432
            session.close()
16727 manish.sha 1433
 
1434
class AppUserBatchDrillDown():
16777 manish.sha 1435
    def on_get(self, req, resp, fortNightOfYear, userId, yearVal):
16887 kshitij.so 1436
        try:
1437
            fortNightOfYear = long(fortNightOfYear)
1438
            userId = long(userId)
1439
            yearVal = long(yearVal)
1440
            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()
1441
            cashbackArray = []
1442
            if appUserBatchDrillDown is None or len(appUserBatchDrillDown)==0:
1443
                resp.body = json.dumps("{}")
1444
            else:
1445
                for appcashBack in appUserBatchDrillDown:
1446
                    userAppBatchDrillDown = UserAppBatchDrillDown(str(appcashBack[0]),long(appcashBack[1]), long(appcashBack[2]))
1447
                    cashbackArray.append(todict(userAppBatchDrillDown))
1448
                resp.body = json.dumps({"UserAppCashBackInBatch":cashbackArray}, encoding='utf-8')
1449
        finally:
1450
            session.close()
16727 manish.sha 1451
 
1452
class AppUserBatchDateDrillDown():
1453
    def on_get(self, req, resp, userId, date):
16887 kshitij.so 1454
        try:
1455
            userId = long(userId)
1456
            date = str(date)
1457
            date = datetime.strptime(date, '%Y-%m-%d')
1458
            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()
1459
            cashbackArray = []
1460
            if appUserBatchDateDrillDown is None or len(appUserBatchDateDrillDown)==0:
1461
                resp.body = json.dumps("{}")
1462
            else:
1463
                for appcashBack in appUserBatchDateDrillDown:
1464
                    userAppBatchDateDrillDown = UserAppBatchDateDrillDown(str(appcashBack[0]),long(appcashBack[1]),long(appcashBack[2]))
1465
                    cashbackArray.append(todict(userAppBatchDateDrillDown))
1466
                resp.body = json.dumps({"UserAppCashBackDateWise":cashbackArray}, encoding='utf-8')
1467
        finally:
1468
            session.close()
16739 manish.sha 1469
 
16748 manish.sha 1470
class AppUserCashBack():
1471
    def on_get(self, req, resp, userId, status):
16887 kshitij.so 1472
        try:
1473
            userId = long(userId)
1474
            status = str(status)
1475
            appUserApprovedCashBacks = user_app_cashbacks.query.filter(user_app_cashbacks.user_id==userId).filter(user_app_cashbacks.status==status).all()
1476
            cashbackArray = []
1477
            if appUserApprovedCashBacks is None or len(appUserApprovedCashBacks)==0:
1478
                resp.body = json.dumps("{}")
1479
            else:
1480
                totalAmount = 0                
1481
                for appUserApprovedCashBack in appUserApprovedCashBacks:
1482
                    totalAmount = totalAmount + appUserApprovedCashBack.amount
16895 manish.sha 1483
                    if appUserApprovedCashBack.creditedDate is not None:
1484
                        appUserApprovedCashBack.creditedDate = str(appUserApprovedCashBack.creditedDate)  
16905 manish.sha 1485
                    cashbackArray.append(todict(appUserApprovedCashBack)) 
1486
 
16887 kshitij.so 1487
                resp.body = json.dumps({"UserAppCashBack":cashbackArray,"TotalAmount":totalAmount}, encoding='utf-8')
1488
        finally:
1489
            session.close()
17278 naman 1490
 
1491
class GetSaleDetail():
1492
    def on_get(self,req,res,date_val):
1493
        try:
1494
                db = get_mongo_connection()
1495
                sum=0
1496
                count=0
1497
                #print date_val, type(date_val)
1498
                #cursor = db.Dtr.merchantOrder.find({'createdOnInt':{'$lt':long(date_val)},'subOrders':{'$exists':True}})
17315 naman 1499
                cursor = db.Dtr.merchantOrder.find({"$and": [ { "createdOnInt":{"$gt":long(date_val)} }, {"createdOnInt":{"$lt":long(date_val)+86401} } ],"subOrders":{"$exists":True}})
17278 naman 1500
 
1501
                for document in cursor:
1502
                    for doc in document['subOrders']:
1503
                        sum = sum + float(doc['amountPaid'])
1504
                        count = count + int(doc['quantity'])
1505
 
1506
                data = {"amount":sum , "quantity":count}
1507
 
1508
                res.body= json.dumps(data,encoding='utf-8')
1509
        finally:
1510
                session.close()
1511
 
17301 kshitij.so 1512
class DummyDeals():
17304 kshitij.so 1513
    def on_get(self,req, resp):
17301 kshitij.so 1514
        categoryId = req.get_param_as_int("categoryId")
1515
        offset = req.get_param_as_int("offset")
1516
        limit = req.get_param_as_int("limit")
1517
        result = Mongo.getDummyDeals(categoryId, offset, limit)
17556 kshitij.so 1518
        resp.body = dumps(result)
17301 kshitij.so 1519
 
17467 manas 1520
class PincodeValidation():
17498 amit.gupta 1521
    def on_get(self,req,resp,pincode):
17467 manas 1522
        json_data={}
1523
        cities=[]
1524
        print pincode
1525
        if len(str(pincode)) ==6:
19391 amit.gupta 1526
            listCities = list(session.query(Postoffices.taluk,Postoffices.state).distinct().filter(Postoffices.pincode==pincode).all())
17467 manas 1527
            if len(listCities)>0:
1528
                for j in listCities:
19391 amit.gupta 1529
                    if j.taluk != 'NA':
1530
                        cities.append(j.taluk)
17467 manas 1531
                json_data['cities'] = cities
1532
                json_data['state'] = listCities[0][1]
1533
                resp.body =  json.dumps(json_data)
1534
            else:
1535
                resp.body = json.dumps("{}")       
1536
        else:
1537
            resp.body = json.dumps("{}")
1538
        session.close()
17301 kshitij.so 1539
 
17556 kshitij.so 1540
class SearchDummyDeals():
1541
    def on_get(self,req,resp):
1542
        offset = req.get_param_as_int("offset")
1543
        limit = req.get_param_as_int("limit")
1544
        searchTerm = req.get_param("searchTerm")
1545
        result = Mongo.searchDummyDeals(searchTerm, limit, offset)
1546
        resp.body = dumps(result)
1547
 
1548
class DummyPricing:
17560 kshitij.so 1549
    def on_get(self, req, resp):
17556 kshitij.so 1550
        skuBundleId = req.get_param_as_int("skuBundleId")
1551
        result = Mongo.getDummyPricing(skuBundleId)
1552
        resp.body = dumps(result)
1553
 
1554
class DealObject:
17560 kshitij.so 1555
    def on_post(self, req, resp):
17569 kshitij.so 1556
        update = req.get_param_as_int("update")
17556 kshitij.so 1557
        try:
1558
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1559
        except ValueError:
1560
            raise falcon.HTTPError(falcon.HTTP_400,
1561
                'Malformed JSON',
1562
                'Could not decode the request body. The '
1563
                'JSON was incorrect.')
17569 kshitij.so 1564
        if update is None:    
1565
            result = Mongo.addDealObject(result_json)
1566
        else:
1567
            result = Mongo.updateDealObject(result_json)
1568
 
17556 kshitij.so 1569
        resp.body = dumps(result)
17569 kshitij.so 1570
 
17556 kshitij.so 1571
 
17560 kshitij.so 1572
    def on_get(self, req, resp):
17567 kshitij.so 1573
        edit = req.get_param_as_int("edit")
1574
        if edit is None:
1575
            offset = req.get_param_as_int("offset")
1576
            limit = req.get_param_as_int("limit")
17560 kshitij.so 1577
 
17567 kshitij.so 1578
            result = Mongo.getAllDealObjects(offset, limit)
1579
            resp.body = dumps(result)
1580
        else:
1581
            id = req.get_param_as_int("id")
1582
            result = Mongo.getDealObjectById(id)
1583
            resp.body = dumps(result)
17560 kshitij.so 1584
 
17563 kshitij.so 1585
class DeleteDealObject:
1586
    def on_get(self, req, resp, id):
1587
        result = Mongo.deleteDealObject(int(id))
1588
        resp.body = dumps(result)
1589
 
17611 kshitij.so 1590
class FeaturedDealObject:
1591
    def on_get(self, req, resp):
1592
 
1593
        offset = req.get_param_as_int("offset")
1594
        limit = req.get_param_as_int("limit")
1595
 
1596
        result = Mongo.getAllFeaturedDealsForDealObject(offset, limit)
1597
        resp.body = dumps(result)
1598
 
17556 kshitij.so 1599
 
17611 kshitij.so 1600
    def on_post(self, req, resp):
1601
 
1602
 
1603
        try:
1604
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1605
        except ValueError:
1606
            raise falcon.HTTPError(falcon.HTTP_400,
1607
                'Malformed JSON',
1608
                'Could not decode the request body. The '
1609
                'JSON was incorrect.')
1610
 
17613 kshitij.so 1611
        result = Mongo.addFeaturedDealForDealObject(result_json)
17611 kshitij.so 1612
        resp.body = json.dumps(result, encoding='utf-8')
1613
 
17615 kshitij.so 1614
class DeleteFeaturedDealObject:
1615
    def on_get(self, req, resp, id):
1616
        result = Mongo.deleteFeaturedDealObject(int(id))
1617
        resp.body = dumps(result)
17611 kshitij.so 1618
 
17653 kshitij.so 1619
class SubCategoryFilter:
1620
    def on_get(self, req, resp):
1621
        category_id = req.get_param_as_int("category_id")
1622
        result = Mongo.getSubCategoryForFilter(category_id)
1623
        resp.body = dumps(result)
1624
 
17726 kshitij.so 1625
class DummyLogin:
1626
    def on_post(self,req,resp):
1627
        try:
1628
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1629
        except ValueError:
1630
            raise falcon.HTTPError(falcon.HTTP_400,
1631
                'Malformed JSON',
1632
                'Could not decode the request body. The '
1633
                'JSON was incorrect.')
1634
 
1635
        result = Mongo.dummyLogin(result_json)
1636
        resp.body = json.dumps(result, encoding='utf-8')
17653 kshitij.so 1637
 
17726 kshitij.so 1638
class DummyRegister:
1639
    def on_post(self,req,resp):
1640
        try:
1641
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1642
        except ValueError:
1643
            raise falcon.HTTPError(falcon.HTTP_400,
1644
                'Malformed JSON',
1645
                'Could not decode the request body. The '
1646
                'JSON was incorrect.')
1647
 
1648
        result = Mongo.dummyRegister(result_json)
1649
        resp.body = json.dumps(result, encoding='utf-8')
1650
 
18896 amit.gupta 1651
class TinSearch:
1652
    def on_get(self,req,resp):
1653
        tin = req.get_param("tin")
1654
        result = getTinInfo(tin)
1655
        resp.body = json.dumps(result, encoding='utf-8')
1656
 
1657
 
1658
def getTinInfo(tin):
1659
    try:
19718 amit.gupta 1660
        curData = session.query(tinxys_stats).filter_by(req_date=date.today()).first()
19666 amit.gupta 1661
        if not curData:
1662
            curData = tinxys_stats()
19718 amit.gupta 1663
            curData.total = 0
1664
            curData.request_failed = 0
1665
            curData.invalid_tin = 0
19666 amit.gupta 1666
        curData.total += 1
1667
        tinInfo = {"isError":False}
18995 amit.gupta 1668
        try:
19666 amit.gupta 1669
            params = ['tin','cst','counter_name','counter_address','state','pan','registered_on','cst_status','valid_since']
1670
            url  = "http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber=" + tin + "&searchBy=TIN"
1671
            req = urllib2.Request(url)
1672
            try:
1673
                connection = urllib2.urlopen(req, timeout=10)
1674
            except:
1675
                curData.request_failed += 1
1676
                tinInfo = {"isError":True,
1677
                        "errorMsg": "Some problem occurred. Try again after some time"
1678
                }
1679
                return tinInfo
1680
            pageHtml = connection.read()
1681
            connection.close()        
1682
            doc = pq(pageHtml)
1683
            index=-1
1684
            for ele in pq(doc.find('table')[2])('tr td:nth-child(2)'):
1685
                index += 1
1686
                text = pq(ele).text().strip()
1687
                if not text:
1688
                    text = pq(ele)('div').text().strip()
1689
                tinInfo[params[index]] = text
1690
            print index, "index"
1691
            if index != 8:
1692
                raise
1693
            if not get_mongo_connection().Dtr.tin.find({"tin":tinInfo['tin']}):
1694
                get_mongo_connection().Dtr.tin.insert(tinInfo)
1695
            address = tinInfo['counter_address']
1696
            m = re.match(".*?(\d{6}).*?", address)
1697
            if m:
1698
                tinInfo['pin'] = m.group(1)
1699
                tinInfo['pin_required'] = False
1700
            else:
1701
                tinInfo['pin_required'] = True
1702
 
1703
            print "TinNumber: Successfully fetched details", tin
18995 amit.gupta 1704
        except:
19666 amit.gupta 1705
            curData.invalid_tin = 1
1706
            traceback.print_exc()
18995 amit.gupta 1707
            tinInfo = {"isError":True,
19666 amit.gupta 1708
                        "errorMsg": "Could not find tin"
18995 amit.gupta 1709
            }
19666 amit.gupta 1710
            print "TinNumber: Problem fetching details", tin
1711
        session.commit()
1712
        return tinInfo
1713
    finally:
1714
        session.close()
18896 amit.gupta 1715
 
1716
 
17730 kshitij.so 1717
class UpdateUser:
1718
    def on_post(self,req,resp):
1719
        try:
1720
            result_json = json.loads(req.stream.read(), encoding='utf-8')
1721
        except ValueError:
1722
            raise falcon.HTTPError(falcon.HTTP_400,
1723
                'Malformed JSON',
1724
                'Could not decode the request body. The '
1725
                'JSON was incorrect.')
1726
 
1727
        result = Mongo.updateDummyUser(result_json)
1728
        resp.body = json.dumps(result, encoding='utf-8')
1729
 
1730
class FetchUser:
1731
    def on_get(self,req,resp):
1732
        user_id = req.get_param_as_int("user_id")
1733
        result = Mongo.getDummyUser(user_id)
1734
        resp.body = json.dumps(result, encoding='utf-8')
17928 kshitij.so 1735
 
1736
class SearchSubCategory:
1737
    def on_get(self,req, resp):
18088 kshitij.so 1738
        subCategoryIds = req.get_param("subCategoryId")
17928 kshitij.so 1739
        searchTerm = req.get_param("searchTerm")
1740
        offset = req.get_param_as_int("offset")
1741
        limit = req.get_param_as_int("limit")
17730 kshitij.so 1742
 
18088 kshitij.so 1743
        result = Mongo.getDealsForSearchText(subCategoryIds, searchTerm,offset, limit)
17928 kshitij.so 1744
        resp.body = json.dumps(result, encoding='utf-8')
1745
 
1746
class SearchSubCategoryCount:
1747
    def on_get(self,req, resp):
18088 kshitij.so 1748
        subCategoryIds = req.get_param("subCategoryId")
17928 kshitij.so 1749
        searchTerm = req.get_param("searchTerm")
18088 kshitij.so 1750
        result = Mongo.getCountForSearchText(subCategoryIds, searchTerm)
17928 kshitij.so 1751
        resp.body = json.dumps(result, encoding='utf-8')
18090 manas 1752
 
1753
class MessageEncryption:
1754
 
1755
    def on_get(self,req,resp):
1756
        message_type = req.get_param("type")
18093 manas 1757
        if message_type == 'encrypt':
18090 manas 1758
            encryption_data = req.get_param("data")
18101 manas 1759
            encrypted_data = encryptMessage(base64.decodestring(encryption_data))
18090 manas 1760
            resp.body =  json.dumps({"result":{"value":encrypted_data}}, encoding='utf-8')
1761
 
18093 manas 1762
        elif message_type == 'decrypt':
18090 manas 1763
            decryption_data = req.get_param("data")
1764
            decrypted_data = decryptMessage(decryption_data)
1765
            resp.body =  json.dumps({"result":{"value":decrypted_data}}, encoding='utf-8')
1766
 
1767
        else:
1768
            resp.body = json.dumps({}, encoding='utf-8')
18256 manas 1769
 
1770
class GetUserCrmApplication:
19442 manas 1771
 
18256 manas 1772
    def on_get(self,req,resp):
18329 manas 1773
        global USER_DETAIL_MAP
18256 manas 1774
        project_name = req.get_param("project_name")
18329 manas 1775
        USER_DETAIL_MAP[project_name]+=1
18386 manas 1776
        lgr.info( "USER_DETAIL_CALL_COUNTER " +  str(USER_DETAIL_MAP[project_name]))
18329 manas 1777
        retryFlag=False
1778
        if USER_DETAIL_MAP[project_name] % TOTAL_USER >= USER_CRM_DEFAULT_FRESH_FACTOR:
1779
                retryFlag=True
1780
        if project_name == 'accs_cart':
18792 manas 1781
            project_id=1
1782
        elif project_name == 'accs_active':
1783
            project_id=2
1784
        elif project_name == 'accs_order':
1785
            project_id=3
19442 manas 1786
        elif project_name == 'accs_cashback_scheme':
1787
            project_id=4
20133 rajender 1788
        elif project_name == 'inactive_users':
1789
            project_id=5
18792 manas 1790
        if retryFlag:
1791
            user = self.getRetryUser(project_id)
1792
        else:
1793
            user = self.getNewUser(project_id)
1794
 
1795
        if user is None:
1796
            resp.body ={}
1797
        else:        
1798
            user.status =  'assigned'
1799
            user.agent_id = req.get_param("agent_id")
1800
            user.counter=1
1801
            user.modified = datetime.now()
1802
            session.commit()
1803
            resp.body = json.dumps(todict(getUserObject(user)), encoding='utf-8')
1804
            session.close()
18620 manas 1805
 
18329 manas 1806
    def getRetryUser(self,projectId,failback=True):
1807
        status = "retry"
18367 manas 1808
        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 1809
 
1810
        if user is not None:
18334 manas 1811
            lgr.info( "getRetryUser " + str(user.id))
18329 manas 1812
        else:
1813
            if failback:
18334 manas 1814
                user = self.getNewUser(projectId,False)
18329 manas 1815
                return user
1816
            else:
1817
                return None
1818
        return user
18291 manas 1819
 
18329 manas 1820
 
18331 manas 1821
    def getNewUser(self,projectId,failback=True):
18329 manas 1822
            user = None 
1823
            try:
18416 manas 1824
                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 1825
                if user is None:
1826
                    insertUserCrmData(projectId)
18416 manas 1827
                    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 1828
                    if user is not None:
1829
                        lgr.info( "getNewUser " + str(user.id))
1830
                    else:
1831
                        if failback:
1832
                            user = self.getRetryUser(projectId,False)
1833
                            return user
1834
                        else:
1835
                            return None
18329 manas 1836
            except:
1837
                print traceback.print_exc()
1838
            return user    
18386 manas 1839
 
18291 manas 1840
    def on_post(self, req, resp):
1841
        returned = False
1842
        self.agentId = req.get_param("agent_id")
1843
        project_name = req.get_param("project_name")
18637 manas 1844
 
18329 manas 1845
        if project_name == 'accs_cart':
18637 manas 1846
            project_id=1
1847
        elif project_name == 'accs_active':
1848
            project_id=2            
1849
        elif project_name == 'accs_order':
1850
            project_id=3            
19442 manas 1851
        elif project_name == 'accs_cashback_scheme':
1852
            project_id=4
20133 rajender 1853
        elif project_name == 'inactive_users':
1854
            project_id=5
19442 manas 1855
 
18637 manas 1856
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
1857
        lgr.info( "Request ----\n"  + str(jsonReq))
1858
        self.jsonReq = jsonReq
1859
        self.callType="default"
1860
        callLaterAccs = self.callLaterAccs
20133 rajender 1861
        invalidNumber = self.invalidNumber
18637 manas 1862
        accsDisposition = self.accsDisposition
1863
        accsOrderDisposition=self.accsOrderDisposition
20133 rajender 1864
        otherreason = self.otherreason
1865
        willplaceorder = self.willplaceorder
20147 rajender 1866
        verifiedLinkSent = self.verifiedLinkSent
20133 rajender 1867
        orderdiffaccount = self.orderdiffaccount
1868
        businessclosed = self.businessclosed
1869
        appuninstalled = self.appuninstalled
18637 manas 1870
        self.userId = int(jsonReq.get('user_id'))
1871
        try:
1872
            self.user = session.query(UserCrmCallingData).filter_by(user_id=self.userId).filter(UserCrmCallingData.project_id==project_id).first()
1873
            self.callDisposition = jsonReq.get('calldispositiontype')
1874
            self.callHistoryCrm = CallHistoryCrm()
1875
            self.callHistoryCrm.agent_id=self.agentId
1876
            self.callHistoryCrm.project_id = project_id
1877
            self.callHistoryCrm.call_disposition = self.callDisposition
1878
            self.callHistoryCrm.user_id=self.userId
1879
            self.callHistoryCrm.duration_sec = int(jsonReq.get("callduration"))
1880
            self.callHistoryCrm.disposition_comments = jsonReq.get('calldispositioncomments')
1881
            self.callHistoryCrm.call_time = datetime.strptime(jsonReq.get("calltime"), '%d/%m/%Y %H:%M:%S')
1882
            self.callHistoryCrm.mobile_number = jsonReq.get('number')
1883
            self.inputs = jsonReq.get("inputs")
1884
            dispositionMap = {  'call_later':callLaterAccs,
1885
                        'ringing_no_answer':callLaterAccs,
1886
                        'not_reachable':callLaterAccs,
1887
                        'switch_off':callLaterAccs,
1888
                        'technical_issue':accsDisposition,
1889
                        'pricing_issue':accsDisposition,
1890
                        'shipping_issue':accsDisposition,
1891
                        'internet_issue':accsDisposition,
1892
                        'checking_price':accsDisposition,
1893
                        'order_process':accsDisposition,
1894
                        'placed_order':accsDisposition,
1895
                        'place_order':accsDisposition,
1896
                        'product_availability':accsOrderDisposition,
1897
                        'return_replacement':accsOrderDisposition,
1898
                        'already_purchased':accsOrderDisposition,
1899
                        'product_quality_issue':accsOrderDisposition,
1900
                        'delayed_delivery':accsOrderDisposition,
18671 manas 1901
                        'other_complaint':accsOrderDisposition,
19442 manas 1902
                        'scheme_not_clear':accsOrderDisposition,
20133 rajender 1903
                        'not_dealing_accessories':accsOrderDisposition,
1904
                        'other_reason':otherreason,
1905
                        'app_uninstalled':appuninstalled,
1906
                        'will_place_order':willplaceorder,
1907
                        'order_diff_acc':orderdiffaccount,
1908
                        'not_retailer':invalidNumber,
1909
                        'business_closed':businessclosed,
1910
                        'invalid_no':invalidNumber,
1911
                        'wrong_no':invalidNumber,
1912
                        'hang_up':invalidNumber,
1913
                        'service_center_retailer':invalidNumber,
20147 rajender 1914
                        'recharge_retailer':invalidNumber,
1915
                        'verified_link_sent':verifiedLinkSent
20133 rajender 1916
 
1917
 
18637 manas 1918
                      }
1919
            returned = dispositionMap[jsonReq.get('calldispositiontype')]()
1920
        finally:
1921
            session.close()
1922
 
1923
        if returned:
1924
            resp.body = "{\"result\":\"success\"}"
1925
        else:
1926
            resp.body = "{\"result\":\"failed\"}"
1927
 
20147 rajender 1928
    def verifiedLinkSent(self,):
1929
        users_referrer, = session.query(Users.referrer).filter_by(id=self.userId).first()
1930
        if users_referrer is not None:
1931
            activationCode=session.query(Activation_Codes).filter_by(code=users_referrer).first()
1932
            if activationCode is not None:
1933
                activationCode.status = False
1934
        self.user.status='done'
1935
        self.user.modified = datetime.now()
1936
        self.user.disposition=self.callDisposition
1937
        if self.callHistoryCrm.disposition_description is not None:
1938
            self.callHistoryCrm.disposition_description = 'App link sent via ' + self.callHistoryCrm.disposition_description
1939
        else: 
1940
            self.callHistoryCrm.disposition_description = 'App link sent'
1941
        session.commit()
1942
        return True
1943
 
1944
 
18628 manas 1945
    def accsOrderDisposition(self):
1946
        self.user.status='done'
1947
        self.user.user_available = 1
1948
        self.user.disposition=self.callDisposition
1949
        self.user.modified = datetime.now()
18712 manas 1950
        a = CrmTicketDtr()
18628 manas 1951
        if self.callDisposition == 'product_availability':
1952
            self.callHistoryCrm.disposition_description='Product Not available'
1953
        elif self.callDisposition == 'return_replacement':
1954
            self.callHistoryCrm.disposition_description='Return or replacement pending'
18923 manas 1955
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18713 manas 1956
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)
18628 manas 1957
        elif self.callDisposition == 'already_purchased':
1958
            self.callHistoryCrm.disposition_description='Already purchased required stock'
19442 manas 1959
        elif self.callDisposition == 'scheme_not_clear':
1960
            self.callHistoryCrm.disposition_description='Scheme Not Clear to the User'
18628 manas 1961
        elif self.callDisposition == 'product_quality_issue':
1962
            self.callHistoryCrm.disposition_description='Product Quality issue'
18923 manas 1963
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18713 manas 1964
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)            
18628 manas 1965
        elif self.callDisposition == 'delayed_delivery':
18637 manas 1966
            self.callHistoryCrm.disposition_description='Delayed Delivery' 
18923 manas 1967
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18713 manas 1968
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)   
18628 manas 1969
        elif self.callDisposition == 'other_complaint':
18637 manas 1970
            self.callHistoryCrm.disposition_description='Other complaint with profitmandi'
18923 manas 1971
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18713 manas 1972
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)
18671 manas 1973
        elif self.callDisposition == 'not_dealing_accessories':
1974
            self.callHistoryCrm.disposition_description='Not Dealing in Accessories/Not Interested'        
18628 manas 1975
        session.commit()
1976
        jdata = self.inputs
1977
        jdata = json.loads(jdata)
1978
        if jdata:
1979
            for d in jdata:
1980
                for key, value in d.iteritems():
1981
                    productpricingInputs = ProductPricingInputs()
1982
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
1983
                    productpricingInputs.agent_id = self.callHistoryCrm.agent_id
1984
                    productpricingInputs.disposition_id = self.callHistoryCrm.id
1985
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
1986
                    productpricingInputs.call_disposition = self.callHistoryCrm.call_disposition
1987
                    productpricingInputs.project_id = self.callHistoryCrm.project_id
1988
                    productpricingInputs.product_input = key
1989
                    productpricingInputs.pricing_input = value
1990
            session.commit()        
1991
        return True
1992
 
20133 rajender 1993
    def willplaceorder(self,):
20136 rajender 1994
        self.user.status='done'
1995
        self.user.modified = datetime.now()
1996
        self.user.disposition=self.callDisposition
1997
        if self.callHistoryCrm.disposition_description is None:
1998
            self.callHistoryCrm.disposition_description = 'User will place order from now' 
20133 rajender 1999
        session.commit()
2000
        return True
20136 rajender 2001
 
20133 rajender 2002
    def orderdiffaccount(self,):
20136 rajender 2003
        self.user.status='done'
2004
        self.user.modified = datetime.now()
2005
        self.user.disposition=self.callDisposition
2006
        if self.callHistoryCrm.disposition_description is None:
2007
            self.callHistoryCrm.disposition_description = 'Placing Order from Different Account' 
20133 rajender 2008
        session.commit()
2009
        return True
20136 rajender 2010
 
20133 rajender 2011
 
2012
    def businessclosed(self,):
20136 rajender 2013
        self.user.status='done'
2014
        self.user.modified = datetime.now()
2015
        self.user.disposition=self.callDisposition
2016
        if self.callHistoryCrm.disposition_description is None:
2017
            self.callHistoryCrm.disposition_description = 'Business Closed' 
20133 rajender 2018
        session.commit()
2019
        return True
20136 rajender 2020
 
20133 rajender 2021
 
2022
    def appuninstalled(self,):
20136 rajender 2023
        self.user.status='done'
2024
        self.user.modified = datetime.now()
2025
        self.user.disposition=self.callDisposition
2026
        if self.callHistoryCrm.disposition_description is None:
2027
            self.callHistoryCrm.disposition_description = 'User uninstalled application' 
2028
        a = CrmTicketDtr()
2029
        a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)
20133 rajender 2030
        session.commit()
2031
        return True
20136 rajender 2032
 
2033
 
20133 rajender 2034
    def invalidNumber(self,):
20136 rajender 2035
 
20133 rajender 2036
        self.user.modified = datetime.now()
2037
        if self.callDisposition == 'invalid_no':
20136 rajender 2038
 
20133 rajender 2039
            self.user.disposition=self.callDisposition
2040
            self.callHistoryCrm.disposition_description = 'Invalid Number'
2041
        elif self.callDisposition == 'wrong_no':
20136 rajender 2042
 
20133 rajender 2043
            self.user.disposition=self.callDisposition
2044
            self.callHistoryCrm.disposition_description = 'Wrong Number'
2045
        elif self.callDisposition == 'hang_up':
20136 rajender 2046
 
20133 rajender 2047
            self.user.disposition=self.callDisposition
2048
            self.callHistoryCrm.disposition_description = 'Hang Up'
2049
        elif self.callDisposition == 'retailer_not_interested':
20136 rajender 2050
 
20133 rajender 2051
            self.user.disposition=self.callDisposition
2052
            if self.callHistoryCrm.disposition_description is None:
2053
                self.callHistoryCrm.disposition_description = 'NA'
2054
            self.callHistoryCrm.disposition_description = 'Reason Retailer Not Interested ' + self.callHistoryCrm.disposition_description
2055
        elif self.callDisposition == 'recharge_retailer':
20136 rajender 2056
 
20133 rajender 2057
            self.user.disposition=self.callDisposition
2058
            self.callHistoryCrm.disposition_description = 'Recharge related. Not a retailer '
2059
        elif self.callDisposition == 'service_center_retailer':
20136 rajender 2060
 
20133 rajender 2061
            self.user.disposition=self.callDisposition
2062
            self.callHistoryCrm.disposition_description = 'Service Center related. Not a retailer'
2063
        elif self.callDisposition == 'not_retailer':
20136 rajender 2064
 
20133 rajender 2065
            self.user.disposition=self.callDisposition
2066
            self.callHistoryCrm.disposition_description = 'Not a retailer'    
2067
        session.commit()
2068
        return True  
2069
 
2070
    def otherreason(self,):
20136 rajender 2071
        self.user.status='done'
20133 rajender 2072
        self.user.modified = datetime.now()
2073
        self.user.disposition=self.callDisposition
2074
        if self.callHistoryCrm.disposition_description is None:
2075
            self.callHistoryCrm.disposition_description = 'Other Reasons' 
2076
        session.commit()
2077
        return True
2078
 
2079
 
18291 manas 2080
    def accsDisposition(self):
2081
        self.user.status='done'
2082
        self.user.user_available = 1
2083
        self.user.disposition=self.callDisposition
2084
        self.user.modified = datetime.now()
2085
        if self.callDisposition == 'technical_issue':
2086
            self.callHistoryCrm.disposition_description='Technical issue at Profitmandi'
18923 manas 2087
            #utils.sendCrmProjectMail(self.userId,self.callHistoryCrm.disposition_description,self.callHistoryCrm.disposition_comments)
18716 manas 2088
            a = CrmTicketDtr()
2089
            a.addTicket(self.userId, self.callHistoryCrm.disposition_description, self.callHistoryCrm.disposition_comments)
18291 manas 2090
        elif self.callDisposition == 'pricing_issue':
2091
            self.callHistoryCrm.disposition_description='Pricing Issue(High)'
2092
        elif self.callDisposition == 'shipping_issue':
2093
            self.callHistoryCrm.disposition_description='Shipping charges related issue'
2094
        elif self.callDisposition == 'internet_issue':
2095
            self.callHistoryCrm.disposition_description='Internet issue at user end'
2096
        elif self.callDisposition == 'checking_price':
2097
            self.callHistoryCrm.disposition_description='Checking price'    
2098
        elif self.callDisposition == 'order_process':
2099
            self.callHistoryCrm.disposition_description='Order Process inquery'    
2100
        elif self.callDisposition == 'placed_order':
2101
            self.callHistoryCrm.disposition_description='Placed Order from Different Account'    
2102
        elif self.callDisposition == 'place_order':
2103
            self.callHistoryCrm.disposition_description='Will Place Order'            
2104
        session.commit()
18360 manas 2105
        jdata = self.inputs
18361 manas 2106
        jdata = json.loads(jdata)
18350 manas 2107
        if jdata:
2108
            for d in jdata:
18360 manas 2109
                for key, value in d.iteritems():
18350 manas 2110
                    productpricingInputs = ProductPricingInputs()
2111
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
2112
                    productpricingInputs.agent_id = self.callHistoryCrm.agent_id
2113
                    productpricingInputs.disposition_id = self.callHistoryCrm.id
2114
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
2115
                    productpricingInputs.call_disposition = self.callHistoryCrm.call_disposition
2116
                    productpricingInputs.project_id = self.callHistoryCrm.project_id
2117
                    productpricingInputs.product_input = key
2118
                    productpricingInputs.pricing_input = value
2119
            session.commit()        
18291 manas 2120
        return True
2121
 
2122
    def callLaterAccs(self):
18329 manas 2123
        self.user.status='retry'
2124
        self.user.modified = datetime.now()
18291 manas 2125
        if self.callDisposition == 'call_later':
18310 manas 2126
            if self.callHistoryCrm.disposition_comments is not None:
18321 manas 2127
                self.user.next_call_time = datetime.strptime(self.callHistoryCrm.disposition_comments, '%d/%m/%Y %H:%M:%S')
18310 manas 2128
                self.callHistoryCrm.disposition_description = 'User requested to call'
2129
                self.callHistoryCrm.disposition_comments = self.callHistoryCrm.disposition_comments
18291 manas 2130
            else:
2131
                self.user.next_call_time = self.callHistoryCrm.call_time + timedelta(days=1)
18310 manas 2132
                self.callHistoryCrm.disposition_description = 'Call Scheduled'
2133
                self.callHistoryCrm.disposition_comments = datetime.strftime(self.user.next_call_time, '%d/%m/%Y %H:%M:%S')
18291 manas 2134
        else: 
18310 manas 2135
            self.callHistoryCrm.disposition_description = 'User was not contactable'
18291 manas 2136
            if self.callDisposition == 'ringing_no_answer':
2137
                if self.user.disposition == 'ringing_no_answer':
2138
                    self.user.retry_count += 1
2139
                else:
2140
                    self.user.disposition = 'ringing_no_answer'
2141
                    self.user.retry_count = 1
2142
            else:
2143
                if self.user.disposition == 'ringing_no_answer':
2144
                    pass
2145
                else:
2146
                    self.user.disposition = 'not_reachable'
2147
                self.user.retry_count += 1
2148
                self.user.invalid_retry_count += 1
2149
 
18306 manas 2150
            retryConfig = session.query(RetryConfig).filter_by(call_type=self.callType, disposition_type=self.user.disposition, retry_count=self.user.retry_count).first()
2151
            if retryConfig is not None:
2152
                self.user.next_call_time = self.callHistoryCrm.call_time + timedelta(minutes = retryConfig.minutes_ahead)
2153
                self.callHistoryCrm.disposition_description = 'Call scheduled on ' + datetime.strftime(self.user.next_call_time, '%d/%m/%Y %H:%M:%S')
2154
            else:
2155
                self.user.status = 'failed'
18335 manas 2156
                self.user.user_available=1
18306 manas 2157
                self.callHistoryCrm.disposition_description = 'Call failed as all attempts exhausted'
18329 manas 2158
        self.user.disposition=self.callDisposition        
18291 manas 2159
        session.commit()
18347 manas 2160
        jdata =self.inputs
18361 manas 2161
        jdata = json.loads(jdata)
18350 manas 2162
        if jdata: 
2163
            for d in jdata:
18360 manas 2164
                for key, value in d.iteritems():
18350 manas 2165
                    productpricingInputs = ProductPricingInputs()
2166
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
2167
                    productpricingInputs.agent_id = self.callHistoryCrm.agent_id
2168
                    productpricingInputs.disposition_id = self.callHistoryCrm.id
2169
                    productpricingInputs.user_id = self.callHistoryCrm.user_id
2170
                    productpricingInputs.call_disposition = self.callHistoryCrm.call_disposition
2171
                    productpricingInputs.project_id = self.callHistoryCrm.project_id
2172
                    productpricingInputs.product_input = key
2173
                    productpricingInputs.pricing_input = value
2174
            session.commit()        
18291 manas 2175
        return True
2176
 
18266 manas 2177
def insertUserCrmData(project_id):
2178
    if project_id==1:  
2179
        getCartDetailsUser()
18386 manas 2180
    if project_id==2:  
2181
        getCartTabsUser()
18620 manas 2182
    if project_id==3:
2183
        getAccsRepeatUsers(project_id)
19442 manas 2184
    if project_id==4:
2185
        getAccsSchemeCashback(project_id)
20133 rajender 2186
    if project_id==5:
2187
        getInactiveUsers(project_id)
19442 manas 2188
 
20133 rajender 2189
def getInactiveUsers(project_id):
2190
    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;"
2191
    userFinalList=[]
2192
    result = fetchResult(PRIOPRITIZING_USER_QUERY)
2193
    for r in result:
2194
        userFinalList.append(r[0])
2195
    for i in userFinalList:
2196
        try:
2197
            userId=i
2198
            userPresent = session.query(UserCrmCallingData).filter_by(user_id=userId).order_by(desc(UserCrmCallingData.modified)).first()
2199
            if userPresent is not None:
2200
                if userPresent.user_available==1:
2201
                    if userPresent.project_id==project_id:
2202
                        continue
2203
                    elif userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
2204
                        continue
2205
                else:
2206
                    continue         
2207
            userMasterData = UserCrmCallingData()
2208
            userMasterData.user_id = userId 
2209
            userMasterData.name =getUsername(userId) 
2210
            userMasterData.project_id = project_id
2211
            userMasterData.user_available=0
2212
            userMasterData.contact1 = getUserContactDetails(userId)
2213
            userMasterData.counter = 0
2214
            userMasterData.retry_count=0
2215
            userMasterData.invalid_retry_count=0
2216
            userMasterData.created = datetime.now()
2217
            userMasterData.modified = datetime.now()
2218
            userMasterData.status = 'new'
2219
            userMasterData.pincode_servicable = checkPincodeServicable(userId)
2220
            session.commit()
2221
        except:
2222
            print traceback.print_exc()
2223
        finally:
2224
            session.close()
2225
 
2226
 
19442 manas 2227
def getAccsSchemeCashback(project_id):
2228
    userMasterMap={}
2229
    skipUserList=[]
19444 manas 2230
    query = "select id from users where lower(referrer) in ('emp01','emp99','emp88')"
19442 manas 2231
    skipUsersresult = fetchResult(query)
2232
    for skipUser in skipUsersresult:
2233
        skipUserList.append(skipUser[0])
2234
    queryFilter = {"user_id":{"$nin":skipUserList}}
2235
    result = get_mongo_connection().Catalog.PromoOffer.find(queryFilter)
2236
    userMasterList =[]
2237
    for r in result:
2238
        userMasterList.append(r.get('user_id'))
2239
    queryfilter ={"url":{"$regex" : "http://api.profittill.com/categories/target"}}
2240
    result = get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilter).distinct('user_id')
2241
    userSeenList=[]
2242
    for r in result:
2243
        userSeenList.append(r)
2244
    finalUserList  = list(set(userMasterList) - set(userSeenList))
2245
    queryFilter = {"user_id":{"$in":finalUserList}}
2246
    result = get_mongo_connection().Catalog.PromoOffer.find(queryFilter)
2247
    for r in result:
2248
        userMasterMap[r.get('user_id')] = r.get('target2')
2249
    d_sorted = sorted(zip(userMasterMap.values(), userMasterMap.keys()),reverse=True)
2250
    counter=0
2251
    for i in d_sorted:
2252
        try:
2253
            userId=i[1]
2254
            if counter==20:
2255
                break
20133 rajender 2256
 
2257
#             userPresent = isUserAvailable(CRM_PROJECTS_USER_AVAILABILITY.get(project_id))
19442 manas 2258
            userPresent = session.query(UserCrmCallingData).filter_by(user_id=userId).order_by(desc(UserCrmCallingData.modified)).first()
2259
            if userPresent is not None:
2260
                if userPresent.user_available==1:
2261
                    if userPresent.project_id==project_id:
2262
                        continue                        
2263
                    elif userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
2264
                        continue
2265
                else:
2266
                    continue               
2267
            counter=counter+1
2268
            userMasterData = UserCrmCallingData()
2269
            userMasterData.user_id = userId 
2270
            userMasterData.name =getUsername(userId) 
2271
            userMasterData.project_id = project_id
2272
            userMasterData.user_available=0
2273
            userMasterData.contact1 = getUserContactDetails(userId)
2274
            userMasterData.counter = 0
2275
            userMasterData.retry_count=0
2276
            userMasterData.invalid_retry_count=0
2277
            userMasterData.created = datetime.now()
2278
            userMasterData.modified = datetime.now()
2279
            userMasterData.status = 'new'
2280
            userMasterData.pincode_servicable = checkPincodeServicable(userId)
2281
            session.commit()
2282
        except:
2283
            print traceback.print_exc()
2284
        finally:
2285
            session.close()
2286
 
18620 manas 2287
def getAccsRepeatUsers(project_id):
2288
 
2289
    usersMasterList=[]
2290
    ACCS_ALL_ORDERS = "select distinct user_id from allorder where category in ('Accs','Accessories') and store_id='spice';"
2291
    result = fetchResult(ACCS_ALL_ORDERS)
2292
    for r in result:
2293
        usersMasterList.append(r[0])
2294
 
2295
    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;"
2296
    result = fetchResult(ACCS_LAST_FIFTEEN_DAYS)
2297
    for r in result:
2298
        if r[0] in usersMasterList:
2299
            usersMasterList.remove(r[0])        
2300
 
2301
    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;"
2302
    userFinalList=[]
2303
    result = fetchResult(PRIOPRITIZING_USER_QUERY)
2304
    for r in result:
2305
        userFinalList.append(r[0])
2306
 
2307
    counter=0
2308
    for i in userFinalList:
2309
        try:
2310
            userId=i
18628 manas 2311
            if counter==20:
18620 manas 2312
                break
2313
            userPresent = session.query(UserCrmCallingData).filter_by(user_id=userId).order_by(desc(UserCrmCallingData.modified)).first()
2314
            if userPresent is not None:
2315
                if userPresent.user_available==1:
2316
                    if userPresent.project_id==project_id:
2317
                        if userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
2318
                            continue
2319
                        else:
2320
                            pass    
18792 manas 2321
                    elif userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
18620 manas 2322
                        continue
2323
                else:
2324
                    continue     
2325
            counter=counter+1
2326
            userMasterData = UserCrmCallingData()
2327
            userMasterData.user_id = userId 
2328
            userMasterData.name =getUsername(userId) 
2329
            userMasterData.project_id = project_id
2330
            userMasterData.user_available=0
2331
            userMasterData.contact1 = getUserContactDetails(userId)
2332
            userMasterData.counter = 0
2333
            userMasterData.retry_count=0
2334
            userMasterData.invalid_retry_count=0
2335
            userMasterData.created = datetime.now()
2336
            userMasterData.modified = datetime.now()
2337
            userMasterData.status = 'new'
2338
            userMasterData.pincode_servicable = checkPincodeServicable(userId)
2339
            session.commit()
2340
        except:
2341
            print traceback.print_exc()
2342
        finally:
2343
            session.close()
2344
 
18256 manas 2345
def getCartDetailsUser():
2346
    userList=[]
2347
    orderUserList=[]
18818 manas 2348
    #userMasterMap={}
18256 manas 2349
    queryfilter = {"$and":
2350
                   [
18792 manas 2351
                    {'created':{"$gte":(to_java_date(datetime.now())-3*86400000)}},
18256 manas 2352
                    {'created':{"$lte":(to_java_date(datetime.now())- 43200000)}},
2353
                    {"url":{"$regex" : "http://api.profittill.com/cartdetails"}}
2354
                    ]
2355
                   }
2356
    result = get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilter).distinct('user_id')
2357
 
2358
    for r in result:
2359
        userList.append(r)
2360
 
18301 manas 2361
    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%'"
2362
 
18256 manas 2363
    result = fetchResult(myquery)
2364
    for r in result:
18301 manas 2365
        orderUserList.append(r[0])
18256 manas 2366
    finalUserList  = list(set(userList) - set(orderUserList))
2367
 
18792 manas 2368
    userCartIdMap={}
2369
    fetchCartId = "select user_id,account_key from user_accounts where account_type='cartId' and user_id in (%s)" % ",".join(map(str,finalUserList))
2370
    result = fetchResult(fetchCartId)
2371
    for r in result:
18818 manas 2372
        userCartIdMap[long(r[1])] = long(r[0])
18843 manas 2373
    client = CatalogClient("catalog_service_server_host_prod","catalog_service_server_port").get_client()
18792 manas 2374
    userMapReturned = client.getCartByValue(userCartIdMap.keys())
18818 manas 2375
    userFinalList=[]
2376
    for i in userMapReturned:
2377
        userFinalList.append(userCartIdMap.get(i))
18792 manas 2378
#     queryfilternew = {"$and":
2379
#                    [
2380
#                     {'user_id':{"$in":finalUserList}},
2381
#                     {'created':{"$gte":(to_java_date(datetime.now())-2*86400000)}},
2382
#                     {'created':{"$lte":(to_java_date(datetime.now())- 43200000)}},
2383
#                     {"url":{"$regex" : "http://api.profittill.com/cartdetails"}}
2384
#                     ]
2385
#                    }
2386
#     itemIds = list(get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilternew))
2387
#      
2388
#     for i in itemIds:
2389
#         if(userMasterMap.has_key(i.get('user_id'))):
2390
#             if userMasterMap.get(i.get('user_id')) > i.get('created'):
2391
#                 userMasterMap[i.get('user_id')]=i.get('created')
2392
#         else:
2393
#             userMasterMap[i.get('user_id')]=i.get('created')
2394
#             
2395
#     d_sorted = sorted(zip(userMasterMap.values(), userMasterMap.keys()))
18818 manas 2396
    addUserToTable(userFinalList,1)
18256 manas 2397
 
18301 manas 2398
def addUserToTable(userList,projectId):
18266 manas 2399
    counter=0
18301 manas 2400
    for i in userList:
2401
        try:
18792 manas 2402
            userId=i
18412 manas 2403
            if counter==20:
18301 manas 2404
                break
2405
            userPresent = session.query(UserCrmCallingData).filter_by(user_id=userId).order_by(desc(UserCrmCallingData.modified)).first()
2406
            if userPresent is not None:
2407
                if userPresent.user_available==1:
2408
                    if userPresent.project_id==projectId:
2409
                        continue
18792 manas 2410
                    elif userPresent.modified.date()>=(datetime.now().date()-timedelta(days=30)):
18301 manas 2411
                        continue
18306 manas 2412
                else:
2413
                    continue     
18266 manas 2414
            counter=counter+1
2415
            userMasterData = UserCrmCallingData()
2416
            userMasterData.user_id = userId 
2417
            userMasterData.name =getUsername(userId) 
18301 manas 2418
            userMasterData.project_id = projectId
18277 manas 2419
            userMasterData.user_available=0
18266 manas 2420
            userMasterData.contact1 = getUserContactDetails(userId)
2421
            userMasterData.counter = 0
18318 manas 2422
            userMasterData.retry_count=0
2423
            userMasterData.invalid_retry_count=0
18266 manas 2424
            userMasterData.created = datetime.now()
2425
            userMasterData.modified = datetime.now()
2426
            userMasterData.status = 'new'
2427
            userMasterData.pincode_servicable = checkPincodeServicable(userId)
2428
            session.commit()
18301 manas 2429
        except:
2430
            print traceback.print_exc()
2431
        finally:
2432
            session.close()    
2433
 
18256 manas 2434
def getCartTabsUser():
18346 manas 2435
    userMasterList=[]
2436
    userList = []
18256 manas 2437
    userMasterMap={}
2438
    queryfilter = {"$and":
2439
                   [
2440
                    {'created':{"$gte":(to_java_date(datetime.now())-2*86400000)}},
2441
                    {'created':{"$lte":(to_java_date(datetime.now())- 43200000)}},
2442
                    {"url":{"$regex" : "http://api.profittill.com/category/6"}}
2443
                    ]
2444
                   }
2445
    result = get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilter).distinct('user_id')
2446
 
2447
    for r in result:
18346 manas 2448
        userMasterList.append(r)
2449
 
2450
    queryfilterVisistedCart = {"$and":
2451
                   [
18386 manas 2452
                    {'user_id':{"$in":userMasterList}},
18346 manas 2453
                    {"url":{"$regex" : "http://api.profittill.com/cartdetails"}}
2454
                    ]
2455
                  }
18386 manas 2456
    result = get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilterVisistedCart).distinct('user_id')   
18346 manas 2457
    for r in result:
18256 manas 2458
        userList.append(r)
2459
 
18416 manas 2460
    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 2461
 
2462
    result = fetchResult(myquery)
2463
    for r in result:
18346 manas 2464
        if r[0] in userList:
2465
            continue
2466
        userList.append(r[0])
18386 manas 2467
 
18346 manas 2468
    finalUserList  = list(set(userMasterList) - set(userList))
18386 manas 2469
 
18256 manas 2470
    queryfilternew = {"$and":
2471
                   [
2472
                    {'user_id':{"$in":finalUserList}},
2473
                    {'created':{"$gte":(to_java_date(datetime.now())-2*86400000)}},
2474
                    {'created':{"$lte":(to_java_date(datetime.now())- 43200000)}},
2475
                    {"url":{"$regex" : "http://api.profittill.com/category/6"}}
2476
                    ]
2477
                   }
2478
    itemIds = list(get_mongo_connection_dtr_data().User.browsinghistories.find(queryfilternew))
2479
 
2480
    for i in itemIds:
2481
        if(userMasterMap.has_key(i.get('user_id'))):
2482
            if userMasterMap.get(i.get('user_id')) > i.get('created'):
2483
                userMasterMap[i.get('user_id')]=i.get('created')
2484
        else:
2485
            userMasterMap[i.get('user_id')]=i.get('created')
2486
 
2487
    d_sorted = sorted(zip(userMasterMap.values(), userMasterMap.keys()))
18792 manas 2488
    userFinalList=[]
2489
    for i in d_sorted:
2490
        userFinalList.append(i[1])
2491
    addUserToTable(userFinalList,2)
18346 manas 2492
 
18266 manas 2493
def getUserContactDetails(userId):
18792 manas 2494
    r = session.query(Users.mobile_number).filter_by(id=userId).first()
2495
    if r is None:
2496
        return None
2497
    else:
2498
        return r[0]
18712 manas 2499
 
18266 manas 2500
def getUsername(userId):
18792 manas 2501
    r = session.query(Users.first_name).filter_by(id=userId).first()
2502
    if r is None:
2503
        return None
2504
    else:
2505
        return r[0]
2506
 
18266 manas 2507
def checkPincodeServicable(userId):
2508
    checkAddressUser = "select distinct pincode from all_user_addresses where user_id= (%s)"
2509
    result = fetchResult(checkAddressUser,userId)
2510
    if len(result)==0:
2511
        return True
2512
    else:
2513
        myquery = "select count(*) from (select distinct pincode from all_user_addresses where user_id= (%s))a join pincodeavailability p on a.pincode=p.code"
2514
        result = fetchResult(myquery,userId)
2515
        if result[0][0]==0:
2516
            return False
2517
        else:
2518
            return True
2519
 
2520
def getUserObject(user):
2521
    obj = Mock()
2522
    obj.user_id = user.user_id
2523
    result = fetchResult("select * from useractive where user_id=%d"%(user.user_id))
2524
    if result == ():
2525
        obj.last_active = None
2526
    else:
2527
        obj.last_active =datetime.strftime(result[0][1], '%d/%m/%Y %H:%M:%S')
18269 manas 2528
    obj.name = user.name    
18266 manas 2529
    obj.contact = user.contact1
18275 manas 2530
    obj.lastOrderTimestamp=None
18256 manas 2531
 
18275 manas 2532
    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 2533
    if details is None:
18275 manas 2534
        obj.lastOrderTimestamp =None
18266 manas 2535
    else:
18366 manas 2536
        obj.lastOrderTimestamp =datetime.strftime(details.created, '%d/%m/%Y %H:%M:%S')
18275 manas 2537
    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 2538
 
18275 manas 2539
    cartResult = fetchResult("select account_key from user_accounts where account_type ='cartId' and user_id=%d"%(user.user_id))
18266 manas 2540
    if cartResult == ():
18268 manas 2541
        obj.lastActiveCartTime = None
18266 manas 2542
    else:
2543
        conn = MySQLdb.connect("192.168.190.114", "root","shop2020", "user")
2544
        cursor = conn.cursor()
18275 manas 2545
        cursor.execute("select updated_on from cart where id=%s",(cartResult[0][0]))
18266 manas 2546
        result = cursor.fetchall()
2547
        if result ==():
18268 manas 2548
            obj.lastActiveCartTime = None
18266 manas 2549
        else:
2550
            print result
18275 manas 2551
            obj.lastActiveCartTime =datetime.strftime(result[0][0], '%d/%m/%Y %H:%M:%S')
18712 manas 2552
        conn.close()
2553
 
2554
    session.close()                
18266 manas 2555
    return obj
2556
 
18709 manas 2557
class CrmTicketDtr():
2558
    def on_post(self,req,resp):
18712 manas 2559
        try:
2560
            customerFeedbackBackMap = {}
2561
            customerFeedbackBackMap['user_id']=req.get_param("user_id")
2562
            user = session.query(Users).filter_by(id=customerFeedbackBackMap.get('user_id')).first()
2563
            if user is not None:
2564
                customerFeedbackBackMap['email']=user.email
2565
                customerFeedbackBackMap['mobile_number']=user.mobile_number
2566
                customerFeedbackBackMap['customer_name']=user.first_name + ' ' + user.last_name
2567
                customerFeedbackBackMap['subject'] = req.get_param("subject")
2568
                customerFeedbackBackMap['message'] = req.get_param("message")
2569
                customerFeedbackBackMap['created'] = datetime.now()
19761 manas 2570
                if ThriftUtils.generateCrmTicket(customerFeedbackBackMap):
18712 manas 2571
                    resp.body={"result":"success"}
2572
                else:
2573
                    resp.body={"result":"failure"}    
18709 manas 2574
            else:
18712 manas 2575
                resp.body={"result":"failure"}
2576
        except:
2577
            print traceback.print_exc()
2578
        finally:
2579
            session.close()            
18709 manas 2580
    def addTicket(self,user_id,subject,message):
18712 manas 2581
        try:
2582
            customerFeedbackBackMap = {}
2583
            customerFeedbackBackMap['user_id']=user_id
2584
            user = session.query(Users).filter_by(id=user_id).first()
2585
            if user is not None:
2586
                customerFeedbackBackMap['email']=user.email
2587
                customerFeedbackBackMap['mobile_number']=user.mobile_number
2588
                customerFeedbackBackMap['customer_name']=user.first_name + ' ' + user.last_name
2589
                customerFeedbackBackMap['subject'] = subject
2590
                customerFeedbackBackMap['message'] = message
2591
                customerFeedbackBackMap['created'] = datetime.now()
19651 manas 2592
                ThriftUtils.generateCrmTicket(customerFeedbackBackMap)
18712 manas 2593
            else:
2594
                print 'User is not present'
2595
        except:
18926 manas 2596
            print traceback.print_exc()                
2597
 
18272 kshitij.so 2598
class UnitDeal():
2599
    def on_get(self,req,resp, id):
2600
        result = Mongo.getDealById(id)
2601
        resp.body = dumps(result)
19290 kshitij.so 2602
 
2603
class SpecialOffer():
2604
    def on_get(self,req,resp):
2605
        user_id = req.get_param_as_int('user_id')
2606
        result = Mongo.getOfferForUser(user_id)
2607
        resp.body = dumps(result)
19388 kshitij.so 2608
 
2609
class BrandSubCatFilter():
2610
    def on_get(self, req, resp):
2611
        category_id = req.get_param_as_int('category_id')
2612
        id_list = req.get_param('id_list')
2613
        type = req.get_param('type')
2614
        result = Mongo.getBrandSubCategoryInfo(category_id, id_list, type)
2615
        resp.body = dumps(result)
19444 manas 2616
 
19451 manas 2617
class RefundAmountWallet():
2618
    def on_post(self,req,resp):
2619
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
2620
        if Mongo.refundAmountInWallet(jsonReq):
2621
            resp.body = "{\"result\":\"success\"}"
2622
        else:
2623
            resp.body = "{\"result\":\"failed\"}"
2624
 
2625
    def on_get(self,req,resp):
2626
        offset = req.get_param_as_int("offset")
2627
        limit = req.get_param_as_int("limit")
2628
        status = req.get_param("status")
19529 manas 2629
        if status: 
2630
            userRefundDetails = Mongo.fetchCrmRefundUsers(status,offset,limit)
2631
        else:
2632
            userRefundDetails = Mongo.fetchCrmRefundUsers(None,offset,limit)
19454 manas 2633
        if userRefundDetails is not None:
19457 manas 2634
            resp.body = dumps(userRefundDetails)
19454 manas 2635
        else:
2636
            resp.body ="{}"
19463 manas 2637
 
2638
class RefundWalletStatus():
2639
    def on_post(self,req,resp):
2640
        status = req.get_param('status')
2641
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
19479 manas 2642
        user_id = int(jsonReq.get('user_id'))
19463 manas 2643
        _id = jsonReq.get('_id')
2644
        if status == utils.REFUND_ADJUSTMENT_MAP.get(1):
19475 manas 2645
            value = int(jsonReq.get('amount'))
2646
            userAmountMap = {}
19469 manas 2647
            datetimeNow = datetime.now()
2648
            batchId = int(time.mktime(datetimeNow.timetuple()))
19475 manas 2649
            userAmountMap[user_id] = value
19497 manas 2650
            Mongo.updateCrmWalletStatus(status, _id,user_id,None,None)
19475 manas 2651
            if refundToWallet(batchId,userAmountMap):
2652
                refundType = jsonReq.get('type')
19497 manas 2653
                approved_by = jsonReq.get('approved_by')
19475 manas 2654
                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})
2655
                get_mongo_connection().Dtr.user.update({"userId":user_id}, {"$inc": { "credited": value, refundType:value}}, upsert=True)
19497 manas 2656
                Mongo.updateCrmWalletStatus(utils.REFUND_ADJUSTMENT_MAP.get(3), _id,user_id,batchId,approved_by)
19475 manas 2657
                print user_id,value                
19556 manas 2658
                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 2659
                resp.body = "{\"result\":\"success\"}"
2660
            else:
2661
                resp.body = "{\"result\":\"failed\"}"
19463 manas 2662
        elif status == utils.REFUND_ADJUSTMENT_MAP.get(2):
19497 manas 2663
            Mongo.updateCrmWalletStatus(status, _id,user_id,None,None)
19469 manas 2664
            resp.body = "{\"result\":\"success\"}"
2665
        else:
2666
            resp.body = "{\"result\":\"failed\"}"
19485 manas 2667
 
2668
class DetailsBatchId():
2669
    def on_get(self,req,resp):
2670
        batchId = req.get_param('batchId')
2671
        userRefundDetails = Mongo.fetchCrmRefundByBatchId(batchId)        
2672
        if userRefundDetails is not None:
19493 manas 2673
            resp.body = dumps(list(userRefundDetails))
19485 manas 2674
        else:
2675
            resp.body ="{}"
19654 kshitij.so 2676
 
2677
class HeaderLinks():
2678
    def on_get(self, req, resp):
2679
        category_id = req.get_param_as_int('category_id')
2680
        result = Mongo.getHeaderLinks(category_id)
2681
        resp.body = dumps(result)
19761 manas 2682
 
2683
class SendTransactionalSms():
2684
    def on_post(self,req,resp,sms_type,identifier,agentId):
19767 manas 2685
        try:
2686
            if sms_type =='code':
2687
                otherMobileNumber = req.get_param('mobile_number')
2688
                if otherMobileNumber is None or str(otherMobileNumber).strip() is '':
2689
                    retailerContact = session.query(RetailerContacts).filter_by(retailer_id=identifier).filter(RetailerContacts.contact_type=='sms').order_by(RetailerContacts.created.desc()).first()
2690
                    if retailerContact is not None:
2691
                        if retailerContact.mobile_number is not None and len(retailerContact.mobile_number)==10:
19776 manas 2692
                            smsStatus = generateSms(identifier,retailerContact.mobile_number,agentId)
19767 manas 2693
                            if smsStatus:
2694
                                resp.body = "{\"result\":\"success\"}"
2695
                            else:
2696
                                resp.body = "{\"result\":\"failed\"}"
19761 manas 2697
                        else:
19767 manas 2698
                            print 'Not a valid number to send the message to '+str(retailerContact.mobile_number)
19761 manas 2699
                            resp.body = "{\"result\":\"failed\"}"
2700
                    else:
19767 manas 2701
                        print 'No number to send the message for retailer id '+str(identifier)
19761 manas 2702
                        resp.body = "{\"result\":\"failed\"}"
2703
                else:
19767 manas 2704
                    if len(str(otherMobileNumber).strip())==10:
19776 manas 2705
                        smsStatus = generateSms(identifier,str(otherMobileNumber).strip(),agentId)
19767 manas 2706
                        if smsStatus:
2707
                            retailerContact = RetailerContacts()
2708
                            retailerContact.retailer_id = identifier
2709
                            retailerContact.agent_id = agentId
2710
                            retailerContact.call_type = 'inbound'
2711
                            retailerContact.contact_type = 'sms'
2712
                            retailerContact.mobile_number = str(otherMobileNumber).strip()
2713
                            session.commit()
2714
                            resp.body = "{\"result\":\"success\"}"
2715
 
2716
                        else:
2717
                            resp.body = "{\"result\":\"failed\"}"
19761 manas 2718
                    else:
19767 manas 2719
                        print 'Not a valid number to send the message to '+str(otherMobileNumber)
19761 manas 2720
                        resp.body = "{\"result\":\"failed\"}"
19767 manas 2721
        except:
2722
            print traceback.print_exc()
2723
        finally:
2724
            session.close()
19761 manas 2725
 
19776 manas 2726
def generateSms(identifier,mobile_number,agentId):
19761 manas 2727
    try:
2728
        retailerLink = session.query(RetailerLinks).filter_by(retailer_id=identifier).first()
2729
        retailer = session.query(Retailers).filter_by(id=identifier).first()
2730
        if retailer is not None:
2731
            if retailerLink is not None:
2732
                code = retailerLink.code
2733
                retailerLink.agent_id = agentId
2734
            else: 
19776 manas 2735
                c = RetailerDetail()
2736
                code = c.getNewRandomCode()
19761 manas 2737
                retailerLink = RetailerLinks()
2738
                retailerLink.code = code
19776 manas 2739
                retailerLink.agent_id = agentId
2740
                retailerLink.retailer_id = identifier
19761 manas 2741
                activationCode=Activation_Codes()
2742
                activationCode.code = code
19777 manas 2743
                activationCode.status = False
19761 manas 2744
            profitmandiUrl = make_tiny(code)
19784 manas 2745
            smsText = "Dear Customer,Download ProfitMandi app now. Get best deals on mobiles & accessories.Invite Code-" + code + " Click to download " + profitmandiUrl
19761 manas 2746
            url_params = { 'ani' : '91'+mobile_number,  'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'cli' : 'PROFTM', 'message' : smsText.strip() }
2747
            encoded_url_params = urllib.urlencode(url_params)
2748
            print 'Mobile Number :- '+str(mobile_number) +' Url Params:- '+str(encoded_url_params)
2749
            url = TRANSACTIONAL_SMS_SEND_URL + encoded_url_params
2750
            response_str = None
2751
            try:
2752
                req = urllib2.Request(url)
2753
                response = urllib2.urlopen(req)
2754
                response_str = response.read()
2755
            except:
2756
                print 'Error while getting response for user id:- Mobile Number:- '+str(mobile_number)
2757
                traceback.print_exc()
2758
                return False
2759
            print 'Mobile Number:- '+str(mobile_number) +' Sent Response:- '+ str(response_str)
2760
            try:
2761
                sms = profitmandi_sms()
2762
                sms.mobile_number = mobile_number
2763
                sms.sms_type = 'code'
2764
                sms.identifier = identifier 
2765
                if "Message sent successfully to " in response_str:
2766
                    response_str_vals = response_str.split('#')
2767
                    sms.status = "smsprocessed"
2768
                    sms.sms_id = response_str_vals[0]
2769
                else:
2770
                    sms.status = "smsrejected"
2771
                    sms.sms_id = None
2772
            except:
2773
                print 'Error while getting response for user id:- Mobile Number:- '+str(mobile_number)
2774
                traceback.print_exc()
2775
                return False
2776
            retailer.status='followup'
2777
            retailer.disposition = 'auto_text_sent'
2778
            retailer.next_call_time = datetime.now() + timedelta(days=1)
2779
            session.commit()
2780
            return True
2781
        else:
2782
            return False
2783
    except:
2784
        print traceback.print_exc()
2785
        return False
2786
    finally:
2787
        session.close()
19897 kshitij.so 2788
 
2789
class FilterDealsByType():
2790
    def on_get(self, req, resp):
2791
        categoryId = req.get_param_as_int("categoryId")
2792
        offset = req.get_param_as_int("offset")
2793
        limit = req.get_param_as_int("limit")
2794
        type = req.get_param("type")
2795
        result = Mongo.getDealsByType(categoryId, offset, limit, type)
2796
        resp.body = dumps(result) 
2797
 
19761 manas 2798
 
19879 naman 2799
 
2800
class GetItemCashback():
2801
    def on_get(self ,req,res):
2802
        itemcashback_id = req.get_param('id')
2803
        offsetval = req.get_param_as_int('offset')
2804
        limitval = req.get_param_as_int('limit')
2805
        allitemcashback = Mongo.getAllItemCasback(itemcashback_id,offsetval,limitval)
2806
        try: 
2807
            if allitemcashback:
2808
                res.body = dumps(allitemcashback)
2809
        except:
2810
                res.body = dumps({})
2811
 
2812
 
2813
    def on_post(self,req,res):
2814
        jsonReq = json.loads(req.stream.read(), encoding='utf-8')
2815
        item_skuId = jsonReq.get('sku')
2816
        cb = jsonReq.get('cash_back')
2817
        cb_description = jsonReq.get('cash_back_description')
2818
        cb_type = jsonReq.get('cash_back_type')
2819
        cb_status = jsonReq.get('cash_back_status')
2820
        response = Mongo.itemCashbackAdd(item_skuId,cb,cb_description,cb_type,cb_status)
2821
        try:
2822
            if response:
2823
                res.body = dumps({"result":"success"})
2824
        except:
2825
            res.body = dumps({"result":"failed"})
20079 kshitij.so 2826
 
2827
class AutoComplete():
2828
    def on_get(self, req, resp):
2829
        search_term = req.get_param('searchString')
2830
        try:
20170 kshitij.so 2831
            resp.body = dumps(getSuggestions(search_term))
20079 kshitij.so 2832
        except:
2833
            resp.body = dumps([])
21157 kshitij.so 2834
 
2835
 
2836
class UserDetails():
21158 kshitij.so 2837
    def on_get(self,req,resp,saholic_user_ids):
2838
        print saholic_user_ids
2839
        user_ids = [(user_id) for user_id in saholic_user_ids.split(',')]
2840
        print user_ids
21157 kshitij.so 2841
        user_map = {}
21158 kshitij.so 2842
        d_users = session.query(Users.first_name, Users.last_name, Users.email, Users.mobile_number, user_accounts.account_key).join((user_accounts,Users.id == user_accounts.user_id)).filter(user_accounts.account_key.in_(user_ids)).filter(user_accounts.account_type == 'saholic').all()
21157 kshitij.so 2843
        for user in d_users:
2844
            user_map[int(user[4])] = {'first_name':user[0],'last_name':user[1],'email':user[2],'mobile_number':user[3]}
2845
        try:
2846
            resp.body = dumps(user_map)
2847
        except:
2848
            resp.body = dumps({})
2849
        finally:
2850
            session.close()
2851
 
15312 amit.gupta 2852
def main():
18386 manas 2853
    a = RetailerDetail()
2854
    retailer = a.getNotActiveRetailer()
2855
    otherContacts = [r for r, in session.query(RetailerContacts.mobile_number).filter_by(retailer_id=retailer.id).order_by(RetailerContacts.contact_type).all()]
2856
    print json.dumps(todict(getRetailerObj(retailer, otherContacts, 'fresh')), encoding='utf-8')
15195 manas 2857
 
15081 amit.gupta 2858
if __name__ == '__main__':
19879 naman 2859
    main()
2860