Subversion Repositories SmartDukaan

Rev

Rev 14128 | Rev 14130 | 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
14127 kshitij.so 50
    saholicCatalogIds = list(get_mongo_connection().Catalog.MasterData.find({'rank':{"$gt":0}}))
13828 kshitij.so 51
    for d in saholicCatalogIds:
14127 kshitij.so 52
        if d['source_id']!=4:
53
            continue
13916 kshitij.so 54
        dealsCatalogIds.append(long(d['identifier'].strip()))
13828 kshitij.so 55
    items = Item.query.filter(Item.catalog_item_id.in_(dealsCatalogIds)).all()
56
    for item in items:
57
        temp = []
58
        if not itemCatalogMap.has_key(item.catalog_item_id):
59
            temp.append(item)
60
            print "****",type(item.catalog_item_id)
61
            itemCatalogMap[item.catalog_item_id] = temp
62
        else:
63
            val = itemCatalogMap.get(item.catalog_item_id)
64
            for l in val:
65
                temp.append(l)
66
            temp.append(item)
67
            itemCatalogMap[item.catalog_item_id] = temp
68
 
69
    for saholicCatalogId in saholicCatalogIds:
14129 kshitij.so 70
        if saholicCatalogId['source_id']!=4:
71
            continue
13916 kshitij.so 72
        d_items = itemCatalogMap.get(long(saholicCatalogId['identifier'].strip()))
13828 kshitij.so 73
        available_price = None
74
        for d_item in d_items: 
75
            if d_item.status == 3:
76
                in_stock =1
77
            else:
78
                in_stock = 0
79
                continue
80
            if dealsMap.get(d_item.id) is not None:
81
                available_price = dealsMap.get(d_item.id).dealPrice
82
            if (available_price !=None):
83
                break
84
        if (available_price is None):
85
            in_stock = 0
86
            for d_item in d_items:
87
                if d_item.status == 3:
88
                    available_price = d_item.sellingPrice
89
                    in_stock =1
90
                    break
91
        print long(saholicCatalogId['identifier'])
92
        print in_stock
93
        print available_price
94
        print dealsMap.get(d_item.id)
95
        print "++++++++++++++++++++++++++"
13850 kshitij.so 96
        if available_price > 0 or available_price is not None:
14127 kshitij.so 97
            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 98
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'available_price':available_price , 'in_stock':in_stock}}, multi=True)
13828 kshitij.so 99
        else:
14127 kshitij.so 100
            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 101
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'in_stock':in_stock}}, multi=True)
13828 kshitij.so 102
 
13916 kshitij.so 103
        try:
104
            recomputeDeal(saholicCatalogId['skuBundleId'])
105
        except:
106
            print "Unable to compute deal for ",saholicCatalogId['skuBundleId']
107
 
108
def recomputeDeal(skuBundleId):
109
    """Lets recompute deal for this bundle"""
110
    print "Recomputing for bundleId",skuBundleId
111
 
112
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
113
    bestPrice = float("inf")
114
    bestOne = None
115
    bestSellerPoints = 0
116
    toUpdate = []
117
    for similarItem in similarItems:
13974 kshitij.so 118
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price']:
13916 kshitij.so 119
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
120
            continue
121
        if similarItem['available_price'] < bestPrice:
122
            bestOne = similarItem
123
            bestPrice = similarItem['available_price']
124
            bestSellerPoints = similarItem['bestSellerPoints']
125
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
126
            bestOne = similarItem
127
            bestPrice = similarItem['available_price']
128
            bestSellerPoints = similarItem['bestSellerPoints']
129
        else:
130
            pass
131
    if bestOne is not None:
132
        for similarItem in similarItems:
133
            toUpdate.append(similarItem['_id'])
134
        toUpdate.remove(bestOne['_id'])
135
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
136
    if len(toUpdate) > 0:
137
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
138
 
13828 kshitij.so 139
def main():
140
    getPrivateDeals()
14128 kshitij.so 141
    getItemsToUpdate()
13828 kshitij.so 142
 
143
if __name__=='__main__':
144
    main()