Subversion Repositories SmartDukaan

Rev

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