Subversion Repositories SmartDukaan

Rev

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