Subversion Repositories SmartDukaan

Rev

Rev 13928 | Rev 13970 | 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
13927 amit.gupta 3
from dtr.main import Store
13785 kshitij.so 4
from dtr.utils.utils import to_java_date
13928 kshitij.so 5
from operator import itemgetter 
13572 kshitij.so 6
 
7
con = None
13907 kshitij.so 8
cashBackMap = {}
13921 kshitij.so 9
itemCashBackMap = {}
13572 kshitij.so 10
 
11
def get_mongo_connection(host='localhost', port=27017):
12
    global con
13
    if con is None:
14
        print "Establishing connection %s host and port %d" %(host,port)
15
        try:
16
            con = pymongo.MongoClient(host, port)
17
        except Exception, e:
18
            print e
19
            return None
20
    return con
21
 
13907 kshitij.so 22
def populateCashBack():
13921 kshitij.so 23
    print "Populating cashback"
13907 kshitij.so 24
    global cashBackMap
13921 kshitij.so 25
    global itemCashBackMap
26
    cashBackMap = {}
27
    itemCashBackMap = {}
13907 kshitij.so 28
    cashBack = list(get_mongo_connection().Catalog.CategoryCashBack.find())
29
    for row in cashBack:
30
        if cashBackMap.has_key(row['source_id']):
31
            temp_map = {}
32
            temp_list = []
33
            arr = cashBackMap.get(row['source_id'])
34
            for val in arr:
35
                temp_list.append(val)
36
            temp_map[row['category_id']] = row
37
            temp_list.append(temp_map)
38
            cashBackMap[row['source_id']] = temp_list 
39
        else:
40
            temp_map = {}
41
            temp_list = []
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):
51
    collection = get_mongo_connection().Dtr.CategoryDiscount
52
    query = []
53
    data['brand'] = data['brand'].strip().upper()
54
    query.append({"brand":data['brand']})
55
    query.append({"category_id":data['category_id']})
56
    r = collection.find({"$and":query})
57
    if r.count() > 0:
13639 kshitij.so 58
        return {0:"Brand & Category info already present."}
13572 kshitij.so 59
    else:
60
        collection.insert(data)
13639 kshitij.so 61
        return {1:"Data added successfully"}
13572 kshitij.so 62
 
63
def getAllCategoryDiscount():
64
    data = []
65
    collection = get_mongo_connection().Dtr.CategoryDiscount
66
    cursor = collection.find()
67
    for val in cursor:
68
        data.append(val)
69
    return data
70
 
71
def addSchemeDetailsForSku(data):
72
    collection = get_mongo_connection().Dtr.SkuSchemeDetails
73
    data['addedOn'] = to_java_date(datetime.now())
74
    collection.insert(data)
13639 kshitij.so 75
    return {1:"Data added successfully"}
13572 kshitij.so 76
 
77
def getAllSkuWiseSchemeDetails():
78
    data = []
79
    collection = get_mongo_connection().Dtr.SkuSchemeDetails
80
    cursor = collection.find()
81
    for val in cursor:
82
        data.append(val)
83
    return data
84
 
85
def addSkuDiscountInfo(data):
86
    collection = get_mongo_connection().Dtr.SkuDiscountInfo
87
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 88
    if cursor.count() > 0:
13639 kshitij.so 89
        return {0:"Sku information already present."}
13572 kshitij.so 90
    else:
91
        collection.insert(data)
13639 kshitij.so 92
        return {1:"Data added successfully"}
13572 kshitij.so 93
 
94
def getallSkuDiscountInfo():
95
    data = []
96
    collection = get_mongo_connection().Dtr.SkuDiscountInfo
97
    cursor = collection.find()
98
    for val in cursor:
99
        data.append(val)
100
    return data
101
 
102
def addExceptionalNlc(data):
103
    collection = get_mongo_connection().Dtr.ExceptionalNlc
104
    cursor = collection.find({"sku":data['sku']})
13642 kshitij.so 105
    if cursor.count() > 0:
13639 kshitij.so 106
        return {0:"Sku information already present."}
13572 kshitij.so 107
    else:
108
        collection.insert(data)
13639 kshitij.so 109
        return {1:"Data added successfully"}
13572 kshitij.so 110
 
111
def getAllExceptionlNlcItems():
112
    data = []
13639 kshitij.so 113
    collection = get_mongo_connection().Dtr.ExceptionalNlc
13572 kshitij.so 114
    cursor = collection.find()
115
    for val in cursor:
116
        data.append(val)
117
    return data
118
 
13582 amit.gupta 119
def getMerchantOrdersByUser(userId, page=1, window=50):
13603 amit.gupta 120
    if page==None:
121
        page = 1
122
 
123
    if window==None:
124
        window = 50
125
    result = {}
13582 amit.gupta 126
    skip = (page-1)*window
13603 amit.gupta 127
    collection = get_mongo_connection().Dtr.merchantOrder
128
    cursor = collection.find({"userId":userId})
129
    total_count = cursor.count()
130
    pages = total_count/window + (0 if total_count%window==0 else 1)  
131
    print "total_count", total_count
132
    if total_count > skip:
133
        cursor = cursor.skip(skip).limit(window)
134
        orders = []
135
        for order in cursor:
136
            del(order["_id"])
137
            orders.append(order)
138
        result['data'] = orders
139
        result['window'] = window
140
        result['totalCount'] = total_count 
141
        result['currCount'] = cursor.count()
142
        result['totalPages'] = pages
143
        result['currPage'] = page    
144
        return result
145
    else:
146
        return result
13630 kshitij.so 147
 
13927 amit.gupta 148
def getRefunds(userId, page=1, window=10):
149
    if page==None:
150
        page = 1
151
 
152
    if window==None:
153
        window = 50
154
    result = {}
155
    skip = (page-1)*window
156
    collection = get_mongo_connection().Dtr.refund
157
    cursor = collection.find({"userId":userId})
158
    total_count = cursor.count()
159
    pages = total_count/window + (0 if total_count%window==0 else 1)  
160
    print "total_count", total_count
161
    if total_count > skip:
162
        cursor = cursor.skip(skip).limit(window).sort({'batchId':-1})
163
        refunds = []
164
        for refund in cursor:
165
            del(refund["_id"])
166
            refunds.append(refund)
167
        result['data'] = refunds
168
        result['window'] = window
169
        result['totalCount'] = total_count 
170
        result['currCount'] = cursor.count()
171
        result['totalPages'] = pages
172
        result['currPage'] = page    
173
        return result
174
    else:
175
        return result
176
 
177
def getPendingRefunds(userId):
178
    result = get_mongo_connection().Dtr.merchantOrder\
179
        .aggregate([
180
                    {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED, 'userId':userId}},
181
                    {'$unwind':"$subOrders"},
182
                    { 
183
                     '$group':{
184
                               '_id':None,
185
                               'amount': { '$sum':'$subOrders.cashBackAmount'},
186
                               }
187
                     }
188
                ])['result'][0]
189
    del(result["_id"])
13932 amit.gupta 190
    result['nextCredit'] = datetime.strftime(next_weekday(datetime.now(), 0),"%Y-%m-%d %H:%M:%S") 
13927 amit.gupta 191
    return result
13795 kshitij.so 192
def getDeals(category_id, offset, limit, sort, direction):
13922 kshitij.so 193
    if not bool(cashBackMap):
13921 kshitij.so 194
        populateCashBack()
13771 kshitij.so 195
    rank = 1
196
    deals = {}
13910 kshitij.so 197
    outer_query = []
198
    outer_query.append({"showDeal":1})
199
    query = {}
200
    query['$gt'] = 0
201
    outer_query.append({'totalPoints':query})
202
    if category_id in (3,5):
203
        outer_query.append({'category_id':category_id})
13803 kshitij.so 204
    if sort is None or direction is None:
205
        direct = -1
13910 kshitij.so 206
        print outer_query
207
        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 208
    else:
13910 kshitij.so 209
        print outer_query
13803 kshitij.so 210
        direct = direction
13910 kshitij.so 211
        if sort == "bestSellerPoints":
212
            print "yes,sorting by bestSellerPoints"
213
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('bestSellerPoints',direct),('rank',direct),('nlcPoints',direct)]).skip(offset).limit(limit))
214
        else:
215
            data = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([(sort,direct)]).skip(offset).limit(limit))
13771 kshitij.so 216
    for d in data:
217
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
218
        if not deals.has_key(item[0]['identifier']):
13921 kshitij.so 219
            item[0]['dealRank'] = rank
220
            try:
221
                cashBack = __getCashBack(item[0]['_id'], item[0]['source_id'], item[0]['category_id'])
222
                if not cashBack or cashBack.get('cash_back_status')!=1:
13928 kshitij.so 223
                    item[0]['cash_back_type'] = 0
224
                    item[0]['cash_back'] = 0
13921 kshitij.so 225
                else:
13928 kshitij.so 226
                    item[0]['cash_back_type'] = cashBack['cash_back_type']
227
                    item[0]['cash_back'] = cashBack['cash_back']
13921 kshitij.so 228
            except:
229
                print "Error in adding cashback to deals"
13928 kshitij.so 230
                item[0]['cash_back_type'] = 0
231
                item[0]['cash_back'] = 0
13771 kshitij.so 232
            deals[item[0]['identifier']] = item[0]
13921 kshitij.so 233
 
13771 kshitij.so 234
            rank +=1
13785 kshitij.so 235
    return sorted(deals.values(), key=itemgetter('dealRank'))
236
 
237
def getItem(skuId):
13795 kshitij.so 238
    try:
239
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
13785 kshitij.so 240
        return skuData
13795 kshitij.so 241
    except:
242
        return [{}]
13836 kshitij.so 243
 
13921 kshitij.so 244
def __getCashBack(skuId, source_id, category_id):
245
    itemCashBack = itemCashBackMap.get(skuId)
246
    if itemCashBack is not None:
247
        return itemCashBack
248
 
249
    sourceCashBack = cashBackMap.get(source_id)
250
    if sourceCashBack is not None and len(sourceCashBack) > 0:
251
        for cashBack in sourceCashBack:
252
            if cashBack.get(category_id) is None:
253
                continue
254
            else:
255
                return cashBack.get(category_id)
256
    else:
257
        return {}
258
 
13836 kshitij.so 259
def getCashBackDetails(identifier, source_id):
13922 kshitij.so 260
    if not bool(cashBackMap):
13921 kshitij.so 261
        populateCashBack()
262
 
13836 kshitij.so 263
    """Need to add item level cashback, no data available right now."""
13771 kshitij.so 264
 
13921 kshitij.so 265
    if source_id in (1,2,4,5):
13839 kshitij.so 266
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 267
    elif source_id == 3:
13839 kshitij.so 268
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
13840 kshitij.so 269
    else:
270
        return {}
13836 kshitij.so 271
    if len(skuData) > 0:
13921 kshitij.so 272
 
273
        itemCashBack = itemCashBackMap.get(skuData[0]['_id'])
274
        if itemCashBack is not None:
275
            return itemCashBack
276
 
277
        sourceCashBack = cashBackMap.get(source_id)
278
        if sourceCashBack is not None and len(sourceCashBack) > 0:
279
            for cashBack in sourceCashBack:
280
                if cashBack.get(skuData[0]['category_id']) is None:
281
                    continue
282
                else:
283
                    return cashBack.get(skuData[0]['category_id'])
13836 kshitij.so 284
        else:
285
            return {} 
286
    else:
287
        return {}
13785 kshitij.so 288
 
13836 kshitij.so 289
 
290
 
13771 kshitij.so 291
 
13572 kshitij.so 292
def main():
13922 kshitij.so 293
    populateCashBack()
13928 kshitij.so 294
    cashBack =  __getCashBack(8839,3,5)
13922 kshitij.so 295
    if not cashBack or cashBack.get('cash_back_status')!=1:
296
        print "no"
297
    else:
298
        print cashBack 
13811 kshitij.so 299
 
13921 kshitij.so 300
 
13572 kshitij.so 301
if __name__=='__main__':
13932 amit.gupta 302
    main()
303
 
304
def next_weekday(d, weekday):
305
    days_ahead = weekday - d.weekday()
306
    if days_ahead <= 0: # Target day already happened this week
307
        days_ahead += 7
308
    return d + datetime.timedelta(days_ahead)