Subversion Repositories SmartDukaan

Rev

Rev 12539 | Rev 12597 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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