Subversion Repositories SmartDukaan

Rev

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