Subversion Repositories SmartDukaan

Rev

Rev 12918 | Rev 13131 | 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 = {}
12717 kshitij.so 40
wpiTodayExpiry = {}
12711 kshitij.so 41
notListed = []
12363 kshitij.so 42
saleMap = {}
12526 anikendra 43
categoryMap = {}
12736 kshitij.so 44
exceptionMap = {1:'WANLC is 0',2:'Unable to fetch our price',3:'No other seller or Unable to fetch competitive pricing',
45
                4:'Promo misconfigured',5:'Unable to calculate competitive pricing',6:'Vat not available'}
12363 kshitij.so 46
DataService.initialize(db_hostname=host)
47
 
12430 kshitij.so 48
amScraper = AmazonAsyncScraper.Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
12363 kshitij.so 49
 
50
class __AmazonItemInfo:
51
 
12845 kshitij.so 52
    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, exceptionType, isNlcOverridden):
12382 kshitij.so 53
        self.asin = asin
12363 kshitij.so 54
        self.nlc = nlc
55
        self.courierCost = courierCost
56
        self.sku = sku
57
        self.product_group = product_group
58
        self.brand = brand
59
        self.model_name = model_name
60
        self.model_number = model_number
61
        self.color = color
62
        self.weight = weight
63
        self.parent_category = parent_category
64
        self.risky = risky
65
        self.vatRate = vatRate
66
        self.runType = runType
67
        self.parent_category_name = parent_category_name
68
        self.sourcePercentage = sourcePercentage
69
        self.ourInventory = ourInventory
70
        self.state_id = state_id
12447 kshitij.so 71
        self.otherCost = otherCost
12845 kshitij.so 72
        self.exceptionType = exceptionType
73
        self.isNlcOverridden = isNlcOverridden
12363 kshitij.so 74
 
75
class __AmazonDetails:
12430 kshitij.so 76
    def __init__(self, sku, ourSp, ourRank, lowestSellerName,lowestSellerSp,secondLowestSellerName, secondLowestSellerSp, thirdLowestSellerName, thirdLowestSellerSp, totalSeller, multipleListings, \
77
                 promoPrice, isPromotion, lowestSellerShippingTime, lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , \
12597 kshitij.so 78
                 thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType, lowestMfnIgnoredOffer, lowestMfnOffer, lowestFbaOffer, \
79
                 isLowestMfnIgnored, isLowestMfn, isLowestFba, competitivePrice):
12363 kshitij.so 80
        self.sku =sku
81
        self.ourSp = ourSp
82
        self.ourRank = ourRank
83
        self.lowestSellerName = lowestSellerName
84
        self.lowestSellerSp = lowestSellerSp
85
        self.secondLowestSellerName = secondLowestSellerName
86
        self.secondLowestSellerSp = secondLowestSellerSp
87
        self.thirdLowestSellerName = thirdLowestSellerName
88
        self.thirdLowestSellerSp = thirdLowestSellerSp
89
        self.totalSeller = totalSeller
12430 kshitij.so 90
        self.multipleListings = multipleListings
91
        self.promoPrice = promoPrice
92
        self.isPromotion = isPromotion
93
        self.lowestSellerShippingTime =lowestSellerShippingTime
94
        self.lowestSellerRating = lowestSellerRating
95
        self.secondLowestSellerShippingTime = secondLowestSellerShippingTime
96
        self.secondLowestSellerRating = secondLowestSellerRating
97
        self.thirdLowestSellerShippingTime= thirdLowestSellerShippingTime
98
        self.thirdLowestSellerRating = thirdLowestSellerRating
99
        self.lowestSellerType = lowestSellerType
100
        self.secondLowestSellerType = secondLowestSellerType
12447 kshitij.so 101
        self.thirdLowestSellerType = thirdLowestSellerType
12597 kshitij.so 102
        self.lowestMfnIgnoredOffer = lowestMfnIgnoredOffer
103
        self.isLowestMfnIgnored = isLowestMfnIgnored 
104
        self.lowestMfnOffer = lowestMfnOffer
105
        self.isLowestMfn = isLowestMfn 
106
        self.lowestFbaOffer = lowestFbaOffer  
107
        self.isLowestFba = isLowestFba
108
        self.competitivePrice = competitivePrice 
12430 kshitij.so 109
 
12363 kshitij.so 110
 
111
class __AmazonPricing:
112
 
12432 kshitij.so 113
    def __init__(self, ourSp, lowestPossibleSp):
12363 kshitij.so 114
        self.ourSp = ourSp
115
        self.lowestPossibleSp = lowestPossibleSp
116
 
12432 kshitij.so 117
class __Promotion:
12433 kshitij.so 118
    def __init__(self, promoPrice, subsidy, promotionType,expiryDate):
12432 kshitij.so 119
        self.promoPrice = promoPrice
120
        self.subsidy = subsidy
121
        self.promotionType = promotionType
12433 kshitij.so 122
        self.expiryDate = expiryDate 
12432 kshitij.so 123
 
12363 kshitij.so 124
 
12432 kshitij.so 125
 
12396 kshitij.so 126
def fetchItemsForAutoDecrease(time):
127
    successfulAutoDecrease = []
128
    autoDecrementItems = session.query(AmazonScrapingHistory).join((Amazonlisted,AmazonScrapingHistory.item_id==Amazonlisted.itemId))\
129
    .filter(AmazonScrapingHistory.timestamp==time).filter(or_(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE,AmazonScrapingHistory.competitiveCategory==CompetitionCategory.COMPETITIVE, AmazonScrapingHistory.competitiveCategory==CompetitionCategory.ALMOST_COMPETE ))\
130
    .filter(Amazonlisted.autoDecrement==True).all()
131
    for autoDecrementItem in autoDecrementItems:
132
        if autoDecrementItem.warehouseLocation == 1:
133
            sku = 'FBA'+str(autoDecrementItem.item_id)
12909 kshitij.so 134
        elif autoDecrementItem.warehouseLocation == 2:
135
            sku = 'FBB'+str(autoDecrementItem.item_id)
12396 kshitij.so 136
        else:
12909 kshitij.so 137
            sku = 'FBG'+str(autoDecrementItem.item_id)
138
 
12432 kshitij.so 139
        if amazonShortTermActivePromotions.has_key(sku):
12396 kshitij.so 140
            markReasonForItem(autoDecrementItem,'Item in short term promotion',Decision.AUTO_DECREMENT_FAILED)
141
            continue
12717 kshitij.so 142
        if wpiTodayExpiry.has_key(sku) and not amazonLongTermActivePromotions.has_key(sku):
143
            markReasonForItem(autoDecrementItem,'Last Promotion ended in 24 hours and no current active promotion',Decision.AUTO_DECREMENT_FAILED)
144
            continue
12484 kshitij.so 145
        if math.ceil(autoDecrementItem.proposedSp) >= autoDecrementItem.promoPrice:
12396 kshitij.so 146
            markReasonForItem(autoDecrementItem,'Proposed SP greater than or equal to current SP',Decision.AUTO_DECREMENT_FAILED)
147
            continue
12479 kshitij.so 148
        if autoDecrementItem.proposedSp < autoDecrementItem.lowestPossibleSp:
12396 kshitij.so 149
            markReasonForItem(autoDecrementItem,'Proposed SP less than lowest possible SP',Decision.AUTO_DECREMENT_FAILED)
150
            continue
151
        try:
152
            daysOfStock = (float(autoDecrementItem.ourInventory))/autoDecrementItem.avgSale
153
        except:
154
            daysOfStock = float("inf")
155
        if autoDecrementItem.competitiveCategory == CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE:
12736 kshitij.so 156
            if daysOfStock < 5:
157
                markReasonForItem(autoDecrementItem,'Days of stock less than 5',Decision.AUTO_DECREMENT_FAILED)
12433 kshitij.so 158
                continue
12396 kshitij.so 159
 
12433 kshitij.so 160
        if autoDecrementItem.competitiveCategory == CompetitionCategory.COMPETITIVE and not autoDecrementItem.isPromotion:
12396 kshitij.so 161
            if autoDecrementItem.parentCategoryId in [10006,10009,11001]:
12433 kshitij.so 162
                if daysOfStock < 1 :
12396 kshitij.so 163
                    markReasonForItem(autoDecrementItem,'Days of stock less than 1',Decision.AUTO_DECREMENT_FAILED)
12433 kshitij.so 164
                    continue
165
 
12396 kshitij.so 166
            else:
167
                if daysOfStock < 3:
168
                    markReasonForItem(autoDecrementItem,'Days of stock less than 3',Decision.AUTO_DECREMENT_FAILED)
12433 kshitij.so 169
                    continue
170
 
171
        if autoDecrementItem.competitiveCategory == CompetitionCategory.COMPETITIVE and autoDecrementItem.isPromotion:
172
            if autoDecrementItem.parentCategoryId in [10006,10009,11001]:
173
                if (amazonLongTermActivePromotions.get(sku).expiryDate - datetime.now()).days >2 and daysOfStock < 1 :
174
                    markReasonForItem(autoDecrementItem,'Promo Item, expiry after 2 days or not enough stock',Decision.AUTO_DECREMENT_FAILED)
175
                    continue
176
 
177
            else:
178
                if (amazonLongTermActivePromotions.get(sku).expiryDate - datetime.now()).days >2 and daysOfStock < 3:
179
                    markReasonForItem(autoDecrementItem,'Promo Item, expiry after 2 days or not enough stock',Decision.AUTO_DECREMENT_FAILED)
180
                    continue
12396 kshitij.so 181
 
182
        autoDecrementItem.ourEnoughStock=True
183
        autoDecrementItem.decision = Decision.AUTO_DECREMENT_SUCCESS
184
        autoDecrementItem.reason = 'All conditions for auto decrement true'
185
        successfulAutoDecrease.append(autoDecrementItem)
186
    session.commit()
187
    return successfulAutoDecrease
188
 
189
def fetchItemsForAutoIncrease(time):
190
    successfulAutoIncrease = []
191
    autoIncrementItems = session.query(AmazonScrapingHistory).join((Amazonlisted,AmazonScrapingHistory.item_id==Amazonlisted.itemId))\
192
    .filter(AmazonScrapingHistory.timestamp==time).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.BUY_BOX)\
193
    .filter(Amazonlisted.autoIncrement==True).all()
194
    transaction_client = TransactionClient().get_client()
12477 kshitij.so 195
    print len(autoIncrementItems)
12396 kshitij.so 196
    for autoIncrementItem in autoIncrementItems:
197
        if autoIncrementItem.warehouseLocation == 1:
198
            sku = 'FBA'+str(autoIncrementItem.item_id)
12909 kshitij.so 199
        elif autoIncrementItem.warehouseLocation == 2:
200
            sku = 'FBB'+str(autoIncrementItem.item_id)
12396 kshitij.so 201
        else:
12909 kshitij.so 202
            sku = 'FBG'+str(autoIncrementItem.item_id)
12432 kshitij.so 203
        if amazonShortTermActivePromotions.has_key(sku):
12396 kshitij.so 204
            markReasonForItem(autoIncrementItem,'Item in short term promotion',Decision.AUTO_INCREMENT_FAILED)
205
            continue
12717 kshitij.so 206
        if wpiTodayExpiry.has_key(sku) and not amazonLongTermActivePromotions.has_key(sku):
207
            markReasonForItem(autoIncrementItem,'Last Promotion ended in 24 hours and no current active promotion',Decision.AUTO_INCREMENT_FAILED)
208
            continue
12396 kshitij.so 209
        if autoIncrementItem.totalSeller==1 and autoIncrementItem.ourRank==1:
210
            markReasonForItem(autoIncrementItem,'We are the only seller',Decision.AUTO_INCREMENT_FAILED)
211
            continue 
12484 kshitij.so 212
        if autoIncrementItem.proposedSp <= autoIncrementItem.promoPrice:
12396 kshitij.so 213
            markReasonForItem(autoIncrementItem,'Proposed SP less than current SP',Decision.AUTO_INCREMENT_FAILED)
214
            continue
12484 kshitij.so 215
        if autoIncrementItem.proposedSp >=10000 and autoIncrementItem.promoPrice<10000:
12396 kshitij.so 216
            markReasonForItem(autoIncrementItem,'Proposed SP is greater than 10,000 and current sp is less than 10,000',Decision.AUTO_INCREMENT_FAILED)
217
            continue
218
 
12917 kshitij.so 219
        if autoIncrementItem.isPromotion and (min(math.ceil(autoIncrementItem.promoPrice+max(10,.01*autoIncrementItem.promoPrice)),autoIncrementItem.proposedSp) > (amazonLongTermActivePromotions.get(sku)).promoPrice):
12447 kshitij.so 220
            markReasonForItem(autoIncrementItem,'Proposed SP cant be greater than promo price',Decision.AUTO_INCREMENT_FAILED)
221
            continue
12917 kshitij.so 222
 
12447 kshitij.so 223
 
12396 kshitij.so 224
        if autoIncrementItem.avgSale==0:
225
            markReasonForItem(autoIncrementItem,'Avg sale is 0',Decision.AUTO_INCREMENT_FAILED)
226
            continue
227
 
228
        daysOfStock = (float(autoIncrementItem.ourInventory))/autoIncrementItem.avgSale
229
        if daysOfStock > 5:
230
            markReasonForItem(autoIncrementItem,'Days of stock greater than 5',Decision.AUTO_INCREMENT_FAILED)
231
            continue
12484 kshitij.so 232
        if autoIncrementItem.isPromotion:
233
            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 234
            print "antecedentPrice ",antecedentPrice
12514 kshitij.so 235
            try:
236
                if antecedentPrice[0] is not None:
237
                    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:
238
                        markReasonForItem(autoIncrementItem,'Maximum price increase in last 24 hours should be 2%',Decision.AUTO_INCREMENT_FAILED)
239
                        continue
240
            except:
241
                if antecedentPrice is not None:
242
                    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:
243
                        markReasonForItem(autoIncrementItem,'Maximum price increase in last 24 hours should be 2%',Decision.AUTO_INCREMENT_FAILED)
244
                        continue
12484 kshitij.so 245
        else:
246
            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 247
            print "antecedentPrice else ",antecedentPrice
12526 anikendra 248
            if antecedentPrice is not None and antecedentPrice[0] is not None:
12484 kshitij.so 249
                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:
250
                    markReasonForItem(autoIncrementItem,'Maximum price increase in last 24 hours should be 2%',Decision.AUTO_INCREMENT_FAILED)
251
                    continue
12876 kshitij.so 252
        if autoIncrementItem.warehouseLocation==1:
253
            fcLocation = 0
254
        elif autoIncrementItem.warehouseLocation==2:
255
            fcLocation = 1
12909 kshitij.so 256
        elif autoIncrementItem.warehouseLocation==3:
257
            fcLocation = 2
12876 kshitij.so 258
        else:
259
            pass
260
        fbaSaleSnapshot = transaction_client.getAmazonFbaSalesLatestSnapshotForItemLocationWise(autoIncrementItem.item_id,fcLocation)
12480 kshitij.so 261
        if getLastDaySale(fbaSaleSnapshot)<=2:
12396 kshitij.so 262
            markReasonForItem(autoIncrementItem,'Last day sale is less than 3',Decision.AUTO_INCREMENT_FAILED)
263
            continue
264
 
265
        autoIncrementItem.ourEnoughStock = False
266
        autoIncrementItem.decision = Decision.AUTO_INCREMENT_SUCCESS
267
        autoIncrementItem.reason = 'All conditions for auto increment true'
268
        successfulAutoIncrease.append(autoIncrementItem)
269
    session.commit()
270
    return successfulAutoIncrease     
271
 
272
 
273
def markReasonForItem(amHistory,reason,decision):
274
    amHistory.decision = decision
275
    amHistory.reason = reason
276
 
12424 kshitij.so 277
def calculateAverageSale(sku):
278
    count,sale = 0,0
279
    oosStatus = saleMap.get(sku)
12803 kshitij.so 280
    if oosStatus is None:
281
        return 0.0
12424 kshitij.so 282
    for obj in oosStatus:
283
        if not obj.isOutOfStock:
284
            count+=1
285
            sale = sale+obj.totalOrderCount
286
    avgSalePerDay=0 if count==0 else (float(sale)/count)
287
    return round(avgSalePerDay,2)
288
 
289
 
12396 kshitij.so 290
def getOosString(oosStatus):
12803 kshitij.so 291
    if oosStatus is None:
292
        return ""
12396 kshitij.so 293
    lastNdaySale=""
294
    for obj in oosStatus:
12423 kshitij.so 295
        if obj.isOutOfStock:
12396 kshitij.so 296
            lastNdaySale += "X-"
297
        else:
12426 kshitij.so 298
            lastNdaySale += str(obj.totalOrderCount) + "-"
12396 kshitij.so 299
    return lastNdaySale[:-1]
300
 
301
def getLastDaySale(fbaSaleSnapshot):
302
    if fbaSaleSnapshot.item_id==0:
303
        return 0
304
    else:
12423 kshitij.so 305
        return fbaSaleSnapshot.totalOrderCount
12597 kshitij.so 306
 
307
def getNoOfDaysInStock(oosStatus):
308
    inStockCount = 0
12803 kshitij.so 309
    if oosStatus is None:
310
        return 0
12597 kshitij.so 311
    for obj in oosStatus:
312
        if not obj.isOutOfStock:
313
            inStockCount+=1
314
    return inStockCount
315
 
316
def getCheapestMfnCount(timestamp,itemId):
317
    query = session.query(func.count(AmazonScrapingHistory.cheapestMfnCount)).filter(AmazonScrapingHistory.item_id==itemId).filter(AmazonScrapingHistory.timestamp>=timestamp-timedelta(days=5))
318
    cheapestCount = query.filter(AmazonScrapingHistory.cheapestMfnCount==True).scalar()
319
    total = query.scalar()
320
    if total==0:
321
        return 0
322
    return float(cheapestCount)/total
323
 
324
 
12396 kshitij.so 325
 
12430 kshitij.so 326
#def syncAsin():
327
##    notListedOnAmazon = []
328
##    diffAsins = []
329
##    login_url = "https://sellercentral.amazon.in/gp/homepage.html"
330
##    br = SellerCentralInventoryReport.login(login_url)
331
##    report_url = "https://sellercentral.amazon.in/gp/upload-download-utils/requestReport.html?type=OpenListingReport&marketplaceID=44571&Request+Report="
332
##    br = SellerCentralInventoryReport.requestReport(br,report_url)
333
##    status_url="https://sellercentral.amazon.in/gp/upload-download-utils/reportStatusData.html"
334
##    br, page = SellerCentralInventoryReport.checkStatus(br,status_url)
335
##    br, batchId = SellerCentralInventoryReport.getReportBatchId(br,page)
336
##    print "*********************************"
337
##    print "Batch Id for request is ",batchId
338
##    print "*********************************"
339
##    ready = False
340
##    retryCount = 0
341
##    while not ready:
342
##        if retryCount == 10:
343
##            print "File not available for download after multiple retries"
344
##            sys.exit(1)
345
##        br, download_link = SellerCentralInventoryReport.downloadReport(br,batchId,status_url)
346
##        if download_link is not None:
347
##            ready= True
348
##            continue
349
##        print "File not ready for download yet.Will try again after 30 seconds."
350
##        retryCount+=1
351
##        time.sleep(30)
352
##    fPath = SellerCentralInventoryReport.fetchFile(download_link['href'],br,batchId)
353
#    fPath = "/tmp/9940651090.txt"
354
#    global amazonAsinPrice
355
#    for line in open(fPath):
356
#        l = line.split('\t')
357
#        if (str(l[0]).startswith('FBA') or str(l[0]).startswith('FBB')):
358
#            obj = __AmazonAsinPrice(l[1],l[2])
359
#            amazonAsinPrice[l[0]] = obj
360
##Can be used to sync asins, not doing due to multiple asins corresponding to one itemId
361
##    systemAsins = session.query(Item,Amazonlisted).join((Amazonlisted,Item.id==Amazonlisted.itemId)).all()
362
##    for systemAsin in systemAsins:
363
##        item = systemAsin[0]
364
##        amListed = systemAsin[1]
365
##        if amazonAsinPrice.get('FBA'+str(item.id)) is None:
366
##            temp=[]
367
##            temp.append(item)
368
##            temp.append(amListed)
369
##            notListedOnAmazon.append(temp)
370
##            continue
371
##        else:
372
##            temp=[]
373
##            temp.append(item)
374
##            temp.append(amListed)
375
##            if item.asin!=((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip():
376
##                diffAsins.append(temp)
377
##                continue
378
##            
379
##    for diffAsin in diffAsins:
380
##        item = diffAsin[0]
381
##        amListed = diffAsin[1]
382
##        item.asin = ((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip()
383
##        amListed.asin = ((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip()
384
##    session.commit()
385
##    session.close()
12363 kshitij.so 386
 
387
def fetchFbaSale():
388
    global saleMap
389
    transaction_client = TransactionClient().get_client()
390
    fbaSaleSnapshot = transaction_client.getAmazonFbaSalesSnapshotForDays(4)
391
    for saleSnapshot in fbaSaleSnapshot:
392
        if saleSnapshot.fcLocation == 0:
393
            if saleMap.has_key('FBA'+str(saleSnapshot.item_id)):
394
                temp = []
12367 kshitij.so 395
                val = saleMap.get('FBA'+str(saleSnapshot.item_id))
396
                for l in val:
12363 kshitij.so 397
                    temp.append(l)
398
                temp.append(saleSnapshot)
12366 kshitij.so 399
                saleMap['FBA'+str(saleSnapshot.item_id)]=temp
12363 kshitij.so 400
            else:
12368 kshitij.so 401
                temp = []
402
                temp.append(saleSnapshot)
403
                saleMap['FBA'+str(saleSnapshot.item_id)] = temp
12909 kshitij.so 404
        elif saleSnapshot.fcLocation == 1:
12363 kshitij.so 405
            if saleMap.has_key('FBB'+str(saleSnapshot.item_id)):
406
                temp = []
12367 kshitij.so 407
                val = saleMap.get('FBB'+str(saleSnapshot.item_id))
408
                for l in val:
12363 kshitij.so 409
                    temp.append(l)
12909 kshitij.so 410
                temp.append(saleSnapshot)
12368 kshitij.so 411
                saleMap['FBB'+str(saleSnapshot.item_id)]=temp
12909 kshitij.so 412
            else:
413
                temp = []
12363 kshitij.so 414
                temp.append(saleSnapshot)
12909 kshitij.so 415
                saleMap['FBB'+str(saleSnapshot.item_id)] = temp
416
        elif saleSnapshot.fcLocation == 2:
417
            if saleMap.has_key('FBG'+str(saleSnapshot.item_id)):
418
                temp = []
419
                val = saleMap.get('FBG'+str(saleSnapshot.item_id))
420
                for l in val:
421
                    temp.append(l)
422
                temp.append(saleSnapshot)
423
                saleMap['FBG'+str(saleSnapshot.item_id)]=temp
12363 kshitij.so 424
            else:
12368 kshitij.so 425
                temp = []
426
                temp.append(saleSnapshot)
12909 kshitij.so 427
                saleMap['FBG'+str(saleSnapshot.item_id)] = temp
428
        else:
429
            continue
12363 kshitij.so 430
 
12424 kshitij.so 431
 
12363 kshitij.so 432
def computeCourierCost(weight):
12378 kshitij.so 433
    try:
434
        cCost = 10.0;
435
        slabs = int((weight*1000)/500-.001)
436
        for slab in range(0,slabs):
437
            cCost = cCost + 10.0;
438
        return cCost;
439
    except:
440
        return 10.0
12363 kshitij.so 441
 
442
 
443
def populateStuff(time,runType):
444
    global amazonLongTermActivePromotions
12396 kshitij.so 445
    global amazonShortTermActivePromotions
12813 kshitij.so 446
    global wpiTodayExpiry
12363 kshitij.so 447
    itemInfo = []
448
    inventory_client = InventoryClient().get_client()
449
    fbaAvailableInventorySnapshot = inventory_client.getAllAvailableAmazonFbaItemInventory()
12489 kshitij.so 450
    if runType=='FAVOURITE':
451
        favourites = session.query(Amazonlisted.itemId).filter(or_(Amazonlisted.autoFavourite==True, Amazonlisted.manualFavourite==True)).all()
12363 kshitij.so 452
    for fbaInventoryItem in fbaAvailableInventorySnapshot:
12489 kshitij.so 453
        if runType=='FAVOURITE':
454
            if not (fbaInventoryItem.item_id in favourites):
455
                continue 
12363 kshitij.so 456
        d_amazon_listed = Amazonlisted.get_by(itemId=fbaInventoryItem.item_id)
457
        if d_amazon_listed is None:
12711 kshitij.so 458
            if fbaInventoryItem.location==0:
459
                sku = 'FBA'+str(fbaInventoryItem.item_id)
460
                notListed.append(sku)
461
            elif fbaInventoryItem.location==1:
462
                sku = 'FBB'+str(fbaInventoryItem.item_id)
463
                notListed.append(sku)
12909 kshitij.so 464
            elif fbaInventoryItem.location==2:
465
                sku = 'FBG'+str(fbaInventoryItem.item_id)
466
                notListed.append(sku)
12711 kshitij.so 467
            else:
468
                pass
12363 kshitij.so 469
            continue
470
        if d_amazon_listed.overrrideWanlc:
12845 kshitij.so 471
            isNlcOverridden = True
12363 kshitij.so 472
            wanlc = d_amazon_listed.exceptionalWanlc
12507 kshitij.so 473
            if wanlc is None:
474
                wanlc = 0.0
12363 kshitij.so 475
        else:
12845 kshitij.so 476
            isNlcOverridden = False
12363 kshitij.so 477
            wanlc = inventory_client.getWanNlcForSource(fbaInventoryItem.item_id,OrderSource.AMAZON)
478
        it = Item.query.filter_by(id=fbaInventoryItem.item_id).one()
479
        category = Category.query.filter_by(id=it.category).one()
480
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
12489 kshitij.so 481
        sourcePercentage = None
482
        sip = SourceItemPercentage.query.filter(SourceItemPercentage.item_id==it.id).filter(SourceItemPercentage.source==OrderSource.AMAZON).filter(SourceItemPercentage.startDate<=time).filter(SourceItemPercentage.expiryDate>=time).first()
483
        if sip is not None:
484
            sourcePercentage = sip
12363 kshitij.so 485
        else:
12489 kshitij.so 486
            scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.AMAZON).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
487
            if scp is not None:
488
                sourcePercentage = scp
489
            else:
490
                spm = SourcePercentageMaster.get_by(source=OrderSource.AMAZON)
491
                sourcePercentage = spm
12375 kshitij.so 492
        if fbaInventoryItem.location==0:
12377 kshitij.so 493
            sku = 'FBA'+str(fbaInventoryItem.item_id)
12363 kshitij.so 494
            state_id = 1
12375 kshitij.so 495
        elif fbaInventoryItem.location==1:
12377 kshitij.so 496
            sku = 'FBB'+str(fbaInventoryItem.item_id)
12363 kshitij.so 497
            state_id = 2
12909 kshitij.so 498
        elif fbaInventoryItem.location==2:
499
            sku = 'FBG'+str(fbaInventoryItem.item_id)
500
            state_id = 3
12363 kshitij.so 501
        else:
502
            continue
503
        cc = computeCourierCost(it.weight)
12379 kshitij.so 504
 
12845 kshitij.so 505
        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,None,isNlcOverridden)
12363 kshitij.so 506
        itemInfo.append(amazonItemInfo)
12556 anikendra 507
    #amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.LONGTERM).filter(AmazonPromotion.promotionActive==True) \
508
    #.group_by(AmazonPromotion.sku).order_by(desc(AmazonPromotion.addedOn)).all()
12363 kshitij.so 509
    amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.LONGTERM).filter(AmazonPromotion.promotionActive==True) \
12556 anikendra 510
    .order_by(desc(AmazonPromotion.addedOn)).all()
12363 kshitij.so 511
    for amPromotion in amPromotions:
12606 kshitij.so 512
        if amazonLongTermActivePromotions.has_key(amPromotion.sku):
513
            continue
12433 kshitij.so 514
        amazonLongTermActivePromotions[amPromotion.sku] = __Promotion(amPromotion.salePrice,amPromotion.subsidy,amPromotion.promotionType,amPromotion.endDate)
12556 anikendra 515
    #amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.SHORTTERM).filter(AmazonPromotion.promotionActive==True) \
516
    #.group_by(AmazonPromotion.sku).order_by(desc(AmazonPromotion.addedOn)).all()
12396 kshitij.so 517
    amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.SHORTTERM).filter(AmazonPromotion.promotionActive==True) \
12556 anikendra 518
    .order_by(desc(AmazonPromotion.addedOn)).all()
12396 kshitij.so 519
    for amPromotion in amPromotions:
12606 kshitij.so 520
        if amazonShortTermActivePromotions.has_key(amPromotion.sku):
521
            continue
12433 kshitij.so 522
        amazonShortTermActivePromotions[amPromotion.sku] = __Promotion(amPromotion.salePrice,amPromotion.subsidy,amPromotion.promotionType,amPromotion.endDate)
12721 kshitij.so 523
    amPromotions = AmazonPromotion.query.filter(AmazonPromotion.endDate>=(time-timedelta(days=1))).filter(AmazonPromotion.endDate<=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.LONGTERM).filter(AmazonPromotion.promotionActive==True) \
12717 kshitij.so 524
    .order_by(desc(AmazonPromotion.addedOn)).all()
12720 kshitij.so 525
    for amPromotion in amPromotions: 
526
        if wpiTodayExpiry.has_key(amPromotion.sku):
527
            continue
12717 kshitij.so 528
        wpiTodayExpiry[amPromotion.sku] = __Promotion(amPromotion.salePrice,amPromotion.subsidy,amPromotion.promotionType,amPromotion.endDate)
12363 kshitij.so 529
    session.close()
12450 kshitij.so 530
    print "No of items populated ",len(itemInfo)
12363 kshitij.so 531
    return itemInfo
532
 
12430 kshitij.so 533
def getPriceAndAsin(itemInfo):
534
    skus = []
535
    for item in itemInfo:
536
        skus.append(item.sku)
537
    ourPricingForSku = amScraper.get_my_pricing_for_sku('A21TJRUUN4KGV', skus)
538
    for item in itemInfo:
539
        ourPricing = ourPricingForSku.get(item.sku)
12441 kshitij.so 540
        if ourPricing is None or len(ourPricing.keys())==0:
12430 kshitij.so 541
            item.ourSp = 0
542
            item.promoPrice = 0
543
            item.isPromotion = False
12473 kshitij.so 544
            item.asin = ''
12430 kshitij.so 545
        else:
546
            item.ourSp = ourPricing.get('sellingPrice')
547
            item.promoPrice = ourPricing.get('promoPrice')
548
            item.isPromotion = ourPricing.get('promotion')
12473 kshitij.so 549
            item.asin = ourPricing.get('asin')
12450 kshitij.so 550
 
12430 kshitij.so 551
 
552
 
12597 kshitij.so 553
def decideCategory(itemInfo,timestamp):
12363 kshitij.so 554
    exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = [],[],[],[],[],[],[] 
12430 kshitij.so 555
    skus = []
12363 kshitij.so 556
    for item in itemInfo:
12430 kshitij.so 557
        skus.append(item.sku)
12597 kshitij.so 558
    pricingResponse = amScraper.get_competitive_pricing_for_sku('A21TJRUUN4KGV', skus)
559
    aggResponse = pricingResponse[0]
560
    otherInfo = pricingResponse[1]
12430 kshitij.so 561
    ourPricingForSku = amScraper.get_my_pricing_for_sku('A21TJRUUN4KGV', skus)
12403 kshitij.so 562
 
12363 kshitij.so 563
    for val in itemInfo:
12430 kshitij.so 564
        scrapInfo = aggResponse.get(val.sku)
12597 kshitij.so 565
        competitvePricingInfo = otherInfo.get(val.sku)
12443 kshitij.so 566
        if scrapInfo is None or len(scrapInfo)==0 or val.nlc==0 or len(ourPricingForSku.get(val.sku).keys())==0:
12363 kshitij.so 567
            temp = []
568
            if val.nlc==0 or val.nlc is None:
12456 kshitij.so 569
                print "WANLC is 0"
12736 kshitij.so 570
                val.exceptionType = 1
571
                #temp.append("WANLC is 0")
12657 kshitij.so 572
            elif ourPricingForSku.get(val.sku) is None or len(ourPricingForSku.get(val.sku).keys())==0:
12456 kshitij.so 573
                print "Unable to fetch our price"
12736 kshitij.so 574
                val.exceptionType = 2
575
                #temp.append("Unable to fetch our price")
12363 kshitij.so 576
            else:
12639 kshitij.so 577
                print "No other seller or Unable to fetch competitive pricing"
12736 kshitij.so 578
                val.exceptionType = 3
579
                #temp.append("No other seller or Unable to fetch competitive pricing")
580
            temp.append(val)
12803 kshitij.so 581
            if val.exceptionType ==3:
582
                val.ourSp = ourPricingForSku.get(val.sku).get('sellingPrice')
583
                val.promoPrice = ourPricingForSku.get(val.sku).get('promoPrice')
584
                val.isPromo = ourPricingForSku.get(val.sku).get('promotion')
585
                sku = val.sku
586
                try:
587
                    val.vatRate = getVatRate(val.sku[3:],val.state_id,val.promoPrice)
588
                except:
589
                    val.exceptionType = 6
590
                if (ourPricingForSku.get(val.sku).get('promotion')!=(amazonLongTermActivePromotions.has_key(val.sku) or amazonShortTermActivePromotions.has_key(val.sku))):
591
                    val.exceptionType = 4
592
                if val.exceptionType ==3:
593
                    lowestPossibleSp = getLowestPossibleSp(None,val,val.sourcePercentage)
594
                    amPricing = __AmazonPricing(val.ourSp,lowestPossibleSp)
595
                    amDetails = __AmazonDetails(sku, float(val.ourSp), 1, '',float(val.ourSp),'', float(0), '', float(0),1,False,val.promoPrice,val.isPromo, \
596
                    '0-0' ,0, '0-0', 0, '0-0' , 0, 'Amazon', '', '', \
597
                    0,0,0,False,False,True,None)
598
                    temp.append(amDetails)
599
                    temp.append(amPricing)
12363 kshitij.so 600
            exceptionList.append(temp)
601
            continue
12430 kshitij.so 602
        val.ourSp = ourPricingForSku.get(val.sku).get('sellingPrice')
603
        val.promoPrice = ourPricingForSku.get(val.sku).get('promoPrice')
604
        val.isPromo = ourPricingForSku.get(val.sku).get('promotion')
12363 kshitij.so 605
        iterator = 0
606
        sku, lowestSellerName,secondLowestSellerName, thirdLowestSellerName = ('',)*4
12432 kshitij.so 607
        ourSp, ourRank, lowestSellerSp, secondLowestSellerSp, thirdLowestSellerSp, lowestPossibleSp = (0,)*6
12430 kshitij.so 608
        lowestSellerShippingTime, lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , \
609
        thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType = (0,)*9
610
        isPromo = False
12363 kshitij.so 611
        sku = val.sku
612
        multipleListings = False
12430 kshitij.so 613
        ourSkuDetails = ourPricingForSku.get(val.sku)
12475 kshitij.so 614
        if (ourSkuDetails.get('promotion')!=(amazonLongTermActivePromotions.has_key(val.sku) or amazonShortTermActivePromotions.has_key(val.sku))):
12432 kshitij.so 615
            temp = []
12736 kshitij.so 616
            val.exceptionType = 4
12432 kshitij.so 617
            temp.append(val)
12456 kshitij.so 618
            print "promo misconfigured"
12736 kshitij.so 619
            #temp.append("Promo misconfigured")
12457 kshitij.so 620
            exceptionList.append(temp)
12432 kshitij.so 621
            continue
12475 kshitij.so 622
 
12430 kshitij.so 623
        scrapInfo.append(ourSkuDetails)
624
        sortedScrapInfo =  sorted(scrapInfo, key=itemgetter('promoPrice','notOurSku'))
625
        for info in sortedScrapInfo:
12465 kshitij.so 626
            if  not info['notOurSku']:
12442 kshitij.so 627
                ourSp = info['sellingPrice']
628
                promoPrice = info['promoPrice']
629
                isPromo = info['promotion']
12430 kshitij.so 630
                ourRank = iterator + 1
12363 kshitij.so 631
 
632
            if iterator == 0:
12430 kshitij.so 633
                lowestSellerSp = info['promoPrice']
634
                lowestSellerShippingTime = info['shippingTime']
635
                lowestSellerRating = info['rating']
636
                lowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 637
 
638
            if iterator == 1:
12430 kshitij.so 639
                secondLowestSellerSp = info['promoPrice']
640
                secondLowestSellerShippingTime = info['shippingTime']
641
                secondLowestSellerRating = info['rating']
642
                secondLowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 643
 
644
            if iterator == 2:
12430 kshitij.so 645
                thirdLowestSellerSp = info['promoPrice']
646
                thirdLowestSellerShippingTime = info['shippingTime']
647
                thirdLowestSellerRating = info['rating']
648
                thirdLowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 649
 
650
            iterator += 1
12401 kshitij.so 651
        print "terminating iterator"
12483 kshitij.so 652
 
12408 kshitij.so 653
        print "Creating object am details",val.sku
12430 kshitij.so 654
        amDetails = __AmazonDetails(sku, float(ourSp), ourRank, lowestSellerName,float(lowestSellerSp),secondLowestSellerName, float(secondLowestSellerSp), thirdLowestSellerName, float(thirdLowestSellerSp),len(scrapInfo),multipleListings,promoPrice,isPromo, \
12597 kshitij.so 655
                    lowestSellerShippingTime ,lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType, \
656
                    competitvePricingInfo['lowestMfnIgnored'],competitvePricingInfo['lowestMfn'],competitvePricingInfo['lowestFba'],competitvePricingInfo['isLowestMfnIgnored'],competitvePricingInfo['isLowestMfn'],competitvePricingInfo['isLowestFba'],None)
657
 
658
        competitivePrice = decideCompetitvePricing(amDetails,val.ourInventory,timestamp)
659
        amDetails.competitivePrice = competitivePrice
12803 kshitij.so 660
 
661
        try:
662
            val.vatRate = getVatRate(val.sku[3:], val.state_id, amDetails.promoPrice)
663
        except:
12597 kshitij.so 664
            temp = []
12803 kshitij.so 665
            val.exceptionType = 6
12597 kshitij.so 666
            temp.append(val)
667
            exceptionList.append(temp)
668
            continue
12803 kshitij.so 669
 
670
        if amDetails.competitivePrice==0.0 and amDetails.ourRank > 1:
12363 kshitij.so 671
            temp = []
12803 kshitij.so 672
            val.exceptionType = 5
12363 kshitij.so 673
            temp.append(val)
12803 kshitij.so 674
            temp.append(amDetails)
675
            lowestPossibleSp = getLowestPossibleSp(amDetails,val,val.sourcePercentage)
676
            amPricing = __AmazonPricing(ourSp,lowestPossibleSp)
677
            temp.append(amPricing)
12363 kshitij.so 678
            exceptionList.append(temp)
679
            continue
680
 
681
        lowestPossibleSp = getLowestPossibleSp(amDetails,val,val.sourcePercentage)
12408 kshitij.so 682
        print "Creating pricing obj"
12432 kshitij.so 683
        amPricing = __AmazonPricing(ourSp,lowestPossibleSp)
12483 kshitij.so 684
        print "sku ",val.sku
685
        print "oursp ",ourSp
686
        print "promoPrice ",promoPrice
687
        print "lowestpossbile sp ",lowestPossibleSp
688
        print "objlowestPossiblesp ",amPricing.lowestPossibleSp
12363 kshitij.so 689
 
12467 kshitij.so 690
        if amDetails.promoPrice < amPricing.lowestPossibleSp:
12363 kshitij.so 691
            temp = []
692
            temp.append(val)
693
            temp.append(amDetails)
694
            temp.append(amPricing)
695
            negativeMargin.append(temp)
12483 kshitij.so 696
            print "val sku cat negative ",val.sku
12363 kshitij.so 697
            continue
698
 
699
        if amDetails.ourRank==1:
700
            temp = []
701
            temp.append(val)
702
            temp.append(amDetails)
703
            temp.append(amPricing)
704
            cheapest.append(temp)
12483 kshitij.so 705
            print "val sku cat cheapest ",val.sku
12363 kshitij.so 706
            continue
707
 
12597 kshitij.so 708
        if val.parent_category in [10006,10009,11001]:
709
            if (amDetails.competitivePrice > amPricing.lowestPossibleSp) and ((((float(float(amDetails.promoPrice) - amDetails.competitivePrice))/float(amDetails.promoPrice))<=.0025) or ((float(amDetails.promoPrice) - amDetails.competitivePrice)<=25)):
710
                temp = []
711
                temp.append(val)
712
                temp.append(amDetails)
713
                temp.append(amPricing)
714
                amongCheapestAndCanCompete.append(temp)
715
                print "val sku cat amongCheapestAndCanCompete  ",val.sku
716
                continue
717
        else:
718
            if (amDetails.competitivePrice > amPricing.lowestPossibleSp) and ((((float(float(amDetails.promoPrice) - amDetails.competitivePrice))/float(amDetails.promoPrice))<=.01) or ((float(amDetails.promoPrice) - amDetails.competitivePrice)<=10)):
719
                temp = []
720
                temp.append(val)
721
                temp.append(amDetails)
722
                temp.append(amPricing)
723
                amongCheapestAndCanCompete.append(temp)
724
                print "val sku cat amongCheapestAndCanCompete  ",val.sku
725
                continue
12363 kshitij.so 726
 
12597 kshitij.so 727
        if (amDetails.competitivePrice > amPricing.lowestPossibleSp):
12363 kshitij.so 728
            temp = []
729
            temp.append(val)
730
            temp.append(amDetails)
731
            temp.append(amPricing)
732
            canCompete.append(temp)
12483 kshitij.so 733
            print "val sku cat can compete  ",val.sku
12363 kshitij.so 734
            continue
735
 
12597 kshitij.so 736
        if amDetails.competitivePrice*(1+.01) >= amPricing.lowestPossibleSp:
12396 kshitij.so 737
            temp = []
738
            temp.append(val)
739
            temp.append(amDetails)
740
            temp.append(amPricing)
741
            almostCompete.append(temp)
12483 kshitij.so 742
            print "val sku cat almost compete  ",val.sku
12396 kshitij.so 743
            continue
744
 
12363 kshitij.so 745
        temp = []
746
        temp.append(val)
747
        temp.append(amDetails)
748
        temp.append(amPricing)
12483 kshitij.so 749
        print "val sku cat cant compete  ",val.sku
12363 kshitij.so 750
        cantCompete.append(temp)
12414 kshitij.so 751
    print "Created category..."
12363 kshitij.so 752
 
753
    return exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete
12396 kshitij.so 754
 
12597 kshitij.so 755
 
756
def decideCompetitvePricing(amDetails,ourInventory,timestamp):
757
    '''
758
        lowestMfnIgnoredOffer, lowestMfnOffer, lowestFbaOffer, isLowestMfnIgnored, isLowestMfn, isLowestFba
759
    '''
760
 
761
    if amDetails.ourRank==1:
762
        return 0.0
763
    else:
764
        if amDetails.isLowestMfn and amDetails.isLowestFba:
765
            if amDetails.lowestMfnOffer >= amDetails.lowestFbaOffer:
766
                return amDetails.lowestFbaOffer
767
            else:
768
                #TODO Check last five days history.
769
                ratio = getCheapestMfnCount(timestamp,amDetails.sku[3:])
770
                daysInStock = getNoOfDaysInStock(saleMap.get(amDetails.sku))
771
                try:
772
                    daysOfStock = (float(ourInventory))/calculateAverageSale(amDetails.sku)
773
                except:
774
                    daysOfStock = float("inf")
775
                if daysInStock >= 4 and daysOfStock > 20 and ratio >=.8:
776
                    return amDetails.lowestMfnOffer
777
                else:
12659 kshitij.so 778
                    print "Unable to calculate competitive pricing for %s in block 1"%(amDetails.sku)
779
                    return amDetails.lowestFbaOffer
12597 kshitij.so 780
        elif amDetails.isLowestFba:
781
            return amDetails.lowestFbaOffer
782
        elif amDetails.isLowestMfn:
783
            #TODO Check last five days history
784
            ratio = getCheapestMfnCount(timestamp,amDetails.sku[3:])
785
            daysInStock = getNoOfDaysInStock(saleMap.get(amDetails.sku))
786
            try:
787
                daysOfStock = (float(ourInventory))/calculateAverageSale(amDetails.sku)
788
            except:
789
                daysOfStock = float("inf")
790
            if daysInStock >= 4 and daysOfStock > 20 and ratio >.8:
791
                return amDetails.lowestMfnOffer
792
            else:
12659 kshitij.so 793
                print "Unable to calculate competitive pricing for %s in block 2"%(amDetails.sku)
794
                return 0.0
12597 kshitij.so 795
        else:
796
            return 0.0
797
 
12556 anikendra 798
def getBreakevenPrice(item,val,spm):
799
    breakEvenPrice = (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));
800
    return round(breakEvenPrice,2)
12363 kshitij.so 801
 
802
def getLowestPossibleSp(amazonDetails,val,spm):
12432 kshitij.so 803
    if val.isPromo:
804
        if amazonLongTermActivePromotions.has_key(val.sku):
12466 kshitij.so 805
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
12432 kshitij.so 806
        else:
12466 kshitij.so 807
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
12597 kshitij.so 808
    else:
809
        subsidy = 0.0
810
 
811
    lowestPossibleSp = (val.nlc-subsidy+(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));
12556 anikendra 812
 
813
    #print (val.nlc-subsidy+(val.courierCost)*(1+(spm.serviceTax/100))*(1+(val.vatRate/100))+(15+val.otherCost)*(1+(val.vatRate)/100))
814
    #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 815
    return round(lowestPossibleSp,2)
816
 
12489 kshitij.so 817
def getNewLowestPossibleSp(item,serviceTax,newVatRate):
818
    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));
819
    if item.isPromotion:
820
        sku = ''
821
        if item.warehouseLocation==1:
822
            sku='FBA'+str(item.item_id)
12909 kshitij.so 823
        elif item.warehouseLocation==2:
824
            sku='FBB'+str(item.item_id)
12489 kshitij.so 825
        else:
12909 kshitij.so 826
            sku='FBG'+str(item.item_id)
12489 kshitij.so 827
        if amazonLongTermActivePromotions.has_key(sku):
828
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
829
        else:
830
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
12556 anikendra 831
        print "subsidy ",subsidy
832
        lowestPossibleSp = (item.wanlc-subsidy+(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));
12489 kshitij.so 833
    return round(lowestPossibleSp,2)
834
 
12363 kshitij.so 835
def getTargetTp(targetSp,spm,val):
12424 kshitij.so 836
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))
12363 kshitij.so 837
    return round(targetTp,2)
838
 
839
def commitExceptionList(exceptionList,timestamp,runType):
840
    for exceptionItem in exceptionList:
841
        val = exceptionItem[0]
842
        amazonScrapingHistory = AmazonScrapingHistory()
843
        amazonScrapingHistory.item_id = val.sku[3:]
12803 kshitij.so 844
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 845
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 846
        amazonScrapingHistory.parentCategoryId = val.parent_category
12639 kshitij.so 847
        amazonScrapingHistory.ourSellingPrice = val.ourSp
848
        amazonScrapingHistory.promoPrice = val.promoPrice
12736 kshitij.so 849
        amazonScrapingHistory.reason = exceptionMap.get(val.exceptionType)
12363 kshitij.so 850
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
851
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.EXCEPTION
12803 kshitij.so 852
        amazonScrapingHistory.exceptionType = val.exceptionType
853
        amazonScrapingHistory.ourInventory = val.ourInventory
12845 kshitij.so 854
        amazonScrapingHistory.isNlcOverridden = val.isNlcOverridden
12803 kshitij.so 855
        if val.exceptionType in (3,5):
856
            amDetails = exceptionItem[1]
857
            amPricing = exceptionItem[2]
858
            if amazonLongTermActivePromotions.has_key(val.sku):
859
                subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
860
            elif amazonShortTermActivePromotions.has_key(val.sku):
861
                subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
862
            else:
863
                subsidy = 0
864
            spm = val.sourcePercentage
865
            amazonScrapingHistory.subsidy = subsidy
866
            amazonScrapingHistory.vatRate = val.vatRate
867
            amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
868
            amazonScrapingHistory.ourRank = amDetails.ourRank
869
            amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
870
            amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
871
            amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
872
            amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
873
            amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
874
            amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
875
            amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
876
            amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
877
            amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
878
            amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
879
            amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
880
            amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
881
            if (amDetails.lowestMfnOffer < amDetails.lowestFbaOffer or amDetails.lowestMfnOffer < amazonScrapingHistory.promoPrice) and amDetails.isLowestMfn:
882
                amazonScrapingHistory.cheapestMfnCount = True
883
            else:
884
                amazonScrapingHistory.cheapestMfnCount = False
885
            amazonScrapingHistory.wanlc = val.nlc
886
            amazonScrapingHistory.otherCost = val.otherCost
887
            amazonScrapingHistory.commission = spm.commission
888
            amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
889
            amazonScrapingHistory.returnProvision = spm.returnProvision
890
            amazonScrapingHistory.isLowestMfnIgnored = amDetails.isLowestMfnIgnored
891
            amazonScrapingHistory.isLowestMfn = amDetails.isLowestMfn
892
            amazonScrapingHistory.isLowestFba = amDetails.isLowestFba
893
            amazonScrapingHistory.lowestMfnIgnoredOffer =amDetails.lowestMfnIgnoredOffer
894
            amazonScrapingHistory.lowestMfnOffer = amDetails.lowestMfnOffer
895
            amazonScrapingHistory.lowestFbaOffer = amDetails.lowestFbaOffer
896
            amazonScrapingHistory.courierCost = val.courierCost
897
            amazonScrapingHistory.risky = val.risky
898
            amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
899
            amazonScrapingHistory.totalSeller = amDetails.totalSeller
900
            amazonScrapingHistory.timestamp = timestamp
901
            amazonScrapingHistory.multipleListings = amDetails.multipleListings
902
            amazonScrapingHistory.isPromotion = val.isPromo
903
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12363 kshitij.so 904
        amazonScrapingHistory.timestamp = timestamp
905
    session.commit()
906
 
907
def commitNegativeMargin(negativeMargin,timestamp,runType):
908
    for negativeMarginItem in negativeMargin:
909
        val = negativeMarginItem[0]
910
        amDetails = negativeMarginItem[1]
911
        amPricing = negativeMarginItem[2]
912
        spm = val.sourcePercentage
12510 kshitij.so 913
        if amazonLongTermActivePromotions.has_key(val.sku):
914
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
915
        elif amazonShortTermActivePromotions.has_key(val.sku):
916
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
917
        else:
918
            subsidy = 0
12363 kshitij.so 919
        amazonScrapingHistory = AmazonScrapingHistory()
920
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 921
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 922
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 923
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 924
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 925
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12510 kshitij.so 926
        amazonScrapingHistory.subsidy = subsidy
927
        amazonScrapingHistory.vatRate = val.vatRate
12363 kshitij.so 928
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
929
        amazonScrapingHistory.ourRank = amDetails.ourRank
930
        amazonScrapingHistory.ourInventory = val.ourInventory
931
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12468 kshitij.so 932
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
933
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
934
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 935
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 936
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
937
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
938
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 939
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 940
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
941
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
942
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12597 kshitij.so 943
        if (amDetails.lowestMfnOffer < amDetails.lowestFbaOffer or amDetails.lowestMfnOffer < amazonScrapingHistory.promoPrice) and amDetails.isLowestMfn:
944
            amazonScrapingHistory.cheapestMfnCount = True
945
        else:
946
            amazonScrapingHistory.cheapestMfnCount = False
12363 kshitij.so 947
        amazonScrapingHistory.wanlc = val.nlc
12845 kshitij.so 948
        amazonScrapingHistory.isNlcOverridden = val.isNlcOverridden
12447 kshitij.so 949
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 950
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 951
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 952
        amazonScrapingHistory.returnProvision = spm.returnProvision
953
        amazonScrapingHistory.courierCost = val.courierCost
954
        amazonScrapingHistory.risky = val.risky
955
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
956
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
957
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
958
        amazonScrapingHistory.timestamp = timestamp
959
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
960
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 961
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 962
    session.commit()
963
 
964
 
965
def commitCheapest(cheapest,timestamp,runType):
966
    for cheapestItem in cheapest:
967
        val = cheapestItem[0]
968
        amDetails = cheapestItem[1]
969
        amPricing = cheapestItem[2]
970
        spm = val.sourcePercentage
12510 kshitij.so 971
        if amazonLongTermActivePromotions.has_key(val.sku):
972
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
973
        elif amazonShortTermActivePromotions.has_key(val.sku):
974
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
975
        else:
976
            subsidy = 0
12363 kshitij.so 977
        amazonScrapingHistory = AmazonScrapingHistory()
978
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 979
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 980
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 981
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 982
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 983
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12510 kshitij.so 984
        amazonScrapingHistory.subsidy = subsidy
985
        amazonScrapingHistory.vatRate = val.vatRate
12363 kshitij.so 986
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
987
        amazonScrapingHistory.ourRank = amDetails.ourRank
988
        amazonScrapingHistory.ourInventory = val.ourInventory
989
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 990
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
991
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
992
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 993
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 994
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
995
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
996
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 997
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 998
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
999
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
1000
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12597 kshitij.so 1001
        amazonScrapingHistory.cheapestMfnCount = False
12447 kshitij.so 1002
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 1003
        amazonScrapingHistory.wanlc = val.nlc
12845 kshitij.so 1004
        amazonScrapingHistory.isNlcOverridden = val.isNlcOverridden
12363 kshitij.so 1005
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 1006
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 1007
        amazonScrapingHistory.returnProvision = spm.returnProvision
1008
        amazonScrapingHistory.courierCost = val.courierCost
1009
        amazonScrapingHistory.risky = val.risky
1010
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
1011
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
1012
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.BUY_BOX
1013
        amazonScrapingHistory.timestamp = timestamp
1014
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12597 kshitij.so 1015
        proposed_sp = max(amDetails.secondLowestSellerSp - 1, amPricing.lowestPossibleSp)
12433 kshitij.so 1016
        if amazonScrapingHistory.isPromotion:
1017
            if amazonLongTermActivePromotions.has_key(val.sku):
12466 kshitij.so 1018
                proposed_sp = min(proposed_sp,(amazonLongTermActivePromotions.get(val.sku)).salePrice)
12433 kshitij.so 1019
            else:
12466 kshitij.so 1020
                proposed_sp = min(proposed_sp,(amazonShortTermActivePromotions.get(val.sku)).salePrice)
12468 kshitij.so 1021
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 1022
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 1023
        #amazonScrapingHistory.proposedTp = proposed_tp
1024
        #amazonScrapingHistory.marginIncreasedPotential = proposed_tp - amPricing.ourTp
12363 kshitij.so 1025
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
1026
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 1027
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 1028
    session.commit()
1029
 
1030
 
1031
 
1032
def commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,runType):
1033
    for amongCheapestAndCanCompeteItem in amongCheapestAndCanCompete:
1034
        val = amongCheapestAndCanCompeteItem[0]
1035
        amDetails = amongCheapestAndCanCompeteItem[1]
1036
        amPricing = amongCheapestAndCanCompeteItem[2]
1037
        spm = val.sourcePercentage
12510 kshitij.so 1038
        if amazonLongTermActivePromotions.has_key(val.sku):
1039
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
1040
        elif amazonShortTermActivePromotions.has_key(val.sku):
1041
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
1042
        else:
1043
            subsidy = 0
12363 kshitij.so 1044
        amazonScrapingHistory = AmazonScrapingHistory()
1045
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 1046
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 1047
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 1048
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 1049
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 1050
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12510 kshitij.so 1051
        amazonScrapingHistory.subsidy = subsidy
1052
        amazonScrapingHistory.vatRate = val.vatRate
12363 kshitij.so 1053
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
1054
        amazonScrapingHistory.ourRank = amDetails.ourRank
1055
        amazonScrapingHistory.ourInventory = val.ourInventory
1056
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 1057
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
1058
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
1059
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 1060
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 1061
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
1062
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
1063
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12470 kshitij.so 1064
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 1065
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
1066
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
1067
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12597 kshitij.so 1068
        amazonScrapingHistory.isLowestMfnIgnored = amDetails.isLowestMfnIgnored
1069
        amazonScrapingHistory.isLowestMfn = amDetails.isLowestMfn
1070
        amazonScrapingHistory.isLowestFba = amDetails.isLowestFba
1071
        amazonScrapingHistory.lowestMfnIgnoredOffer =amDetails.lowestMfnIgnoredOffer
1072
        amazonScrapingHistory.lowestMfnOffer = amDetails.lowestMfnOffer
1073
        amazonScrapingHistory.lowestFbaOffer = amDetails.lowestFbaOffer
1074
        amazonScrapingHistory.competitivePrice = amDetails.competitivePrice
1075
        if (amDetails.lowestMfnOffer < amDetails.lowestFbaOffer or amDetails.lowestMfnOffer < amazonScrapingHistory.promoPrice) and amDetails.isLowestMfn:
1076
            amazonScrapingHistory.cheapestMfnCount = True
1077
        else:
1078
            amazonScrapingHistory.cheapestMfnCount = False
12447 kshitij.so 1079
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 1080
        amazonScrapingHistory.wanlc = val.nlc
12845 kshitij.so 1081
        amazonScrapingHistory.isNlcOverridden = val.isNlcOverridden
12363 kshitij.so 1082
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 1083
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 1084
        amazonScrapingHistory.returnProvision = spm.returnProvision
1085
        amazonScrapingHistory.courierCost = val.courierCost
1086
        amazonScrapingHistory.risky = val.risky
1087
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
1088
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
1089
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE
1090
        amazonScrapingHistory.timestamp = timestamp
1091
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12597 kshitij.so 1092
        proposed_sp = max(amDetails.competitivePrice - 1, amPricing.lowestPossibleSp)
12468 kshitij.so 1093
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 1094
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 1095
        #amazonScrapingHistory.proposedTp = proposed_tp
12363 kshitij.so 1096
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
1097
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 1098
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 1099
    session.commit()
1100
 
1101
def commitCanCompete(canCompete,timestamp,runType):
1102
    for canCompeteItem in canCompete:
1103
        val = canCompeteItem[0]
1104
        amDetails = canCompeteItem[1]
1105
        amPricing = canCompeteItem[2]
1106
        spm = val.sourcePercentage
12510 kshitij.so 1107
        if amazonLongTermActivePromotions.has_key(val.sku):
1108
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
1109
        elif amazonShortTermActivePromotions.has_key(val.sku):
1110
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
1111
        else:
1112
            subsidy = 0
12363 kshitij.so 1113
        amazonScrapingHistory = AmazonScrapingHistory()
1114
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 1115
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 1116
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 1117
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 1118
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 1119
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12510 kshitij.so 1120
        amazonScrapingHistory.subsidy = subsidy
1121
        amazonScrapingHistory.vatRate = val.vatRate
12363 kshitij.so 1122
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
1123
        amazonScrapingHistory.ourRank = amDetails.ourRank
1124
        amazonScrapingHistory.ourInventory = val.ourInventory
1125
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 1126
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
1127
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
1128
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 1129
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 1130
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
1131
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
1132
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 1133
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 1134
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
1135
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
1136
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12597 kshitij.so 1137
        amazonScrapingHistory.isLowestMfnIgnored = amDetails.isLowestMfnIgnored
1138
        amazonScrapingHistory.isLowestMfn = amDetails.isLowestMfn
1139
        amazonScrapingHistory.isLowestFba = amDetails.isLowestFba
1140
        amazonScrapingHistory.lowestMfnIgnoredOffer =amDetails.lowestMfnIgnoredOffer
1141
        amazonScrapingHistory.lowestMfnOffer = amDetails.lowestMfnOffer
1142
        amazonScrapingHistory.lowestFbaOffer = amDetails.lowestFbaOffer
1143
        amazonScrapingHistory.competitivePrice = amDetails.competitivePrice
1144
        if (amDetails.lowestMfnOffer < amDetails.lowestFbaOffer or amDetails.lowestMfnOffer < amazonScrapingHistory.promoPrice) and amDetails.isLowestMfn:
1145
            amazonScrapingHistory.cheapestMfnCount = True
1146
        else:
1147
            amazonScrapingHistory.cheapestMfnCount = False
12447 kshitij.so 1148
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 1149
        amazonScrapingHistory.wanlc = val.nlc
12845 kshitij.so 1150
        amazonScrapingHistory.isNlcOverridden = val.isNlcOverridden
12363 kshitij.so 1151
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 1152
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 1153
        amazonScrapingHistory.returnProvision = spm.returnProvision
1154
        amazonScrapingHistory.courierCost = val.courierCost
1155
        amazonScrapingHistory.risky = val.risky
1156
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
1157
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
1158
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
1159
        amazonScrapingHistory.timestamp = timestamp
1160
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12597 kshitij.so 1161
        proposed_sp = max(amDetails.competitivePrice - 1, amPricing.lowestPossibleSp)
12468 kshitij.so 1162
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 1163
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 1164
        #amazonScrapingHistory.proposedTp = proposed_tp
12363 kshitij.so 1165
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
1166
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 1167
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 1168
    session.commit()
1169
 
12383 kshitij.so 1170
def commitAlmostCompete(almostCompete,timestamp,runType):
12396 kshitij.so 1171
    for almostCompeteItem in almostCompete:
1172
        val = almostCompeteItem[0]
1173
        amDetails = almostCompeteItem[1]
1174
        amPricing = almostCompeteItem[2]
1175
        spm = val.sourcePercentage
12510 kshitij.so 1176
        if amazonLongTermActivePromotions.has_key(val.sku):
1177
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
1178
        elif amazonShortTermActivePromotions.has_key(val.sku):
1179
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
1180
        else:
1181
            subsidy = 0
12396 kshitij.so 1182
        amazonScrapingHistory = AmazonScrapingHistory()
1183
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 1184
        amazonScrapingHistory.asin = val.asin
12396 kshitij.so 1185
        amazonScrapingHistory.warehouseLocation = val.state_id
1186
        amazonScrapingHistory.parentCategoryId = val.parent_category
1187
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 1188
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12510 kshitij.so 1189
        amazonScrapingHistory.subsidy = subsidy
1190
        amazonScrapingHistory.vatRate = val.vatRate
12396 kshitij.so 1191
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
1192
        amazonScrapingHistory.ourRank = amDetails.ourRank
1193
        amazonScrapingHistory.ourInventory = val.ourInventory
1194
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 1195
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
1196
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
1197
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12396 kshitij.so 1198
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 1199
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
1200
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
1201
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12396 kshitij.so 1202
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 1203
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
1204
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
1205
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12597 kshitij.so 1206
        amazonScrapingHistory.isLowestMfnIgnored = amDetails.isLowestMfnIgnored
1207
        amazonScrapingHistory.isLowestMfn = amDetails.isLowestMfn
1208
        amazonScrapingHistory.isLowestFba = amDetails.isLowestFba
1209
        amazonScrapingHistory.lowestMfnIgnoredOffer =amDetails.lowestMfnIgnoredOffer
1210
        amazonScrapingHistory.lowestMfnOffer = amDetails.lowestMfnOffer
1211
        amazonScrapingHistory.lowestFbaOffer = amDetails.lowestFbaOffer
1212
        amazonScrapingHistory.competitivePrice = amDetails.competitivePrice
1213
        if (amDetails.lowestMfnOffer < amDetails.lowestFbaOffer or amDetails.lowestMfnOffer < amazonScrapingHistory.promoPrice) and amDetails.isLowestMfn:
1214
            amazonScrapingHistory.cheapestMfnCount = True
1215
        else:
1216
            amazonScrapingHistory.cheapestMfnCount = False
12447 kshitij.so 1217
        amazonScrapingHistory.otherCost = val.otherCost
12396 kshitij.so 1218
        amazonScrapingHistory.wanlc = val.nlc
12845 kshitij.so 1219
        amazonScrapingHistory.isNlcOverridden = val.isNlcOverridden
12396 kshitij.so 1220
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 1221
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12396 kshitij.so 1222
        amazonScrapingHistory.returnProvision = spm.returnProvision
1223
        amazonScrapingHistory.courierCost = val.courierCost
1224
        amazonScrapingHistory.risky = val.risky
1225
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
1226
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
1227
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.ALMOST_COMPETE
1228
        amazonScrapingHistory.timestamp = timestamp
1229
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12597 kshitij.so 1230
        proposed_sp = min(amDetails.competitivePrice*(1+.01),amPricing.lowestPossibleSp)
12468 kshitij.so 1231
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
1232
        #target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
12396 kshitij.so 1233
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 1234
        #amazonScrapingHistory.proposedTp = proposed_tp
1235
        #amazonScrapingHistory.targetNlc = target_nlc
12396 kshitij.so 1236
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
1237
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 1238
        amazonScrapingHistory.isPromotion = val.isPromo
12396 kshitij.so 1239
    session.commit()
12363 kshitij.so 1240
 
12396 kshitij.so 1241
 
12363 kshitij.so 1242
def commitCantCompete(cantCompete, timestamp,runType):
1243
    for cantCompeteItem in cantCompete:
1244
        val = cantCompeteItem[0]
1245
        amDetails = cantCompeteItem[1]
1246
        amPricing = cantCompeteItem[2]
1247
        spm = val.sourcePercentage
12510 kshitij.so 1248
        if amazonLongTermActivePromotions.has_key(val.sku):
1249
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
1250
        elif amazonShortTermActivePromotions.has_key(val.sku):
1251
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
1252
        else:
1253
            subsidy = 0
12363 kshitij.so 1254
        amazonScrapingHistory = AmazonScrapingHistory()
1255
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 1256
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 1257
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 1258
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 1259
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 1260
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12510 kshitij.so 1261
        amazonScrapingHistory.subsidy = subsidy
1262
        amazonScrapingHistory.vatRate = val.vatRate
12363 kshitij.so 1263
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
1264
        amazonScrapingHistory.ourRank = amDetails.ourRank
1265
        amazonScrapingHistory.ourInventory = val.ourInventory
1266
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 1267
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
1268
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
1269
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 1270
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 1271
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
1272
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
1273
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 1274
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 1275
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
1276
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
1277
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12597 kshitij.so 1278
        amazonScrapingHistory.isLowestMfnIgnored = amDetails.isLowestMfnIgnored
1279
        amazonScrapingHistory.isLowestMfn = amDetails.isLowestMfn
1280
        amazonScrapingHistory.isLowestFba = amDetails.isLowestFba
1281
        amazonScrapingHistory.lowestMfnIgnoredOffer =amDetails.lowestMfnIgnoredOffer
1282
        amazonScrapingHistory.lowestMfnOffer = amDetails.lowestMfnOffer
1283
        amazonScrapingHistory.lowestFbaOffer = amDetails.lowestFbaOffer
1284
        if (amDetails.lowestMfnOffer < amDetails.lowestFbaOffer or amDetails.lowestMfnOffer < amazonScrapingHistory.promoPrice) and amDetails.isLowestMfn:
1285
            amazonScrapingHistory.cheapestMfnCount = True
1286
        else:
1287
            amazonScrapingHistory.cheapestMfnCount = False
1288
        amazonScrapingHistory.competitivePrice = amDetails.competitivePrice
12447 kshitij.so 1289
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 1290
        amazonScrapingHistory.wanlc = val.nlc
12845 kshitij.so 1291
        amazonScrapingHistory.isNlcOverridden = val.isNlcOverridden
12363 kshitij.so 1292
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 1293
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 1294
        amazonScrapingHistory.returnProvision = spm.returnProvision
1295
        amazonScrapingHistory.courierCost = val.courierCost
1296
        amazonScrapingHistory.risky = val.risky
1297
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
1298
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
1299
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
1300
        amazonScrapingHistory.timestamp = timestamp
1301
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12597 kshitij.so 1302
        proposed_sp = amDetails.competitivePrice - max(5, amDetails.competitivePrice*0.001)
12468 kshitij.so 1303
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
1304
        #target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
12363 kshitij.so 1305
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 1306
        #amazonScrapingHistory.proposedTp = proposed_tp
1307
        #amazonScrapingHistory.targetNlc = target_nlc
12363 kshitij.so 1308
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
1309
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 1310
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 1311
    session.commit()
1312
 
12396 kshitij.so 1313
def markAutoFavourites(time):
1314
    nowAutoFav = []
1315
    previouslyAutoFav = []
1316
    stockList = []
1317
    saleList = []
12803 kshitij.so 1318
    items = session.query(func.sum(AmazonScrapingHistory.ourInventory),AmazonScrapingHistory.item_id).filter(AmazonScrapingHistory.timestamp==time).group_by(AmazonScrapingHistory.item_id).all()
12396 kshitij.so 1319
    allItems = session.query(Amazonlisted).all()
1320
    for item in items:
1321
        reason = ""
1322
        if item[0]>=5:
1323
            stockList.append(item[1])
1324
 
1325
    for sku, val in saleMap.iteritems():
1326
        totalSale = 0
12909 kshitij.so 1327
        item_id = sku.replace('FBA','').replace('FBB','').replace('FBG','')
12396 kshitij.so 1328
        val =saleMap.get('FBA'+str(item_id))
1329
        if val is not None:
1330
            for sale in val:
1331
                totalSale += sale.totalOrderCount
1332
        val =saleMap.get('FBB'+str(item_id))
1333
        if val is not None:
1334
            for sale in val:
1335
                totalSale += sale.totalOrderCount
12909 kshitij.so 1336
        val =saleMap.get('FBG'+str(item_id))
1337
        if val is not None:
1338
            for sale in val:
1339
                totalSale += sale.totalOrderCount
12396 kshitij.so 1340
        if totalSale > 0:
1341
            saleList.append(item_id)
1342
 
1343
    for aItem in allItems:
1344
        reason = ""
1345
        toMark = False
1346
        if aItem.itemId in saleList:
1347
            toMark = True
1348
            reason+="Total FC sale is greater than 1 for last five days.."
1349
        if aItem.itemId in stockList:
1350
            toMark = True
12660 kshitij.so 1351
            reason+="Fulfillable Stock in FC is >=5"
12396 kshitij.so 1352
        if not aItem.autoFavourite:
1353
            print "Item is not under auto favourite"
1354
        if toMark:
1355
            temp=[]
1356
            temp.append(aItem.itemId)
1357
            temp.append(reason)
1358
            nowAutoFav.append(temp)
1359
        if (not toMark) and aItem.autoFavourite:
1360
            previouslyAutoFav.append(aItem.itemId)
1361
        aItem.autoFavourite = toMark
1362
    session.commit()
1363
    return previouslyAutoFav, nowAutoFav
1364
 
12526 anikendra 1365
#Write the excel sheet headers for identical sheets
1366
def writeheaders(sheet,heading_xf):
1367
    sheet.write(0, 0, "Item Id", heading_xf)
1368
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1369
    sheet.write(0, 2, "Asin", heading_xf)
12845 kshitij.so 1370
    sheet.write(0, 3, "URL", heading_xf)
1371
    sheet.write(0, 4, "Location", heading_xf)
1372
    sheet.write(0, 5, "Brand", heading_xf)
1373
    sheet.write(0, 6, "Category", heading_xf)
1374
    sheet.write(0, 7, "Product Name", heading_xf)
1375
    sheet.write(0, 8, "Weight", heading_xf)
1376
    sheet.write(0, 9, "Courier Cost", heading_xf)
1377
    sheet.write(0, 10, "MRP", heading_xf)
1378
    sheet.write(0, 11, "Our SP", heading_xf)
1379
    sheet.write(0, 12, "Promo Price", heading_xf)
1380
    sheet.write(0, 13, "Is Promotion", heading_xf)
1381
    sheet.write(0, 14, "Lowest Possible SP", heading_xf)
1382
    sheet.write(0, 15, "Rank", heading_xf)
1383
    sheet.write(0, 16, "Competitive Category", heading_xf)
1384
    sheet.write(0, 17, "Our Inventory", heading_xf)
1385
    sheet.write(0, 18, "Lowest Seller SP", heading_xf)
1386
    sheet.write(0, 19, "Lowest Seller Rating", heading_xf)
1387
    sheet.write(0, 20, "Lowest Seller Shipping Time", heading_xf)
1388
    sheet.write(0, 21, "Second Lowest Seller SP", heading_xf)
1389
    sheet.write(0, 22, "Second Lowest Seller Rating", heading_xf)
1390
    sheet.write(0, 23, "Second Lowest Seller Shipping Time", heading_xf)
1391
    sheet.write(0, 24, "Third Lowest Seller SP", heading_xf)
1392
    sheet.write(0, 25, "Third Lowest Seller Rating", heading_xf)
1393
    sheet.write(0, 26, "Third Lowest Seller Shipping Time", heading_xf)
1394
    sheet.write(0, 27, "Lowest MFN Ignored", heading_xf)
1395
    sheet.write(0, 28, "Lowest MFN", heading_xf)
1396
    sheet.write(0, 29, "Lowest FBA", heading_xf)
1397
    sheet.write(0, 30, "Competitive Price", heading_xf)
1398
    sheet.write(0, 31, "Other Cost", heading_xf)
1399
    sheet.write(0, 32, "WANLC", heading_xf)
1400
    sheet.write(0, 33, "Overridden WANLC", heading_xf)
1401
    sheet.write(0, 34, "Subsidy", heading_xf)
1402
    sheet.write(0, 35, "MAX SALE PRICE", heading_xf)
1403
    sheet.write(0, 36, "Commission", heading_xf)
1404
    sheet.write(0, 37, "Competitor Commission", heading_xf)
1405
    sheet.write(0, 38, "Return Provision", heading_xf)
1406
    sheet.write(0, 39, "Vat Rate", heading_xf)
1407
    sheet.write(0, 40, "Margin", heading_xf)
1408
    sheet.write(0, 41, "Proposed Sp", heading_xf)
1409
    sheet.write(0, 42, "Avg Sale", heading_xf)
1410
    sheet.write(0, 43, "NOD", heading_xf)
1411
    sheet.write(0, 44, "Sales History", heading_xf)
1412
    sheet.write(0, 45, "Decision", heading_xf)
1413
    sheet.write(0, 46, "Reason", heading_xf)
1414
    sheet.write(0, 47, "Updated Price", heading_xf)
1415
    sheet.write(0, 48, "Proposed Margin", heading_xf)
1416
    sheet.write(0, 49, "Inventory Movement Status", heading_xf)
12526 anikendra 1417
 
1418
def getPackagingCost(data):
1419
    #TODO : Get packagingCost from marketplaceitems table
1420
    return 15
1421
 
1422
def getReturnCost(data):
1423
    return round(data.returnProvision * data.promoPrice/100)
1424
 
12736 kshitij.so 1425
def getNewReturnCost(data,proposedSp):
1426
    return round(data.returnProvision * proposedSp/100)
1427
 
12526 anikendra 1428
def getServiceTax(data):
1429
    #TODO : Get service tax from marketplaceitems table
1430
    return 12.36
1431
 
1432
def getClosingFee(data):
1433
    myClosingFee = 0
12556 anikendra 1434
    return myClosingFee*(1+getServiceTax(data)/100)
12526 anikendra 1435
 
1436
def getCommission(data):
12556 anikendra 1437
    return (data.commission * data.promoPrice/100)*(1+getServiceTax(data)/100)
12526 anikendra 1438
 
12736 kshitij.so 1439
def getNewCommission(data,proposedSp):
1440
    return (data.commission * proposedSp/100)*(1+getServiceTax(data)/100)
1441
 
12526 anikendra 1442
def getCourierCost(data):
12556 anikendra 1443
    return data.courierCost*(1+getServiceTax(data)/100)
12526 anikendra 1444
 
12556 anikendra 1445
def getCostToAmazon(data):
1446
    myCostToAmazon = round(data.promoPrice*data.commission/100*(1+getServiceTax(data)/100)+getCourierCost(data)*(1+getServiceTax(data)/100))
1447
    return myCostToAmazon
1448
 
12677 kshitij.so 1449
def getMsp(item_id,location):
1450
    if location==1:
1451
        sku='FBA'+str(item_id)
1452
    elif location==2:
1453
        sku='FBB'+str(item_id)
12909 kshitij.so 1454
    elif location==3:
1455
        sku='FBG'+str(item_id)
12677 kshitij.so 1456
    else:
1457
        return 0.0
1458
    if amazonLongTermActivePromotions.has_key(sku):
12679 kshitij.so 1459
        msp = (amazonLongTermActivePromotions.get(sku)).promoPrice
12677 kshitij.so 1460
    elif amazonShortTermActivePromotions.has_key(sku):
12679 kshitij.so 1461
        msp = (amazonShortTermActivePromotions.get(sku)).promoPrice
12677 kshitij.so 1462
    else:
1463
        msp = 0
1464
    return msp
1465
 
1466
 
12639 kshitij.so 1467
def getInventoryMovementStatus(amScraping):
1468
    try:
12659 kshitij.so 1469
        nodStock = (float(amScraping.ourInventory))/amScraping.avgSale
12643 kshitij.so 1470
    except Exception as e:
1471
        print "exception in nod stock"
1472
        print e
1473
        nodStock = float("inf")
12639 kshitij.so 1474
    try:
1475
        if amScraping.avgSale==0:
1476
            return "Not Moving"
12659 kshitij.so 1477
        elif nodStock > 20:
12639 kshitij.so 1478
            return "Slow Moving"
1479
        else:
12659 kshitij.so 1480
            return "Moving"
12643 kshitij.so 1481
    except Exception as e:
1482
        print e
1483
        print "exception in ims"
12639 kshitij.so 1484
        return ""
1485
 
12526 anikendra 1486
def getMargin(amScraping):
1487
    #sheet.write(sheet_iterator, 30, round(amScraping.promoPrice - amScraping.lowestPossibleSp))
1488
    #Promo Price minus costs plus subsidy
1489
    #costs = WANLC (actual or overrrde whichever is applicable) + Courier cost + Closing fee + Commission + Packaging + VAT + Returns Cost + other cost.
12556 anikendra 1490
    '''
12526 anikendra 1491
    if(amScraping.ourSellingPrice >= amScraping.promoPrice):
1492
	mySubsidy = amScraping.subsidy
1493
    else:
1494
	mySubsidy = 0
12556 anikendra 1495
    '''
12526 anikendra 1496
    print 'promo price ',amScraping.promoPrice
12556 anikendra 1497
    #print 'mySubsidy ',mySubsidy
12526 anikendra 1498
    print 'wanlc ',amScraping.wanlc
1499
    print 'courier cost ',getCourierCost(amScraping)
1500
    print 'closing fee ',getClosingFee(amScraping)
12736 kshitij.so 1501
    print 'commission ',getCommission(amScraping) #1
12526 anikendra 1502
    print 'packaging ',getPackagingCost(amScraping)
12736 kshitij.so 1503
    print 'vat ',getVat(amScraping) #2
1504
    print 'return cost ',getReturnCost(amScraping) #3
12526 anikendra 1505
    print 'other cost ',amScraping.otherCost
12736 kshitij.so 1506
    print 'cost to amazon ',getCostToAmazon(amScraping) #4
12526 anikendra 1507
    myCosts = amScraping.wanlc + getCourierCost(amScraping) + getClosingFee(amScraping) + getCommission(amScraping) + getPackagingCost(amScraping) + getVat(amScraping) + getReturnCost(amScraping) + amScraping.otherCost 
12556 anikendra 1508
    margin = amScraping.promoPrice - myCosts + amScraping.subsidy
1509
    print 'margin for ',amScraping.item_id,' is ',margin
12526 anikendra 1510
    return round(margin)
1511
 
12736 kshitij.so 1512
def getNewMargin(amScraping,proposedSp):
12803 kshitij.so 1513
    myCosts = amScraping.wanlc + getCourierCost(amScraping) + getClosingFee(amScraping) + getNewCommission(amScraping,proposedSp) + getPackagingCost(amScraping) + getNewVat(amScraping,getVatRate(amScraping.item_id,amScraping.warehouseLocation,proposedSp),proposedSp) + getNewReturnCost(amScraping,proposedSp) + amScraping.otherCost 
12736 kshitij.so 1514
    margin = proposedSp - myCosts + amScraping.subsidy
1515
    print 'New margin for ',amScraping.item_id,' is ',margin
1516
    return round(margin)
1517
 
12526 anikendra 1518
def getVat(data):
1519
    #VAT amount = Promo Price/(1+Vat Rate)*VAT Rate minus NLC/(1+VAT Rate)*VAT Rate
1520
    myVatPercentage = data.vatRate/100
1521
    myVat = myVatPercentage*(data.promoPrice/(1+myVatPercentage) - data.wanlc/(1+myVatPercentage))
1522
    if(myVat<0):
1523
        return 0
1524
    else:
1525
        return round(myVat)
12736 kshitij.so 1526
 
1527
def getNewVat(data,vatRate,proposedSp):
1528
    myVatPercentage = vatRate/100
1529
    myVat = myVatPercentage*(proposedSp/(1+myVatPercentage) - data.wanlc/(1+myVatPercentage))
1530
    if(myVat<0):
1531
        return 0
1532
    else:
1533
        return round(myVat)
12526 anikendra 1534
 
12736 kshitij.so 1535
 
12526 anikendra 1536
def getCategory(data):
1537
    return categoryMap[data.category]
1538
 
12444 kshitij.so 1539
def writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,runType):
12680 kshitij.so 1540
    wbk = xlwt.Workbook(encoding="UTF-8")
1541
    sheet = wbk.add_sheet('Competiton Det')
12396 kshitij.so 1542
    xstr = lambda s: s or ""
1543
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1544
 
1545
    excel_integer_format = '0'
1546
    integer_style = xlwt.XFStyle()
1547
    integer_style.num_format_str = excel_integer_format
12526 anikendra 1548
    writeheaders(sheet,heading_xf)
1549
    '''
12396 kshitij.so 1550
    sheet.write(0, 0, "Item Id", heading_xf)
1551
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1552
    sheet.write(0, 2, "Asin", heading_xf)
1553
    sheet.write(0, 3, "Location", heading_xf)
1554
    sheet.write(0, 4, "Brand", heading_xf)
1555
    sheet.write(0, 5, "Product Name", heading_xf)
1556
    sheet.write(0, 6, "Weight", heading_xf)
1557
    sheet.write(0, 7, "Courier Cost", heading_xf)
1558
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1559
    sheet.write(0, 9, "Promo Price", heading_xf)
1560
    sheet.write(0, 10, "Is Promotion", heading_xf)
1561
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1562
    sheet.write(0, 12, "Rank", heading_xf)
1563
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1564
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1565
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1566
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1567
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1568
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1569
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1570
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1571
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1572
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1573
    sheet.write(0, 23, "Other Cost", heading_xf)
1574
    sheet.write(0, 24, "WANLC", heading_xf)
12526 anikendra 1575
    sheet.write(0, 25, "Subsidy", heading_xf)
1576
    sheet.write(0, 26, "Commission", heading_xf)
1577
    sheet.write(0, 27, "Competitor Commission", heading_xf)
1578
    sheet.write(0, 28, "Return Provision", heading_xf)
1579
    sheet.write(0, 29, "Vat Rate", heading_xf)
1580
    sheet.write(0, 30, "Margin", heading_xf)
1581
    sheet.write(0, 31, "Risky", heading_xf)
1582
    sheet.write(0, 32, "Proposed Sp", heading_xf)
1583
    sheet.write(0, 33, "Avg Sale", heading_xf)
1584
    sheet.write(0, 34, "Sales History", heading_xf)
1585
    '''
12396 kshitij.so 1586
    sheet_iterator = 1
12476 kshitij.so 1587
    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 1588
    for cantCompeteItem in cantCompeteItems:
1589
        amScraping =  cantCompeteItem[0]
1590
        item = cantCompeteItem[1]
1591
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1592
        if amScraping.warehouseLocation == 1:
1593
            sku = 'FBA'+str(amScraping.item_id)
1594
            loc = 'MUMBAI'
12909 kshitij.so 1595
        elif amScraping.warehouseLocation == 2:
12396 kshitij.so 1596
            sku = 'FBB'+str(amScraping.item_id)
1597
            loc = 'BANGLORE'
12909 kshitij.so 1598
        else:
1599
            sku = 'FBG'+str(amScraping.item_id)
1600
            loc = 'GURGAON'
12396 kshitij.so 1601
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1602
        sheet.write(sheet_iterator, 2, amScraping.asin)
12845 kshitij.so 1603
        sheet.write(sheet_iterator, 3, 'http://www.amazon.in/dp/'+amScraping.asin)
1604
        sheet.write(sheet_iterator, 4, loc)
1605
        sheet.write(sheet_iterator, 5, item.brand)
1606
        sheet.write(sheet_iterator, 6, getCategory(item))
1607
        sheet.write(sheet_iterator, 7, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1608
        sheet.write(sheet_iterator, 8, item.weight)
1609
        sheet.write(sheet_iterator, 9, amScraping.courierCost)
1610
        sheet.write(sheet_iterator, 10, item.mrp)
1611
        sheet.write(sheet_iterator, 11, amScraping.ourSellingPrice)
1612
        sheet.write(sheet_iterator, 12, amScraping.promoPrice)
12432 kshitij.so 1613
        if amScraping.isPromotion:
12845 kshitij.so 1614
            sheet.write(sheet_iterator, 13, "Yes")
12432 kshitij.so 1615
        else:
12845 kshitij.so 1616
            sheet.write(sheet_iterator, 13, "No")
1617
        sheet.write(sheet_iterator, 14, amScraping.lowestPossibleSp)
12396 kshitij.so 1618
        if amScraping.ourRank > 3:
12845 kshitij.so 1619
            sheet.write(sheet_iterator, 15, 'Greater than 3')
12396 kshitij.so 1620
        else:
12845 kshitij.so 1621
            sheet.write(sheet_iterator, 15, amScraping.ourRank)
1622
        sheet.write(sheet_iterator, 16, 'Cant Compete')
1623
        sheet.write(sheet_iterator, 17, amScraping.ourInventory)
1624
        sheet.write(sheet_iterator, 18, amScraping.lowestSellerSp)
1625
        sheet.write(sheet_iterator, 19, amScraping.lowestSellerRating)
1626
        sheet.write(sheet_iterator, 20, amScraping.lowestSellerShippingTime)
1627
        sheet.write(sheet_iterator, 21, amScraping.secondLowestSellerSp)
1628
        sheet.write(sheet_iterator, 22, amScraping.secondLowestSellerRating)
1629
        sheet.write(sheet_iterator, 23, amScraping.secondLowestSellerShippingTime)
1630
        sheet.write(sheet_iterator, 24, amScraping.thirdLowestSellerSp)
1631
        sheet.write(sheet_iterator, 25, amScraping.thirdLowestSellerRating)
1632
        sheet.write(sheet_iterator, 26, amScraping.thirdLowestSellerShippingTime)
1633
        sheet.write(sheet_iterator, 27, amScraping.lowestMfnIgnoredOffer)
1634
        sheet.write(sheet_iterator, 28, amScraping.lowestMfnOffer)
1635
        sheet.write(sheet_iterator, 29, amScraping.lowestFbaOffer)
1636
        sheet.write(sheet_iterator, 30, amScraping.competitivePrice)
1637
        sheet.write(sheet_iterator, 31, amScraping.otherCost)
1638
        sheet.write(sheet_iterator, 32, amScraping.wanlc)
1639
        sheet.write(sheet_iterator, 33, amScraping.isNlcOverridden)
1640
        sheet.write(sheet_iterator, 34, amScraping.subsidy)
12678 kshitij.so 1641
        if amScraping.isPromotion:
12845 kshitij.so 1642
            sheet.write(sheet_iterator, 35, getMsp(amScraping.item_id,amScraping.warehouseLocation))
12677 kshitij.so 1643
        else:
12845 kshitij.so 1644
            sheet.write(sheet_iterator, 35, 0.0)
1645
        sheet.write(sheet_iterator, 36, amScraping.commission)
1646
        sheet.write(sheet_iterator, 37, amScraping.competitorCommission)
1647
        sheet.write(sheet_iterator, 38, amScraping.returnProvision)
1648
        sheet.write(sheet_iterator, 39, amScraping.vatRate)
1649
        sheet.write(sheet_iterator, 40, getMargin(amScraping))
1650
        sheet.write(sheet_iterator, 41, amScraping.proposedSp)
1651
        sheet.write(sheet_iterator, 42, amScraping.avgSale)
12639 kshitij.so 1652
        try:
1653
            daysOfStock = (float(amScraping.ourInventory))/amScraping.avgSale
1654
        except:
1655
            daysOfStock = float("inf")
12652 kshitij.so 1656
        if str(daysOfStock)=='inf':
12845 kshitij.so 1657
            sheet.write(sheet_iterator, 43, str(daysOfStock))
12652 kshitij.so 1658
        else:
12845 kshitij.so 1659
            sheet.write(sheet_iterator, 43, str(round(daysOfStock,1)))
1660
        sheet.write(sheet_iterator, 44, getOosString(saleMap.get(sku)))
12643 kshitij.so 1661
        #sheet.write(sheet_iterator, 44, round(amScraping.proposedSp - getNewLowestPossibleSp(amScraping,12.36,getNewVatRate(amScraping.item_id,amScraping.warehouseLocation,amScraping.proposedSp))))
12845 kshitij.so 1662
        sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12396 kshitij.so 1663
        sheet_iterator+=1
12597 kshitij.so 1664
    #TODO : Take excell sheet generation code inside a function 
12476 kshitij.so 1665
    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 1666
    for competitiveItem in competitiveItems:
1667
        amScraping =  competitiveItem[0]
1668
        item = competitiveItem[1]
1669
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1670
        if amScraping.warehouseLocation == 1:
1671
            sku = 'FBA'+str(amScraping.item_id)
1672
            loc = 'MUMBAI'
12909 kshitij.so 1673
        elif amScraping.warehouseLocation == 2:
12396 kshitij.so 1674
            sku = 'FBB'+str(amScraping.item_id)
1675
            loc = 'BANGLORE'
12909 kshitij.so 1676
        else:
1677
            sku='FBG'+str(amScraping.item_id)
1678
            loc = 'GURGAON'
12396 kshitij.so 1679
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1680
        sheet.write(sheet_iterator, 2, amScraping.asin)
12845 kshitij.so 1681
        sheet.write(sheet_iterator, 3, 'http://www.amazon.in/dp/'+amScraping.asin)
1682
        sheet.write(sheet_iterator, 4, loc)
1683
        sheet.write(sheet_iterator, 5, item.brand)
1684
        sheet.write(sheet_iterator, 6, getCategory(item))
1685
        sheet.write(sheet_iterator, 7, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1686
        sheet.write(sheet_iterator, 8, item.weight)
1687
        sheet.write(sheet_iterator, 9, amScraping.courierCost)
1688
        sheet.write(sheet_iterator, 10, item.mrp)
1689
        sheet.write(sheet_iterator, 11, amScraping.ourSellingPrice)
1690
        sheet.write(sheet_iterator, 12, amScraping.promoPrice)
12432 kshitij.so 1691
        if amScraping.isPromotion:
12845 kshitij.so 1692
            sheet.write(sheet_iterator, 13, "Yes")
12432 kshitij.so 1693
        else:
12845 kshitij.so 1694
            sheet.write(sheet_iterator, 13, "No")
1695
        sheet.write(sheet_iterator, 14, amScraping.lowestPossibleSp)
12396 kshitij.so 1696
        if amScraping.ourRank > 3:
12845 kshitij.so 1697
            sheet.write(sheet_iterator, 15, 'Greater than 3')
12396 kshitij.so 1698
        else:
12845 kshitij.so 1699
            sheet.write(sheet_iterator, 15, amScraping.ourRank)
1700
        sheet.write(sheet_iterator, 16, 'Competitive')
1701
        sheet.write(sheet_iterator, 17, amScraping.ourInventory)
1702
        sheet.write(sheet_iterator, 18, amScraping.lowestSellerSp)
1703
        sheet.write(sheet_iterator, 19, amScraping.lowestSellerRating)
1704
        sheet.write(sheet_iterator, 20, amScraping.lowestSellerShippingTime)
1705
        sheet.write(sheet_iterator, 21, amScraping.secondLowestSellerSp)
1706
        sheet.write(sheet_iterator, 22, amScraping.secondLowestSellerRating)
1707
        sheet.write(sheet_iterator, 23, amScraping.secondLowestSellerShippingTime)
1708
        sheet.write(sheet_iterator, 24, amScraping.thirdLowestSellerSp)
1709
        sheet.write(sheet_iterator, 25, amScraping.thirdLowestSellerRating)
1710
        sheet.write(sheet_iterator, 26, amScraping.thirdLowestSellerShippingTime)
1711
        sheet.write(sheet_iterator, 27, amScraping.lowestMfnIgnoredOffer)
1712
        sheet.write(sheet_iterator, 28, amScraping.lowestMfnOffer)
1713
        sheet.write(sheet_iterator, 29, amScraping.lowestFbaOffer)
1714
        sheet.write(sheet_iterator, 30, amScraping.competitivePrice)
1715
        sheet.write(sheet_iterator, 31, amScraping.otherCost)
1716
        sheet.write(sheet_iterator, 32, amScraping.wanlc)
1717
        sheet.write(sheet_iterator, 33, amScraping.isNlcOverridden)
1718
        sheet.write(sheet_iterator, 34, amScraping.subsidy)
12678 kshitij.so 1719
        if amScraping.isPromotion:
12845 kshitij.so 1720
            sheet.write(sheet_iterator, 35, getMsp(amScraping.item_id,amScraping.warehouseLocation))
12677 kshitij.so 1721
        else:
12845 kshitij.so 1722
            sheet.write(sheet_iterator, 35, 0.0)
1723
        sheet.write(sheet_iterator, 36, amScraping.commission)
1724
        sheet.write(sheet_iterator, 37, amScraping.competitorCommission)
1725
        sheet.write(sheet_iterator, 38, amScraping.returnProvision)
1726
        sheet.write(sheet_iterator, 39, amScraping.vatRate)
1727
        sheet.write(sheet_iterator, 40, getMargin(amScraping))
1728
        sheet.write(sheet_iterator, 41, amScraping.proposedSp)
1729
        sheet.write(sheet_iterator, 42, amScraping.avgSale)
12639 kshitij.so 1730
        try:
1731
            daysOfStock = (float(amScraping.ourInventory))/amScraping.avgSale
1732
        except:
1733
            daysOfStock = float("inf")
12652 kshitij.so 1734
        if str(daysOfStock)=='inf':
12845 kshitij.so 1735
            sheet.write(sheet_iterator, 43, str(daysOfStock))
12652 kshitij.so 1736
        else:
12845 kshitij.so 1737
            sheet.write(sheet_iterator, 43, str(round(daysOfStock,1)))
1738
        sheet.write(sheet_iterator, 44, getOosString(saleMap.get(sku)))
12444 kshitij.so 1739
        if amScraping.decision is None:
12845 kshitij.so 1740
            sheet.write(sheet_iterator, 45, 'Auto Pricing Inactive')
1741
            sheet.write(sheet_iterator, 48, getNewMargin(amScraping,amScraping.proposedSp))
1742
            sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12444 kshitij.so 1743
            sheet_iterator+=1
1744
            continue
12845 kshitij.so 1745
        sheet.write(sheet_iterator, 45, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1746
        sheet.write(sheet_iterator, 46, amScraping.reason)
12444 kshitij.so 1747
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12845 kshitij.so 1748
            sheet.write(sheet_iterator, 47, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1749
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12928 kshitij.so 1750
            sheet.write(sheet_iterator, 47, min(math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice)),amScraping.proposedSp))
12845 kshitij.so 1751
        sheet.write(sheet_iterator, 48, getNewMargin(amScraping,amScraping.proposedSp))
1752
        sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12396 kshitij.so 1753
        sheet_iterator+=1
1754
 
12476 kshitij.so 1755
    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 1756
    for almostCompetitiveItem in almostCompetitiveItems:
1757
        amScraping =  almostCompetitiveItem[0]
1758
        item = almostCompetitiveItem[1]
1759
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1760
        if amScraping.warehouseLocation == 1:
1761
            sku = 'FBA'+str(amScraping.item_id)
1762
            loc = 'MUMBAI'
12909 kshitij.so 1763
        elif amScraping.warehouseLocation == 2:
12396 kshitij.so 1764
            sku = 'FBB'+str(amScraping.item_id)
1765
            loc = 'BANGLORE'
12909 kshitij.so 1766
        else:
1767
            sku = 'FBG'+str(amScraping.item_id)
1768
            loc = 'GURGAON'
12396 kshitij.so 1769
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1770
        sheet.write(sheet_iterator, 2, amScraping.asin)
12845 kshitij.so 1771
        sheet.write(sheet_iterator, 3, 'http://www.amazon.in/dp/'+amScraping.asin)
1772
        sheet.write(sheet_iterator, 4, loc)
1773
        sheet.write(sheet_iterator, 5, item.brand)
1774
        sheet.write(sheet_iterator, 6, getCategory(item))
1775
        sheet.write(sheet_iterator, 7, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1776
        sheet.write(sheet_iterator, 8, item.weight)
1777
        sheet.write(sheet_iterator, 9, amScraping.courierCost)
1778
        sheet.write(sheet_iterator, 10, item.mrp)
1779
        sheet.write(sheet_iterator, 11, amScraping.ourSellingPrice)
1780
        sheet.write(sheet_iterator, 12, amScraping.promoPrice)
12432 kshitij.so 1781
        if amScraping.isPromotion:
12845 kshitij.so 1782
            sheet.write(sheet_iterator, 13, "Yes")
12432 kshitij.so 1783
        else:
12845 kshitij.so 1784
            sheet.write(sheet_iterator, 13, "No")
1785
        sheet.write(sheet_iterator, 14, amScraping.lowestPossibleSp)
12396 kshitij.so 1786
        if amScraping.ourRank > 3:
12845 kshitij.so 1787
            sheet.write(sheet_iterator, 15, 'Greater than 3')
12396 kshitij.so 1788
        else:
12845 kshitij.so 1789
            sheet.write(sheet_iterator, 15, amScraping.ourRank)
1790
        sheet.write(sheet_iterator, 16, 'Almost Competitive')
1791
        sheet.write(sheet_iterator, 17, amScraping.ourInventory)
1792
        sheet.write(sheet_iterator, 18, amScraping.lowestSellerSp)
1793
        sheet.write(sheet_iterator, 19, amScraping.lowestSellerRating)
1794
        sheet.write(sheet_iterator, 20, amScraping.lowestSellerShippingTime)
1795
        sheet.write(sheet_iterator, 21, amScraping.secondLowestSellerSp)
1796
        sheet.write(sheet_iterator, 22, amScraping.secondLowestSellerRating)
1797
        sheet.write(sheet_iterator, 23, amScraping.secondLowestSellerShippingTime)
1798
        sheet.write(sheet_iterator, 24, amScraping.thirdLowestSellerSp)
1799
        sheet.write(sheet_iterator, 25, amScraping.thirdLowestSellerRating)
1800
        sheet.write(sheet_iterator, 26, amScraping.thirdLowestSellerShippingTime)
1801
        sheet.write(sheet_iterator, 27, amScraping.lowestMfnIgnoredOffer)
1802
        sheet.write(sheet_iterator, 28, amScraping.lowestMfnOffer)
1803
        sheet.write(sheet_iterator, 29, amScraping.lowestFbaOffer)
1804
        sheet.write(sheet_iterator, 30, amScraping.competitivePrice)
1805
        sheet.write(sheet_iterator, 31, amScraping.otherCost)
1806
        sheet.write(sheet_iterator, 32, amScraping.wanlc)
1807
        sheet.write(sheet_iterator, 33, amScraping.isNlcOverridden)
1808
        sheet.write(sheet_iterator, 34, amScraping.subsidy)
12678 kshitij.so 1809
        if amScraping.isPromotion:
12845 kshitij.so 1810
            sheet.write(sheet_iterator, 35, getMsp(amScraping.item_id,amScraping.warehouseLocation))
12677 kshitij.so 1811
        else:
12845 kshitij.so 1812
            sheet.write(sheet_iterator, 35, 0.0)
1813
        sheet.write(sheet_iterator, 36, amScraping.commission)
1814
        sheet.write(sheet_iterator, 37, amScraping.competitorCommission)
1815
        sheet.write(sheet_iterator, 38, amScraping.returnProvision)
1816
        sheet.write(sheet_iterator, 39, amScraping.vatRate)
1817
        sheet.write(sheet_iterator, 40, getMargin(amScraping))
1818
        sheet.write(sheet_iterator, 41, amScraping.proposedSp)
1819
        sheet.write(sheet_iterator, 42, amScraping.avgSale)
12639 kshitij.so 1820
        try:
1821
            daysOfStock = (float(amScraping.ourInventory))/amScraping.avgSale
1822
        except:
1823
            daysOfStock = float("inf")
12652 kshitij.so 1824
        if str(daysOfStock)=='inf':
12845 kshitij.so 1825
            sheet.write(sheet_iterator, 43, str(daysOfStock))
12652 kshitij.so 1826
        else:
12845 kshitij.so 1827
            sheet.write(sheet_iterator, 43, str(round(daysOfStock,1)))
1828
        sheet.write(sheet_iterator, 44, getOosString(saleMap.get(sku)))
12444 kshitij.so 1829
        if amScraping.decision is None:
12845 kshitij.so 1830
            sheet.write(sheet_iterator, 45, 'Auto Pricing Inactive')
1831
            sheet.write(sheet_iterator, 48, getNewMargin(amScraping,amScraping.proposedSp))
1832
            sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12444 kshitij.so 1833
            sheet_iterator+=1
1834
            continue
12845 kshitij.so 1835
        sheet.write(sheet_iterator, 45, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1836
        sheet.write(sheet_iterator, 46, amScraping.reason)
12444 kshitij.so 1837
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12845 kshitij.so 1838
            sheet.write(sheet_iterator, 47, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1839
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12928 kshitij.so 1840
            sheet.write(sheet_iterator, 47, min(math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice)),amScraping.proposedSp))
12845 kshitij.so 1841
        sheet.write(sheet_iterator, 48, getNewMargin(amScraping,amScraping.proposedSp))
1842
        sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12396 kshitij.so 1843
        sheet_iterator+=1
1844
 
12476 kshitij.so 1845
    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 1846
    for amongCheapestItem in amongCheapestItems:
1847
        amScraping =  amongCheapestItem[0]
1848
        item = amongCheapestItem[1]
1849
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1850
        if amScraping.warehouseLocation == 1:
1851
            sku = 'FBA'+str(amScraping.item_id)
1852
            loc = 'MUMBAI'
12909 kshitij.so 1853
        elif amScraping.warehouseLocation == 2:
12396 kshitij.so 1854
            sku = 'FBB'+str(amScraping.item_id)
1855
            loc = 'BANGLORE'
12909 kshitij.so 1856
        else:
1857
            sku = 'FBG'+str(amScraping.item_id)
1858
            loc = 'GURGAON'
12396 kshitij.so 1859
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1860
        sheet.write(sheet_iterator, 2, amScraping.asin)
12845 kshitij.so 1861
        sheet.write(sheet_iterator, 3, 'http://www.amazon.in/dp/'+amScraping.asin)
1862
        sheet.write(sheet_iterator, 4, loc)
1863
        sheet.write(sheet_iterator, 5, item.brand)
1864
        sheet.write(sheet_iterator, 6, getCategory(item))
1865
        sheet.write(sheet_iterator, 7, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1866
        sheet.write(sheet_iterator, 8, item.weight)
1867
        sheet.write(sheet_iterator, 9, amScraping.courierCost)
1868
        sheet.write(sheet_iterator, 10, item.mrp)
1869
        sheet.write(sheet_iterator, 11, amScraping.ourSellingPrice)
1870
        sheet.write(sheet_iterator, 12, amScraping.promoPrice)
12432 kshitij.so 1871
        if amScraping.isPromotion:
12845 kshitij.so 1872
            sheet.write(sheet_iterator, 13, "Yes")
12432 kshitij.so 1873
        else:
12845 kshitij.so 1874
            sheet.write(sheet_iterator, 13, "No")
1875
        sheet.write(sheet_iterator, 14, amScraping.lowestPossibleSp)
12396 kshitij.so 1876
        if amScraping.ourRank > 3:
12845 kshitij.so 1877
            sheet.write(sheet_iterator, 15, 'Greater than 3')
12396 kshitij.so 1878
        else:
12845 kshitij.so 1879
            sheet.write(sheet_iterator, 15, amScraping.ourRank)
1880
        sheet.write(sheet_iterator, 16, 'Among Cheapest')
1881
        sheet.write(sheet_iterator, 17, amScraping.ourInventory)
1882
        sheet.write(sheet_iterator, 18, amScraping.lowestSellerSp)
1883
        sheet.write(sheet_iterator, 19, amScraping.lowestSellerRating)
1884
        sheet.write(sheet_iterator, 20, amScraping.lowestSellerShippingTime)
1885
        sheet.write(sheet_iterator, 21, amScraping.secondLowestSellerSp)
1886
        sheet.write(sheet_iterator, 22, amScraping.secondLowestSellerRating)
1887
        sheet.write(sheet_iterator, 23, amScraping.secondLowestSellerShippingTime)
1888
        sheet.write(sheet_iterator, 24, amScraping.thirdLowestSellerSp)
1889
        sheet.write(sheet_iterator, 25, amScraping.thirdLowestSellerRating)
1890
        sheet.write(sheet_iterator, 26, amScraping.thirdLowestSellerShippingTime)
1891
        sheet.write(sheet_iterator, 27, amScraping.lowestMfnIgnoredOffer)
1892
        sheet.write(sheet_iterator, 28, amScraping.lowestMfnOffer)
1893
        sheet.write(sheet_iterator, 29, amScraping.lowestFbaOffer)
1894
        sheet.write(sheet_iterator, 30, amScraping.competitivePrice)
1895
        sheet.write(sheet_iterator, 31, amScraping.otherCost)
1896
        sheet.write(sheet_iterator, 32, amScraping.wanlc)
1897
        sheet.write(sheet_iterator, 33, amScraping.isNlcOverridden)
1898
        sheet.write(sheet_iterator, 34, amScraping.subsidy)
12678 kshitij.so 1899
        if amScraping.isPromotion:
12845 kshitij.so 1900
            sheet.write(sheet_iterator, 35, getMsp(amScraping.item_id,amScraping.warehouseLocation))
12677 kshitij.so 1901
        else:
12845 kshitij.so 1902
            sheet.write(sheet_iterator, 35, 0.0)
1903
        sheet.write(sheet_iterator, 36, amScraping.commission)
1904
        sheet.write(sheet_iterator, 37, amScraping.competitorCommission)
1905
        sheet.write(sheet_iterator, 38, amScraping.returnProvision)
1906
        sheet.write(sheet_iterator, 39, amScraping.vatRate)
1907
        sheet.write(sheet_iterator, 40, getMargin(amScraping))
1908
        sheet.write(sheet_iterator, 41, amScraping.proposedSp)
1909
        sheet.write(sheet_iterator, 42, amScraping.avgSale)
12639 kshitij.so 1910
        try:
1911
            daysOfStock = (float(amScraping.ourInventory))/amScraping.avgSale
1912
        except:
1913
            daysOfStock = float("inf")
12652 kshitij.so 1914
        if str(daysOfStock)=='inf':
12845 kshitij.so 1915
            sheet.write(sheet_iterator, 43, str(daysOfStock))
12652 kshitij.so 1916
        else:
12845 kshitij.so 1917
            sheet.write(sheet_iterator, 43, str(round(daysOfStock,1)))
1918
        sheet.write(sheet_iterator, 44, getOosString(saleMap.get(sku)))
12444 kshitij.so 1919
        if amScraping.decision is None:
12845 kshitij.so 1920
            sheet.write(sheet_iterator, 45, 'Auto Pricing Inactive')
1921
            sheet.write(sheet_iterator, 48, getNewMargin(amScraping,amScraping.proposedSp))
1922
            sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12444 kshitij.so 1923
            sheet_iterator+=1
1924
            continue
12845 kshitij.so 1925
        sheet.write(sheet_iterator, 45, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1926
        sheet.write(sheet_iterator, 46, amScraping.reason)
12444 kshitij.so 1927
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12845 kshitij.so 1928
            sheet.write(sheet_iterator, 47, math.ceil(amScraping.proposedSp))
12444 kshitij.so 1929
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12928 kshitij.so 1930
            sheet.write(sheet_iterator, 47, min(math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice)),amScraping.proposedSp))
12845 kshitij.so 1931
        sheet.write(sheet_iterator, 48, getNewMargin(amScraping,amScraping.proposedSp))
1932
        sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12396 kshitij.so 1933
        sheet_iterator+=1
12928 kshitij.so 1934
 
12396 kshitij.so 1935
 
12639 kshitij.so 1936
#    sheet = wbk.add_sheet('Cheapest')
1937
#    xstr = lambda s: s or ""
1938
#    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1939
#    
1940
#    excel_integer_format = '0'
1941
#    integer_style = xlwt.XFStyle()
1942
#    integer_style.num_format_str = excel_integer_format
1943
#    sheet.write(0, 0, "Item Id", heading_xf)
1944
#    sheet.write(0, 1, "Amazon Sku", heading_xf)
1945
#    sheet.write(0, 2, "Asin", heading_xf)
1946
#    sheet.write(0, 3, "Location", heading_xf)
1947
#    sheet.write(0, 4, "Brand", heading_xf)
1948
#    sheet.write(0, 5, "Category", heading_xf)
1949
#    sheet.write(0, 6, "Product Name", heading_xf)
1950
#    sheet.write(0, 7, "Weight", heading_xf)
1951
#    sheet.write(0, 8, "Courier Cost", heading_xf)
1952
#    sheet.write(0, 9, "Our SP", heading_xf)
1953
#    sheet.write(0, 10, "Promo Price", heading_xf)
1954
#    sheet.write(0, 11, "Is Promotion", heading_xf)
1955
#    sheet.write(0, 12, "Lowest Possible SP", heading_xf)
1956
#    sheet.write(0, 13, "Rank", heading_xf)
1957
#    sheet.write(0, 14, "Our Inventory", heading_xf)
1958
#    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1959
#    sheet.write(0, 16, "Lowest Seller Rating", heading_xf)
1960
#    sheet.write(0, 17, "Lowest Seller Shipping Time", heading_xf)
1961
#    sheet.write(0, 18, "Second Lowest Seller SP", heading_xf)
1962
#    sheet.write(0, 19, "Second Lowest Seller Rating", heading_xf)
1963
#    sheet.write(0, 20, "Second Lowest Seller Shipping Time", heading_xf)
1964
#    sheet.write(0, 21, "Third Lowest Seller SP", heading_xf)
1965
#    sheet.write(0, 22, "Third Lowest Seller Rating", heading_xf)
1966
#    sheet.write(0, 23, "Third Lowest Seller Shipping Time", heading_xf)
1967
#    sheet.write(0, 24, "Other Cost", heading_xf)
1968
#    sheet.write(0, 25, "WANLC", heading_xf)
1969
#    sheet.write(0, 26, "Subsidy", heading_xf)
1970
#    sheet.write(0, 27, "Commission", heading_xf)
1971
#    sheet.write(0, 28, "Competitor Commission", heading_xf)
1972
#    sheet.write(0, 29, "Return Provision", heading_xf)
1973
#    sheet.write(0, 30, "Vat Rate", heading_xf)
1974
#    sheet.write(0, 31, "Margin", heading_xf)
1975
#    sheet.write(0, 32, "Proposed Sp", heading_xf)
1976
#    sheet.write(0, 33, "Avg Sale", heading_xf)
1977
#    sheet.write(0, 34, "Sales History", heading_xf)
1978
#    sheet.write(0, 35, "Decision", heading_xf)
1979
#    sheet.write(0, 36, "Reason", heading_xf)
1980
#    sheet.write(0, 37, "Updated Price", heading_xf)
1981
#    sheet_iterator = 1
12476 kshitij.so 1982
    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 1983
    for cheapestItem in cheapestItems:
1984
        amScraping =  cheapestItem[0]
1985
        item = cheapestItem[1]
1986
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1987
        if amScraping.warehouseLocation == 1:
1988
            sku = 'FBA'+str(amScraping.item_id)
1989
            loc = 'MUMBAI'
12909 kshitij.so 1990
        elif amScraping.warehouseLocation == 2:
12396 kshitij.so 1991
            sku = 'FBB'+str(amScraping.item_id)
1992
            loc = 'BANGLORE'
12909 kshitij.so 1993
        else:
1994
            sku = 'FBG'+str(amScraping.item_id)
1995
            loc = 'GURGAON'
12396 kshitij.so 1996
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1997
        sheet.write(sheet_iterator, 2, amScraping.asin)
12845 kshitij.so 1998
        sheet.write(sheet_iterator, 3, 'http://www.amazon.in/dp/'+amScraping.asin)
1999
        sheet.write(sheet_iterator, 4, loc)
2000
        sheet.write(sheet_iterator, 5, item.brand)
2001
        sheet.write(sheet_iterator, 6, getCategory(item))
2002
        sheet.write(sheet_iterator, 7, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
2003
        sheet.write(sheet_iterator, 8, item.weight)
2004
        sheet.write(sheet_iterator, 9, amScraping.courierCost)
2005
        sheet.write(sheet_iterator, 10, item.mrp)
2006
        sheet.write(sheet_iterator, 11, amScraping.ourSellingPrice)
2007
        sheet.write(sheet_iterator, 12, amScraping.promoPrice)
12432 kshitij.so 2008
        if amScraping.isPromotion:
12845 kshitij.so 2009
            sheet.write(sheet_iterator, 13, "Yes")
12432 kshitij.so 2010
        else:
12845 kshitij.so 2011
            sheet.write(sheet_iterator, 13, "No")
2012
        sheet.write(sheet_iterator, 14, amScraping.lowestPossibleSp)
12396 kshitij.so 2013
        if amScraping.ourRank > 3:
12845 kshitij.so 2014
            sheet.write(sheet_iterator, 15, 'Greater than 3')
12396 kshitij.so 2015
        else:
12845 kshitij.so 2016
            sheet.write(sheet_iterator, 15, amScraping.ourRank)
2017
        sheet.write(sheet_iterator, 16, 'Cheapest')
2018
        sheet.write(sheet_iterator, 17, amScraping.ourInventory)
2019
        sheet.write(sheet_iterator, 18, amScraping.lowestSellerSp)
2020
        sheet.write(sheet_iterator, 19, amScraping.lowestSellerRating)
2021
        sheet.write(sheet_iterator, 20, amScraping.lowestSellerShippingTime)
2022
        sheet.write(sheet_iterator, 21, amScraping.secondLowestSellerSp)
2023
        sheet.write(sheet_iterator, 22, amScraping.secondLowestSellerRating)
2024
        sheet.write(sheet_iterator, 23, amScraping.secondLowestSellerShippingTime)
2025
        sheet.write(sheet_iterator, 24, amScraping.thirdLowestSellerSp)
2026
        sheet.write(sheet_iterator, 25, amScraping.thirdLowestSellerRating)
2027
        sheet.write(sheet_iterator, 26, amScraping.thirdLowestSellerShippingTime)
12639 kshitij.so 2028
        sheet.write(sheet_iterator, 27, '')
2029
        sheet.write(sheet_iterator, 28, '')
12845 kshitij.so 2030
        sheet.write(sheet_iterator, 29, '')
2031
        sheet.write(sheet_iterator, 30, '')
2032
        sheet.write(sheet_iterator, 31, amScraping.otherCost)
2033
        sheet.write(sheet_iterator, 32, amScraping.wanlc)
2034
        sheet.write(sheet_iterator, 33, amScraping.isNlcOverridden)
2035
        sheet.write(sheet_iterator, 34, amScraping.subsidy)
12678 kshitij.so 2036
        if amScraping.isPromotion:
12845 kshitij.so 2037
            sheet.write(sheet_iterator, 35, getMsp(amScraping.item_id,amScraping.warehouseLocation))
12677 kshitij.so 2038
        else:
12845 kshitij.so 2039
            sheet.write(sheet_iterator, 35, 0.0)
2040
        sheet.write(sheet_iterator, 36, amScraping.commission)
2041
        sheet.write(sheet_iterator, 37, amScraping.competitorCommission)
2042
        sheet.write(sheet_iterator, 38, amScraping.returnProvision)
2043
        sheet.write(sheet_iterator, 39, amScraping.vatRate)
2044
        sheet.write(sheet_iterator, 40, getMargin(amScraping))
2045
        sheet.write(sheet_iterator, 41, amScraping.proposedSp)
2046
        sheet.write(sheet_iterator, 42, amScraping.avgSale)
12639 kshitij.so 2047
        try:
2048
            daysOfStock = (float(amScraping.ourInventory))/amScraping.avgSale
2049
        except:
2050
            daysOfStock = float("inf")
12652 kshitij.so 2051
        if str(daysOfStock)=='inf':
12845 kshitij.so 2052
            sheet.write(sheet_iterator, 43, str(daysOfStock))
12652 kshitij.so 2053
        else:
12845 kshitij.so 2054
            sheet.write(sheet_iterator, 43, str(round(daysOfStock,1)))
2055
        sheet.write(sheet_iterator, 44, getOosString(saleMap.get(sku)))
12444 kshitij.so 2056
        if amScraping.decision is None:
12845 kshitij.so 2057
            sheet.write(sheet_iterator, 45, 'Auto Pricing Inactive')
2058
            sheet.write(sheet_iterator, 48, getNewMargin(amScraping,amScraping.proposedSp))
2059
            sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12444 kshitij.so 2060
            sheet_iterator+=1
2061
            continue
12845 kshitij.so 2062
        sheet.write(sheet_iterator, 45, Decision._VALUES_TO_NAMES.get(amScraping.decision))
2063
        sheet.write(sheet_iterator, 46, amScraping.reason)
12444 kshitij.so 2064
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12845 kshitij.so 2065
            sheet.write(sheet_iterator, 47, math.ceil(amScraping.proposedSp))
12444 kshitij.so 2066
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12928 kshitij.so 2067
            sheet.write(sheet_iterator, 47, min(math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice)),amScraping.proposedSp))
12845 kshitij.so 2068
        sheet.write(sheet_iterator, 48, getNewMargin(amScraping,math.ceil(amScraping.promoPrice+max(10,.01*amScraping.promoPrice))))
2069
        sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12396 kshitij.so 2070
        sheet_iterator+=1
2071
 
12803 kshitij.so 2072
    exceptionCheapItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.EXCEPTION).filter(AmazonScrapingHistory.timestamp==timestamp)\
2073
    .filter(or_(AmazonScrapingHistory.exceptionType==3,AmazonScrapingHistory.exceptionType==5)).all()
2074
 
2075
    for exceptionCheapItem in exceptionCheapItems:
2076
        amScraping =  exceptionCheapItem[0]
2077
        item = exceptionCheapItem[1]
2078
        sheet.write(sheet_iterator, 0, amScraping.item_id)
2079
        if amScraping.warehouseLocation == 1:
2080
            sku = 'FBA'+str(amScraping.item_id)
2081
            loc = 'MUMBAI'
12909 kshitij.so 2082
        elif amScraping.warehouseLocation == 2:
12803 kshitij.so 2083
            sku = 'FBB'+str(amScraping.item_id)
2084
            loc = 'BANGLORE'
12909 kshitij.so 2085
        else:
2086
            sku = 'FBG'+str(amScraping.item_id)
2087
            loc = 'GURGAON'
12803 kshitij.so 2088
        sheet.write(sheet_iterator, 1, sku)
2089
        sheet.write(sheet_iterator, 2, amScraping.asin)
12845 kshitij.so 2090
        sheet.write(sheet_iterator, 3, 'http://www.amazon.in/dp/'+amScraping.asin)
2091
        sheet.write(sheet_iterator, 4, loc)
2092
        sheet.write(sheet_iterator, 5, item.brand)
2093
        sheet.write(sheet_iterator, 6, getCategory(item))
2094
        sheet.write(sheet_iterator, 7, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
2095
        sheet.write(sheet_iterator, 8, item.weight)
2096
        sheet.write(sheet_iterator, 9, amScraping.courierCost)
2097
        sheet.write(sheet_iterator, 10, item.mrp)
2098
        sheet.write(sheet_iterator, 11, amScraping.ourSellingPrice)
2099
        sheet.write(sheet_iterator, 12, amScraping.promoPrice)
12803 kshitij.so 2100
        if amScraping.isPromotion:
12845 kshitij.so 2101
            sheet.write(sheet_iterator, 13, "Yes")
12803 kshitij.so 2102
        else:
12845 kshitij.so 2103
            sheet.write(sheet_iterator, 13, "No")
2104
        sheet.write(sheet_iterator, 14, amScraping.lowestPossibleSp)
12803 kshitij.so 2105
        if amScraping.ourRank > 3:
12845 kshitij.so 2106
            sheet.write(sheet_iterator, 15, 'Greater than 3')
12803 kshitij.so 2107
        else:
12845 kshitij.so 2108
            sheet.write(sheet_iterator, 15, amScraping.ourRank)
2109
        sheet.write(sheet_iterator, 16, 'Cheapest')
2110
        sheet.write(sheet_iterator, 17, amScraping.ourInventory)
2111
        sheet.write(sheet_iterator, 18, amScraping.lowestSellerSp)
2112
        sheet.write(sheet_iterator, 19, amScraping.lowestSellerRating)
2113
        sheet.write(sheet_iterator, 20, amScraping.lowestSellerShippingTime)
2114
        sheet.write(sheet_iterator, 21, amScraping.secondLowestSellerSp)
2115
        sheet.write(sheet_iterator, 22, amScraping.secondLowestSellerRating)
2116
        sheet.write(sheet_iterator, 23, amScraping.secondLowestSellerShippingTime)
2117
        sheet.write(sheet_iterator, 24, amScraping.thirdLowestSellerSp)
2118
        sheet.write(sheet_iterator, 25, amScraping.thirdLowestSellerRating)
2119
        sheet.write(sheet_iterator, 26, amScraping.thirdLowestSellerShippingTime)
2120
        sheet.write(sheet_iterator, 27, amScraping.lowestMfnIgnoredOffer)
2121
        sheet.write(sheet_iterator, 28, amScraping.lowestMfnOffer)
2122
        sheet.write(sheet_iterator, 29, amScraping.lowestFbaOffer)
2123
        sheet.write(sheet_iterator, 30, amScraping.competitivePrice)
2124
        sheet.write(sheet_iterator, 31, amScraping.otherCost)
2125
        sheet.write(sheet_iterator, 32, amScraping.wanlc)
2126
        sheet.write(sheet_iterator, 33, amScraping.isNlcOverridden)
2127
        sheet.write(sheet_iterator, 34, amScraping.subsidy)
12803 kshitij.so 2128
        if amScraping.isPromotion:
12845 kshitij.so 2129
            sheet.write(sheet_iterator, 35, getMsp(amScraping.item_id,amScraping.warehouseLocation))
12803 kshitij.so 2130
        else:
12845 kshitij.so 2131
            sheet.write(sheet_iterator, 35, 0.0)
2132
        sheet.write(sheet_iterator, 36, amScraping.commission)
2133
        sheet.write(sheet_iterator, 37, amScraping.competitorCommission)
2134
        sheet.write(sheet_iterator, 38, amScraping.returnProvision)
2135
        sheet.write(sheet_iterator, 39, amScraping.vatRate)
2136
        sheet.write(sheet_iterator, 40, getMargin(amScraping))
2137
        sheet.write(sheet_iterator, 41, amScraping.proposedSp)
2138
        sheet.write(sheet_iterator, 42, amScraping.avgSale)
12803 kshitij.so 2139
        try:
2140
            daysOfStock = (float(amScraping.ourInventory))/amScraping.avgSale
2141
        except:
2142
            daysOfStock = float("inf")
2143
        if str(daysOfStock)=='inf':
12845 kshitij.so 2144
            sheet.write(sheet_iterator, 43, str(daysOfStock))
12803 kshitij.so 2145
        else:
12845 kshitij.so 2146
            sheet.write(sheet_iterator, 43, str(round(daysOfStock,1)))
2147
        sheet.write(sheet_iterator, 44, getOosString(saleMap.get(sku)))
2148
        sheet.write(sheet_iterator, 45, 'AUTO_INCREMENT_FAILED')
12803 kshitij.so 2149
        if amScraping.exceptionType==3:
12845 kshitij.so 2150
            sheet.write(sheet_iterator, 46, 'We are the only seller')
12803 kshitij.so 2151
        else:
12845 kshitij.so 2152
            sheet.write(sheet_iterator, 46, amScraping.reason)
2153
        sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12803 kshitij.so 2154
        sheet_iterator+=1
2155
 
2156
 
12639 kshitij.so 2157
#    sheet = wbk.add_sheet('Negative Margin')
2158
#    xstr = lambda s: s or ""
2159
#    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
2160
#    
2161
#    excel_integer_format = '0'
2162
#    integer_style = xlwt.XFStyle()
2163
#    integer_style.num_format_str = excel_integer_format
2164
#    sheet.write(0, 0, "Item Id", heading_xf)
2165
#    sheet.write(0, 1, "Amazon Sku", heading_xf)
2166
#    sheet.write(0, 2, "Asin", heading_xf)
2167
#    sheet.write(0, 3, "Location", heading_xf)
2168
#    sheet.write(0, 4, "Brand", heading_xf)
2169
#    sheet.write(0, 5, "Category", heading_xf)
2170
#    sheet.write(0, 6, "Product Name", heading_xf)
2171
#    sheet.write(0, 7, "Weight", heading_xf)
2172
#    sheet.write(0, 8, "Courier Cost", heading_xf)
2173
#    sheet.write(0, 9, "Our SP", heading_xf)
2174
#    sheet.write(0, 10, "Promo Price", heading_xf)
2175
#    sheet.write(0, 11, "Is Promotion", heading_xf)
2176
#    sheet.write(0, 12, "Lowest Possible SP", heading_xf)
2177
#    sheet.write(0, 13, "Rank", heading_xf)
2178
#    sheet.write(0, 14, "Our Inventory", heading_xf)
2179
#    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
2180
#    sheet.write(0, 16, "Lowest Seller Rating", heading_xf)
2181
#    sheet.write(0, 17, "Lowest Seller Shipping Time", heading_xf)
2182
#    sheet.write(0, 18, "Second Lowest Seller SP", heading_xf)
2183
#    sheet.write(0, 19, "Second Lowest Seller Rating", heading_xf)
2184
#    sheet.write(0, 20, "Second Lowest Seller Shipping Time", heading_xf)
2185
#    sheet.write(0, 21, "Third Lowest Seller SP", heading_xf)
2186
#    sheet.write(0, 22, "Third Lowest Seller Rating", heading_xf)
2187
#    sheet.write(0, 23, "Third Lowest Seller Shipping Time", heading_xf)
2188
#    sheet.write(0, 24, "Other Cost", heading_xf)
2189
#    sheet.write(0, 25, "WANLC", heading_xf)
2190
#    sheet.write(0, 26, "Subsidy", heading_xf)
2191
#    sheet.write(0, 27, "Commission", heading_xf)
2192
#    sheet.write(0, 28, "Competitor Commission", heading_xf)
2193
#    sheet.write(0, 29, "Return Provision", heading_xf)
2194
#    sheet.write(0, 30, "Vat Rate", heading_xf)
2195
#    sheet.write(0, 31, "Margin", heading_xf)
2196
#    sheet.write(0, 32, "Avg Sale", heading_xf)
2197
#    sheet.write(0, 33, "Sales History", heading_xf)
2198
#    
2199
#    sheet_iterator = 1
2200
    negativeMargins = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.NEGATIVE_MARGIN).filter(AmazonScrapingHistory.timestamp==timestamp).all()
2201
    for negativeMarginItem in negativeMargins:
2202
        amScraping =  negativeMarginItem[0]
2203
        item = negativeMarginItem[1]
12396 kshitij.so 2204
        sheet.write(sheet_iterator, 0, amScraping.item_id)
2205
        if amScraping.warehouseLocation == 1:
2206
            sku = 'FBA'+str(amScraping.item_id)
2207
            loc = 'MUMBAI'
12909 kshitij.so 2208
        elif amScraping.warehouseLocation == 2:
12396 kshitij.so 2209
            sku = 'FBB'+str(amScraping.item_id)
2210
            loc = 'BANGLORE'
12909 kshitij.so 2211
        else:
2212
            sku = 'FBG'+str(amScraping.item_id)
2213
            loc = 'GURGAON'
12396 kshitij.so 2214
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 2215
        sheet.write(sheet_iterator, 2, amScraping.asin)
12845 kshitij.so 2216
        sheet.write(sheet_iterator, 3, 'http://www.amazon.in/dp/'+amScraping.asin)
2217
        sheet.write(sheet_iterator, 4, loc)
2218
        sheet.write(sheet_iterator, 5, item.brand)
2219
        sheet.write(sheet_iterator, 6, getCategory(item))
2220
        sheet.write(sheet_iterator, 7, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
2221
        sheet.write(sheet_iterator, 8, item.weight)
2222
        sheet.write(sheet_iterator, 9, amScraping.courierCost)
2223
        sheet.write(sheet_iterator, 10, item.mrp)
2224
        sheet.write(sheet_iterator, 11, amScraping.ourSellingPrice)
2225
        sheet.write(sheet_iterator, 12, amScraping.promoPrice)
12432 kshitij.so 2226
        if amScraping.isPromotion:
12845 kshitij.so 2227
            sheet.write(sheet_iterator, 13, "Yes")
12432 kshitij.so 2228
        else:
12845 kshitij.so 2229
            sheet.write(sheet_iterator, 13, "No")
2230
        sheet.write(sheet_iterator, 14, amScraping.lowestPossibleSp)
12396 kshitij.so 2231
        if amScraping.ourRank > 3:
12845 kshitij.so 2232
            sheet.write(sheet_iterator, 15, 'Greater than 3')
12396 kshitij.so 2233
        else:
12845 kshitij.so 2234
            sheet.write(sheet_iterator, 15, amScraping.ourRank)
2235
        sheet.write(sheet_iterator, 16, 'Negative Margin')
2236
        sheet.write(sheet_iterator, 17, amScraping.ourInventory)
2237
        sheet.write(sheet_iterator, 18, amScraping.lowestSellerSp)
2238
        sheet.write(sheet_iterator, 19, amScraping.lowestSellerRating)
2239
        sheet.write(sheet_iterator, 20, amScraping.lowestSellerShippingTime)
2240
        sheet.write(sheet_iterator, 21, amScraping.secondLowestSellerSp)
2241
        sheet.write(sheet_iterator, 22, amScraping.secondLowestSellerRating)
2242
        sheet.write(sheet_iterator, 23, amScraping.secondLowestSellerShippingTime)
2243
        sheet.write(sheet_iterator, 24, amScraping.thirdLowestSellerSp)
2244
        sheet.write(sheet_iterator, 25, amScraping.thirdLowestSellerRating)
2245
        sheet.write(sheet_iterator, 26, amScraping.thirdLowestSellerShippingTime)
12639 kshitij.so 2246
        sheet.write(sheet_iterator, 27, '')
2247
        sheet.write(sheet_iterator, 28, '')
12845 kshitij.so 2248
        sheet.write(sheet_iterator, 29, '')
2249
        sheet.write(sheet_iterator, 30, '')
2250
        sheet.write(sheet_iterator, 31, amScraping.otherCost)
2251
        sheet.write(sheet_iterator, 32, amScraping.wanlc)
2252
        sheet.write(sheet_iterator, 33, amScraping.isNlcOverridden)
2253
        sheet.write(sheet_iterator, 34, amScraping.subsidy)
12678 kshitij.so 2254
        if amScraping.isPromotion:
12845 kshitij.so 2255
            sheet.write(sheet_iterator, 35, getMsp(amScraping.item_id,amScraping.warehouseLocation))
12677 kshitij.so 2256
        else:
12845 kshitij.so 2257
            sheet.write(sheet_iterator, 35, 0.0)
2258
        sheet.write(sheet_iterator, 36, amScraping.commission)
2259
        sheet.write(sheet_iterator, 37, amScraping.competitorCommission)
2260
        sheet.write(sheet_iterator, 38, amScraping.returnProvision)
2261
        sheet.write(sheet_iterator, 39, amScraping.vatRate)
2262
        sheet.write(sheet_iterator, 40, getMargin(amScraping))
2263
        sheet.write(sheet_iterator, 42, amScraping.avgSale)
12639 kshitij.so 2264
        try:
2265
            daysOfStock = (float(amScraping.ourInventory))/amScraping.avgSale
2266
        except:
2267
            daysOfStock = float("inf")
12652 kshitij.so 2268
        if str(daysOfStock)=='inf':
12845 kshitij.so 2269
            sheet.write(sheet_iterator, 43, str(daysOfStock))
12652 kshitij.so 2270
        else:
12845 kshitij.so 2271
            sheet.write(sheet_iterator, 43, str(round(daysOfStock,1)))
2272
        sheet.write(sheet_iterator, 44, getOosString(saleMap.get(sku)))
2273
        sheet.write(sheet_iterator, 49, getInventoryMovementStatus(amScraping))
12396 kshitij.so 2274
        sheet_iterator+=1
2275
 
2276
    sheet = wbk.add_sheet('Exception List')
2277
    xstr = lambda s: s or ""
2278
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
2279
 
2280
    excel_integer_format = '0'
2281
    integer_style = xlwt.XFStyle()
2282
    integer_style.num_format_str = excel_integer_format
2283
 
2284
    sheet.write(0, 0, "Item Id", heading_xf)
2285
    sheet.write(0, 1, "Amazon Sku", heading_xf)
2286
    sheet.write(0, 2, "Asin", heading_xf)
12845 kshitij.so 2287
    sheet.write(0, 3, "URL", heading_xf)
2288
    sheet.write(0, 4, "Location", heading_xf)
2289
    sheet.write(0, 5, "Brand", heading_xf)
2290
    sheet.write(0, 6, "Category", heading_xf)
2291
    sheet.write(0, 7, "Product Name", heading_xf)
2292
    sheet.write(0, 8, "MRP", heading_xf)
2293
    sheet.write(0, 9, "Selling Price", heading_xf)
2294
    sheet.write(0, 10, "Promo Price", heading_xf)
2295
    sheet.write(0, 11, "Inventory", heading_xf)
2296
    sheet.write(0, 12, "Avg Sale", heading_xf)
2297
    sheet.write(0, 13, "NOD", heading_xf)
2298
    sheet.write(0, 14, "Sales History", heading_xf)
2299
    sheet.write(0, 15, "Inventory Movement Status", heading_xf)
2300
    sheet.write(0, 16, "Reason", heading_xf)
12396 kshitij.so 2301
 
2302
    sheet_iterator = 1
12803 kshitij.so 2303
    exceptionListItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.EXCEPTION).filter(AmazonScrapingHistory.timestamp==timestamp).all()
2304
    for exceptionListItem in exceptionListItems:
2305
        amScraping =  exceptionListItem[0]
2306
        if amScraping.exceptionType in (3,5):
2307
            continue
2308
        item = exceptionListItem[1]
12396 kshitij.so 2309
        sheet.write(sheet_iterator, 0, amScraping.item_id)
2310
        if amScraping.warehouseLocation == 1:
2311
            sku = 'FBA'+str(amScraping.item_id)
2312
            loc = 'MUMBAI'
12909 kshitij.so 2313
        elif amScraping.warehouseLocation == 2:
12396 kshitij.so 2314
            sku = 'FBB'+str(amScraping.item_id)
2315
            loc = 'BANGLORE'
12909 kshitij.so 2316
        else:
2317
            sku = 'FBG'+str(amScraping.item_id)
2318
            loc = 'GURGAON'
12396 kshitij.so 2319
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 2320
        sheet.write(sheet_iterator, 2, amScraping.asin)
12845 kshitij.so 2321
        sheet.write(sheet_iterator, 3, 'http://www.amazon.in/dp/'+amScraping.asin)
2322
        sheet.write(sheet_iterator, 4, loc)
2323
        sheet.write(sheet_iterator, 5, item.brand)
2324
        sheet.write(sheet_iterator, 6, getCategory(item))
2325
        sheet.write(sheet_iterator, 7, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
2326
        sheet.write(sheet_iterator, 8, item.mrp)
2327
        sheet.write(sheet_iterator, 9, amScraping.ourSellingPrice)
2328
        sheet.write(sheet_iterator, 10, amScraping.promoPrice)
2329
        sheet.write(sheet_iterator, 11, amScraping.ourInventory)
2330
        sheet.write(sheet_iterator, 12, amScraping.avgSale)
12803 kshitij.so 2331
        try:
2332
            daysOfStock = (float(amScraping.ourInventory))/amScraping.avgSale
2333
        except:
2334
            daysOfStock = float("inf")
2335
        if str(daysOfStock)=='inf':
12845 kshitij.so 2336
            sheet.write(sheet_iterator, 13, str(daysOfStock))
12803 kshitij.so 2337
        else:
12845 kshitij.so 2338
            sheet.write(sheet_iterator, 13, str(round(daysOfStock,1)))
2339
        sheet.write(sheet_iterator, 14, getOosString(saleMap.get(sku)))
2340
        sheet.write(sheet_iterator, 15, getInventoryMovementStatus(amScraping))
2341
        sheet.write(sheet_iterator, 16, amScraping.reason)
12396 kshitij.so 2342
        sheet_iterator+=1      
2343
 
12444 kshitij.so 2344
 
12639 kshitij.so 2345
    if (runType in ('FULL','FULL-OTHER')):    
12444 kshitij.so 2346
        sheet = wbk.add_sheet('Auto Favorites')
2347
 
2348
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
2349
 
2350
        excel_integer_format = '0'
2351
        integer_style = xlwt.XFStyle()
2352
        integer_style.num_format_str = excel_integer_format
2353
        xstr = lambda s: s or ""
2354
 
2355
        sheet.write(0, 0, "Item ID", heading_xf)
2356
        sheet.write(0, 1, "Brand", heading_xf)
2357
        sheet.write(0, 2, "Product Name", heading_xf)
2358
        sheet.write(0, 3, "Auto Favourite", heading_xf)
2359
        sheet.write(0, 4, "Reason", heading_xf)
2360
 
2361
        sheet_iterator=1
2362
        for autoFav in nowAutoFav:
2363
            itemId = autoFav[0]
2364
            reason = autoFav[1]
2365
            it = Item.query.filter_by(id=itemId).one()
2366
            sheet.write(sheet_iterator, 0, itemId)
2367
            sheet.write(sheet_iterator, 1, it.brand)
2368
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
2369
            sheet.write(sheet_iterator, 3, "True")
2370
            sheet.write(sheet_iterator, 4, reason)
2371
            sheet_iterator+=1
2372
        for prevFav in previousAutoFav:
2373
            it = Item.query.filter_by(id=prevFav).one()
2374
            sheet.write(sheet_iterator, 0, prevFav)
2375
            sheet.write(sheet_iterator, 1, it.brand)
2376
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
2377
            sheet.write(sheet_iterator, 3, "False")
2378
            sheet_iterator+=1
2379
 
12478 kshitij.so 2380
    filename = "/tmp/amazon-report-"+runType+" " + str(timestamp) + ".xls"
12396 kshitij.so 2381
    wbk.save(filename)
12489 kshitij.so 2382
    try:
12677 kshitij.so 2383
        #EmailAttachmentSender.mail("build@shop2020.in", "cafe@nes", ["kshitij.sood@saholic.com"], " Amazon Auto Pricing "+runType+" " + str(timestamp), "", [get_attachment_part(filename)], [""], [])
2384
        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","amit.gupta@saholic.com","kshitij.sood@saholic.com","chaitnaya.vats@saholic.com","khushal.bhatia@saholic.com"], [])
12489 kshitij.so 2385
    except Exception as e:
2386
        print e
2387
        print "Unable to send report.Trying with local SMTP"
2388
        smtpServer = smtplib.SMTP('localhost')
2389
        smtpServer.set_debuglevel(1)
2390
        sender = 'build@shop2020.in'
12677 kshitij.so 2391
        #recipients = ["kshitij.sood@saholic.com"]
12489 kshitij.so 2392
        msg = MIMEMultipart()
2393
        msg['Subject'] = "Amazon Auto Pricing" + ' '+runType+' - ' + str(datetime.now())
2394
        msg['From'] = sender
12677 kshitij.so 2395
        recipients = ['rajneesh.arora@saholic.com','anikendra.das@saholic.com','amit.gupta@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 2396
        msg['To'] = ",".join(recipients)
2397
        fileMsg = email.mime.base.MIMEBase('application','vnd.ms-excel')
2398
        fileMsg.set_payload(file(filename).read())
2399
        email.encoders.encode_base64(fileMsg)
2400
        fileMsg.add_header('Content-Disposition','attachment;filename=amazon-auto-pricing.xls')
2401
        msg.attach(fileMsg)
2402
        try:
2403
            smtpServer.sendmail(sender, recipients, msg.as_string())
2404
            print "Successfully sent email"
2405
        except:
2406
            print "Error: unable to send email."
2407
 
12803 kshitij.so 2408
def getVatRate(item_id,state,price):
12489 kshitij.so 2409
    itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==item_id, ItemVatMaster.stateId==state)).first()
2410
    if itemVatMaster is None:
2411
        d_item = Item.query.filter_by(id=item_id).first()
2412
        if d_item is None:
2413
            raise 
2414
        else:
2415
            vatMaster = CategoryVatMaster.query.filter(and_(CategoryVatMaster.categoryId==d_item.category, CategoryVatMaster.minVal<=price,  CategoryVatMaster.maxVal>=price,  CategoryVatMaster.stateId == state)).first()
2416
        if vatMaster is None:
2417
            raise
2418
        else:
2419
            vatRate = vatMaster.vatPercent
2420
    else:
2421
        vatRate = itemVatMaster.vatPercentage
2422
    return vatRate
2423
 
2424
def sendAutoPricingMail(successfulAutoDecrease,successfulAutoIncrease):
2425
    if len(successfulAutoDecrease)==0 and len(successfulAutoIncrease)==0 :
2426
        return
2427
    xstr = lambda s: s or ""
2428
    message="""<html>
2429
            <body>
2430
            <h3>Auto Decrease Items</h3>
2431
            <table border="1" style="width:100%;">
2432
            <thead>
2433
            <tr><th>Item Id</th>
2434
            <th>Amazon SKU</th>
2435
            <th>Product Name</th>
2436
            <th>Old Price</th>
2437
            <th>New Price</th>
2438
            <th>Subsidy</th>
2439
            <th>Old Margin</th>
2440
            <th>New Margin</th>
2441
            <th>Commission %</th>
2442
            <th>Return Provision %</th>
2443
            <th>Inventory</th>
2444
            <th>Sales History</th>
2445
            <th>Category</th>
12711 kshitij.so 2446
            <th>isListed</th>
2447
            <th>Price Feed Suppressed</th>
12489 kshitij.so 2448
            </tr></thead>
2449
            <tbody>"""
2450
    for item in successfulAutoDecrease:
2451
        it = Item.query.filter_by(id=item.item_id).one()
12711 kshitij.so 2452
        amItem = Amazonlisted.get_by(itemId=item.item_id)
2453
        isListed =""
2454
        priceSuppress =""
2455
        if item.warehouseLocation==1:
2456
            if amItem.isFba:
2457
                isListed = "Yes"
2458
            else:
2459
                isListed = "No"
2460
            if amItem.suppressFbaPriceUpdate:
2461
                priceSuppress = "Yes"
12716 kshitij.so 2462
            else:   
2463
                priceSuppress = "No"
2464
        elif item.warehouseLocation==2:
2465
            if amItem.isFbb:
2466
                isListed = "Yes"
12711 kshitij.so 2467
            else:
12716 kshitij.so 2468
                isListed = "No"
2469
            if amItem.suppressFbbPriceUpdate:
2470
                priceSuppress = "Yes"
2471
            else:
12711 kshitij.so 2472
                priceSuppress = "No"
12909 kshitij.so 2473
        elif item.warehouseLocation==3:
2474
            if amItem.isFbg:
2475
                isListed = "Yes"
2476
            else:
2477
                isListed = "No"
2478
            if amItem.suppressFbgPriceUpdate:
2479
                priceSuppress = "Yes"
2480
            else:
2481
                priceSuppress = "No"
12716 kshitij.so 2482
        else:
12909 kshitij.so 2483
            continue
12736 kshitij.so 2484
        #vatRate = getNewVatRate(item.item_id,item.warehouseLocation,item.proposedSp)
12556 anikendra 2485
        #oldMargin = item.ourSellingPrice - item.lowestPossibleSp
12736 kshitij.so 2486
        oldMargin = getMargin(item)
2487
        #newMargin = round(item.proposedSp - getNewLowestPossibleSp(item,12.36,vatRate))
2488
        newMargin = getNewMargin(item,item.proposedSp)
12489 kshitij.so 2489
        sku = ''
2490
        if item.warehouseLocation==1:
2491
            sku='FBA'+str(item.item_id)
12909 kshitij.so 2492
        elif item.warehouseLocation==2:
2493
            sku='FBB'+str(item.item_id)
12489 kshitij.so 2494
        else:
12909 kshitij.so 2495
            sku='FBG'+str(item.item_id)
12489 kshitij.so 2496
        if amazonLongTermActivePromotions.has_key(sku):
2497
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
2498
        elif amazonShortTermActivePromotions.has_key(sku):
2499
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
2500
        else:
2501
            subsidy = 0
2502
        message+="""<tr>
2503
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
2504
                <td style="text-align:center">"""+sku+"""</td>
2505
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
12556 anikendra 2506
                <td style="text-align:center">"""+str(item.promoPrice)+"""</td>
12489 kshitij.so 2507
                <td style="text-align:center">"""+str(math.ceil(item.proposedSp))+"""</td>
2508
                <td style="text-align:center">"""+str(round(subsidy))+"""</td>
12716 kshitij.so 2509
                <td style="text-align:center">"""+str(round(oldMargin))+" ("+str(round((oldMargin/item.promoPrice)*100,1))+"%)"+"""</td>
12501 kshitij.so 2510
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/item.proposedSp)*100,1))+"%)"+"""</td>
12489 kshitij.so 2511
                <td style="text-align:center">"""+str(item.commission)+" %"+"""</td>
2512
                <td style="text-align:center">"""+str(item.returnProvision)+" %"+"""</td>
2513
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
2514
                <td style="text-align:center">"""+getOosString(saleMap.get(sku))+"""</td>
2515
                <td style="text-align:center">"""+str(CompetitionCategory._VALUES_TO_NAMES.get(item.competitiveCategory))+"""</td>
12711 kshitij.so 2516
                <td style="text-align:center">"""+isListed+"""</td>
2517
                <td style="text-align:center">"""+priceSuppress+"""</td>
12489 kshitij.so 2518
                </tr>"""
2519
    message+="""</tbody></table><h3>Auto Increase Items</h3><table border="1" style="width:100%;">
2520
            <thead>
2521
            <tr><th>Item Id</th>
2522
            <th>Amazon SKU</th>
2523
            <th>Product Name</th>
2524
            <th>Old Price</th>
2525
            <th>New Price</th>
2526
            <th>Subsidy</th>
2527
            <th>Old Margin</th>
2528
            <th>New Margin</th>
2529
            <th>Commission %</th>
2530
            <th>Return Provision %</th>
2531
            <th>Inventory</th>
2532
            <th>Sales History</th>
2533
            <th>Category</th>
12711 kshitij.so 2534
            <th>isListed</th>
2535
            <th>Price Feed Suppressed</th>
12489 kshitij.so 2536
            </tr></thead>
2537
            <tbody>"""
2538
    for item in successfulAutoIncrease:
2539
        it = Item.query.filter_by(id=item.item_id).one()
12711 kshitij.so 2540
        amItem = Amazonlisted.get_by(itemId=item.item_id)
2541
        isListed =""
2542
        priceSuppress =""
2543
        if item.warehouseLocation==1:
2544
            if amItem.isFba:
2545
                isListed = "Yes"
2546
            else:
2547
                isListed = "No"
2548
            if amItem.suppressFbaPriceUpdate:
2549
                priceSuppress = "Yes"
2550
            else:
2551
                priceSuppress = "No"
12716 kshitij.so 2552
        elif item.warehouseLocation==2:
2553
            if amItem.isFbb:
2554
                isListed = "Yes"
2555
            else:
2556
                isListed = "No"
2557
            if amItem.suppressFbbPriceUpdate:
2558
                priceSuppress = "Yes"
2559
            else:
2560
                priceSuppress = "No"
12909 kshitij.so 2561
        elif item.warehouseLocation==3:
2562
            if amItem.isFbg:
2563
                isListed = "Yes"
2564
            else:
2565
                isListed = "No"
2566
            if amItem.suppressFbgPriceUpdate:
2567
                priceSuppress = "Yes"
2568
            else:
2569
                priceSuppress = "No"
12716 kshitij.so 2570
        else:
12909 kshitij.so 2571
            continue
12736 kshitij.so 2572
        #vatRate = getNewVatRate(item.item_id,item.warehouseLocation,math.ceil(item.promoPrice+max(10,.01*item.promoPrice)))
12556 anikendra 2573
        #oldMargin = item.ourSellingPrice - item.lowestPossibleSp
12736 kshitij.so 2574
        oldMargin = getMargin(item)
2575
        #newMargin = round(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)) - getNewLowestPossibleSp(item,12.36,vatRate))
12916 kshitij.so 2576
        newMargin = getNewMargin(item,math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp)))
12489 kshitij.so 2577
        sku = ''
2578
        if item.warehouseLocation==1:
2579
            sku='FBA'+str(item.item_id)
12909 kshitij.so 2580
        elif item.warehouseLocation==2:
2581
            sku='FBB'+str(item.item_id)
12489 kshitij.so 2582
        else:
12909 kshitij.so 2583
            sku='FBG'+str(item.item_id)
12489 kshitij.so 2584
        if amazonLongTermActivePromotions.has_key(sku):
2585
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
2586
        elif amazonShortTermActivePromotions.has_key(sku):
2587
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
2588
        else:
2589
            subsidy = 0
2590
        message+="""<tr>
2591
                <td style="text-align:center">"""+str(item.item_id)+"""</td>
2592
                <td style="text-align:center">"""+sku+"""</td>
2593
                <td style="text-align:center">"""+xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)+"""</td>
12556 anikendra 2594
                <td style="text-align:center">"""+str(item.promoPrice)+"""</td>
12916 kshitij.so 2595
                <td style="text-align:center">"""+str(math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp)))+"""</td>
12489 kshitij.so 2596
                <td style="text-align:center">"""+str(round(subsidy))+"""</td>
12711 kshitij.so 2597
                <td style="text-align:center">"""+str(round((oldMargin),1))+" ("+str(round((oldMargin/item.promoPrice)*100,1))+"%)"+"""</td>
12916 kshitij.so 2598
                <td style="text-align:center">"""+str(newMargin)+" ("+str(round((newMargin/(math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp))))*100,1))+"%)"+"""</td>
12489 kshitij.so 2599
                <td style="text-align:center">"""+str(item.commission)+" %"+"""</td>
2600
                <td style="text-align:center">"""+str(item.returnProvision)+" %"+"""</td>
2601
                <td style="text-align:center">"""+str(item.ourInventory)+"""</td>
2602
                <td style="text-align:center">"""+getOosString(saleMap.get(sku))+"""</td>
2603
                <td style="text-align:center">"""+str(CompetitionCategory._VALUES_TO_NAMES.get(item.competitiveCategory))+"""</td>
12711 kshitij.so 2604
                <td style="text-align:center">"""+isListed+"""</td>
2605
                <td style="text-align:center">"""+priceSuppress+"""</td>
12489 kshitij.so 2606
                </tr>"""
12711 kshitij.so 2607
    message+="""</tbody></table><h3>Create Listing On Our Dashboard - Stock is present in FC</h3><table border="1" style="width:100%;">
2608
            <thead>
2609
            <tr><th>Item Id</th>
2610
            <th>Amazon SKU</th>
2611
            <th>Product Name</th></tr></thead>
2612
            <tbody>
2613
            """
2614
    for sku in notListed:
12712 kshitij.so 2615
        try:
2616
            it = Item.query.filter_by(id=int(sku[3:])).one()
2617
            productName = xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color)
2618
        except:
2619
            it = None
2620
            productName = "Not found"
12711 kshitij.so 2621
        message+="""<tr>
2622
        <td style="text-align:center">"""+sku[3:]+"""</td>
2623
        <td style="text-align:center">"""+sku+"""</td>
12712 kshitij.so 2624
        <td style="text-align:center">"""+productName+"""</td>
12711 kshitij.so 2625
        </tr>"""
12489 kshitij.so 2626
    message+="""</tbody></table></body></html>"""
2627
    print message
2628
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2629
    mailServer.ehlo()
2630
    mailServer.starttls()
2631
    mailServer.ehlo()
2632
 
12677 kshitij.so 2633
    #recipients = ['kshitij.sood@saholic.com']
2634
    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 2635
    msg = MIMEMultipart()
2636
    msg['Subject'] = "Amazon Auto Pricing" + ' - ' + str(datetime.now())
2637
    msg['From'] = ""
2638
    msg['To'] = ",".join(recipients)
2639
    msg.preamble = "Amazon Auto Pricing" + ' - ' + str(datetime.now())
2640
    html_msg = MIMEText(message, 'html')
2641
    msg.attach(html_msg)
2642
    try:
2643
        mailServer.login("build@shop2020.in", "cafe@nes")
2644
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2645
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2646
    except Exception as e:
2647
        print e
2648
        print "Unable to send pricing mail.Lets try with local SMTP."
2649
        smtpServer = smtplib.SMTP('localhost')
2650
        smtpServer.set_debuglevel(1)
2651
        sender = 'build@shop2020.in'
2652
        try:
2653
            smtpServer.sendmail(sender, recipients, msg.as_string())
2654
            print "Successfully sent email"
2655
        except:
2656
            print "Error: unable to send email."
2657
 
12526 anikendra 2658
def generateCategoryMap():
2659
    global categoryMap
2660
    result = session.query(Category.id,Category.display_name).all()
2661
    for cat in result:
12597 kshitij.so 2662
        categoryMap[cat.id] = cat.display_name
12526 anikendra 2663
 
12639 kshitij.so 2664
def sendAlertForNegativeMargins(timestamp):
2665
    negativeMargins = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.NEGATIVE_MARGIN).filter(AmazonScrapingHistory.timestamp==timestamp).all()
2666
    if negativeMargins[0] is None or len(negativeMargins[0])==0:
2667
        return
2668
    xstr = lambda s: s or ""
2669
    message="""<html>
2670
            <body>
2671
            <h3 style="color:red;">Amazon FC Negative Margins</h3>
2672
            <table border="1" style="width:100%;">
2673
            <thead>
2674
            <tr><th>Item Id</th>
2675
            <th>Amazon SKU</th>
2676
            <th>Product Name</th>
2677
            <th>Selling Price</th>
2678
            <th>Promo Price</th>
2679
            <th>Subsidy</th>
2680
            <th>Lowest Possible SP</th>
12647 kshitij.so 2681
            <th>WANLC</th>
12639 kshitij.so 2682
            <th>Margin</th>
2683
            <th>Commission %</th>
2684
            <th>Return Provision %</th>
2685
            <th>Inventory</th>
2686
            <th>Sales History</th>
2687
            </tr></thead>
2688
            <tbody>"""
2689
    for negativeMarginItems in negativeMargins:
2690
        amScraping = negativeMarginItems[0]
2691
        item = negativeMarginItems[1]
2692
        if amScraping.warehouseLocation==1:
12642 kshitij.so 2693
            sku='FBA'+str(amScraping.item_id)
12909 kshitij.so 2694
        elif amScraping.warehouseLocation==2:
2695
            sku='FBB'+str(amScraping.item_id)
12639 kshitij.so 2696
        else:
12909 kshitij.so 2697
            sku='FBG'+str(amScraping.item_id)
12644 kshitij.so 2698
        if amazonLongTermActivePromotions.has_key(sku):
2699
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
2700
        elif amazonShortTermActivePromotions.has_key(sku):
12639 kshitij.so 2701
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
2702
        else:
2703
            subsidy = 0
2704
        message+="""<tr>
2705
                <td style="text-align:center">"""+str(amScraping.item_id)+"""</td>
12644 kshitij.so 2706
                <td style="text-align:center">"""+sku+"""</td>
12639 kshitij.so 2707
                <td style="text-align:center">"""+xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color)+"""</td>
2708
                <td style="text-align:center">"""+str(amScraping.ourSellingPrice)+"""</td>
2709
                <td style="text-align:center">"""+str(amScraping.promoPrice)+"""</td>
2710
                <td style="text-align:center">"""+str(subsidy)+"""</td>
2711
                <td style="text-align:center">"""+str(amScraping.lowestPossibleSp)+"""</td>
2712
                <td style="text-align:center">"""+str(amScraping.wanlc)+"""</td>
12736 kshitij.so 2713
                <td style="text-align:center">"""+str(round(getMargin(amScraping)))+" ("+str(round((getMargin(amScraping)/amScraping.promoPrice)*100,1))+"%)"+"""</td>
12639 kshitij.so 2714
                <td style="text-align:center">"""+str(amScraping.commission)+" %"+"""</td>
2715
                <td style="text-align:center">"""+str(amScraping.returnProvision)+" %"+"""</td>
2716
                <td style="text-align:center">"""+str(amScraping.ourInventory)+"""</td>
12645 kshitij.so 2717
                <td style="text-align:center">"""+getOosString(saleMap.get(sku))+"""</td>
12639 kshitij.so 2718
                </tr>"""
2719
    message+="""</tbody></table></body></html>"""
2720
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2721
    mailServer.ehlo()
2722
    mailServer.starttls()
2723
    mailServer.ehlo()
2724
 
12677 kshitij.so 2725
    #recipients = ['kshitij.sood@saholic.com']
2726
    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']
12639 kshitij.so 2727
    msg = MIMEMultipart()
2728
    msg['Subject'] = "Amazon Negative Margin" + ' - ' + str(datetime.now())
2729
    msg['From'] = ""
2730
    msg['To'] = ",".join(recipients)
2731
    msg.preamble = "Amazon Negative Margin" + ' - ' + str(datetime.now())
2732
    html_msg = MIMEText(message, 'html')
2733
    msg.attach(html_msg)
2734
    try:
2735
        mailServer.login("build@shop2020.in", "cafe@nes")
2736
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2737
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2738
    except Exception as e:
2739
        print e
2740
        print "Unable to send Amazon Negative margin mail.Lets try local SMTP"
2741
        smtpServer = smtplib.SMTP('localhost')
2742
        smtpServer.set_debuglevel(1)
2743
        sender = 'build@shop2020.in'
2744
        try:
2745
            smtpServer.sendmail(sender, recipients, msg.as_string())
2746
            print "Successfully sent email"
2747
        except:
2748
            print "Error: unable to send email."
2749
 
2750
def sendAlertForCantCompete(timestamp):
2751
    cantCompeteItemsList = session.query(AmazonScrapingHistory).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).filter(AmazonScrapingHistory.timestamp==timestamp).all()
12649 kshitij.so 2752
    print cantCompeteItemsList
12639 kshitij.so 2753
    if cantCompeteItemsList is None or len(cantCompeteItemsList)==0:
2754
        return
2755
    xstr = lambda s: s or ""
2756
    message="""<html>
2757
            <body>
2758
            <h3 style="color:red;">Amazon FC Cant Compete Items</h3>
2759
            <table border="1" style="width:100%;">
2760
            <thead>
2761
            <tr><th>Item Id</th>
2762
            <th>Amazon SKU</th>
2763
            <th>Product Name</th>
2764
            <th>Selling Price</th>
2765
            <th>Promo Price</th>
2766
            <th>Subsidy</th>
2767
            <th>Lowest Possible SP</th>
2768
            <th>WANLC</th>
2769
            <th>Margin</th>
2770
            <th>Commission %</th>
2771
            <th>Return Provision %</th>
2772
            <th>Competitive Price</th>
12651 kshitij.so 2773
            <th>Proposed SP</th>
12639 kshitij.so 2774
            <th>Inventory</th>
2775
            <th>Sales History</th>
2776
            </tr></thead>
2777
            <tbody>"""
12649 kshitij.so 2778
    cantCompeteItems = sorted(list(cantCompeteItemsList), key=lambda x: x.ourInventory, reverse=True)
12639 kshitij.so 2779
    for cantCompeteItem in cantCompeteItems:
2780
        amScraping = cantCompeteItem
2781
        item = Item.query.filter_by(id=amScraping.item_id).one()
2782
        if amScraping.warehouseLocation==1:
12642 kshitij.so 2783
            sku='FBA'+str(amScraping.item_id)
12909 kshitij.so 2784
        elif amScraping.warehouseLocation==2:
2785
            sku='FBB'+str(amScraping.item_id)
12639 kshitij.so 2786
        else:
12909 kshitij.so 2787
            sku='FBG'+str(amScraping.item_id)
12644 kshitij.so 2788
        if amazonLongTermActivePromotions.has_key(sku):
2789
            subsidy = (amazonLongTermActivePromotions.get(sku)).subsidy
2790
        elif amazonShortTermActivePromotions.has_key(sku):
12639 kshitij.so 2791
            subsidy = (amazonShortTermActivePromotions.get(sku)).subsidy
2792
        else:
2793
            subsidy = 0
2794
        message+="""<tr>
2795
                <td style="text-align:center">"""+str(amScraping.item_id)+"""</td>
12644 kshitij.so 2796
                <td style="text-align:center">"""+sku+"""</td>
12639 kshitij.so 2797
                <td style="text-align:center">"""+xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color)+"""</td>
2798
                <td style="text-align:center">"""+str(amScraping.ourSellingPrice)+"""</td>
2799
                <td style="text-align:center">"""+str(amScraping.promoPrice)+"""</td>
2800
                <td style="text-align:center">"""+str(subsidy)+"""</td>
2801
                <td style="text-align:center">"""+str(amScraping.lowestPossibleSp)+"""</td>
2802
                <td style="text-align:center">"""+str(amScraping.wanlc)+"""</td>
12736 kshitij.so 2803
                <td style="text-align:center">"""+str(round(getMargin(amScraping)))+" ("+str(round((getMargin(amScraping)/amScraping.promoPrice)*100,1))+"%)"+"""</td>
12639 kshitij.so 2804
                <td style="text-align:center">"""+str(amScraping.commission)+" %"+"""</td>
2805
                <td style="text-align:center">"""+str(amScraping.returnProvision)+" %"+"""</td>
2806
                <td style="text-align:center">"""+str(amScraping.competitivePrice)+" %"+"""</td>
2807
                <td style="text-align:center">"""+str(amScraping.proposedSp)+" %"+"""</td>
2808
                <td style="text-align:center">"""+str(amScraping.ourInventory)+"""</td>
12645 kshitij.so 2809
                <td style="text-align:center">"""+getOosString(saleMap.get(sku))+"""</td>
12639 kshitij.so 2810
                </tr>"""
2811
    message+="""</tbody></table></body></html>"""
2812
    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
2813
    mailServer.ehlo()
2814
    mailServer.starttls()
2815
    mailServer.ehlo()
2816
 
12677 kshitij.so 2817
    #recipients = ['kshitij.sood@saholic.com']
2818
    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']
12639 kshitij.so 2819
    msg = MIMEMultipart()
2820
    msg['Subject'] = "Amazon Cant Compete Items" + ' - ' + str(datetime.now())
2821
    msg['From'] = ""
2822
    msg['To'] = ",".join(recipients)
2823
    msg.preamble = "Amazon Cant Compete Items" + ' - ' + str(datetime.now())
2824
    html_msg = MIMEText(message, 'html')
2825
    msg.attach(html_msg)
2826
    try:
2827
        mailServer.login("build@shop2020.in", "cafe@nes")
2828
        #mailServer.sendmail("cafe@nes", ['kshitij.sood@saholic.com'], msg.as_string())
2829
        mailServer.sendmail("cafe@nes", recipients, msg.as_string())
2830
    except Exception as e:
2831
        print e
2832
        print "Unable to send Amazon Cant Compete Items mail.Lets try local SMTP"
2833
        smtpServer = smtplib.SMTP('localhost')
2834
        smtpServer.set_debuglevel(1)
2835
        sender = 'build@shop2020.in'
2836
        try:
2837
            smtpServer.sendmail(sender, recipients, msg.as_string())
2838
            print "Successfully sent email"
2839
        except:
12711 kshitij.so 2840
            print "Error: unable to send email."
12639 kshitij.so 2841
 
12711 kshitij.so 2842
def commitPricing(successfulAutoDecrease,successfulAutoIncrease):
2843
    if len(successfulAutoDecrease)==0 and len(successfulAutoIncrease)==0 :
2844
        return
2845
    for item in successfulAutoDecrease:
2846
        amItem = Amazonlisted.get_by(itemId=item.item_id)
2847
        if item.warehouseLocation==1:
2848
            if item.isPromotion:
2849
                amItem.fbaPromoPrice = math.ceil(item.proposedSp)
2850
            else:
2851
                amItem.fbaPrice = math.ceil(item.proposedSp)
2852
            amItem.fbaPriceLastUpdatedOn = datetime.now()
2853
        elif item.warehouseLocation==2:
2854
            if item.isPromotion:
2855
                amItem.fbbPromoPrice = math.ceil(item.proposedSp)
2856
            else:
2857
                amItem.fbbPrice = math.ceil(item.proposedSp)
12718 kshitij.so 2858
            amItem.fbbPriceLastUpdatedOn = datetime.now()
12909 kshitij.so 2859
        elif item.warehouseLocation==3:
2860
            if item.isPromotion:
2861
                amItem.fbgPromoPrice = math.ceil(item.proposedSp)
2862
            else:
2863
                amItem.fbgPrice = math.ceil(item.proposedSp)
2864
            amItem.fbgPriceLastUpdatedOn = datetime.now()
12716 kshitij.so 2865
        else:
12909 kshitij.so 2866
            continue
12715 kshitij.so 2867
    session.commit()
12711 kshitij.so 2868
    for item in successfulAutoIncrease:
2869
        amItem = Amazonlisted.get_by(itemId=item.item_id)
2870
        if item.warehouseLocation==1:
2871
            if item.isPromotion:
12916 kshitij.so 2872
                amItem.fbaPromoPrice = math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp))
12711 kshitij.so 2873
            else:
12916 kshitij.so 2874
                amItem.fbaPrice = math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp))
12711 kshitij.so 2875
            amItem.fbaPriceLastUpdatedOn = datetime.now()
2876
        elif item.warehouseLocation==2:
2877
            if item.isPromotion:
12916 kshitij.so 2878
                amItem.fbbPromoPrice = math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp))
12711 kshitij.so 2879
            else:
12916 kshitij.so 2880
                amItem.fbbPrice = math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp))
12711 kshitij.so 2881
            amItem.fbbPriceLastUpdatedOn = datetime.now()
12909 kshitij.so 2882
        elif item.warehouseLocation==3:
2883
            if item.isPromotion:
12916 kshitij.so 2884
                amItem.fbgPromoPrice = math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp))
12909 kshitij.so 2885
            else:
12916 kshitij.so 2886
                amItem.fbgPrice = math.ceil(min(math.ceil(item.promoPrice+max(10,.01*item.promoPrice)),item.proposedSp))
12909 kshitij.so 2887
            amItem.fbgPriceLastUpdatedOn = datetime.now()
12716 kshitij.so 2888
        else:
12909 kshitij.so 2889
            continue
12715 kshitij.so 2890
    session.commit()
2891
 
12711 kshitij.so 2892
 
12363 kshitij.so 2893
def main():
2894
    parser = optparse.OptionParser()
2895
    parser.add_option("-t", "--type", dest="runType",
2896
                   default="FULL", type="string",
12639 kshitij.so 2897
                   help="Run type FULL or FAVOURITE or FULL-OTHER")
12363 kshitij.so 2898
    (options, args) = parser.parse_args()
12639 kshitij.so 2899
    if options.runType not in ('FULL','FAVOURITE','FULL-OTHER'):
12363 kshitij.so 2900
        print "Run type argument illegal."
2901
        sys.exit(1)
12597 kshitij.so 2902
    time.sleep(5)
12363 kshitij.so 2903
    timestamp = datetime.now()
12526 anikendra 2904
    generateCategoryMap()
12363 kshitij.so 2905
    fetchFbaSale()
2906
    itemInfo = populateStuff(timestamp,options.runType)
2907
    itemsToPopulate = 0
12430 kshitij.so 2908
    toSync = 0
2909
    lenItems = len(itemInfo)
2910
    while(toSync < lenItems):
2911
        oldSync = toSync
2912
        if lenItems >= 20:
2913
            toSync = 20
2914
        else:
2915
            toSync = lenItems - oldSync
2916
        getPriceAndAsin(itemInfo[oldSync:toSync+oldSync])
2917
        toSync = oldSync + toSync
2918
 
12363 kshitij.so 2919
    while (len(itemInfo)>0):
12430 kshitij.so 2920
        if len(itemInfo) >= 20:
2921
            itemsToPopulate = 20
12363 kshitij.so 2922
        else:
2923
            itemsToPopulate = len(itemInfo)
12597 kshitij.so 2924
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate],timestamp)
12363 kshitij.so 2925
        itemInfo[0:itemsToPopulate] = []
2926
        commitExceptionList(exceptionList,timestamp,options.runType)
2927
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
2928
        commitCheapest(cheapest,timestamp,options.runType)
2929
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
2930
        commitCanCompete(canCompete,timestamp,options.runType)
2931
        commitAlmostCompete(almostCompete,timestamp,options.runType)
2932
        commitCantCompete(cantCompete, timestamp,options.runType)
12396 kshitij.so 2933
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
2934
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
2935
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
2936
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
12444 kshitij.so 2937
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,options.runType)
12711 kshitij.so 2938
    commitPricing(autoDecreaseItems,autoIncreaseItems)
12491 kshitij.so 2939
    sendAutoPricingMail(autoDecreaseItems,autoIncreaseItems)
12639 kshitij.so 2940
    if options.runType == 'FULL-OTHER':
2941
        sendAlertForNegativeMargins(timestamp)
2942
        sendAlertForCantCompete(timestamp)
12363 kshitij.so 2943
if __name__=='__main__':
12526 anikendra 2944
    main()