Subversion Repositories SmartDukaan

Rev

Rev 13974 | Rev 14128 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

from elixir import * 
from shop2020.model.v1.catalog.impl import DataService
from shop2020.model.v1.catalog.impl.DataService import PrivateDeals, Item
from sqlalchemy.sql.functions import now
from datetime import datetime, timedelta
import pymongo
from dtr.utils.utils import to_java_date
import optparse

dealsMap = {}
con = None
dealsCatalogIds = []
itemCatalogMap = {}
timestamp = datetime.now()
print to_java_date(timestamp)

parser = optparse.OptionParser()
parser.add_option("-H", "--host", dest="hostname",
                      default="localhost",
                      type="string", help="The HOST where the DB server is running",
                      metavar="HOST")

(options, args) = parser.parse_args()
DataService.initialize(db_hostname=options.hostname)

def get_mongo_connection(host='localhost', port=27017):
    global con
    if con is None:
        print "Establishing connection %s host and port %d" %(host,port)
        try:
            con = pymongo.MongoClient(host, port)
        except Exception, e:
            print e
            return None
    return con

def getPrivateDeals():
    global dealsMap
    dealsMap = dict()
    all_active_items_query =  session.query(PrivateDeals).filter(PrivateDeals.isActive==True).filter(now().between(PrivateDeals.startDate, PrivateDeals.endDate + timedelta(days=0)))
    all_active_private_deals = all_active_items_query.all()
    if all_active_private_deals is not None or all_active_private_deals!=[]:
        for active_private_deal in all_active_private_deals:
            item = Item.get_by(id = active_private_deal.item_id)
            if item.sellingPrice >  active_private_deal.dealPrice and item.status==3:
                dealsMap[active_private_deal.item_id] = active_private_deal

def getItemsToUpdate():
    global dealsCatalogIds
    global itemCatalogMap
    saholicCatalogIds = list(get_mongo_connection().Catalog.MasterData.find({'rank':{"$gt":0},'source_id':4}))
    for d in saholicCatalogIds:
        dealsCatalogIds.append(long(d['identifier'].strip()))
    items = Item.query.filter(Item.catalog_item_id.in_(dealsCatalogIds)).all()
    for item in items:
        temp = []
        if not itemCatalogMap.has_key(item.catalog_item_id):
            temp.append(item)
            print "****",type(item.catalog_item_id)
            itemCatalogMap[item.catalog_item_id] = temp
        else:
            val = itemCatalogMap.get(item.catalog_item_id)
            for l in val:
                temp.append(l)
            temp.append(item)
            itemCatalogMap[item.catalog_item_id] = temp
            
    for saholicCatalogId in saholicCatalogIds:
        d_items = itemCatalogMap.get(long(saholicCatalogId['identifier'].strip()))
        available_price = None
        for d_item in d_items: 
            if d_item.status == 3:
                in_stock =1
            else:
                in_stock = 0
                continue
            if dealsMap.get(d_item.id) is not None:
                available_price = dealsMap.get(d_item.id).dealPrice
            if (available_price !=None):
                break
        if (available_price is None):
            in_stock = 0
            for d_item in d_items:
                if d_item.status == 3:
                    available_price = d_item.sellingPrice
                    in_stock =1
                    break
        print long(saholicCatalogId['identifier'])
        print in_stock
        print available_price
        print dealsMap.get(d_item.id)
        print "++++++++++++++++++++++++++"
        if available_price > 0 or available_price is not None:
            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)
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'available_price':available_price , 'in_stock':in_stock}}, multi=True)
        else:
            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)
            get_mongo_connection().Catalog.Deals.update({'_id':saholicCatalogId['_id']}, {'$set' : {'in_stock':in_stock}}, multi=True)
        
        try:
            recomputeDeal(saholicCatalogId['skuBundleId'])
        except:
            print "Unable to compute deal for ",saholicCatalogId['skuBundleId']

def recomputeDeal(skuBundleId):
    """Lets recompute deal for this bundle"""
    print "Recomputing for bundleId",skuBundleId
    
    similarItems = list(get_mongo_connection().Catalog.Deals.find({'skuBundleId':skuBundleId}).sort([('available_price',pymongo.ASCENDING)]))
    bestPrice = float("inf")
    bestOne = None
    bestSellerPoints = 0
    toUpdate = []
    for similarItem in similarItems:
        if similarItem['in_stock'] == 0 or similarItem['maxprice'] is None or similarItem['maxprice'] < similarItem['available_price']:
            get_mongo_connection().Catalog.Deals.update({ '_id' : similarItem['_id'] }, {'$set':{'showDeal':0 }})
            continue
        if similarItem['available_price'] < bestPrice:
            bestOne = similarItem
            bestPrice = similarItem['available_price']
            bestSellerPoints = similarItem['bestSellerPoints']
        elif similarItem['available_price'] == bestPrice and bestSellerPoints < similarItem['bestSellerPoints']:
            bestOne = similarItem
            bestPrice = similarItem['available_price']
            bestSellerPoints = similarItem['bestSellerPoints']
        else:
            pass
    if bestOne is not None:
        for similarItem in similarItems:
            toUpdate.append(similarItem['_id'])
        toUpdate.remove(bestOne['_id'])
        get_mongo_connection().Catalog.Deals.update({ '_id' : bestOne['_id'] }, {'$set':{'showDeal':1 }})
    if len(toUpdate) > 0:
        get_mongo_connection().Catalog.Deals.update({ '_id' : { "$in": toUpdate } }, {'$set':{'showDeal':0 }},upsert=False, multi=True)
        
def main():
    getPrivateDeals()
    getItemsToUpdate()

if __name__=='__main__':
    main()