Subversion Repositories SmartDukaan

Rev

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