Subversion Repositories SmartDukaan

Rev

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

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