Subversion Repositories SmartDukaan

Rev

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