Subversion Repositories SmartDukaan

Rev

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