Subversion Repositories SmartDukaan

Rev

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