Subversion Repositories SmartDukaan

Rev

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