Subversion Repositories SmartDukaan

Rev

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