Subversion Repositories SmartDukaan

Rev

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

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