Subversion Repositories SmartDukaan

Rev

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