Subversion Repositories SmartDukaan

Rev

Rev 12479 | Rev 12481 | 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"
12363 kshitij.so 493
 
494
 
12408 kshitij.so 495
        print "Creating object am details",val.sku
12430 kshitij.so 496
        amDetails = __AmazonDetails(sku, float(ourSp), ourRank, lowestSellerName,float(lowestSellerSp),secondLowestSellerName, float(secondLowestSellerSp), thirdLowestSellerName, float(thirdLowestSellerSp),len(scrapInfo),multipleListings,promoPrice,isPromo, \
497
                    lowestSellerShippingTime ,lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType)
12414 kshitij.so 498
        print "am details obj created"
12363 kshitij.so 499
        try:
12414 kshitij.so 500
            print "inside val getter"
12418 kshitij.so 501
            itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==int(val.sku[3:]), ItemVatMaster.stateId==val.state_id)).first()
502
            if itemVatMaster is None:
12419 kshitij.so 503
                d_item = Item.query.filter_by(id=int(val.sku[3:])).first()
504
                if d_item is None:
505
                    raise 
506
                else:
12430 kshitij.so 507
                    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 508
                if vatMaster is None:
12418 kshitij.so 509
                    raise
12419 kshitij.so 510
                else:
511
                    val.vatRate = vatMaster.vatPercent
512
                    print "vat fetched"
12418 kshitij.so 513
            else:
514
                val.vatRate = itemVatMaster.vatPercentage
12419 kshitij.so 515
                print "vat fetched"
12363 kshitij.so 516
        except:
12414 kshitij.so 517
            print "vat exception"
12363 kshitij.so 518
            temp = []
519
            temp.append(val)
520
            temp.append("Vat not available")
521
            exceptionList.append(temp)
522
            continue
523
 
524
        lowestPossibleSp = getLowestPossibleSp(amDetails,val,val.sourcePercentage)
12408 kshitij.so 525
        print "Creating pricing obj"
12432 kshitij.so 526
        amPricing = __AmazonPricing(ourSp,lowestPossibleSp)
12363 kshitij.so 527
 
12467 kshitij.so 528
        if amDetails.promoPrice < amPricing.lowestPossibleSp:
12363 kshitij.so 529
            temp = []
530
            temp.append(val)
531
            temp.append(amDetails)
532
            temp.append(amPricing)
533
            negativeMargin.append(temp)
534
            continue
535
 
536
        if amDetails.ourRank==1:
537
            temp = []
538
            temp.append(val)
539
            temp.append(amDetails)
540
            temp.append(amPricing)
541
            cheapest.append(temp)
542
            continue
543
 
12469 kshitij.so 544
        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 545
            temp = []
546
            temp.append(val)
547
            temp.append(amDetails)
548
            temp.append(amPricing)
549
            amongCheapestAndCanCompete.append(temp)
550
            continue
551
 
552
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp):
553
            temp = []
554
            temp.append(val)
555
            temp.append(amDetails)
556
            temp.append(amPricing)
557
            canCompete.append(temp)
558
            continue
559
 
12403 kshitij.so 560
        if amDetails.lowestSellerSp*(1+.01) >= amPricing.lowestPossibleSp:
12396 kshitij.so 561
            temp = []
562
            temp.append(val)
563
            temp.append(amDetails)
564
            temp.append(amPricing)
565
            almostCompete.append(temp)
566
            continue
567
 
568
 
12363 kshitij.so 569
        temp = []
570
        temp.append(val)
571
        temp.append(amDetails)
572
        temp.append(amPricing)
573
        cantCompete.append(temp)
12414 kshitij.so 574
    print "Created category..."
12363 kshitij.so 575
 
576
    return exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete
12396 kshitij.so 577
 
12363 kshitij.so 578
 
579
def getLowestPossibleSp(amazonDetails,val,spm):
12447 kshitij.so 580
    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 581
    if val.isPromo:
582
        if amazonLongTermActivePromotions.has_key(val.sku):
12466 kshitij.so 583
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
12432 kshitij.so 584
        else:
12466 kshitij.so 585
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
12432 kshitij.so 586
        lowestPossibleSp = lowestPossibleSp - subsidy
12363 kshitij.so 587
    return round(lowestPossibleSp,2)
588
 
589
def getTargetTp(targetSp,spm,val):
12424 kshitij.so 590
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))
12363 kshitij.so 591
    return round(targetTp,2)
592
 
593
def commitExceptionList(exceptionList,timestamp,runType):
594
    for exceptionItem in exceptionList:
595
        val = exceptionItem[0]
596
        reason = exceptionItem[1]
597
        amazonScrapingHistory = AmazonScrapingHistory()
598
        amazonScrapingHistory.item_id = val.sku[3:]
599
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 600
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 601
        amazonScrapingHistory.reason = reason
602
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
603
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.EXCEPTION
604
        amazonScrapingHistory.timestamp = timestamp
605
    session.commit()
606
 
607
def commitNegativeMargin(negativeMargin,timestamp,runType):
608
    for negativeMarginItem in negativeMargin:
609
        val = negativeMarginItem[0]
610
        amDetails = negativeMarginItem[1]
611
        amPricing = negativeMarginItem[2]
612
        spm = val.sourcePercentage
613
        amazonScrapingHistory = AmazonScrapingHistory()
614
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 615
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 616
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 617
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 618
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 619
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 620
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
621
        amazonScrapingHistory.ourRank = amDetails.ourRank
622
        amazonScrapingHistory.ourInventory = val.ourInventory
623
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12468 kshitij.so 624
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
625
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
626
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 627
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 628
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
629
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
630
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 631
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 632
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
633
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
634
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12363 kshitij.so 635
        amazonScrapingHistory.wanlc = val.nlc
12447 kshitij.so 636
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 637
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 638
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 639
        amazonScrapingHistory.returnProvision = spm.returnProvision
640
        amazonScrapingHistory.courierCost = val.courierCost
641
        amazonScrapingHistory.risky = val.risky
642
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
643
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
644
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
645
        amazonScrapingHistory.timestamp = timestamp
646
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
647
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 648
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 649
    session.commit()
650
 
651
 
652
def commitCheapest(cheapest,timestamp,runType):
653
    for cheapestItem in cheapest:
654
        val = cheapestItem[0]
655
        amDetails = cheapestItem[1]
656
        amPricing = cheapestItem[2]
657
        spm = val.sourcePercentage
658
        amazonScrapingHistory = AmazonScrapingHistory()
659
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 660
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 661
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 662
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 663
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 664
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 665
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
666
        amazonScrapingHistory.ourRank = amDetails.ourRank
667
        amazonScrapingHistory.ourInventory = val.ourInventory
668
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 669
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
670
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
671
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 672
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 673
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
674
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
675
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 676
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 677
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
678
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
679
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 680
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 681
        amazonScrapingHistory.wanlc = val.nlc
682
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 683
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 684
        amazonScrapingHistory.returnProvision = spm.returnProvision
685
        amazonScrapingHistory.courierCost = val.courierCost
686
        amazonScrapingHistory.risky = val.risky
687
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
688
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
689
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.BUY_BOX
690
        amazonScrapingHistory.timestamp = timestamp
691
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12430 kshitij.so 692
        proposed_sp = max(amDetails.secondLowestSellerSp - max((20, amDetails.secondLowestSellerSp*0.002)), amPricing.lowestPossibleSp)
12433 kshitij.so 693
        if amazonScrapingHistory.isPromotion:
694
            if amazonLongTermActivePromotions.has_key(val.sku):
12466 kshitij.so 695
                proposed_sp = min(proposed_sp,(amazonLongTermActivePromotions.get(val.sku)).salePrice)
12433 kshitij.so 696
            else:
12466 kshitij.so 697
                proposed_sp = min(proposed_sp,(amazonShortTermActivePromotions.get(val.sku)).salePrice)
12468 kshitij.so 698
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 699
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 700
        #amazonScrapingHistory.proposedTp = proposed_tp
701
        #amazonScrapingHistory.marginIncreasedPotential = proposed_tp - amPricing.ourTp
12363 kshitij.so 702
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
703
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 704
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 705
    session.commit()
706
 
707
 
708
 
709
def commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,runType):
710
    for amongCheapestAndCanCompeteItem in amongCheapestAndCanCompete:
711
        val = amongCheapestAndCanCompeteItem[0]
712
        amDetails = amongCheapestAndCanCompeteItem[1]
713
        amPricing = amongCheapestAndCanCompeteItem[2]
714
        spm = val.sourcePercentage
715
        amazonScrapingHistory = AmazonScrapingHistory()
716
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 717
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 718
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 719
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 720
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 721
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 722
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
723
        amazonScrapingHistory.ourRank = amDetails.ourRank
724
        amazonScrapingHistory.ourInventory = val.ourInventory
725
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 726
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
727
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
728
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 729
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 730
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
731
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
732
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12470 kshitij.so 733
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 734
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
735
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
736
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 737
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 738
        amazonScrapingHistory.wanlc = val.nlc
739
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 740
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 741
        amazonScrapingHistory.returnProvision = spm.returnProvision
742
        amazonScrapingHistory.courierCost = val.courierCost
743
        amazonScrapingHistory.risky = val.risky
744
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
745
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
746
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE
747
        amazonScrapingHistory.timestamp = timestamp
748
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
749
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
12468 kshitij.so 750
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 751
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 752
        #amazonScrapingHistory.proposedTp = proposed_tp
12363 kshitij.so 753
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
754
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 755
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 756
    session.commit()
757
 
758
def commitCanCompete(canCompete,timestamp,runType):
759
    for canCompeteItem in canCompete:
760
        val = canCompeteItem[0]
761
        amDetails = canCompeteItem[1]
762
        amPricing = canCompeteItem[2]
763
        spm = val.sourcePercentage
764
        amazonScrapingHistory = AmazonScrapingHistory()
765
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 766
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 767
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 768
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 769
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 770
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 771
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
772
        amazonScrapingHistory.ourRank = amDetails.ourRank
773
        amazonScrapingHistory.ourInventory = val.ourInventory
774
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 775
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
776
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
777
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 778
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 779
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
780
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
781
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 782
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 783
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
784
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
785
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 786
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 787
        amazonScrapingHistory.wanlc = val.nlc
788
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 789
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 790
        amazonScrapingHistory.returnProvision = spm.returnProvision
791
        amazonScrapingHistory.courierCost = val.courierCost
792
        amazonScrapingHistory.risky = val.risky
793
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
794
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
795
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
796
        amazonScrapingHistory.timestamp = timestamp
797
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
798
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
12468 kshitij.so 799
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 800
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 801
        #amazonScrapingHistory.proposedTp = proposed_tp
12363 kshitij.so 802
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
803
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 804
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 805
    session.commit()
806
 
12383 kshitij.so 807
def commitAlmostCompete(almostCompete,timestamp,runType):
12396 kshitij.so 808
    for almostCompeteItem in almostCompete:
809
        val = almostCompeteItem[0]
810
        amDetails = almostCompeteItem[1]
811
        amPricing = almostCompeteItem[2]
812
        spm = val.sourcePercentage
813
        amazonScrapingHistory = AmazonScrapingHistory()
814
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 815
        amazonScrapingHistory.asin = val.asin
12396 kshitij.so 816
        amazonScrapingHistory.warehouseLocation = val.state_id
817
        amazonScrapingHistory.parentCategoryId = val.parent_category
818
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 819
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12396 kshitij.so 820
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
821
        amazonScrapingHistory.ourRank = amDetails.ourRank
822
        amazonScrapingHistory.ourInventory = val.ourInventory
823
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 824
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
825
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
826
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12396 kshitij.so 827
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 828
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
829
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
830
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12396 kshitij.so 831
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 832
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
833
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
834
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 835
        amazonScrapingHistory.otherCost = val.otherCost
12396 kshitij.so 836
        amazonScrapingHistory.wanlc = val.nlc
837
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 838
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12396 kshitij.so 839
        amazonScrapingHistory.returnProvision = spm.returnProvision
840
        amazonScrapingHistory.courierCost = val.courierCost
841
        amazonScrapingHistory.risky = val.risky
842
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
843
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
844
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.ALMOST_COMPETE
845
        amazonScrapingHistory.timestamp = timestamp
846
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12425 kshitij.so 847
        proposed_sp = min(amDetails.lowestSellerSp*(1+.01),amPricing.lowestPossibleSp)
12468 kshitij.so 848
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
849
        #target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
12396 kshitij.so 850
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 851
        #amazonScrapingHistory.proposedTp = proposed_tp
852
        #amazonScrapingHistory.targetNlc = target_nlc
12396 kshitij.so 853
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
854
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 855
        amazonScrapingHistory.isPromotion = val.isPromo
12396 kshitij.so 856
    session.commit()
12363 kshitij.so 857
 
12396 kshitij.so 858
 
12363 kshitij.so 859
def commitCantCompete(cantCompete, timestamp,runType):
860
    for cantCompeteItem in cantCompete:
861
        val = cantCompeteItem[0]
862
        amDetails = cantCompeteItem[1]
863
        amPricing = cantCompeteItem[2]
864
        spm = val.sourcePercentage
865
        amazonScrapingHistory = AmazonScrapingHistory()
866
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 867
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 868
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 869
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 870
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 871
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 872
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
873
        amazonScrapingHistory.ourRank = amDetails.ourRank
874
        amazonScrapingHistory.ourInventory = val.ourInventory
875
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 876
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
877
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
878
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 879
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 880
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
881
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
882
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 883
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 884
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
885
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
886
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 887
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 888
        amazonScrapingHistory.wanlc = val.nlc
889
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 890
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 891
        amazonScrapingHistory.returnProvision = spm.returnProvision
892
        amazonScrapingHistory.courierCost = val.courierCost
893
        amazonScrapingHistory.risky = val.risky
894
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
895
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
896
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
897
        amazonScrapingHistory.timestamp = timestamp
898
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
899
        proposed_sp = amDetails.lowestSellerSp - max(5, amDetails.lowestSellerSp*0.001)
12468 kshitij.so 900
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
901
        #target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
12363 kshitij.so 902
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 903
        #amazonScrapingHistory.proposedTp = proposed_tp
904
        #amazonScrapingHistory.targetNlc = target_nlc
12363 kshitij.so 905
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
906
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 907
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 908
    session.commit()
909
 
12396 kshitij.so 910
def markAutoFavourites(time):
911
    nowAutoFav = []
912
    previouslyAutoFav = []
913
    stockList = []
914
    saleList = []
915
    items = session.query(func.sum(AmazonScrapingHistory.ourInventory),AmazonScrapingHistory.item_id).group_by(AmazonScrapingHistory.item_id).all()
916
    allItems = session.query(Amazonlisted).all()
917
    for item in items:
918
        reason = ""
919
        if item[0]>=5:
920
            stockList.append(item[1])
921
 
922
    for sku, val in saleMap.iteritems():
923
        totalSale = 0
924
        item_id = sku.replace('FBA','').replace('FBB','')
925
        val =saleMap.get('FBA'+str(item_id))
926
        if val is not None:
927
            for sale in val:
928
                totalSale += sale.totalOrderCount
929
        val =saleMap.get('FBB'+str(item_id))
930
        if val is not None:
931
            for sale in val:
932
                totalSale += sale.totalOrderCount
933
        if totalSale > 0:
934
            saleList.append(item_id)
935
 
936
    for aItem in allItems:
937
        reason = ""
938
        toMark = False
939
        if aItem.itemId in saleList:
940
            toMark = True
941
            reason+="Total FC sale is greater than 1 for last five days.."
942
        if aItem.itemId in stockList:
943
            toMark = True
944
            reason+="Item is present in buy box in last 3 days"
945
        if not aItem.autoFavourite:
946
            print "Item is not under auto favourite"
947
        if toMark:
948
            temp=[]
949
            temp.append(aItem.itemId)
950
            temp.append(reason)
951
            nowAutoFav.append(temp)
952
        if (not toMark) and aItem.autoFavourite:
953
            previouslyAutoFav.append(aItem.itemId)
954
        aItem.autoFavourite = toMark
955
    session.commit()
956
    return previouslyAutoFav, nowAutoFav
957
 
12444 kshitij.so 958
def writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,runType):
12396 kshitij.so 959
    wbk = xlwt.Workbook()
960
    sheet = wbk.add_sheet('Can\'t Compete')
961
    xstr = lambda s: s or ""
962
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
963
 
964
    excel_integer_format = '0'
965
    integer_style = xlwt.XFStyle()
966
    integer_style.num_format_str = excel_integer_format
967
 
968
    sheet.write(0, 0, "Item Id", heading_xf)
969
    sheet.write(0, 1, "Amazon Sku", heading_xf)
970
    sheet.write(0, 2, "Asin", heading_xf)
971
    sheet.write(0, 3, "Location", heading_xf)
972
    sheet.write(0, 4, "Brand", heading_xf)
973
    sheet.write(0, 5, "Product Name", heading_xf)
974
    sheet.write(0, 6, "Weight", heading_xf)
975
    sheet.write(0, 7, "Courier Cost", heading_xf)
976
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 977
    sheet.write(0, 9, "Promo Price", heading_xf)
978
    sheet.write(0, 10, "Is Promotion", heading_xf)
979
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 980
    sheet.write(0, 12, "Rank", heading_xf)
981
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 982
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
983
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
984
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 985
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 986
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
987
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
988
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
989
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
990
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 991
    sheet.write(0, 23, "Other Cost", heading_xf)
992
    sheet.write(0, 24, "WANLC", heading_xf)
993
    sheet.write(0, 25, "Commission", heading_xf)
994
    sheet.write(0, 26, "Competitor Commission", heading_xf)
995
    sheet.write(0, 27, "Return Provision", heading_xf)
996
    sheet.write(0, 28, "Margin", heading_xf)
997
    sheet.write(0, 29, "Risky", heading_xf)
998
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 999
    sheet.write(0, 31, "Avg Sale", heading_xf)
1000
    sheet.write(0, 32, "Sales History", heading_xf)
1001
    sheet.write(0, 33, "Decision", heading_xf)
1002
    sheet.write(0, 34, "Reason", heading_xf)
1003
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1004
 
1005
    sheet_iterator = 1
12476 kshitij.so 1006
    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 1007
    for cantCompeteItem in cantCompeteItems:
1008
        amScraping =  cantCompeteItem[0]
1009
        item = cantCompeteItem[1]
1010
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1011
        if amScraping.warehouseLocation == 1:
1012
            sku = 'FBA'+str(amScraping.item_id)
1013
            loc = 'MUMBAI'
1014
        else:
1015
            sku = 'FBB'+str(amScraping.item_id)
1016
            loc = 'BANGLORE'
1017
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1018
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1019
        sheet.write(sheet_iterator, 3, loc)
1020
        sheet.write(sheet_iterator, 4, item.brand)
1021
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1022
        sheet.write(sheet_iterator, 6, item.weight)
1023
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1024
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1025
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1026
        if amScraping.isPromotion:
1027
            sheet.write(sheet_iterator, 10, "Yes")
1028
        else:
1029
            sheet.write(sheet_iterator, 10, "Yes")
1030
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1031
        if amScraping.ourRank > 3:
1032
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1033
        else:
1034
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1035
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1036
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1037
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1038
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1039
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1040
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1041
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1042
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1043
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1044
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1045
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1046
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1047
        sheet.write(sheet_iterator, 25, amScraping.commission)
1048
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1049
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1050
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1051
        sheet.write(sheet_iterator, 29, item.risky)
1052
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1053
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1054
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1055
        if amScraping.decision is None:
12468 kshitij.so 1056
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1057
            sheet_iterator+=1
1058
            continue
12468 kshitij.so 1059
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1060
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1061
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1062
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1063
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1064
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1065
        sheet_iterator+=1
1066
 
1067
    sheet = wbk.add_sheet('Competitive')
1068
    xstr = lambda s: s or ""
1069
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1070
 
1071
    excel_integer_format = '0'
1072
    integer_style = xlwt.XFStyle()
1073
    integer_style.num_format_str = excel_integer_format
1074
 
1075
    sheet.write(0, 0, "Item Id", heading_xf)
1076
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1077
    sheet.write(0, 2, "Asin", heading_xf)
1078
    sheet.write(0, 3, "Location", heading_xf)
1079
    sheet.write(0, 4, "Brand", heading_xf)
1080
    sheet.write(0, 5, "Product Name", heading_xf)
1081
    sheet.write(0, 6, "Weight", heading_xf)
1082
    sheet.write(0, 7, "Courier Cost", heading_xf)
1083
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1084
    sheet.write(0, 9, "Promo Price", heading_xf)
1085
    sheet.write(0, 10, "Is Promotion", heading_xf)
1086
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1087
    sheet.write(0, 12, "Rank", heading_xf)
1088
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1089
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1090
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1091
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1092
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1093
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1094
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1095
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1096
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1097
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1098
    sheet.write(0, 23, "Other Cost", heading_xf)
1099
    sheet.write(0, 24, "WANLC", heading_xf)
1100
    sheet.write(0, 25, "Commission", heading_xf)
1101
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1102
    sheet.write(0, 27, "Return Provision", heading_xf)
1103
    sheet.write(0, 28, "Margin", heading_xf)
1104
    sheet.write(0, 29, "Risky", heading_xf)
1105
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1106
    sheet.write(0, 31, "Avg Sale", heading_xf)
1107
    sheet.write(0, 32, "Sales History", heading_xf)
1108
    sheet.write(0, 33, "Decision", heading_xf)
1109
    sheet.write(0, 34, "Reason", heading_xf)
1110
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1111
 
1112
    sheet_iterator = 1
12476 kshitij.so 1113
    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 1114
    for competitiveItem in competitiveItems:
1115
        amScraping =  competitiveItem[0]
1116
        item = competitiveItem[1]
1117
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1118
        if amScraping.warehouseLocation == 1:
1119
            sku = 'FBA'+str(amScraping.item_id)
1120
            loc = 'MUMBAI'
1121
        else:
1122
            sku = 'FBB'+str(amScraping.item_id)
1123
            loc = 'BANGLORE'
1124
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1125
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1126
        sheet.write(sheet_iterator, 3, loc)
1127
        sheet.write(sheet_iterator, 4, item.brand)
1128
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1129
        sheet.write(sheet_iterator, 6, item.weight)
1130
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1131
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1132
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1133
        if amScraping.isPromotion:
1134
            sheet.write(sheet_iterator, 10, "Yes")
1135
        else:
1136
            sheet.write(sheet_iterator, 10, "Yes")
1137
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1138
        if amScraping.ourRank > 3:
1139
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1140
        else:
1141
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1142
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1143
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1144
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1145
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1146
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1147
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1148
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1149
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1150
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1151
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1152
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1153
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1154
        sheet.write(sheet_iterator, 25, amScraping.commission)
1155
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1156
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1157
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1158
        sheet.write(sheet_iterator, 29, item.risky)
1159
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1160
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1161
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1162
        if amScraping.decision is None:
12468 kshitij.so 1163
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1164
            sheet_iterator+=1
1165
            continue
12468 kshitij.so 1166
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1167
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1168
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1169
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1170
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1171
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1172
        sheet_iterator+=1
1173
 
1174
    sheet = wbk.add_sheet('Almost Competitive')
1175
    xstr = lambda s: s or ""
1176
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1177
 
1178
    excel_integer_format = '0'
1179
    integer_style = xlwt.XFStyle()
1180
    integer_style.num_format_str = excel_integer_format
1181
 
1182
    sheet.write(0, 0, "Item Id", heading_xf)
1183
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1184
    sheet.write(0, 2, "Asin", heading_xf)
1185
    sheet.write(0, 3, "Location", heading_xf)
1186
    sheet.write(0, 4, "Brand", heading_xf)
1187
    sheet.write(0, 5, "Product Name", heading_xf)
1188
    sheet.write(0, 6, "Weight", heading_xf)
1189
    sheet.write(0, 7, "Courier Cost", heading_xf)
1190
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1191
    sheet.write(0, 9, "Promo Price", heading_xf)
1192
    sheet.write(0, 10, "Is Promotion", heading_xf)
1193
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1194
    sheet.write(0, 12, "Rank", heading_xf)
1195
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1196
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1197
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1198
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1199
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1200
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1201
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1202
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1203
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1204
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1205
    sheet.write(0, 23, "Other Cost", heading_xf)
1206
    sheet.write(0, 24, "WANLC", heading_xf)
1207
    sheet.write(0, 25, "Commission", heading_xf)
1208
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1209
    sheet.write(0, 27, "Return Provision", heading_xf)
1210
    sheet.write(0, 28, "Margin", heading_xf)
1211
    sheet.write(0, 29, "Risky", heading_xf)
1212
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1213
    sheet.write(0, 31, "Avg Sale", heading_xf)
1214
    sheet.write(0, 32, "Sales History", heading_xf)
1215
    sheet.write(0, 33, "Decision", heading_xf)
1216
    sheet.write(0, 34, "Reason", heading_xf)
1217
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1218
 
1219
    sheet_iterator = 1
12476 kshitij.so 1220
    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 1221
    for almostCompetitiveItem in almostCompetitiveItems:
1222
        amScraping =  almostCompetitiveItem[0]
1223
        item = almostCompetitiveItem[1]
1224
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1225
        if amScraping.warehouseLocation == 1:
1226
            sku = 'FBA'+str(amScraping.item_id)
1227
            loc = 'MUMBAI'
1228
        else:
1229
            sku = 'FBB'+str(amScraping.item_id)
1230
            loc = 'BANGLORE'
12432 kshitij.so 1231
        amScraping =  competitiveItem[0]
1232
        item = competitiveItem[1]
1233
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1234
        if amScraping.warehouseLocation == 1:
1235
            sku = 'FBA'+str(amScraping.item_id)
1236
            loc = 'MUMBAI'
1237
        else:
1238
            sku = 'FBB'+str(amScraping.item_id)
1239
            loc = 'BANGLORE'
12396 kshitij.so 1240
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1241
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1242
        sheet.write(sheet_iterator, 3, loc)
1243
        sheet.write(sheet_iterator, 4, item.brand)
1244
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1245
        sheet.write(sheet_iterator, 6, item.weight)
1246
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1247
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1248
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1249
        if amScraping.isPromotion:
1250
            sheet.write(sheet_iterator, 10, "Yes")
1251
        else:
1252
            sheet.write(sheet_iterator, 10, "Yes")
1253
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1254
        if amScraping.ourRank > 3:
1255
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1256
        else:
1257
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1258
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1259
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1260
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1261
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1262
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1263
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1264
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1265
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1266
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1267
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1268
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1269
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1270
        sheet.write(sheet_iterator, 25, amScraping.commission)
1271
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1272
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1273
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1274
        sheet.write(sheet_iterator, 29, item.risky)
1275
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1276
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1277
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1278
        if amScraping.decision is None:
12468 kshitij.so 1279
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1280
            sheet_iterator+=1
1281
            continue
12468 kshitij.so 1282
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1283
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1284
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1285
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1286
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1287
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1288
        sheet_iterator+=1
1289
 
1290
    sheet = wbk.add_sheet('Among Cheapest')
1291
    xstr = lambda s: s or ""
1292
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1293
 
1294
    excel_integer_format = '0'
1295
    integer_style = xlwt.XFStyle()
1296
    integer_style.num_format_str = excel_integer_format
1297
 
1298
    sheet.write(0, 0, "Item Id", heading_xf)
1299
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1300
    sheet.write(0, 2, "Asin", heading_xf)
1301
    sheet.write(0, 3, "Location", heading_xf)
1302
    sheet.write(0, 4, "Brand", heading_xf)
1303
    sheet.write(0, 5, "Product Name", heading_xf)
1304
    sheet.write(0, 6, "Weight", heading_xf)
1305
    sheet.write(0, 7, "Courier Cost", heading_xf)
1306
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1307
    sheet.write(0, 9, "Promo Price", heading_xf)
1308
    sheet.write(0, 10, "Is Promotion", heading_xf)
1309
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1310
    sheet.write(0, 12, "Rank", heading_xf)
1311
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1312
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1313
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1314
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1315
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1316
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1317
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1318
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1319
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1320
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1321
    sheet.write(0, 23, "Other Cost", heading_xf)
1322
    sheet.write(0, 24, "WANLC", heading_xf)
1323
    sheet.write(0, 25, "Commission", heading_xf)
1324
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1325
    sheet.write(0, 27, "Return Provision", heading_xf)
1326
    sheet.write(0, 28, "Margin", heading_xf)
1327
    sheet.write(0, 29, "Risky", heading_xf)
1328
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1329
    sheet.write(0, 31, "Avg Sale", heading_xf)
1330
    sheet.write(0, 32, "Sales History", heading_xf)
1331
    sheet.write(0, 33, "Decision", heading_xf)
1332
    sheet.write(0, 34, "Reason", heading_xf)
1333
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1334
 
1335
    sheet_iterator = 1
12476 kshitij.so 1336
    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 1337
    for amongCheapestItem in amongCheapestItems:
1338
        amScraping =  amongCheapestItem[0]
1339
        item = amongCheapestItem[1]
1340
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1341
        if amScraping.warehouseLocation == 1:
1342
            sku = 'FBA'+str(amScraping.item_id)
1343
            loc = 'MUMBAI'
1344
        else:
1345
            sku = 'FBB'+str(amScraping.item_id)
1346
            loc = 'BANGLORE'
1347
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1348
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1349
        sheet.write(sheet_iterator, 3, loc)
1350
        sheet.write(sheet_iterator, 4, item.brand)
1351
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1352
        sheet.write(sheet_iterator, 6, item.weight)
1353
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1354
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1355
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1356
        if amScraping.isPromotion:
1357
            sheet.write(sheet_iterator, 10, "Yes")
1358
        else:
1359
            sheet.write(sheet_iterator, 10, "Yes")
1360
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1361
        if amScraping.ourRank > 3:
1362
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1363
        else:
1364
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1365
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1366
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1367
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1368
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1369
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1370
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1371
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1372
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1373
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1374
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1375
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1376
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1377
        sheet.write(sheet_iterator, 25, amScraping.commission)
1378
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1379
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1380
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1381
        sheet.write(sheet_iterator, 29, item.risky)
1382
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1383
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1384
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1385
        if amScraping.decision is None:
12468 kshitij.so 1386
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1387
            sheet_iterator+=1
1388
            continue
12468 kshitij.so 1389
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1390
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1391
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1392
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1393
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1394
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1395
        sheet_iterator+=1
1396
 
1397
    sheet = wbk.add_sheet('Cheapest')
1398
    xstr = lambda s: s or ""
1399
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1400
 
1401
    excel_integer_format = '0'
1402
    integer_style = xlwt.XFStyle()
1403
    integer_style.num_format_str = excel_integer_format
1404
 
1405
    sheet.write(0, 0, "Item Id", heading_xf)
1406
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1407
    sheet.write(0, 2, "Asin", heading_xf)
1408
    sheet.write(0, 3, "Location", heading_xf)
1409
    sheet.write(0, 4, "Brand", heading_xf)
1410
    sheet.write(0, 5, "Product Name", heading_xf)
1411
    sheet.write(0, 6, "Weight", heading_xf)
1412
    sheet.write(0, 7, "Courier Cost", heading_xf)
1413
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1414
    sheet.write(0, 9, "Promo Price", heading_xf)
1415
    sheet.write(0, 10, "Is Promotion", heading_xf)
1416
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1417
    sheet.write(0, 12, "Rank", heading_xf)
1418
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1419
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1420
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1421
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1422
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1423
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1424
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1425
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1426
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1427
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1428
    sheet.write(0, 23, "Other Cost", heading_xf)
1429
    sheet.write(0, 24, "WANLC", heading_xf)
1430
    sheet.write(0, 25, "Commission", heading_xf)
1431
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1432
    sheet.write(0, 27, "Return Provision", heading_xf)
1433
    sheet.write(0, 28, "Margin", heading_xf)
1434
    sheet.write(0, 29, "Risky", heading_xf)
1435
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1436
    sheet.write(0, 31, "Avg Sale", heading_xf)
1437
    sheet.write(0, 32, "Sales History", heading_xf)
1438
    sheet.write(0, 33, "Decision", heading_xf)
1439
    sheet.write(0, 34, "Reason", heading_xf)
1440
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1441
 
1442
    sheet_iterator = 1
12476 kshitij.so 1443
    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 1444
    for cheapestItem in cheapestItems:
1445
        amScraping =  cheapestItem[0]
1446
        item = cheapestItem[1]
1447
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1448
        if amScraping.warehouseLocation == 1:
1449
            sku = 'FBA'+str(amScraping.item_id)
1450
            loc = 'MUMBAI'
1451
        else:
1452
            sku = 'FBB'+str(amScraping.item_id)
1453
            loc = 'BANGLORE'
1454
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1455
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1456
        sheet.write(sheet_iterator, 3, loc)
1457
        sheet.write(sheet_iterator, 4, item.brand)
1458
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1459
        sheet.write(sheet_iterator, 6, item.weight)
1460
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1461
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1462
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1463
        if amScraping.isPromotion:
1464
            sheet.write(sheet_iterator, 10, "Yes")
1465
        else:
1466
            sheet.write(sheet_iterator, 10, "Yes")
1467
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1468
        if amScraping.ourRank > 3:
1469
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1470
        else:
1471
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1472
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1473
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1474
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1475
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1476
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1477
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1478
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1479
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1480
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1481
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1482
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1483
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1484
        sheet.write(sheet_iterator, 25, amScraping.commission)
1485
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1486
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1487
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1488
        sheet.write(sheet_iterator, 29, item.risky)
1489
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1490
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1491
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1492
        if amScraping.decision is None:
12468 kshitij.so 1493
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1494
            sheet_iterator+=1
1495
            continue
12468 kshitij.so 1496
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1497
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1498
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1499
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1500
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1501
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1502
        sheet_iterator+=1
1503
 
1504
    sheet = wbk.add_sheet('Negative Margin')
1505
    xstr = lambda s: s or ""
1506
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1507
 
1508
    excel_integer_format = '0'
1509
    integer_style = xlwt.XFStyle()
1510
    integer_style.num_format_str = excel_integer_format
1511
 
1512
    sheet.write(0, 0, "Item Id", heading_xf)
1513
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1514
    sheet.write(0, 2, "Asin", heading_xf)
1515
    sheet.write(0, 3, "Location", heading_xf)
1516
    sheet.write(0, 4, "Brand", heading_xf)
1517
    sheet.write(0, 5, "Product Name", heading_xf)
1518
    sheet.write(0, 6, "Weight", heading_xf)
1519
    sheet.write(0, 7, "Courier Cost", heading_xf)
1520
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1521
    sheet.write(0, 9, "Promo Price", heading_xf)
1522
    sheet.write(0, 10, "Is Promotion", heading_xf)
1523
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1524
    sheet.write(0, 12, "Rank", heading_xf)
1525
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1526
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1527
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1528
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1529
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1530
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1531
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1532
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1533
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1534
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1535
    sheet.write(0, 23, "Other Cost", heading_xf)
1536
    sheet.write(0, 24, "WANLC", heading_xf)
1537
    sheet.write(0, 25, "Commission", heading_xf)
1538
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1539
    sheet.write(0, 27, "Return Provision", heading_xf)
1540
    sheet.write(0, 28, "Margin", heading_xf)
1541
    sheet.write(0, 29, "Avg Sale", heading_xf)
1542
    sheet.write(0, 30, "Sales History", heading_xf)
12396 kshitij.so 1543
 
1544
    sheet_iterator = 1
12476 kshitij.so 1545
    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 1546
    for amongCheapestItem in amongCheapestItems:
1547
        amScraping =  amongCheapestItem[0]
1548
        item = amongCheapestItem[1]
1549
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1550
        if amScraping.warehouseLocation == 1:
1551
            sku = 'FBA'+str(amScraping.item_id)
1552
            loc = 'MUMBAI'
1553
        else:
1554
            sku = 'FBB'+str(amScraping.item_id)
1555
            loc = 'BANGLORE'
1556
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1557
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1558
        sheet.write(sheet_iterator, 3, loc)
1559
        sheet.write(sheet_iterator, 4, item.brand)
1560
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1561
        sheet.write(sheet_iterator, 6, item.weight)
1562
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1563
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1564
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1565
        if amScraping.isPromotion:
1566
            sheet.write(sheet_iterator, 10, "Yes")
1567
        else:
1568
            sheet.write(sheet_iterator, 10, "Yes")
1569
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1570
        if amScraping.ourRank > 3:
1571
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1572
        else:
1573
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1574
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1575
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1576
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1577
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1578
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1579
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1580
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1581
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1582
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1583
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1584
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1585
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1586
        sheet.write(sheet_iterator, 25, amScraping.commission)
1587
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1588
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
12468 kshitij.so 1589
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
12447 kshitij.so 1590
        sheet.write(sheet_iterator, 29, amScraping.avgSale)
1591
        sheet.write(sheet_iterator, 30, getOosString(saleMap.get(sku)))
12396 kshitij.so 1592
        sheet_iterator+=1
1593
 
1594
    sheet = wbk.add_sheet('Exception List')
1595
    xstr = lambda s: s or ""
1596
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1597
 
1598
    excel_integer_format = '0'
1599
    integer_style = xlwt.XFStyle()
1600
    integer_style.num_format_str = excel_integer_format
1601
 
1602
    sheet.write(0, 0, "Item Id", heading_xf)
1603
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1604
    sheet.write(0, 2, "Asin", heading_xf)
1605
    sheet.write(0, 3, "Location", heading_xf)
1606
    sheet.write(0, 4, "Brand", heading_xf)
1607
    sheet.write(0, 5, "Product Name", heading_xf)
1608
    sheet.write(0, 6, "Reason", heading_xf)
1609
 
1610
    sheet_iterator = 1
12476 kshitij.so 1611
    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 1612
    for amongCheapestItem in amongCheapestItems:
1613
        amScraping =  amongCheapestItem[0]
1614
        item = amongCheapestItem[1]
1615
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1616
        if amScraping.warehouseLocation == 1:
1617
            sku = 'FBA'+str(amScraping.item_id)
1618
            loc = 'MUMBAI'
1619
        else:
1620
            sku = 'FBB'+str(amScraping.item_id)
1621
            loc = 'BANGLORE'
1622
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1623
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1624
        sheet.write(sheet_iterator, 3, loc)
1625
        sheet.write(sheet_iterator, 4, item.brand)
1626
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1627
        sheet.write(sheet_iterator, 6, amScraping.reason)
1628
        sheet_iterator+=1      
1629
 
12444 kshitij.so 1630
 
1631
    if (runType=='FULL'):    
1632
        sheet = wbk.add_sheet('Auto Favorites')
1633
 
1634
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1635
 
1636
        excel_integer_format = '0'
1637
        integer_style = xlwt.XFStyle()
1638
        integer_style.num_format_str = excel_integer_format
1639
        xstr = lambda s: s or ""
1640
 
1641
        sheet.write(0, 0, "Item ID", heading_xf)
1642
        sheet.write(0, 1, "Brand", heading_xf)
1643
        sheet.write(0, 2, "Product Name", heading_xf)
1644
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1645
        sheet.write(0, 4, "Reason", heading_xf)
1646
 
1647
        sheet_iterator=1
1648
        for autoFav in nowAutoFav:
1649
            itemId = autoFav[0]
1650
            reason = autoFav[1]
1651
            it = Item.query.filter_by(id=itemId).one()
1652
            sheet.write(sheet_iterator, 0, itemId)
1653
            sheet.write(sheet_iterator, 1, it.brand)
1654
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1655
            sheet.write(sheet_iterator, 3, "True")
1656
            sheet.write(sheet_iterator, 4, reason)
1657
            sheet_iterator+=1
1658
        for prevFav in previousAutoFav:
1659
            it = Item.query.filter_by(id=prevFav).one()
1660
            sheet.write(sheet_iterator, 0, prevFav)
1661
            sheet.write(sheet_iterator, 1, it.brand)
1662
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1663
            sheet.write(sheet_iterator, 3, "False")
1664
            sheet_iterator+=1
1665
 
12478 kshitij.so 1666
    filename = "/tmp/amazon-report-"+runType+" " + str(timestamp) + ".xls"
12396 kshitij.so 1667
    wbk.save(filename)
1668
 
12363 kshitij.so 1669
def main():
1670
    parser = optparse.OptionParser()
1671
    parser.add_option("-t", "--type", dest="runType",
1672
                   default="FULL", type="string",
1673
                   help="Run type FULL or FAVOURITE")
1674
    (options, args) = parser.parse_args()
1675
    if options.runType not in ('FULL','FAVOURITE'):
1676
        print "Run type argument illegal."
1677
        sys.exit(1)
1678
    time.sleep(5)
1679
    timestamp = datetime.now()
1680
    fetchFbaSale()
1681
    itemInfo = populateStuff(timestamp,options.runType)
1682
    itemsToPopulate = 0
12430 kshitij.so 1683
    toSync = 0
1684
    lenItems = len(itemInfo)
1685
    while(toSync < lenItems):
1686
        oldSync = toSync
1687
        if lenItems >= 20:
1688
            toSync = 20
1689
        else:
1690
            toSync = lenItems - oldSync
1691
        getPriceAndAsin(itemInfo[oldSync:toSync+oldSync])
1692
        toSync = oldSync + toSync
1693
 
12363 kshitij.so 1694
    while (len(itemInfo)>0):
12430 kshitij.so 1695
        if len(itemInfo) >= 20:
1696
            itemsToPopulate = 20
12363 kshitij.so 1697
        else:
1698
            itemsToPopulate = len(itemInfo)
12456 kshitij.so 1699
        print "items to popluate"
12370 kshitij.so 1700
        print itemsToPopulate
12363 kshitij.so 1701
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate])
1702
        itemInfo[0:itemsToPopulate] = []
1703
        commitExceptionList(exceptionList,timestamp,options.runType)
1704
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
1705
        commitCheapest(cheapest,timestamp,options.runType)
1706
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
1707
        commitCanCompete(canCompete,timestamp,options.runType)
1708
        commitAlmostCompete(almostCompete,timestamp,options.runType)
1709
        commitCantCompete(cantCompete, timestamp,options.runType)
12396 kshitij.so 1710
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1711
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1712
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1713
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
12444 kshitij.so 1714
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,options.runType)
12363 kshitij.so 1715
if __name__=='__main__':
1716
    main()