Subversion Repositories SmartDukaan

Rev

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