Subversion Repositories SmartDukaan

Rev

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