Subversion Repositories SmartDukaan

Rev

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

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