Subversion Repositories SmartDukaan

Rev

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