Subversion Repositories SmartDukaan

Rev

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