Subversion Repositories SmartDukaan

Rev

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

Rev 11228 Rev 11560
Line 17... Line 17...
17
from datetime import date, datetime, timedelta
17
from datetime import date, datetime, timedelta
18
from shop2020.utils import EmailAttachmentSender
18
from shop2020.utils import EmailAttachmentSender
19
from shop2020.utils.EmailAttachmentSender import get_attachment_part
19
from shop2020.utils.EmailAttachmentSender import get_attachment_part
20
import math
20
import math
21
from operator import itemgetter
21
from operator import itemgetter
-
 
22
from functools import partial
22
import simplejson as json
23
import simplejson as json
23
import xlwt
24
import xlwt
24
import optparse
25
import optparse
25
import sys
26
import sys
26
import smtplib
27
import smtplib
-
 
28
import threading
-
 
29
from multiprocessing import Process 
27
from email.mime.text import MIMEText
30
from email.mime.text import MIMEText
28
import email
31
import email
29
from email.mime.multipart import MIMEMultipart
32
from email.mime.multipart import MIMEMultipart
30
import email.encoders
33
import email.encoders
31
import cookielib
34
import cookielib
Line 35... Line 38...
35
syncPrice=config_client.get_property('sync_price_on_marketplace')
38
syncPrice=config_client.get_property('sync_price_on_marketplace')
36
 
39
 
37
 
40
 
38
DataService.initialize(db_hostname=host)
41
DataService.initialize(db_hostname=host)
39
 
42
 
-
 
43
threads = []
40
inventoryMap = {}
44
inventoryMap = {}
41
itemSaleMap = {}
45
itemSaleMap = {}
-
 
46
cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap = [],[],[],[],[],[],[],[]
42
 
47
 
43
class __FlipkartDetails:
48
class __FlipkartDetails:
44
    
49
    
45
    def __init__(self,rank ,ourSp , secondLowestSellerSp, prefSellerSp, lowestSellerSp, lowestSellerScore, prefSellerScore, secondLowestSellerScore, ourScore, shippingTimeLowerLimitLowestSeller,shippingTimeUpperLimitLowestSeller, \
50
    def __init__(self,rank ,ourSp , secondLowestSellerSp, prefSellerSp, lowestSellerSp, lowestSellerScore, prefSellerScore, secondLowestSellerScore, ourScore, shippingTimeLowerLimitLowestSeller,shippingTimeUpperLimitLowestSeller, \
46
    shippingTimeLowerLimitPrefSeller, shippingTimeUpperLimitPrefSeller, shippingTimeLowerLimitOur, shippingTimeUpperLimitOur, shippingTimeLowerLimitSecondLowestSeller, shippingTimeUpperLimitSecondLowestSeller, totalAvailableSeller, lowestSellerName, lowestSellerCode, secondLowestSellerName, secondLowestSellerCode, prefSellerName, prefSellerCode, lowestSellerBuyTrend, \
51
    shippingTimeLowerLimitPrefSeller, shippingTimeUpperLimitPrefSeller, shippingTimeLowerLimitOur, shippingTimeUpperLimitOur, shippingTimeLowerLimitSecondLowestSeller, shippingTimeUpperLimitSecondLowestSeller, totalAvailableSeller, lowestSellerName, lowestSellerCode, secondLowestSellerName, secondLowestSellerCode, prefSellerName, prefSellerCode, lowestSellerBuyTrend, \
Line 76... Line 81...
76
        self.secondLowestSellerBuyTrend = secondLowestSellerBuyTrend
81
        self.secondLowestSellerBuyTrend = secondLowestSellerBuyTrend
77
        self.ourCode = ourCode
82
        self.ourCode = ourCode
78
 
83
 
79
class __FlipkartItemInfo:
84
class __FlipkartItemInfo:
80
    
85
    
81
    def __init__(self, fkSerialNumber, nlc, courierCost, item_id, product_group, brand, model_name, model_number, color, weight, parent_category, risky, warehouseId, vatRate, runType, parent_category_name, sourcePercentage, ourFlipkartInventory):
86
    def __init__(self, fkSerialNumber, nlc, courierCost, item_id, product_group, brand, model_name, model_number, color, weight, parent_category, risky, warehouseId, vatRate, runType, parent_category_name, sourcePercentage, ourFlipkartInventory, skuAtFlipkart):
82
        
87
        
83
        self.fkSerialNumber = fkSerialNumber
88
        self.fkSerialNumber = fkSerialNumber
84
        self.nlc = nlc
89
        self.nlc = nlc
85
        self.courierCost = courierCost
90
        self.courierCost = courierCost
86
        self.item_id = item_id
91
        self.item_id = item_id
Line 95... Line 100...
95
        self.warehouseId = warehouseId
100
        self.warehouseId = warehouseId
96
        self.vatRate = vatRate
101
        self.vatRate = vatRate
97
        self.runType = runType
102
        self.runType = runType
98
        self.parent_category_name = parent_category_name
103
        self.parent_category_name = parent_category_name
99
        self.sourcePercentage = sourcePercentage
104
        self.sourcePercentage = sourcePercentage
100
        self.ourFlipkartInventory = ourFlipkartInventory 
105
        self.ourFlipkartInventory = ourFlipkartInventory
-
 
106
        self.skuAtFlipkart = skuAtFlipkart  
101
 
107
 
102
class __FlipkartPricing:
108
class __FlipkartPricing:
103
    
109
    
104
    def __init__(self, ourSp, ourTp, lowestTp, lowestPossibleTp, secondLowestSellerTp, lowestPossibleSp, prefSellerTp):
110
    def __init__(self, ourSp, ourTp, lowestTp, lowestPossibleTp, secondLowestSellerTp, lowestPossibleSp, prefSellerTp):
105
        self.ourTp = ourTp
111
        self.ourTp = ourTp
Line 639... Line 645...
639
            if scp is not None:
645
            if scp is not None:
640
                sourcePercentage = scp
646
                sourcePercentage = scp
641
            else:
647
            else:
642
                spm = SourcePercentageMaster.get_by(source=OrderSource.FLIPKART)
648
                spm = SourcePercentageMaster.get_by(source=OrderSource.FLIPKART)
643
                sourcePercentage = spm
649
                sourcePercentage = spm
644
        try:
650
#        try:
645
            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(flipkart_item.skuAtFlipkart))
651
#            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(flipkart_item.skuAtFlipkart))
646
            r = requests.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
652
#            r = requests.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
647
            print "Inventory info",r.json()
653
#            print "Inventory info",r.json()
648
            stock_count = int((r.json()['attributeValues'])['stock_count'])
654
#            stock_count = int((r.json()['attributeValues'])['stock_count'])
649
        except:
655
#        except:
650
            stock_count = 0
656
#            stock_count = 0
651
        flipkartItemInfo = __FlipkartItemInfo(flipkart_item.flipkartSerialNumber, flipkart_item.maxNlc,mp_item.courierCost, it.id, it.product_group, it.brand, it.model_name, it.model_number, it.color, it.weight, category.parent_category_id, it.risky, flipkart_item.warehouseId, None, runType, parent_category.display_name,sourcePercentage,stock_count)
657
        flipkartItemInfo = __FlipkartItemInfo(flipkart_item.flipkartSerialNumber, flipkart_item.maxNlc,mp_item.courierCost, it.id, it.product_group, it.brand, it.model_name, it.model_number, it.color, it.weight, category.parent_category_id, it.risky, flipkart_item.warehouseId, None, runType, parent_category.display_name,sourcePercentage,None,flipkart_item.skuAtFlipkart)
652
        itemInfo.append(flipkartItemInfo)
658
        itemInfo.append(flipkartItemInfo)
653
    return itemInfo
659
    return itemInfo
654
 
660
 
655
def fetchDetails(flipkartSerialNumber,scraper):
661
def fetchDetails(flipkartSerialNumber,scraper):
656
    url = "http://www.flipkart.com/ps/%s"%(flipkartSerialNumber)
662
    url = "http://www.flipkart.com/ps/%s"%(flipkartSerialNumber)
Line 764... Line 770...
764
        return 'MEDIUM'
770
        return 'MEDIUM'
765
    else:
771
    else:
766
        return 'LOW'  
772
        return 'LOW'  
767
 
773
 
768
def decideCategory(itemInfo,scraper):
774
def decideCategory(itemInfo,scraper):
-
 
775
    print "length****",len(itemInfo)
769
    global itemSaleMap
776
    global itemSaleMap
-
 
777
    global cantCompete 
-
 
778
    global buyBoxItems 
-
 
779
    global competitive 
770
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap = [],[],[],[],[],[],[],[]
780
    global competitiveNoInventory
-
 
781
    global exceptionItems
-
 
782
    global negativeMargin
-
 
783
    global cheapButNotPref
-
 
784
    global prefButNotCheap
-
 
785
    
771
    catalog_client = CatalogClient().get_client()
786
    catalog_client = CatalogClient().get_client()
772
    inventory_client = InventoryClient().get_client()
787
    inventory_client = InventoryClient().get_client()
773
    
788
    
774
    for val in itemInfo:
789
    for val in itemInfo:
775
        spm = val.sourcePercentage
790
        spm = val.sourcePercentage
Line 781... Line 796...
781
            print "Unable to fetch details of",val.fkSerialNumber
796
            print "Unable to fetch details of",val.fkSerialNumber
782
            print e
797
            print e
783
            exceptionItems.append(val)
798
            exceptionItems.append(val)
784
            continue
799
            continue
785
        
800
        
-
 
801
        try:
-
 
802
            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(val.skuAtFlipkart))
-
 
803
            r = requests.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
-
 
804
            print "Inventory info",r.json()
-
 
805
            stock_count = int((r.json()['attributeValues'])['stock_count'])
-
 
806
        except:
-
 
807
            stock_count = 0
-
 
808
        
-
 
809
        val.ourFlipkartInventory = stock_count
-
 
810
        
786
        if (flipkartDetails.totalAvailableSeller==0):
811
        if (flipkartDetails.totalAvailableSeller==0):
787
            exceptionItems.append(val)
812
            exceptionItems.append(val)
788
            continue
813
            continue
789
        
814
        
790
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.FLIPKART)
815
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.FLIPKART)
Line 887... Line 912...
887
        flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,lowestPossibleSp,prefSellerTp)
912
        flipkartPricing = __FlipkartPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,lowestPossibleSp,prefSellerTp)
888
        temp.append(flipkartPricing)
913
        temp.append(flipkartPricing)
889
        temp.append(mpItem)
914
        temp.append(mpItem)
890
        cantCompete.append(temp)
915
        cantCompete.append(temp)
891
    
916
    
892
    return cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap
917
    #return cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap
893
 
918
 
894
def getOtherTp(flipkartDetails,val,spm,prefferedSeller):
919
def getOtherTp(flipkartDetails,val,spm,prefferedSeller):
895
    if val.parent_category==10011 or val.parent_category==12001:
920
    if val.parent_category==10011 or val.parent_category==12001:
896
        commissionPercentage = spm.competitorCommissionAccessory
921
        commissionPercentage = spm.competitorCommissionAccessory
897
    else:
922
    else:
Line 1840... Line 1865...
1840
        sheet_iterator+=1
1865
        sheet_iterator+=1
1841
    
1866
    
1842
    filename = "/tmp/flipkart-report-"+runType+" " + str(timestamp) + ".xls"
1867
    filename = "/tmp/flipkart-report-"+runType+" " + str(timestamp) + ".xls"
1843
    wbk.save(filename)
1868
    wbk.save(filename)
1844
    try:
1869
    try:
1845
        #EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["rajneesh.arora@saholic.com","anikendra.das@saholic.com","kshitij.sood@saholic.com"], " Flipkart Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
1870
        EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Flipkart Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
1846
        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"], " Flipkart Scraping "+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"], [])
1871
        #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"], " Flipkart Scraping "+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"], [])
1847
    except Exception as e:
1872
    except Exception as e:
1848
        print e
1873
        print e
1849
        print "Unable to send report.Trying with local SMTP"
1874
        print "Unable to send report.Trying with local SMTP"
1850
        smtpServer = smtplib.SMTP('localhost')
1875
        smtpServer = smtplib.SMTP('localhost')
1851
        smtpServer.set_debuglevel(1)
1876
        smtpServer.set_debuglevel(1)
1852
        sender = 'support@shop2020.in'
1877
        sender = 'support@shop2020.in'
1853
        #recipients = ["kshitij.sood@saholic.com"]
1878
        recipients = ["kshitij.sood@saholic.com"]
1854
        msg = MIMEMultipart()
1879
        msg = MIMEMultipart()
1855
        msg['Subject'] = "Flipkart Scraping" + ' '+runType+' - ' + str(datetime.now())
1880
        msg['Subject'] = "Flipkart Scraping" + ' '+runType+' - ' + str(datetime.now())
1856
        msg['From'] = sender
1881
        msg['From'] = sender
1857
        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']
1882
        #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']
1858
        msg['To'] = ",".join(recipients)
1883
        msg['To'] = ",".join(recipients)
1859
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
1884
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
1860
        fileMsg.set_payload(file(filename).read())
1885
        fileMsg.set_payload(file(filename).read())
1861
        email.encoders.encode_base64(fileMsg)
1886
        email.encoders.encode_base64(fileMsg)
1862
        fileMsg.add_header('Content-Disposition','attachment;filename=flipkart.xls')
1887
        fileMsg.add_header('Content-Disposition','attachment;filename=flipkart.xls')
Line 1864... Line 1889...
1864
        try:
1889
        try:
1865
            smtpServer.sendmail(sender, recipients, msg.as_string())
1890
            smtpServer.sendmail(sender, recipients, msg.as_string())
1866
            print "Successfully sent email"
1891
            print "Successfully sent email"
1867
        except:
1892
        except:
1868
            print "Error: unable to send email."
1893
            print "Error: unable to send email."
-
 
1894
            
-
 
1895
def test(start,end):
-
 
1896
    print "Start "+str(start)+" end"+str(end)
-
 
1897
            
-
 
1898
def threadsToSpawn(runType,itemInfo,scraper,itemPopulated):
-
 
1899
    global threads
-
 
1900
    if runType == RunType.FAVOURITE:
-
 
1901
        startOffset = itemPopulated
-
 
1902
        endOffset = startOffset
-
 
1903
        while(len(threads)< 3 and endOffset<len(itemInfo)):
-
 
1904
            endOffset = startOffset + 20
-
 
1905
            if (endOffset >= len(itemInfo)):
-
 
1906
                endOffset = len(itemInfo)
-
 
1907
            t = threading.Thread(target=partial(decideCategory, itemInfo[startOffset:endOffset], scraper))
-
 
1908
            #t = threading.Thread(target=partial(test, startOffset, endOffset))
-
 
1909
            threads.append(t)
-
 
1910
            startOffset = startOffset + 20
-
 
1911
        [t.start() for t in threads]
-
 
1912
        [t.join() for t in threads] 
-
 
1913
        threads = []
-
 
1914
        return endOffset
-
 
1915
    else:
-
 
1916
        startOffset = itemPopulated
-
 
1917
        endOffset = startOffset
-
 
1918
        while(len(threads)< 10 and endOffset<len(itemInfo)):
-
 
1919
            endOffset = startOffset + 50
-
 
1920
            if (endOffset >= len(itemInfo)):
-
 
1921
                endOffset = len(itemInfo)
-
 
1922
            t = Process(target=decideCategory,args=(itemInfo[startOffset:endOffset], scraper))
-
 
1923
            #t = threading.Thread(target=partial(decideCategory, itemInfo[startOffset:endOffset], scraper))
-
 
1924
            #t = threading.Thread(target=partial(test, startOffset, endOffset))
-
 
1925
            threads.append(t)
-
 
1926
            startOffset = startOffset + 50
-
 
1927
        [t.start() for t in threads]
-
 
1928
        [t.join() for t in threads] 
-
 
1929
        threads = []
-
 
1930
        return endOffset
-
 
1931
    
1869
 
1932
    
1870
def main():
1933
def main():
1871
    parser = optparse.OptionParser()
1934
    parser = optparse.OptionParser()
1872
    parser.add_option("-t", "--type", dest="runType",
1935
    parser.add_option("-t", "--type", dest="runType",
1873
                   default="FULL", type="string",
1936
                   default="FULL", type="string",
1874
                   help="Run type FULL or FAVOURITE")
1937
                   help="Run type FULL or FAVOURITE")
Line 1877... Line 1940...
1877
        print "Run type argument illegal."
1940
        print "Run type argument illegal."
1878
        sys.exit(1)
1941
        sys.exit(1)
1879
    timestamp = datetime.now()
1942
    timestamp = datetime.now()
1880
    scraper = FlipkartScraper.FlipkartScraper()
1943
    scraper = FlipkartScraper.FlipkartScraper()
1881
    itemInfo= populateStuff(options.runType,timestamp)
1944
    itemInfo= populateStuff(options.runType,timestamp)
-
 
1945
    itemsPopulated = 0
1882
    cantCompete, buyBoxItems, competitive, \
1946
    while (itemsPopulated<len(itemInfo)):
1883
    competitiveNoInventory, exceptionList, negativeMargin, cheapButNotPref, prefButNotCheap = decideCategory(itemInfo,scraper)
1947
        itemsPopulated = threadsToSpawn(options.runType,itemInfo,scraper,itemsPopulated)
1884
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).one()
1948
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).one()
1885
    exceptionItems = commitExceptionList(exceptionList,timestamp)
1949
    commitExceptionList(exceptionItems,timestamp)
1886
    cantComepeteItems = commitCantCompete(cantCompete,timestamp)
1950
    commitCantCompete(cantCompete,timestamp)
1887
    buyBoxList = commitBuyBox(buyBoxItems,timestamp)
1951
    commitBuyBox(buyBoxItems,timestamp)
1888
    competitiveItems = commitCompetitive(competitive,timestamp)
1952
    commitCompetitive(competitive,timestamp)
1889
    competitiveNoInventoryItems = commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
1953
    commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
1890
    negativeMarginItems = commitNegativeMargin(negativeMargin,timestamp)
1954
    commitNegativeMargin(negativeMargin,timestamp)
1891
    cheapButNotPrefItems = commitCheapButNotPref(cheapButNotPref,timestamp)
1955
    commitCheapButNotPref(cheapButNotPref,timestamp)
1892
    prefButNotCheapItems = commitPrefButNotCheap(prefButNotCheap, timestamp)
1956
    commitPrefButNotCheap(prefButNotCheap, timestamp)
-
 
1957
    #getLastUpdatedOn(mailSender.start, mailSender.stop)
1893
    #successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
1958
    #successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
1894
    #successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
1959
    #successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
1895
    if options.runType=='FULL':
1960
    if options.runType=='FULL':
1896
        previousAutoFav, nowAutoFav = markAutoFavourite()
1961
        previousAutoFav, nowAutoFav = markAutoFavourite()
1897
    if options.runType=='FULL':
1962
    if options.runType=='FULL':
1898
        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, cheapButNotPref, prefButNotCheap, previousAutoFav, nowAutoFav,timestamp, options.runType)
1963
        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap, previousAutoFav, nowAutoFav,timestamp, options.runType)
1899
    else:
1964
    else:
1900
        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionList, negativeMargin, cheapButNotPref, prefButNotCheap, None, None, timestamp, options.runType)
1965
        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap, None, None, timestamp, options.runType)
1901
 
1966
 
1902
 
1967
 
1903
if __name__ == '__main__':
1968
if __name__ == '__main__':
1904
    main()
1969
    main()
1905
1970