Subversion Repositories SmartDukaan

Rev

Rev 12473 | Rev 12476 | 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
12363 kshitij.so 23
 
24
 
25
config_client = ConfigClient()
26
host = config_client.get_property('staging_hostname')
27
syncPrice=config_client.get_property('sync_price_on_marketplace')
28
 
29
amazonAsinPrice={}
12432 kshitij.so 30
amazonLongTermActivePromotions = {}
31
amazonShortTermActivePromotions = {}
12363 kshitij.so 32
saleMap = {}
33
DataService.initialize(db_hostname=host)
34
 
12430 kshitij.so 35
amScraper = AmazonAsyncScraper.Products("AKIAII3SGRXBJDPCHSGQ", "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg", "AF6E3O0VE0X4D")
12363 kshitij.so 36
 
37
class __AmazonItemInfo:
38
 
12447 kshitij.so 39
    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 40
        self.asin = asin
12363 kshitij.so 41
        self.nlc = nlc
42
        self.courierCost = courierCost
43
        self.sku = sku
44
        self.product_group = product_group
45
        self.brand = brand
46
        self.model_name = model_name
47
        self.model_number = model_number
48
        self.color = color
49
        self.weight = weight
50
        self.parent_category = parent_category
51
        self.risky = risky
52
        self.vatRate = vatRate
53
        self.runType = runType
54
        self.parent_category_name = parent_category_name
55
        self.sourcePercentage = sourcePercentage
56
        self.ourInventory = ourInventory
57
        self.state_id = state_id
12447 kshitij.so 58
        self.otherCost = otherCost
12363 kshitij.so 59
 
60
class __AmazonDetails:
12430 kshitij.so 61
    def __init__(self, sku, ourSp, ourRank, lowestSellerName,lowestSellerSp,secondLowestSellerName, secondLowestSellerSp, thirdLowestSellerName, thirdLowestSellerSp, totalSeller, multipleListings, \
62
                 promoPrice, isPromotion, lowestSellerShippingTime, lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , \
63
                 thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType):
12363 kshitij.so 64
        self.sku =sku
65
        self.ourSp = ourSp
66
        self.ourRank = ourRank
67
        self.lowestSellerName = lowestSellerName
68
        self.lowestSellerSp = lowestSellerSp
69
        self.secondLowestSellerName = secondLowestSellerName
70
        self.secondLowestSellerSp = secondLowestSellerSp
71
        self.thirdLowestSellerName = thirdLowestSellerName
72
        self.thirdLowestSellerSp = thirdLowestSellerSp
73
        self.totalSeller = totalSeller
12430 kshitij.so 74
        self.multipleListings = multipleListings
75
        self.promoPrice = promoPrice
76
        self.isPromotion = isPromotion
77
        self.lowestSellerShippingTime =lowestSellerShippingTime
78
        self.lowestSellerRating = lowestSellerRating
79
        self.secondLowestSellerShippingTime = secondLowestSellerShippingTime
80
        self.secondLowestSellerRating = secondLowestSellerRating
81
        self.thirdLowestSellerShippingTime= thirdLowestSellerShippingTime
82
        self.thirdLowestSellerRating = thirdLowestSellerRating
83
        self.lowestSellerType = lowestSellerType
84
        self.secondLowestSellerType = secondLowestSellerType
12447 kshitij.so 85
        self.thirdLowestSellerType = thirdLowestSellerType
12430 kshitij.so 86
 
12363 kshitij.so 87
 
88
class __AmazonPricing:
89
 
12432 kshitij.so 90
    def __init__(self, ourSp, lowestPossibleSp):
12363 kshitij.so 91
        self.ourSp = ourSp
92
        self.lowestPossibleSp = lowestPossibleSp
93
 
12432 kshitij.so 94
class __Promotion:
12433 kshitij.so 95
    def __init__(self, promoPrice, subsidy, promotionType,expiryDate):
12432 kshitij.so 96
        self.promoPrice = promoPrice
97
        self.subsidy = subsidy
98
        self.promotionType = promotionType
12433 kshitij.so 99
        self.expiryDate = expiryDate 
12432 kshitij.so 100
 
12363 kshitij.so 101
 
12432 kshitij.so 102
 
12396 kshitij.so 103
def fetchItemsForAutoDecrease(time):
104
    successfulAutoDecrease = []
105
    autoDecrementItems = session.query(AmazonScrapingHistory).join((Amazonlisted,AmazonScrapingHistory.item_id==Amazonlisted.itemId))\
106
    .filter(AmazonScrapingHistory.timestamp==time).filter(or_(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE,AmazonScrapingHistory.competitiveCategory==CompetitionCategory.COMPETITIVE, AmazonScrapingHistory.competitiveCategory==CompetitionCategory.ALMOST_COMPETE ))\
107
    .filter(Amazonlisted.autoDecrement==True).all()
108
    for autoDecrementItem in autoDecrementItems:
109
        if autoDecrementItem.warehouseLocation == 1:
110
            sku = 'FBA'+str(autoDecrementItem.item_id)
111
        else:
112
            sku = 'FBB'+str(autoDecrementItem.item_id)
12432 kshitij.so 113
        if amazonShortTermActivePromotions.has_key(sku):
12396 kshitij.so 114
            markReasonForItem(autoDecrementItem,'Item in short term promotion',Decision.AUTO_DECREMENT_FAILED)
115
            continue
116
        if math.ceil(autoDecrementItem.proposedSp) >= autoDecrementItem.ourSellingPrice:
117
            markReasonForItem(autoDecrementItem,'Proposed SP greater than or equal to current SP',Decision.AUTO_DECREMENT_FAILED)
118
            continue
119
        if autoDecrementItem.proposedSellingPrice < autoDecrementItem.lowestPossibleSp:
120
            markReasonForItem(autoDecrementItem,'Proposed SP less than lowest possible SP',Decision.AUTO_DECREMENT_FAILED)
121
            continue
122
        try:
123
            daysOfStock = (float(autoDecrementItem.ourInventory))/autoDecrementItem.avgSale
124
        except:
125
            daysOfStock = float("inf")
126
        if autoDecrementItem.competitiveCategory == CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE:
127
            if daysOfStock < 20:
128
                markReasonForItem(autoDecrementItem,'Days of stock less than 20',Decision.AUTO_DECREMENT_FAILED)
12433 kshitij.so 129
                continue
12396 kshitij.so 130
 
12433 kshitij.so 131
        if autoDecrementItem.competitiveCategory == CompetitionCategory.COMPETITIVE and not autoDecrementItem.isPromotion:
12396 kshitij.so 132
            if autoDecrementItem.parentCategoryId in [10006,10009,11001]:
12433 kshitij.so 133
                if daysOfStock < 1 :
12396 kshitij.so 134
                    markReasonForItem(autoDecrementItem,'Days of stock less than 1',Decision.AUTO_DECREMENT_FAILED)
12433 kshitij.so 135
                    continue
136
 
12396 kshitij.so 137
            else:
138
                if daysOfStock < 3:
139
                    markReasonForItem(autoDecrementItem,'Days of stock less than 3',Decision.AUTO_DECREMENT_FAILED)
12433 kshitij.so 140
                    continue
141
 
142
        if autoDecrementItem.competitiveCategory == CompetitionCategory.COMPETITIVE and autoDecrementItem.isPromotion:
143
            if autoDecrementItem.parentCategoryId in [10006,10009,11001]:
144
                if (amazonLongTermActivePromotions.get(sku).expiryDate - datetime.now()).days >2 and daysOfStock < 1 :
145
                    markReasonForItem(autoDecrementItem,'Promo Item, expiry after 2 days or not enough stock',Decision.AUTO_DECREMENT_FAILED)
146
                    continue
147
 
148
            else:
149
                if (amazonLongTermActivePromotions.get(sku).expiryDate - datetime.now()).days >2 and daysOfStock < 3:
150
                    markReasonForItem(autoDecrementItem,'Promo Item, expiry after 2 days or not enough stock',Decision.AUTO_DECREMENT_FAILED)
151
                    continue
12396 kshitij.so 152
 
153
        autoDecrementItem.ourEnoughStock=True
154
        autoDecrementItem.decision = Decision.AUTO_DECREMENT_SUCCESS
155
        autoDecrementItem.reason = 'All conditions for auto decrement true'
156
        successfulAutoDecrease.append(autoDecrementItem)
157
    session.commit()
158
    session.close()
159
    return successfulAutoDecrease
160
 
161
def fetchItemsForAutoIncrease(time):
162
    successfulAutoIncrease = []
163
    autoIncrementItems = session.query(AmazonScrapingHistory).join((Amazonlisted,AmazonScrapingHistory.item_id==Amazonlisted.itemId))\
164
    .filter(AmazonScrapingHistory.timestamp==time).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.BUY_BOX)\
165
    .filter(Amazonlisted.autoIncrement==True).all()
166
    transaction_client = TransactionClient().get_client()
167
    for autoIncrementItem in autoIncrementItems:
168
        if autoIncrementItem.warehouseLocation == 1:
169
            sku = 'FBA'+str(autoIncrementItem.item_id)
170
        else:
171
            sku = 'FBB'+str(autoIncrementItem.item_id)
12432 kshitij.so 172
        if amazonShortTermActivePromotions.has_key(sku):
12396 kshitij.so 173
            markReasonForItem(autoIncrementItem,'Item in short term promotion',Decision.AUTO_INCREMENT_FAILED)
174
            continue
175
        if autoIncrementItem.totalSeller==1 and autoIncrementItem.ourRank==1:
176
            markReasonForItem(autoIncrementItem,'We are the only seller',Decision.AUTO_INCREMENT_FAILED)
177
            continue 
178
        if autoIncrementItem.proposedSp <= autoIncrementItem.ourSellingPrice:
179
            markReasonForItem(autoIncrementItem,'Proposed SP less than current SP',Decision.AUTO_INCREMENT_FAILED)
180
            continue
181
        if autoIncrementItem.proposedSellingPrice >=10000 and autoIncrementItem.ourSellingPrice<10000:
182
            markReasonForItem(autoIncrementItem,'Proposed SP is greater than 10,000 and current sp is less than 10,000',Decision.AUTO_INCREMENT_FAILED)
183
            continue
184
 
12447 kshitij.so 185
        if autoIncrementItem.isPromotion and math.ceil(autoIncrementItem.promoPrice+max(10,.01*autoIncrementItem.promoPrice)) > (amazonLongTermActivePromotions.get(sku)).promoPrice:
186
            markReasonForItem(autoIncrementItem,'Proposed SP cant be greater than promo price',Decision.AUTO_INCREMENT_FAILED)
187
            continue
188
 
189
 
12396 kshitij.so 190
        if autoIncrementItem.avgSale==0:
191
            markReasonForItem(autoIncrementItem,'Avg sale is 0',Decision.AUTO_INCREMENT_FAILED)
192
            continue
193
 
194
        daysOfStock = (float(autoIncrementItem.ourInventory))/autoIncrementItem.avgSale
195
        if daysOfStock > 5:
196
            markReasonForItem(autoIncrementItem,'Days of stock greater than 5',Decision.AUTO_INCREMENT_FAILED)
197
            continue
198
        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()
199
        if antecedentPrice is not None:
200
            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:
201
                markReasonForItem(autoIncrementItem,'Maximum price increase in last 24 hours should be 2%',Decision.AUTO_INCREMENT_FAILED)
202
                continue
203
        fbaSaleSnapshot = transaction_client.getAmazonFbaSalesLatestSnapshotForItemLocationWise(autoIncrementItem.item_id,autoIncrementItem.warehouseLocation)
204
        if getLastDaySale(fbaSaleSnapshot,autoIncrementItem.warehouseLocation-1)<=2:
205
            markReasonForItem(autoIncrementItem,'Last day sale is less than 3',Decision.AUTO_INCREMENT_FAILED)
206
            continue
207
 
208
        autoIncrementItem.ourEnoughStock = False
209
        autoIncrementItem.decision = Decision.AUTO_INCREMENT_SUCCESS
210
        autoIncrementItem.reason = 'All conditions for auto increment true'
211
        successfulAutoIncrease.append(autoIncrementItem)
212
    session.commit()
213
    return successfulAutoIncrease     
214
 
215
 
216
def markReasonForItem(amHistory,reason,decision):
217
    amHistory.decision = decision
218
    amHistory.reason = reason
219
 
12424 kshitij.so 220
def calculateAverageSale(sku):
221
    count,sale = 0,0
222
    oosStatus = saleMap.get(sku)
223
    for obj in oosStatus:
224
        if not obj.isOutOfStock:
225
            count+=1
226
            sale = sale+obj.totalOrderCount
227
    avgSalePerDay=0 if count==0 else (float(sale)/count)
228
    return round(avgSalePerDay,2)
229
 
230
 
12396 kshitij.so 231
def getOosString(oosStatus):
232
    lastNdaySale=""
233
    for obj in oosStatus:
12423 kshitij.so 234
        if obj.isOutOfStock:
12396 kshitij.so 235
            lastNdaySale += "X-"
236
        else:
12426 kshitij.so 237
            lastNdaySale += str(obj.totalOrderCount) + "-"
12396 kshitij.so 238
    return lastNdaySale[:-1]
239
 
240
def getLastDaySale(fbaSaleSnapshot):
241
    if fbaSaleSnapshot.item_id==0:
242
        return 0
243
    else:
12423 kshitij.so 244
        return fbaSaleSnapshot.totalOrderCount
12396 kshitij.so 245
 
12430 kshitij.so 246
#def syncAsin():
247
##    notListedOnAmazon = []
248
##    diffAsins = []
249
##    login_url = "https://sellercentral.amazon.in/gp/homepage.html"
250
##    br = SellerCentralInventoryReport.login(login_url)
251
##    report_url = "https://sellercentral.amazon.in/gp/upload-download-utils/requestReport.html?type=OpenListingReport&marketplaceID=44571&Request+Report="
252
##    br = SellerCentralInventoryReport.requestReport(br,report_url)
253
##    status_url="https://sellercentral.amazon.in/gp/upload-download-utils/reportStatusData.html"
254
##    br, page = SellerCentralInventoryReport.checkStatus(br,status_url)
255
##    br, batchId = SellerCentralInventoryReport.getReportBatchId(br,page)
256
##    print "*********************************"
257
##    print "Batch Id for request is ",batchId
258
##    print "*********************************"
259
##    ready = False
260
##    retryCount = 0
261
##    while not ready:
262
##        if retryCount == 10:
263
##            print "File not available for download after multiple retries"
264
##            sys.exit(1)
265
##        br, download_link = SellerCentralInventoryReport.downloadReport(br,batchId,status_url)
266
##        if download_link is not None:
267
##            ready= True
268
##            continue
269
##        print "File not ready for download yet.Will try again after 30 seconds."
270
##        retryCount+=1
271
##        time.sleep(30)
272
##    fPath = SellerCentralInventoryReport.fetchFile(download_link['href'],br,batchId)
273
#    fPath = "/tmp/9940651090.txt"
274
#    global amazonAsinPrice
275
#    for line in open(fPath):
276
#        l = line.split('\t')
277
#        if (str(l[0]).startswith('FBA') or str(l[0]).startswith('FBB')):
278
#            obj = __AmazonAsinPrice(l[1],l[2])
279
#            amazonAsinPrice[l[0]] = obj
280
##Can be used to sync asins, not doing due to multiple asins corresponding to one itemId
281
##    systemAsins = session.query(Item,Amazonlisted).join((Amazonlisted,Item.id==Amazonlisted.itemId)).all()
282
##    for systemAsin in systemAsins:
283
##        item = systemAsin[0]
284
##        amListed = systemAsin[1]
285
##        if amazonAsinPrice.get('FBA'+str(item.id)) is None:
286
##            temp=[]
287
##            temp.append(item)
288
##            temp.append(amListed)
289
##            notListedOnAmazon.append(temp)
290
##            continue
291
##        else:
292
##            temp=[]
293
##            temp.append(item)
294
##            temp.append(amListed)
295
##            if item.asin!=((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip():
296
##                diffAsins.append(temp)
297
##                continue
298
##            
299
##    for diffAsin in diffAsins:
300
##        item = diffAsin[0]
301
##        amListed = diffAsin[1]
302
##        item.asin = ((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip()
303
##        amListed.asin = ((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip()
304
##    session.commit()
305
##    session.close()
12363 kshitij.so 306
 
307
def fetchFbaSale():
308
    global saleMap
309
    transaction_client = TransactionClient().get_client()
310
    fbaSaleSnapshot = transaction_client.getAmazonFbaSalesSnapshotForDays(4)
311
    for saleSnapshot in fbaSaleSnapshot:
312
        if saleSnapshot.fcLocation == 0:
313
            if saleMap.has_key('FBA'+str(saleSnapshot.item_id)):
314
                temp = []
12367 kshitij.so 315
                val = saleMap.get('FBA'+str(saleSnapshot.item_id))
316
                for l in val:
12363 kshitij.so 317
                    temp.append(l)
318
                temp.append(saleSnapshot)
12366 kshitij.so 319
                saleMap['FBA'+str(saleSnapshot.item_id)]=temp
12363 kshitij.so 320
            else:
12368 kshitij.so 321
                temp = []
322
                temp.append(saleSnapshot)
323
                saleMap['FBA'+str(saleSnapshot.item_id)] = temp
12363 kshitij.so 324
        else:
325
            if saleMap.has_key('FBB'+str(saleSnapshot.item_id)):
326
                temp = []
12367 kshitij.so 327
                val = saleMap.get('FBB'+str(saleSnapshot.item_id))
328
                for l in val:
12363 kshitij.so 329
                    temp.append(l)
12368 kshitij.so 330
                saleMap['FBB'+str(saleSnapshot.item_id)]=temp
12363 kshitij.so 331
                temp.append(saleSnapshot)
332
            else:
12368 kshitij.so 333
                temp = []
334
                temp.append(saleSnapshot)
335
                saleMap['FBB'+str(saleSnapshot.item_id)] = temp
12363 kshitij.so 336
 
12424 kshitij.so 337
 
12363 kshitij.so 338
def computeCourierCost(weight):
12378 kshitij.so 339
    try:
340
        cCost = 10.0;
341
        slabs = int((weight*1000)/500-.001)
342
        for slab in range(0,slabs):
343
            cCost = cCost + 10.0;
344
        return cCost;
345
    except:
346
        return 10.0
12363 kshitij.so 347
 
348
 
349
def populateStuff(time,runType):
350
    global amazonLongTermActivePromotions
12396 kshitij.so 351
    global amazonShortTermActivePromotions
12363 kshitij.so 352
    itemInfo = []
353
    inventory_client = InventoryClient().get_client()
354
    fbaAvailableInventorySnapshot = inventory_client.getAllAvailableAmazonFbaItemInventory()
12387 kshitij.so 355
    print len(fbaAvailableInventorySnapshot)
12363 kshitij.so 356
    for fbaInventoryItem in fbaAvailableInventorySnapshot:
357
        d_amazon_listed = Amazonlisted.get_by(itemId=fbaInventoryItem.item_id)
358
        if d_amazon_listed is None:
359
            continue
360
        if d_amazon_listed.overrrideWanlc:
361
            wanlc = d_amazon_listed.exceptionalWanlc
362
        else:
363
            wanlc = inventory_client.getWanNlcForSource(fbaInventoryItem.item_id,OrderSource.AMAZON)
364
        it = Item.query.filter_by(id=fbaInventoryItem.item_id).one()
365
        category = Category.query.filter_by(id=it.category).one()
366
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
367
        scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.AMAZON).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
368
        if scp is not None:
369
            sourcePercentage = scp
370
        else:
371
            spm = SourcePercentageMaster.get_by(source=OrderSource.AMAZON)
372
            sourcePercentage = spm
12375 kshitij.so 373
        if fbaInventoryItem.location==0:
12377 kshitij.so 374
            sku = 'FBA'+str(fbaInventoryItem.item_id)
12363 kshitij.so 375
            state_id = 1
12375 kshitij.so 376
        elif fbaInventoryItem.location==1:
12377 kshitij.so 377
            sku = 'FBB'+str(fbaInventoryItem.item_id)
12363 kshitij.so 378
            state_id = 2
379
        else:
380
            continue
381
        cc = computeCourierCost(it.weight)
12379 kshitij.so 382
 
12447 kshitij.so 383
        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 384
        itemInfo.append(amazonItemInfo)
385
    amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.LONGTERM).filter(AmazonPromotion.promotionActive==True) \
386
    .group_by(AmazonPromotion.sku).order_by(desc(AmazonPromotion.addedOn)).all()
387
    for amPromotion in amPromotions:
12433 kshitij.so 388
        amazonLongTermActivePromotions[amPromotion.sku] = __Promotion(amPromotion.salePrice,amPromotion.subsidy,amPromotion.promotionType,amPromotion.endDate)
12396 kshitij.so 389
    amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.SHORTTERM).filter(AmazonPromotion.promotionActive==True) \
390
    .group_by(AmazonPromotion.sku).order_by(desc(AmazonPromotion.addedOn)).all()
391
    for amPromotion in amPromotions:
12433 kshitij.so 392
        amazonShortTermActivePromotions[amPromotion.sku] = __Promotion(amPromotion.salePrice,amPromotion.subsidy,amPromotion.promotionType,amPromotion.endDate)
12363 kshitij.so 393
    session.close()
12450 kshitij.so 394
    print "No of items populated ",len(itemInfo)
12452 kshitij.so 395
    sleep(5)
12363 kshitij.so 396
    return itemInfo
397
 
12430 kshitij.so 398
def getPriceAndAsin(itemInfo):
399
    skus = []
400
    for item in itemInfo:
401
        skus.append(item.sku)
402
    ourPricingForSku = amScraper.get_my_pricing_for_sku('A21TJRUUN4KGV', skus)
403
    for item in itemInfo:
404
        ourPricing = ourPricingForSku.get(item.sku)
12441 kshitij.so 405
        if ourPricing is None or len(ourPricing.keys())==0:
12430 kshitij.so 406
            item.ourSp = 0
407
            item.promoPrice = 0
408
            item.isPromotion = False
12473 kshitij.so 409
            item.asin = ''
12430 kshitij.so 410
        else:
411
            item.ourSp = ourPricing.get('sellingPrice')
412
            item.promoPrice = ourPricing.get('promoPrice')
413
            item.isPromotion = ourPricing.get('promotion')
12473 kshitij.so 414
            item.asin = ourPricing.get('asin')
12450 kshitij.so 415
 
12430 kshitij.so 416
 
417
 
12363 kshitij.so 418
def decideCategory(itemInfo):
419
    exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = [],[],[],[],[],[],[] 
12430 kshitij.so 420
    skus = []
12363 kshitij.so 421
    for item in itemInfo:
12430 kshitij.so 422
        skus.append(item.sku)
423
    aggResponse = amScraper.get_competitive_pricing_for_sku('A21TJRUUN4KGV', skus)
424
    ourPricingForSku = amScraper.get_my_pricing_for_sku('A21TJRUUN4KGV', skus)
12403 kshitij.so 425
 
12363 kshitij.so 426
    for val in itemInfo:
12430 kshitij.so 427
        scrapInfo = aggResponse.get(val.sku)
12443 kshitij.so 428
        if scrapInfo is None or len(scrapInfo)==0 or val.nlc==0 or len(ourPricingForSku.get(val.sku).keys())==0:
12363 kshitij.so 429
            temp = []
430
            temp.append(val)
431
            if val.nlc==0 or val.nlc is None:
12456 kshitij.so 432
                print "WANLC is 0"
12363 kshitij.so 433
                temp.append("WANLC is 0")
12443 kshitij.so 434
            elif ourPricingForSku.get(val.sku) is None or ourPricingForSku.get(val.sku).keys()==0:
12456 kshitij.so 435
                print "Unable to fetch our price"
12430 kshitij.so 436
                temp.append("Unable to fetch our price")
12363 kshitij.so 437
            else:
12456 kshitij.so 438
                print "Unable to fetch competive pricing"
12430 kshitij.so 439
                temp.append("Unable to fetch competitive pricing")
12363 kshitij.so 440
            exceptionList.append(temp)
441
            continue
12430 kshitij.so 442
        val.ourSp = ourPricingForSku.get(val.sku).get('sellingPrice')
443
        val.promoPrice = ourPricingForSku.get(val.sku).get('promoPrice')
444
        val.isPromo = ourPricingForSku.get(val.sku).get('promotion')
12363 kshitij.so 445
        iterator = 0
446
        sku, lowestSellerName,secondLowestSellerName, thirdLowestSellerName = ('',)*4
12432 kshitij.so 447
        ourSp, ourRank, lowestSellerSp, secondLowestSellerSp, thirdLowestSellerSp, lowestPossibleSp = (0,)*6
12430 kshitij.so 448
        lowestSellerShippingTime, lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , \
449
        thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType = (0,)*9
450
        isPromo = False
12363 kshitij.so 451
        sku = val.sku
452
        multipleListings = False
12430 kshitij.so 453
        ourSkuDetails = ourPricingForSku.get(val.sku)
12475 kshitij.so 454
        if (ourSkuDetails.get('promotion')!=(amazonLongTermActivePromotions.has_key(val.sku) or amazonShortTermActivePromotions.has_key(val.sku))):
12432 kshitij.so 455
            temp = []
456
            temp.append(val)
12456 kshitij.so 457
            print "promo misconfigured"
12432 kshitij.so 458
            temp.append("Promo misconfigured")
12457 kshitij.so 459
            exceptionList.append(temp)
12432 kshitij.so 460
            continue
12475 kshitij.so 461
 
12430 kshitij.so 462
        scrapInfo.append(ourSkuDetails)
463
        sortedScrapInfo =  sorted(scrapInfo, key=itemgetter('promoPrice','notOurSku'))
464
        for info in sortedScrapInfo:
12465 kshitij.so 465
            if  not info['notOurSku']:
12442 kshitij.so 466
                ourSp = info['sellingPrice']
467
                promoPrice = info['promoPrice']
468
                isPromo = info['promotion']
12430 kshitij.so 469
                ourRank = iterator + 1
12363 kshitij.so 470
 
471
            if iterator == 0:
12430 kshitij.so 472
                lowestSellerSp = info['promoPrice']
473
                lowestSellerShippingTime = info['shippingTime']
474
                lowestSellerRating = info['rating']
475
                lowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 476
 
477
            if iterator == 1:
12430 kshitij.so 478
                secondLowestSellerSp = info['promoPrice']
479
                secondLowestSellerShippingTime = info['shippingTime']
480
                secondLowestSellerRating = info['rating']
481
                secondLowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 482
 
483
            if iterator == 2:
12430 kshitij.so 484
                thirdLowestSellerSp = info['promoPrice']
485
                thirdLowestSellerShippingTime = info['shippingTime']
486
                thirdLowestSellerRating = info['rating']
487
                thirdLowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 488
 
489
            iterator += 1
12401 kshitij.so 490
        print "terminating iterator"
12363 kshitij.so 491
 
492
 
12408 kshitij.so 493
        print "Creating object am details",val.sku
12430 kshitij.so 494
        amDetails = __AmazonDetails(sku, float(ourSp), ourRank, lowestSellerName,float(lowestSellerSp),secondLowestSellerName, float(secondLowestSellerSp), thirdLowestSellerName, float(thirdLowestSellerSp),len(scrapInfo),multipleListings,promoPrice,isPromo, \
495
                    lowestSellerShippingTime ,lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType)
12414 kshitij.so 496
        print "am details obj created"
12363 kshitij.so 497
        try:
12414 kshitij.so 498
            print "inside val getter"
12418 kshitij.so 499
            itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==int(val.sku[3:]), ItemVatMaster.stateId==val.state_id)).first()
500
            if itemVatMaster is None:
12419 kshitij.so 501
                d_item = Item.query.filter_by(id=int(val.sku[3:])).first()
502
                if d_item is None:
503
                    raise 
504
                else:
12430 kshitij.so 505
                    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 506
                if vatMaster is None:
12418 kshitij.so 507
                    raise
12419 kshitij.so 508
                else:
509
                    val.vatRate = vatMaster.vatPercent
510
                    print "vat fetched"
12418 kshitij.so 511
            else:
512
                val.vatRate = itemVatMaster.vatPercentage
12419 kshitij.so 513
                print "vat fetched"
12363 kshitij.so 514
        except:
12414 kshitij.so 515
            print "vat exception"
12363 kshitij.so 516
            temp = []
517
            temp.append(val)
518
            temp.append("Vat not available")
519
            exceptionList.append(temp)
520
            continue
521
 
522
        lowestPossibleSp = getLowestPossibleSp(amDetails,val,val.sourcePercentage)
12408 kshitij.so 523
        print "Creating pricing obj"
12432 kshitij.so 524
        amPricing = __AmazonPricing(ourSp,lowestPossibleSp)
12363 kshitij.so 525
 
12467 kshitij.so 526
        if amDetails.promoPrice < amPricing.lowestPossibleSp:
12363 kshitij.so 527
            temp = []
528
            temp.append(val)
529
            temp.append(amDetails)
530
            temp.append(amPricing)
531
            negativeMargin.append(temp)
532
            continue
533
 
534
        if amDetails.ourRank==1:
535
            temp = []
536
            temp.append(val)
537
            temp.append(amDetails)
538
            temp.append(amPricing)
539
            cheapest.append(temp)
540
            continue
541
 
12469 kshitij.so 542
        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 543
            temp = []
544
            temp.append(val)
545
            temp.append(amDetails)
546
            temp.append(amPricing)
547
            amongCheapestAndCanCompete.append(temp)
548
            continue
549
 
550
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp):
551
            temp = []
552
            temp.append(val)
553
            temp.append(amDetails)
554
            temp.append(amPricing)
555
            canCompete.append(temp)
556
            continue
557
 
12403 kshitij.so 558
        if amDetails.lowestSellerSp*(1+.01) >= amPricing.lowestPossibleSp:
12396 kshitij.so 559
            temp = []
560
            temp.append(val)
561
            temp.append(amDetails)
562
            temp.append(amPricing)
563
            almostCompete.append(temp)
564
            continue
565
 
566
 
12363 kshitij.so 567
        temp = []
568
        temp.append(val)
569
        temp.append(amDetails)
570
        temp.append(amPricing)
571
        cantCompete.append(temp)
12414 kshitij.so 572
    print "Created category..."
12363 kshitij.so 573
 
574
    return exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete
12396 kshitij.so 575
 
12363 kshitij.so 576
 
577
def getLowestPossibleSp(amazonDetails,val,spm):
12447 kshitij.so 578
    lowestPossibleSp = (val.nlc+(val.courierCost)*(1+(spm.serviceTax/100))*(1+(val.vatRate/100))+(15+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 579
    if val.isPromo:
580
        if amazonLongTermActivePromotions.has_key(val.sku):
12466 kshitij.so 581
            subsidy = (amazonLongTermActivePromotions.get(val.sku)).subsidy
12432 kshitij.so 582
        else:
12466 kshitij.so 583
            subsidy = (amazonShortTermActivePromotions.get(val.sku)).subsidy
12432 kshitij.so 584
        lowestPossibleSp = lowestPossibleSp - subsidy
12363 kshitij.so 585
    return round(lowestPossibleSp,2)
586
 
587
def getTargetTp(targetSp,spm,val):
12424 kshitij.so 588
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))
12363 kshitij.so 589
    return round(targetTp,2)
590
 
591
def commitExceptionList(exceptionList,timestamp,runType):
592
    for exceptionItem in exceptionList:
593
        val = exceptionItem[0]
594
        reason = exceptionItem[1]
595
        amazonScrapingHistory = AmazonScrapingHistory()
596
        amazonScrapingHistory.item_id = val.sku[3:]
597
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 598
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 599
        amazonScrapingHistory.reason = reason
600
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
601
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.EXCEPTION
602
        amazonScrapingHistory.timestamp = timestamp
603
    session.commit()
604
 
605
def commitNegativeMargin(negativeMargin,timestamp,runType):
606
    for negativeMarginItem in negativeMargin:
607
        val = negativeMarginItem[0]
608
        amDetails = negativeMarginItem[1]
609
        amPricing = negativeMarginItem[2]
610
        spm = val.sourcePercentage
611
        amazonScrapingHistory = AmazonScrapingHistory()
612
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 613
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 614
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 615
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 616
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 617
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 618
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
619
        amazonScrapingHistory.ourRank = amDetails.ourRank
620
        amazonScrapingHistory.ourInventory = val.ourInventory
621
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12468 kshitij.so 622
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
623
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
624
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 625
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 626
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
627
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
628
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 629
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 630
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
631
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
632
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12363 kshitij.so 633
        amazonScrapingHistory.wanlc = val.nlc
12447 kshitij.so 634
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 635
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 636
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 637
        amazonScrapingHistory.returnProvision = spm.returnProvision
638
        amazonScrapingHistory.courierCost = val.courierCost
639
        amazonScrapingHistory.risky = val.risky
640
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
641
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
642
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
643
        amazonScrapingHistory.timestamp = timestamp
644
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
645
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 646
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 647
    session.commit()
648
 
649
 
650
def commitCheapest(cheapest,timestamp,runType):
651
    for cheapestItem in cheapest:
652
        val = cheapestItem[0]
653
        amDetails = cheapestItem[1]
654
        amPricing = cheapestItem[2]
655
        spm = val.sourcePercentage
656
        amazonScrapingHistory = AmazonScrapingHistory()
657
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 658
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 659
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 660
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 661
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 662
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 663
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
664
        amazonScrapingHistory.ourRank = amDetails.ourRank
665
        amazonScrapingHistory.ourInventory = val.ourInventory
666
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 667
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
668
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
669
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 670
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 671
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
672
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
673
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 674
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 675
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
676
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
677
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 678
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 679
        amazonScrapingHistory.wanlc = val.nlc
680
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 681
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 682
        amazonScrapingHistory.returnProvision = spm.returnProvision
683
        amazonScrapingHistory.courierCost = val.courierCost
684
        amazonScrapingHistory.risky = val.risky
685
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
686
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
687
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.BUY_BOX
688
        amazonScrapingHistory.timestamp = timestamp
689
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12430 kshitij.so 690
        proposed_sp = max(amDetails.secondLowestSellerSp - max((20, amDetails.secondLowestSellerSp*0.002)), amPricing.lowestPossibleSp)
12433 kshitij.so 691
        if amazonScrapingHistory.isPromotion:
692
            if amazonLongTermActivePromotions.has_key(val.sku):
12466 kshitij.so 693
                proposed_sp = min(proposed_sp,(amazonLongTermActivePromotions.get(val.sku)).salePrice)
12433 kshitij.so 694
            else:
12466 kshitij.so 695
                proposed_sp = min(proposed_sp,(amazonShortTermActivePromotions.get(val.sku)).salePrice)
12468 kshitij.so 696
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 697
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 698
        #amazonScrapingHistory.proposedTp = proposed_tp
699
        #amazonScrapingHistory.marginIncreasedPotential = proposed_tp - amPricing.ourTp
12363 kshitij.so 700
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
701
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 702
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 703
    session.commit()
704
 
705
 
706
 
707
def commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,runType):
708
    for amongCheapestAndCanCompeteItem in amongCheapestAndCanCompete:
709
        val = amongCheapestAndCanCompeteItem[0]
710
        amDetails = amongCheapestAndCanCompeteItem[1]
711
        amPricing = amongCheapestAndCanCompeteItem[2]
712
        spm = val.sourcePercentage
713
        amazonScrapingHistory = AmazonScrapingHistory()
714
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 715
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 716
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 717
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 718
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 719
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 720
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
721
        amazonScrapingHistory.ourRank = amDetails.ourRank
722
        amazonScrapingHistory.ourInventory = val.ourInventory
723
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 724
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
725
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
726
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 727
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 728
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
729
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
730
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12470 kshitij.so 731
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 732
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
733
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
734
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 735
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 736
        amazonScrapingHistory.wanlc = val.nlc
737
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 738
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 739
        amazonScrapingHistory.returnProvision = spm.returnProvision
740
        amazonScrapingHistory.courierCost = val.courierCost
741
        amazonScrapingHistory.risky = val.risky
742
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
743
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
744
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE
745
        amazonScrapingHistory.timestamp = timestamp
746
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
747
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
12468 kshitij.so 748
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 749
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 750
        #amazonScrapingHistory.proposedTp = proposed_tp
12363 kshitij.so 751
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
752
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 753
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 754
    session.commit()
755
 
756
def commitCanCompete(canCompete,timestamp,runType):
757
    for canCompeteItem in canCompete:
758
        val = canCompeteItem[0]
759
        amDetails = canCompeteItem[1]
760
        amPricing = canCompeteItem[2]
761
        spm = val.sourcePercentage
762
        amazonScrapingHistory = AmazonScrapingHistory()
763
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 764
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 765
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 766
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 767
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 768
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 769
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
770
        amazonScrapingHistory.ourRank = amDetails.ourRank
771
        amazonScrapingHistory.ourInventory = val.ourInventory
772
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 773
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
774
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
775
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 776
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 777
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
778
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
779
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 780
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 781
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
782
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
783
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 784
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 785
        amazonScrapingHistory.wanlc = val.nlc
786
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 787
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 788
        amazonScrapingHistory.returnProvision = spm.returnProvision
789
        amazonScrapingHistory.courierCost = val.courierCost
790
        amazonScrapingHistory.risky = val.risky
791
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
792
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
793
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
794
        amazonScrapingHistory.timestamp = timestamp
795
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
796
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
12468 kshitij.so 797
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
12363 kshitij.so 798
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 799
        #amazonScrapingHistory.proposedTp = proposed_tp
12363 kshitij.so 800
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
801
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 802
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 803
    session.commit()
804
 
12383 kshitij.so 805
def commitAlmostCompete(almostCompete,timestamp,runType):
12396 kshitij.so 806
    for almostCompeteItem in almostCompete:
807
        val = almostCompeteItem[0]
808
        amDetails = almostCompeteItem[1]
809
        amPricing = almostCompeteItem[2]
810
        spm = val.sourcePercentage
811
        amazonScrapingHistory = AmazonScrapingHistory()
812
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 813
        amazonScrapingHistory.asin = val.asin
12396 kshitij.so 814
        amazonScrapingHistory.warehouseLocation = val.state_id
815
        amazonScrapingHistory.parentCategoryId = val.parent_category
816
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 817
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12396 kshitij.so 818
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
819
        amazonScrapingHistory.ourRank = amDetails.ourRank
820
        amazonScrapingHistory.ourInventory = val.ourInventory
821
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 822
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
823
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
824
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12396 kshitij.so 825
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 826
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
827
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
828
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12396 kshitij.so 829
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 830
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
831
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
832
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 833
        amazonScrapingHistory.otherCost = val.otherCost
12396 kshitij.so 834
        amazonScrapingHistory.wanlc = val.nlc
835
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 836
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12396 kshitij.so 837
        amazonScrapingHistory.returnProvision = spm.returnProvision
838
        amazonScrapingHistory.courierCost = val.courierCost
839
        amazonScrapingHistory.risky = val.risky
840
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
841
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
842
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.ALMOST_COMPETE
843
        amazonScrapingHistory.timestamp = timestamp
844
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12425 kshitij.so 845
        proposed_sp = min(amDetails.lowestSellerSp*(1+.01),amPricing.lowestPossibleSp)
12468 kshitij.so 846
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
847
        #target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
12396 kshitij.so 848
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 849
        #amazonScrapingHistory.proposedTp = proposed_tp
850
        #amazonScrapingHistory.targetNlc = target_nlc
12396 kshitij.so 851
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
852
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 853
        amazonScrapingHistory.isPromotion = val.isPromo
12396 kshitij.so 854
    session.commit()
12363 kshitij.so 855
 
12396 kshitij.so 856
 
12363 kshitij.so 857
def commitCantCompete(cantCompete, timestamp,runType):
858
    for cantCompeteItem in cantCompete:
859
        val = cantCompeteItem[0]
860
        amDetails = cantCompeteItem[1]
861
        amPricing = cantCompeteItem[2]
862
        spm = val.sourcePercentage
863
        amazonScrapingHistory = AmazonScrapingHistory()
864
        amazonScrapingHistory.item_id = val.sku[3:]
12471 kshitij.so 865
        amazonScrapingHistory.asin = val.asin
12363 kshitij.so 866
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 867
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 868
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 869
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 870
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
871
        amazonScrapingHistory.ourRank = amDetails.ourRank
872
        amazonScrapingHistory.ourInventory = val.ourInventory
873
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 874
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
875
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
876
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 877
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12468 kshitij.so 878
        amazonScrapingHistory.secondLowestSellerShippingTime = amDetails.secondLowestSellerShippingTime
879
        amazonScrapingHistory.secondLowestSellerRating = amDetails.secondLowestSellerRating
880
        amazonScrapingHistory.secondLowestSellerType = amDetails.secondLowestSellerType
12363 kshitij.so 881
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12468 kshitij.so 882
        amazonScrapingHistory.thirdLowestSellerShippingTime = amDetails.thirdLowestSellerShippingTime
883
        amazonScrapingHistory.thirdLowestSellerRating = amDetails.thirdLowestSellerRating
884
        amazonScrapingHistory.thirdLowestSellerType = amDetails.thirdLowestSellerType
12447 kshitij.so 885
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 886
        amazonScrapingHistory.wanlc = val.nlc
887
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 888
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 889
        amazonScrapingHistory.returnProvision = spm.returnProvision
890
        amazonScrapingHistory.courierCost = val.courierCost
891
        amazonScrapingHistory.risky = val.risky
892
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
893
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
894
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
895
        amazonScrapingHistory.timestamp = timestamp
896
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
897
        proposed_sp = amDetails.lowestSellerSp - max(5, amDetails.lowestSellerSp*0.001)
12468 kshitij.so 898
        #proposed_tp = getTargetTp(proposed_sp,spm,val)
899
        #target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
12363 kshitij.so 900
        amazonScrapingHistory.proposedSp = proposed_sp
12468 kshitij.so 901
        #amazonScrapingHistory.proposedTp = proposed_tp
902
        #amazonScrapingHistory.targetNlc = target_nlc
12363 kshitij.so 903
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
904
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 905
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 906
    session.commit()
907
 
12396 kshitij.so 908
def markAutoFavourites(time):
909
    nowAutoFav = []
910
    previouslyAutoFav = []
911
    stockList = []
912
    saleList = []
913
    items = session.query(func.sum(AmazonScrapingHistory.ourInventory),AmazonScrapingHistory.item_id).group_by(AmazonScrapingHistory.item_id).all()
914
    allItems = session.query(Amazonlisted).all()
915
    for item in items:
916
        reason = ""
917
        if item[0]>=5:
918
            stockList.append(item[1])
919
 
920
    for sku, val in saleMap.iteritems():
921
        totalSale = 0
922
        item_id = sku.replace('FBA','').replace('FBB','')
923
        val =saleMap.get('FBA'+str(item_id))
924
        if val is not None:
925
            for sale in val:
926
                totalSale += sale.totalOrderCount
927
        val =saleMap.get('FBB'+str(item_id))
928
        if val is not None:
929
            for sale in val:
930
                totalSale += sale.totalOrderCount
931
        if totalSale > 0:
932
            saleList.append(item_id)
933
 
934
    for aItem in allItems:
935
        reason = ""
936
        toMark = False
937
        if aItem.itemId in saleList:
938
            toMark = True
939
            reason+="Total FC sale is greater than 1 for last five days.."
940
        if aItem.itemId in stockList:
941
            toMark = True
942
            reason+="Item is present in buy box in last 3 days"
943
        if not aItem.autoFavourite:
944
            print "Item is not under auto favourite"
945
        if toMark:
946
            temp=[]
947
            temp.append(aItem.itemId)
948
            temp.append(reason)
949
            nowAutoFav.append(temp)
950
        if (not toMark) and aItem.autoFavourite:
951
            previouslyAutoFav.append(aItem.itemId)
952
        aItem.autoFavourite = toMark
953
    session.commit()
954
    return previouslyAutoFav, nowAutoFav
955
 
12444 kshitij.so 956
def writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,runType):
12396 kshitij.so 957
    wbk = xlwt.Workbook()
958
    sheet = wbk.add_sheet('Can\'t Compete')
959
    xstr = lambda s: s or ""
960
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
961
 
962
    excel_integer_format = '0'
963
    integer_style = xlwt.XFStyle()
964
    integer_style.num_format_str = excel_integer_format
965
 
966
    sheet.write(0, 0, "Item Id", heading_xf)
967
    sheet.write(0, 1, "Amazon Sku", heading_xf)
968
    sheet.write(0, 2, "Asin", heading_xf)
969
    sheet.write(0, 3, "Location", heading_xf)
970
    sheet.write(0, 4, "Brand", heading_xf)
971
    sheet.write(0, 5, "Product Name", heading_xf)
972
    sheet.write(0, 6, "Weight", heading_xf)
973
    sheet.write(0, 7, "Courier Cost", heading_xf)
974
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 975
    sheet.write(0, 9, "Promo Price", heading_xf)
976
    sheet.write(0, 10, "Is Promotion", heading_xf)
977
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 978
    sheet.write(0, 12, "Rank", heading_xf)
979
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 980
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
981
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
982
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 983
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 984
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
985
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
986
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
987
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
988
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 989
    sheet.write(0, 23, "Other Cost", heading_xf)
990
    sheet.write(0, 24, "WANLC", heading_xf)
991
    sheet.write(0, 25, "Commission", heading_xf)
992
    sheet.write(0, 26, "Competitor Commission", heading_xf)
993
    sheet.write(0, 27, "Return Provision", heading_xf)
994
    sheet.write(0, 28, "Margin", heading_xf)
995
    sheet.write(0, 29, "Risky", heading_xf)
996
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 997
    sheet.write(0, 31, "Avg Sale", heading_xf)
998
    sheet.write(0, 32, "Sales History", heading_xf)
999
    sheet.write(0, 33, "Decision", heading_xf)
1000
    sheet.write(0, 34, "Reason", heading_xf)
1001
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1002
 
1003
    sheet_iterator = 1
1004
    cantCompeteItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
1005
    for cantCompeteItem in cantCompeteItems:
1006
        amScraping =  cantCompeteItem[0]
1007
        item = cantCompeteItem[1]
1008
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1009
        if amScraping.warehouseLocation == 1:
1010
            sku = 'FBA'+str(amScraping.item_id)
1011
            loc = 'MUMBAI'
1012
        else:
1013
            sku = 'FBB'+str(amScraping.item_id)
1014
            loc = 'BANGLORE'
1015
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1016
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1017
        sheet.write(sheet_iterator, 3, loc)
1018
        sheet.write(sheet_iterator, 4, item.brand)
1019
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1020
        sheet.write(sheet_iterator, 6, item.weight)
1021
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1022
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1023
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1024
        if amScraping.isPromotion:
1025
            sheet.write(sheet_iterator, 10, "Yes")
1026
        else:
1027
            sheet.write(sheet_iterator, 10, "Yes")
1028
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1029
        if amScraping.ourRank > 3:
1030
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1031
        else:
1032
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1033
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1034
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1035
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1036
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1037
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1038
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1039
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1040
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1041
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1042
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1043
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1044
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1045
        sheet.write(sheet_iterator, 25, amScraping.commission)
1046
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1047
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1048
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1049
        sheet.write(sheet_iterator, 29, item.risky)
1050
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1051
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1052
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1053
        if amScraping.decision is None:
12468 kshitij.so 1054
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1055
            sheet_iterator+=1
1056
            continue
12468 kshitij.so 1057
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1058
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1059
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12468 kshitij.so 1060
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1061
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1062
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1063
        sheet_iterator+=1
1064
 
1065
    sheet = wbk.add_sheet('Competitive')
1066
    xstr = lambda s: s or ""
1067
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1068
 
1069
    excel_integer_format = '0'
1070
    integer_style = xlwt.XFStyle()
1071
    integer_style.num_format_str = excel_integer_format
1072
 
1073
    sheet.write(0, 0, "Item Id", heading_xf)
1074
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1075
    sheet.write(0, 2, "Asin", heading_xf)
1076
    sheet.write(0, 3, "Location", heading_xf)
1077
    sheet.write(0, 4, "Brand", heading_xf)
1078
    sheet.write(0, 5, "Product Name", heading_xf)
1079
    sheet.write(0, 6, "Weight", heading_xf)
1080
    sheet.write(0, 7, "Courier Cost", heading_xf)
1081
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1082
    sheet.write(0, 9, "Promo Price", heading_xf)
1083
    sheet.write(0, 10, "Is Promotion", heading_xf)
1084
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1085
    sheet.write(0, 12, "Rank", heading_xf)
1086
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1087
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1088
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1089
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1090
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1091
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1092
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1093
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1094
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1095
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1096
    sheet.write(0, 23, "Other Cost", heading_xf)
1097
    sheet.write(0, 24, "WANLC", heading_xf)
1098
    sheet.write(0, 25, "Commission", heading_xf)
1099
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1100
    sheet.write(0, 27, "Return Provision", heading_xf)
1101
    sheet.write(0, 28, "Margin", heading_xf)
1102
    sheet.write(0, 29, "Risky", heading_xf)
1103
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1104
    sheet.write(0, 31, "Avg Sale", heading_xf)
1105
    sheet.write(0, 32, "Sales History", heading_xf)
1106
    sheet.write(0, 33, "Decision", heading_xf)
1107
    sheet.write(0, 34, "Reason", heading_xf)
1108
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1109
 
1110
    sheet_iterator = 1
1111
    competitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.COMPETITIVE).all()
1112
    for competitiveItem in competitiveItems:
1113
        amScraping =  competitiveItem[0]
1114
        item = competitiveItem[1]
1115
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1116
        if amScraping.warehouseLocation == 1:
1117
            sku = 'FBA'+str(amScraping.item_id)
1118
            loc = 'MUMBAI'
1119
        else:
1120
            sku = 'FBB'+str(amScraping.item_id)
1121
            loc = 'BANGLORE'
1122
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1123
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1124
        sheet.write(sheet_iterator, 3, loc)
1125
        sheet.write(sheet_iterator, 4, item.brand)
1126
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1127
        sheet.write(sheet_iterator, 6, item.weight)
1128
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1129
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1130
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1131
        if amScraping.isPromotion:
1132
            sheet.write(sheet_iterator, 10, "Yes")
1133
        else:
1134
            sheet.write(sheet_iterator, 10, "Yes")
1135
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1136
        if amScraping.ourRank > 3:
1137
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1138
        else:
1139
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1140
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1141
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1142
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1143
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1144
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1145
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1146
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1147
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1148
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1149
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1150
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1151
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1152
        sheet.write(sheet_iterator, 25, amScraping.commission)
1153
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1154
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1155
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1156
        sheet.write(sheet_iterator, 29, item.risky)
1157
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1158
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1159
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1160
        if amScraping.decision is None:
12468 kshitij.so 1161
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1162
            sheet_iterator+=1
1163
            continue
12468 kshitij.so 1164
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1165
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1166
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12468 kshitij.so 1167
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1168
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1169
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1170
        sheet_iterator+=1
1171
 
1172
    sheet = wbk.add_sheet('Almost Competitive')
1173
    xstr = lambda s: s or ""
1174
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1175
 
1176
    excel_integer_format = '0'
1177
    integer_style = xlwt.XFStyle()
1178
    integer_style.num_format_str = excel_integer_format
1179
 
1180
    sheet.write(0, 0, "Item Id", heading_xf)
1181
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1182
    sheet.write(0, 2, "Asin", heading_xf)
1183
    sheet.write(0, 3, "Location", heading_xf)
1184
    sheet.write(0, 4, "Brand", heading_xf)
1185
    sheet.write(0, 5, "Product Name", heading_xf)
1186
    sheet.write(0, 6, "Weight", heading_xf)
1187
    sheet.write(0, 7, "Courier Cost", heading_xf)
1188
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1189
    sheet.write(0, 9, "Promo Price", heading_xf)
1190
    sheet.write(0, 10, "Is Promotion", heading_xf)
1191
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1192
    sheet.write(0, 12, "Rank", heading_xf)
1193
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1194
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1195
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1196
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1197
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1198
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1199
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1200
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1201
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1202
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1203
    sheet.write(0, 23, "Other Cost", heading_xf)
1204
    sheet.write(0, 24, "WANLC", heading_xf)
1205
    sheet.write(0, 25, "Commission", heading_xf)
1206
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1207
    sheet.write(0, 27, "Return Provision", heading_xf)
1208
    sheet.write(0, 28, "Margin", heading_xf)
1209
    sheet.write(0, 29, "Risky", heading_xf)
1210
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1211
    sheet.write(0, 31, "Avg Sale", heading_xf)
1212
    sheet.write(0, 32, "Sales History", heading_xf)
1213
    sheet.write(0, 33, "Decision", heading_xf)
1214
    sheet.write(0, 34, "Reason", heading_xf)
1215
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1216
 
1217
    sheet_iterator = 1
1218
    almostCompetitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.ALMOST_COMPETE).all()
1219
    for almostCompetitiveItem in almostCompetitiveItems:
1220
        amScraping =  almostCompetitiveItem[0]
1221
        item = almostCompetitiveItem[1]
1222
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1223
        if amScraping.warehouseLocation == 1:
1224
            sku = 'FBA'+str(amScraping.item_id)
1225
            loc = 'MUMBAI'
1226
        else:
1227
            sku = 'FBB'+str(amScraping.item_id)
1228
            loc = 'BANGLORE'
12432 kshitij.so 1229
        amScraping =  competitiveItem[0]
1230
        item = competitiveItem[1]
1231
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1232
        if amScraping.warehouseLocation == 1:
1233
            sku = 'FBA'+str(amScraping.item_id)
1234
            loc = 'MUMBAI'
1235
        else:
1236
            sku = 'FBB'+str(amScraping.item_id)
1237
            loc = 'BANGLORE'
12396 kshitij.so 1238
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1239
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1240
        sheet.write(sheet_iterator, 3, loc)
1241
        sheet.write(sheet_iterator, 4, item.brand)
1242
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1243
        sheet.write(sheet_iterator, 6, item.weight)
1244
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1245
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1246
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1247
        if amScraping.isPromotion:
1248
            sheet.write(sheet_iterator, 10, "Yes")
1249
        else:
1250
            sheet.write(sheet_iterator, 10, "Yes")
1251
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1252
        if amScraping.ourRank > 3:
1253
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1254
        else:
1255
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1256
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1257
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1258
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1259
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1260
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1261
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1262
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1263
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1264
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1265
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1266
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1267
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1268
        sheet.write(sheet_iterator, 25, amScraping.commission)
1269
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1270
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1271
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1272
        sheet.write(sheet_iterator, 29, item.risky)
1273
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1274
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1275
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1276
        if amScraping.decision is None:
12468 kshitij.so 1277
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1278
            sheet_iterator+=1
1279
            continue
12468 kshitij.so 1280
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1281
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1282
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12468 kshitij.so 1283
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1284
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1285
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1286
        sheet_iterator+=1
1287
 
1288
    sheet = wbk.add_sheet('Among Cheapest')
1289
    xstr = lambda s: s or ""
1290
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1291
 
1292
    excel_integer_format = '0'
1293
    integer_style = xlwt.XFStyle()
1294
    integer_style.num_format_str = excel_integer_format
1295
 
1296
    sheet.write(0, 0, "Item Id", heading_xf)
1297
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1298
    sheet.write(0, 2, "Asin", heading_xf)
1299
    sheet.write(0, 3, "Location", heading_xf)
1300
    sheet.write(0, 4, "Brand", heading_xf)
1301
    sheet.write(0, 5, "Product Name", heading_xf)
1302
    sheet.write(0, 6, "Weight", heading_xf)
1303
    sheet.write(0, 7, "Courier Cost", heading_xf)
1304
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1305
    sheet.write(0, 9, "Promo Price", heading_xf)
1306
    sheet.write(0, 10, "Is Promotion", heading_xf)
1307
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1308
    sheet.write(0, 12, "Rank", heading_xf)
1309
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1310
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1311
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1312
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1313
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1314
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1315
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1316
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1317
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1318
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1319
    sheet.write(0, 23, "Other Cost", heading_xf)
1320
    sheet.write(0, 24, "WANLC", heading_xf)
1321
    sheet.write(0, 25, "Commission", heading_xf)
1322
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1323
    sheet.write(0, 27, "Return Provision", heading_xf)
1324
    sheet.write(0, 28, "Margin", heading_xf)
1325
    sheet.write(0, 29, "Risky", heading_xf)
1326
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1327
    sheet.write(0, 31, "Avg Sale", heading_xf)
1328
    sheet.write(0, 32, "Sales History", heading_xf)
1329
    sheet.write(0, 33, "Decision", heading_xf)
1330
    sheet.write(0, 34, "Reason", heading_xf)
1331
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1332
 
1333
    sheet_iterator = 1
1334
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1335
    for amongCheapestItem in amongCheapestItems:
1336
        amScraping =  amongCheapestItem[0]
1337
        item = amongCheapestItem[1]
1338
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1339
        if amScraping.warehouseLocation == 1:
1340
            sku = 'FBA'+str(amScraping.item_id)
1341
            loc = 'MUMBAI'
1342
        else:
1343
            sku = 'FBB'+str(amScraping.item_id)
1344
            loc = 'BANGLORE'
1345
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1346
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1347
        sheet.write(sheet_iterator, 3, loc)
1348
        sheet.write(sheet_iterator, 4, item.brand)
1349
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1350
        sheet.write(sheet_iterator, 6, item.weight)
1351
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1352
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1353
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1354
        if amScraping.isPromotion:
1355
            sheet.write(sheet_iterator, 10, "Yes")
1356
        else:
1357
            sheet.write(sheet_iterator, 10, "Yes")
1358
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1359
        if amScraping.ourRank > 3:
1360
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1361
        else:
1362
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1363
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1364
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1365
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1366
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1367
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1368
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1369
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1370
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1371
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1372
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1373
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1374
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1375
        sheet.write(sheet_iterator, 25, amScraping.commission)
1376
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1377
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1378
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1379
        sheet.write(sheet_iterator, 29, item.risky)
1380
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1381
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1382
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1383
        if amScraping.decision is None:
12468 kshitij.so 1384
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1385
            sheet_iterator+=1
1386
            continue
12468 kshitij.so 1387
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1388
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1389
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12468 kshitij.so 1390
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1391
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1392
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1393
        sheet_iterator+=1
1394
 
1395
    sheet = wbk.add_sheet('Cheapest')
1396
    xstr = lambda s: s or ""
1397
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1398
 
1399
    excel_integer_format = '0'
1400
    integer_style = xlwt.XFStyle()
1401
    integer_style.num_format_str = excel_integer_format
1402
 
1403
    sheet.write(0, 0, "Item Id", heading_xf)
1404
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1405
    sheet.write(0, 2, "Asin", heading_xf)
1406
    sheet.write(0, 3, "Location", heading_xf)
1407
    sheet.write(0, 4, "Brand", heading_xf)
1408
    sheet.write(0, 5, "Product Name", heading_xf)
1409
    sheet.write(0, 6, "Weight", heading_xf)
1410
    sheet.write(0, 7, "Courier Cost", heading_xf)
1411
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1412
    sheet.write(0, 9, "Promo Price", heading_xf)
1413
    sheet.write(0, 10, "Is Promotion", heading_xf)
1414
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1415
    sheet.write(0, 12, "Rank", heading_xf)
1416
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1417
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1418
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1419
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1420
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1421
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1422
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1423
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1424
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1425
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1426
    sheet.write(0, 23, "Other Cost", heading_xf)
1427
    sheet.write(0, 24, "WANLC", heading_xf)
1428
    sheet.write(0, 25, "Commission", heading_xf)
1429
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1430
    sheet.write(0, 27, "Return Provision", heading_xf)
1431
    sheet.write(0, 28, "Margin", heading_xf)
1432
    sheet.write(0, 29, "Risky", heading_xf)
1433
    sheet.write(0, 30, "Proposed Sp", heading_xf)
12468 kshitij.so 1434
    sheet.write(0, 31, "Avg Sale", heading_xf)
1435
    sheet.write(0, 32, "Sales History", heading_xf)
1436
    sheet.write(0, 33, "Decision", heading_xf)
1437
    sheet.write(0, 34, "Reason", heading_xf)
1438
    sheet.write(0, 35, "Updated Price", heading_xf)
12396 kshitij.so 1439
 
1440
    sheet_iterator = 1
1441
    cheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1442
    for cheapestItem in cheapestItems:
1443
        amScraping =  cheapestItem[0]
1444
        item = cheapestItem[1]
1445
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1446
        if amScraping.warehouseLocation == 1:
1447
            sku = 'FBA'+str(amScraping.item_id)
1448
            loc = 'MUMBAI'
1449
        else:
1450
            sku = 'FBB'+str(amScraping.item_id)
1451
            loc = 'BANGLORE'
1452
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1453
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1454
        sheet.write(sheet_iterator, 3, loc)
1455
        sheet.write(sheet_iterator, 4, item.brand)
1456
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1457
        sheet.write(sheet_iterator, 6, item.weight)
1458
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1459
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1460
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1461
        if amScraping.isPromotion:
1462
            sheet.write(sheet_iterator, 10, "Yes")
1463
        else:
1464
            sheet.write(sheet_iterator, 10, "Yes")
1465
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1466
        if amScraping.ourRank > 3:
1467
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1468
        else:
1469
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1470
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1471
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1472
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1473
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1474
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1475
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1476
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1477
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1478
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1479
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1480
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1481
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1482
        sheet.write(sheet_iterator, 25, amScraping.commission)
1483
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1484
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1485
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1486
        sheet.write(sheet_iterator, 29, item.risky)
1487
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
12468 kshitij.so 1488
        sheet.write(sheet_iterator, 31, amScraping.avgSale)
1489
        sheet.write(sheet_iterator, 32, getOosString(saleMap.get(sku)))
12444 kshitij.so 1490
        if amScraping.decision is None:
12468 kshitij.so 1491
            sheet.write(sheet_iterator, 33, 'Auto Pricing Inactive')
12444 kshitij.so 1492
            sheet_iterator+=1
1493
            continue
12468 kshitij.so 1494
        sheet.write(sheet_iterator, 33, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1495
        sheet.write(sheet_iterator, 34, amScraping.reason)
12444 kshitij.so 1496
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12468 kshitij.so 1497
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1498
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12468 kshitij.so 1499
            sheet.write(sheet_iterator, 35, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1500
        sheet_iterator+=1
1501
 
1502
    sheet = wbk.add_sheet('Negative Margin')
1503
    xstr = lambda s: s or ""
1504
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1505
 
1506
    excel_integer_format = '0'
1507
    integer_style = xlwt.XFStyle()
1508
    integer_style.num_format_str = excel_integer_format
1509
 
1510
    sheet.write(0, 0, "Item Id", heading_xf)
1511
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1512
    sheet.write(0, 2, "Asin", heading_xf)
1513
    sheet.write(0, 3, "Location", heading_xf)
1514
    sheet.write(0, 4, "Brand", heading_xf)
1515
    sheet.write(0, 5, "Product Name", heading_xf)
1516
    sheet.write(0, 6, "Weight", heading_xf)
1517
    sheet.write(0, 7, "Courier Cost", heading_xf)
1518
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1519
    sheet.write(0, 9, "Promo Price", heading_xf)
1520
    sheet.write(0, 10, "Is Promotion", heading_xf)
1521
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1522
    sheet.write(0, 12, "Rank", heading_xf)
1523
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1524
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1525
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1526
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1527
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1528
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1529
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1530
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1531
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1532
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1533
    sheet.write(0, 23, "Other Cost", heading_xf)
1534
    sheet.write(0, 24, "WANLC", heading_xf)
1535
    sheet.write(0, 25, "Commission", heading_xf)
1536
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1537
    sheet.write(0, 27, "Return Provision", heading_xf)
1538
    sheet.write(0, 28, "Margin", heading_xf)
1539
    sheet.write(0, 29, "Avg Sale", heading_xf)
1540
    sheet.write(0, 30, "Sales History", heading_xf)
12396 kshitij.so 1541
 
1542
    sheet_iterator = 1
12475 kshitij.so 1543
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.NEGATIVE_MARGIN).all()
12396 kshitij.so 1544
    for amongCheapestItem in amongCheapestItems:
1545
        amScraping =  amongCheapestItem[0]
1546
        item = amongCheapestItem[1]
1547
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1548
        if amScraping.warehouseLocation == 1:
1549
            sku = 'FBA'+str(amScraping.item_id)
1550
            loc = 'MUMBAI'
1551
        else:
1552
            sku = 'FBB'+str(amScraping.item_id)
1553
            loc = 'BANGLORE'
1554
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1555
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1556
        sheet.write(sheet_iterator, 3, loc)
1557
        sheet.write(sheet_iterator, 4, item.brand)
1558
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1559
        sheet.write(sheet_iterator, 6, item.weight)
1560
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1561
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1562
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1563
        if amScraping.isPromotion:
1564
            sheet.write(sheet_iterator, 10, "Yes")
1565
        else:
1566
            sheet.write(sheet_iterator, 10, "Yes")
1567
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1568
        if amScraping.ourRank > 3:
1569
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1570
        else:
1571
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1572
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1573
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1574
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1575
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1576
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1577
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1578
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1579
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1580
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1581
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1582
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1583
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1584
        sheet.write(sheet_iterator, 25, amScraping.commission)
1585
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1586
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
12468 kshitij.so 1587
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
12447 kshitij.so 1588
        sheet.write(sheet_iterator, 29, amScraping.avgSale)
1589
        sheet.write(sheet_iterator, 30, getOosString(saleMap.get(sku)))
12396 kshitij.so 1590
        sheet_iterator+=1
1591
 
1592
    sheet = wbk.add_sheet('Exception List')
1593
    xstr = lambda s: s or ""
1594
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1595
 
1596
    excel_integer_format = '0'
1597
    integer_style = xlwt.XFStyle()
1598
    integer_style.num_format_str = excel_integer_format
1599
 
1600
    sheet.write(0, 0, "Item Id", heading_xf)
1601
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1602
    sheet.write(0, 2, "Asin", heading_xf)
1603
    sheet.write(0, 3, "Location", heading_xf)
1604
    sheet.write(0, 4, "Brand", heading_xf)
1605
    sheet.write(0, 5, "Product Name", heading_xf)
1606
    sheet.write(0, 6, "Reason", heading_xf)
1607
 
1608
    sheet_iterator = 1
12475 kshitij.so 1609
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.EXCEPTION).all()
12396 kshitij.so 1610
    for amongCheapestItem in amongCheapestItems:
1611
        amScraping =  amongCheapestItem[0]
1612
        item = amongCheapestItem[1]
1613
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1614
        if amScraping.warehouseLocation == 1:
1615
            sku = 'FBA'+str(amScraping.item_id)
1616
            loc = 'MUMBAI'
1617
        else:
1618
            sku = 'FBB'+str(amScraping.item_id)
1619
            loc = 'BANGLORE'
1620
        sheet.write(sheet_iterator, 1, sku)
12471 kshitij.so 1621
        sheet.write(sheet_iterator, 2, amScraping.asin)
12396 kshitij.so 1622
        sheet.write(sheet_iterator, 3, loc)
1623
        sheet.write(sheet_iterator, 4, item.brand)
1624
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1625
        sheet.write(sheet_iterator, 6, amScraping.reason)
1626
        sheet_iterator+=1      
1627
 
12444 kshitij.so 1628
 
1629
    if (runType=='FULL'):    
1630
        sheet = wbk.add_sheet('Auto Favorites')
1631
 
1632
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1633
 
1634
        excel_integer_format = '0'
1635
        integer_style = xlwt.XFStyle()
1636
        integer_style.num_format_str = excel_integer_format
1637
        xstr = lambda s: s or ""
1638
 
1639
        sheet.write(0, 0, "Item ID", heading_xf)
1640
        sheet.write(0, 1, "Brand", heading_xf)
1641
        sheet.write(0, 2, "Product Name", heading_xf)
1642
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1643
        sheet.write(0, 4, "Reason", heading_xf)
1644
 
1645
        sheet_iterator=1
1646
        for autoFav in nowAutoFav:
1647
            itemId = autoFav[0]
1648
            reason = autoFav[1]
1649
            it = Item.query.filter_by(id=itemId).one()
1650
            sheet.write(sheet_iterator, 0, itemId)
1651
            sheet.write(sheet_iterator, 1, it.brand)
1652
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1653
            sheet.write(sheet_iterator, 3, "True")
1654
            sheet.write(sheet_iterator, 4, reason)
1655
            sheet_iterator+=1
1656
        for prevFav in previousAutoFav:
1657
            it = Item.query.filter_by(id=prevFav).one()
1658
            sheet.write(sheet_iterator, 0, prevFav)
1659
            sheet.write(sheet_iterator, 1, it.brand)
1660
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1661
            sheet.write(sheet_iterator, 3, "False")
1662
            sheet_iterator+=1
1663
 
12396 kshitij.so 1664
    filename = "/tmp/amazon-scraping.xls"
1665
    wbk.save(filename)
1666
 
12363 kshitij.so 1667
def main():
1668
    parser = optparse.OptionParser()
1669
    parser.add_option("-t", "--type", dest="runType",
1670
                   default="FULL", type="string",
1671
                   help="Run type FULL or FAVOURITE")
1672
    (options, args) = parser.parse_args()
1673
    if options.runType not in ('FULL','FAVOURITE'):
1674
        print "Run type argument illegal."
1675
        sys.exit(1)
1676
    time.sleep(5)
1677
    timestamp = datetime.now()
1678
    fetchFbaSale()
1679
    itemInfo = populateStuff(timestamp,options.runType)
1680
    itemsToPopulate = 0
12430 kshitij.so 1681
    toSync = 0
1682
    lenItems = len(itemInfo)
1683
    while(toSync < lenItems):
1684
        oldSync = toSync
1685
        if lenItems >= 20:
1686
            toSync = 20
1687
        else:
1688
            toSync = lenItems - oldSync
1689
        getPriceAndAsin(itemInfo[oldSync:toSync+oldSync])
1690
        toSync = oldSync + toSync
1691
 
12363 kshitij.so 1692
    while (len(itemInfo)>0):
12430 kshitij.so 1693
        if len(itemInfo) >= 20:
1694
            itemsToPopulate = 20
12363 kshitij.so 1695
        else:
1696
            itemsToPopulate = len(itemInfo)
12456 kshitij.so 1697
        print "items to popluate"
12370 kshitij.so 1698
        print itemsToPopulate
12363 kshitij.so 1699
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate])
1700
        itemInfo[0:itemsToPopulate] = []
1701
        commitExceptionList(exceptionList,timestamp,options.runType)
1702
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
1703
        commitCheapest(cheapest,timestamp,options.runType)
1704
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
1705
        commitCanCompete(canCompete,timestamp,options.runType)
1706
        commitAlmostCompete(almostCompete,timestamp,options.runType)
1707
        commitCantCompete(cantCompete, timestamp,options.runType)
12396 kshitij.so 1708
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1709
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1710
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1711
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
12444 kshitij.so 1712
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,options.runType)
12363 kshitij.so 1713
if __name__=='__main__':
1714
    main()