Subversion Repositories SmartDukaan

Rev

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