Subversion Repositories SmartDukaan

Rev

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