Subversion Repositories SmartDukaan

Rev

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

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