Subversion Repositories SmartDukaan

Rev

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

from elixir import *
from shop2020.config.client.ConfigClient import ConfigClient
from shop2020.model.v1.catalog.impl import DataService
from shop2020.model.v1.catalog.impl.DataService import SnapdealItem, MarketplaceItems, Item
from shop2020.thriftpy.model.v1.order.ttypes import OrderSource
import mechanize
import sys
import cookielib
from time import sleep
import json
import smtplib
from datetime import datetime
from shop2020.utils import EmailAttachmentSender
from shop2020.utils.EmailAttachmentSender import get_attachment_part
from email.mime.text import MIMEText
import email
from email.mime.multipart import MIMEMultipart
import email.encoders

config_client = ConfigClient()
host = config_client.get_property('staging_hostname')
DataService.initialize(db_hostname=host)

class __SnapdealInfo:
    def __init__(self, sellingPrice, weight, transferPrice, commission, commissionPercentage, courierCost, sellingPriceSnapdeal, transferPriceSnapdeal, fixedMargin, fixedMarginPercentage, collectionCharges, logisticCostSnapdeal, weightSnapdeal, supc, itemId):
        
        self.sellingPrice = sellingPrice
        self.weight = weight
        self.transferPrice = transferPrice
        self.commission = commission
        self.commissionPercentage = commissionPercentage
        self.courierCost = courierCost
        self.sellingPriceSnapdeal = sellingPriceSnapdeal
        self.transferPriceSnapdeal = transferPriceSnapdeal
        self.fixedMargin = fixedMargin
        self.fixedMarginPercentage = fixedMarginPercentage
        self.collectionCharges = collectionCharges
        self.logisticCostSnapdeal = logisticCostSnapdeal
        self.weightSnapdeal = weightSnapdeal
        self.supc = supc
        self.itemId = itemId

def getBrowserObject():
    br = mechanize.Browser(factory=mechanize.RobustFactory())
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)
    br.set_handle_equiv(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)
    br.set_debug_http(False)
    br.set_debug_redirects(False)
    br.set_debug_responses(False)
    
    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
    
    br.addheaders = [('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-Encoding', 'gzip,deflate,sdch'),                  
                     ('Accept-Language', 'en-US,en;q=0.8'),                     
                     ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.3')]
    return br

def login(url):
    br = getBrowserObject()
    br.open(url)
    response = br.open(url)
    br.select_form(nr=0)
    br.form['username'] = "saholic-snapdeal@saholic.com"
    br.form['password'] = "bc452ce4"
    print "Trying to login"
    response = br.submit()
    return br

def populateStuff(br):
    exceptionList = []
    fetchedItems = []
    items = session.query(SnapdealItem,MarketplaceItems).join((MarketplaceItems,SnapdealItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
    for item in items:
        snapdealItem = item[0]
        marketplaceItem = item[1]
        try:
            print "Inside try for fetch data"
            snapdealInfo = fetchData(br,snapdealItem.supc)
        except Exception as e:
            exceptionList.append(item)
            print "Unable to fetch details ",e
            continue
        snapdealInfo.sellingPrice = snapdealItem.sellingPrice
        snapdealInfo.courierCost = snapdealItem.courierCost
        snapdealInfo.transferPrice = snapdealItem.transferPrice
        snapdealInfo.commissionPercentage = marketplaceItem.commission
        snapdealInfo.commission = snapdealItem.commission
        snapdealInfo.itemId = snapdealItem.item_id
        fetchedItems.append(snapdealInfo)
    return exceptionList, fetchedItems

def fetchData(br,supc):
    url="http://seller.snapdeal.com/pricing/search?searchType=SUPC&searchValue=%s&gridType=normal&_search=false&nd=1396007375971&rows=30&page=1&sidx=&sord=asc"%(supc)
    sleep(1)
    response = br.open(url)
    dataform = str(response.read()).strip("'<>() ").replace('\'', '\"')
    struct = json.loads(dataform)
    sdObj = struct['rows'][0]
    print sdObj
    snapdealInfo = __SnapdealInfo(None,None,None,None,None,None,sdObj['sellingPrice'],sdObj['netSellerPayable'],sdObj['fixedMarginAmount'],sdObj['fixedMarginPercent'],sdObj['collectionCharges'],sdObj['logisticCost'],sdObj['deadWeight'],supc,None)
    return snapdealInfo

def filterData(fetchedItems):
    for data in fetchedItems:
        if ( data.transferPrice - data.transferPriceSnapdeal >= -3 ) and (data.transferPrice - data.transferPriceSnapdeal <= 3):
            print "Removing itemId ",data.itemId
            fetchedItems.remove(data)
    return fetchedItems

def 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>
            </tr></thead>
            <tbody>"""
    for data in filteredData:
        if data.transferPriceSnapdeal < data.transferPrice:
            it = Item.query.filter_by(id=data.itemId).one()
            message+="""<tr>
            <td style="text-align:center">"""+str(data.itemId)+"""</td>
            <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.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(data.commission*1.1236)+"""</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.1236,2))+"%"+"""</td>
            <td style="text-align:center">"""+str(it.weight*100)+" gms"+"""</td>
            <td style="text-align:center">"""+str(data.weightSnapdeal)+" gms"+"""</td>
            <td style="text-align:center">"""+str(data.courierCost*1.1236)+"""</td>
            <td style="text-align:center">"""+str(data.logisticCostSnapdeal)+" gms"+"""</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>
            </tr></thead>
            <tbody>"""
    for data in filteredData:
        if data.transferPriceSnapdeal >= data.transferPrice:
            it = Item.query.filter_by(id=data.itemId).one()
            message+="""<tr>
            <td style="text-align:center">"""+str(data.itemId)+"""</td>
            <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.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(data.commission*1.1236)+"""</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.1236,2))+"%"+"""</td>
            <td style="text-align:center">"""+str(it.weight*100)+" gms"+"""</td>
            <td style="text-align:center">"""+str(data.weightSnapdeal)+" gms"+"""</td>
            <td style="text-align:center">"""+str(data.courierCost*1.1236)+"""</td>
            <td style="text-align:center">"""+str(data.logisticCostSnapdeal)+"""</td>
            </tr>"""
    message+="""</tbody></table>"""
    message+="""
            <h3>Unable To Fetch Items</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]
        it = Item.query.filter_by(id=data.itemId).one()
        message+="""<tr>
            <td style="text-align:center">"""+str(data.itemId)+"""</td>
            <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.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(snapdealItem.commission*1.1236)+"""</td>
            <td style="text-align:center">"""+str(marketplaceItem.commissionPercentage)+"%"+"""</td>
            <td style="text-align:center">"""+str(it.weight*100)+" gms"+"""</td>
            <td style="text-align:center">"""+str(snapdealItem.courierCost*1.1236)+"""</td>
            </tr>"""
    message+="""</tbody></table></body></html>"""
    print message
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    
    recipients = ['kshitij.sood@saholic.com']
    #recipients = ['rajneesh.arora@saholic.com','rajveer.singh@saholic.com','vikram.raghav@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']
    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 e
        print "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 main():
    print "Opening snapdeal seller login page"
    br = login("http://selleraccounts.snapdeal.com/")
    exceptionList, fetchedItems = populateStuff(br)
    filteredData = filterData(fetchedItems)
    sendMail(filteredData,exceptionList)
       
    
if __name__ == "__main__":
    main()