Subversion Repositories SmartDukaan

Rev

Rev 12426 | Rev 12432 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
12363 kshitij.so 1
from elixir import *
12418 kshitij.so 2
from sqlalchemy.sql import or_ ,func, asc, desc, and_
12363 kshitij.so 3
from shop2020.config.client.ConfigClient import ConfigClient
4
from shop2020.model.v1.catalog.impl import DataService
12364 kshitij.so 5
from shop2020.model.v1.catalog.impl.DataService import Amazonlisted, Item, \
12418 kshitij.so 6
Category, SourcePercentageMaster,SourceCategoryPercentage, SourceItemPercentage, AmazonPromotion, AmazonScrapingHistory, \
7
ItemVatMaster, CategoryVatMaster
12363 kshitij.so 8
from shop2020.thriftpy.model.v1.order.ttypes import OrderSource
12430 kshitij.so 9
from shop2020.thriftpy.model.v1.catalog.ttypes import CompetitionCategory, \
12363 kshitij.so 10
Decision, RunType, AmazonPromotionType
12430 kshitij.so 11
from shop2020.model.v1.catalog.script import AmazonAsyncScraper
12363 kshitij.so 12
from shop2020.clients.InventoryClient import InventoryClient
13
from shop2020.clients.TransactionClient import TransactionClient
14
import time 
15
from datetime import date, datetime, timedelta
16
import math
17
import simplejson as json
18
import xlwt
19
import optparse
20
import sys
12430 kshitij.so 21
from operator import itemgetter
12363 kshitij.so 22
 
23
 
24
config_client = ConfigClient()
25
host = config_client.get_property('staging_hostname')
26
syncPrice=config_client.get_property('sync_price_on_marketplace')
27
 
28
amazonAsinPrice={}
29
amazonLongTermActivePromotions = []
12396 kshitij.so 30
amazonShortTermActivePromotions = []
12363 kshitij.so 31
saleMap = {}
32
DataService.initialize(db_hostname=host)
33
 
12430 kshitij.so 34
amScraper = AmazonAsyncScraper.Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
12363 kshitij.so 35
 
36
class __AmazonItemInfo:
37
 
38
    def __init__(self, asin, nlc, courierCost, sku, product_group, brand, model_name, model_number, color, weight, parent_category, risky, vatRate, runType, parent_category_name, sourcePercentage, ourInventory, state_id):
12382 kshitij.so 39
        self.asin = asin
12363 kshitij.so 40
        self.nlc = nlc
41
        self.courierCost = courierCost
42
        self.sku = sku
43
        self.product_group = product_group
44
        self.brand = brand
45
        self.model_name = model_name
46
        self.model_number = model_number
47
        self.color = color
48
        self.weight = weight
49
        self.parent_category = parent_category
50
        self.risky = risky
51
        self.vatRate = vatRate
52
        self.runType = runType
53
        self.parent_category_name = parent_category_name
54
        self.sourcePercentage = sourcePercentage
55
        self.ourInventory = ourInventory
56
        self.state_id = state_id
57
 
58
class __AmazonDetails:
12430 kshitij.so 59
    def __init__(self, sku, ourSp, ourRank, lowestSellerName,lowestSellerSp,secondLowestSellerName, secondLowestSellerSp, thirdLowestSellerName, thirdLowestSellerSp, totalSeller, multipleListings, \
60
                 promoPrice, isPromotion, lowestSellerShippingTime, lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , \
61
                 thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType):
12363 kshitij.so 62
        self.sku =sku
63
        self.ourSp = ourSp
64
        self.ourRank = ourRank
65
        self.lowestSellerName = lowestSellerName
66
        self.lowestSellerSp = lowestSellerSp
67
        self.secondLowestSellerName = secondLowestSellerName
68
        self.secondLowestSellerSp = secondLowestSellerSp
69
        self.thirdLowestSellerName = thirdLowestSellerName
70
        self.thirdLowestSellerSp = thirdLowestSellerSp
71
        self.totalSeller = totalSeller
12430 kshitij.so 72
        self.multipleListings = multipleListings
73
        self.promoPrice = promoPrice
74
        self.isPromotion = isPromotion
75
        self.lowestSellerShippingTime =lowestSellerShippingTime
76
        self.lowestSellerRating = lowestSellerRating
77
        self.secondLowestSellerShippingTime = secondLowestSellerShippingTime
78
        self.secondLowestSellerRating = secondLowestSellerRating
79
        self.thirdLowestSellerShippingTime= thirdLowestSellerShippingTime
80
        self.thirdLowestSellerRating = thirdLowestSellerRating
81
        self.lowestSellerType = lowestSellerType
82
        self.secondLowestSellerType = secondLowestSellerType
83
        self.thirdLowestSellerType = thirdLowestSellerType    
84
 
12363 kshitij.so 85
 
86
class __AmazonPricing:
87
 
88
    def __init__(self, ourSp, ourTp, lowestPossibleTp, lowestPossibleSp):
89
        self.ourTp = ourTp
90
        self.lowestPossibleTp = lowestPossibleTp
91
        self.ourSp = ourSp
92
        self.lowestPossibleSp = lowestPossibleSp
93
 
94
 
12396 kshitij.so 95
def fetchItemsForAutoDecrease(time):
96
    successfulAutoDecrease = []
97
    autoDecrementItems = session.query(AmazonScrapingHistory).join((Amazonlisted,AmazonScrapingHistory.item_id==Amazonlisted.itemId))\
98
    .filter(AmazonScrapingHistory.timestamp==time).filter(or_(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE,AmazonScrapingHistory.competitiveCategory==CompetitionCategory.COMPETITIVE, AmazonScrapingHistory.competitiveCategory==CompetitionCategory.ALMOST_COMPETE ))\
99
    .filter(Amazonlisted.autoDecrement==True).all()
100
    for autoDecrementItem in autoDecrementItems:
101
        if autoDecrementItem.warehouseLocation == 1:
102
            sku = 'FBA'+str(autoDecrementItem.item_id)
103
        else:
104
            sku = 'FBB'+str(autoDecrementItem.item_id)
105
        if sku in amazonShortTermActivePromotions:
106
            markReasonForItem(autoDecrementItem,'Item in short term promotion',Decision.AUTO_DECREMENT_FAILED)
107
            continue
108
        if math.ceil(autoDecrementItem.proposedSp) >= autoDecrementItem.ourSellingPrice:
109
            markReasonForItem(autoDecrementItem,'Proposed SP greater than or equal to current SP',Decision.AUTO_DECREMENT_FAILED)
110
            continue
111
        if autoDecrementItem.proposedSellingPrice < autoDecrementItem.lowestPossibleSp:
112
            markReasonForItem(autoDecrementItem,'Proposed SP less than lowest possible SP',Decision.AUTO_DECREMENT_FAILED)
113
            continue
114
        try:
115
            daysOfStock = (float(autoDecrementItem.ourInventory))/autoDecrementItem.avgSale
116
        except:
117
            daysOfStock = float("inf")
118
        if autoDecrementItem.competitiveCategory == CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE:
119
            if daysOfStock < 20:
120
                markReasonForItem(autoDecrementItem,'Days of stock less than 20',Decision.AUTO_DECREMENT_FAILED)
121
 
122
        if autoDecrementItem.competitiveCategory == CompetitionCategory.COMPETITIVE:
123
            if autoDecrementItem.parentCategoryId in [10006,10009,11001]:
124
                if daysOfStock < 1:
125
                    markReasonForItem(autoDecrementItem,'Days of stock less than 1',Decision.AUTO_DECREMENT_FAILED)
126
            else:
127
                if daysOfStock < 3:
128
                    markReasonForItem(autoDecrementItem,'Days of stock less than 3',Decision.AUTO_DECREMENT_FAILED)
129
 
130
        autoDecrementItem.ourEnoughStock=True
131
        autoDecrementItem.decision = Decision.AUTO_DECREMENT_SUCCESS
132
        autoDecrementItem.reason = 'All conditions for auto decrement true'
133
        successfulAutoDecrease.append(autoDecrementItem)
134
    session.commit()
135
    session.close()
136
    return successfulAutoDecrease
137
 
138
def fetchItemsForAutoIncrease(time):
139
    successfulAutoIncrease = []
140
    autoIncrementItems = session.query(AmazonScrapingHistory).join((Amazonlisted,AmazonScrapingHistory.item_id==Amazonlisted.itemId))\
141
    .filter(AmazonScrapingHistory.timestamp==time).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.BUY_BOX)\
142
    .filter(Amazonlisted.autoIncrement==True).all()
143
    transaction_client = TransactionClient().get_client()
144
    for autoIncrementItem in autoIncrementItems:
145
        if autoIncrementItem.warehouseLocation == 1:
146
            sku = 'FBA'+str(autoIncrementItem.item_id)
147
        else:
148
            sku = 'FBB'+str(autoIncrementItem.item_id)
149
        if sku in amazonShortTermActivePromotions:
150
            markReasonForItem(autoIncrementItem,'Item in short term promotion',Decision.AUTO_INCREMENT_FAILED)
151
            continue
152
        if autoIncrementItem.totalSeller==1 and autoIncrementItem.ourRank==1:
153
            markReasonForItem(autoIncrementItem,'We are the only seller',Decision.AUTO_INCREMENT_FAILED)
154
            continue 
155
        if autoIncrementItem.proposedSp <= autoIncrementItem.ourSellingPrice:
156
            markReasonForItem(autoIncrementItem,'Proposed SP less than current SP',Decision.AUTO_INCREMENT_FAILED)
157
            continue
158
        if autoIncrementItem.proposedSellingPrice >=10000 and autoIncrementItem.ourSellingPrice<10000:
159
            markReasonForItem(autoIncrementItem,'Proposed SP is greater than 10,000 and current sp is less than 10,000',Decision.AUTO_INCREMENT_FAILED)
160
            continue
161
 
162
        if autoIncrementItem.avgSale==0:
163
            markReasonForItem(autoIncrementItem,'Avg sale is 0',Decision.AUTO_INCREMENT_FAILED)
164
            continue
165
 
166
        daysOfStock = (float(autoIncrementItem.ourInventory))/autoIncrementItem.avgSale
167
        if daysOfStock > 5:
168
            markReasonForItem(autoIncrementItem,'Days of stock greater than 5',Decision.AUTO_INCREMENT_FAILED)
169
            continue
170
        antecedentPrice = session.query(AmazonScrapingHistory.ourSellingPrice).filter(AmazonScrapingHistory.item_id==autoIncrementItem.item_id).filter(AmazonScrapingHistory.timestamp>time-timedelta(days=1)).order_by(asc(AmazonScrapingHistory.timestamp)).first()
171
        if antecedentPrice is not None:
172
            if float(math.ceil(autoIncrementItem.ourSellingPrice+max(10,.01*autoIncrementItem.ourSellingPrice))-math.ceil(antecedentPrice[0]+max(10,.01*antecedentPrice[0])))/math.ceil(antecedentPrice[0]+max(10,.01*antecedentPrice[0]))>.02:
173
                markReasonForItem(autoIncrementItem,'Maximum price increase in last 24 hours should be 2%',Decision.AUTO_INCREMENT_FAILED)
174
                continue
175
        fbaSaleSnapshot = transaction_client.getAmazonFbaSalesLatestSnapshotForItemLocationWise(autoIncrementItem.item_id,autoIncrementItem.warehouseLocation)
176
        if getLastDaySale(fbaSaleSnapshot,autoIncrementItem.warehouseLocation-1)<=2:
177
            markReasonForItem(autoIncrementItem,'Last day sale is less than 3',Decision.AUTO_INCREMENT_FAILED)
178
            continue
179
 
180
        autoIncrementItem.ourEnoughStock = False
181
        autoIncrementItem.decision = Decision.AUTO_INCREMENT_SUCCESS
182
        autoIncrementItem.reason = 'All conditions for auto increment true'
183
        successfulAutoIncrease.append(autoIncrementItem)
184
    session.commit()
185
    return successfulAutoIncrease     
186
 
187
 
188
def markReasonForItem(amHistory,reason,decision):
189
    amHistory.decision = decision
190
    amHistory.reason = reason
191
 
12424 kshitij.so 192
def calculateAverageSale(sku):
193
    count,sale = 0,0
194
    oosStatus = saleMap.get(sku)
195
    for obj in oosStatus:
196
        if not obj.isOutOfStock:
197
            count+=1
198
            sale = sale+obj.totalOrderCount
199
    avgSalePerDay=0 if count==0 else (float(sale)/count)
200
    return round(avgSalePerDay,2)
201
 
202
 
12396 kshitij.so 203
def getOosString(oosStatus):
204
    lastNdaySale=""
205
    for obj in oosStatus:
12423 kshitij.so 206
        if obj.isOutOfStock:
12396 kshitij.so 207
            lastNdaySale += "X-"
208
        else:
12426 kshitij.so 209
            lastNdaySale += str(obj.totalOrderCount) + "-"
12396 kshitij.so 210
    return lastNdaySale[:-1]
211
 
212
def getLastDaySale(fbaSaleSnapshot):
213
    if fbaSaleSnapshot.item_id==0:
214
        return 0
215
    else:
12423 kshitij.so 216
        return fbaSaleSnapshot.totalOrderCount
12396 kshitij.so 217
 
12430 kshitij.so 218
#def syncAsin():
219
##    notListedOnAmazon = []
220
##    diffAsins = []
221
##    login_url = "https://sellercentral.amazon.in/gp/homepage.html"
222
##    br = SellerCentralInventoryReport.login(login_url)
223
##    report_url = "https://sellercentral.amazon.in/gp/upload-download-utils/requestReport.html?type=OpenListingReport&marketplaceID=44571&Request+Report="
224
##    br = SellerCentralInventoryReport.requestReport(br,report_url)
225
##    status_url="https://sellercentral.amazon.in/gp/upload-download-utils/reportStatusData.html"
226
##    br, page = SellerCentralInventoryReport.checkStatus(br,status_url)
227
##    br, batchId = SellerCentralInventoryReport.getReportBatchId(br,page)
228
##    print "*********************************"
229
##    print "Batch Id for request is ",batchId
230
##    print "*********************************"
231
##    ready = False
232
##    retryCount = 0
233
##    while not ready:
234
##        if retryCount == 10:
235
##            print "File not available for download after multiple retries"
236
##            sys.exit(1)
237
##        br, download_link = SellerCentralInventoryReport.downloadReport(br,batchId,status_url)
238
##        if download_link is not None:
239
##            ready= True
240
##            continue
241
##        print "File not ready for download yet.Will try again after 30 seconds."
242
##        retryCount+=1
243
##        time.sleep(30)
244
##    fPath = SellerCentralInventoryReport.fetchFile(download_link['href'],br,batchId)
245
#    fPath = "/tmp/9940651090.txt"
246
#    global amazonAsinPrice
247
#    for line in open(fPath):
248
#        l = line.split('\t')
249
#        if (str(l[0]).startswith('FBA') or str(l[0]).startswith('FBB')):
250
#            obj = __AmazonAsinPrice(l[1],l[2])
251
#            amazonAsinPrice[l[0]] = obj
252
##Can be used to sync asins, not doing due to multiple asins corresponding to one itemId
253
##    systemAsins = session.query(Item,Amazonlisted).join((Amazonlisted,Item.id==Amazonlisted.itemId)).all()
254
##    for systemAsin in systemAsins:
255
##        item = systemAsin[0]
256
##        amListed = systemAsin[1]
257
##        if amazonAsinPrice.get('FBA'+str(item.id)) is None:
258
##            temp=[]
259
##            temp.append(item)
260
##            temp.append(amListed)
261
##            notListedOnAmazon.append(temp)
262
##            continue
263
##        else:
264
##            temp=[]
265
##            temp.append(item)
266
##            temp.append(amListed)
267
##            if item.asin!=((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip():
268
##                diffAsins.append(temp)
269
##                continue
270
##            
271
##    for diffAsin in diffAsins:
272
##        item = diffAsin[0]
273
##        amListed = diffAsin[1]
274
##        item.asin = ((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip()
275
##        amListed.asin = ((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip()
276
##    session.commit()
277
##    session.close()
12363 kshitij.so 278
 
279
def fetchFbaSale():
280
    global saleMap
281
    transaction_client = TransactionClient().get_client()
282
    fbaSaleSnapshot = transaction_client.getAmazonFbaSalesSnapshotForDays(4)
283
    for saleSnapshot in fbaSaleSnapshot:
284
        if saleSnapshot.fcLocation == 0:
285
            if saleMap.has_key('FBA'+str(saleSnapshot.item_id)):
286
                temp = []
12367 kshitij.so 287
                val = saleMap.get('FBA'+str(saleSnapshot.item_id))
288
                for l in val:
12363 kshitij.so 289
                    temp.append(l)
290
                temp.append(saleSnapshot)
12366 kshitij.so 291
                saleMap['FBA'+str(saleSnapshot.item_id)]=temp
12363 kshitij.so 292
            else:
12368 kshitij.so 293
                temp = []
294
                temp.append(saleSnapshot)
295
                saleMap['FBA'+str(saleSnapshot.item_id)] = temp
12363 kshitij.so 296
        else:
297
            if saleMap.has_key('FBB'+str(saleSnapshot.item_id)):
298
                temp = []
12367 kshitij.so 299
                val = saleMap.get('FBB'+str(saleSnapshot.item_id))
300
                for l in val:
12363 kshitij.so 301
                    temp.append(l)
12368 kshitij.so 302
                saleMap['FBB'+str(saleSnapshot.item_id)]=temp
12363 kshitij.so 303
                temp.append(saleSnapshot)
304
            else:
12368 kshitij.so 305
                temp = []
306
                temp.append(saleSnapshot)
307
                saleMap['FBB'+str(saleSnapshot.item_id)] = temp
12363 kshitij.so 308
 
12424 kshitij.so 309
 
12363 kshitij.so 310
def computeCourierCost(weight):
12378 kshitij.so 311
    try:
312
        cCost = 10.0;
313
        slabs = int((weight*1000)/500-.001)
314
        for slab in range(0,slabs):
315
            cCost = cCost + 10.0;
316
        return cCost;
317
    except:
318
        return 10.0
12363 kshitij.so 319
 
320
 
321
def populateStuff(time,runType):
322
    global amazonLongTermActivePromotions
12396 kshitij.so 323
    global amazonShortTermActivePromotions
12363 kshitij.so 324
    itemInfo = []
325
    inventory_client = InventoryClient().get_client()
326
    fbaAvailableInventorySnapshot = inventory_client.getAllAvailableAmazonFbaItemInventory()
12387 kshitij.so 327
    print len(fbaAvailableInventorySnapshot)
12363 kshitij.so 328
    for fbaInventoryItem in fbaAvailableInventorySnapshot:
329
        d_amazon_listed = Amazonlisted.get_by(itemId=fbaInventoryItem.item_id)
330
        if d_amazon_listed is None:
331
            continue
332
        if d_amazon_listed.overrrideWanlc:
333
            wanlc = d_amazon_listed.exceptionalWanlc
334
        else:
335
            wanlc = inventory_client.getWanNlcForSource(fbaInventoryItem.item_id,OrderSource.AMAZON)
336
        it = Item.query.filter_by(id=fbaInventoryItem.item_id).one()
337
        category = Category.query.filter_by(id=it.category).one()
338
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
339
        scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.AMAZON).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
340
        if scp is not None:
341
            sourcePercentage = scp
342
        else:
343
            spm = SourcePercentageMaster.get_by(source=OrderSource.AMAZON)
344
            sourcePercentage = spm
12375 kshitij.so 345
        if fbaInventoryItem.location==0:
12377 kshitij.so 346
            sku = 'FBA'+str(fbaInventoryItem.item_id)
12363 kshitij.so 347
            state_id = 1
12375 kshitij.so 348
        elif fbaInventoryItem.location==1:
12377 kshitij.so 349
            sku = 'FBB'+str(fbaInventoryItem.item_id)
12363 kshitij.so 350
            state_id = 2
351
        else:
352
            continue
353
        cc = computeCourierCost(it.weight)
12379 kshitij.so 354
 
12430 kshitij.so 355
        amazonItemInfo = __AmazonItemInfo(None, wanlc,cc, sku, it.product_group, it.brand, it.model_name, it.model_number, it.color, it.weight, category.parent_category_id, it.risky, None, runType, parent_category.display_name,sourcePercentage,fbaInventoryItem.availability,state_id)
12363 kshitij.so 356
        itemInfo.append(amazonItemInfo)
357
    amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.LONGTERM).filter(AmazonPromotion.promotionActive==True) \
358
    .group_by(AmazonPromotion.sku).order_by(desc(AmazonPromotion.addedOn)).all()
359
    for amPromotion in amPromotions:
360
        amazonLongTermActivePromotions.append(amPromotion.sku)
12396 kshitij.so 361
    amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.SHORTTERM).filter(AmazonPromotion.promotionActive==True) \
362
    .group_by(AmazonPromotion.sku).order_by(desc(AmazonPromotion.addedOn)).all()
363
    for amPromotion in amPromotions:
364
        amazonShortTermActivePromotions.append(amPromotion.sku)
12363 kshitij.so 365
    session.close()
366
    return itemInfo
367
 
12430 kshitij.so 368
def getPriceAndAsin(itemInfo):
369
    skus = []
370
    for item in itemInfo:
371
        skus.append(item.sku)
372
    ourPricingForSku = amScraper.get_my_pricing_for_sku('A21TJRUUN4KGV', skus)
373
    for item in itemInfo:
374
        ourPricing = ourPricingForSku.get(item.sku)
375
        if len(ourPricing.keys())==0:
376
            item.ourSp = 0
377
            item.promoPrice = 0
378
            item.isPromotion = False
379
        else:
380
            item.ourSp = ourPricing.get('sellingPrice')
381
            item.promoPrice = ourPricing.get('promoPrice')
382
            item.isPromotion = ourPricing.get('promotion')
383
 
384
 
12363 kshitij.so 385
def decideCategory(itemInfo):
386
    exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = [],[],[],[],[],[],[] 
12430 kshitij.so 387
    skus = []
12363 kshitij.so 388
    for item in itemInfo:
12430 kshitij.so 389
        skus.append(item.sku)
390
    aggResponse = amScraper.get_competitive_pricing_for_sku('A21TJRUUN4KGV', skus)
391
    ourPricingForSku = amScraper.get_my_pricing_for_sku('A21TJRUUN4KGV', skus)
12403 kshitij.so 392
 
12363 kshitij.so 393
    for val in itemInfo:
12430 kshitij.so 394
        scrapInfo = aggResponse.get(val.sku)
395
        if len(scrapInfo)==0 or val.nlc==0 or len(ourPricingForSku.get(val.sku).keys())==0:
12363 kshitij.so 396
            temp = []
397
            temp.append(val)
398
            if val.nlc==0 or val.nlc is None:
399
                temp.append("WANLC is 0")
12430 kshitij.so 400
            elif len(ourPricingForSku.get(val.sku).keys())==0:
401
                temp.append("Unable to fetch our price")
12363 kshitij.so 402
            else:
12430 kshitij.so 403
                temp.append("Unable to fetch competitive pricing")
12363 kshitij.so 404
            exceptionList.append(temp)
405
            continue
12430 kshitij.so 406
        val.asin = ourPricingForSku.get(val.sku).get('asin')
407
        val.ourSp = ourPricingForSku.get(val.sku).get('sellingPrice')
408
        val.promoPrice = ourPricingForSku.get(val.sku).get('promoPrice')
409
        val.isPromo = ourPricingForSku.get(val.sku).get('promotion')
12363 kshitij.so 410
        iterator = 0
411
        sku, lowestSellerName,secondLowestSellerName, thirdLowestSellerName = ('',)*4
412
        ourSp, ourRank, lowestSellerSp, secondLowestSellerSp, thirdLowestSellerSp, ourTp, lowestPossibleSp, lowestPossibleTp = (0,)*8
12430 kshitij.so 413
        lowestSellerShippingTime, lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , \
414
        thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType = (0,)*9
415
        isPromo = False
12363 kshitij.so 416
        sku = val.sku
417
        scrapedSkuLocation = None
418
        multipleListings = False
12430 kshitij.so 419
        ourSkuDetails = ourPricingForSku.get(val.sku)
420
        scrapInfo.append(ourSkuDetails)
421
        sortedScrapInfo =  sorted(scrapInfo, key=itemgetter('promoPrice','notOurSku'))
422
        for info in sortedScrapInfo:
423
            if  not info.notOurSku:
424
                ourSp = info.sellingPrice
425
                promoPrice = info.promoPrice
426
                isPromo = info.promotion
427
                ourRank = iterator + 1
12363 kshitij.so 428
 
429
            if iterator == 0:
12430 kshitij.so 430
                lowestSellerSp = info['promoPrice']
431
                lowestSellerShippingTime = info['shippingTime']
432
                lowestSellerRating = info['rating']
433
                lowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 434
 
435
            if iterator == 1:
12430 kshitij.so 436
                secondLowestSellerSp = info['promoPrice']
437
                secondLowestSellerShippingTime = info['shippingTime']
438
                secondLowestSellerRating = info['rating']
439
                secondLowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 440
 
441
            if iterator == 2:
12430 kshitij.so 442
                thirdLowestSellerSp = info['promoPrice']
443
                thirdLowestSellerShippingTime = info['shippingTime']
444
                thirdLowestSellerRating = info['rating']
445
                thirdLowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 446
 
447
            iterator += 1
12401 kshitij.so 448
        print "terminating iterator"
12363 kshitij.so 449
 
450
 
12408 kshitij.so 451
        print "Creating object am details",val.sku
12430 kshitij.so 452
        amDetails = __AmazonDetails(sku, float(ourSp), ourRank, lowestSellerName,float(lowestSellerSp),secondLowestSellerName, float(secondLowestSellerSp), thirdLowestSellerName, float(thirdLowestSellerSp),len(scrapInfo),multipleListings,promoPrice,isPromo, \
453
                    lowestSellerShippingTime ,lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType)
12414 kshitij.so 454
        print "am details obj created"
12363 kshitij.so 455
        try:
12414 kshitij.so 456
            print "inside val getter"
12418 kshitij.so 457
            itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==int(val.sku[3:]), ItemVatMaster.stateId==val.state_id)).first()
458
            if itemVatMaster is None:
12419 kshitij.so 459
                d_item = Item.query.filter_by(id=int(val.sku[3:])).first()
460
                if d_item is None:
461
                    raise 
462
                else:
12430 kshitij.so 463
                    vatMaster = CategoryVatMaster.query.filter(and_(CategoryVatMaster.categoryId==d_item.category, CategoryVatMaster.minVal<=amDetails.promoPrice,  CategoryVatMaster.maxVal>=amDetails.promoPrice,  CategoryVatMaster.stateId == val.state_id)).first()
12419 kshitij.so 464
                if vatMaster is None:
12418 kshitij.so 465
                    raise
12419 kshitij.so 466
                else:
467
                    val.vatRate = vatMaster.vatPercent
468
                    print "vat fetched"
12418 kshitij.so 469
            else:
470
                val.vatRate = itemVatMaster.vatPercentage
12419 kshitij.so 471
                print "vat fetched"
12363 kshitij.so 472
        except:
12414 kshitij.so 473
            print "vat exception"
12363 kshitij.so 474
            temp = []
475
            temp.append(val)
476
            temp.append("Vat not available")
477
            exceptionList.append(temp)
478
            continue
479
 
480
        ourTp = getOurTp(amDetails,val,val.sourcePercentage)
481
        lowestPossibleTp = getLowestPossibleTp(amDetails,val,val.sourcePercentage)
482
        lowestPossibleSp = getLowestPossibleSp(amDetails,val,val.sourcePercentage)
12408 kshitij.so 483
        print "Creating pricing obj"
12363 kshitij.so 484
        amPricing = __AmazonPricing(ourSp,ourTp,lowestPossibleTp,lowestPossibleSp)
485
 
486
        if amPricing.ourTp < amPricing.lowestPossibleTp:
487
            temp = []
488
            temp.append(val)
489
            temp.append(amDetails)
490
            temp.append(amPricing)
491
            negativeMargin.append(temp)
492
            continue
493
 
494
        if amDetails.ourRank==1:
495
            temp = []
496
            temp.append(val)
497
            temp.append(amDetails)
498
            temp.append(amPricing)
499
            cheapest.append(temp)
500
            continue
501
 
12430 kshitij.so 502
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp) and ((((float(amDetails.promoPrice - amDetails.lowestSellerSp))/amDetails.promoPrice)<=.01) or ((amDetails.promoPrice - amDetails.lowestSellerSp)<=25)):
12363 kshitij.so 503
            temp = []
504
            temp.append(val)
505
            temp.append(amDetails)
506
            temp.append(amPricing)
507
            amongCheapestAndCanCompete.append(temp)
508
            continue
509
 
510
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp):
511
            temp = []
512
            temp.append(val)
513
            temp.append(amDetails)
514
            temp.append(amPricing)
515
            canCompete.append(temp)
516
            continue
517
 
12403 kshitij.so 518
        if amDetails.lowestSellerSp*(1+.01) >= amPricing.lowestPossibleSp:
12396 kshitij.so 519
            temp = []
520
            temp.append(val)
521
            temp.append(amDetails)
522
            temp.append(amPricing)
523
            almostCompete.append(temp)
524
            continue
525
 
526
 
12363 kshitij.so 527
        temp = []
528
        temp.append(val)
529
        temp.append(amDetails)
530
        temp.append(amPricing)
531
        cantCompete.append(temp)
12414 kshitij.so 532
    print "Created category..."
12363 kshitij.so 533
 
534
    return exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete
12396 kshitij.so 535
 
12363 kshitij.so 536
def getOurTp(amazonDetails,val,spm):
12430 kshitij.so 537
    ourTp = amazonDetails.promoPrice- amazonDetails.promoPrice*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))*(1+(spm.serviceTax/100));
12363 kshitij.so 538
    return round(ourTp,2)
539
 
540
def getLowestPossibleTp(amazonDetails,val,spm):
12430 kshitij.so 541
    vat = (amazonDetails.promoPrice/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100)
542
    inHouseCost = 15+vat+(spm.returnProvision/100)*amazonDetails.promoPrice
12363 kshitij.so 543
    lowest_possible_tp = val.nlc+inHouseCost
544
    return round(lowest_possible_tp,2)
545
 
546
def getLowestPossibleSp(amazonDetails,val,spm):
547
    lowestPossibleSp = (val.nlc+(val.courierCost)*(1+(spm.serviceTax/100))*(1+(val.vatRate/100))+(15)*(1+(val.vatRate)/100))/(1-(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))*(1+(val.vatRate)/100)-(spm.returnProvision/100)*(1+(val.vatRate)/100));
548
    return round(lowestPossibleSp,2)
549
 
550
def getTargetTp(targetSp,spm,val):
12424 kshitij.so 551
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))
12363 kshitij.so 552
    return round(targetTp,2)
553
 
554
def commitExceptionList(exceptionList,timestamp,runType):
555
    for exceptionItem in exceptionList:
556
        val = exceptionItem[0]
557
        reason = exceptionItem[1]
558
        amazonScrapingHistory = AmazonScrapingHistory()
559
        amazonScrapingHistory.item_id = val.sku[3:]
560
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 561
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 562
        amazonScrapingHistory.reason = reason
563
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
564
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.EXCEPTION
565
        amazonScrapingHistory.timestamp = timestamp
566
    session.commit()
567
 
568
def commitNegativeMargin(negativeMargin,timestamp,runType):
569
    for negativeMarginItem in negativeMargin:
570
        val = negativeMarginItem[0]
571
        amDetails = negativeMarginItem[1]
572
        amPricing = negativeMarginItem[2]
573
        spm = val.sourcePercentage
574
        amazonScrapingHistory = AmazonScrapingHistory()
575
        amazonScrapingHistory.item_id = val.sku[3:]
576
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 577
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 578
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
579
        amazonScrapingHistory.ourTp = amPricing.ourTp
580
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
581
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
582
        amazonScrapingHistory.ourRank = amDetails.ourRank
583
        amazonScrapingHistory.ourInventory = val.ourInventory
584
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
585
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
586
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
587
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
588
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
589
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
590
        amazonScrapingHistory.wanlc = val.nlc
591
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 592
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 593
        amazonScrapingHistory.returnProvision = spm.returnProvision
594
        amazonScrapingHistory.courierCost = val.courierCost
595
        amazonScrapingHistory.risky = val.risky
596
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
597
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
598
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
599
        amazonScrapingHistory.timestamp = timestamp
600
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
601
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
602
    session.commit()
603
 
604
 
605
def commitCheapest(cheapest,timestamp,runType):
606
    for cheapestItem in cheapest:
607
        val = cheapestItem[0]
608
        amDetails = cheapestItem[1]
609
        amPricing = cheapestItem[2]
610
        spm = val.sourcePercentage
611
        amazonScrapingHistory = AmazonScrapingHistory()
612
        amazonScrapingHistory.item_id = val.sku[3:]
613
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 614
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 615
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
616
        amazonScrapingHistory.ourTp = amPricing.ourTp
617
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
618
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
619
        amazonScrapingHistory.ourRank = amDetails.ourRank
620
        amazonScrapingHistory.ourInventory = val.ourInventory
621
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
622
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 623
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
624
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
625
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 626
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
627
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 628
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
629
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
630
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12363 kshitij.so 631
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
632
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 633
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
634
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
635
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12363 kshitij.so 636
        amazonScrapingHistory.wanlc = val.nlc
637
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 638
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 639
        amazonScrapingHistory.returnProvision = spm.returnProvision
640
        amazonScrapingHistory.courierCost = val.courierCost
641
        amazonScrapingHistory.risky = val.risky
642
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
643
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
644
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.BUY_BOX
645
        amazonScrapingHistory.timestamp = timestamp
646
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12430 kshitij.so 647
        proposed_sp = max(amDetails.secondLowestSellerSp - max((20, amDetails.secondLowestSellerSp*0.002)), amPricing.lowestPossibleSp)
12363 kshitij.so 648
        proposed_tp = getTargetTp(proposed_sp,spm,val)
649
        amazonScrapingHistory.proposedSp = proposed_sp
650
        amazonScrapingHistory.proposedTp = proposed_tp
651
        amazonScrapingHistory.marginIncreasedPotential = proposed_tp - amPricing.ourTp
652
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
653
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
654
    session.commit()
655
 
656
 
657
 
658
def commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,runType):
659
    for amongCheapestAndCanCompeteItem in amongCheapestAndCanCompete:
660
        val = amongCheapestAndCanCompeteItem[0]
661
        amDetails = amongCheapestAndCanCompeteItem[1]
662
        amPricing = amongCheapestAndCanCompeteItem[2]
663
        spm = val.sourcePercentage
664
        amazonScrapingHistory = AmazonScrapingHistory()
665
        amazonScrapingHistory.item_id = val.sku[3:]
666
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 667
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 668
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
669
        amazonScrapingHistory.ourTp = amPricing.ourTp
670
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
671
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
672
        amazonScrapingHistory.ourRank = amDetails.ourRank
673
        amazonScrapingHistory.ourInventory = val.ourInventory
674
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
675
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 676
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
677
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
678
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 679
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
680
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 681
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
682
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
683
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12363 kshitij.so 684
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
685
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 686
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
687
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
688
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12363 kshitij.so 689
        amazonScrapingHistory.wanlc = val.nlc
690
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 691
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 692
        amazonScrapingHistory.returnProvision = spm.returnProvision
693
        amazonScrapingHistory.courierCost = val.courierCost
694
        amazonScrapingHistory.risky = val.risky
695
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
696
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
697
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE
698
        amazonScrapingHistory.timestamp = timestamp
699
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
700
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
701
        proposed_tp = getTargetTp(proposed_sp,spm,val)
702
        amazonScrapingHistory.proposedSp = proposed_sp
703
        amazonScrapingHistory.proposedTp = proposed_tp
704
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
705
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
706
    session.commit()
707
 
708
def commitCanCompete(canCompete,timestamp,runType):
709
    for canCompeteItem in canCompete:
710
        val = canCompeteItem[0]
711
        amDetails = canCompeteItem[1]
712
        amPricing = canCompeteItem[2]
713
        spm = val.sourcePercentage
714
        amazonScrapingHistory = AmazonScrapingHistory()
715
        amazonScrapingHistory.item_id = val.sku[3:]
716
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 717
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 718
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
719
        amazonScrapingHistory.ourTp = amPricing.ourTp
720
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
721
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
722
        amazonScrapingHistory.ourRank = amDetails.ourRank
723
        amazonScrapingHistory.ourInventory = val.ourInventory
724
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
725
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 726
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
727
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
728
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 729
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
730
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 731
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
732
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
733
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12363 kshitij.so 734
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
735
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 736
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
737
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
738
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12363 kshitij.so 739
        amazonScrapingHistory.wanlc = val.nlc
740
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 741
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 742
        amazonScrapingHistory.returnProvision = spm.returnProvision
743
        amazonScrapingHistory.courierCost = val.courierCost
744
        amazonScrapingHistory.risky = val.risky
745
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
746
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
747
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
748
        amazonScrapingHistory.timestamp = timestamp
749
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
750
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
751
        proposed_tp = getTargetTp(proposed_sp,spm,val)
752
        amazonScrapingHistory.proposedSp = proposed_sp
753
        amazonScrapingHistory.proposedTp = proposed_tp
754
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
755
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
756
    session.commit()
757
 
12383 kshitij.so 758
def commitAlmostCompete(almostCompete,timestamp,runType):
12396 kshitij.so 759
    for almostCompeteItem in almostCompete:
760
        val = almostCompeteItem[0]
761
        amDetails = almostCompeteItem[1]
762
        amPricing = almostCompeteItem[2]
763
        spm = val.sourcePercentage
764
        amazonScrapingHistory = AmazonScrapingHistory()
765
        amazonScrapingHistory.item_id = val.sku[3:]
766
        amazonScrapingHistory.warehouseLocation = val.state_id
767
        amazonScrapingHistory.parentCategoryId = val.parent_category
768
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
769
        amazonScrapingHistory.ourTp = amPricing.ourTp
770
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
771
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
772
        amazonScrapingHistory.ourRank = amDetails.ourRank
773
        amazonScrapingHistory.ourInventory = val.ourInventory
774
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
775
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 776
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
777
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
778
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12396 kshitij.so 779
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
780
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 781
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
782
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
783
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12396 kshitij.so 784
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
785
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 786
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
787
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
788
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12396 kshitij.so 789
        amazonScrapingHistory.wanlc = val.nlc
790
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 791
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12396 kshitij.so 792
        amazonScrapingHistory.returnProvision = spm.returnProvision
793
        amazonScrapingHistory.courierCost = val.courierCost
794
        amazonScrapingHistory.risky = val.risky
795
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
796
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
797
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.ALMOST_COMPETE
798
        amazonScrapingHistory.timestamp = timestamp
799
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12425 kshitij.so 800
        proposed_sp = min(amDetails.lowestSellerSp*(1+.01),amPricing.lowestPossibleSp)
12396 kshitij.so 801
        proposed_tp = getTargetTp(proposed_sp,spm,val)
802
        target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
803
        amazonScrapingHistory.proposedSp = proposed_sp
804
        amazonScrapingHistory.proposedTp = proposed_tp
805
        amazonScrapingHistory.targetNlc = target_nlc
806
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
807
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
808
    session.commit()
12363 kshitij.so 809
 
12396 kshitij.so 810
 
12363 kshitij.so 811
def commitCantCompete(cantCompete, timestamp,runType):
812
    for cantCompeteItem in cantCompete:
813
        val = cantCompeteItem[0]
814
        amDetails = cantCompeteItem[1]
815
        amPricing = cantCompeteItem[2]
816
        spm = val.sourcePercentage
817
        amazonScrapingHistory = AmazonScrapingHistory()
818
        amazonScrapingHistory.item_id = val.sku[3:]
819
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 820
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 821
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
822
        amazonScrapingHistory.ourTp = amPricing.ourTp
823
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
824
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
825
        amazonScrapingHistory.ourRank = amDetails.ourRank
826
        amazonScrapingHistory.ourInventory = val.ourInventory
827
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
828
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 829
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
830
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
831
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 832
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
833
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 834
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
835
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
836
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12363 kshitij.so 837
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
838
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 839
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
840
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
841
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12363 kshitij.so 842
        amazonScrapingHistory.wanlc = val.nlc
843
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 844
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 845
        amazonScrapingHistory.returnProvision = spm.returnProvision
846
        amazonScrapingHistory.courierCost = val.courierCost
847
        amazonScrapingHistory.risky = val.risky
848
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
849
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
850
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
851
        amazonScrapingHistory.timestamp = timestamp
852
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
853
        proposed_sp = amDetails.lowestSellerSp - max(5, amDetails.lowestSellerSp*0.001)
854
        proposed_tp = getTargetTp(proposed_sp,spm,val)
855
        target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
856
        amazonScrapingHistory.proposedSp = proposed_sp
857
        amazonScrapingHistory.proposedTp = proposed_tp
858
        amazonScrapingHistory.targetNlc = target_nlc
859
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
860
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
861
    session.commit()
862
 
12396 kshitij.so 863
def markAutoFavourites(time):
864
    nowAutoFav = []
865
    previouslyAutoFav = []
866
    stockList = []
867
    saleList = []
868
    items = session.query(func.sum(AmazonScrapingHistory.ourInventory),AmazonScrapingHistory.item_id).group_by(AmazonScrapingHistory.item_id).all()
869
    allItems = session.query(Amazonlisted).all()
870
    for item in items:
871
        reason = ""
872
        if item[0]>=5:
873
            stockList.append(item[1])
874
 
875
    for sku, val in saleMap.iteritems():
876
        totalSale = 0
877
        item_id = sku.replace('FBA','').replace('FBB','')
878
        val =saleMap.get('FBA'+str(item_id))
879
        if val is not None:
880
            for sale in val:
881
                totalSale += sale.totalOrderCount
882
        val =saleMap.get('FBB'+str(item_id))
883
        if val is not None:
884
            for sale in val:
885
                totalSale += sale.totalOrderCount
886
        if totalSale > 0:
887
            saleList.append(item_id)
888
 
889
    for aItem in allItems:
890
        reason = ""
891
        toMark = False
892
        if aItem.itemId in saleList:
893
            toMark = True
894
            reason+="Total FC sale is greater than 1 for last five days.."
895
        if aItem.itemId in stockList:
896
            toMark = True
897
            reason+="Item is present in buy box in last 3 days"
898
        if not aItem.autoFavourite:
899
            print "Item is not under auto favourite"
900
        if toMark:
901
            temp=[]
902
            temp.append(aItem.itemId)
903
            temp.append(reason)
904
            nowAutoFav.append(temp)
905
        if (not toMark) and aItem.autoFavourite:
906
            previouslyAutoFav.append(aItem.itemId)
907
        aItem.autoFavourite = toMark
908
    session.commit()
909
    return previouslyAutoFav, nowAutoFav
910
 
911
def writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav):
912
    wbk = xlwt.Workbook()
913
    sheet = wbk.add_sheet('Can\'t Compete')
914
    xstr = lambda s: s or ""
915
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
916
 
917
    excel_integer_format = '0'
918
    integer_style = xlwt.XFStyle()
919
    integer_style.num_format_str = excel_integer_format
920
 
921
    sheet.write(0, 0, "Item Id", heading_xf)
922
    sheet.write(0, 1, "Amazon Sku", heading_xf)
923
    sheet.write(0, 2, "Asin", heading_xf)
924
    sheet.write(0, 3, "Location", heading_xf)
925
    sheet.write(0, 4, "Brand", heading_xf)
926
    sheet.write(0, 5, "Product Name", heading_xf)
927
    sheet.write(0, 6, "Weight", heading_xf)
928
    sheet.write(0, 7, "Courier Cost", heading_xf)
929
    sheet.write(0, 8, "Our SP", heading_xf)
930
    sheet.write(0, 9, "Our Tp", heading_xf)
931
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
932
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
933
    sheet.write(0, 12, "Rank", heading_xf)
934
    sheet.write(0, 13, "Our Inventory", heading_xf)
935
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
936
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
937
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
938
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
939
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
940
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
941
    sheet.write(0, 20, "WANLC", heading_xf)
942
    sheet.write(0, 21, "Commission", heading_xf)
943
    sheet.write(0, 22, "Competitor Commission", heading_xf)
944
    sheet.write(0, 23, "Return Provision", heading_xf)
945
    sheet.write(0, 24, "Margin", heading_xf)
946
    sheet.write(0, 25, "Risky", heading_xf)
947
    sheet.write(0, 26, "Proposed Sp", heading_xf)
948
    sheet.write(0, 27, "Proposed Tp", heading_xf)
949
    sheet.write(0, 28, "Target Nlc", heading_xf)
950
    sheet.write(0, 29, "Avg Sale", heading_xf)
951
    sheet.write(0, 30, "Sales History", heading_xf)
952
 
953
    sheet_iterator = 1
954
    cantCompeteItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
955
    for cantCompeteItem in cantCompeteItems:
956
        amScraping =  cantCompeteItem[0]
957
        item = cantCompeteItem[1]
958
        sheet.write(sheet_iterator, 0, amScraping.item_id)
959
        if amScraping.warehouseLocation == 1:
960
            sku = 'FBA'+str(amScraping.item_id)
961
            loc = 'MUMBAI'
962
        else:
963
            sku = 'FBB'+str(amScraping.item_id)
964
            loc = 'BANGLORE'
965
        sheet.write(sheet_iterator, 1, sku)
966
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
967
        sheet.write(sheet_iterator, 3, loc)
968
        sheet.write(sheet_iterator, 4, item.brand)
969
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
970
        sheet.write(sheet_iterator, 6, item.weight)
971
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
972
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
973
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
974
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
975
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
976
        if amScraping.ourRank > 3:
977
            sheet.write(sheet_iterator, 12, 'Greater than 3')
978
        else:
979
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
980
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
981
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
982
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
983
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
984
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
985
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
986
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
987
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
988
        sheet.write(sheet_iterator, 21, amScraping.commission)
989
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
990
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
991
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
992
        sheet.write(sheet_iterator, 25, item.risky)
993
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
994
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
995
        sheet.write(sheet_iterator, 28, amScraping.targetNlc)
996
        sheet.write(sheet_iterator, 29, amScraping.avgSale)
997
        sheet.write(sheet_iterator, 30, getOosString(saleMap.get(sku)))
998
        sheet_iterator+=1
999
 
1000
    sheet = wbk.add_sheet('Competitive')
1001
    xstr = lambda s: s or ""
1002
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1003
 
1004
    excel_integer_format = '0'
1005
    integer_style = xlwt.XFStyle()
1006
    integer_style.num_format_str = excel_integer_format
1007
 
1008
    sheet.write(0, 0, "Item Id", heading_xf)
1009
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1010
    sheet.write(0, 2, "Asin", heading_xf)
1011
    sheet.write(0, 3, "Location", heading_xf)
1012
    sheet.write(0, 4, "Brand", heading_xf)
1013
    sheet.write(0, 5, "Product Name", heading_xf)
1014
    sheet.write(0, 6, "Weight", heading_xf)
1015
    sheet.write(0, 7, "Courier Cost", heading_xf)
1016
    sheet.write(0, 8, "Our SP", heading_xf)
1017
    sheet.write(0, 9, "Our Tp", heading_xf)
1018
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1019
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1020
    sheet.write(0, 12, "Rank", heading_xf)
1021
    sheet.write(0, 13, "Our Inventory", heading_xf)
1022
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1023
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1024
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1025
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1026
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1027
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1028
    sheet.write(0, 20, "WANLC", heading_xf)
1029
    sheet.write(0, 21, "Commission", heading_xf)
1030
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1031
    sheet.write(0, 23, "Return Provision", heading_xf)
1032
    sheet.write(0, 24, "Margin", heading_xf)
1033
    sheet.write(0, 25, "Risky", heading_xf)
1034
    sheet.write(0, 26, "Proposed Sp", heading_xf)
1035
    sheet.write(0, 27, "Proposed Tp", heading_xf)
1036
    sheet.write(0, 28, "Avg Sale", heading_xf)
1037
    sheet.write(0, 29, "Sales History", heading_xf)
1038
 
1039
    sheet_iterator = 1
1040
    competitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.COMPETITIVE).all()
1041
    for competitiveItem in competitiveItems:
1042
        amScraping =  competitiveItem[0]
1043
        item = competitiveItem[1]
1044
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1045
        if amScraping.warehouseLocation == 1:
1046
            sku = 'FBA'+str(amScraping.item_id)
1047
            loc = 'MUMBAI'
1048
        else:
1049
            sku = 'FBB'+str(amScraping.item_id)
1050
            loc = 'BANGLORE'
1051
        sheet.write(sheet_iterator, 1, sku)
1052
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1053
        sheet.write(sheet_iterator, 3, loc)
1054
        sheet.write(sheet_iterator, 4, item.brand)
1055
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1056
        sheet.write(sheet_iterator, 6, item.weight)
1057
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1058
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1059
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1060
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1061
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1062
        if amScraping.ourRank > 3:
1063
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1064
        else:
1065
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1066
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1067
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1068
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1069
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1070
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1071
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1072
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1073
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1074
        sheet.write(sheet_iterator, 21, amScraping.commission)
1075
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1076
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1077
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1078
        sheet.write(sheet_iterator, 25, item.risky)
1079
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
1080
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
1081
        sheet.write(sheet_iterator, 28, amScraping.avgSale)
1082
        sheet.write(sheet_iterator, 29, getOosString(saleMap.get(sku)))
1083
        sheet_iterator+=1
1084
 
1085
    sheet = wbk.add_sheet('Almost Competitive')
1086
    xstr = lambda s: s or ""
1087
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1088
 
1089
    excel_integer_format = '0'
1090
    integer_style = xlwt.XFStyle()
1091
    integer_style.num_format_str = excel_integer_format
1092
 
1093
    sheet.write(0, 0, "Item Id", heading_xf)
1094
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1095
    sheet.write(0, 2, "Asin", heading_xf)
1096
    sheet.write(0, 3, "Location", heading_xf)
1097
    sheet.write(0, 4, "Brand", heading_xf)
1098
    sheet.write(0, 5, "Product Name", heading_xf)
1099
    sheet.write(0, 6, "Weight", heading_xf)
1100
    sheet.write(0, 7, "Courier Cost", heading_xf)
1101
    sheet.write(0, 8, "Our SP", heading_xf)
1102
    sheet.write(0, 9, "Our Tp", heading_xf)
1103
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1104
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1105
    sheet.write(0, 12, "Rank", heading_xf)
1106
    sheet.write(0, 13, "Our Inventory", heading_xf)
1107
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1108
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1109
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1110
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1111
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1112
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1113
    sheet.write(0, 20, "WANLC", heading_xf)
1114
    sheet.write(0, 21, "Commission", heading_xf)
1115
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1116
    sheet.write(0, 23, "Return Provision", heading_xf)
1117
    sheet.write(0, 24, "Margin", heading_xf)
1118
    sheet.write(0, 25, "Risky", heading_xf)
1119
    sheet.write(0, 26, "Proposed Sp", heading_xf)
1120
    sheet.write(0, 27, "Proposed Tp", heading_xf)
1121
    sheet.write(0, 28, "Avg Sale", heading_xf)
1122
    sheet.write(0, 29, "Sales History", heading_xf)
1123
 
1124
    sheet_iterator = 1
1125
    almostCompetitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.ALMOST_COMPETE).all()
1126
    for almostCompetitiveItem in almostCompetitiveItems:
1127
        amScraping =  almostCompetitiveItem[0]
1128
        item = almostCompetitiveItem[1]
1129
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1130
        if amScraping.warehouseLocation == 1:
1131
            sku = 'FBA'+str(amScraping.item_id)
1132
            loc = 'MUMBAI'
1133
        else:
1134
            sku = 'FBB'+str(amScraping.item_id)
1135
            loc = 'BANGLORE'
1136
        sheet.write(sheet_iterator, 1, sku)
1137
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1138
        sheet.write(sheet_iterator, 3, loc)
1139
        sheet.write(sheet_iterator, 4, item.brand)
1140
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1141
        sheet.write(sheet_iterator, 6, item.weight)
1142
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1143
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1144
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1145
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1146
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1147
        if amScraping.ourRank > 3:
1148
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1149
        else:
1150
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1151
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1152
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1153
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1154
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1155
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1156
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1157
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1158
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1159
        sheet.write(sheet_iterator, 21, amScraping.commission)
1160
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1161
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1162
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1163
        sheet.write(sheet_iterator, 25, item.risky)
1164
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
1165
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
1166
        sheet.write(sheet_iterator, 28, amScraping.avgSale)
1167
        sheet.write(sheet_iterator, 29, getOosString(saleMap.get(sku)))
1168
        sheet_iterator+=1
1169
 
1170
    sheet = wbk.add_sheet('Among Cheapest')
1171
    xstr = lambda s: s or ""
1172
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1173
 
1174
    excel_integer_format = '0'
1175
    integer_style = xlwt.XFStyle()
1176
    integer_style.num_format_str = excel_integer_format
1177
 
1178
    sheet.write(0, 0, "Item Id", heading_xf)
1179
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1180
    sheet.write(0, 2, "Asin", heading_xf)
1181
    sheet.write(0, 3, "Location", heading_xf)
1182
    sheet.write(0, 4, "Brand", heading_xf)
1183
    sheet.write(0, 5, "Product Name", heading_xf)
1184
    sheet.write(0, 6, "Weight", heading_xf)
1185
    sheet.write(0, 7, "Courier Cost", heading_xf)
1186
    sheet.write(0, 8, "Our SP", heading_xf)
1187
    sheet.write(0, 9, "Our Tp", heading_xf)
1188
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1189
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1190
    sheet.write(0, 12, "Rank", heading_xf)
1191
    sheet.write(0, 13, "Our Inventory", heading_xf)
1192
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1193
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1194
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1195
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1196
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1197
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1198
    sheet.write(0, 20, "WANLC", heading_xf)
1199
    sheet.write(0, 21, "Commission", heading_xf)
1200
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1201
    sheet.write(0, 23, "Return Provision", heading_xf)
1202
    sheet.write(0, 24, "Margin", heading_xf)
1203
    sheet.write(0, 25, "Risky", heading_xf)
1204
    sheet.write(0, 26, "Proposed Sp", heading_xf)
1205
    sheet.write(0, 27, "Proposed Tp", heading_xf)
1206
    sheet.write(0, 28, "Avg Sale", heading_xf)
1207
    sheet.write(0, 29, "Sales History", heading_xf)
1208
 
1209
    sheet_iterator = 1
1210
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1211
    for amongCheapestItem in amongCheapestItems:
1212
        amScraping =  amongCheapestItem[0]
1213
        item = amongCheapestItem[1]
1214
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1215
        if amScraping.warehouseLocation == 1:
1216
            sku = 'FBA'+str(amScraping.item_id)
1217
            loc = 'MUMBAI'
1218
        else:
1219
            sku = 'FBB'+str(amScraping.item_id)
1220
            loc = 'BANGLORE'
1221
        sheet.write(sheet_iterator, 1, sku)
1222
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1223
        sheet.write(sheet_iterator, 3, loc)
1224
        sheet.write(sheet_iterator, 4, item.brand)
1225
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1226
        sheet.write(sheet_iterator, 6, item.weight)
1227
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1228
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1229
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1230
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1231
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1232
        if amScraping.ourRank > 3:
1233
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1234
        else:
1235
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1236
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1237
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1238
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1239
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1240
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1241
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1242
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1243
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1244
        sheet.write(sheet_iterator, 21, amScraping.commission)
1245
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1246
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1247
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1248
        sheet.write(sheet_iterator, 25, item.risky)
1249
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
1250
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
1251
        sheet.write(sheet_iterator, 28, amScraping.avgSale)
1252
        sheet.write(sheet_iterator, 29, getOosString(saleMap.get(sku)))
1253
        sheet_iterator+=1
1254
 
1255
    sheet = wbk.add_sheet('Cheapest')
1256
    xstr = lambda s: s or ""
1257
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1258
 
1259
    excel_integer_format = '0'
1260
    integer_style = xlwt.XFStyle()
1261
    integer_style.num_format_str = excel_integer_format
1262
 
1263
    sheet.write(0, 0, "Item Id", heading_xf)
1264
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1265
    sheet.write(0, 2, "Asin", heading_xf)
1266
    sheet.write(0, 3, "Location", heading_xf)
1267
    sheet.write(0, 4, "Brand", heading_xf)
1268
    sheet.write(0, 5, "Product Name", heading_xf)
1269
    sheet.write(0, 6, "Weight", heading_xf)
1270
    sheet.write(0, 7, "Courier Cost", heading_xf)
1271
    sheet.write(0, 8, "Our SP", heading_xf)
1272
    sheet.write(0, 9, "Our Tp", heading_xf)
1273
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1274
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1275
    sheet.write(0, 12, "Rank", heading_xf)
1276
    sheet.write(0, 13, "Our Inventory", heading_xf)
1277
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1278
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1279
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1280
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1281
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1282
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1283
    sheet.write(0, 20, "WANLC", heading_xf)
1284
    sheet.write(0, 21, "Commission", heading_xf)
1285
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1286
    sheet.write(0, 23, "Return Provision", heading_xf)
1287
    sheet.write(0, 24, "Margin", heading_xf)
1288
    sheet.write(0, 25, "Risky", heading_xf)
1289
    sheet.write(0, 26, "Proposed Sp", heading_xf)
1290
    sheet.write(0, 27, "Proposed Tp", heading_xf)
1291
    sheet.write(0, 28, "Margin Increased Potential", heading_xf)
1292
    sheet.write(0, 29, "Avg Sale", heading_xf)
1293
    sheet.write(0, 30, "Sales History", heading_xf)
1294
 
1295
    sheet_iterator = 1
1296
    cheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1297
    for cheapestItem in cheapestItems:
1298
        amScraping =  cheapestItem[0]
1299
        item = cheapestItem[1]
1300
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1301
        if amScraping.warehouseLocation == 1:
1302
            sku = 'FBA'+str(amScraping.item_id)
1303
            loc = 'MUMBAI'
1304
        else:
1305
            sku = 'FBB'+str(amScraping.item_id)
1306
            loc = 'BANGLORE'
1307
        sheet.write(sheet_iterator, 1, sku)
1308
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1309
        sheet.write(sheet_iterator, 3, loc)
1310
        sheet.write(sheet_iterator, 4, item.brand)
1311
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1312
        sheet.write(sheet_iterator, 6, item.weight)
1313
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1314
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1315
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1316
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1317
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1318
        if amScraping.ourRank > 3:
1319
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1320
        else:
1321
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1322
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1323
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1324
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1325
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1326
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1327
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1328
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1329
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1330
        sheet.write(sheet_iterator, 21, amScraping.commission)
1331
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1332
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1333
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1334
        sheet.write(sheet_iterator, 25, item.risky)
1335
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
1336
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
1337
        sheet.write(sheet_iterator, 28, amScraping.marginIncreasedPotential)
1338
        sheet.write(sheet_iterator, 29, amScraping.avgSale)
1339
        sheet.write(sheet_iterator, 30, getOosString(saleMap.get(sku)))
1340
        sheet_iterator+=1
1341
 
1342
    sheet = wbk.add_sheet('Negative Margin')
1343
    xstr = lambda s: s or ""
1344
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1345
 
1346
    excel_integer_format = '0'
1347
    integer_style = xlwt.XFStyle()
1348
    integer_style.num_format_str = excel_integer_format
1349
 
1350
    sheet.write(0, 0, "Item Id", heading_xf)
1351
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1352
    sheet.write(0, 2, "Asin", heading_xf)
1353
    sheet.write(0, 3, "Location", heading_xf)
1354
    sheet.write(0, 4, "Brand", heading_xf)
1355
    sheet.write(0, 5, "Product Name", heading_xf)
1356
    sheet.write(0, 6, "Weight", heading_xf)
1357
    sheet.write(0, 7, "Courier Cost", heading_xf)
1358
    sheet.write(0, 8, "Our SP", heading_xf)
1359
    sheet.write(0, 9, "Our Tp", heading_xf)
1360
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1361
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1362
    sheet.write(0, 12, "Rank", heading_xf)
1363
    sheet.write(0, 13, "Our Inventory", heading_xf)
1364
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1365
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1366
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1367
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1368
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1369
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1370
    sheet.write(0, 20, "WANLC", heading_xf)
1371
    sheet.write(0, 21, "Commission", heading_xf)
1372
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1373
    sheet.write(0, 23, "Return Provision", heading_xf)
1374
    sheet.write(0, 24, "Margin", heading_xf)
1375
    sheet.write(0, 25, "Avg Sale", heading_xf)
1376
    sheet.write(0, 26, "Sales History", heading_xf)
1377
 
1378
    sheet_iterator = 1
1379
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1380
    for amongCheapestItem in amongCheapestItems:
1381
        amScraping =  amongCheapestItem[0]
1382
        item = amongCheapestItem[1]
1383
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1384
        if amScraping.warehouseLocation == 1:
1385
            sku = 'FBA'+str(amScraping.item_id)
1386
            loc = 'MUMBAI'
1387
        else:
1388
            sku = 'FBB'+str(amScraping.item_id)
1389
            loc = 'BANGLORE'
1390
        sheet.write(sheet_iterator, 1, sku)
1391
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1392
        sheet.write(sheet_iterator, 3, loc)
1393
        sheet.write(sheet_iterator, 4, item.brand)
1394
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1395
        sheet.write(sheet_iterator, 6, item.weight)
1396
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1397
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1398
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1399
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1400
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1401
        if amScraping.ourRank > 3:
1402
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1403
        else:
1404
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1405
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1406
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1407
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1408
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1409
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1410
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1411
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1412
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1413
        sheet.write(sheet_iterator, 21, amScraping.commission)
1414
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1415
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1416
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1417
        sheet.write(sheet_iterator, 25, amScraping.avgSale)
1418
        sheet.write(sheet_iterator, 26, getOosString(saleMap.get(sku)))
1419
        sheet_iterator+=1
1420
 
1421
    sheet = wbk.add_sheet('Exception List')
1422
    xstr = lambda s: s or ""
1423
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1424
 
1425
    excel_integer_format = '0'
1426
    integer_style = xlwt.XFStyle()
1427
    integer_style.num_format_str = excel_integer_format
1428
 
1429
    sheet.write(0, 0, "Item Id", heading_xf)
1430
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1431
    sheet.write(0, 2, "Asin", heading_xf)
1432
    sheet.write(0, 3, "Location", heading_xf)
1433
    sheet.write(0, 4, "Brand", heading_xf)
1434
    sheet.write(0, 5, "Product Name", heading_xf)
1435
    sheet.write(0, 6, "Reason", heading_xf)
1436
 
1437
    sheet_iterator = 1
1438
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1439
    for amongCheapestItem in amongCheapestItems:
1440
        amScraping =  amongCheapestItem[0]
1441
        item = amongCheapestItem[1]
1442
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1443
        if amScraping.warehouseLocation == 1:
1444
            sku = 'FBA'+str(amScraping.item_id)
1445
            loc = 'MUMBAI'
1446
        else:
1447
            sku = 'FBB'+str(amScraping.item_id)
1448
            loc = 'BANGLORE'
1449
        sheet.write(sheet_iterator, 1, sku)
1450
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1451
        sheet.write(sheet_iterator, 3, loc)
1452
        sheet.write(sheet_iterator, 4, item.brand)
1453
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1454
        sheet.write(sheet_iterator, 6, amScraping.reason)
1455
        sheet_iterator+=1      
1456
 
1457
    filename = "/tmp/amazon-scraping.xls"
1458
    wbk.save(filename)
1459
 
12363 kshitij.so 1460
def main():
1461
    parser = optparse.OptionParser()
1462
    parser.add_option("-t", "--type", dest="runType",
1463
                   default="FULL", type="string",
1464
                   help="Run type FULL or FAVOURITE")
1465
    (options, args) = parser.parse_args()
1466
    if options.runType not in ('FULL','FAVOURITE'):
1467
        print "Run type argument illegal."
1468
        sys.exit(1)
1469
    time.sleep(5)
1470
    timestamp = datetime.now()
1471
    fetchFbaSale()
1472
    itemInfo = populateStuff(timestamp,options.runType)
1473
    itemsToPopulate = 0
12430 kshitij.so 1474
    toSync = 0
1475
    lenItems = len(itemInfo)
1476
    while(toSync < lenItems):
1477
        oldSync = toSync
1478
        if lenItems >= 20:
1479
            toSync = 20
1480
        else:
1481
            toSync = lenItems - oldSync
1482
        getPriceAndAsin(itemInfo[oldSync:toSync+oldSync])
1483
        toSync = oldSync + toSync
1484
 
12363 kshitij.so 1485
    while (len(itemInfo)>0):
12430 kshitij.so 1486
        if len(itemInfo) >= 20:
1487
            itemsToPopulate = 20
12363 kshitij.so 1488
        else:
1489
            itemsToPopulate = len(itemInfo)
12370 kshitij.so 1490
        print itemsToPopulate
12363 kshitij.so 1491
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate])
1492
        itemInfo[0:itemsToPopulate] = []
1493
        commitExceptionList(exceptionList,timestamp,options.runType)
1494
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
1495
        commitCheapest(cheapest,timestamp,options.runType)
1496
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
1497
        commitCanCompete(canCompete,timestamp,options.runType)
1498
        commitAlmostCompete(almostCompete,timestamp,options.runType)
1499
        commitCantCompete(cantCompete, timestamp,options.runType)
12396 kshitij.so 1500
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1501
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1502
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1503
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
1504
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav)
12363 kshitij.so 1505
if __name__=='__main__':
1506
    main()