Subversion Repositories SmartDukaan

Rev

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

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