Subversion Repositories SmartDukaan

Rev

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

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