Subversion Repositories SmartDukaan

Rev

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