Subversion Repositories SmartDukaan

Rev

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