Subversion Repositories SmartDukaan

Rev

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