Subversion Repositories SmartDukaan

Rev

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