Subversion Repositories SmartDukaan

Rev

Rev 12443 | Rev 12447 | 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
 
12444 kshitij.so 919
def writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,runType):
12396 kshitij.so 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)
12444 kshitij.so 963
    sheet.write(0, 34, "Decision", heading_xf)
964
    sheet.write(0, 35, "Reason", heading_xf)
965
    sheet.write(0, 36, "Updated Price", heading_xf)
12396 kshitij.so 966
 
967
    sheet_iterator = 1
968
    cantCompeteItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
969
    for cantCompeteItem in cantCompeteItems:
970
        amScraping =  cantCompeteItem[0]
971
        item = cantCompeteItem[1]
972
        sheet.write(sheet_iterator, 0, amScraping.item_id)
973
        if amScraping.warehouseLocation == 1:
974
            sku = 'FBA'+str(amScraping.item_id)
975
            loc = 'MUMBAI'
976
        else:
977
            sku = 'FBB'+str(amScraping.item_id)
978
            loc = 'BANGLORE'
979
        sheet.write(sheet_iterator, 1, sku)
980
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
981
        sheet.write(sheet_iterator, 3, loc)
982
        sheet.write(sheet_iterator, 4, item.brand)
983
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
984
        sheet.write(sheet_iterator, 6, item.weight)
985
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
986
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 987
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
988
        if amScraping.isPromotion:
989
            sheet.write(sheet_iterator, 10, "Yes")
990
        else:
991
            sheet.write(sheet_iterator, 10, "Yes")
992
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 993
        if amScraping.ourRank > 3:
994
            sheet.write(sheet_iterator, 12, 'Greater than 3')
995
        else:
996
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
997
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 998
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
999
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1000
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1001
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1002
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1003
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1004
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1005
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1006
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
1007
        sheet.write(sheet_iterator, 23, amScraping.wanlc)
1008
        sheet.write(sheet_iterator, 24, amScraping.commission)
1009
        sheet.write(sheet_iterator, 25, amScraping.competitorCommission)
1010
        sheet.write(sheet_iterator, 26, amScraping.returnProvision)
1011
        sheet.write(sheet_iterator, 27, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1012
        sheet.write(sheet_iterator, 28, item.risky)
1013
        sheet.write(sheet_iterator, 29, amScraping.proposedSp)
1014
        sheet.write(sheet_iterator, 30, amScraping.proposedTp)
1015
        sheet.write(sheet_iterator, 31, amScraping.targetNlc)
1016
        sheet.write(sheet_iterator, 32, amScraping.avgSale)
1017
        sheet.write(sheet_iterator, 33, getOosString(saleMap.get(sku)))
12444 kshitij.so 1018
        if amScraping.decision is None:
1019
            sheet.write(sheet_iterator, 34, 'Auto Pricing Inactive')
1020
            sheet_iterator+=1
1021
            continue
1022
        sheet.write(sheet_iterator, 34, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1023
        sheet.write(sheet_iterator, 35, amScraping.reason)
1024
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
1025
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.proposedSellingPrice))
1026
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
1027
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1028
        sheet_iterator+=1
1029
 
1030
    sheet = wbk.add_sheet('Competitive')
1031
    xstr = lambda s: s or ""
1032
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1033
 
1034
    excel_integer_format = '0'
1035
    integer_style = xlwt.XFStyle()
1036
    integer_style.num_format_str = excel_integer_format
1037
 
1038
    sheet.write(0, 0, "Item Id", heading_xf)
1039
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1040
    sheet.write(0, 2, "Asin", heading_xf)
1041
    sheet.write(0, 3, "Location", heading_xf)
1042
    sheet.write(0, 4, "Brand", heading_xf)
1043
    sheet.write(0, 5, "Product Name", heading_xf)
1044
    sheet.write(0, 6, "Weight", heading_xf)
1045
    sheet.write(0, 7, "Courier Cost", heading_xf)
1046
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1047
    sheet.write(0, 9, "Promo Price", heading_xf)
1048
    sheet.write(0, 10, "Is Promotion", heading_xf)
1049
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1050
    sheet.write(0, 12, "Rank", heading_xf)
1051
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1052
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1053
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1054
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1055
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1056
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1057
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1058
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1059
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1060
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
1061
    sheet.write(0, 23, "WANLC", heading_xf)
1062
    sheet.write(0, 24, "Commission", heading_xf)
1063
    sheet.write(0, 25, "Competitor Commission", heading_xf)
1064
    sheet.write(0, 26, "Return Provision", heading_xf)
1065
    sheet.write(0, 27, "Margin", heading_xf)
1066
    sheet.write(0, 28, "Risky", heading_xf)
1067
    sheet.write(0, 29, "Proposed Sp", heading_xf)
1068
    sheet.write(0, 30, "Proposed Tp", heading_xf)
1069
    sheet.write(0, 31, "Avg Sale", heading_xf)
1070
    sheet.write(0, 32, "Sales History", heading_xf)
12444 kshitij.so 1071
    sheet.write(0, 33, "Decision", heading_xf)
1072
    sheet.write(0, 34, "Reason", heading_xf)
1073
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1074
 
1075
    sheet_iterator = 1
1076
    competitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.COMPETITIVE).all()
1077
    for competitiveItem in competitiveItems:
1078
        amScraping =  competitiveItem[0]
1079
        item = competitiveItem[1]
1080
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1081
        if amScraping.warehouseLocation == 1:
1082
            sku = 'FBA'+str(amScraping.item_id)
1083
            loc = 'MUMBAI'
1084
        else:
1085
            sku = 'FBB'+str(amScraping.item_id)
1086
            loc = 'BANGLORE'
1087
        sheet.write(sheet_iterator, 1, sku)
1088
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1089
        sheet.write(sheet_iterator, 3, loc)
1090
        sheet.write(sheet_iterator, 4, item.brand)
1091
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1092
        sheet.write(sheet_iterator, 6, item.weight)
1093
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1094
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1095
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1096
        if amScraping.isPromotion:
1097
            sheet.write(sheet_iterator, 10, "Yes")
1098
        else:
1099
            sheet.write(sheet_iterator, 10, "Yes")
1100
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1101
        if amScraping.ourRank > 3:
1102
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1103
        else:
1104
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1105
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1106
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1107
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1108
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1109
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1110
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1111
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1112
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1113
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1114
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
1115
        sheet.write(sheet_iterator, 23, amScraping.wanlc)
1116
        sheet.write(sheet_iterator, 24, amScraping.commission)
1117
        sheet.write(sheet_iterator, 25, amScraping.competitorCommission)
1118
        sheet.write(sheet_iterator, 26, amScraping.returnProvision)
1119
        sheet.write(sheet_iterator, 27, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1120
        sheet.write(sheet_iterator, 28, item.risky)
1121
        sheet.write(sheet_iterator, 29, amScraping.proposedSp)
1122
        sheet.write(sheet_iterator, 30, amScraping.proposedTp)
1123
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1124
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1125
        if amScraping.decision is None:
1126
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
1127
            sheet_iterator+=1
1128
            continue
1129
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1130
        sheet.write(sheet_iterator, 34, amScraping.reason)
1131
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
1132
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSellingPrice))
1133
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
1134
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1135
        sheet_iterator+=1
1136
 
1137
    sheet = wbk.add_sheet('Almost Competitive')
1138
    xstr = lambda s: s or ""
1139
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1140
 
1141
    excel_integer_format = '0'
1142
    integer_style = xlwt.XFStyle()
1143
    integer_style.num_format_str = excel_integer_format
1144
 
1145
    sheet.write(0, 0, "Item Id", heading_xf)
1146
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1147
    sheet.write(0, 2, "Asin", heading_xf)
1148
    sheet.write(0, 3, "Location", heading_xf)
1149
    sheet.write(0, 4, "Brand", heading_xf)
1150
    sheet.write(0, 5, "Product Name", heading_xf)
1151
    sheet.write(0, 6, "Weight", heading_xf)
1152
    sheet.write(0, 7, "Courier Cost", heading_xf)
1153
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1154
    sheet.write(0, 9, "Promo Price", heading_xf)
1155
    sheet.write(0, 10, "Is Promotion", heading_xf)
1156
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1157
    sheet.write(0, 12, "Rank", heading_xf)
1158
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1159
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1160
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1161
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1162
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1163
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1164
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1165
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1166
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1167
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
1168
    sheet.write(0, 23, "WANLC", heading_xf)
1169
    sheet.write(0, 24, "Commission", heading_xf)
1170
    sheet.write(0, 25, "Competitor Commission", heading_xf)
1171
    sheet.write(0, 26, "Return Provision", heading_xf)
1172
    sheet.write(0, 27, "Margin", heading_xf)
1173
    sheet.write(0, 28, "Risky", heading_xf)
1174
    sheet.write(0, 29, "Proposed Sp", heading_xf)
1175
    sheet.write(0, 30, "Proposed Tp", heading_xf)
1176
    sheet.write(0, 31, "Avg Sale", heading_xf)
1177
    sheet.write(0, 32, "Sales History", heading_xf)
12444 kshitij.so 1178
    sheet.write(0, 33, "Decision", heading_xf)
1179
    sheet.write(0, 34, "Reason", heading_xf)
1180
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1181
 
1182
    sheet_iterator = 1
1183
    almostCompetitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.ALMOST_COMPETE).all()
1184
    for almostCompetitiveItem in almostCompetitiveItems:
1185
        amScraping =  almostCompetitiveItem[0]
1186
        item = almostCompetitiveItem[1]
1187
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1188
        if amScraping.warehouseLocation == 1:
1189
            sku = 'FBA'+str(amScraping.item_id)
1190
            loc = 'MUMBAI'
1191
        else:
1192
            sku = 'FBB'+str(amScraping.item_id)
1193
            loc = 'BANGLORE'
12432 kshitij.so 1194
        amScraping =  competitiveItem[0]
1195
        item = competitiveItem[1]
1196
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1197
        if amScraping.warehouseLocation == 1:
1198
            sku = 'FBA'+str(amScraping.item_id)
1199
            loc = 'MUMBAI'
1200
        else:
1201
            sku = 'FBB'+str(amScraping.item_id)
1202
            loc = 'BANGLORE'
12396 kshitij.so 1203
        sheet.write(sheet_iterator, 1, sku)
1204
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1205
        sheet.write(sheet_iterator, 3, loc)
1206
        sheet.write(sheet_iterator, 4, item.brand)
1207
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1208
        sheet.write(sheet_iterator, 6, item.weight)
1209
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1210
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1211
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1212
        if amScraping.isPromotion:
1213
            sheet.write(sheet_iterator, 10, "Yes")
1214
        else:
1215
            sheet.write(sheet_iterator, 10, "Yes")
1216
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1217
        if amScraping.ourRank > 3:
1218
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1219
        else:
1220
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1221
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1222
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1223
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1224
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1225
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1226
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1227
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1228
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1229
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1230
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
1231
        sheet.write(sheet_iterator, 23, amScraping.wanlc)
1232
        sheet.write(sheet_iterator, 24, amScraping.commission)
1233
        sheet.write(sheet_iterator, 25, amScraping.competitorCommission)
1234
        sheet.write(sheet_iterator, 26, amScraping.returnProvision)
1235
        sheet.write(sheet_iterator, 27, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1236
        sheet.write(sheet_iterator, 28, item.risky)
1237
        sheet.write(sheet_iterator, 29, amScraping.proposedSp)
1238
        sheet.write(sheet_iterator, 30, amScraping.proposedTp)
1239
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1240
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1241
        if amScraping.decision is None:
1242
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
1243
            sheet_iterator+=1
1244
            continue
1245
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1246
        sheet.write(sheet_iterator, 34, amScraping.reason)
1247
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
1248
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSellingPrice))
1249
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
1250
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1251
        sheet_iterator+=1
1252
 
1253
    sheet = wbk.add_sheet('Among Cheapest')
1254
    xstr = lambda s: s or ""
1255
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1256
 
1257
    excel_integer_format = '0'
1258
    integer_style = xlwt.XFStyle()
1259
    integer_style.num_format_str = excel_integer_format
1260
 
1261
    sheet.write(0, 0, "Item Id", heading_xf)
1262
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1263
    sheet.write(0, 2, "Asin", heading_xf)
1264
    sheet.write(0, 3, "Location", heading_xf)
1265
    sheet.write(0, 4, "Brand", heading_xf)
1266
    sheet.write(0, 5, "Product Name", heading_xf)
1267
    sheet.write(0, 6, "Weight", heading_xf)
1268
    sheet.write(0, 7, "Courier Cost", heading_xf)
1269
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1270
    sheet.write(0, 9, "Promo Price", heading_xf)
1271
    sheet.write(0, 10, "Is Promotion", heading_xf)
1272
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1273
    sheet.write(0, 12, "Rank", heading_xf)
1274
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1275
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1276
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1277
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1278
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1279
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1280
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1281
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1282
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1283
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
1284
    sheet.write(0, 23, "WANLC", heading_xf)
1285
    sheet.write(0, 24, "Commission", heading_xf)
1286
    sheet.write(0, 25, "Competitor Commission", heading_xf)
1287
    sheet.write(0, 26, "Return Provision", heading_xf)
1288
    sheet.write(0, 27, "Margin", heading_xf)
1289
    sheet.write(0, 28, "Risky", heading_xf)
1290
    sheet.write(0, 29, "Proposed Sp", heading_xf)
1291
    sheet.write(0, 30, "Proposed Tp", heading_xf)
1292
    sheet.write(0, 31, "Avg Sale", heading_xf)
1293
    sheet.write(0, 32, "Sales History", heading_xf)
12444 kshitij.so 1294
    sheet.write(0, 33, "Decision", heading_xf)
1295
    sheet.write(0, 34, "Reason", heading_xf)
1296
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1297
 
1298
    sheet_iterator = 1
1299
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1300
    for amongCheapestItem in amongCheapestItems:
1301
        amScraping =  amongCheapestItem[0]
1302
        item = amongCheapestItem[1]
1303
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1304
        if amScraping.warehouseLocation == 1:
1305
            sku = 'FBA'+str(amScraping.item_id)
1306
            loc = 'MUMBAI'
1307
        else:
1308
            sku = 'FBB'+str(amScraping.item_id)
1309
            loc = 'BANGLORE'
1310
        sheet.write(sheet_iterator, 1, sku)
1311
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1312
        sheet.write(sheet_iterator, 3, loc)
1313
        sheet.write(sheet_iterator, 4, item.brand)
1314
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1315
        sheet.write(sheet_iterator, 6, item.weight)
1316
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1317
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1318
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1319
        if amScraping.isPromotion:
1320
            sheet.write(sheet_iterator, 10, "Yes")
1321
        else:
1322
            sheet.write(sheet_iterator, 10, "Yes")
1323
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1324
        if amScraping.ourRank > 3:
1325
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1326
        else:
1327
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1328
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1329
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1330
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1331
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1332
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1333
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1334
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1335
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1336
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1337
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
1338
        sheet.write(sheet_iterator, 23, amScraping.wanlc)
1339
        sheet.write(sheet_iterator, 24, amScraping.commission)
1340
        sheet.write(sheet_iterator, 25, amScraping.competitorCommission)
1341
        sheet.write(sheet_iterator, 26, amScraping.returnProvision)
1342
        sheet.write(sheet_iterator, 27, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1343
        sheet.write(sheet_iterator, 28, item.risky)
1344
        sheet.write(sheet_iterator, 29, amScraping.proposedSp)
1345
        sheet.write(sheet_iterator, 30, amScraping.proposedTp)
1346
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1347
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1348
        if amScraping.decision is None:
1349
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
1350
            sheet_iterator+=1
1351
            continue
1352
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1353
        sheet.write(sheet_iterator, 34, amScraping.reason)
1354
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
1355
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSellingPrice))
1356
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
1357
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1358
        sheet_iterator+=1
1359
 
1360
    sheet = wbk.add_sheet('Cheapest')
1361
    xstr = lambda s: s or ""
1362
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1363
 
1364
    excel_integer_format = '0'
1365
    integer_style = xlwt.XFStyle()
1366
    integer_style.num_format_str = excel_integer_format
1367
 
1368
    sheet.write(0, 0, "Item Id", heading_xf)
1369
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1370
    sheet.write(0, 2, "Asin", heading_xf)
1371
    sheet.write(0, 3, "Location", heading_xf)
1372
    sheet.write(0, 4, "Brand", heading_xf)
1373
    sheet.write(0, 5, "Product Name", heading_xf)
1374
    sheet.write(0, 6, "Weight", heading_xf)
1375
    sheet.write(0, 7, "Courier Cost", heading_xf)
1376
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1377
    sheet.write(0, 9, "Promo Price", heading_xf)
1378
    sheet.write(0, 10, "Is Promotion", heading_xf)
1379
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1380
    sheet.write(0, 12, "Rank", heading_xf)
1381
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1382
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1383
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1384
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1385
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1386
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1387
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1388
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1389
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1390
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
1391
    sheet.write(0, 23, "WANLC", heading_xf)
1392
    sheet.write(0, 24, "Commission", heading_xf)
1393
    sheet.write(0, 25, "Competitor Commission", heading_xf)
1394
    sheet.write(0, 26, "Return Provision", heading_xf)
1395
    sheet.write(0, 27, "Margin", heading_xf)
1396
    sheet.write(0, 28, "Risky", heading_xf)
1397
    sheet.write(0, 29, "Proposed Sp", heading_xf)
1398
    sheet.write(0, 30, "Proposed Tp", heading_xf)
1399
    sheet.write(0, 31, "Margin Increased Potential", heading_xf)
1400
    sheet.write(0, 32, "Avg Sale", heading_xf)
1401
    sheet.write(0, 33, "Sales History", heading_xf)
12444 kshitij.so 1402
    sheet.write(0, 34, "Decision", heading_xf)
1403
    sheet.write(0, 35, "Reason", heading_xf)
1404
    sheet.write(0, 36, "Updated Price", heading_xf)
12396 kshitij.so 1405
 
1406
    sheet_iterator = 1
1407
    cheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1408
    for cheapestItem in cheapestItems:
1409
        amScraping =  cheapestItem[0]
1410
        item = cheapestItem[1]
1411
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1412
        if amScraping.warehouseLocation == 1:
1413
            sku = 'FBA'+str(amScraping.item_id)
1414
            loc = 'MUMBAI'
1415
        else:
1416
            sku = 'FBB'+str(amScraping.item_id)
1417
            loc = 'BANGLORE'
1418
        sheet.write(sheet_iterator, 1, sku)
1419
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1420
        sheet.write(sheet_iterator, 3, loc)
1421
        sheet.write(sheet_iterator, 4, item.brand)
1422
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1423
        sheet.write(sheet_iterator, 6, item.weight)
1424
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1425
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1426
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1427
        if amScraping.isPromotion:
1428
            sheet.write(sheet_iterator, 10, "Yes")
1429
        else:
1430
            sheet.write(sheet_iterator, 10, "Yes")
1431
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1432
        if amScraping.ourRank > 3:
1433
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1434
        else:
1435
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1436
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1437
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1438
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1439
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1440
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1441
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1442
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1443
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1444
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1445
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
1446
        sheet.write(sheet_iterator, 23, amScraping.wanlc)
1447
        sheet.write(sheet_iterator, 24, amScraping.commission)
1448
        sheet.write(sheet_iterator, 25, amScraping.competitorCommission)
1449
        sheet.write(sheet_iterator, 26, amScraping.returnProvision)
1450
        sheet.write(sheet_iterator, 27, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1451
        sheet.write(sheet_iterator, 28, item.risky)
1452
        sheet.write(sheet_iterator, 29, amScraping.proposedSp)
1453
        sheet.write(sheet_iterator, 30, amScraping.proposedTp)
1454
        sheet.write(sheet_iterator, 31, amScraping.targetNlc)
1455
        sheet.write(sheet_iterator, 32, amScraping.avgSale)
1456
        sheet.write(sheet_iterator, 33, getOosString(saleMap.get(sku)))
12444 kshitij.so 1457
        if amScraping.decision is None:
1458
            sheet.write(sheet_iterator, 34, 'Auto Pricing Inactive')
1459
            sheet_iterator+=1
1460
            continue
1461
        sheet.write(sheet_iterator, 34, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1462
        sheet.write(sheet_iterator, 35, amScraping.reason)
1463
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
1464
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.proposedSellingPrice))
1465
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
1466
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1467
        sheet_iterator+=1
1468
 
1469
    sheet = wbk.add_sheet('Negative Margin')
1470
    xstr = lambda s: s or ""
1471
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1472
 
1473
    excel_integer_format = '0'
1474
    integer_style = xlwt.XFStyle()
1475
    integer_style.num_format_str = excel_integer_format
1476
 
1477
    sheet.write(0, 0, "Item Id", heading_xf)
1478
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1479
    sheet.write(0, 2, "Asin", heading_xf)
1480
    sheet.write(0, 3, "Location", heading_xf)
1481
    sheet.write(0, 4, "Brand", heading_xf)
1482
    sheet.write(0, 5, "Product Name", heading_xf)
1483
    sheet.write(0, 6, "Weight", heading_xf)
1484
    sheet.write(0, 7, "Courier Cost", heading_xf)
1485
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1486
    sheet.write(0, 9, "Promo Price", heading_xf)
1487
    sheet.write(0, 10, "Is Promotion", heading_xf)
1488
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1489
    sheet.write(0, 12, "Rank", heading_xf)
1490
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1491
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1492
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1493
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1494
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1495
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1496
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1497
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1498
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1499
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
1500
    sheet.write(0, 23, "WANLC", heading_xf)
1501
    sheet.write(0, 24, "Commission", heading_xf)
1502
    sheet.write(0, 25, "Competitor Commission", heading_xf)
1503
    sheet.write(0, 26, "Return Provision", heading_xf)
1504
    sheet.write(0, 27, "Margin", heading_xf)
1505
    sheet.write(0, 28, "Avg Sale", heading_xf)
1506
    sheet.write(0, 29, "Sales History", heading_xf)
12396 kshitij.so 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, item.weight)
1526
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1527
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1528
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1529
        if amScraping.isPromotion:
1530
            sheet.write(sheet_iterator, 10, "Yes")
1531
        else:
1532
            sheet.write(sheet_iterator, 10, "Yes")
1533
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1534
        if amScraping.ourRank > 3:
1535
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1536
        else:
1537
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1538
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1539
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1540
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1541
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1542
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1543
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1544
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1545
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1546
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1547
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
1548
        sheet.write(sheet_iterator, 23, amScraping.wanlc)
1549
        sheet.write(sheet_iterator, 24, amScraping.commission)
1550
        sheet.write(sheet_iterator, 25, amScraping.competitorCommission)
1551
        sheet.write(sheet_iterator, 26, amScraping.returnProvision)
1552
        sheet.write(sheet_iterator, 27, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1553
        sheet.write(sheet_iterator, 28, amScraping.avgSale)
1554
        sheet.write(sheet_iterator, 29, getOosString(saleMap.get(sku)))
12396 kshitij.so 1555
        sheet_iterator+=1
1556
 
1557
    sheet = wbk.add_sheet('Exception List')
1558
    xstr = lambda s: s or ""
1559
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1560
 
1561
    excel_integer_format = '0'
1562
    integer_style = xlwt.XFStyle()
1563
    integer_style.num_format_str = excel_integer_format
1564
 
1565
    sheet.write(0, 0, "Item Id", heading_xf)
1566
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1567
    sheet.write(0, 2, "Asin", heading_xf)
1568
    sheet.write(0, 3, "Location", heading_xf)
1569
    sheet.write(0, 4, "Brand", heading_xf)
1570
    sheet.write(0, 5, "Product Name", heading_xf)
1571
    sheet.write(0, 6, "Reason", heading_xf)
1572
 
1573
    sheet_iterator = 1
1574
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1575
    for amongCheapestItem in amongCheapestItems:
1576
        amScraping =  amongCheapestItem[0]
1577
        item = amongCheapestItem[1]
1578
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1579
        if amScraping.warehouseLocation == 1:
1580
            sku = 'FBA'+str(amScraping.item_id)
1581
            loc = 'MUMBAI'
1582
        else:
1583
            sku = 'FBB'+str(amScraping.item_id)
1584
            loc = 'BANGLORE'
1585
        sheet.write(sheet_iterator, 1, sku)
1586
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1587
        sheet.write(sheet_iterator, 3, loc)
1588
        sheet.write(sheet_iterator, 4, item.brand)
1589
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1590
        sheet.write(sheet_iterator, 6, amScraping.reason)
1591
        sheet_iterator+=1      
1592
 
12444 kshitij.so 1593
 
1594
    if (runType=='FULL'):    
1595
        sheet = wbk.add_sheet('Auto Favorites')
1596
 
1597
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1598
 
1599
        excel_integer_format = '0'
1600
        integer_style = xlwt.XFStyle()
1601
        integer_style.num_format_str = excel_integer_format
1602
        xstr = lambda s: s or ""
1603
 
1604
        sheet.write(0, 0, "Item ID", heading_xf)
1605
        sheet.write(0, 1, "Brand", heading_xf)
1606
        sheet.write(0, 2, "Product Name", heading_xf)
1607
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1608
        sheet.write(0, 4, "Reason", heading_xf)
1609
 
1610
        sheet_iterator=1
1611
        for autoFav in nowAutoFav:
1612
            itemId = autoFav[0]
1613
            reason = autoFav[1]
1614
            it = Item.query.filter_by(id=itemId).one()
1615
            sheet.write(sheet_iterator, 0, itemId)
1616
            sheet.write(sheet_iterator, 1, it.brand)
1617
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1618
            sheet.write(sheet_iterator, 3, "True")
1619
            sheet.write(sheet_iterator, 4, reason)
1620
            sheet_iterator+=1
1621
        for prevFav in previousAutoFav:
1622
            it = Item.query.filter_by(id=prevFav).one()
1623
            sheet.write(sheet_iterator, 0, prevFav)
1624
            sheet.write(sheet_iterator, 1, it.brand)
1625
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1626
            sheet.write(sheet_iterator, 3, "False")
1627
            sheet_iterator+=1
1628
 
12396 kshitij.so 1629
    filename = "/tmp/amazon-scraping.xls"
1630
    wbk.save(filename)
1631
 
12363 kshitij.so 1632
def main():
1633
    parser = optparse.OptionParser()
1634
    parser.add_option("-t", "--type", dest="runType",
1635
                   default="FULL", type="string",
1636
                   help="Run type FULL or FAVOURITE")
1637
    (options, args) = parser.parse_args()
1638
    if options.runType not in ('FULL','FAVOURITE'):
1639
        print "Run type argument illegal."
1640
        sys.exit(1)
1641
    time.sleep(5)
1642
    timestamp = datetime.now()
1643
    fetchFbaSale()
1644
    itemInfo = populateStuff(timestamp,options.runType)
1645
    itemsToPopulate = 0
12430 kshitij.so 1646
    toSync = 0
1647
    lenItems = len(itemInfo)
1648
    while(toSync < lenItems):
1649
        oldSync = toSync
1650
        if lenItems >= 20:
1651
            toSync = 20
1652
        else:
1653
            toSync = lenItems - oldSync
1654
        getPriceAndAsin(itemInfo[oldSync:toSync+oldSync])
1655
        toSync = oldSync + toSync
1656
 
12363 kshitij.so 1657
    while (len(itemInfo)>0):
12430 kshitij.so 1658
        if len(itemInfo) >= 20:
1659
            itemsToPopulate = 20
12363 kshitij.so 1660
        else:
1661
            itemsToPopulate = len(itemInfo)
12370 kshitij.so 1662
        print itemsToPopulate
12363 kshitij.so 1663
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate])
1664
        itemInfo[0:itemsToPopulate] = []
1665
        commitExceptionList(exceptionList,timestamp,options.runType)
1666
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
1667
        commitCheapest(cheapest,timestamp,options.runType)
1668
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
1669
        commitCanCompete(canCompete,timestamp,options.runType)
1670
        commitAlmostCompete(almostCompete,timestamp,options.runType)
1671
        commitCantCompete(cantCompete, timestamp,options.runType)
12396 kshitij.so 1672
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1673
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1674
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1675
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
12444 kshitij.so 1676
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,options.runType)
12363 kshitij.so 1677
if __name__=='__main__':
1678
    main()