Subversion Repositories SmartDukaan

Rev

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

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