Subversion Repositories SmartDukaan

Rev

Rev 12492 | Rev 12494 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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