Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
13928 kshitij.so 1
import pymongo
13572 kshitij.so 2
from datetime import datetime
13986 amit.gupta 3
from datetime import timedelta
13927 amit.gupta 4
from dtr.main import Store
13785 kshitij.so 5
from dtr.utils.utils import to_java_date
13970 kshitij.so 6
from operator import itemgetter
7
from bson.objectid import ObjectId
13572 kshitij.so 8
 
9
con = None
13907 kshitij.so 10
cashBackMap = {}
13921 kshitij.so 11
itemCashBackMap = {}
13572 kshitij.so 12
 
13
def get_mongo_connection(host='localhost', port=27017):
14
    global con
15
    if con is None:
16
        print "Establishing connection %s host and port %d" %(host,port)
17
        try:
18
            con = pymongo.MongoClient(host, port)
19
        except Exception, e:
20
            print e
21
            return None
22
    return con
23
 
13907 kshitij.so 24
def populateCashBack():
13921 kshitij.so 25
    print "Populating cashback"
13907 kshitij.so 26
    global cashBackMap
13921 kshitij.so 27
    global itemCashBackMap
28
    cashBackMap = {}
29
    itemCashBackMap = {}
13907 kshitij.so 30
    cashBack = list(get_mongo_connection().Catalog.CategoryCashBack.find())
31
    for row in cashBack:
13970 kshitij.so 32
        temp_map = {}
33
        temp_list = []
13907 kshitij.so 34
        if cashBackMap.has_key(row['source_id']):
35
            arr = cashBackMap.get(row['source_id'])
36
            for val in arr:
37
                temp_list.append(val)
38
            temp_map[row['category_id']] = row
39
            temp_list.append(temp_map)
40
            cashBackMap[row['source_id']] = temp_list 
41
        else:
42
            temp_map[row['category_id']] = row
43
            temp_list.append(temp_map)
44
            cashBackMap[row['source_id']] = temp_list
13921 kshitij.so 45
    itemCashBack = list(get_mongo_connection().Catalog.ItemCashBack.find())
46
    for row in itemCashBack:
47
        if not itemCashBackMap.has_key(row['skuId']):
48
            itemCashBackMap[row['skuId']] = row
13907 kshitij.so 49
 
13572 kshitij.so 50
def addCategoryDiscount(data):
13970 kshitij.so 51
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 52
    query = []
53
    data['brand'] = data['brand'].strip().upper()
13970 kshitij.so 54
    data['discountType'] = data['discountType'].upper().strip()
13572 kshitij.so 55
    query.append({"brand":data['brand']})
56
    query.append({"category_id":data['category_id']})
57
    r = collection.find({"$and":query})
58
    if r.count() > 0:
13639 kshitij.so 59
        return {0:"Brand & Category info already present."}
13572 kshitij.so 60
    else:
61
        collection.insert(data)
13970 kshitij.so 62
        get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
13639 kshitij.so 63
        return {1:"Data added successfully"}
13572 kshitij.so 64
 
13970 kshitij.so 65
def updateCategoryDiscount(data,_id):
66
    try:
67
        collection = get_mongo_connection().Catalog.CategoryDiscount
68
        collection.update({'_id':ObjectId(_id)},{"$set":{'min_discount':data['min_discount'],'max_discount':data['max_discount'],'discountType':data['discountType'].upper().strip()}},upsert=False, multi = False)
69
        get_mongo_connection().Catalog.MasterData.update({'brand':data['brand'],'category_id':data['category_id']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=True)
70
        return {1:"Data updated successfully"}
71
    except:
72
        return {0:"Data not updated."}
73
 
74
 
13572 kshitij.so 75
def getAllCategoryDiscount():
76
    data = []
13970 kshitij.so 77
    collection = get_mongo_connection().Catalog.CategoryDiscount
13572 kshitij.so 78
    cursor = collection.find()
79
    for val in cursor:
80
        data.append(val)
81
    return data
82
 
83
def addSchemeDetailsForSku(data):
13970 kshitij.so 84
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
13572 kshitij.so 85
    data['addedOn'] = to_java_date(datetime.now())
86
    collection.insert(data)
13639 kshitij.so 87
    return {1:"Data added successfully"}
13572 kshitij.so 88
 
89
def getAllSkuWiseSchemeDetails():
90
    data = []
13970 kshitij.so 91
    collection = get_mongo_connection().Catalog.SkuSchemeDetails
13572 kshitij.so 92
    cursor = collection.find()
93
    for val in cursor:
94
        data.append(val)
95
    return data
96
 
97
def addSkuDiscountInfo(data):
13970 kshitij.so 98
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
13572 kshitij.so 99
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 100
    if cursor.count() > 0:
13639 kshitij.so 101
        return {0:"Sku information already present."}
13572 kshitij.so 102
    else:
103
        collection.insert(data)
13970 kshitij.so 104
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
13639 kshitij.so 105
        return {1:"Data added successfully"}
13572 kshitij.so 106
 
13970 kshitij.so 107
def getallSkuDiscountInfo(offset, limit):
13572 kshitij.so 108
    data = []
13970 kshitij.so 109
    collection = get_mongo_connection().Catalog.SkuDiscountInfo
110
    cursor = collection.find().skip(offset).limit(limit)
13572 kshitij.so 111
    for val in cursor:
13970 kshitij.so 112
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
113
        if len(master) > 0:
114
            val['brand'] = master['brand']
115
            val['source_product_name'] = master['source_product_name']
116
            val['skuBundleId'] = master['skuBundleId']
117
        else:
118
            val['brand'] = ""
119
            val['source_product_name'] = ""
120
            val['skuBundleId'] = ""
13572 kshitij.so 121
        data.append(val)
122
    return data
123
 
13970 kshitij.so 124
def updateSkuDiscount(data,_id):
125
    try:
126
        collection = get_mongo_connection().Catalog.SkuDiscountInfo
127
        collection.update({'_id':ObjectId(_id)},{"$set":{'min_discount':data['min_discount'],'max_discount':data['max_discount'],'discountType':data['discountType'].upper().strip()}},upsert=False, multi = False)
128
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
129
        return {1:"Data updated successfully"}
130
    except:
131
        return {0:"Data not updated."}
132
 
133
 
13572 kshitij.so 134
def addExceptionalNlc(data):
13970 kshitij.so 135
    collection = get_mongo_connection().Catalog.ExceptionalNlc
13572 kshitij.so 136
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 137
    if cursor.count() > 0:
13639 kshitij.so 138
        return {0:"Sku information already present."}
13572 kshitij.so 139
    else:
140
        collection.insert(data)
13970 kshitij.so 141
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
13639 kshitij.so 142
        return {1:"Data added successfully"}
13572 kshitij.so 143
 
13970 kshitij.so 144
def getAllExceptionlNlcItems(offset, limit):
13572 kshitij.so 145
    data = []
13970 kshitij.so 146
    collection = get_mongo_connection().Catalog.ExceptionalNlc
13572 kshitij.so 147
    cursor = collection.find()
148
    for val in cursor:
13970 kshitij.so 149
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
150
        if len(master) > 0:
151
            val['brand'] = master['brand']
152
            val['source_product_name'] = master['source_product_name']
153
            val['skuBundleId'] = master['skuBundleId']
154
        else:
155
            val['brand'] = ""
156
            val['source_product_name'] = ""
157
            val['skuBundleId'] = ""
13572 kshitij.so 158
        data.append(val)
159
    return data
160
 
13582 amit.gupta 161
def getMerchantOrdersByUser(userId, page=1, window=50):
13603 amit.gupta 162
    if page==None:
163
        page = 1
164
 
165
    if window==None:
166
        window = 50
167
    result = {}
13582 amit.gupta 168
    skip = (page-1)*window
13603 amit.gupta 169
    collection = get_mongo_connection().Dtr.merchantOrder
170
    cursor = collection.find({"userId":userId})
171
    total_count = cursor.count()
172
    pages = total_count/window + (0 if total_count%window==0 else 1)  
173
    print "total_count", total_count
174
    if total_count > skip:
175
        cursor = cursor.skip(skip).limit(window)
176
        orders = []
177
        for order in cursor:
178
            del(order["_id"])
179
            orders.append(order)
180
        result['data'] = orders
181
        result['window'] = window
182
        result['totalCount'] = total_count 
183
        result['currCount'] = cursor.count()
184
        result['totalPages'] = pages
185
        result['currPage'] = page    
186
        return result
187
    else:
188
        return result
13630 kshitij.so 189
 
13927 amit.gupta 190
def getRefunds(userId, page=1, window=10):
191
    if page==None:
192
        page = 1
193
 
194
    if window==None:
195
        window = 50
196
    result = {}
197
    skip = (page-1)*window
198
    collection = get_mongo_connection().Dtr.refund
199
    cursor = collection.find({"userId":userId})
200
    total_count = cursor.count()
201
    pages = total_count/window + (0 if total_count%window==0 else 1)  
202
    print "total_count", total_count
203
    if total_count > skip:
204
        cursor = cursor.skip(skip).limit(window).sort({'batchId':-1})
205
        refunds = []
206
        for refund in cursor:
207
            del(refund["_id"])
208
            refunds.append(refund)
209
        result['data'] = refunds
210
        result['window'] = window
211
        result['totalCount'] = total_count 
212
        result['currCount'] = cursor.count()
213
        result['totalPages'] = pages
214
        result['currPage'] = page    
215
        return result
216
    else:
217
        return result
218
 
219
def getPendingRefunds(userId):
220
    result = get_mongo_connection().Dtr.merchantOrder\
221
        .aggregate([
222
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED, 'userId':userId}},
223
                    {'$unwind':"$subOrders"},
224
                    { 
225
                     '$group':{
226
                               '_id':None,
227
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
228
                               }
229
                     }
13987 amit.gupta 230
                ])['result']
231
 
232
    if len(result)>0:
233
        result = result[0]        
234
        result.pop("_id")
235
    else:
236
        result={}
237
        result['amount'] = 0.0
13988 amit.gupta 238
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), 0),"%Y-%m-%d %H:%M:%S")
13927 amit.gupta 239
    return result
13795 kshitij.so 240
def getDeals(category_id, offset, limit, sort, direction):
13922 kshitij.so 241
    if not bool(cashBackMap):
13921 kshitij.so 242
        populateCashBack()
13771 kshitij.so 243
    rank = 1
244
    deals = {}
13910 kshitij.so 245
    outer_query = []
246
    outer_query.append({"showDeal":1})
247
    query = {}
248
    query['$gt'] = 0
249
    outer_query.append({'totalPoints':query})
250
    if category_id in (3,5):
251
        outer_query.append({'category_id':category_id})
13803 kshitij.so 252
    if sort is None or direction is None:
253
        direct = -1
13910 kshitij.so 254
        print outer_query
255
        data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('totalPoints',direct),('bestSellerPoints',direct),('nlcPoints',direct),('rank',direct)]).skip(offset).limit(limit))
13795 kshitij.so 256
    else:
13910 kshitij.so 257
        print outer_query
13803 kshitij.so 258
        direct = direction
13910 kshitij.so 259
        if sort == "bestSellerPoints":
260
            print "yes,sorting by bestSellerPoints"
261
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
262
        else:
263
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 264
    for d in data:
265
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
266
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 267
            item[0]['dealRank'] = rank
268
            try:
269
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
270
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 271
                    item[0]['cash_back_type'] = 0
272
                    item[0]['cash_back'] = 0
13921 kshitij.so 273
                else:
13928 kshitij.so 274
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
275
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 276
            except:
277
                print "Error in adding cashback to deals"
13928 kshitij.so 278
                item[0]['cash_back_type'] = 0
279
                item[0]['cash_back'] = 0
13771 kshitij.so 280
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 281
 
13771 kshitij.so 282
            rank +=1
13785 kshitij.so 283
    return sorted(deals.values(), key=itemgetter('dealRank'))
284
 
285
def getItem(skuId):
13795 kshitij.so 286
    try:
287
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
13785 kshitij.so 288
        return skuData
13795 kshitij.so 289
    except:
290
        return [{}]
13836 kshitij.so 291
 
13921 kshitij.so 292
def __getCashBack(skuId, source_id, category_id):
293
    itemCashBack = itemCashBackMap.get(skuId)
294
    if itemCashBack is not None:
295
        return itemCashBack
296
 
297
    sourceCashBack = cashBackMap.get(source_id)
298
    if sourceCashBack is not None and len(sourceCashBack) > 0:
299
        for cashBack in sourceCashBack:
300
            if cashBack.get(category_id) is None:
301
                continue
302
            else:
303
                return cashBack.get(category_id)
304
    else:
305
        return {}
306
 
13836 kshitij.so 307
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 308
    if not bool(cashBackMap):
13921 kshitij.so 309
        populateCashBack()
310
 
13836 kshitij.so 311
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 312
 
13921 kshitij.so 313
    if source_id in (1,2,4,5):
13839 kshitij.so 314
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 315
    elif source_id == 3:
13839 kshitij.so 316
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 317
    else:
318
        return {}
13836 kshitij.so 319
    if len(skuData) > 0:
13921 kshitij.so 320
 
321
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
322
        if itemCashBack is not None:
323
            return itemCashBack
324
 
325
        sourceCashBack = cashBackMap.get(source_id)
326
        if sourceCashBack is not None and len(sourceCashBack) > 0:
327
            for cashBack in sourceCashBack:
328
                if cashBack.get(skuData[0]['category_id']) is None:
329
                    continue
330
                else:
331
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 332
        else:
333
            return {} 
334
    else:
335
        return {}
13986 amit.gupta 336
 
337
 
338
def next_weekday(d, weekday):
339
    days_ahead = weekday - d.weekday()
340
    if days_ahead <= 0: # Target day already happened this week
341
        days_ahead += 7
342
    return d + timedelta(days_ahead)
343
 
13771 kshitij.so 344
 
13970 kshitij.so 345
def getAllDealerPrices(offset, limit):
346
    data = []
347
    collection = get_mongo_connection().Catalog.SkuDealerPrices
348
    cursor = collection.find().skip(offset).limit(limit)
349
    for val in cursor:
350
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
351
        if len(master) > 0:
352
            val['brand'] = master['brand']
353
            val['source_product_name'] = master['source_product_name']
354
            val['skuBundleId'] = master['skuBundleId']
355
        else:
356
            val['brand'] = ""
357
            val['source_product_name'] = ""
358
            val['skuBundleId'] = ""
359
        data.append(val)
360
    return data
361
 
362
def addSkuDealerPrice(data):
363
    collection = get_mongo_connection().Catalog.SkuDealerPrices
364
    cursor = collection.find({"sku":data['sku']})
365
    if cursor.count() > 0:
366
        return {0:"Sku information already present."}
367
    else:
368
        collection.insert(data)
369
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
370
        return {1:"Data added successfully"}
371
 
372
def updateSkuDealerPrice(data, _id):
373
    try:
374
        collection = get_mongo_connection().Catalog.SkuDealerPrices
375
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
376
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
377
        return {1:"Data updated successfully"}
378
    except:
379
        return {0:"Data not updated."}
380
 
381
def updateExceptionalNlc(data, _id):
382
    try:
383
        collection = get_mongo_connection().Catalog.ExceptionalNlc
384
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
385
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
386
        return {1:"Data updated successfully"}
387
    except:
388
        return {0:"Data not updated."}
389
 
390
 
13572 kshitij.so 391
def main():
13989 amit.gupta 392
    print getPendingRefunds(15) 
13811 kshitij.so 393
 
13921 kshitij.so 394
 
13572 kshitij.so 395
if __name__=='__main__':
13932 amit.gupta 396
    main()