Subversion Repositories SmartDukaan

Rev

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

Rev 11571 Rev 11581
Line 83... Line 83...
83
        self.secondLowestSellerBuyTrend = secondLowestSellerBuyTrend
83
        self.secondLowestSellerBuyTrend = secondLowestSellerBuyTrend
84
        self.ourCode = ourCode
84
        self.ourCode = ourCode
85
 
85
 
86
class __FlipkartItemInfo:
86
class __FlipkartItemInfo:
87
    
87
    
88
    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, flipkartDetails):
88
    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, flipkartDetails, stateId):
89
        
89
        
90
        self.fkSerialNumber = fkSerialNumber
90
        self.fkSerialNumber = fkSerialNumber
91
        self.nlc = nlc
91
        self.nlc = nlc
92
        self.courierCost = courierCost
92
        self.courierCost = courierCost
93
        self.item_id = item_id
93
        self.item_id = item_id
Line 104... Line 104...
104
        self.runType = runType
104
        self.runType = runType
105
        self.parent_category_name = parent_category_name
105
        self.parent_category_name = parent_category_name
106
        self.sourcePercentage = sourcePercentage
106
        self.sourcePercentage = sourcePercentage
107
        self.ourFlipkartInventory = ourFlipkartInventory
107
        self.ourFlipkartInventory = ourFlipkartInventory
108
        self.skuAtFlipkart = skuAtFlipkart
108
        self.skuAtFlipkart = skuAtFlipkart
109
        self.flipkartDetails = flipkartDetails  
109
        self.flipkartDetails = flipkartDetails
-
 
110
        self.stateId = stateId  
110
 
111
 
111
class __FlipkartPricing:
112
class __FlipkartPricing:
112
    
113
    
113
    def __init__(self, ourSp, ourTp, lowestTp, lowestPossibleTp, secondLowestSellerTp, lowestPossibleSp, prefSellerTp):
114
    def __init__(self, ourSp, ourTp, lowestTp, lowestPossibleTp, secondLowestSellerTp, lowestPossibleSp, prefSellerTp):
114
        self.ourTp = ourTp
115
        self.ourTp = ourTp
Line 624... Line 625...
624
        prefButNotCheapItems.append(mpHistory)
625
        prefButNotCheapItems.append(mpHistory)
625
    session.commit()
626
    session.commit()
626
    return prefButNotCheapItems
627
    return prefButNotCheapItems
627
 
628
 
628
def populateStuff(runType,time):
629
def populateStuff(runType,time):
-
 
630
    global itemSaleMap
629
    itemInfo = []
631
    itemInfo = []
630
    if runType=='FAVOURITE':
632
    if runType=='FAVOURITE':
631
        items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).\
633
        items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).\
632
        filter(or_(MarketplaceItems.autoFavourite==True, MarketplaceItems.manualFavourite==True)).all()
634
        filter(or_(MarketplaceItems.autoFavourite==True, MarketplaceItems.manualFavourite==True)).all()
633
    else:
635
    else:
634
        #items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
636
        #items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
635
        items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
637
        items = session.query(FlipkartItem,MarketplaceItems).join((MarketplaceItems,FlipkartItem.item_id==MarketplaceItems.itemId)).filter(MarketplaceItems.source==OrderSource.FLIPKART).all()
-
 
638
        
-
 
639
    inventory_client = InventoryClient().get_client()
-
 
640
    
636
    for item in items:
641
    for item in items:
637
        flipkart_item = item[0]
642
        flipkart_item = item[0]
638
        mp_item = item[1]
643
        mp_item = item[1]
639
        it = Item.query.filter_by(id=flipkart_item.item_id).one()
644
        it = Item.query.filter_by(id=flipkart_item.item_id).one()
640
        category = Category.query.filter_by(id=it.category).one()
645
        category = Category.query.filter_by(id=it.category).one()
Line 648... Line 653...
648
            if scp is not None:
653
            if scp is not None:
649
                sourcePercentage = scp
654
                sourcePercentage = scp
650
            else:
655
            else:
651
                spm = SourcePercentageMaster.get_by(source=OrderSource.FLIPKART)
656
                spm = SourcePercentageMaster.get_by(source=OrderSource.FLIPKART)
652
                sourcePercentage = spm
657
                sourcePercentage = spm
-
 
658
    
-
 
659
        warehouse = inventory_client.getWarehouse(flipkart_item.warehouseId)    
-
 
660
        itemSaleList = []
-
 
661
        oosForAllSources = inventory_client.getOosStatusesForXDaysForItem(flipkart_item.item_id, 0, 3)
-
 
662
        oosForFlipkart = inventory_client.getOosStatusesForXDaysForItem(flipkart_item.item_id, OrderSource.FLIPKART, 5)
-
 
663
        oosForFlipkartLastDay = inventory_client.getOosStatusesForXDaysForItem(flipkart_item.item_id, OrderSource.FLIPKART, 1)
-
 
664
        itemSaleList.append(oosForAllSources)
-
 
665
        itemSaleList.append(oosForFlipkart)
-
 
666
        itemSaleList.append(calculateAverageSale(oosForAllSources))
-
 
667
        itemSaleList.append(calculateAverageSale(oosForFlipkart))
-
 
668
        itemSaleList.append(calculateAverageSale(oosForFlipkartLastDay))
-
 
669
        itemSaleList.append(calculateTotalSale(oosForFlipkart))
-
 
670
        itemSaleMap[flipkart_item.item_id]=itemSaleList
-
 
671
        
653
#        try:
672
#        try:
654
#            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(flipkart_item.skuAtFlipkart))
673
#            request_url = "https://api.flipkart.net/sellers/skus/%s/listings"%(str(flipkart_item.skuAtFlipkart))
655
#            r = requests.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
674
#            r = requests.get(request_url, auth=('m2z93iskuj81qiid', '0c7ab6a5-98c0-4cdc-8be3-72c591e0add4'))
656
#            print "Inventory info",r.json()
675
#            print "Inventory info",r.json()
657
#            stock_count = int((r.json()['attributeValues'])['stock_count'])
676
#            stock_count = int((r.json()['attributeValues'])['stock_count'])
658
#        except:
677
#        except:
659
#            stock_count = 0
678
#            stock_count = 0
660
        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,None)
679
        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,None,warehouse.stateId)
661
        itemInfo.append(flipkartItemInfo)
680
        itemInfo.append(flipkartItemInfo)
662
    return itemInfo
681
    return itemInfo
663
 
682
 
664
def fetchDetails(flipkartSerialNumber,scraper):
683
def fetchDetails(flipkartSerialNumber,scraper):
665
    url = "http://www.flipkart.com/ps/%s"%(flipkartSerialNumber)
684
    url = "http://www.flipkart.com/ps/%s"%(flipkartSerialNumber)
666
    #url = "http://www.flipkart.com/ps/MOBDTXVZXVY3GFG8"
685
    #url = "http://www.flipkart.com/ps/MOBDTXVZXVY3GFG8"
667
    scraper.read(url)
686
    scraper.read(url)
668
    vendorsData = scraper.createData()
687
    vendorsData = scraper.createData()
669
    print "Vendor data for flipkartSerialNumber",flipkartSerialNumber
688
    print "Vendor data for flipkartSerialNumber",flipkartSerialNumber
670
    print "Json Data",vendorsData
689
    print "Json Data",vendorsData
-
 
690
    sortedVendorsData = []
671
    sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
691
    sortedVendorsData = sorted(vendorsData, key=itemgetter('sellingPrice'))
672
    rank ,ourSp, iterator, secondLowestSellerSp, prefSellerSp, lowestSellerSp, lowestSellerScore, prefSellerScore, secondLowestSellerScore, ourScore, shippingTimeLowerLimitLowestSeller,shippingTimeUpperLimitLowestSeller, \
692
    rank ,ourSp, iterator, secondLowestSellerSp, prefSellerSp, lowestSellerSp, lowestSellerScore, prefSellerScore, secondLowestSellerScore, ourScore, shippingTimeLowerLimitLowestSeller,shippingTimeUpperLimitLowestSeller, \
673
    shippingTimeLowerLimitPrefSeller, shippingTimeUpperLimitPrefSeller, shippingTimeLowerLimitOur, shippingTimeUpperLimitOur, shippingTimeLowerLimitSecondLowestSeller, shippingTimeUpperLimitSecondLowestSeller, totalAvailableSeller= (0,)*19
693
    shippingTimeLowerLimitPrefSeller, shippingTimeUpperLimitPrefSeller, shippingTimeLowerLimitOur, shippingTimeUpperLimitOur, shippingTimeLowerLimitSecondLowestSeller, shippingTimeUpperLimitSecondLowestSeller, totalAvailableSeller= (0,)*19
674
    lowestSellerName, lowestSellerCode, secondLowestSellerName, secondLowestSellerCode, prefSellerName, prefSellerCode, lowestSellerBuyTrend, \
694
    lowestSellerName, lowestSellerCode, secondLowestSellerName, secondLowestSellerCode, prefSellerName, prefSellerCode, lowestSellerBuyTrend, \
675
    ourBuyTrend, prefSellerBuyTrend, secondLowestSellerBuyTrend, ourCode = ('',)*11
695
    ourBuyTrend, prefSellerBuyTrend, secondLowestSellerBuyTrend, ourCode = ('',)*11
Line 779... Line 799...
779
    global itemSaleMap
799
    global itemSaleMap
780
    
800
    
781
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap = [],[],[],[],[],[],[],[]
801
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap = [],[],[],[],[],[],[],[]
782
    
802
    
783
    catalog_client = CatalogClient().get_client()
803
    catalog_client = CatalogClient().get_client()
784
    inventory_client = InventoryClient().get_client()
-
 
785
    
804
    
786
    for val in itemInfo:
805
    for val in itemInfo:
787
        spm = val.sourcePercentage
806
        spm = val.sourcePercentage
788
        flipkartDetails = val.flipkartDetails
807
        flipkartDetails = val.flipkartDetails
789
        #print "Fetching details of ",val.fkSerialNumber
-
 
790
        #flipkartDetails = fetchDetails(val.fkSerialNumber,scraper)
-
 
791
        
-
 
792
        if (flipkartDetails.totalAvailableSeller==0):
808
        if (flipkartDetails is None or flipkartDetails.totalAvailableSeller==0):
793
            exceptionItems.append(val)
809
            exceptionItems.append(val)
794
            continue
810
            continue
795
        
811
        
796
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.FLIPKART)
812
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.FLIPKART)
797
        warehouse = inventory_client.getWarehouse(val.warehouseId)
-
 
798
        
-
 
799
        itemSaleList = []
-
 
800
        oosForAllSources = inventory_client.getOosStatusesForXDaysForItem(val.item_id, 0, 3)
-
 
801
        oosForFlipkart = inventory_client.getOosStatusesForXDaysForItem(val.item_id, OrderSource.FLIPKART, 5)
-
 
802
        oosForFlipkartLastDay = inventory_client.getOosStatusesForXDaysForItem(val.item_id, OrderSource.FLIPKART, 1)
-
 
803
        itemSaleList.append(oosForAllSources)
-
 
804
        itemSaleList.append(oosForFlipkart)
-
 
805
        itemSaleList.append(calculateAverageSale(oosForAllSources))
-
 
806
        itemSaleList.append(calculateAverageSale(oosForFlipkart))
-
 
807
        itemSaleList.append(calculateAverageSale(oosForFlipkartLastDay))
-
 
808
        itemSaleList.append(calculateTotalSale(oosForFlipkart))
-
 
809
        itemSaleMap[val.item_id]=itemSaleList
-
 
810
        
-
 
811
        if flipkartDetails.rank==0:
813
        if flipkartDetails.rank==0:
812
            flipkartDetails.ourSp = mpItem.currentSp
814
            flipkartDetails.ourSp = mpItem.currentSp
813
            ourSp = mpItem.currentSp
815
            ourSp = mpItem.currentSp
814
        else:
816
        else:
815
            ourSp = flipkartDetails.ourSp
817
            ourSp = flipkartDetails.ourSp
816
        vatRate = catalog_client.getVatPercentageForItem(val.item_id, warehouse.stateId, flipkartDetails.ourSp)
818
        vatRate = catalog_client.getVatPercentageForItem(val.item_id, val.stateId, flipkartDetails.ourSp)
817
        val.vatRate = vatRate
819
        val.vatRate = vatRate
818
        if (flipkartDetails.ourBuyTrend == 'PrefCheap') or (flipkartDetails.rank==1 and flipkartDetails.totalAvailableSeller==1):
820
        if (flipkartDetails.ourBuyTrend == 'PrefCheap') or (flipkartDetails.rank==1 and flipkartDetails.totalAvailableSeller==1):
819
            temp=[]
821
            temp=[]
820
            temp.append(flipkartDetails)
822
            temp.append(flipkartDetails)
821
            temp.append(val)
823
            temp.append(val)
Line 1914... Line 1916...
1914
        threads = []
1916
        threads = []
1915
        return endOffset
1917
        return endOffset
1916
    else:
1918
    else:
1917
        count = 0
1919
        count = 0
1918
        pool = ThreadPool(5)
1920
        pool = ThreadPool(5)
1919
        startOffset = itemPopulated
1921
        startOffset = 0
1920
        endOffset = startOffset
1922
        endOffset = startOffset
1921
        while(count<5 and endOffset<len(itemInfo)):
1923
        while(count<5 and endOffset<len(itemInfo)):
1922
            print "inside while",testcount
1924
            print "inside while",testcount
1923
            endOffset = startOffset + 50
1925
            endOffset = startOffset + 20
1924
            if (endOffset >= len(itemInfo)):
1926
            if (endOffset >= len(itemInfo)):
1925
                endOffset = len(itemInfo)
1927
                endOffset = len(itemInfo)
1926
                
1928
            print "pool offset start end count"+str(startOffset)+" "+str(endOffset)+" "+str(count)
1927
            print itemInfo[startOffset:endOffset]
1929
            time.sleep(10)
1928
            pool.map(populateScrapingResults,itemInfo[startOffset:endOffset])
1930
            pool.map(populateScrapingResults,itemInfo[startOffset:endOffset])
1929
            #t = Process(target=decideCategory,args=(itemInfo[startOffset:endOffset], scraper))
1931
            #t = Process(target=decideCategory,args=(itemInfo[startOffset:endOffset], scraper))
1930
            #t = threading.Thread(target=partial(decideCategory, itemInfo[startOffset:endOffset], scraper))
1932
            #t = threading.Thread(target=partial(decideCategory, itemInfo[startOffset:endOffset], scraper))
1931
            #t = threading.Thread(target=partial(test, startOffset, endOffset))
1933
            #t = threading.Thread(target=partial(test, startOffset, endOffset))
1932
            #threads.append(t)
1934
            #threads.append(t)
1933
            startOffset = startOffset + 50
1935
            startOffset = startOffset + 20
1934
            count+=1
1936
            count+=1
1935
        #[t.start() for t in threads]
1937
        #[t.start() for t in threads]
1936
        #[t.join() for t in threads] 
1938
        #[t.join() for t in threads] 
1937
        #threads = []
1939
        #threads = []
-
 
1940
        print "terminating while"
1938
        pool.close()
1941
        pool.close()
1939
        pool.join()
1942
        pool.join()
-
 
1943
        print "joining threads"
-
 
1944
        time.sleep(5)
1940
        "returning offset******"
1945
        print "returning offset******"
1941
        time.sleep(5) 
1946
        time.sleep(5) 
1942
        return endOffset
1947
        return endOffset
1943
    
1948
    
1944
    
1949
    
1945
def main():
1950
def main():
Line 1950... Line 1955...
1950
    (options, args) = parser.parse_args()
1955
    (options, args) = parser.parse_args()
1951
    if options.runType not in ('FULL','FAVOURITE'):
1956
    if options.runType not in ('FULL','FAVOURITE'):
1952
        print "Run type argument illegal."
1957
        print "Run type argument illegal."
1953
        sys.exit(1)
1958
        sys.exit(1)
1954
    timestamp = datetime.now()
1959
    timestamp = datetime.now()
-
 
1960
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).one()
1955
    itemInfo= populateStuff(options.runType,timestamp)
1961
    itemInfo= populateStuff(options.runType,timestamp)
1956
    itemsPopulated = 0
1962
    itemsPopulated = 0
1957
    while (itemsPopulated<len(itemInfo)):
1963
    while (itemsPopulated<len(itemInfo)):
1958
        itemsPopulated = threadsToSpawn(options.runType,itemInfo,scraper,itemsPopulated)
1964
        itemsPopulated = threadsToSpawn(options.runType,itemInfo,scraper,itemsPopulated)
1959
    previousProcessingTimestamp = session.query(func.max(MarketPlaceHistory.timestamp)).filter(MarketPlaceHistory.source==OrderSource.FLIPKART).one()
-
 
1960
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap = decideCategory(itemInfo)
1965
        cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap = decideCategory(itemInfo[0:itemsPopulated])
-
 
1966
        itemInfo[0:itemsPopulated] = []
1961
    commitExceptionList(exceptionItems,timestamp)
1967
        commitExceptionList(exceptionItems,timestamp)
1962
    commitCantCompete(cantCompete,timestamp)
1968
        commitCantCompete(cantCompete,timestamp)
1963
    commitBuyBox(buyBoxItems,timestamp)
1969
        commitBuyBox(buyBoxItems,timestamp)
1964
    commitCompetitive(competitive,timestamp)
1970
        commitCompetitive(competitive,timestamp)
1965
    commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
1971
        commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
1966
    commitNegativeMargin(negativeMargin,timestamp)
1972
        commitNegativeMargin(negativeMargin,timestamp)
1967
    commitCheapButNotPref(cheapButNotPref,timestamp)
1973
        commitCheapButNotPref(cheapButNotPref,timestamp)
1968
    commitPrefButNotCheap(prefButNotCheap, timestamp)
1974
        commitPrefButNotCheap(prefButNotCheap, timestamp)
-
 
1975
        cantCompete[:], buyBoxItems[:], competitive[:], competitiveNoInventory[:], exceptionItems[:], negativeMargin[:], cheapButNotPref[:], prefButNotCheap[:] =[],[],[],[],[],[],[],[]
-
 
1976
        
1969
    #getLastUpdatedOn(mailSender.start, mailSender.stop)
1977
        #getLastUpdatedOn(mailSender.start, mailSender.stop)
1970
    #successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
1978
    #successfulAutoDecrease = fetchItemsForAutoDecrease(timestamp)
1971
    #successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
1979
    #successfulAutoIncrease = fetchItemsForAutoIncrease(timestamp)
1972
    if options.runType=='FULL':
1980
#    if options.runType=='FULL':
1973
        previousAutoFav, nowAutoFav = markAutoFavourite()
1981
#        previousAutoFav, nowAutoFav = markAutoFavourite()
1974
    if options.runType=='FULL':
1982
#    if options.runType=='FULL':
1975
        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap, previousAutoFav, nowAutoFav,timestamp, options.runType)
1983
#        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap, previousAutoFav, nowAutoFav,timestamp, options.runType)
1976
    else:
1984
#    else:
1977
        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap, None, None, timestamp, options.runType)
1985
#        write_report(cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin, cheapButNotPref, prefButNotCheap, None, None, timestamp, options.runType)
1978
 
-
 
1979
 
1986
 
1980
if __name__ == '__main__':
1987
if __name__ == '__main__':
1981
    main()
1988
    main()
1982
1989