Subversion Repositories SmartDukaan

Rev

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

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