Rev 20172 | Blame | Compare with Previous | Last modification | View Log | RSS feed
from elixir import *import pymongofrom dtr.storage.MemCache import MemCacheimport xlwtfrom dtr.storage import DataServicefrom dtr.storage.DataService import brand_preferences, user_actions, price_preferencesfrom email.mime.multipart import MIMEMultipartimport email.encodersimport smtplibfrom datetime import datetimefrom dtr.utils.utils import statusMapmc = MemCache()con =NoneDataService.initialize(db_hostname='127.0.0.1')class __SkuInfo:def __init__(self, _id, skuBundleId, category_id, mrp, available_price, source_id, rank, maxNlc, minNlc, schemeAmount, minDiscount, \maxDiscount, discountType, dp, nlcPoints, bestSellerPoints, totalPoints,in_stock,maxprice,showDeal,persPoints, \fav_weight,brand_weight,asp_weight,catalogBestSellerPoints):self._id = _idself.skuBundleId = skuBundleIdself.category_id = category_idself.mrp = mrpself.available_price = available_priceself.source_id = source_idself.rank = rankself.maxNlc = maxNlcself.minNlc = minNlcself.schemeAmount = schemeAmountself.minDiscount = minDiscountself.maxDiscount = maxDiscountself.discountType = discountTypeself.dp = dpself.nlcPoints = nlcPointsself.bestSellerPoints = bestSellerPointsself.totalPoints = totalPointsself.in_stock = in_stockself.maxprice = maxpriceself.showDeal = showDealself.persPoints = persPointsself.fav_weight = fav_weightself.brand_weight = brand_weightself.asp_weight = asp_weightself.catalogBestSellerPoints = catalogBestSellerPointsdef get_mongo_connection(host='localhost', port=27017):global conif con is None:print "Establishing connection %s host and port %d" %(host,port)try:con = pymongo.MongoClient(host, port)except Exception, e:print ereturn Nonereturn condef generateSheet(user_id):"Generating user specific deals for ",user_iduserId = int(user_id)outer_query = []outer_query.append({"showDeal":1})query = {}query['$gt'] = 0outer_query.append({'totalPoints':query})brandPrefMap = {}pricePrefMap = {}actionsMap = {}brand_p = session.query(price_preferences).filter_by(user_id=userId).all()for x in brand_p:pricePrefMap[x.category_id] = [x.min_price,x.max_price]for x in session.query(brand_preferences).filter_by(user_id=userId).all():temp_map = {}if brandPrefMap.has_key((x.brand).strip().upper()):val = brandPrefMap.get((x.brand).strip().upper())temp_map[x.category_id] = 1 if x.status == 'show' else 0val.append(temp_map)else:temp = []temp_map[x.category_id] = 1 if x.status == 'show' else 0temp.append(temp_map)brandPrefMap[(x.brand).strip().upper()] = tempfor x in session.query(user_actions).filter_by(user_id=userId).all():actionsMap[x.store_product_id] = 1 if x.action == 'like' else 0all_deals = list(get_mongo_connection().Catalog.Deals.find({"$and":outer_query}).sort([('totalPoints',pymongo.DESCENDING),('bestSellerPoints',pymongo.DESCENDING),('nlcPoints',pymongo.DESCENDING),('rank',pymongo.DESCENDING)]))all_category_deals = []print actionsMapprint brandPrefMapprint pricePrefMapfor deal in all_deals:if actionsMap.get(deal['_id']) == 0:fav_weight =.25elif actionsMap.get(deal['_id']) == 1:fav_weight = 1.5else:fav_weight = 1if brandPrefMap.get(deal['brand'].strip().upper()) is not None:brand_weight = 1for brandInfo in brandPrefMap.get(deal['brand'].strip().upper()):if brandInfo.get(deal['category_id']) is not None:if brandInfo.get(deal['category_id']) == 1:brand_weight = 2.0else:brand_weight = 1if pricePrefMap.get(deal['category_id']) is not None:if deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1]:asp_weight = 1.5elif deal['available_price'] >= pricePrefMap.get(deal['category_id'])[0] - 0.5 * pricePrefMap.get(deal['category_id'])[0] and deal['available_price'] <= pricePrefMap.get(deal['category_id'])[1] + 0.5 * pricePrefMap.get(deal['category_id'])[1]:asp_weight = 1.2else:asp_weight = 1else:asp_weight = 1persPoints = deal['totalPoints'] * fav_weight * brand_weight * asp_weightdeal['fav_weight'] = fav_weightdeal['brand_weight'] = brand_weightdeal['asp_weight'] = asp_weightdeal['persPoints'] = persPointsall_category_deals.append(deal)print deal['_id']print deal['fav_weight']print deal['brand_weight']print deal['asp_weight']print deal['persPoints']print "==================="sorted_deals = sorted(all_category_deals, key = lambda x: (x['persPoints'],x['totalPoints'],x['bestSellerPoints'], x['nlcPoints'], x['rank']),reverse=True)p = []for x in sorted_deals:s_info = __SkuInfo(x['_id'], x['skuBundleId'], x['category_id'],x['mrp'],x['available_price'],x['source_id'],x['rank'],x['maxNlc'], \x['minNlc'], x['schemeAmount'],x['minDiscount'],x['maxDiscount'],x['discountType'],x['dp'],x['nlcPoints'],x['bestSellerPoints'], \x['totalPoints'],x['in_stock'],x['maxprice'],x['showDeal'],x['persPoints'],x['fav_weight'],x['brand_weight'],x['asp_weight'], \x['catalogBestSellerPoints'])p.append(s_info)wbk = xlwt.Workbook()sheet = wbk.add_sheet('User Deals')xstr = lambda s: s or ""heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')excel_integer_format = '0'integer_style = xlwt.XFStyle()integer_style.num_format_str = excel_integer_formatsheet.write(0, 0, "Item ID", heading_xf)sheet.write(0, 1, "Catalog Item Id", heading_xf)sheet.write(0, 2, "Category", heading_xf)sheet.write(0, 3, "Brand", heading_xf)sheet.write(0, 4, "Product Name", heading_xf)sheet.write(0, 5, "Item Status", heading_xf)sheet.write(0, 6, "Stock Status", heading_xf)sheet.write(0, 7, "MarketPlace", heading_xf)sheet.write(0, 8, "MarketPlace Identifier", heading_xf)sheet.write(0, 9, "MarketPlace Secondary Identifier", heading_xf)sheet.write(0, 10, "Product Name (Marketplace)", heading_xf)sheet.write(0, 11, "Url", heading_xf)sheet.write(0, 12, "Price", heading_xf)sheet.write(0, 13, "Mrp", heading_xf)sheet.write(0, 14, "DP", heading_xf)sheet.write(0, 15, "Scheme Amount", heading_xf)sheet.write(0, 16, "Discount Type", heading_xf)sheet.write(0, 17, "Min Discount", heading_xf)sheet.write(0, 18, "Max Discount", heading_xf)sheet.write(0, 19, "Max Nlc", heading_xf)sheet.write(0, 20, "Min Nlc", heading_xf)sheet.write(0, 21, "Max Price", heading_xf)sheet.write(0, 22, "Rank", heading_xf)sheet.write(0, 23, "Nlc Points", heading_xf)sheet.write(0, 24, "Best Seller Points", heading_xf)sheet.write(0, 25, "Catalog Best Seller Points", heading_xf)sheet.write(0, 26, "Total Points", heading_xf)sheet.write(0, 27, "Pers Points", heading_xf)sheet.write(0, 28, "Show Deals", heading_xf)sheet.write(0, 29, "Fav Weight", heading_xf)sheet.write(0, 30, "Brand Weight", heading_xf)sheet.write(0, 31, "Asp Weight", heading_xf)it = 1for x in p:y = list(get_mongo_connection().Catalog.MasterData.find({'_id':x._id}))sheet.write(it, 0, x._id)sheet.write(it, 1, x.skuBundleId)if x.category_id == 3:category = 'Mobiles'elif x.category_id == 5:category = 'Tablets'elif x.category_id == 6:category = 'Accessories'sheet.write(it, 2, category)sheet.write(it, 3, y[0]['brand'])sheet.write(it, 4, y[0]['product_name'])sheet.write(it, 5, statusMap.get(y[0]['status']))if y[0]['in_stock'] ==1:sheet.write(it, 6, 'In Stock')else:sheet.write(it, 6, 'Out Of Stock')sheet.write(it, 7, y[0]['source'])sheet.write(it, 8, y[0]['identifier'])sheet.write(it, 9, y[0]['secondaryIdentifier'])sheet.write(it, 10, y[0]['source_product_name'])sheet.write(it, 11, y[0]['marketPlaceUrl'])sheet.write(it, 12, y[0]['available_price'])sheet.write(it, 13, x.mrp)sheet.write(it, 14, x.dp)sheet.write(it, 15, x.schemeAmount)sheet.write(it, 16, x.discountType)sheet.write(it, 17, x.minDiscount)sheet.write(it, 18, x.maxDiscount)sheet.write(it, 19, x.maxNlc)sheet.write(it, 20, x.minNlc)sheet.write(it, 21, x.maxprice)sheet.write(it, 22, x.rank)sheet.write(it, 23, x.nlcPoints)sheet.write(it, 24, x.bestSellerPoints)sheet.write(it, 25, x.catalogBestSellerPoints)sheet.write(it, 26, x.totalPoints)sheet.write(it, 27, x.persPoints)sheet.write(it, 28, x.showDeal)sheet.write(it, 29, x.fav_weight)sheet.write(it, 30, x.brand_weight)sheet.write(it, 31, x.asp_weight)it+=1filename = "/tmp/deal-data-user-specific"+str(datetime.now())+".xls"wbk.save(filename)smtpServer = smtplib.SMTP('localhost')#smtpServer.set_debuglevel(1)sender = 'dtr@shop2020.in'if userId==27:recipients = ['kshitij.sood@saholic.com']elif userId==52:recipients = ['manoj.kumar@shop2020.in']else:recipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com', 'khushal.bhatia@saholic.com']msg = MIMEMultipart()msg['Subject'] = "DTR Deals data (UserOnly) UserId - "+str(userId)+"" + ' - ' + str(datetime.now())msg['From'] = sendermsg['To'] = ",".join(recipients)fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')fileMsg.set_payload(file(filename).read())email.encoders.encode_base64(fileMsg)fileMsg.add_header('Content-Disposition','attachment;filename=User_Deal_Sheet_Dtr'+str(userId)+"" + ' - ' + str(datetime.now())+'.xls')msg.attach(fileMsg)try:smtpServer.sendmail(sender, recipients, msg.as_string())print "Successfully sent email"except:print "Error: unable to send email."def main():generateSheet(8)if __name__=='__main__':main()