Subversion Repositories SmartDukaan

Rev

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