Subversion Repositories SmartDukaan

Rev

Rev 12484 | Rev 12490 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 12484 Rev 12489
Line 18... Line 18...
18
import simplejson as json
18
import simplejson as json
19
import xlwt
19
import xlwt
20
import optparse
20
import optparse
21
import sys
21
import sys
22
from operator import itemgetter
22
from operator import itemgetter
-
 
23
from shop2020.utils import EmailAttachmentSender
-
 
24
from shop2020.utils.EmailAttachmentSender import get_attachment_part
-
 
25
import smtplib
-
 
26
from multiprocessing import Process 
-
 
27
from email.mime.text import MIMEText
-
 
28
import email
-
 
29
from email.mime.multipart import MIMEMultipart
-
 
30
import email.encoders
23
 
31
 
24
 
32
 
25
config_client = ConfigClient()
33
config_client = ConfigClient()
26
host = config_client.get_property('staging_hostname')
34
host = config_client.get_property('staging_hostname')
27
syncPrice=config_client.get_property('sync_price_on_marketplace')
35
syncPrice=config_client.get_property('sync_price_on_marketplace')
Line 359... Line 367...
359
    global amazonLongTermActivePromotions
367
    global amazonLongTermActivePromotions
360
    global amazonShortTermActivePromotions
368
    global amazonShortTermActivePromotions
361
    itemInfo = []
369
    itemInfo = []
362
    inventory_client = InventoryClient().get_client()
370
    inventory_client = InventoryClient().get_client()
363
    fbaAvailableInventorySnapshot = inventory_client.getAllAvailableAmazonFbaItemInventory()
371
    fbaAvailableInventorySnapshot = inventory_client.getAllAvailableAmazonFbaItemInventory()
364
    print len(fbaAvailableInventorySnapshot)
372
    if runType=='FAVOURITE':
-
 
373
        favourites = session.query(Amazonlisted.itemId).filter(or_(Amazonlisted.autoFavourite==True, Amazonlisted.manualFavourite==True)).all()
365
    for fbaInventoryItem in fbaAvailableInventorySnapshot:
374
    for fbaInventoryItem in fbaAvailableInventorySnapshot:
-
 
375
        if runType=='FAVOURITE':
-
 
376
            if not (fbaInventoryItem.item_id in favourites):
-
 
377
                continue 
366
        d_amazon_listed = Amazonlisted.get_by(itemId=fbaInventoryItem.item_id)
378
        d_amazon_listed = Amazonlisted.get_by(itemId=fbaInventoryItem.item_id)
367
        if d_amazon_listed is None:
379
        if d_amazon_listed is None:
368
            continue
380
            continue
369
        if d_amazon_listed.overrrideWanlc:
381
        if d_amazon_listed.overrrideWanlc:
370
            wanlc = d_amazon_listed.exceptionalWanlc
382
            wanlc = d_amazon_listed.exceptionalWanlc
371
        else:
383
        else:
372
            wanlc = inventory_client.getWanNlcForSource(fbaInventoryItem.item_id,OrderSource.AMAZON)
384
            wanlc = inventory_client.getWanNlcForSource(fbaInventoryItem.item_id,OrderSource.AMAZON)
373
        it = Item.query.filter_by(id=fbaInventoryItem.item_id).one()
385
        it = Item.query.filter_by(id=fbaInventoryItem.item_id).one()
374
        category = Category.query.filter_by(id=it.category).one()
386
        category = Category.query.filter_by(id=it.category).one()
375
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
387
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
-
 
388
        sourcePercentage = None
376
        scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.AMAZON).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
389
        sip = SourceItemPercentage.query.filter(SourceItemPercentage.item_id==it.id).filter(SourceItemPercentage.source==OrderSource.AMAZON).filter(SourceItemPercentage.startDate<=time).filter(SourceItemPercentage.expiryDate>=time).first()
377
        if scp is not None:
390
        if sip is not None:
378
            sourcePercentage = scp
391
            sourcePercentage = sip
379
        else:
392
        else:
380
            spm = SourcePercentageMaster.get_by(source=OrderSource.AMAZON)
393
            scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.AMAZON).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
-
 
394
            if scp is not None:
-
 
395
                sourcePercentage = scp
-
 
396
            else:
-
 
397
                spm = SourcePercentageMaster.get_by(source=OrderSource.AMAZON)
381
            sourcePercentage = spm
398
                sourcePercentage = spm
382
        if fbaInventoryItem.location==0:
399
        if fbaInventoryItem.location==0:
383
            sku = 'FBA'+str(fbaInventoryItem.item_id)
400
            sku = 'FBA'+str(fbaInventoryItem.item_id)
384
            state_id = 1
401
            state_id = 1
385
        elif fbaInventoryItem.location==1:
402
        elif fbaInventoryItem.location==1:
386
            sku = 'FBB'+str(fbaInventoryItem.item_id)
403
            sku = 'FBB'+str(fbaInventoryItem.item_id)
Line 601... Line 618...
601
        else:
618
        else:
602
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
619
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
603
        lowestPossibleSp = lowestPossibleSp - subsidy
620
        lowestPossibleSp = lowestPossibleSp - subsidy
604
    return round(lowestPossibleSp,2)
621
    return round(lowestPossibleSp,2)
605
 
622
 
-
 
623
def getNewLowestPossibleSp(item,serviceTax,newVatRate):
-
 
624
    lowestPossibleSp = (item.wanlc+(item.courierCost)*(1+(serviceTax/100))*(1+(newVatRate/100))+(15+item.otherCost)*(1+(newVatRate)/100))/(1-(item.commission/100)*(1+(serviceTax/100))*(1+(newVatRate)/100)-(item.returnProvision/100)*(1+(newVatRate)/100));
-
 
625
    if item.isPromotion:
-
 
626
        sku = ''
-
 
627
        if item.warehouseLocation==1:
-
 
628
            sku='FBA'+str(item.item_id)
-
 
629
        else:
-
 
630
            sku='FBB'+str(item.item_id)
-
 
631
        if amazonLongTermActivePromotions.has_key(sku):
-
 
632
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
-
 
633
        else:
-
 
634
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
-
 
635
        lowestPossibleSp = lowestPossibleSp - subsidy
-
 
636
    return round(lowestPossibleSp,2)
-
 
637
 
-
 
638
 
606
def getTargetTp(targetSp,spm,val):
639
def getTargetTp(targetSp,spm,val):
607
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))
640
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))
608
    return round(targetTp,2)
641
    return round(targetTp,2)
609
 
642
 
610
def commitExceptionList(exceptionList,timestamp,runType):
643
def commitExceptionList(exceptionList,timestamp,runType):
Line 1666... Line 1699...
1666
            sheet.write(sheet_iterator, 3, "False")
1699
            sheet.write(sheet_iterator, 3, "False")
1667
            sheet_iterator+=1
1700
            sheet_iterator+=1
1668
    
1701
    
1669
    filename = "/tmp/amazon-report-"+runType+" " + str(timestamp) + ".xls"
1702
    filename = "/tmp/amazon-report-"+runType+" " + str(timestamp) + ".xls"
1670
    wbk.save(filename)
1703
    wbk.save(filename)
-
 
1704
    try:
-
 
1705
        EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Amazon Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
-
 
1706
        #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"], " Amazon Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], ["rajneesh.arora@saholic.com","anikendra.das@saholic.com","vikram.raghav@saholic.com","kshitij.sood@saholic.com","chaitnaya.vats@saholic.com","khushal.bhatia@saholic.com"], [])
-
 
1707
    except Exception as e:
-
 
1708
        print e
-
 
1709
        print "Unable to send report.Trying with local SMTP"
-
 
1710
        smtpServer = smtplib.SMTP('localhost')
-
 
1711
        smtpServer.set_debuglevel(1)
-
 
1712
        sender = 'build@shop2020.in'
-
 
1713
        recipients = ["kshitij.sood@saholic.com"]
-
 
1714
        msg = MIMEMultipart()
-
 
1715
        msg['Subject'] = "Amazon Auto Pricing" + ' '+runType+' - ' + str(datetime.now())
-
 
1716
        msg['From'] = sender
-
 
1717
        #recipients = ['rajneesh.arora@saholic.com','anikendra.das@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']
-
 
1718
        msg['To'] = ",".join(recipients)
-
 
1719
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
-
 
1720
        fileMsg.set_payload(file(filename).read())
-
 
1721
        email.encoders.encode_base64(fileMsg)
-
 
1722
        fileMsg.add_header('Content-Disposition','attachment;filename=amazon-auto-pricing.xls')
-
 
1723
        msg.attach(fileMsg)
-
 
1724
        try:
-
 
1725
            smtpServer.sendmail(sender, recipients, msg.as_string())
-
 
1726
            print "Successfully sent email"
-
 
1727
        except:
-
 
1728
            print "Error: unable to send email."
-
 
1729
 
-
 
1730
def getNewVatRate(item_id,state,price):
-
 
1731
    itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==item_id, ItemVatMaster.stateId==state)).first()
-
 
1732
    if itemVatMaster is None:
-
 
1733
        d_item = Item.query.filter_by(id=item_id).first()
-
 
1734
        if d_item is None:
-
 
1735
            raise 
-
 
1736
        else:
-
 
1737
            vatMaster = CategoryVatMaster.query.filter(and_(CategoryVatMaster.categoryId==d_item.category, CategoryVatMaster.minVal<=price,  CategoryVatMaster.maxVal>=price,  CategoryVatMaster.stateId == state)).first()
-
 
1738
        if vatMaster is None:
-
 
1739
            raise
-
 
1740
        else:
-
 
1741
            vatRate = vatMaster.vatPercent
-
 
1742
    else:
-
 
1743
        vatRate = itemVatMaster.vatPercentage
-
 
1744
    return vatRate
-
 
1745
 
-
 
1746
def sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease):
-
 
1747
    if len(successfulAutoDecrease)==0 and len(successfulAutoIncrease)==0 :
-
 
1748
        return
-
 
1749
    xstr = lambda s: s or ""
-
 
1750
    message="""<html>
-
 
1751
            <body>
-
 
1752
            <h3>Auto Decrease Items</h3>
-
 
1753
            <table border="1" style="width:100%;">
-
 
1754
            <thead>
-
 
1755
            <tr><th>Item Id</th>
-
 
1756
            <th>Amazon SKU</th>
-
 
1757
            <th>Product Name</th>
-
 
1758
            <th>Old Price</th>
-
 
1759
            <th>New Price</th>
-
 
1760
            <th>Subsidy</th>
-
 
1761
            <th>Old Margin</th>
-
 
1762
            <th>New Margin</th>
-
 
1763
            <th>Commission %</th>
-
 
1764
            <th>Return Provision %</th>
-
 
1765
            <th>Inventory</th>
-
 
1766
            <th>Sales History</th>
-
 
1767
            <th>Category</th>
-
 
1768
            </tr></thead>
-
 
1769
            <tbody>"""
-
 
1770
    for item in successfulAutoDecrease:
-
 
1771
        it = Item.query.filter_by(id=item.item_id).one()
-
 
1772
        vatRate = getNewVatRate(item.item_id,item.warehouseLocation,item.proposedSp)
-
 
1773
        oldMargin = item.ourSellingPrice - item.lowestPossibleSp
-
 
1774
        newMargin = round(item.proposedSp - getNewLowestPossibleSp(item,12.36,vatRate))
-
 
1775
        sku = ''
-
 
1776
        if item.warehouseLocation==1:
-
 
1777
            sku='FBA'+str(item.item_id)
-
 
1778
        else:
-
 
1779
            sku='FBB'+str(item.item_id)  
-
 
1780
        if amazonLongTermActivePromotions.has_key(sku):
-
 
1781
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
-
 
1782
        elif amazonShortTermActivePromotions.has_key(sku):
-
 
1783
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
-
 
1784
        else:
-
 
1785
            subsidy = 0
-
 
1786
        message+="""<tr>
-
 
1787
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
-
 
1788
                <td style="text-align:center">"""+sku+"""</td>
-
 
1789
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
-
 
1790
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
-
 
1791
                <td style="text-align:center">"""+str(math.ceil(item.proposedSp))+"""</td>
-
 
1792
                <td style="text-align:center">"""+str(math.ceil(item.proposedSp))+"""</td>
-
 
1793
                <td style="text-align:center">"""+str(round(subsidy))+"""</td>
-
 
1794
                <td style="text-align:center">"""+str(round(oldMargin))+" ("+str(round((oldMargin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
-
 
1795
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/item.proposedSellingPrice)*100,1))+"%)"+"""</td>
-
 
1796
                <td style="text-align:center">"""+str(item.commission)+" %"+"""</td>
-
 
1797
                <td style="text-align:center">"""+str(item.returnProvision)+" %"+"""</td>
-
 
1798
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
-
 
1799
                <td style="text-align:center">"""+getOosString(saleMap.get(sku))+"""</td>
-
 
1800
                <td style="text-align:center">"""+str(CompetitionCategory._VALUES_TO_NAMES.get(item.competitiveCategory))+"""</td>
-
 
1801
                </tr>"""
-
 
1802
    message+="""</tbody></table><h3>Auto Increase Items</h3><table border="1" style="width:100%;">
-
 
1803
            <thead>
-
 
1804
            <tr><th>Item Id</th>
-
 
1805
            <th>Amazon SKU</th>
-
 
1806
            <th>Product Name</th>
-
 
1807
            <th>Old Price</th>
-
 
1808
            <th>New Price</th>
-
 
1809
            <th>Subsidy</th>
-
 
1810
            <th>Old Margin</th>
-
 
1811
            <th>New Margin</th>
-
 
1812
            <th>Commission %</th>
-
 
1813
            <th>Return Provision %</th>
-
 
1814
            <th>Inventory</th>
-
 
1815
            <th>Sales History</th>
-
 
1816
            <th>Category</th>
-
 
1817
            </tr></thead>
-
 
1818
            <tbody>"""
-
 
1819
    for item in successfulAutoIncrease:
-
 
1820
        it = Item.query.filter_by(id=item.item_id).one()
-
 
1821
        vatRate = getNewVatRate(item.item_id,item.warehouseLocation,math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
-
 
1822
        oldMargin = item.ourSellingPrice - item.lowestPossibleSp
-
 
1823
        newMargin = round(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)) - getNewLowestPossibleSp(item,12.36,vatRate))
-
 
1824
        sku = ''
-
 
1825
        if item.warehouseLocation==1:
-
 
1826
            sku='FBA'+str(item.item_id)
-
 
1827
        else:
-
 
1828
            sku='FBB'+str(item.item_id)  
-
 
1829
        if amazonLongTermActivePromotions.has_key(sku):
-
 
1830
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
-
 
1831
        elif amazonShortTermActivePromotions.has_key(sku):
-
 
1832
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
-
 
1833
        else:
-
 
1834
            subsidy = 0
-
 
1835
        message+="""<tr>
-
 
1836
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
-
 
1837
                <td style="text-align:center">"""+sku+"""</td>
-
 
1838
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
-
 
1839
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
-
 
1840
                <td style="text-align:center">"""+str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))+"""</td>
-
 
1841
                <td style="text-align:center">"""+str(round(subsidy))+"""</td>
-
 
1842
                <td style="text-align:center">"""+str(round((oldMargin),1))+" ("+str(round((oldMargin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
-
 
1843
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))*100,1))+"%)"+"""</td>
-
 
1844
                <td style="text-align:center">"""+str(item.commission)+" %"+"""</td>
-
 
1845
                <td style="text-align:center">"""+str(item.returnProvision)+" %"+"""</td>
-
 
1846
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
-
 
1847
                <td style="text-align:center">"""+getOosString(saleMap.get(sku))+"""</td>
-
 
1848
                <td style="text-align:center">"""+str(CompetitionCategory._VALUES_TO_NAMES.get(item.competitiveCategory))+"""</td>
-
 
1849
                </tr>"""
-
 
1850
    message+="""</tbody></table></body></html>"""
-
 
1851
    print message
-
 
1852
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
-
 
1853
    mailServer.ehlo()
-
 
1854
    mailServer.starttls()
-
 
1855
    mailServer.ehlo()
-
 
1856
 
-
 
1857
    recipients = ['kshitij.sood@saholic.com']
-
 
1858
    #recipients = ['rajneesh.arora@saholic.com','anikendra.das@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']
-
 
1859
    msg = MIMEMultipart()
-
 
1860
    msg['Subject'] = "Amazon Auto Pricing" + ' - ' + str(datetime.now())
-
 
1861
    msg['From'] = ""
-
 
1862
    msg['To'] = ",".join(recipients)
-
 
1863
    msg.preamble = "Amazon Auto Pricing" + ' - ' + str(datetime.now())
-
 
1864
    html_msg = MIMEText(message, 'html')
-
 
1865
    msg.attach(html_msg)
-
 
1866
    try:
-
 
1867
        mailServer.login("build@shop2020.in", "cafe@nes")
-
 
1868
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
-
 
1869
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
-
 
1870
    except Exception as e:
-
 
1871
        print e
-
 
1872
        print "Unable to send pricing mail.Lets try with local SMTP."
-
 
1873
        smtpServer = smtplib.SMTP('localhost')
-
 
1874
        smtpServer.set_debuglevel(1)
-
 
1875
        sender = 'build@shop2020.in'
-
 
1876
        try:
-
 
1877
            smtpServer.sendmail(sender, recipients, msg.as_string())
-
 
1878
            print "Successfully sent email"
-
 
1879
        except:
-
 
1880
            print "Error: unable to send email."
-
 
1881
 
1671
    
1882
    
1672
def main():
1883
def main():
1673
    parser = optparse.OptionParser()
1884
    parser = optparse.OptionParser()
1674
    parser.add_option("-t", "--type", dest="runType",
1885
    parser.add_option("-t", "--type", dest="runType",
1675
                   default="FULL", type="string",
1886
                   default="FULL", type="string",
Line 1713... Line 1924...
1713
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1924
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1714
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1925
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1715
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1926
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1716
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
1927
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
1717
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,options.runType)
1928
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,options.runType)
-
 
1929
    sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease)
1718
if __name__=='__main__':
1930
if __name__=='__main__':
1719
    main()
1931
    main()
1720
1932