Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
13828 kshitij.so 1
from elixir import * 
2
from shop2020.model.v1.catalog.impl import DataService
3
from shop2020.model.v1.catalog.impl.DataService import PrivateDeals, Item
4
from sqlalchemy.sql.functions import now
5
from datetime import datetime, timedelta
6
import pymongo
7
from dtr.utils.utils import to_java_date
13843 kshitij.so 8
import optparse
14325 kshitij.so 9
from dtr.storage.MemCache import MemCache
14705 kshitij.so 10
from dtr.utils.utils import getCashBack
15268 kshitij.so 11
from dtr.utils.utils import getNlcPoints
12
import traceback
13828 kshitij.so 13
 
14
dealsMap = {}
15
con = None
16
dealsCatalogIds = []
17
itemCatalogMap = {}
18
 
13843 kshitij.so 19
parser = optparse.OptionParser()
14259 kshitij.so 20
parser.add_option("-H", "--host", dest="hostname",
13843 kshitij.so 21
                      default="localhost",
22
                      type="string", help="The HOST where the DB server is running",
14259 kshitij.so 23
                      metavar="db_host")
14253 kshitij.so 24
parser.add_option("-m", "--m", dest="mongoHost",
25
                      default="localhost",
26
                      type="string", help="The HOST where the mongo server is running",
27
                      metavar="mongo_host")
13828 kshitij.so 28
 
13849 kshitij.so 29
(options, args) = parser.parse_args()
14325 kshitij.so 30
 
31
mc = MemCache(options.mongoHost)
32
 
13843 kshitij.so 33
DataService.initialize(db_hostname=options.hostname)
34
 
16019 kshitij.so 35
SOURCE_MAP = {'AMAZON':1,'FLIPKART':2,'SNAPDEAL':3,'SAHOLIC':4, 'SHOPCLUES.COM':5}
36
 
14253 kshitij.so 37
def get_mongo_connection(host=options.mongoHost, port=27017):
13828 kshitij.so 38
    global con
39
    if con is None:
40
        print "Establishing connection %s host and port %d" %(host,port)
41
        try:
42
            con = pymongo.MongoClient(host, port)
43
        except Exception, e:
44
            print e
45
            return None
46
    return con
47
 
48
def getPrivateDeals():
14259 kshitij.so 49
    try:
50
        global dealsMap
51
        dealsMap = dict()
52
        all_active_items_query =  session.query(PrivateDeals).filter(PrivateDeals.isActive==True).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate))
53
        all_active_private_deals = all_active_items_query.all()
54
        if all_active_private_deals is not None or all_active_private_deals!=[]:
55
            for active_private_deal in all_active_private_deals:
15268 kshitij.so 56
                print active_private_deal.item_id
14259 kshitij.so 57
                item = Item.get_by(id = active_private_deal.item_id)
58
                if item.sellingPrice >  active_private_deal.dealPrice and item.status==3:
59
                    dealsMap[active_private_deal.item_id] = active_private_deal
60
    finally:
61
        session.close()
13828 kshitij.so 62
 
63
def getItemsToUpdate():
64
    global dealsCatalogIds
65
    global itemCatalogMap
15268 kshitij.so 66
    toScrapMap = {}
14130 kshitij.so 67
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{"$gt":0}}))
68
    for bestSeller in bestSellers: 
69
        saholicCatalogIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':4}))
70
        for d in saholicCatalogIds:
71
            if d['source_id']!=4:
72
                continue
15268 kshitij.so 73
            d['dealFlag'] = 0
74
            d['dealType'] = 0
75
            d['dealPoints'] = 0
76
            d['manualDealThresholdPrice'] = None
77
            toScrapMap[d['_id']] = d
14130 kshitij.so 78
            dealsCatalogIds.append(long(d['identifier'].strip()))
15268 kshitij.so 79
    dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':4,'showDeal':1,'totalPoints':{'$gt':0}}))
80
    for deal in dealFlagged:
81
        if not toScrapMap.has_key(deal['_id']):
82
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':deal['_id']}))
83
            data[0]['dealFlag'] = 0
84
            data[0]['dealType'] = 0
85
            data[0]['dealPoints'] = 0
86
            data[0]['manualDealThresholdPrice'] = None
87
            toScrapMap[deal['_id']] = data[0]
88
            if long(data[0]['identifier'].strip()) not in dealsCatalogIds: 
89
                dealsCatalogIds.append(long(data[0]['identifier'].strip()))
90
    manualDeals = list(get_mongo_connection().Catalog.ManualDeals.find({'startDate':{'$lte':to_java_date(datetime.now())},'endDate':{'$gte':to_java_date(datetime.now())},'source_id':4}))
91
    for manualDeal in manualDeals:
92
        if not toScrapMap.has_key(manualDeal['sku']):
93
            data = list(get_mongo_connection().Catalog.MasterData.find({'_id':manualDeal['sku']}))
94
            if len(data) > 0:
95
                data[0]['dealFlag'] = 1
96
                data[0]['dealType'] = manualDeal['dealType']
97
                data[0]['dealPoints'] = manualDeal['dealPoints']
98
                data[0]['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
99
                toScrapMap[manualDeal['sku']] = data[0]
100
                if long(data[0]['identifier'].strip()) not in dealsCatalogIds: 
101
                    dealsCatalogIds.append(long(data[0]['identifier'].strip()))
102
        else:
103
            data = toScrapMap.get(manualDeal['sku'])
104
            data['dealFlag'] = 1
105
            data['dealType'] = manualDeal['dealType']
106
            data['dealPoints'] = manualDeal['dealPoints']
107
            data['manualDealThresholdPrice'] = manualDeal['dealThresholdPrice']
108
 
13828 kshitij.so 109
    items = Item.query.filter(Item.catalog_item_id.in_(dealsCatalogIds)).all()
110
    for item in items:
111
        temp = []
112
        if not itemCatalogMap.has_key(item.catalog_item_id):
113
            temp.append(item)
14179 kshitij.so 114
            print "****",item.catalog_item_id
13828 kshitij.so 115
            itemCatalogMap[item.catalog_item_id] = temp
116
        else:
117
            val = itemCatalogMap.get(item.catalog_item_id)
118
            for l in val:
119
                temp.append(l)
120
            temp.append(item)
121
            itemCatalogMap[item.catalog_item_id] = temp
122
 
15268 kshitij.so 123
    for saholicCatalogId in toScrapMap.itervalues():
14129 kshitij.so 124
        if saholicCatalogId['source_id']!=4:
125
            continue
13916 kshitij.so 126
        d_items = itemCatalogMap.get(long(saholicCatalogId['identifier'].strip()))
13828 kshitij.so 127
        available_price = None
14179 kshitij.so 128
        in_stock = 0
129
        if d_items is not None:
13828 kshitij.so 130
            for d_item in d_items:
14179 kshitij.so 131
                in_stock = 0 
13828 kshitij.so 132
                if d_item.status == 3:
133
                    in_stock =1
14179 kshitij.so 134
                else:
135
                    continue
136
                if dealsMap.get(d_item.id) is not None:
137
                    available_price = dealsMap.get(d_item.id).dealPrice
138
                if (available_price !=None):
13828 kshitij.so 139
                    break
14179 kshitij.so 140
        if (available_price is None):
141
            in_stock = 0
142
            if d_items is not None:
143
                for d_item in d_items:
144
                    if d_item.status == 3:
145
                        available_price = d_item.sellingPrice
146
                        in_stock =1
147
                        break
13828 kshitij.so 148
        print long(saholicCatalogId['identifier'])
149
        print in_stock
150
        print available_price
151
        print dealsMap.get(d_item.id)
152
        print "++++++++++++++++++++++++++"
13850 kshitij.so 153
        if available_price > 0 or available_price is not None:
14127 kshitij.so 154
            get_mongo_connection().Catalog.MasterData.update({'_id':saholicCatalogId['_id']}, {'$set' : {'available_price':available_price,'updatedOn':to_java_date(datetime.now()),'priceUpdatedOn':to_java_date(datetime.now()),'in_stock':in_stock}}, multi=True)
13916 kshitij.so 155
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'available_price':available_price , 'in_stock':in_stock}}, multi=True)
13828 kshitij.so 156
        else:
14127 kshitij.so 157
            get_mongo_connection().Catalog.MasterData.update({'_id':saholicCatalogId['_id']}, {'$set' : {'updatedOn':to_java_date(datetime.now()),'in_stock':in_stock,'priceUpdatedOn':to_java_date(datetime.now())}}, multi=True)
13916 kshitij.so 158
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'in_stock':in_stock}}, multi=True)
13828 kshitij.so 159
 
13916 kshitij.so 160
        try:
15268 kshitij.so 161
            recomputeDeal(saholicCatalogId)
13916 kshitij.so 162
        except:
163
            print "Unable to compute deal for ",saholicCatalogId['skuBundleId']
164
 
14325 kshitij.so 165
def populateNegativeDeals():
166
    negativeDeals = get_mongo_connection().Catalog.NegativeDeals.find().distinct('sku')
15268 kshitij.so 167
    mc.set("negative_deals", negativeDeals, 600)
168
 
169
def recomputePoints(item, deal):
170
    try:
171
        nlcPoints = getNlcPoints(item, deal['minNlc'], deal['maxNlc'], deal['available_price'])
172
    except:
173
        traceback.print_exc()
174
        nlcPoints = deal['nlcPoints']
175
    if item['manualDealThresholdPrice'] >= deal['available_price']:
176
        dealPoints = item['dealPoints']
177
    else:
178
        dealPoints = 0
179
    get_mongo_connection().Catalog.Deals.update({'_id':deal['_id']},{"$set":{'totalPoints':deal['totalPoints'] - deal['nlcPoints'] + nlcPoints - deal['dealPoints'] +dealPoints , 'nlcPoints': nlcPoints, 'dealPoints': dealPoints, 'manualDealThresholdPrice': item['manualDealThresholdPrice']}})
14325 kshitij.so 180
 
15268 kshitij.so 181
 
182
def recomputeDeal(item):
13916 kshitij.so 183
    """Lets recompute deal for this bundle"""
16019 kshitij.so 184
    print "Recomputing for bundleId %d" %(item.get('skuBundleId'))
15268 kshitij.so 185
    skuBundleId = item['skuBundleId']
13916 kshitij.so 186
 
187
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
188
    bestPrice = float("inf")
189
    bestOne = None
190
    bestSellerPoints = 0
191
    toUpdate = []
16019 kshitij.so 192
    prepaidBestPrice = float("inf")
193
    prepaidBestOne = None
194
    prepaidBestSellerPoints = 0
13916 kshitij.so 195
    for similarItem in similarItems:
15268 kshitij.so 196
        if similarItem['_id'] == item['_id']:
197
            try:
198
                recomputePoints(item, similarItem)
199
            except:
200
                traceback.print_exc()
16019 kshitij.so 201
        if similarItem['codAvailable'] ==1:
202
            if mc.get("negative_deals") is None:
203
                populateNegativeDeals()
204
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
205
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
206
                continue
207
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
208
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
209
                continue
210
            if similarItem['available_price'] < bestPrice:
211
                bestOne = similarItem
212
                bestPrice = similarItem['available_price']
213
                bestSellerPoints = similarItem['bestSellerPoints']
214
            elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
215
                bestOne = similarItem
216
                bestPrice = similarItem['available_price']
217
                bestSellerPoints = similarItem['bestSellerPoints']
218
            else:
219
                pass
13916 kshitij.so 220
        else:
16019 kshitij.so 221
            if mc.get("negative_deals") is None:
222
                populateNegativeDeals()
223
            if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price'] or similarItem['_id'] in mc.get("negative_deals"):
224
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0, 'prepaidDeal':0 }})
225
                continue
226
            if similarItem['source_id'] == SOURCE_MAP.get('SHOPCLUES.COM') and similarItem['rank']==0:
227
                get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':0 }})
228
                continue
229
            if similarItem['available_price'] < prepaidBestPrice:
230
                prepaidBestOne = similarItem
231
                prepaidBestPrice = similarItem['available_price']
232
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
233
            elif similarItem['available_price'] == prepaidBestPrice and prepaidBestSellerPoints < similarItem['bestSellerPoints']:
234
                prepaidBestOne = similarItem
235
                prepaidBestPrice = similarItem['available_price']
236
                prepaidBestSellerPoints = similarItem['bestSellerPoints']
237
            else:
238
                pass
16026 kshitij.so 239
    if bestOne is not None or prepaidBestOne is not None:
13916 kshitij.so 240
        for similarItem in similarItems:
241
            toUpdate.append(similarItem['_id'])
16026 kshitij.so 242
        if bestOne is not None:
243
            toUpdate.remove(bestOne['_id'])
244
            get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1,'prepaidDeal':0 }})
245
        if prepaidBestOne is not None:
16075 kshitij.so 246
            if bestOne is not None:
247
                if prepaidBestOne['available_price'] < bestOne['available_price']: 
248
                    toUpdate.remove(prepaidBestOne['_id'])
249
                    get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
250
            else:
251
                toUpdate.remove(prepaidBestOne['_id'])
252
                get_mongo_connection().Catalog.Deals.update({ '_id' : prepaidBestOne['_id'] }, {'$set':{'showDeal':0,'prepaidDeal':1 }})
13916 kshitij.so 253
    if len(toUpdate) > 0:
16019 kshitij.so 254
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0,'prepaidDeal':0 }},upsert=False, multi=True)
255
 
256
 
13916 kshitij.so 257
 
13828 kshitij.so 258
def main():
259
    getPrivateDeals()
14259 kshitij.so 260
    try:
261
        getItemsToUpdate()
262
    finally:
263
        session.close()
15268 kshitij.so 264
    print "Done with saholic pricing"
13828 kshitij.so 265
 
266
if __name__=='__main__':
267
    main()