Subversion Repositories SmartDukaan

Rev

Rev 14253 | Rev 14325 | 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()
14259 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",
14259 kshitij.so 19
                      metavar="db_host")
14253 kshitij.so 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():
14259 kshitij.so 40
    try:
41
        global dealsMap
42
        dealsMap = dict()
43
        all_active_items_query =  session.query(PrivateDeals).filter(PrivateDeals.isActive==True).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate))
44
        print all_active_items_query
45
        all_active_private_deals = all_active_items_query.all()
46
        if all_active_private_deals is not None or all_active_private_deals!=[]:
47
            for active_private_deal in all_active_private_deals:
48
                item = Item.get_by(id = active_private_deal.item_id)
49
                if item.sellingPrice >  active_private_deal.dealPrice and item.status==3:
50
                    dealsMap[active_private_deal.item_id] = active_private_deal
51
    finally:
52
        session.close()
13828 kshitij.so 53
 
54
def getItemsToUpdate():
55
    global dealsCatalogIds
56
    global itemCatalogMap
14130 kshitij.so 57
    bestSellers = list(get_mongo_connection().Catalog.MasterData.find({'rank':{"$gt":0}}))
58
    for bestSeller in bestSellers: 
59
        saholicCatalogIds = list(get_mongo_connection().Catalog.MasterData.find({'skuBundleId':bestSeller['skuBundleId'],'source_id':4}))
60
        for d in saholicCatalogIds:
61
            if d['source_id']!=4:
62
                continue
63
            dealsCatalogIds.append(long(d['identifier'].strip()))
14253 kshitij.so 64
#    dealFlagged = list(get_mongo_connection().Catalog.Deals.find({'source_id':4,'showDeal':1,'totalPoints':{'$gt':0}}))
65
#    for deal in dealFlagged:
66
#        if not (deal['_id']) in dealsCatalogIds:
67
#            dealsCatalogIds.append(long(deal['identifier'].strip()))
13828 kshitij.so 68
    items = Item.query.filter(Item.catalog_item_id.in_(dealsCatalogIds)).all()
69
    for item in items:
70
        temp = []
71
        if not itemCatalogMap.has_key(item.catalog_item_id):
72
            temp.append(item)
14179 kshitij.so 73
            print "****",item.catalog_item_id
13828 kshitij.so 74
            itemCatalogMap[item.catalog_item_id] = temp
75
        else:
76
            val = itemCatalogMap.get(item.catalog_item_id)
77
            for l in val:
78
                temp.append(l)
79
            temp.append(item)
80
            itemCatalogMap[item.catalog_item_id] = temp
81
 
14130 kshitij.so 82
    for saholicCatalogId in bestSellers:
14129 kshitij.so 83
        if saholicCatalogId['source_id']!=4:
84
            continue
13916 kshitij.so 85
        d_items = itemCatalogMap.get(long(saholicCatalogId['identifier'].strip()))
13828 kshitij.so 86
        available_price = None
14179 kshitij.so 87
        in_stock = 0
88
        if d_items is not None:
13828 kshitij.so 89
            for d_item in d_items:
14179 kshitij.so 90
                in_stock = 0 
13828 kshitij.so 91
                if d_item.status == 3:
92
                    in_stock =1
14179 kshitij.so 93
                else:
94
                    continue
95
                if dealsMap.get(d_item.id) is not None:
96
                    available_price = dealsMap.get(d_item.id).dealPrice
97
                if (available_price !=None):
13828 kshitij.so 98
                    break
14179 kshitij.so 99
        if (available_price is None):
100
            in_stock = 0
101
            if d_items is not None:
102
                for d_item in d_items:
103
                    if d_item.status == 3:
104
                        available_price = d_item.sellingPrice
105
                        in_stock =1
106
                        break
13828 kshitij.so 107
        print long(saholicCatalogId['identifier'])
108
        print in_stock
109
        print available_price
110
        print dealsMap.get(d_item.id)
111
        print "++++++++++++++++++++++++++"
13850 kshitij.so 112
        if available_price > 0 or available_price is not None:
14127 kshitij.so 113
            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 114
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'available_price':available_price , 'in_stock':in_stock}}, multi=True)
13828 kshitij.so 115
        else:
14127 kshitij.so 116
            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 117
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'in_stock':in_stock}}, multi=True)
13828 kshitij.so 118
 
13916 kshitij.so 119
        try:
120
            recomputeDeal(saholicCatalogId['skuBundleId'])
121
        except:
122
            print "Unable to compute deal for ",saholicCatalogId['skuBundleId']
123
 
124
def recomputeDeal(skuBundleId):
125
    """Lets recompute deal for this bundle"""
126
    print "Recomputing for bundleId",skuBundleId
127
 
128
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
129
    bestPrice = float("inf")
130
    bestOne = None
131
    bestSellerPoints = 0
132
    toUpdate = []
133
    for similarItem in similarItems:
13974 kshitij.so 134
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price']:
13916 kshitij.so 135
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
136
            continue
137
        if similarItem['available_price'] < bestPrice:
138
            bestOne = similarItem
139
            bestPrice = similarItem['available_price']
140
            bestSellerPoints = similarItem['bestSellerPoints']
141
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
142
            bestOne = similarItem
143
            bestPrice = similarItem['available_price']
144
            bestSellerPoints = similarItem['bestSellerPoints']
145
        else:
146
            pass
147
    if bestOne is not None:
148
        for similarItem in similarItems:
149
            toUpdate.append(similarItem['_id'])
150
        toUpdate.remove(bestOne['_id'])
151
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
152
    if len(toUpdate) > 0:
153
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
154
 
13828 kshitij.so 155
def main():
156
    getPrivateDeals()
14259 kshitij.so 157
    try:
158
        getItemsToUpdate()
159
    finally:
160
        session.close()
13828 kshitij.so 161
 
162
if __name__=='__main__':
163
    main()