Rev 15453 | Blame | Compare with Previous | Last modification | View Log | RSS feed
from elixir import *from shop2020.config.client.ConfigClient import ConfigClientfrom shop2020.model.v1.catalog.impl import DataServicefrom shop2020.model.v1.catalog.impl.DataService import SnapdealItem, MarketplaceItems, Item, Category, \MarketPlaceUpdateHistoryfrom shop2020.thriftpy.model.v1.order.ttypes import OrderSourceimport sysimport cookielibfrom time import sleepimport jsonimport smtplibimport xlwtfrom datetime import datetimefrom shop2020.utils import EmailAttachmentSenderfrom shop2020.utils.EmailAttachmentSender import get_attachment_partfrom email.mime.text import MIMETextimport emailfrom email.mime.multipart import MIMEMultipartimport email.encodersimport copyimport tracebackimport urllib2import pymongofrom dtr.utils.utils import get_mongo_connectionconfig_client = ConfigClient()host = config_client.get_property('staging_hostname')DataService.initialize(db_hostname=host)courierCostToSync = []oldPricing = []headers = {'User-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11','Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Accept-Language' : 'en-US,en;q=0.8','Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'}class __SnapdealInfo:def __init__(self, sellingPrice, weight, transferPrice, commission, commissionPercentage, courierCost, sellingPriceSnapdeal, transferPriceSnapdeal, fixedMargin, \fixedMarginPercentage, collectionCharges, logisticCostSnapdeal, weightSnapdeal, supc, itemId, parentCategory, productGroup ,brand, modelName, modelNumber, \color,reason,woodenPackagingCost):self.sellingPrice = sellingPriceself.weight = weightself.transferPrice = transferPriceself.commission = commissionself.commissionPercentage = commissionPercentageself.courierCost = courierCostself.sellingPriceSnapdeal = sellingPriceSnapdealself.transferPriceSnapdeal = transferPriceSnapdealself.fixedMargin = fixedMarginself.fixedMarginPercentage = fixedMarginPercentageself.collectionCharges = collectionChargesself.logisticCostSnapdeal = logisticCostSnapdealself.weightSnapdeal = weightSnapdealself.supc = supcself.itemId = itemIdself.parentCategory = parentCategoryself.productGroup = productGroupself.brand = brandself.modelName = modelNameself.modelNumber = modelNumberself.color = colorself.reason = reasonself.woodenPackagingCost = woodenPackagingCostdef addCookie():try:mongoHost = config_client.get_property('support_backup_host')except:mongoHost = "localhost"cookie = get_mongo_connection(host=mongoHost).Snapdeal.Cookies.find_one()headers['Cookie'] = 'SERVERID=%s;sfJSESSIONID=%s;'%(cookie.get('SERVERID'),cookie.get('sfJSESSIONID'))print headersdef ungzipResponse(r,b):headers = r.info()if headers.get('Content-Encoding')=='gzip':import gzipprint "********************"print "Deflating gzip response"print "********************"gz = gzip.GzipFile(fileobj=r, mode='rb')html = gz.read()gz.close()headers["Content-type"] = "text/html; charset=utf-8"r.set_data( html )b.set_response(r)def populateStuff():exceptionList = []fetchedItems = []items = session.query(SnapdealItem,MarketplaceItems,Item).join((MarketplaceItems,SnapdealItem.item_id==MarketplaceItems.itemId)).join((Item,SnapdealItem.item_id==Item.id)).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()#items = session.query(SnapdealItem,MarketplaceItems,Item).join((MarketplaceItems,SnapdealItem.item_id==MarketplaceItems.itemId)).join((Item,SnapdealItem.item_id==Item.id)).filter(SnapdealItem.item_id==12613).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()for item in items:snapdealItem = item[0]marketplaceItem = item[1]ds_item = item[2]category = Category.query.filter_by(id=ds_item.category).one()parent_category = Category.query.filter_by(id=category.parent_category_id).first()try:snapdealInfo = fetchData(snapdealItem.supc)except Exception as e:exceptionList.append(item)traceback.print_exc()print "Unable to fetch details ",econtinuesnapdealInfo.sellingPrice = snapdealItem.sellingPricesnapdealInfo.courierCost = snapdealItem.courierCostMarketplacesnapdealInfo.transferPrice = snapdealItem.transferPricesnapdealInfo.commissionPercentage = marketplaceItem.commissionsnapdealInfo.commission = snapdealItem.commissionsnapdealInfo.itemId = snapdealItem.item_idsnapdealInfo.parentCategory = parent_category.display_namesnapdealInfo.productGroup = ds_item.product_groupsnapdealInfo.brand = ds_item.brandsnapdealInfo.modelName = ds_item.model_namesnapdealInfo.modelNumber = ds_item.model_numbersnapdealInfo.color = ds_item.colorsnapdealInfo.weight = ds_item.weightfetchedItems.append(snapdealInfo)return exceptionList, fetchedItemsdef fetchData(supc):print "Fetching data for ",supcurl="http://seller.snapdeal.com/pricing/search?_search=false&gridType=normal&page=1&rows=30&searchType=SUPC&searchValue=%s&sidx=priceUpdateTime&sord=desc"%(supc)request = urllib2.Request(url, headers=headers)response = urllib2.urlopen(request)#dataform = str(response.read()).strip("'<>() ").replace('\'', '\"')struct = json.loads(response.read())sdObj = struct['rows'][0]print sdObjif type(sdObj['catalogLive']) is None or not (sdObj['catalogLive']):raisewoodenPackagingCost = 0.0woodenPackagingCost = sdObj['extraFulfillmentFeesAfterWaiver']snapdealInfo = __SnapdealInfo(None,None,None,None,None,None,sdObj['sellingPrice'],sdObj['netSellerPayable'],sdObj['fixedMarginAmount'],sdObj['fixedMarginPercent'],sdObj['collectionCharges'],sdObj['logisticCost'],sdObj['deadWeight'],supc,None, \None, None, None, None, None, None, None,woodenPackagingCost)return snapdealInfodef filterData(fetchedItems):filterList = []for data in fetchedItems:if ( data.transferPrice - data.transferPriceSnapdeal >= -3 ) and (data.transferPrice - data.transferPriceSnapdeal <= 3):print "continue for",data.itemIdcontinuefilterList.append(data)return filterListdef sendMail(filteredData,exceptionList):xstr = lambda s: s or ""message="""<html><body><h3>Low TP On Snapdeal</h3><table border="1" style="width:100%;"><thead><tr><th>Item Id</th><th>Product Name</th><th>Our System Selling Price</th><th>Selling Price Snapdeal</th><th>Our System Transfer Price</th><th>Snapdeal Transfer Price</th><th>Our System Commission</th><th>Snapdeal Commission</th><th>Our System Commission %</th><th>Snapdeal Commission %</th><th>Our System Weight</th><th>Snapdeal Weight</th><th>Our Courier Cost</th><th>Snapdeal Courier Charges</th><th>Reason</th></tr></thead><tbody>"""for data in filteredData:if data.transferPriceSnapdeal < data.transferPrice:message+="""<tr><td style="text-align:center">"""+str(data.itemId)+"""</td><td style="text-align:center">"""+xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color)+"""</td><td style="text-align:center">"""+str(data.sellingPrice)+"""</td><td style="text-align:center">"""+str(data.sellingPriceSnapdeal)+"""</td><td style="text-align:center">"""+str(data.transferPrice)+"""</td><td style="text-align:center">"""+str(data.transferPriceSnapdeal)+"""</td><td style="text-align:center">"""+str(round(data.commission*1.14,2))+"""</td><td style="text-align:center">"""+str(round(float(data.fixedMargin)+float(data.collectionCharges),2))+"""</td><td style="text-align:center">"""+str(data.commissionPercentage)+"%"+"""</td><td style="text-align:center">"""+str(round(float(data.fixedMarginPercentage)/1.14,2))+"%"+"""</td><td style="text-align:center">"""+str(data.weight*1000)+" gms"+"""</td><td style="text-align:center">"""+str(data.weightSnapdeal)+" gms"+"""</td><td style="text-align:center">"""+str(round(data.courierCost*1.14,2))+"""</td><td style="text-align:center">"""+str(round(data.logisticCostSnapdeal,2)+round(data.woodenPackagingCost,2))+"""</td><td style="text-align:center">"""+getReason(data)+"""</td></tr>"""message+="""</tbody></table>"""message+="""<h3>High TP On Snapdeal</h3><table border="1" style="width:100%;"><thead><tr><th>Item Id</th><th>Product Name</th><th>Our System Selling Price</th><th>Selling Price Snapdeal</th><th>Our System Transfer Price</th><th>Snapdeal Transfer Price</th><th>Our System Commission</th><th>Snapdeal Commission</th><th>Our System Commission %</th><th>Snapdeal Commission %</th><th>Our System Weight</th><th>Snapdeal Weight</th><th>Our Courier Cost</th><th>Snapdeal Courier Charges</th><th>Reason</th></tr></thead><tbody>"""for data in filteredData:if data.transferPriceSnapdeal >= data.transferPrice:message+="""<tr><td style="text-align:center">"""+str(data.itemId)+"""</td><td style="text-align:center">"""+xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color)+"""</td><td style="text-align:center">"""+str(data.sellingPrice)+"""</td><td style="text-align:center">"""+str(data.sellingPriceSnapdeal)+"""</td><td style="text-align:center">"""+str(data.transferPrice)+"""</td><td style="text-align:center">"""+str(data.transferPriceSnapdeal)+"""</td><td style="text-align:center">"""+str(round(data.commission*1.14,2))+"""</td><td style="text-align:center">"""+str(round(float(data.fixedMargin)+float(data.collectionCharges),2))+"""</td><td style="text-align:center">"""+str(data.commissionPercentage)+"%"+"""</td><td style="text-align:center">"""+str(round(float(data.fixedMarginPercentage)/1.14,2))+"%"+"""</td><td style="text-align:center">"""+str(data.weight*1000)+" gms"+"""</td><td style="text-align:center">"""+str(data.weightSnapdeal)+" gms"+"""</td><td style="text-align:center">"""+str(round(data.courierCost*1.14,2))+"""</td><td style="text-align:center">"""+str(round(data.logisticCostSnapdeal,2)+round(data.woodenPackagingCost,2))+"""</td><td style="text-align:center">"""+getReason(data)+"""</td></tr>"""message+="""</tbody></table>"""message+="""<h3 style="color:red;font-weight:bold">Please Check</h3><h3>Items not live on Snapdeal</h3><table border="1" style="width:100%;"><thead><tr><th>Item Id</th><th>Product Name</th><th>Our System Selling Price</th><th>Our System Transfer Price</th><th>Our System Commission</th><th>Our System Commission %</th><th>Our System Weight</th><th>Our Courier Cost</th></tr></thead><tbody>"""for data in exceptionList:snapdealItem = data[0]marketplaceItem = data[1]ds_item = data[2]message+="""<tr><td style="text-align:center">"""+str(ds_item.id)+"""</td><td style="text-align:center">"""+xstr(ds_item.brand)+" "+xstr(ds_item.model_name)+" "+xstr(ds_item.model_number)+" "+xstr(ds_item.color)+"""</td><td style="text-align:center">"""+str(snapdealItem.sellingPrice)+"""</td><td style="text-align:center">"""+str(snapdealItem.transferPrice)+"""</td><td style="text-align:center">"""+str(round(snapdealItem.commission*1.14,2))+"""</td><td style="text-align:center">"""+str(marketplaceItem.commission)+"%"+"""</td><td style="text-align:center">"""+str(ds_item.weight*1000)+" gms"+"""</td><td style="text-align:center">"""+str(round(snapdealItem.courierCost*1.14,2))+"""</td></tr>"""message+="""</tbody></table></body></html>"""print messagemailServer = smtplib.SMTP("smtp.gmail.com", 587)mailServer.ehlo()mailServer.starttls()mailServer.ehlo()#recipients = ['kshitij.sood@saholic.com']recipients = ['rajneesh.arora@saholic.com','anikendra.das@saholic.com','kshitij.sood@saholic.com','khushal.bhatia@saholic.com','chaitnaya.vats@saholic.com','chandan.kumar@saholic.com','manoj.kumar@saholic.com','yukti.jain@saholic.com','ankush.dhingra@saholic.com','yatin.singh@saholic.com','sandeep.sachdeva@saholic.com']msg = MIMEMultipart()msg['Subject'] = "Snapdeal TP Reconciliation" + ' - ' + str(datetime.now())msg['From'] = ""msg['To'] = ",".join(recipients)msg.preamble = "Snapdeal TP Reconciliation" + ' - ' + str(datetime.now())html_msg = MIMEText(message, 'html')msg.attach(html_msg)try:mailServer.login("build@shop2020.in", "cafe@nes")#mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())mailServer.sendmail("cafe@nes", recipients, msg.as_string())except Exception as e:print eprint "Unable to send Snapdeal TP Reconciliation mail.Lets try with local SMTP."smtpServer = smtplib.SMTP('localhost')smtpServer.set_debuglevel(1)sender = 'support@shop2020.in'try:smtpServer.sendmail(sender, recipients, msg.as_string())print "Successfully sent email"except:print "Error: unable to send email."def write_report(filteredData,exceptionList):wbk = xlwt.Workbook(encoding="UTF-8")sheet = wbk.add_sheet('Low TP SD')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, "Category", heading_xf)sheet.write(0, 2, "Product Group.", heading_xf)sheet.write(0, 3, "SUPC", heading_xf)sheet.write(0, 4, "Brand", heading_xf)sheet.write(0, 5, "Product Name", heading_xf)sheet.write(0, 6, "Our System SP", heading_xf)sheet.write(0, 7, "Snapdeal SP", heading_xf)sheet.write(0, 8, "Our TP", heading_xf)sheet.write(0, 9, "Snapdeal TP", heading_xf)sheet.write(0, 10, "Our System Commission", heading_xf)sheet.write(0, 11, "Snapdeal Commission", heading_xf)sheet.write(0, 12, "Our System Commission %", heading_xf)sheet.write(0, 13, "Snapdeal Commission %", heading_xf)sheet.write(0, 14, "Our System Weight (gms)", heading_xf)sheet.write(0, 15, "Snapdeal Weight", heading_xf)sheet.write(0, 16, "Our Courier Cost", heading_xf)sheet.write(0, 17, "Snapdeal Courier Cost", heading_xf)sheet.write(0, 18, "Reason", heading_xf)sheet_iterator=1for data in filteredData:if data.transferPriceSnapdeal < data.transferPrice:sheet.write(sheet_iterator, 0, data.itemId)sheet.write(sheet_iterator, 1, data.parentCategory)sheet.write(sheet_iterator, 2, data.productGroup)sheet.write(sheet_iterator, 3, data.supc)sheet.write(sheet_iterator, 4, data.brand)sheet.write(sheet_iterator, 5, xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color))sheet.write(sheet_iterator, 6, data.sellingPrice)sheet.write(sheet_iterator, 7, data.sellingPriceSnapdeal)sheet.write(sheet_iterator, 8, data.transferPrice)sheet.write(sheet_iterator, 9, data.transferPriceSnapdeal)sheet.write(sheet_iterator, 10, round(data.commission*1.14,2))sheet.write(sheet_iterator, 11, round(float(data.fixedMargin)+float(data.collectionCharges),2))sheet.write(sheet_iterator, 12, data.commissionPercentage)sheet.write(sheet_iterator, 13, round(float(data.fixedMarginPercentage)/1.14,2))sheet.write(sheet_iterator, 14, data.weight*1000)sheet.write(sheet_iterator, 15, data.weightSnapdeal)sheet.write(sheet_iterator, 16, round(data.courierCost*1.14,2))sheet.write(sheet_iterator, 17, round(data.logisticCostSnapdeal,2)+round(data.woodenPackagingCost,2))sheet.write(sheet_iterator, 18, getReasonSheet(data))sheet_iterator+=1sheet = wbk.add_sheet('High TP SD')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_formatxstr = lambda s: s or ""sheet.write(0, 0, "Item ID", heading_xf)sheet.write(0, 1, "Category", heading_xf)sheet.write(0, 2, "Product Group.", heading_xf)sheet.write(0, 3, "SUPC", heading_xf)sheet.write(0, 4, "Brand", heading_xf)sheet.write(0, 5, "Product Name", heading_xf)sheet.write(0, 6, "Our System SP", heading_xf)sheet.write(0, 7, "Snapdeal SP", heading_xf)sheet.write(0, 8, "Our TP", heading_xf)sheet.write(0, 9, "Snapdeal TP", heading_xf)sheet.write(0, 10, "Our System Commission", heading_xf)sheet.write(0, 11, "Snapdeal Commission", heading_xf)sheet.write(0, 12, "Our System Commission %", heading_xf)sheet.write(0, 13, "Snapdeal Commission %", heading_xf)sheet.write(0, 14, "Our System Weight (gms)", heading_xf)sheet.write(0, 15, "Snapdeal Weight", heading_xf)sheet.write(0, 16, "Our Courier Cost", heading_xf)sheet.write(0, 17, "Snapdeal Courier Cost", heading_xf)sheet.write(0, 18, "Reason", heading_xf)sheet_iterator=1for data in filteredData:if data.transferPriceSnapdeal > data.transferPrice:sheet.write(sheet_iterator, 0, data.itemId)sheet.write(sheet_iterator, 1, data.parentCategory)sheet.write(sheet_iterator, 2, data.productGroup)sheet.write(sheet_iterator, 3, data.supc)sheet.write(sheet_iterator, 4, data.brand)sheet.write(sheet_iterator, 5, xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color))sheet.write(sheet_iterator, 6, data.sellingPrice)sheet.write(sheet_iterator, 7, data.sellingPriceSnapdeal)sheet.write(sheet_iterator, 8, data.transferPrice)sheet.write(sheet_iterator, 9, data.transferPriceSnapdeal)sheet.write(sheet_iterator, 10, round(data.commission*1.14,2))sheet.write(sheet_iterator, 11, round(float(data.fixedMargin)+float(data.collectionCharges),2))sheet.write(sheet_iterator, 12, data.commissionPercentage)sheet.write(sheet_iterator, 13, round(float(data.fixedMarginPercentage)/1.14,2))sheet.write(sheet_iterator, 14, data.weight*1000)sheet.write(sheet_iterator, 15, data.weightSnapdeal)sheet.write(sheet_iterator, 16, round(data.courierCost*1.14,2))sheet.write(sheet_iterator, 17, round(data.logisticCostSnapdeal,2)+round(data.woodenPackagingCost,2))sheet.write(sheet_iterator, 18, getReasonSheet(data))sheet_iterator+=1sheet = wbk.add_sheet('Exceptions')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_formatxstr = lambda s: s or ""sheet.write(0, 0, "Item ID", heading_xf)sheet.write(0, 1, "SUPC", heading_xf)sheet.write(0, 2, "Brand", heading_xf)sheet.write(0, 3, "Product Name", heading_xf)sheet.write(0, 4, "Our System SP", heading_xf)sheet.write(0, 5, "Our TP", heading_xf)sheet.write(0, 6, "Our System Commission", heading_xf)sheet.write(0, 7, "Our System Commission %", heading_xf)sheet.write(0, 8, "Our System Weight (gms)", heading_xf)sheet.write(0, 9, "Our Courier Cost", heading_xf)sheet_iterator=1for data in exceptionList:snapdealItem = data[0]marketplaceItem = data[1]ds_item = data[2]sheet.write(sheet_iterator, 0, ds_item.id)sheet.write(sheet_iterator, 1, snapdealItem.supc)sheet.write(sheet_iterator, 2, ds_item.brand)sheet.write(sheet_iterator, 3, xstr(ds_item.brand)+" "+xstr(ds_item.model_name)+" "+xstr(ds_item.model_number)+" "+xstr(ds_item.color))sheet.write(sheet_iterator, 4, snapdealItem.sellingPrice)sheet.write(sheet_iterator, 5, snapdealItem.transferPrice)sheet.write(sheet_iterator, 6, round(snapdealItem.commission*1.14,2))sheet.write(sheet_iterator, 7, marketplaceItem.commission)sheet.write(sheet_iterator, 8, (ds_item.weight*1000))sheet.write(sheet_iterator, 9, round(snapdealItem.courierCost*1.14,2))sheet_iterator+=1filename = "/tmp/snapdeal-tp-reconciliation-" + str(datetime.now()) + ".xls"wbk.save(filename)try:#EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Snapdeal TP Reconciliation "+ str(datetime.now()), "", [get_attachment_part(filename)], [""], [])EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["chandan.kumar@saholic.com","manoj.kumar@saholic.com","yukti.jain@saholic.com","ankush.dhingra@saholic.com","manoj.pal@saholic.com","sandeep.sachdeva@saholic.com"], " Snapdeal TP Reconciliation "+ str(datetime.now()), "", [get_attachment_part(filename)], ["rajneesh.arora@saholic.com","kshitij.sood@saholic.com","chaitnaya.vats@saholic.com","khushal.bhatia@saholic.com"], [])except Exception as e:print eprint "Unable to send report.Trying with local SMTP"smtpServer = smtplib.SMTP('localhost')smtpServer.set_debuglevel(1)sender = 'support@shop2020.in'#recipients = ['kshitij.sood@saholic.com']msg = MIMEMultipart()msg['Subject'] = "Snapdeal TP Reconciliation" + ' - ' + str(datetime.now())msg['From'] = senderrecipients = ['rajneesh.arora@saholic.com','kshitij.sood@saholic.com','khushal.bhatia@saholic.com','chaitnaya.vats@saholic.com','chandan.kumar@saholic.com','manoj.kumar@saholic.com','yukti.jain@saholic.com','ankush.dhingra@saholic.com','manoj.pal@saholic.com','sandeep.sachdeva@saholic.com']msg['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=snapdeal_tp_recon.xls')msg.attach(fileMsg)try:smtpServer.sendmail(sender, recipients, msg.as_string())print "Successfully sent email"except:print "Error: unable to send email."def getReason(data):global courierCostToSyncreason=""if data.sellingPrice!=data.sellingPriceSnapdeal:reason+="Selling Price is different."if data.commissionPercentage!= round(float(data.fixedMarginPercentage)/1.14,2):reason+="Commission is different."if round(data.courierCost*1.14)!=round(data.logisticCostSnapdeal+data.woodenPackagingCost):reason+="Courier Cost is different-Check Weight."courierCostToSync.append(data)return reasondef getReasonSheet(data):reason=""if data.sellingPrice!=data.sellingPriceSnapdeal:reason+="Selling Price is different."if data.commissionPercentage!= round(float(data.fixedMarginPercentage)/1.14,2):reason+="Commission is different."if round(data.courierCost*1.14)!=round(data.logisticCostSnapdeal+data.woodenPackagingCost):reason+="Courier Cost is different-Check Weight."return reasondef syncCourierCost(courierCostToSync):global oldPricingfor item in courierCostToSync:sdItem = SnapdealItem.get_by(item_id=item.itemId)mpItem = MarketplaceItems.get_by(itemId=item.itemId, source=OrderSource.SNAPDEAL)oldMpItem = copy.deepcopy(mpItem)temp = []temp.append(item)temp.append(oldMpItem)addHistory(sdItem)sdItem.courierCostMarketplace = round((item.logisticCostSnapdeal+item.woodenPackagingCost)/1.14)sdItem.transferPrice = getNewTp(mpItem,item)sdItem.serviceTax = getNewServiceTax(mpItem,sdItem,item)mpItem.courierCostMarketplace = round((item.logisticCostSnapdeal+item.woodenPackagingCost)/1.14)mpItem.currentTp = getNewTp(mpItem,item)mpItem.minimumPossibleSp = getNewLowestPossibleSp(mpItem,sdItem,item)temp.append(mpItem)oldPricing.append(temp)session.commit()def addHistory(item):itemHistory = MarketPlaceUpdateHistory()itemHistory.item_id = item.item_iditemHistory.source = OrderSource.SNAPDEALitemHistory.exceptionPrice = item.exceptionPriceitemHistory.warehouseId = item.warehouseIditemHistory.isListedOnSource = item.isListedOnSnapdealitemHistory.transferPrice = item.transferPriceitemHistory.sellingPrice = item.sellingPriceitemHistory.courierCost = item.courierCostitemHistory.commission = item.commissionitemHistory.serviceTax = item.serviceTaxitemHistory.suppressPriceFeed = item.suppressPriceFeeditemHistory.suppressInventoryFeed = item.suppressInventoryFeeditemHistory.updatedOn = item.updatedOnitemHistory.maxNlc = item.maxNlcitemHistory.skuAtSource = item.skuAtSnapdealitemHistory.marketPlaceSerialNumber = item.supcitemHistory.priceUpdatedBy = item.priceUpdatedByitemHistory.courierCostMarketplace = item.courierCostMarketplacedef getNewTp(mpItem,data):ourTp = mpItem.currentSp- mpItem.currentSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-((data.logisticCostSnapdeal+data.woodenPackagingCost)/1.14+mpItem.closingFee)*(1+(mpItem.serviceTax/100))-(max(20,(mpItem.pgFee/100)*mpItem.currentSp)*(1+(mpItem.serviceTax/100)));return round(ourTp,2)def getNewServiceTax(mpItem,sdItem,data):return round(mpItem.serviceTax/100*(sdItem.commission+(data.logisticCostSnapdeal+data.woodenPackagingCost)/1.14),2)def getNewLowestPossibleSp(mpItem,sdItem,data):if (mpItem.pgFee/100)*mpItem.currentSp>=20:lowestPossibleSp = (sdItem.maxNlc+(((data.logisticCostSnapdeal+data.woodenPackagingCost)/1.14)+mpItem.closingFee)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat/100))+(mpItem.packagingCost+mpItem.otherCost)*(1+(mpItem.vat)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100+mpItem.pgFee/100)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat)/100)-(mpItem.returnProvision/100)*(1+(mpItem.vat)/100));else:lowestPossibleSp = (sdItem.maxNlc+(((data.logisticCostSnapdeal+data.woodenPackagingCost)/1.14)+mpItem.closingFee+20)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat/100))+(mpItem.packagingCost+mpItem.otherCost)*(1+(mpItem.vat)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))*(1+(mpItem.vat)/100)-(mpItem.returnProvision/100)*(1+(mpItem.vat)/100));return round(lowestPossibleSp,2)def sendCCSyncMail():if len(courierCostToSync) == 0:returnxstr = lambda s: s or ""message="""<html><body><h3>Courier cost synced</h3><table border="1" style="width:100%;"><thead><tr><th>Item Id</th><th>Product Name</th><th>Selling Price</th><th>Old Transfer Price</th><th>New Transfer Price</th><th>Old Courier Cost</th><th>New Courier Cost</th><th>Old Margin</th><th>New Margin</th><th>Old Margin %</th><th>New Margin %</th></tr></thead><tbody>"""for value in oldPricing:data = value[0]mpItemOld = value[1]mpItemNew = value[2]message+="""<tr><td style="text-align:center">"""+str(data.itemId)+"""</td><td style="text-align:center">"""+xstr(data.brand)+" "+xstr(data.modelName)+" "+xstr(data.modelNumber)+" "+xstr(data.color)+"""</td><td style="text-align:center">"""+str(mpItemOld.currentSp)+"""</td><td style="text-align:center">"""+str(mpItemOld.currentTp)+"""</td><td style="text-align:center">"""+str(mpItemNew.currentTp)+"""</td><td style="text-align:center">"""+str(mpItemOld.courierCostMarketplace)+"""</td><td style="text-align:center">"""+str(mpItemNew.courierCostMarketplace)+"""</td><td style="text-align:center">"""+str(round(mpItemOld.currentTp-mpItemOld.minimumPossibleTp))+"""</td><td style="text-align:center">"""+str(round(mpItemNew.currentTp-mpItemNew.minimumPossibleTp))+"""</td><td style="text-align:center">"""+str(round(((mpItemOld.currentTp-mpItemOld.minimumPossibleTp)/mpItemOld.currentSp)*100,2))+"""</td><td style="text-align:center">"""+str(round(((mpItemNew.currentTp-mpItemNew.minimumPossibleTp)/mpItemNew.currentSp)*100,2))+"""</td></tr>"""message+="""</tbody></table></body></html>"""print messagemailServer = smtplib.SMTP("smtp.gmail.com", 587)mailServer.ehlo()mailServer.starttls()mailServer.ehlo()#recipients = ['kshitij.sood@saholic.com']recipients = ['rajneesh.arora@saholic.com','anikendra.das@saholic.com','kshitij.sood@saholic.com','khushal.bhatia@saholic.com','chaitnaya.vats@saholic.com','chandan.kumar@saholic.com','manoj.kumar@saholic.com','yukti.jain@saholic.com','ankush.dhingra@saholic.com','manoj.pal@saholic.com','sandeep.sachdeva@saholic.com']msg = MIMEMultipart()msg['Subject'] = "Snapdeal Courier Cost Synced" + ' - ' + str(datetime.now())msg['From'] = ""msg['To'] = ",".join(recipients)msg.preamble = "Snapdeal Courier Cost Synced" + ' - ' + str(datetime.now())html_msg = MIMEText(message, 'html')msg.attach(html_msg)try:mailServer.login("build@shop2020.in", "cafe@nes")#mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())mailServer.sendmail("cafe@nes", recipients, msg.as_string())except Exception as e:print eprint "Unable to send Snapdeal Courier Cost mail.Lets try with local SMTP."smtpServer = smtplib.SMTP('localhost')smtpServer.set_debuglevel(1)sender = 'support@shop2020.in'try:smtpServer.sendmail(sender, recipients, msg.as_string())print "Successfully sent email"except:print "Error: unable to send email."def main():addCookie()exceptionList, fetchedItems = populateStuff()filteredData = filterData(fetchedItems)sendMail(filteredData,exceptionList)write_report(filteredData,exceptionList)syncCourierCost(courierCostToSync)sendCCSyncMail()if __name__ == "__main__":main()