Subversion Repositories SmartDukaan

Rev

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

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