Subversion Repositories SmartDukaan

Rev

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