Subversion Repositories SmartDukaan

Rev

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

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