Subversion Repositories SmartDukaan

Rev

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