Subversion Repositories SmartDukaan

Rev

Rev 13970 | Rev 13987 | 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
                     }
230
                ])['result'][0]
13986 amit.gupta 231
 
232
    result.pop("_id")
233
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), 0),"%Y-%m-%d %H:%M:%S")
13927 amit.gupta 234
    return result
13795 kshitij.so 235
def getDeals(category_id, offset, limit, sort, direction):
13922 kshitij.so 236
    if not bool(cashBackMap):
13921 kshitij.so 237
        populateCashBack()
13771 kshitij.so 238
    rank = 1
239
    deals = {}
13910 kshitij.so 240
    outer_query = []
241
    outer_query.append({"showDeal":1})
242
    query = {}
243
    query['$gt'] = 0
244
    outer_query.append({'totalPoints':query})
245
    if category_id in (3,5):
246
        outer_query.append({'category_id':category_id})
13803 kshitij.so 247
    if sort is None or direction is None:
248
        direct = -1
13910 kshitij.so 249
        print outer_query
250
        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 251
    else:
13910 kshitij.so 252
        print outer_query
13803 kshitij.so 253
        direct = direction
13910 kshitij.so 254
        if sort == "bestSellerPoints":
255
            print "yes,sorting by bestSellerPoints"
256
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
257
        else:
258
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 259
    for d in data:
260
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
261
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 262
            item[0]['dealRank'] = rank
263
            try:
264
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
265
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 266
                    item[0]['cash_back_type'] = 0
267
                    item[0]['cash_back'] = 0
13921 kshitij.so 268
                else:
13928 kshitij.so 269
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
270
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 271
            except:
272
                print "Error in adding cashback to deals"
13928 kshitij.so 273
                item[0]['cash_back_type'] = 0
274
                item[0]['cash_back'] = 0
13771 kshitij.so 275
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 276
 
13771 kshitij.so 277
            rank +=1
13785 kshitij.so 278
    return sorted(deals.values(), key=itemgetter('dealRank'))
279
 
280
def getItem(skuId):
13795 kshitij.so 281
    try:
282
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
13785 kshitij.so 283
        return skuData
13795 kshitij.so 284
    except:
285
        return [{}]
13836 kshitij.so 286
 
13921 kshitij.so 287
def __getCashBack(skuId, source_id, category_id):
288
    itemCashBack = itemCashBackMap.get(skuId)
289
    if itemCashBack is not None:
290
        return itemCashBack
291
 
292
    sourceCashBack = cashBackMap.get(source_id)
293
    if sourceCashBack is not None and len(sourceCashBack) > 0:
294
        for cashBack in sourceCashBack:
295
            if cashBack.get(category_id) is None:
296
                continue
297
            else:
298
                return cashBack.get(category_id)
299
    else:
300
        return {}
301
 
13836 kshitij.so 302
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 303
    if not bool(cashBackMap):
13921 kshitij.so 304
        populateCashBack()
305
 
13836 kshitij.so 306
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 307
 
13921 kshitij.so 308
    if source_id in (1,2,4,5):
13839 kshitij.so 309
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 310
    elif source_id == 3:
13839 kshitij.so 311
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 312
    else:
313
        return {}
13836 kshitij.so 314
    if len(skuData) > 0:
13921 kshitij.so 315
 
316
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
317
        if itemCashBack is not None:
318
            return itemCashBack
319
 
320
        sourceCashBack = cashBackMap.get(source_id)
321
        if sourceCashBack is not None and len(sourceCashBack) > 0:
322
            for cashBack in sourceCashBack:
323
                if cashBack.get(skuData[0]['category_id']) is None:
324
                    continue
325
                else:
326
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 327
        else:
328
            return {} 
329
    else:
330
        return {}
13986 amit.gupta 331
 
332
 
333
def next_weekday(d, weekday):
334
    days_ahead = weekday - d.weekday()
335
    if days_ahead <= 0: # Target day already happened this week
336
        days_ahead += 7
337
    return d + timedelta(days_ahead)
338
 
13771 kshitij.so 339
 
13970 kshitij.so 340
def getAllDealerPrices(offset, limit):
341
    data = []
342
    collection = get_mongo_connection().Catalog.SkuDealerPrices
343
    cursor = collection.find().skip(offset).limit(limit)
344
    for val in cursor:
345
        master = list(get_mongo_connection().Catalog.MasterData.find({'_id':val['sku']}))
346
        if len(master) > 0:
347
            val['brand'] = master['brand']
348
            val['source_product_name'] = master['source_product_name']
349
            val['skuBundleId'] = master['skuBundleId']
350
        else:
351
            val['brand'] = ""
352
            val['source_product_name'] = ""
353
            val['skuBundleId'] = ""
354
        data.append(val)
355
    return data
356
 
357
def addSkuDealerPrice(data):
358
    collection = get_mongo_connection().Catalog.SkuDealerPrices
359
    cursor = collection.find({"sku":data['sku']})
360
    if cursor.count() > 0:
361
        return {0:"Sku information already present."}
362
    else:
363
        collection.insert(data)
364
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
365
        return {1:"Data added successfully"}
366
 
367
def updateSkuDealerPrice(data, _id):
368
    try:
369
        collection = get_mongo_connection().Catalog.SkuDealerPrices
370
        collection.update({'_id':ObjectId(_id)},{"$set":{'dp':data['dp']}},upsert=False, multi = False)
371
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
372
        return {1:"Data updated successfully"}
373
    except:
374
        return {0:"Data not updated."}
375
 
376
def updateExceptionalNlc(data, _id):
377
    try:
378
        collection = get_mongo_connection().Catalog.ExceptionalNlc
379
        collection.update({'_id':ObjectId(_id)},{"$set":{'maxNlc':data['maxNlc'], 'minNlc':data['minNlc'], 'overrideNlc':data['overrideNlc']}},upsert=False, multi = False)
380
        get_mongo_connection().Catalog.MasterData.update({'_id':data['sku']},{"$set":{'updatedOn':to_java_date(datetime.now())}},multi=False)
381
        return {1:"Data updated successfully"}
382
    except:
383
        return {0:"Data not updated."}
384
 
385
 
13572 kshitij.so 386
def main():
13986 amit.gupta 387
    getPendingRefunds(1) 
13811 kshitij.so 388
 
13921 kshitij.so 389
 
13572 kshitij.so 390
if __name__=='__main__':
13932 amit.gupta 391
    main()