Subversion Repositories SmartDukaan

Rev

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