Subversion Repositories SmartDukaan

Rev

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