Subversion Repositories SmartDukaan

Rev

Rev 12845 | Rev 12909 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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