Subversion Repositories SmartDukaan

Rev

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