Subversion Repositories SmartDukaan

Rev

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

import pymongo
from datetime import datetime
from dtr.utils.utils import to_java_date
from operator import itemgetter 

con = None

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 addCategoryDiscount(data):
    collection = get_mongo_connection().Dtr.CategoryDiscount
    query = []
    data['brand'] = data['brand'].strip().upper()
    query.append({"brand":data['brand']})
    query.append({"category_id":data['category_id']})
    r = collection.find({"$and":query})
    if r.count() > 0:
        return {0:"Brand & Category info already present."}
    else:
        collection.insert(data)
        return {1:"Data added successfully"}

def getAllCategoryDiscount():
    data = []
    collection = get_mongo_connection().Dtr.CategoryDiscount
    cursor = collection.find()
    for val in cursor:
        data.append(val)
    return data

def addSchemeDetailsForSku(data):
    collection = get_mongo_connection().Dtr.SkuSchemeDetails
    data['addedOn'] = to_java_date(datetime.now())
    collection.insert(data)
    return {1:"Data added successfully"}

def getAllSkuWiseSchemeDetails():
    data = []
    collection = get_mongo_connection().Dtr.SkuSchemeDetails
    cursor = collection.find()
    for val in cursor:
        data.append(val)
    return data

def addSkuDiscountInfo(data):
    collection = get_mongo_connection().Dtr.SkuDiscountInfo
    cursor = collection.find({"sku":data['sku']})
    if cursor.count() > 0:
        return {0:"Sku information already present."}
    else:
        collection.insert(data)
        return {1:"Data added successfully"}

def getallSkuDiscountInfo():
    data = []
    collection = get_mongo_connection().Dtr.SkuDiscountInfo
    cursor = collection.find()
    for val in cursor:
        data.append(val)
    return data

def addExceptionalNlc(data):
    collection = get_mongo_connection().Dtr.ExceptionalNlc
    cursor = collection.find({"sku":data['sku']})
    if cursor.count() > 0:
        return {0:"Sku information already present."}
    else:
        collection.insert(data)
        return {1:"Data added successfully"}

def getAllExceptionlNlcItems():
    data = []
    collection = get_mongo_connection().Dtr.ExceptionalNlc
    cursor = collection.find()
    for val in cursor:
        data.append(val)
    return data

def getMerchantOrdersByUser(userId, page=1, window=50):
    if page==None:
        page = 1
        
    if window==None:
        window = 50
    result = {}
    skip = (page-1)*window
    collection = get_mongo_connection().Dtr.merchantOrder
    cursor = collection.find({"userId":userId})
    total_count = cursor.count()
    pages = total_count/window + (0 if total_count%window==0 else 1)  
    print "total_count", total_count
    if total_count > skip:
        cursor = cursor.skip(skip).limit(window)
        orders = []
        for order in cursor:
            del(order["_id"])
            orders.append(order)
        result['data'] = orders
        result['window'] = window
        result['totalCount'] = total_count 
        result['currCount'] = cursor.count()
        result['totalPages'] = pages
        result['currPage'] = page    
        return result
    else:
        return result

def getDeals(category_id, offset, limit, sort, direction):
    rank = 1
    deals = {}
    if sort is None or direction is None:
        sortField = "totalPoints"
        direct = -1
    else:
        sortField = sort
        direct = direction
    if category_id == 0:
        data = list(get_mongo_connection().Catalog.Deals.find({'rank':{'$gt':0},'showDeal':1}).sort([(sortField,direct)]).skip(offset).limit(limit))
    else:
        data = list(get_mongo_connection().Catalog.Deals.find({'rank':{'$gt':0},'category_id':category_id,'showDeal':1}).sort([(sortField,direct)]).skip(offset).limit(limit))
    print data[0]['_id']
    for d in data:
        item = list(get_mongo_connection().Catalog.MasterData.find({'_id':d['_id']}))
        if not deals.has_key(item[0]['identifier']):
            item[0]['dealRank'] = rank 
            deals[item[0]['identifier']] = item[0]
            rank +=1
    return sorted(deals.values(), key=itemgetter('dealRank'))

def getItem(skuId):
    try:
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'_id':int(skuId)}))
        return skuData
    except:
        return [{}]

def getCashBackDetails(identifier, source_id):
    """Need to add item level cashback, no data available right now."""
    
    if source_id in (1,2,4):
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'identifier':identifier.strip(), 'source_id':source_id}))
    elif source_id == 3:
        skuData = list(get_mongo_connection().Catalog.MasterData.find({'secondaryIdentifier':identifier.strip(), 'source_id':source_id}))
    else:
        return {}
    if len(skuData) > 0:
        cashback = list(get_mongo_connection().Catalog.CategoryCashBack.find({'category_id':skuData[0]['category_id'], 'source_id':source_id}))
        if len(cashback) > 0:
            return cashback[0]
        else:
            return {} 
    else:
        return {}
    
    
    

def main():
    getDeals(3, 0, 10,"","")
    
if __name__=='__main__':
    main()