Subversion Repositories SmartDukaan

Rev

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