Subversion Repositories SmartDukaan

Rev

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