Subversion Repositories SmartDukaan

Rev

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

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