Subversion Repositories SmartDukaan

Rev

Rev 20457 | Rev 20697 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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