Subversion Repositories SmartDukaan

Rev

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