Subversion Repositories SmartDukaan

Rev

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