Subversion Repositories SmartDukaan

Rev

Rev 12491 | Rev 12493 | 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
12363 kshitij.so 630
    return round(lowestPossibleSp,2)
631
 
12489 kshitij.so 632
def getNewLowestPossibleSp(item,serviceTax,newVatRate):
633
    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));
634
    if item.isPromotion:
635
        sku = ''
636
        if item.warehouseLocation==1:
637
            sku='FBA'+str(item.item_id)
638
        else:
639
            sku='FBB'+str(item.item_id)
640
        if amazonLongTermActivePromotions.has_key(sku):
641
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
642
        else:
643
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
644
        lowestPossibleSp = lowestPossibleSp - subsidy
645
    return round(lowestPossibleSp,2)
646
 
647
 
12363 kshitij.so 648
def getTargetTp(targetSp,spm,val):
12424 kshitij.so 649
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))
12363 kshitij.so 650
    return round(targetTp,2)
651
 
652
def commitExceptionList(exceptionList,timestamp,runType):
653
    for exceptionItem in exceptionList:
654
        val = exceptionItem[0]
655
        reason = exceptionItem[1]
656
        amazonScrapingHistory = AmazonScrapingHistory()
657
        amazonScrapingHistory.item_id = val.sku[3:]
658
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 659
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 660
        amazonScrapingHistory.reason = reason
661
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
662
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.EXCEPTION
663
        amazonScrapingHistory.timestamp = timestamp
664
    session.commit()
665
 
666
def commitNegativeMargin(negativeMargin,timestamp,runType):
667
    for negativeMarginItem in negativeMargin:
668
        val = negativeMarginItem[0]
669
        amDetails = negativeMarginItem[1]
670
        amPricing = negativeMarginItem[2]
671
        spm = val.sourcePercentage
672
        amazonScrapingHistory = AmazonScrapingHistory()
673
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 674
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 675
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 676
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 677
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 678
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 679
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
680
        amazonScrapingHistory.ourRank = amDetails.ourRank
681
        amazonScrapingHistory.ourInventory = val.ourInventory
682
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12468 kshitij.so 683
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
684
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
685
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 686
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 687
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
688
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
689
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 690
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 691
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
692
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
693
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12363 kshitij.so 694
        amazonScrapingHistory.wanlc = val.nlc
12447 kshitij.so 695
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 696
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 697
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 698
        amazonScrapingHistory.returnProvision = spm.returnProvision
699
        amazonScrapingHistory.courierCost = val.courierCost
700
        amazonScrapingHistory.risky = val.risky
701
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
702
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
703
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
704
        amazonScrapingHistory.timestamp = timestamp
705
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
706
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 707
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 708
    session.commit()
709
 
710
 
711
def commitCheapest(cheapest,timestamp,runType):
712
    for cheapestItem in cheapest:
713
        val = cheapestItem[0]
714
        amDetails = cheapestItem[1]
715
        amPricing = cheapestItem[2]
716
        spm = val.sourcePercentage
717
        amazonScrapingHistory = AmazonScrapingHistory()
718
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 719
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 720
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 721
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 722
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 723
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 724
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
725
        amazonScrapingHistory.ourRank = amDetails.ourRank
726
        amazonScrapingHistory.ourInventory = val.ourInventory
727
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 728
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
729
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
730
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 731
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 732
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
733
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
734
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 735
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 736
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
737
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
738
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 739
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 740
        amazonScrapingHistory.wanlc = val.nlc
741
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 742
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 743
        amazonScrapingHistory.returnProvision = spm.returnProvision
744
        amazonScrapingHistory.courierCost = val.courierCost
745
        amazonScrapingHistory.risky = val.risky
746
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
747
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
748
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.BUY_BOX
749
        amazonScrapingHistory.timestamp = timestamp
750
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12430 kshitij.so 751
        proposed_sp = max(amDetails.secondLowestSellerSp - max((20, amDetails.secondLowestSellerSp*0.002)), amPricing.lowestPossibleSp)
12433 kshitij.so 752
        if amazonScrapingHistory.isPromotion:
753
            if amazonLongTermActivePromotions.has_key(val.sku):
12466 kshitij.so 754
                proposed_sp = min(proposed_sp,(amazonLongTermActivePromotions.get(val.sku)).salePrice)
12433 kshitij.so 755
            else:
12466 kshitij.so 756
                proposed_sp = min(proposed_sp,(amazonShortTermActivePromotions.get(val.sku)).salePrice)
12468 kshitij.so 757
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 758
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 759
        #amazonScrapingHistory.proposedTp = proposed_tp
760
        #amazonScrapingHistory.marginIncreasedPotential = proposed_tp - amPricing.ourTp
12363 kshitij.so 761
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
762
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 763
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 764
    session.commit()
765
 
766
 
767
 
768
def commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,runType):
769
    for amongCheapestAndCanCompeteItem in amongCheapestAndCanCompete:
770
        val = amongCheapestAndCanCompeteItem[0]
771
        amDetails = amongCheapestAndCanCompeteItem[1]
772
        amPricing = amongCheapestAndCanCompeteItem[2]
773
        spm = val.sourcePercentage
774
        amazonScrapingHistory = AmazonScrapingHistory()
775
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 776
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 777
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 778
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 779
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 780
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 781
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
782
        amazonScrapingHistory.ourRank = amDetails.ourRank
783
        amazonScrapingHistory.ourInventory = val.ourInventory
784
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 785
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
786
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
787
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 788
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 789
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
790
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
791
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12470 kshitij.so 792
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 793
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
794
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
795
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 796
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 797
        amazonScrapingHistory.wanlc = val.nlc
798
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 799
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 800
        amazonScrapingHistory.returnProvision = spm.returnProvision
801
        amazonScrapingHistory.courierCost = val.courierCost
802
        amazonScrapingHistory.risky = val.risky
803
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
804
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
805
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE
806
        amazonScrapingHistory.timestamp = timestamp
807
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
808
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
12468 kshitij.so 809
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 810
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 811
        #amazonScrapingHistory.proposedTp = proposed_tp
12363 kshitij.so 812
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
813
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 814
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 815
    session.commit()
816
 
817
def commitCanCompete(canCompete,timestamp,runType):
818
    for canCompeteItem in canCompete:
819
        val = canCompeteItem[0]
820
        amDetails = canCompeteItem[1]
821
        amPricing = canCompeteItem[2]
822
        spm = val.sourcePercentage
823
        amazonScrapingHistory = AmazonScrapingHistory()
824
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 825
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 826
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 827
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 828
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 829
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 830
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
831
        amazonScrapingHistory.ourRank = amDetails.ourRank
832
        amazonScrapingHistory.ourInventory = val.ourInventory
833
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 834
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
835
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
836
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 837
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 838
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
839
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
840
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 841
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 842
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
843
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
844
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 845
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 846
        amazonScrapingHistory.wanlc = val.nlc
847
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 848
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 849
        amazonScrapingHistory.returnProvision = spm.returnProvision
850
        amazonScrapingHistory.courierCost = val.courierCost
851
        amazonScrapingHistory.risky = val.risky
852
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
853
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
854
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
855
        amazonScrapingHistory.timestamp = timestamp
856
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
857
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
12468 kshitij.so 858
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 859
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 860
        #amazonScrapingHistory.proposedTp = proposed_tp
12363 kshitij.so 861
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
862
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 863
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 864
    session.commit()
865
 
12383 kshitij.so 866
def commitAlmostCompete(almostCompete,timestamp,runType):
12396 kshitij.so 867
    for almostCompeteItem in almostCompete:
868
        val = almostCompeteItem[0]
869
        amDetails = almostCompeteItem[1]
870
        amPricing = almostCompeteItem[2]
871
        spm = val.sourcePercentage
872
        amazonScrapingHistory = AmazonScrapingHistory()
873
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 874
        amazonScrapingHistory.asin = val.asin
12396 kshitij.so 875
        amazonScrapingHistory.warehouseLocation = val.state_id
876
        amazonScrapingHistory.parentCategoryId = val.parent_category
877
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 878
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12396 kshitij.so 879
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
880
        amazonScrapingHistory.ourRank = amDetails.ourRank
881
        amazonScrapingHistory.ourInventory = val.ourInventory
882
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 883
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
884
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
885
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12396 kshitij.so 886
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 887
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
888
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
889
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12396 kshitij.so 890
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 891
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
892
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
893
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 894
        amazonScrapingHistory.otherCost = val.otherCost
12396 kshitij.so 895
        amazonScrapingHistory.wanlc = val.nlc
896
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 897
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12396 kshitij.so 898
        amazonScrapingHistory.returnProvision = spm.returnProvision
899
        amazonScrapingHistory.courierCost = val.courierCost
900
        amazonScrapingHistory.risky = val.risky
901
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
902
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
903
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.ALMOST_COMPETE
904
        amazonScrapingHistory.timestamp = timestamp
905
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12425 kshitij.so 906
        proposed_sp = min(amDetails.lowestSellerSp*(1+.01),amPricing.lowestPossibleSp)
12468 kshitij.so 907
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
908
        #target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
12396 kshitij.so 909
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 910
        #amazonScrapingHistory.proposedTp = proposed_tp
911
        #amazonScrapingHistory.targetNlc = target_nlc
12396 kshitij.so 912
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
913
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 914
        amazonScrapingHistory.isPromotion = val.isPromo
12396 kshitij.so 915
    session.commit()
12363 kshitij.so 916
 
12396 kshitij.so 917
 
12363 kshitij.so 918
def commitCantCompete(cantCompete, timestamp,runType):
919
    for cantCompeteItem in cantCompete:
920
        val = cantCompeteItem[0]
921
        amDetails = cantCompeteItem[1]
922
        amPricing = cantCompeteItem[2]
923
        spm = val.sourcePercentage
924
        amazonScrapingHistory = AmazonScrapingHistory()
925
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 926
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 927
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 928
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 929
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 930
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 931
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
932
        amazonScrapingHistory.ourRank = amDetails.ourRank
933
        amazonScrapingHistory.ourInventory = val.ourInventory
934
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 935
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
936
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
937
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 938
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 939
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
940
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
941
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 942
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 943
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
944
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
945
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 946
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 947
        amazonScrapingHistory.wanlc = val.nlc
948
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 949
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 950
        amazonScrapingHistory.returnProvision = spm.returnProvision
951
        amazonScrapingHistory.courierCost = val.courierCost
952
        amazonScrapingHistory.risky = val.risky
953
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
954
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
955
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
956
        amazonScrapingHistory.timestamp = timestamp
957
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
958
        proposed_sp = amDetails.lowestSellerSp - max(5, amDetails.lowestSellerSp*0.001)
12468 kshitij.so 959
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
960
        #target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
12363 kshitij.so 961
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 962
        #amazonScrapingHistory.proposedTp = proposed_tp
963
        #amazonScrapingHistory.targetNlc = target_nlc
12363 kshitij.so 964
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
965
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 966
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 967
    session.commit()
968
 
12396 kshitij.so 969
def markAutoFavourites(time):
970
    nowAutoFav = []
971
    previouslyAutoFav = []
972
    stockList = []
973
    saleList = []
974
    items = session.query(func.sum(AmazonScrapingHistory.ourInventory),AmazonScrapingHistory.item_id).group_by(AmazonScrapingHistory.item_id).all()
975
    allItems = session.query(Amazonlisted).all()
976
    for item in items:
977
        reason = ""
978
        if item[0]>=5:
979
            stockList.append(item[1])
980
 
981
    for sku, val in saleMap.iteritems():
982
        totalSale = 0
983
        item_id = sku.replace('FBA','').replace('FBB','')
984
        val =saleMap.get('FBA'+str(item_id))
985
        if val is not None:
986
            for sale in val:
987
                totalSale += sale.totalOrderCount
988
        val =saleMap.get('FBB'+str(item_id))
989
        if val is not None:
990
            for sale in val:
991
                totalSale += sale.totalOrderCount
992
        if totalSale > 0:
993
            saleList.append(item_id)
994
 
995
    for aItem in allItems:
996
        reason = ""
997
        toMark = False
998
        if aItem.itemId in saleList:
999
            toMark = True
1000
            reason+="Total FC sale is greater than 1 for last five days.."
1001
        if aItem.itemId in stockList:
1002
            toMark = True
1003
            reason+="Item is present in buy box in last 3 days"
1004
        if not aItem.autoFavourite:
1005
            print "Item is not under auto favourite"
1006
        if toMark:
1007
            temp=[]
1008
            temp.append(aItem.itemId)
1009
            temp.append(reason)
1010
            nowAutoFav.append(temp)
1011
        if (not toMark) and aItem.autoFavourite:
1012
            previouslyAutoFav.append(aItem.itemId)
1013
        aItem.autoFavourite = toMark
1014
    session.commit()
1015
    return previouslyAutoFav, nowAutoFav
1016
 
12444 kshitij.so 1017
def writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,runType):
12396 kshitij.so 1018
    wbk = xlwt.Workbook()
1019
    sheet = wbk.add_sheet('Can\'t Compete')
1020
    xstr = lambda s: s or ""
1021
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1022
 
1023
    excel_integer_format = '0'
1024
    integer_style = xlwt.XFStyle()
1025
    integer_style.num_format_str = excel_integer_format
1026
 
1027
    sheet.write(0, 0, "Item Id", heading_xf)
1028
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1029
    sheet.write(0, 2, "Asin", heading_xf)
1030
    sheet.write(0, 3, "Location", heading_xf)
1031
    sheet.write(0, 4, "Brand", heading_xf)
1032
    sheet.write(0, 5, "Product Name", heading_xf)
1033
    sheet.write(0, 6, "Weight", heading_xf)
1034
    sheet.write(0, 7, "Courier Cost", heading_xf)
1035
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1036
    sheet.write(0, 9, "Promo Price", heading_xf)
1037
    sheet.write(0, 10, "Is Promotion", heading_xf)
1038
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1039
    sheet.write(0, 12, "Rank", heading_xf)
1040
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1041
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1042
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1043
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1044
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1045
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1046
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1047
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1048
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1049
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1050
    sheet.write(0, 23, "Other Cost", heading_xf)
1051
    sheet.write(0, 24, "WANLC", heading_xf)
1052
    sheet.write(0, 25, "Commission", heading_xf)
1053
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1054
    sheet.write(0, 27, "Return Provision", heading_xf)
1055
    sheet.write(0, 28, "Margin", heading_xf)
1056
    sheet.write(0, 29, "Risky", heading_xf)
1057
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1058
    sheet.write(0, 31, "Avg Sale", heading_xf)
1059
    sheet.write(0, 32, "Sales History", heading_xf)
12396 kshitij.so 1060
 
1061
    sheet_iterator = 1
12476 kshitij.so 1062
    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 1063
    for cantCompeteItem in cantCompeteItems:
1064
        amScraping =  cantCompeteItem[0]
1065
        item = cantCompeteItem[1]
1066
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1067
        if amScraping.warehouseLocation == 1:
1068
            sku = 'FBA'+str(amScraping.item_id)
1069
            loc = 'MUMBAI'
1070
        else:
1071
            sku = 'FBB'+str(amScraping.item_id)
1072
            loc = 'BANGLORE'
1073
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1074
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1075
        sheet.write(sheet_iterator, 3, loc)
1076
        sheet.write(sheet_iterator, 4, item.brand)
1077
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1078
        sheet.write(sheet_iterator, 6, item.weight)
1079
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1080
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1081
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1082
        if amScraping.isPromotion:
1083
            sheet.write(sheet_iterator, 10, "Yes")
1084
        else:
12483 kshitij.so 1085
            sheet.write(sheet_iterator, 10, "No")
12432 kshitij.so 1086
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1087
        if amScraping.ourRank > 3:
1088
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1089
        else:
1090
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1091
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1092
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1093
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1094
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1095
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1096
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1097
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1098
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1099
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1100
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1101
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1102
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1103
        sheet.write(sheet_iterator, 25, amScraping.commission)
1104
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1105
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
12484 kshitij.so 1106
        sheet.write(sheet_iterator, 28, round(amScraping.promoPrice - amScraping.lowestPossibleSp))
12447 kshitij.so 1107
        sheet.write(sheet_iterator, 29, item.risky)
1108
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1109
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1110
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12396 kshitij.so 1111
        sheet_iterator+=1
1112
 
1113
    sheet = wbk.add_sheet('Competitive')
1114
    xstr = lambda s: s or ""
1115
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1116
 
1117
    excel_integer_format = '0'
1118
    integer_style = xlwt.XFStyle()
1119
    integer_style.num_format_str = excel_integer_format
1120
 
1121
    sheet.write(0, 0, "Item Id", heading_xf)
1122
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1123
    sheet.write(0, 2, "Asin", heading_xf)
1124
    sheet.write(0, 3, "Location", heading_xf)
1125
    sheet.write(0, 4, "Brand", heading_xf)
1126
    sheet.write(0, 5, "Product Name", heading_xf)
1127
    sheet.write(0, 6, "Weight", heading_xf)
1128
    sheet.write(0, 7, "Courier Cost", heading_xf)
1129
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1130
    sheet.write(0, 9, "Promo Price", heading_xf)
1131
    sheet.write(0, 10, "Is Promotion", heading_xf)
1132
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1133
    sheet.write(0, 12, "Rank", heading_xf)
1134
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1135
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1136
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1137
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1138
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1139
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1140
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1141
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1142
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1143
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1144
    sheet.write(0, 23, "Other Cost", heading_xf)
1145
    sheet.write(0, 24, "WANLC", heading_xf)
1146
    sheet.write(0, 25, "Commission", heading_xf)
1147
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1148
    sheet.write(0, 27, "Return Provision", heading_xf)
1149
    sheet.write(0, 28, "Margin", heading_xf)
1150
    sheet.write(0, 29, "Risky", heading_xf)
1151
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1152
    sheet.write(0, 31, "Avg Sale", heading_xf)
1153
    sheet.write(0, 32, "Sales History", heading_xf)
1154
    sheet.write(0, 33, "Decision", heading_xf)
1155
    sheet.write(0, 34, "Reason", heading_xf)
1156
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1157
 
1158
    sheet_iterator = 1
12476 kshitij.so 1159
    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 1160
    for competitiveItem in competitiveItems:
1161
        amScraping =  competitiveItem[0]
1162
        item = competitiveItem[1]
1163
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1164
        if amScraping.warehouseLocation == 1:
1165
            sku = 'FBA'+str(amScraping.item_id)
1166
            loc = 'MUMBAI'
1167
        else:
1168
            sku = 'FBB'+str(amScraping.item_id)
1169
            loc = 'BANGLORE'
1170
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1171
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1172
        sheet.write(sheet_iterator, 3, loc)
1173
        sheet.write(sheet_iterator, 4, item.brand)
1174
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1175
        sheet.write(sheet_iterator, 6, item.weight)
1176
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1177
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1178
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1179
        if amScraping.isPromotion:
1180
            sheet.write(sheet_iterator, 10, "Yes")
1181
        else:
12483 kshitij.so 1182
            sheet.write(sheet_iterator, 10, "No")
12432 kshitij.so 1183
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1184
        if amScraping.ourRank > 3:
1185
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1186
        else:
1187
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1188
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1189
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1190
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1191
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1192
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1193
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1194
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1195
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1196
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1197
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1198
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1199
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1200
        sheet.write(sheet_iterator, 25, amScraping.commission)
1201
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1202
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
12484 kshitij.so 1203
        sheet.write(sheet_iterator, 28, round(amScraping.promoPrice - amScraping.lowestPossibleSp))
12447 kshitij.so 1204
        sheet.write(sheet_iterator, 29, item.risky)
1205
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1206
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1207
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1208
        if amScraping.decision is None:
12468 kshitij.so 1209
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1210
            sheet_iterator+=1
1211
            continue
12468 kshitij.so 1212
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1213
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1214
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1215
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1216
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12484 kshitij.so 1217
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice)))
12396 kshitij.so 1218
        sheet_iterator+=1
1219
 
1220
    sheet = wbk.add_sheet('Almost Competitive')
1221
    xstr = lambda s: s or ""
1222
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1223
 
1224
    excel_integer_format = '0'
1225
    integer_style = xlwt.XFStyle()
1226
    integer_style.num_format_str = excel_integer_format
1227
 
1228
    sheet.write(0, 0, "Item Id", heading_xf)
1229
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1230
    sheet.write(0, 2, "Asin", heading_xf)
1231
    sheet.write(0, 3, "Location", heading_xf)
1232
    sheet.write(0, 4, "Brand", heading_xf)
1233
    sheet.write(0, 5, "Product Name", heading_xf)
1234
    sheet.write(0, 6, "Weight", heading_xf)
1235
    sheet.write(0, 7, "Courier Cost", heading_xf)
1236
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1237
    sheet.write(0, 9, "Promo Price", heading_xf)
1238
    sheet.write(0, 10, "Is Promotion", heading_xf)
1239
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1240
    sheet.write(0, 12, "Rank", heading_xf)
1241
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1242
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1243
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1244
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1245
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1246
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1247
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1248
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1249
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1250
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1251
    sheet.write(0, 23, "Other Cost", heading_xf)
1252
    sheet.write(0, 24, "WANLC", heading_xf)
1253
    sheet.write(0, 25, "Commission", heading_xf)
1254
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1255
    sheet.write(0, 27, "Return Provision", heading_xf)
1256
    sheet.write(0, 28, "Margin", heading_xf)
1257
    sheet.write(0, 29, "Risky", heading_xf)
1258
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1259
    sheet.write(0, 31, "Avg Sale", heading_xf)
1260
    sheet.write(0, 32, "Sales History", heading_xf)
1261
    sheet.write(0, 33, "Decision", heading_xf)
1262
    sheet.write(0, 34, "Reason", heading_xf)
1263
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1264
 
1265
    sheet_iterator = 1
12476 kshitij.so 1266
    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 1267
    for almostCompetitiveItem in almostCompetitiveItems:
1268
        amScraping =  almostCompetitiveItem[0]
1269
        item = almostCompetitiveItem[1]
1270
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1271
        if amScraping.warehouseLocation == 1:
1272
            sku = 'FBA'+str(amScraping.item_id)
1273
            loc = 'MUMBAI'
1274
        else:
1275
            sku = 'FBB'+str(amScraping.item_id)
1276
            loc = 'BANGLORE'
12432 kshitij.so 1277
        amScraping =  competitiveItem[0]
1278
        item = competitiveItem[1]
1279
        if amScraping.warehouseLocation == 1:
1280
            sku = 'FBA'+str(amScraping.item_id)
1281
            loc = 'MUMBAI'
1282
        else:
1283
            sku = 'FBB'+str(amScraping.item_id)
1284
            loc = 'BANGLORE'
12396 kshitij.so 1285
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1286
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1287
        sheet.write(sheet_iterator, 3, loc)
1288
        sheet.write(sheet_iterator, 4, item.brand)
1289
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1290
        sheet.write(sheet_iterator, 6, item.weight)
1291
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1292
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1293
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1294
        if amScraping.isPromotion:
1295
            sheet.write(sheet_iterator, 10, "Yes")
1296
        else:
12483 kshitij.so 1297
            sheet.write(sheet_iterator, 10, "No")
12432 kshitij.so 1298
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1299
        if amScraping.ourRank > 3:
1300
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1301
        else:
1302
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1303
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1304
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1305
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1306
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1307
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1308
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1309
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1310
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1311
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1312
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1313
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1314
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1315
        sheet.write(sheet_iterator, 25, amScraping.commission)
1316
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1317
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
12484 kshitij.so 1318
        sheet.write(sheet_iterator, 28, round(amScraping.promoPrice - amScraping.lowestPossibleSp))
12447 kshitij.so 1319
        sheet.write(sheet_iterator, 29, item.risky)
1320
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1321
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1322
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1323
        if amScraping.decision is None:
12468 kshitij.so 1324
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1325
            sheet_iterator+=1
1326
            continue
12468 kshitij.so 1327
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1328
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1329
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1330
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1331
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12484 kshitij.so 1332
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice)))
12396 kshitij.so 1333
        sheet_iterator+=1
1334
 
1335
    sheet = wbk.add_sheet('Among Cheapest')
1336
    xstr = lambda s: s or ""
1337
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1338
 
1339
    excel_integer_format = '0'
1340
    integer_style = xlwt.XFStyle()
1341
    integer_style.num_format_str = excel_integer_format
1342
 
1343
    sheet.write(0, 0, "Item Id", heading_xf)
1344
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1345
    sheet.write(0, 2, "Asin", heading_xf)
1346
    sheet.write(0, 3, "Location", heading_xf)
1347
    sheet.write(0, 4, "Brand", heading_xf)
1348
    sheet.write(0, 5, "Product Name", heading_xf)
1349
    sheet.write(0, 6, "Weight", heading_xf)
1350
    sheet.write(0, 7, "Courier Cost", heading_xf)
1351
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1352
    sheet.write(0, 9, "Promo Price", heading_xf)
1353
    sheet.write(0, 10, "Is Promotion", heading_xf)
1354
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1355
    sheet.write(0, 12, "Rank", heading_xf)
1356
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1357
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1358
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1359
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1360
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1361
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1362
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1363
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1364
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1365
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1366
    sheet.write(0, 23, "Other Cost", heading_xf)
1367
    sheet.write(0, 24, "WANLC", heading_xf)
1368
    sheet.write(0, 25, "Commission", heading_xf)
1369
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1370
    sheet.write(0, 27, "Return Provision", heading_xf)
1371
    sheet.write(0, 28, "Margin", heading_xf)
1372
    sheet.write(0, 29, "Risky", heading_xf)
1373
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1374
    sheet.write(0, 31, "Avg Sale", heading_xf)
1375
    sheet.write(0, 32, "Sales History", heading_xf)
1376
    sheet.write(0, 33, "Decision", heading_xf)
1377
    sheet.write(0, 34, "Reason", heading_xf)
1378
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1379
 
1380
    sheet_iterator = 1
12476 kshitij.so 1381
    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 1382
    for amongCheapestItem in amongCheapestItems:
1383
        amScraping =  amongCheapestItem[0]
1384
        item = amongCheapestItem[1]
1385
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1386
        if amScraping.warehouseLocation == 1:
1387
            sku = 'FBA'+str(amScraping.item_id)
1388
            loc = 'MUMBAI'
1389
        else:
1390
            sku = 'FBB'+str(amScraping.item_id)
1391
            loc = 'BANGLORE'
1392
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1393
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1394
        sheet.write(sheet_iterator, 3, loc)
1395
        sheet.write(sheet_iterator, 4, item.brand)
1396
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1397
        sheet.write(sheet_iterator, 6, item.weight)
1398
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1399
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1400
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1401
        if amScraping.isPromotion:
1402
            sheet.write(sheet_iterator, 10, "Yes")
1403
        else:
12483 kshitij.so 1404
            sheet.write(sheet_iterator, 10, "No")
12432 kshitij.so 1405
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1406
        if amScraping.ourRank > 3:
1407
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1408
        else:
1409
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1410
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1411
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1412
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1413
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1414
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1415
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1416
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1417
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1418
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1419
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1420
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1421
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1422
        sheet.write(sheet_iterator, 25, amScraping.commission)
1423
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1424
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
12484 kshitij.so 1425
        sheet.write(sheet_iterator, 28, round(amScraping.promoPrice - amScraping.lowestPossibleSp))
12447 kshitij.so 1426
        sheet.write(sheet_iterator, 29, item.risky)
1427
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1428
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1429
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1430
        if amScraping.decision is None:
12468 kshitij.so 1431
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1432
            sheet_iterator+=1
1433
            continue
12468 kshitij.so 1434
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1435
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1436
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1437
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1438
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12484 kshitij.so 1439
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice)))
12396 kshitij.so 1440
        sheet_iterator+=1
1441
 
1442
    sheet = wbk.add_sheet('Cheapest')
1443
    xstr = lambda s: s or ""
1444
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1445
 
1446
    excel_integer_format = '0'
1447
    integer_style = xlwt.XFStyle()
1448
    integer_style.num_format_str = excel_integer_format
1449
 
1450
    sheet.write(0, 0, "Item Id", heading_xf)
1451
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1452
    sheet.write(0, 2, "Asin", heading_xf)
1453
    sheet.write(0, 3, "Location", heading_xf)
1454
    sheet.write(0, 4, "Brand", heading_xf)
1455
    sheet.write(0, 5, "Product Name", heading_xf)
1456
    sheet.write(0, 6, "Weight", heading_xf)
1457
    sheet.write(0, 7, "Courier Cost", heading_xf)
1458
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1459
    sheet.write(0, 9, "Promo Price", heading_xf)
1460
    sheet.write(0, 10, "Is Promotion", heading_xf)
1461
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1462
    sheet.write(0, 12, "Rank", heading_xf)
1463
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1464
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1465
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1466
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1467
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1468
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1469
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1470
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1471
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1472
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1473
    sheet.write(0, 23, "Other Cost", heading_xf)
1474
    sheet.write(0, 24, "WANLC", heading_xf)
1475
    sheet.write(0, 25, "Commission", heading_xf)
1476
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1477
    sheet.write(0, 27, "Return Provision", heading_xf)
1478
    sheet.write(0, 28, "Margin", heading_xf)
1479
    sheet.write(0, 29, "Risky", heading_xf)
1480
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1481
    sheet.write(0, 31, "Avg Sale", heading_xf)
1482
    sheet.write(0, 32, "Sales History", heading_xf)
1483
    sheet.write(0, 33, "Decision", heading_xf)
1484
    sheet.write(0, 34, "Reason", heading_xf)
1485
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1486
 
1487
    sheet_iterator = 1
12476 kshitij.so 1488
    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 1489
    for cheapestItem in cheapestItems:
1490
        amScraping =  cheapestItem[0]
1491
        item = cheapestItem[1]
1492
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1493
        if amScraping.warehouseLocation == 1:
1494
            sku = 'FBA'+str(amScraping.item_id)
1495
            loc = 'MUMBAI'
1496
        else:
1497
            sku = 'FBB'+str(amScraping.item_id)
1498
            loc = 'BANGLORE'
1499
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1500
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1501
        sheet.write(sheet_iterator, 3, loc)
1502
        sheet.write(sheet_iterator, 4, item.brand)
1503
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1504
        sheet.write(sheet_iterator, 6, item.weight)
1505
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1506
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1507
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1508
        if amScraping.isPromotion:
1509
            sheet.write(sheet_iterator, 10, "Yes")
1510
        else:
12483 kshitij.so 1511
            sheet.write(sheet_iterator, 10, "No")
12432 kshitij.so 1512
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1513
        if amScraping.ourRank > 3:
1514
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1515
        else:
1516
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1517
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1518
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1519
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1520
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1521
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1522
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1523
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1524
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1525
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1526
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1527
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1528
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1529
        sheet.write(sheet_iterator, 25, amScraping.commission)
1530
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1531
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
12484 kshitij.so 1532
        sheet.write(sheet_iterator, 28, round(amScraping.promoPrice - amScraping.lowestPossibleSp))
12447 kshitij.so 1533
        sheet.write(sheet_iterator, 29, item.risky)
1534
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1535
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1536
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1537
        if amScraping.decision is None:
12468 kshitij.so 1538
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1539
            sheet_iterator+=1
1540
            continue
12468 kshitij.so 1541
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1542
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1543
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12479 kshitij.so 1544
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1545
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12484 kshitij.so 1546
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice)))
12396 kshitij.so 1547
        sheet_iterator+=1
1548
 
1549
    sheet = wbk.add_sheet('Negative Margin')
1550
    xstr = lambda s: s or ""
1551
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1552
 
1553
    excel_integer_format = '0'
1554
    integer_style = xlwt.XFStyle()
1555
    integer_style.num_format_str = excel_integer_format
1556
 
1557
    sheet.write(0, 0, "Item Id", heading_xf)
1558
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1559
    sheet.write(0, 2, "Asin", heading_xf)
1560
    sheet.write(0, 3, "Location", heading_xf)
1561
    sheet.write(0, 4, "Brand", heading_xf)
1562
    sheet.write(0, 5, "Product Name", heading_xf)
1563
    sheet.write(0, 6, "Weight", heading_xf)
1564
    sheet.write(0, 7, "Courier Cost", heading_xf)
1565
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1566
    sheet.write(0, 9, "Promo Price", heading_xf)
1567
    sheet.write(0, 10, "Is Promotion", heading_xf)
1568
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1569
    sheet.write(0, 12, "Rank", heading_xf)
1570
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1571
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1572
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1573
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1574
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1575
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1576
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1577
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1578
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1579
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1580
    sheet.write(0, 23, "Other Cost", heading_xf)
1581
    sheet.write(0, 24, "WANLC", heading_xf)
1582
    sheet.write(0, 25, "Commission", heading_xf)
1583
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1584
    sheet.write(0, 27, "Return Provision", heading_xf)
1585
    sheet.write(0, 28, "Margin", heading_xf)
1586
    sheet.write(0, 29, "Avg Sale", heading_xf)
1587
    sheet.write(0, 30, "Sales History", heading_xf)
12396 kshitij.so 1588
 
1589
    sheet_iterator = 1
12476 kshitij.so 1590
    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 1591
    for amongCheapestItem in amongCheapestItems:
1592
        amScraping =  amongCheapestItem[0]
1593
        item = amongCheapestItem[1]
1594
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1595
        if amScraping.warehouseLocation == 1:
1596
            sku = 'FBA'+str(amScraping.item_id)
1597
            loc = 'MUMBAI'
1598
        else:
1599
            sku = 'FBB'+str(amScraping.item_id)
1600
            loc = 'BANGLORE'
1601
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1602
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1603
        sheet.write(sheet_iterator, 3, loc)
1604
        sheet.write(sheet_iterator, 4, item.brand)
1605
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1606
        sheet.write(sheet_iterator, 6, item.weight)
1607
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1608
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1609
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1610
        if amScraping.isPromotion:
1611
            sheet.write(sheet_iterator, 10, "Yes")
1612
        else:
12483 kshitij.so 1613
            sheet.write(sheet_iterator, 10, "No")
12432 kshitij.so 1614
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1615
        if amScraping.ourRank > 3:
1616
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1617
        else:
1618
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1619
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1620
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1621
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1622
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1623
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1624
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1625
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1626
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1627
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1628
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1629
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1630
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1631
        sheet.write(sheet_iterator, 25, amScraping.commission)
1632
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1633
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
12484 kshitij.so 1634
        sheet.write(sheet_iterator, 28, round(amScraping.promoPrice - amScraping.lowestPossibleSp))
12447 kshitij.so 1635
        sheet.write(sheet_iterator, 29, amScraping.avgSale)
1636
        sheet.write(sheet_iterator, 30, getOosString(saleMap.get(sku)))
12396 kshitij.so 1637
        sheet_iterator+=1
1638
 
1639
    sheet = wbk.add_sheet('Exception List')
1640
    xstr = lambda s: s or ""
1641
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1642
 
1643
    excel_integer_format = '0'
1644
    integer_style = xlwt.XFStyle()
1645
    integer_style.num_format_str = excel_integer_format
1646
 
1647
    sheet.write(0, 0, "Item Id", heading_xf)
1648
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1649
    sheet.write(0, 2, "Asin", heading_xf)
1650
    sheet.write(0, 3, "Location", heading_xf)
1651
    sheet.write(0, 4, "Brand", heading_xf)
1652
    sheet.write(0, 5, "Product Name", heading_xf)
1653
    sheet.write(0, 6, "Reason", heading_xf)
1654
 
1655
    sheet_iterator = 1
12476 kshitij.so 1656
    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 1657
    for amongCheapestItem in amongCheapestItems:
1658
        amScraping =  amongCheapestItem[0]
1659
        item = amongCheapestItem[1]
1660
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1661
        if amScraping.warehouseLocation == 1:
1662
            sku = 'FBA'+str(amScraping.item_id)
1663
            loc = 'MUMBAI'
1664
        else:
1665
            sku = 'FBB'+str(amScraping.item_id)
1666
            loc = 'BANGLORE'
1667
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1668
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1669
        sheet.write(sheet_iterator, 3, loc)
1670
        sheet.write(sheet_iterator, 4, item.brand)
1671
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1672
        sheet.write(sheet_iterator, 6, amScraping.reason)
1673
        sheet_iterator+=1      
1674
 
12444 kshitij.so 1675
 
1676
    if (runType=='FULL'):    
1677
        sheet = wbk.add_sheet('Auto Favorites')
1678
 
1679
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1680
 
1681
        excel_integer_format = '0'
1682
        integer_style = xlwt.XFStyle()
1683
        integer_style.num_format_str = excel_integer_format
1684
        xstr = lambda s: s or ""
1685
 
1686
        sheet.write(0, 0, "Item ID", heading_xf)
1687
        sheet.write(0, 1, "Brand", heading_xf)
1688
        sheet.write(0, 2, "Product Name", heading_xf)
1689
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1690
        sheet.write(0, 4, "Reason", heading_xf)
1691
 
1692
        sheet_iterator=1
1693
        for autoFav in nowAutoFav:
1694
            itemId = autoFav[0]
1695
            reason = autoFav[1]
1696
            it = Item.query.filter_by(id=itemId).one()
1697
            sheet.write(sheet_iterator, 0, itemId)
1698
            sheet.write(sheet_iterator, 1, it.brand)
1699
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1700
            sheet.write(sheet_iterator, 3, "True")
1701
            sheet.write(sheet_iterator, 4, reason)
1702
            sheet_iterator+=1
1703
        for prevFav in previousAutoFav:
1704
            it = Item.query.filter_by(id=prevFav).one()
1705
            sheet.write(sheet_iterator, 0, prevFav)
1706
            sheet.write(sheet_iterator, 1, it.brand)
1707
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1708
            sheet.write(sheet_iterator, 3, "False")
1709
            sheet_iterator+=1
1710
 
12478 kshitij.so 1711
    filename = "/tmp/amazon-report-"+runType+" " + str(timestamp) + ".xls"
12396 kshitij.so 1712
    wbk.save(filename)
12489 kshitij.so 1713
    try:
1714
        EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Amazon Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
1715
        #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"], [])
1716
    except Exception as e:
1717
        print e
1718
        print "Unable to send report.Trying with local SMTP"
1719
        smtpServer = smtplib.SMTP('localhost')
1720
        smtpServer.set_debuglevel(1)
1721
        sender = 'build@shop2020.in'
1722
        recipients = ["kshitij.sood@saholic.com"]
1723
        msg = MIMEMultipart()
1724
        msg['Subject'] = "Amazon Auto Pricing" + ' '+runType+' - ' + str(datetime.now())
1725
        msg['From'] = sender
1726
        #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']
1727
        msg['To'] = ",".join(recipients)
1728
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
1729
        fileMsg.set_payload(file(filename).read())
1730
        email.encoders.encode_base64(fileMsg)
1731
        fileMsg.add_header('Content-Disposition','attachment;filename=amazon-auto-pricing.xls')
1732
        msg.attach(fileMsg)
1733
        try:
1734
            smtpServer.sendmail(sender, recipients, msg.as_string())
1735
            print "Successfully sent email"
1736
        except:
1737
            print "Error: unable to send email."
1738
 
1739
def getNewVatRate(item_id,state,price):
1740
    itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==item_id, ItemVatMaster.stateId==state)).first()
1741
    if itemVatMaster is None:
1742
        d_item = Item.query.filter_by(id=item_id).first()
1743
        if d_item is None:
1744
            raise 
1745
        else:
1746
            vatMaster = CategoryVatMaster.query.filter(and_(CategoryVatMaster.categoryId==d_item.category, CategoryVatMaster.minVal<=price,  CategoryVatMaster.maxVal>=price,  CategoryVatMaster.stateId == state)).first()
1747
        if vatMaster is None:
1748
            raise
1749
        else:
1750
            vatRate = vatMaster.vatPercent
1751
    else:
1752
        vatRate = itemVatMaster.vatPercentage
1753
    return vatRate
1754
 
1755
def sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease):
1756
    if len(successfulAutoDecrease)==0 and len(successfulAutoIncrease)==0 :
1757
        return
1758
    xstr = lambda s: s or ""
1759
    message="""<html>
12490 kshitij.so 1760
            <h3 style="color:red;">Test Run.Please validate with costing sheet before taking any decision></h3>
12489 kshitij.so 1761
            <body>
1762
            <h3>Auto Decrease Items</h3>
1763
            <table border="1" style="width:100%;">
1764
            <thead>
1765
            <tr><th>Item Id</th>
1766
            <th>Amazon SKU</th>
1767
            <th>Product Name</th>
1768
            <th>Old Price</th>
1769
            <th>New Price</th>
1770
            <th>Subsidy</th>
1771
            <th>Old Margin</th>
1772
            <th>New Margin</th>
1773
            <th>Commission %</th>
1774
            <th>Return Provision %</th>
1775
            <th>Inventory</th>
1776
            <th>Sales History</th>
1777
            <th>Category</th>
1778
            </tr></thead>
1779
            <tbody>"""
1780
    for item in successfulAutoDecrease:
1781
        it = Item.query.filter_by(id=item.item_id).one()
1782
        vatRate = getNewVatRate(item.item_id,item.warehouseLocation,item.proposedSp)
1783
        oldMargin = item.ourSellingPrice - item.lowestPossibleSp
1784
        newMargin = round(item.proposedSp - getNewLowestPossibleSp(item,12.36,vatRate))
1785
        sku = ''
1786
        if item.warehouseLocation==1:
1787
            sku='FBA'+str(item.item_id)
1788
        else:
1789
            sku='FBB'+str(item.item_id)  
1790
        if amazonLongTermActivePromotions.has_key(sku):
1791
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
1792
        elif amazonShortTermActivePromotions.has_key(sku):
1793
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
1794
        else:
1795
            subsidy = 0
1796
        message+="""<tr>
1797
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1798
                <td style="text-align:center">"""+sku+"""</td>
1799
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1800
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1801
                <td style="text-align:center">"""+str(math.ceil(item.proposedSp))+"""</td>
1802
                <td style="text-align:center">"""+str(math.ceil(item.proposedSp))+"""</td>
1803
                <td style="text-align:center">"""+str(round(subsidy))+"""</td>
1804
                <td style="text-align:center">"""+str(round(oldMargin))+" ("+str(round((oldMargin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1805
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/item.proposedSellingPrice)*100,1))+"%)"+"""</td>
1806
                <td style="text-align:center">"""+str(item.commission)+" %"+"""</td>
1807
                <td style="text-align:center">"""+str(item.returnProvision)+" %"+"""</td>
1808
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1809
                <td style="text-align:center">"""+getOosString(saleMap.get(sku))+"""</td>
1810
                <td style="text-align:center">"""+str(CompetitionCategory._VALUES_TO_NAMES.get(item.competitiveCategory))+"""</td>
1811
                </tr>"""
1812
    message+="""</tbody></table><h3>Auto Increase Items</h3><table border="1" style="width:100%;">
1813
            <thead>
1814
            <tr><th>Item Id</th>
1815
            <th>Amazon SKU</th>
1816
            <th>Product Name</th>
1817
            <th>Old Price</th>
1818
            <th>New Price</th>
1819
            <th>Subsidy</th>
1820
            <th>Old Margin</th>
1821
            <th>New Margin</th>
1822
            <th>Commission %</th>
1823
            <th>Return Provision %</th>
1824
            <th>Inventory</th>
1825
            <th>Sales History</th>
1826
            <th>Category</th>
1827
            </tr></thead>
1828
            <tbody>"""
1829
    for item in successfulAutoIncrease:
1830
        it = Item.query.filter_by(id=item.item_id).one()
1831
        vatRate = getNewVatRate(item.item_id,item.warehouseLocation,math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))
1832
        oldMargin = item.ourSellingPrice - item.lowestPossibleSp
1833
        newMargin = round(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)) - getNewLowestPossibleSp(item,12.36,vatRate))
1834
        sku = ''
1835
        if item.warehouseLocation==1:
1836
            sku='FBA'+str(item.item_id)
1837
        else:
1838
            sku='FBB'+str(item.item_id)  
1839
        if amazonLongTermActivePromotions.has_key(sku):
1840
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
1841
        elif amazonShortTermActivePromotions.has_key(sku):
1842
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
1843
        else:
1844
            subsidy = 0
1845
        message+="""<tr>
1846
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
1847
                <td style="text-align:center">"""+sku+"""</td>
1848
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
1849
                <td style="text-align:center">"""+str(item.ourSellingPrice)+"""</td>
1850
                <td style="text-align:center">"""+str(math.ceil(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))+"""</td>
1851
                <td style="text-align:center">"""+str(round(subsidy))+"""</td>
1852
                <td style="text-align:center">"""+str(round((oldMargin),1))+" ("+str(round((oldMargin/item.ourSellingPrice)*100,1))+"%)"+"""</td>
1853
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/(item.ourSellingPrice+max(10,.01*item.ourSellingPrice)))*100,1))+"%)"+"""</td>
1854
                <td style="text-align:center">"""+str(item.commission)+" %"+"""</td>
1855
                <td style="text-align:center">"""+str(item.returnProvision)+" %"+"""</td>
1856
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
1857
                <td style="text-align:center">"""+getOosString(saleMap.get(sku))+"""</td>
1858
                <td style="text-align:center">"""+str(CompetitionCategory._VALUES_TO_NAMES.get(item.competitiveCategory))+"""</td>
1859
                </tr>"""
1860
    message+="""</tbody></table></body></html>"""
1861
    print message
1862
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
1863
    mailServer.ehlo()
1864
    mailServer.starttls()
1865
    mailServer.ehlo()
1866
 
1867
    recipients = ['kshitij.sood@saholic.com']
1868
    #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']
1869
    msg = MIMEMultipart()
1870
    msg['Subject'] = "Amazon Auto Pricing" + ' - ' + str(datetime.now())
1871
    msg['From'] = ""
1872
    msg['To'] = ",".join(recipients)
1873
    msg.preamble = "Amazon Auto Pricing" + ' - ' + str(datetime.now())
1874
    html_msg = MIMEText(message, 'html')
1875
    msg.attach(html_msg)
1876
    try:
1877
        mailServer.login("build@shop2020.in", "cafe@nes")
1878
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
1879
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
1880
    except Exception as e:
1881
        print e
1882
        print "Unable to send pricing mail.Lets try with local SMTP."
1883
        smtpServer = smtplib.SMTP('localhost')
1884
        smtpServer.set_debuglevel(1)
1885
        sender = 'build@shop2020.in'
1886
        try:
1887
            smtpServer.sendmail(sender, recipients, msg.as_string())
1888
            print "Successfully sent email"
1889
        except:
1890
            print "Error: unable to send email."
1891
 
12396 kshitij.so 1892
 
12363 kshitij.so 1893
def main():
1894
    parser = optparse.OptionParser()
1895
    parser.add_option("-t", "--type", dest="runType",
1896
                   default="FULL", type="string",
1897
                   help="Run type FULL or FAVOURITE")
1898
    (options, args) = parser.parse_args()
1899
    if options.runType not in ('FULL','FAVOURITE'):
1900
        print "Run type argument illegal."
1901
        sys.exit(1)
1902
    time.sleep(5)
1903
    timestamp = datetime.now()
1904
    fetchFbaSale()
1905
    itemInfo = populateStuff(timestamp,options.runType)
1906
    itemsToPopulate = 0
12430 kshitij.so 1907
    toSync = 0
1908
    lenItems = len(itemInfo)
1909
    while(toSync < lenItems):
1910
        oldSync = toSync
1911
        if lenItems >= 20:
1912
            toSync = 20
1913
        else:
1914
            toSync = lenItems - oldSync
1915
        getPriceAndAsin(itemInfo[oldSync:toSync+oldSync])
1916
        toSync = oldSync + toSync
1917
 
12363 kshitij.so 1918
    while (len(itemInfo)>0):
12430 kshitij.so 1919
        if len(itemInfo) >= 20:
1920
            itemsToPopulate = 20
12363 kshitij.so 1921
        else:
1922
            itemsToPopulate = len(itemInfo)
12456 kshitij.so 1923
        print "items to popluate"
12370 kshitij.so 1924
        print itemsToPopulate
12363 kshitij.so 1925
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate])
1926
        itemInfo[0:itemsToPopulate] = []
1927
        commitExceptionList(exceptionList,timestamp,options.runType)
1928
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
1929
        commitCheapest(cheapest,timestamp,options.runType)
1930
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
1931
        commitCanCompete(canCompete,timestamp,options.runType)
1932
        commitAlmostCompete(almostCompete,timestamp,options.runType)
1933
        commitCantCompete(cantCompete, timestamp,options.runType)
12396 kshitij.so 1934
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1935
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1936
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1937
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
12444 kshitij.so 1938
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,options.runType)
12491 kshitij.so 1939
    sendAutoPricingMail(autoDecreaseItems,autoIncreaseItems)
12363 kshitij.so 1940
if __name__=='__main__':
1941
    main()