Subversion Repositories SmartDukaan

Rev

Rev 14129 | Rev 14179 | 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
13828 kshitij.so 9
 
10
dealsMap = {}
11
con = None
12
dealsCatalogIds = []
13
itemCatalogMap = {}
14
 
13843 kshitij.so 15
parser = optparse.OptionParser()
16
parser.add_option("-H", "--host", dest="hostname",
17
                      default="localhost",
18
                      type="string", help="The HOST where the DB server is running",
19
                      metavar="HOST")
13828 kshitij.so 20
 
13849 kshitij.so 21
(options, args) = parser.parse_args()
13843 kshitij.so 22
DataService.initialize(db_hostname=options.hostname)
23
 
13828 kshitij.so 24
def get_mongo_connection(host='localhost', port=27017):
25
    global con
26
    if con is None:
27
        print "Establishing connection %s host and port %d" %(host,port)
28
        try:
29
            con = pymongo.MongoClient(host, port)
30
        except Exception, e:
31
            print e
32
            return None
33
    return con
34
 
35
def getPrivateDeals():
36
    global dealsMap
37
    dealsMap = dict()
14127 kshitij.so 38
    all_active_items_query =  session.query(PrivateDeals).filter(PrivateDeals.isActive==True).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate))
39
    print all_active_items_query
13828 kshitij.so 40
    all_active_private_deals = all_active_items_query.all()
41
    if all_active_private_deals is not None or all_active_private_deals!=[]:
42
        for active_private_deal in all_active_private_deals:
43
            item = Item.get_by(id = active_private_deal.item_id)
44
            if item.sellingPrice >  active_private_deal.dealPrice and item.status==3:
45
                dealsMap[active_private_deal.item_id] = active_private_deal
46
 
47
def getItemsToUpdate():
48
    global dealsCatalogIds
49
    global itemCatalogMap
14130 kshitij.so 50
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{"$gt":0}}))
51
    for bestSeller in bestSellers: 
52
        saholicCatalogIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':4}))
53
        for d in saholicCatalogIds:
54
            if d['source_id']!=4:
55
                continue
56
            dealsCatalogIds.append(long(d['identifier'].strip()))
13828 kshitij.so 57
    items = Item.query.filter(Item.catalog_item_id.in_(dealsCatalogIds)).all()
58
    for item in items:
59
        temp = []
60
        if not itemCatalogMap.has_key(item.catalog_item_id):
61
            temp.append(item)
62
            print "****",type(item.catalog_item_id)
63
            itemCatalogMap[item.catalog_item_id] = temp
64
        else:
65
            val = itemCatalogMap.get(item.catalog_item_id)
66
            for l in val:
67
                temp.append(l)
68
            temp.append(item)
69
            itemCatalogMap[item.catalog_item_id] = temp
70
 
14130 kshitij.so 71
    for saholicCatalogId in bestSellers:
14129 kshitij.so 72
        if saholicCatalogId['source_id']!=4:
73
            continue
13916 kshitij.so 74
        d_items = itemCatalogMap.get(long(saholicCatalogId['identifier'].strip()))
13828 kshitij.so 75
        available_price = None
76
        for d_item in d_items: 
77
            if d_item.status == 3:
78
                in_stock =1
79
            else:
80
                in_stock = 0
81
                continue
82
            if dealsMap.get(d_item.id) is not None:
83
                available_price = dealsMap.get(d_item.id).dealPrice
84
            if (available_price !=None):
85
                break
86
        if (available_price is None):
87
            in_stock = 0
88
            for d_item in d_items:
89
                if d_item.status == 3:
90
                    available_price = d_item.sellingPrice
91
                    in_stock =1
92
                    break
93
        print long(saholicCatalogId['identifier'])
94
        print in_stock
95
        print available_price
96
        print dealsMap.get(d_item.id)
97
        print "++++++++++++++++++++++++++"
13850 kshitij.so 98
        if available_price > 0 or available_price is not None:
14127 kshitij.so 99
            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 100
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'available_price':available_price , 'in_stock':in_stock}}, multi=True)
13828 kshitij.so 101
        else:
14127 kshitij.so 102
            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 103
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'in_stock':in_stock}}, multi=True)
13828 kshitij.so 104
 
13916 kshitij.so 105
        try:
106
            recomputeDeal(saholicCatalogId['skuBundleId'])
107
        except:
108
            print "Unable to compute deal for ",saholicCatalogId['skuBundleId']
109
 
110
def recomputeDeal(skuBundleId):
111
    """Lets recompute deal for this bundle"""
112
    print "Recomputing for bundleId",skuBundleId
113
 
114
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
115
    bestPrice = float("inf")
116
    bestOne = None
117
    bestSellerPoints = 0
118
    toUpdate = []
119
    for similarItem in similarItems:
13974 kshitij.so 120
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price']:
13916 kshitij.so 121
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
122
            continue
123
        if similarItem['available_price'] < bestPrice:
124
            bestOne = similarItem
125
            bestPrice = similarItem['available_price']
126
            bestSellerPoints = similarItem['bestSellerPoints']
127
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
128
            bestOne = similarItem
129
            bestPrice = similarItem['available_price']
130
            bestSellerPoints = similarItem['bestSellerPoints']
131
        else:
132
            pass
133
    if bestOne is not None:
134
        for similarItem in similarItems:
135
            toUpdate.append(similarItem['_id'])
136
        toUpdate.remove(bestOne['_id'])
137
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
138
    if len(toUpdate) > 0:
139
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
140
 
13828 kshitij.so 141
def main():
142
    getPrivateDeals()
14128 kshitij.so 143
    getItemsToUpdate()
13828 kshitij.so 144
 
145
if __name__=='__main__':
146
    main()