Subversion Repositories SmartDukaan

Rev

Rev 12447 | Rev 12452 | 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()
12450 kshitij.so 393
    print "No of items populated ",len(itemInfo)
394
    time.sleep(10)
12363 kshitij.so 395
    return itemInfo
396
 
12430 kshitij.so 397
def getPriceAndAsin(itemInfo):
398
    skus = []
399
    for item in itemInfo:
400
        skus.append(item.sku)
401
    ourPricingForSku = amScraper.get_my_pricing_for_sku('A21TJRUUN4KGV', skus)
402
    for item in itemInfo:
403
        ourPricing = ourPricingForSku.get(item.sku)
12441 kshitij.so 404
        if ourPricing is None or len(ourPricing.keys())==0:
12430 kshitij.so 405
            item.ourSp = 0
406
            item.promoPrice = 0
407
            item.isPromotion = False
408
        else:
409
            item.ourSp = ourPricing.get('sellingPrice')
410
            item.promoPrice = ourPricing.get('promoPrice')
411
            item.isPromotion = ourPricing.get('promotion')
12450 kshitij.so 412
 
12430 kshitij.so 413
 
414
 
12363 kshitij.so 415
def decideCategory(itemInfo):
416
    exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = [],[],[],[],[],[],[] 
12430 kshitij.so 417
    skus = []
12363 kshitij.so 418
    for item in itemInfo:
12430 kshitij.so 419
        skus.append(item.sku)
420
    aggResponse = amScraper.get_competitive_pricing_for_sku('A21TJRUUN4KGV', skus)
421
    ourPricingForSku = amScraper.get_my_pricing_for_sku('A21TJRUUN4KGV', skus)
12403 kshitij.so 422
 
12363 kshitij.so 423
    for val in itemInfo:
12430 kshitij.so 424
        scrapInfo = aggResponse.get(val.sku)
12443 kshitij.so 425
        if scrapInfo is None or len(scrapInfo)==0 or val.nlc==0 or len(ourPricingForSku.get(val.sku).keys())==0:
12363 kshitij.so 426
            temp = []
427
            temp.append(val)
428
            if val.nlc==0 or val.nlc is None:
429
                temp.append("WANLC is 0")
12443 kshitij.so 430
            elif ourPricingForSku.get(val.sku) is None or ourPricingForSku.get(val.sku).keys()==0:
12430 kshitij.so 431
                temp.append("Unable to fetch our price")
12363 kshitij.so 432
            else:
12430 kshitij.so 433
                temp.append("Unable to fetch competitive pricing")
12363 kshitij.so 434
            exceptionList.append(temp)
435
            continue
12430 kshitij.so 436
        val.asin = ourPricingForSku.get(val.sku).get('asin')
437
        val.ourSp = ourPricingForSku.get(val.sku).get('sellingPrice')
438
        val.promoPrice = ourPricingForSku.get(val.sku).get('promoPrice')
439
        val.isPromo = ourPricingForSku.get(val.sku).get('promotion')
12363 kshitij.so 440
        iterator = 0
441
        sku, lowestSellerName,secondLowestSellerName, thirdLowestSellerName = ('',)*4
12432 kshitij.so 442
        ourSp, ourRank, lowestSellerSp, secondLowestSellerSp, thirdLowestSellerSp, lowestPossibleSp = (0,)*6
12430 kshitij.so 443
        lowestSellerShippingTime, lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , \
444
        thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType = (0,)*9
445
        isPromo = False
12363 kshitij.so 446
        sku = val.sku
447
        multipleListings = False
12430 kshitij.so 448
        ourSkuDetails = ourPricingForSku.get(val.sku)
12442 kshitij.so 449
        if not (ourSkuDetails.get('promotion') and (amazonLongTermActivePromotions.has_key(val.sku) or amazonShortTermActivePromotions.has_key(val.sku))):
12432 kshitij.so 450
            temp = []
451
            temp.append(val)
452
            temp.append("Promo misconfigured")
453
            continue
454
 
12430 kshitij.so 455
        scrapInfo.append(ourSkuDetails)
456
        sortedScrapInfo =  sorted(scrapInfo, key=itemgetter('promoPrice','notOurSku'))
457
        for info in sortedScrapInfo:
458
            if  not info.notOurSku:
12442 kshitij.so 459
                ourSp = info['sellingPrice']
460
                promoPrice = info['promoPrice']
461
                isPromo = info['promotion']
12430 kshitij.so 462
                ourRank = iterator + 1
12363 kshitij.so 463
 
464
            if iterator == 0:
12430 kshitij.so 465
                lowestSellerSp = info['promoPrice']
466
                lowestSellerShippingTime = info['shippingTime']
467
                lowestSellerRating = info['rating']
468
                lowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 469
 
470
            if iterator == 1:
12430 kshitij.so 471
                secondLowestSellerSp = info['promoPrice']
472
                secondLowestSellerShippingTime = info['shippingTime']
473
                secondLowestSellerRating = info['rating']
474
                secondLowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 475
 
476
            if iterator == 2:
12430 kshitij.so 477
                thirdLowestSellerSp = info['promoPrice']
478
                thirdLowestSellerShippingTime = info['shippingTime']
479
                thirdLowestSellerRating = info['rating']
480
                thirdLowestSellerType = info['fulfillmentChannel']
12363 kshitij.so 481
 
482
            iterator += 1
12401 kshitij.so 483
        print "terminating iterator"
12363 kshitij.so 484
 
485
 
12408 kshitij.so 486
        print "Creating object am details",val.sku
12430 kshitij.so 487
        amDetails = __AmazonDetails(sku, float(ourSp), ourRank, lowestSellerName,float(lowestSellerSp),secondLowestSellerName, float(secondLowestSellerSp), thirdLowestSellerName, float(thirdLowestSellerSp),len(scrapInfo),multipleListings,promoPrice,isPromo, \
488
                    lowestSellerShippingTime ,lowestSellerRating, secondLowestSellerShippingTime, secondLowestSellerRating, thirdLowestSellerShippingTime , thirdLowestSellerRating, lowestSellerType, secondLowestSellerType, thirdLowestSellerType)
12414 kshitij.so 489
        print "am details obj created"
12363 kshitij.so 490
        try:
12414 kshitij.so 491
            print "inside val getter"
12418 kshitij.so 492
            itemVatMaster = ItemVatMaster.query.filter(and_(ItemVatMaster.itemId==int(val.sku[3:]), ItemVatMaster.stateId==val.state_id)).first()
493
            if itemVatMaster is None:
12419 kshitij.so 494
                d_item = Item.query.filter_by(id=int(val.sku[3:])).first()
495
                if d_item is None:
496
                    raise 
497
                else:
12430 kshitij.so 498
                    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 499
                if vatMaster is None:
12418 kshitij.so 500
                    raise
12419 kshitij.so 501
                else:
502
                    val.vatRate = vatMaster.vatPercent
503
                    print "vat fetched"
12418 kshitij.so 504
            else:
505
                val.vatRate = itemVatMaster.vatPercentage
12419 kshitij.so 506
                print "vat fetched"
12363 kshitij.so 507
        except:
12414 kshitij.so 508
            print "vat exception"
12363 kshitij.so 509
            temp = []
510
            temp.append(val)
511
            temp.append("Vat not available")
512
            exceptionList.append(temp)
513
            continue
514
 
515
        lowestPossibleSp = getLowestPossibleSp(amDetails,val,val.sourcePercentage)
12408 kshitij.so 516
        print "Creating pricing obj"
12432 kshitij.so 517
        amPricing = __AmazonPricing(ourSp,lowestPossibleSp)
12363 kshitij.so 518
 
12432 kshitij.so 519
        if amPricing.promoPrice < amPricing.lowestPossibleSp:
12363 kshitij.so 520
            temp = []
521
            temp.append(val)
522
            temp.append(amDetails)
523
            temp.append(amPricing)
524
            negativeMargin.append(temp)
525
            continue
526
 
527
        if amDetails.ourRank==1:
528
            temp = []
529
            temp.append(val)
530
            temp.append(amDetails)
531
            temp.append(amPricing)
532
            cheapest.append(temp)
533
            continue
534
 
12430 kshitij.so 535
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp) and ((((float(amDetails.promoPrice - amDetails.lowestSellerSp))/amDetails.promoPrice)<=.01) or ((amDetails.promoPrice - amDetails.lowestSellerSp)<=25)):
12363 kshitij.so 536
            temp = []
537
            temp.append(val)
538
            temp.append(amDetails)
539
            temp.append(amPricing)
540
            amongCheapestAndCanCompete.append(temp)
541
            continue
542
 
543
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp):
544
            temp = []
545
            temp.append(val)
546
            temp.append(amDetails)
547
            temp.append(amPricing)
548
            canCompete.append(temp)
549
            continue
550
 
12403 kshitij.so 551
        if amDetails.lowestSellerSp*(1+.01) >= amPricing.lowestPossibleSp:
12396 kshitij.so 552
            temp = []
553
            temp.append(val)
554
            temp.append(amDetails)
555
            temp.append(amPricing)
556
            almostCompete.append(temp)
557
            continue
558
 
559
 
12363 kshitij.so 560
        temp = []
561
        temp.append(val)
562
        temp.append(amDetails)
563
        temp.append(amPricing)
564
        cantCompete.append(temp)
12414 kshitij.so 565
    print "Created category..."
12363 kshitij.so 566
 
567
    return exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete
12396 kshitij.so 568
 
12363 kshitij.so 569
 
570
def getLowestPossibleSp(amazonDetails,val,spm):
12447 kshitij.so 571
    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 572
    if val.isPromo:
573
        if amazonLongTermActivePromotions.has_key(val.sku):
574
            subsidy = (amazonLongTermActivePromotions.has_key(val.sku)).subsidy
575
        else:
576
            subsidy = (amazonShortTermActivePromotions.has_key(val.sku)).subsidy
577
        lowestPossibleSp = lowestPossibleSp - subsidy
12363 kshitij.so 578
    return round(lowestPossibleSp,2)
579
 
580
def getTargetTp(targetSp,spm,val):
12424 kshitij.so 581
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(spm.serviceTax/100))
12363 kshitij.so 582
    return round(targetTp,2)
583
 
584
def commitExceptionList(exceptionList,timestamp,runType):
585
    for exceptionItem in exceptionList:
586
        val = exceptionItem[0]
587
        reason = exceptionItem[1]
588
        amazonScrapingHistory = AmazonScrapingHistory()
589
        amazonScrapingHistory.item_id = val.sku[3:]
590
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 591
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 592
        amazonScrapingHistory.reason = reason
593
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
594
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.EXCEPTION
595
        amazonScrapingHistory.timestamp = timestamp
596
    session.commit()
597
 
598
def commitNegativeMargin(negativeMargin,timestamp,runType):
599
    for negativeMarginItem in negativeMargin:
600
        val = negativeMarginItem[0]
601
        amDetails = negativeMarginItem[1]
602
        amPricing = negativeMarginItem[2]
603
        spm = val.sourcePercentage
604
        amazonScrapingHistory = AmazonScrapingHistory()
605
        amazonScrapingHistory.item_id = val.sku[3:]
606
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 607
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 608
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 609
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 610
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
611
        amazonScrapingHistory.ourRank = amDetails.ourRank
612
        amazonScrapingHistory.ourInventory = val.ourInventory
613
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
614
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
615
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
616
        amazonScrapingHistory.wanlc = val.nlc
12447 kshitij.so 617
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 618
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 619
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 620
        amazonScrapingHistory.returnProvision = spm.returnProvision
621
        amazonScrapingHistory.courierCost = val.courierCost
622
        amazonScrapingHistory.risky = val.risky
623
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
624
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
625
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
626
        amazonScrapingHistory.timestamp = timestamp
627
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
628
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 629
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 630
    session.commit()
631
 
632
 
633
def commitCheapest(cheapest,timestamp,runType):
634
    for cheapestItem in cheapest:
635
        val = cheapestItem[0]
636
        amDetails = cheapestItem[1]
637
        amPricing = cheapestItem[2]
638
        spm = val.sourcePercentage
639
        amazonScrapingHistory = AmazonScrapingHistory()
640
        amazonScrapingHistory.item_id = val.sku[3:]
641
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 642
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 643
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 644
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 645
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
646
        amazonScrapingHistory.ourRank = amDetails.ourRank
647
        amazonScrapingHistory.ourInventory = val.ourInventory
648
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 649
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
650
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
651
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 652
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 653
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
654
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
655
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12363 kshitij.so 656
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 657
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
658
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
659
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12447 kshitij.so 660
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 661
        amazonScrapingHistory.wanlc = val.nlc
662
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 663
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 664
        amazonScrapingHistory.returnProvision = spm.returnProvision
665
        amazonScrapingHistory.courierCost = val.courierCost
666
        amazonScrapingHistory.risky = val.risky
667
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
668
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
669
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.BUY_BOX
670
        amazonScrapingHistory.timestamp = timestamp
671
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12430 kshitij.so 672
        proposed_sp = max(amDetails.secondLowestSellerSp - max((20, amDetails.secondLowestSellerSp*0.002)), amPricing.lowestPossibleSp)
12433 kshitij.so 673
        if amazonScrapingHistory.isPromotion:
674
            if amazonLongTermActivePromotions.has_key(val.sku):
675
                proposed_sp = min(proposed_sp,(amazonLongTermActivePromotions.has_key(val.sku)).salePrice)
676
            else:
677
                proposed_sp = min(proposed_sp,(amazonShortTermActivePromotions.has_key(val.sku)).salePrice)
12363 kshitij.so 678
        proposed_tp = getTargetTp(proposed_sp,spm,val)
679
        amazonScrapingHistory.proposedSp = proposed_sp
680
        amazonScrapingHistory.proposedTp = proposed_tp
681
        amazonScrapingHistory.marginIncreasedPotential = proposed_tp - amPricing.ourTp
682
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
683
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 684
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 685
    session.commit()
686
 
687
 
688
 
689
def commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,runType):
690
    for amongCheapestAndCanCompeteItem in amongCheapestAndCanCompete:
691
        val = amongCheapestAndCanCompeteItem[0]
692
        amDetails = amongCheapestAndCanCompeteItem[1]
693
        amPricing = amongCheapestAndCanCompeteItem[2]
694
        spm = val.sourcePercentage
695
        amazonScrapingHistory = AmazonScrapingHistory()
696
        amazonScrapingHistory.item_id = val.sku[3:]
697
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 698
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 699
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 700
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 701
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
702
        amazonScrapingHistory.ourRank = amDetails.ourRank
703
        amazonScrapingHistory.ourInventory = val.ourInventory
704
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 705
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
706
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
707
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 708
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 709
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
710
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
711
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12363 kshitij.so 712
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 713
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
714
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
715
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12447 kshitij.so 716
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 717
        amazonScrapingHistory.wanlc = val.nlc
718
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 719
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 720
        amazonScrapingHistory.returnProvision = spm.returnProvision
721
        amazonScrapingHistory.courierCost = val.courierCost
722
        amazonScrapingHistory.risky = val.risky
723
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
724
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
725
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE
726
        amazonScrapingHistory.timestamp = timestamp
727
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
728
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
729
        proposed_tp = getTargetTp(proposed_sp,spm,val)
730
        amazonScrapingHistory.proposedSp = proposed_sp
731
        amazonScrapingHistory.proposedTp = proposed_tp
732
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
733
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 734
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 735
    session.commit()
736
 
737
def commitCanCompete(canCompete,timestamp,runType):
738
    for canCompeteItem in canCompete:
739
        val = canCompeteItem[0]
740
        amDetails = canCompeteItem[1]
741
        amPricing = canCompeteItem[2]
742
        spm = val.sourcePercentage
743
        amazonScrapingHistory = AmazonScrapingHistory()
744
        amazonScrapingHistory.item_id = val.sku[3:]
745
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 746
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 747
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 748
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 749
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
750
        amazonScrapingHistory.ourRank = amDetails.ourRank
751
        amazonScrapingHistory.ourInventory = val.ourInventory
752
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 753
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
754
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
755
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 756
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 757
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
758
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
759
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12363 kshitij.so 760
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 761
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
762
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
763
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12447 kshitij.so 764
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 765
        amazonScrapingHistory.wanlc = val.nlc
766
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 767
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 768
        amazonScrapingHistory.returnProvision = spm.returnProvision
769
        amazonScrapingHistory.courierCost = val.courierCost
770
        amazonScrapingHistory.risky = val.risky
771
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
772
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
773
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
774
        amazonScrapingHistory.timestamp = timestamp
775
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
776
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
777
        proposed_tp = getTargetTp(proposed_sp,spm,val)
778
        amazonScrapingHistory.proposedSp = proposed_sp
779
        amazonScrapingHistory.proposedTp = proposed_tp
780
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
781
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 782
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 783
    session.commit()
784
 
12383 kshitij.so 785
def commitAlmostCompete(almostCompete,timestamp,runType):
12396 kshitij.so 786
    for almostCompeteItem in almostCompete:
787
        val = almostCompeteItem[0]
788
        amDetails = almostCompeteItem[1]
789
        amPricing = almostCompeteItem[2]
790
        spm = val.sourcePercentage
791
        amazonScrapingHistory = AmazonScrapingHistory()
792
        amazonScrapingHistory.item_id = val.sku[3:]
793
        amazonScrapingHistory.warehouseLocation = val.state_id
794
        amazonScrapingHistory.parentCategoryId = val.parent_category
795
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 796
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12396 kshitij.so 797
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
798
        amazonScrapingHistory.ourRank = amDetails.ourRank
799
        amazonScrapingHistory.ourInventory = val.ourInventory
800
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 801
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
802
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
803
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12396 kshitij.so 804
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 805
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
806
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
807
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12396 kshitij.so 808
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 809
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
810
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
811
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12447 kshitij.so 812
        amazonScrapingHistory.otherCost = val.otherCost
12396 kshitij.so 813
        amazonScrapingHistory.wanlc = val.nlc
814
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 815
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12396 kshitij.so 816
        amazonScrapingHistory.returnProvision = spm.returnProvision
817
        amazonScrapingHistory.courierCost = val.courierCost
818
        amazonScrapingHistory.risky = val.risky
819
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
820
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
821
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.ALMOST_COMPETE
822
        amazonScrapingHistory.timestamp = timestamp
823
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
12425 kshitij.so 824
        proposed_sp = min(amDetails.lowestSellerSp*(1+.01),amPricing.lowestPossibleSp)
12396 kshitij.so 825
        proposed_tp = getTargetTp(proposed_sp,spm,val)
826
        target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
827
        amazonScrapingHistory.proposedSp = proposed_sp
828
        amazonScrapingHistory.proposedTp = proposed_tp
829
        amazonScrapingHistory.targetNlc = target_nlc
830
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
831
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 832
        amazonScrapingHistory.isPromotion = val.isPromo
12396 kshitij.so 833
    session.commit()
12363 kshitij.so 834
 
12396 kshitij.so 835
 
12363 kshitij.so 836
def commitCantCompete(cantCompete, timestamp,runType):
837
    for cantCompeteItem in cantCompete:
838
        val = cantCompeteItem[0]
839
        amDetails = cantCompeteItem[1]
840
        amPricing = cantCompeteItem[2]
841
        spm = val.sourcePercentage
842
        amazonScrapingHistory = AmazonScrapingHistory()
843
        amazonScrapingHistory.item_id = val.sku[3:]
844
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 845
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 846
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
12432 kshitij.so 847
        amazonScrapingHistory.promoPrice = amDetails.promoPrice
12363 kshitij.so 848
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
849
        amazonScrapingHistory.ourRank = amDetails.ourRank
850
        amazonScrapingHistory.ourInventory = val.ourInventory
851
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
12430 kshitij.so 852
        amazonScrapingHistory.lowestSellerShippingTime = amDetails.lowestSellerShippingTime
853
        amazonScrapingHistory.lowestSellerRating = amDetails.lowestSellerRating
854
        amazonScrapingHistory.lowestSellerType = amDetails.lowestSellerType
12363 kshitij.so 855
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
12430 kshitij.so 856
        amazonScrapingHistory.secondSellerShippingTime = amDetails.secondSellerShippingTime
857
        amazonScrapingHistory.secondSellerRating = amDetails.secondSellerRating
858
        amazonScrapingHistory.secondSellerType = amDetails.secondSellerType
12363 kshitij.so 859
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
12430 kshitij.so 860
        amazonScrapingHistory.thirdSellerShippingTime = amDetails.thirdSellerShippingTime
861
        amazonScrapingHistory.thirdSellerRating = amDetails.thirdSellerRating
862
        amazonScrapingHistory.thirdSellerType = amDetails.thirdSellerType
12447 kshitij.so 863
        amazonScrapingHistory.otherCost = val.otherCost
12363 kshitij.so 864
        amazonScrapingHistory.wanlc = val.nlc
865
        amazonScrapingHistory.commission = spm.commission
12422 kshitij.so 866
        amazonScrapingHistory.competitorCommission = spm.competitorCommissionOther
12363 kshitij.so 867
        amazonScrapingHistory.returnProvision = spm.returnProvision
868
        amazonScrapingHistory.courierCost = val.courierCost
869
        amazonScrapingHistory.risky = val.risky
870
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
871
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
872
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
873
        amazonScrapingHistory.timestamp = timestamp
874
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
875
        proposed_sp = amDetails.lowestSellerSp - max(5, amDetails.lowestSellerSp*0.001)
876
        proposed_tp = getTargetTp(proposed_sp,spm,val)
877
        target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
878
        amazonScrapingHistory.proposedSp = proposed_sp
879
        amazonScrapingHistory.proposedTp = proposed_tp
880
        amazonScrapingHistory.targetNlc = target_nlc
881
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
882
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
12432 kshitij.so 883
        amazonScrapingHistory.isPromotion = val.isPromo
12363 kshitij.so 884
    session.commit()
885
 
12396 kshitij.so 886
def markAutoFavourites(time):
887
    nowAutoFav = []
888
    previouslyAutoFav = []
889
    stockList = []
890
    saleList = []
891
    items = session.query(func.sum(AmazonScrapingHistory.ourInventory),AmazonScrapingHistory.item_id).group_by(AmazonScrapingHistory.item_id).all()
892
    allItems = session.query(Amazonlisted).all()
893
    for item in items:
894
        reason = ""
895
        if item[0]>=5:
896
            stockList.append(item[1])
897
 
898
    for sku, val in saleMap.iteritems():
899
        totalSale = 0
900
        item_id = sku.replace('FBA','').replace('FBB','')
901
        val =saleMap.get('FBA'+str(item_id))
902
        if val is not None:
903
            for sale in val:
904
                totalSale += sale.totalOrderCount
905
        val =saleMap.get('FBB'+str(item_id))
906
        if val is not None:
907
            for sale in val:
908
                totalSale += sale.totalOrderCount
909
        if totalSale > 0:
910
            saleList.append(item_id)
911
 
912
    for aItem in allItems:
913
        reason = ""
914
        toMark = False
915
        if aItem.itemId in saleList:
916
            toMark = True
917
            reason+="Total FC sale is greater than 1 for last five days.."
918
        if aItem.itemId in stockList:
919
            toMark = True
920
            reason+="Item is present in buy box in last 3 days"
921
        if not aItem.autoFavourite:
922
            print "Item is not under auto favourite"
923
        if toMark:
924
            temp=[]
925
            temp.append(aItem.itemId)
926
            temp.append(reason)
927
            nowAutoFav.append(temp)
928
        if (not toMark) and aItem.autoFavourite:
929
            previouslyAutoFav.append(aItem.itemId)
930
        aItem.autoFavourite = toMark
931
    session.commit()
932
    return previouslyAutoFav, nowAutoFav
933
 
12444 kshitij.so 934
def writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,runType):
12396 kshitij.so 935
    wbk = xlwt.Workbook()
936
    sheet = wbk.add_sheet('Can\'t Compete')
937
    xstr = lambda s: s or ""
938
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
939
 
940
    excel_integer_format = '0'
941
    integer_style = xlwt.XFStyle()
942
    integer_style.num_format_str = excel_integer_format
943
 
944
    sheet.write(0, 0, "Item Id", heading_xf)
945
    sheet.write(0, 1, "Amazon Sku", heading_xf)
946
    sheet.write(0, 2, "Asin", heading_xf)
947
    sheet.write(0, 3, "Location", heading_xf)
948
    sheet.write(0, 4, "Brand", heading_xf)
949
    sheet.write(0, 5, "Product Name", heading_xf)
950
    sheet.write(0, 6, "Weight", heading_xf)
951
    sheet.write(0, 7, "Courier Cost", heading_xf)
952
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 953
    sheet.write(0, 9, "Promo Price", heading_xf)
954
    sheet.write(0, 10, "Is Promotion", heading_xf)
955
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 956
    sheet.write(0, 12, "Rank", heading_xf)
957
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 958
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
959
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
960
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 961
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 962
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
963
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
964
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
965
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
966
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 967
    sheet.write(0, 23, "Other Cost", heading_xf)
968
    sheet.write(0, 24, "WANLC", heading_xf)
969
    sheet.write(0, 25, "Commission", heading_xf)
970
    sheet.write(0, 26, "Competitor Commission", heading_xf)
971
    sheet.write(0, 27, "Return Provision", heading_xf)
972
    sheet.write(0, 28, "Margin", heading_xf)
973
    sheet.write(0, 29, "Risky", heading_xf)
974
    sheet.write(0, 30, "Proposed Sp", heading_xf)
975
    sheet.write(0, 31, "Proposed Tp", heading_xf)
976
    sheet.write(0, 32, "Target Nlc", heading_xf)
977
    sheet.write(0, 33, "Avg Sale", heading_xf)
978
    sheet.write(0, 34, "Sales History", heading_xf)
979
    sheet.write(0, 35, "Decision", heading_xf)
980
    sheet.write(0, 36, "Reason", heading_xf)
981
    sheet.write(0, 37, "Updated Price", heading_xf)
12396 kshitij.so 982
 
983
    sheet_iterator = 1
984
    cantCompeteItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
985
    for cantCompeteItem in cantCompeteItems:
986
        amScraping =  cantCompeteItem[0]
987
        item = cantCompeteItem[1]
988
        sheet.write(sheet_iterator, 0, amScraping.item_id)
989
        if amScraping.warehouseLocation == 1:
990
            sku = 'FBA'+str(amScraping.item_id)
991
            loc = 'MUMBAI'
992
        else:
993
            sku = 'FBB'+str(amScraping.item_id)
994
            loc = 'BANGLORE'
995
        sheet.write(sheet_iterator, 1, sku)
996
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
997
        sheet.write(sheet_iterator, 3, loc)
998
        sheet.write(sheet_iterator, 4, item.brand)
999
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1000
        sheet.write(sheet_iterator, 6, item.weight)
1001
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1002
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1003
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1004
        if amScraping.isPromotion:
1005
            sheet.write(sheet_iterator, 10, "Yes")
1006
        else:
1007
            sheet.write(sheet_iterator, 10, "Yes")
1008
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1009
        if amScraping.ourRank > 3:
1010
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1011
        else:
1012
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1013
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1014
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1015
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1016
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1017
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1018
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1019
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1020
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1021
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1022
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1023
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1024
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1025
        sheet.write(sheet_iterator, 25, amScraping.commission)
1026
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1027
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1028
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1029
        sheet.write(sheet_iterator, 29, item.risky)
1030
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
1031
        sheet.write(sheet_iterator, 31, amScraping.proposedTp)
1032
        sheet.write(sheet_iterator, 32, amScraping.targetNlc)
1033
        sheet.write(sheet_iterator, 33, amScraping.avgSale)
1034
        sheet.write(sheet_iterator, 34, getOosString(saleMap.get(sku)))
12444 kshitij.so 1035
        if amScraping.decision is None:
12447 kshitij.so 1036
            sheet.write(sheet_iterator, 35, 'Auto Pricing Inactive')
12444 kshitij.so 1037
            sheet_iterator+=1
1038
            continue
12447 kshitij.so 1039
        sheet.write(sheet_iterator, 35, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1040
        sheet.write(sheet_iterator, 36, amScraping.reason)
12444 kshitij.so 1041
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12447 kshitij.so 1042
            sheet.write(sheet_iterator, 37, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1043
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12447 kshitij.so 1044
            sheet.write(sheet_iterator, 37, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1045
        sheet_iterator+=1
1046
 
1047
    sheet = wbk.add_sheet('Competitive')
1048
    xstr = lambda s: s or ""
1049
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1050
 
1051
    excel_integer_format = '0'
1052
    integer_style = xlwt.XFStyle()
1053
    integer_style.num_format_str = excel_integer_format
1054
 
1055
    sheet.write(0, 0, "Item Id", heading_xf)
1056
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1057
    sheet.write(0, 2, "Asin", heading_xf)
1058
    sheet.write(0, 3, "Location", heading_xf)
1059
    sheet.write(0, 4, "Brand", heading_xf)
1060
    sheet.write(0, 5, "Product Name", heading_xf)
1061
    sheet.write(0, 6, "Weight", heading_xf)
1062
    sheet.write(0, 7, "Courier Cost", heading_xf)
1063
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1064
    sheet.write(0, 9, "Promo Price", heading_xf)
1065
    sheet.write(0, 10, "Is Promotion", heading_xf)
1066
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1067
    sheet.write(0, 12, "Rank", heading_xf)
1068
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1069
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1070
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1071
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1072
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1073
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1074
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1075
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1076
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1077
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1078
    sheet.write(0, 23, "Other Cost", heading_xf)
1079
    sheet.write(0, 24, "WANLC", heading_xf)
1080
    sheet.write(0, 25, "Commission", heading_xf)
1081
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1082
    sheet.write(0, 27, "Return Provision", heading_xf)
1083
    sheet.write(0, 28, "Margin", heading_xf)
1084
    sheet.write(0, 29, "Risky", heading_xf)
1085
    sheet.write(0, 30, "Proposed Sp", heading_xf)
1086
    sheet.write(0, 31, "Proposed Tp", heading_xf)
1087
    sheet.write(0, 32, "Avg Sale", heading_xf)
1088
    sheet.write(0, 33, "Sales History", heading_xf)
1089
    sheet.write(0, 34, "Decision", heading_xf)
1090
    sheet.write(0, 35, "Reason", heading_xf)
1091
    sheet.write(0, 36, "Updated Price", heading_xf)
12396 kshitij.so 1092
 
1093
    sheet_iterator = 1
1094
    competitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.COMPETITIVE).all()
1095
    for competitiveItem in competitiveItems:
1096
        amScraping =  competitiveItem[0]
1097
        item = competitiveItem[1]
1098
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1099
        if amScraping.warehouseLocation == 1:
1100
            sku = 'FBA'+str(amScraping.item_id)
1101
            loc = 'MUMBAI'
1102
        else:
1103
            sku = 'FBB'+str(amScraping.item_id)
1104
            loc = 'BANGLORE'
1105
        sheet.write(sheet_iterator, 1, sku)
1106
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1107
        sheet.write(sheet_iterator, 3, loc)
1108
        sheet.write(sheet_iterator, 4, item.brand)
1109
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1110
        sheet.write(sheet_iterator, 6, item.weight)
1111
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1112
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1113
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1114
        if amScraping.isPromotion:
1115
            sheet.write(sheet_iterator, 10, "Yes")
1116
        else:
1117
            sheet.write(sheet_iterator, 10, "Yes")
1118
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1119
        if amScraping.ourRank > 3:
1120
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1121
        else:
1122
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1123
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1124
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1125
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1126
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1127
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1128
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1129
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1130
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1131
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1132
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1133
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1134
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1135
        sheet.write(sheet_iterator, 25, amScraping.commission)
1136
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1137
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1138
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1139
        sheet.write(sheet_iterator, 29, item.risky)
1140
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
1141
        sheet.write(sheet_iterator, 31, amScraping.proposedTp)
1142
        sheet.write(sheet_iterator, 32, amScraping.avgSale)
1143
        sheet.write(sheet_iterator, 33, getOosString(saleMap.get(sku)))
12444 kshitij.so 1144
        if amScraping.decision is None:
12447 kshitij.so 1145
            sheet.write(sheet_iterator, 34, 'Auto Pricing Inactive')
12444 kshitij.so 1146
            sheet_iterator+=1
1147
            continue
12447 kshitij.so 1148
        sheet.write(sheet_iterator, 34, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1149
        sheet.write(sheet_iterator, 35, amScraping.reason)
12444 kshitij.so 1150
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12447 kshitij.so 1151
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1152
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12447 kshitij.so 1153
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1154
        sheet_iterator+=1
1155
 
1156
    sheet = wbk.add_sheet('Almost Competitive')
1157
    xstr = lambda s: s or ""
1158
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1159
 
1160
    excel_integer_format = '0'
1161
    integer_style = xlwt.XFStyle()
1162
    integer_style.num_format_str = excel_integer_format
1163
 
1164
    sheet.write(0, 0, "Item Id", heading_xf)
1165
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1166
    sheet.write(0, 2, "Asin", heading_xf)
1167
    sheet.write(0, 3, "Location", heading_xf)
1168
    sheet.write(0, 4, "Brand", heading_xf)
1169
    sheet.write(0, 5, "Product Name", heading_xf)
1170
    sheet.write(0, 6, "Weight", heading_xf)
1171
    sheet.write(0, 7, "Courier Cost", heading_xf)
1172
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1173
    sheet.write(0, 9, "Promo Price", heading_xf)
1174
    sheet.write(0, 10, "Is Promotion", heading_xf)
1175
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1176
    sheet.write(0, 12, "Rank", heading_xf)
1177
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1178
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1179
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1180
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1181
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1182
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1183
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1184
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1185
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1186
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1187
    sheet.write(0, 23, "Other Cost", heading_xf)
1188
    sheet.write(0, 24, "WANLC", heading_xf)
1189
    sheet.write(0, 25, "Commission", heading_xf)
1190
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1191
    sheet.write(0, 27, "Return Provision", heading_xf)
1192
    sheet.write(0, 28, "Margin", heading_xf)
1193
    sheet.write(0, 29, "Risky", heading_xf)
1194
    sheet.write(0, 30, "Proposed Sp", heading_xf)
1195
    sheet.write(0, 31, "Proposed Tp", heading_xf)
1196
    sheet.write(0, 32, "Avg Sale", heading_xf)
1197
    sheet.write(0, 33, "Sales History", heading_xf)
1198
    sheet.write(0, 34, "Decision", heading_xf)
1199
    sheet.write(0, 35, "Reason", heading_xf)
1200
    sheet.write(0, 36, "Updated Price", heading_xf)
12396 kshitij.so 1201
 
1202
    sheet_iterator = 1
1203
    almostCompetitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.ALMOST_COMPETE).all()
1204
    for almostCompetitiveItem in almostCompetitiveItems:
1205
        amScraping =  almostCompetitiveItem[0]
1206
        item = almostCompetitiveItem[1]
1207
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1208
        if amScraping.warehouseLocation == 1:
1209
            sku = 'FBA'+str(amScraping.item_id)
1210
            loc = 'MUMBAI'
1211
        else:
1212
            sku = 'FBB'+str(amScraping.item_id)
1213
            loc = 'BANGLORE'
12432 kshitij.so 1214
        amScraping =  competitiveItem[0]
1215
        item = competitiveItem[1]
1216
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1217
        if amScraping.warehouseLocation == 1:
1218
            sku = 'FBA'+str(amScraping.item_id)
1219
            loc = 'MUMBAI'
1220
        else:
1221
            sku = 'FBB'+str(amScraping.item_id)
1222
            loc = 'BANGLORE'
12396 kshitij.so 1223
        sheet.write(sheet_iterator, 1, sku)
1224
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1225
        sheet.write(sheet_iterator, 3, loc)
1226
        sheet.write(sheet_iterator, 4, item.brand)
1227
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1228
        sheet.write(sheet_iterator, 6, item.weight)
1229
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1230
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1231
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1232
        if amScraping.isPromotion:
1233
            sheet.write(sheet_iterator, 10, "Yes")
1234
        else:
1235
            sheet.write(sheet_iterator, 10, "Yes")
1236
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1237
        if amScraping.ourRank > 3:
1238
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1239
        else:
1240
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1241
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1242
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1243
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1244
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1245
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1246
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1247
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1248
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1249
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1250
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1251
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1252
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1253
        sheet.write(sheet_iterator, 25, amScraping.commission)
1254
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1255
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1256
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1257
        sheet.write(sheet_iterator, 29, item.risky)
1258
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
1259
        sheet.write(sheet_iterator, 31, amScraping.proposedTp)
1260
        sheet.write(sheet_iterator, 32, amScraping.avgSale)
1261
        sheet.write(sheet_iterator, 33, getOosString(saleMap.get(sku)))
12444 kshitij.so 1262
        if amScraping.decision is None:
12447 kshitij.so 1263
            sheet.write(sheet_iterator, 34, 'Auto Pricing Inactive')
12444 kshitij.so 1264
            sheet_iterator+=1
1265
            continue
12447 kshitij.so 1266
        sheet.write(sheet_iterator, 34, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1267
        sheet.write(sheet_iterator, 35, amScraping.reason)
12444 kshitij.so 1268
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12447 kshitij.so 1269
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1270
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12447 kshitij.so 1271
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1272
        sheet_iterator+=1
1273
 
1274
    sheet = wbk.add_sheet('Among Cheapest')
1275
    xstr = lambda s: s or ""
1276
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1277
 
1278
    excel_integer_format = '0'
1279
    integer_style = xlwt.XFStyle()
1280
    integer_style.num_format_str = excel_integer_format
1281
 
1282
    sheet.write(0, 0, "Item Id", heading_xf)
1283
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1284
    sheet.write(0, 2, "Asin", heading_xf)
1285
    sheet.write(0, 3, "Location", heading_xf)
1286
    sheet.write(0, 4, "Brand", heading_xf)
1287
    sheet.write(0, 5, "Product Name", heading_xf)
1288
    sheet.write(0, 6, "Weight", heading_xf)
1289
    sheet.write(0, 7, "Courier Cost", heading_xf)
1290
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1291
    sheet.write(0, 9, "Promo Price", heading_xf)
1292
    sheet.write(0, 10, "Is Promotion", heading_xf)
1293
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1294
    sheet.write(0, 12, "Rank", heading_xf)
1295
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1296
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1297
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1298
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1299
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1300
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1301
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1302
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1303
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1304
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1305
    sheet.write(0, 23, "Other Cost", heading_xf)
1306
    sheet.write(0, 24, "WANLC", heading_xf)
1307
    sheet.write(0, 25, "Commission", heading_xf)
1308
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1309
    sheet.write(0, 27, "Return Provision", heading_xf)
1310
    sheet.write(0, 28, "Margin", heading_xf)
1311
    sheet.write(0, 29, "Risky", heading_xf)
1312
    sheet.write(0, 30, "Proposed Sp", heading_xf)
1313
    sheet.write(0, 31, "Proposed Tp", heading_xf)
1314
    sheet.write(0, 32, "Avg Sale", heading_xf)
1315
    sheet.write(0, 33, "Sales History", heading_xf)
1316
    sheet.write(0, 34, "Decision", heading_xf)
1317
    sheet.write(0, 35, "Reason", heading_xf)
1318
    sheet.write(0, 36, "Updated Price", heading_xf)
12396 kshitij.so 1319
 
1320
    sheet_iterator = 1
1321
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1322
    for amongCheapestItem in amongCheapestItems:
1323
        amScraping =  amongCheapestItem[0]
1324
        item = amongCheapestItem[1]
1325
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1326
        if amScraping.warehouseLocation == 1:
1327
            sku = 'FBA'+str(amScraping.item_id)
1328
            loc = 'MUMBAI'
1329
        else:
1330
            sku = 'FBB'+str(amScraping.item_id)
1331
            loc = 'BANGLORE'
1332
        sheet.write(sheet_iterator, 1, sku)
1333
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1334
        sheet.write(sheet_iterator, 3, loc)
1335
        sheet.write(sheet_iterator, 4, item.brand)
1336
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1337
        sheet.write(sheet_iterator, 6, item.weight)
1338
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1339
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1340
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1341
        if amScraping.isPromotion:
1342
            sheet.write(sheet_iterator, 10, "Yes")
1343
        else:
1344
            sheet.write(sheet_iterator, 10, "Yes")
1345
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1346
        if amScraping.ourRank > 3:
1347
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1348
        else:
1349
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1350
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1351
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1352
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1353
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1354
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1355
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1356
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1357
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1358
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1359
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1360
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1361
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1362
        sheet.write(sheet_iterator, 25, amScraping.commission)
1363
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1364
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1365
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1366
        sheet.write(sheet_iterator, 29, item.risky)
1367
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
1368
        sheet.write(sheet_iterator, 31, amScraping.proposedTp)
1369
        sheet.write(sheet_iterator, 32, amScraping.avgSale)
1370
        sheet.write(sheet_iterator, 33, getOosString(saleMap.get(sku)))
12444 kshitij.so 1371
        if amScraping.decision is None:
12447 kshitij.so 1372
            sheet.write(sheet_iterator, 34, 'Auto Pricing Inactive')
12444 kshitij.so 1373
            sheet_iterator+=1
1374
            continue
12447 kshitij.so 1375
        sheet.write(sheet_iterator, 34, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1376
        sheet.write(sheet_iterator, 35, amScraping.reason)
12444 kshitij.so 1377
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12447 kshitij.so 1378
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1379
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12447 kshitij.so 1380
            sheet.write(sheet_iterator, 36, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1381
        sheet_iterator+=1
1382
 
1383
    sheet = wbk.add_sheet('Cheapest')
1384
    xstr = lambda s: s or ""
1385
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1386
 
1387
    excel_integer_format = '0'
1388
    integer_style = xlwt.XFStyle()
1389
    integer_style.num_format_str = excel_integer_format
1390
 
1391
    sheet.write(0, 0, "Item Id", heading_xf)
1392
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1393
    sheet.write(0, 2, "Asin", heading_xf)
1394
    sheet.write(0, 3, "Location", heading_xf)
1395
    sheet.write(0, 4, "Brand", heading_xf)
1396
    sheet.write(0, 5, "Product Name", heading_xf)
1397
    sheet.write(0, 6, "Weight", heading_xf)
1398
    sheet.write(0, 7, "Courier Cost", heading_xf)
1399
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1400
    sheet.write(0, 9, "Promo Price", heading_xf)
1401
    sheet.write(0, 10, "Is Promotion", heading_xf)
1402
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1403
    sheet.write(0, 12, "Rank", heading_xf)
1404
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1405
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1406
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1407
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1408
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1409
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1410
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1411
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1412
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1413
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1414
    sheet.write(0, 23, "Other Cost", heading_xf)
1415
    sheet.write(0, 24, "WANLC", heading_xf)
1416
    sheet.write(0, 25, "Commission", heading_xf)
1417
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1418
    sheet.write(0, 27, "Return Provision", heading_xf)
1419
    sheet.write(0, 28, "Margin", heading_xf)
1420
    sheet.write(0, 29, "Risky", heading_xf)
1421
    sheet.write(0, 30, "Proposed Sp", heading_xf)
1422
    sheet.write(0, 31, "Proposed Tp", heading_xf)
1423
    sheet.write(0, 32, "Margin Increased Potential", heading_xf)
1424
    sheet.write(0, 33, "Avg Sale", heading_xf)
1425
    sheet.write(0, 34, "Sales History", heading_xf)
1426
    sheet.write(0, 35, "Decision", heading_xf)
1427
    sheet.write(0, 36, "Reason", heading_xf)
1428
    sheet.write(0, 37, "Updated Price", heading_xf)
12396 kshitij.so 1429
 
1430
    sheet_iterator = 1
1431
    cheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1432
    for cheapestItem in cheapestItems:
1433
        amScraping =  cheapestItem[0]
1434
        item = cheapestItem[1]
1435
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1436
        if amScraping.warehouseLocation == 1:
1437
            sku = 'FBA'+str(amScraping.item_id)
1438
            loc = 'MUMBAI'
1439
        else:
1440
            sku = 'FBB'+str(amScraping.item_id)
1441
            loc = 'BANGLORE'
1442
        sheet.write(sheet_iterator, 1, sku)
1443
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1444
        sheet.write(sheet_iterator, 3, loc)
1445
        sheet.write(sheet_iterator, 4, item.brand)
1446
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1447
        sheet.write(sheet_iterator, 6, item.weight)
1448
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1449
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1450
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1451
        if amScraping.isPromotion:
1452
            sheet.write(sheet_iterator, 10, "Yes")
1453
        else:
1454
            sheet.write(sheet_iterator, 10, "Yes")
1455
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1456
        if amScraping.ourRank > 3:
1457
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1458
        else:
1459
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1460
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1461
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1462
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1463
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1464
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1465
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1466
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1467
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1468
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1469
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1470
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1471
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1472
        sheet.write(sheet_iterator, 25, amScraping.commission)
1473
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1474
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1475
        sheet.write(sheet_iterator, 28, round(amScraping.ourSellingPrice - amScraping.lowestPossibleSp))
1476
        sheet.write(sheet_iterator, 29, item.risky)
1477
        sheet.write(sheet_iterator, 30, amScraping.proposedSp)
1478
        sheet.write(sheet_iterator, 31, amScraping.proposedTp)
1479
        sheet.write(sheet_iterator, 32, amScraping.targetNlc)
1480
        sheet.write(sheet_iterator, 33, amScraping.avgSale)
1481
        sheet.write(sheet_iterator, 34, getOosString(saleMap.get(sku)))
12444 kshitij.so 1482
        if amScraping.decision is None:
12447 kshitij.so 1483
            sheet.write(sheet_iterator, 35, 'Auto Pricing Inactive')
12444 kshitij.so 1484
            sheet_iterator+=1
1485
            continue
12447 kshitij.so 1486
        sheet.write(sheet_iterator, 35, Decision._VALUES_TO_NAMES.get(amScraping.decision))
1487
        sheet.write(sheet_iterator, 36, amScraping.reason)
12444 kshitij.so 1488
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_DECREMENT_SUCCESS":
12447 kshitij.so 1489
            sheet.write(sheet_iterator, 37, math.ceil(amScraping.proposedSellingPrice))
12444 kshitij.so 1490
        if Decision._VALUES_TO_NAMES.get(amScraping.decision) == "AUTO_INCREMENT_SUCCESS":
12447 kshitij.so 1491
            sheet.write(sheet_iterator, 37, math.ceil(amScraping.ourSellingPrice+max(10,.01*amScraping.ourSellingPrice)))
12396 kshitij.so 1492
        sheet_iterator+=1
1493
 
1494
    sheet = wbk.add_sheet('Negative Margin')
1495
    xstr = lambda s: s or ""
1496
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1497
 
1498
    excel_integer_format = '0'
1499
    integer_style = xlwt.XFStyle()
1500
    integer_style.num_format_str = excel_integer_format
1501
 
1502
    sheet.write(0, 0, "Item Id", heading_xf)
1503
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1504
    sheet.write(0, 2, "Asin", heading_xf)
1505
    sheet.write(0, 3, "Location", heading_xf)
1506
    sheet.write(0, 4, "Brand", heading_xf)
1507
    sheet.write(0, 5, "Product Name", heading_xf)
1508
    sheet.write(0, 6, "Weight", heading_xf)
1509
    sheet.write(0, 7, "Courier Cost", heading_xf)
1510
    sheet.write(0, 8, "Our SP", heading_xf)
12432 kshitij.so 1511
    sheet.write(0, 9, "Promo Price", heading_xf)
1512
    sheet.write(0, 10, "Is Promotion", heading_xf)
1513
    sheet.write(0, 11, "Lowest Possible SP", heading_xf)
12396 kshitij.so 1514
    sheet.write(0, 12, "Rank", heading_xf)
1515
    sheet.write(0, 13, "Our Inventory", heading_xf)
12432 kshitij.so 1516
    sheet.write(0, 14, "Lowest Seller SP", heading_xf)
1517
    sheet.write(0, 15, "Lowest Seller Rating", heading_xf)
1518
    sheet.write(0, 16, "Lowest Seller Shipping Time", heading_xf)
12396 kshitij.so 1519
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
12432 kshitij.so 1520
    sheet.write(0, 18, "Second Lowest Seller Rating", heading_xf)
1521
    sheet.write(0, 19, "Second Lowest Seller Shipping Time", heading_xf)
1522
    sheet.write(0, 20, "Third Lowest Seller SP", heading_xf)
1523
    sheet.write(0, 21, "Third Lowest Seller Rating", heading_xf)
1524
    sheet.write(0, 22, "Third Lowest Seller Shipping Time", heading_xf)
12447 kshitij.so 1525
    sheet.write(0, 23, "Other Cost", heading_xf)
1526
    sheet.write(0, 24, "WANLC", heading_xf)
1527
    sheet.write(0, 25, "Commission", heading_xf)
1528
    sheet.write(0, 26, "Competitor Commission", heading_xf)
1529
    sheet.write(0, 27, "Return Provision", heading_xf)
1530
    sheet.write(0, 28, "Margin", heading_xf)
1531
    sheet.write(0, 29, "Avg Sale", heading_xf)
1532
    sheet.write(0, 30, "Sales History", heading_xf)
12396 kshitij.so 1533
 
1534
    sheet_iterator = 1
1535
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1536
    for amongCheapestItem in amongCheapestItems:
1537
        amScraping =  amongCheapestItem[0]
1538
        item = amongCheapestItem[1]
1539
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1540
        if amScraping.warehouseLocation == 1:
1541
            sku = 'FBA'+str(amScraping.item_id)
1542
            loc = 'MUMBAI'
1543
        else:
1544
            sku = 'FBB'+str(amScraping.item_id)
1545
            loc = 'BANGLORE'
1546
        sheet.write(sheet_iterator, 1, sku)
1547
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1548
        sheet.write(sheet_iterator, 3, loc)
1549
        sheet.write(sheet_iterator, 4, item.brand)
1550
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1551
        sheet.write(sheet_iterator, 6, item.weight)
1552
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1553
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
12432 kshitij.so 1554
        sheet.write(sheet_iterator, 9, amScraping.promoPrice)
1555
        if amScraping.isPromotion:
1556
            sheet.write(sheet_iterator, 10, "Yes")
1557
        else:
1558
            sheet.write(sheet_iterator, 10, "Yes")
1559
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleSp)
12396 kshitij.so 1560
        if amScraping.ourRank > 3:
1561
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1562
        else:
1563
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1564
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
12432 kshitij.so 1565
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerSp)
1566
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerRating)
1567
        sheet.write(sheet_iterator, 16, amScraping.lowestSellerShippingTime)
12396 kshitij.so 1568
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
12432 kshitij.so 1569
        sheet.write(sheet_iterator, 18, amScraping.secondLowestSellerRating)
1570
        sheet.write(sheet_iterator, 19, amScraping.secondLowestSellerShippingTime)
1571
        sheet.write(sheet_iterator, 20, amScraping.thirdLowestSellerSp)
1572
        sheet.write(sheet_iterator, 21, amScraping.thirdLowestSellerRating)
1573
        sheet.write(sheet_iterator, 22, amScraping.thirdLowestSellerShippingTime)
12447 kshitij.so 1574
        sheet.write(sheet_iterator, 23, amScraping.otherCost)
1575
        sheet.write(sheet_iterator, 24, amScraping.wanlc)
1576
        sheet.write(sheet_iterator, 25, amScraping.commission)
1577
        sheet.write(sheet_iterator, 26, amScraping.competitorCommission)
1578
        sheet.write(sheet_iterator, 27, amScraping.returnProvision)
1579
        sheet.write(sheet_iterator, 28, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1580
        sheet.write(sheet_iterator, 29, amScraping.avgSale)
1581
        sheet.write(sheet_iterator, 30, getOosString(saleMap.get(sku)))
12396 kshitij.so 1582
        sheet_iterator+=1
1583
 
1584
    sheet = wbk.add_sheet('Exception List')
1585
    xstr = lambda s: s or ""
1586
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1587
 
1588
    excel_integer_format = '0'
1589
    integer_style = xlwt.XFStyle()
1590
    integer_style.num_format_str = excel_integer_format
1591
 
1592
    sheet.write(0, 0, "Item Id", heading_xf)
1593
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1594
    sheet.write(0, 2, "Asin", heading_xf)
1595
    sheet.write(0, 3, "Location", heading_xf)
1596
    sheet.write(0, 4, "Brand", heading_xf)
1597
    sheet.write(0, 5, "Product Name", heading_xf)
1598
    sheet.write(0, 6, "Reason", heading_xf)
1599
 
1600
    sheet_iterator = 1
1601
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1602
    for amongCheapestItem in amongCheapestItems:
1603
        amScraping =  amongCheapestItem[0]
1604
        item = amongCheapestItem[1]
1605
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1606
        if amScraping.warehouseLocation == 1:
1607
            sku = 'FBA'+str(amScraping.item_id)
1608
            loc = 'MUMBAI'
1609
        else:
1610
            sku = 'FBB'+str(amScraping.item_id)
1611
            loc = 'BANGLORE'
1612
        sheet.write(sheet_iterator, 1, sku)
1613
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1614
        sheet.write(sheet_iterator, 3, loc)
1615
        sheet.write(sheet_iterator, 4, item.brand)
1616
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1617
        sheet.write(sheet_iterator, 6, amScraping.reason)
1618
        sheet_iterator+=1      
1619
 
12444 kshitij.so 1620
 
1621
    if (runType=='FULL'):    
1622
        sheet = wbk.add_sheet('Auto Favorites')
1623
 
1624
        heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1625
 
1626
        excel_integer_format = '0'
1627
        integer_style = xlwt.XFStyle()
1628
        integer_style.num_format_str = excel_integer_format
1629
        xstr = lambda s: s or ""
1630
 
1631
        sheet.write(0, 0, "Item ID", heading_xf)
1632
        sheet.write(0, 1, "Brand", heading_xf)
1633
        sheet.write(0, 2, "Product Name", heading_xf)
1634
        sheet.write(0, 3, "Auto Favourite", heading_xf)
1635
        sheet.write(0, 4, "Reason", heading_xf)
1636
 
1637
        sheet_iterator=1
1638
        for autoFav in nowAutoFav:
1639
            itemId = autoFav[0]
1640
            reason = autoFav[1]
1641
            it = Item.query.filter_by(id=itemId).one()
1642
            sheet.write(sheet_iterator, 0, itemId)
1643
            sheet.write(sheet_iterator, 1, it.brand)
1644
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1645
            sheet.write(sheet_iterator, 3, "True")
1646
            sheet.write(sheet_iterator, 4, reason)
1647
            sheet_iterator+=1
1648
        for prevFav in previousAutoFav:
1649
            it = Item.query.filter_by(id=prevFav).one()
1650
            sheet.write(sheet_iterator, 0, prevFav)
1651
            sheet.write(sheet_iterator, 1, it.brand)
1652
            sheet.write(sheet_iterator, 2, xstr(it.brand)+" "+xstr(it.model_name)+" "+xstr(it.model_number)+" "+xstr(it.color))
1653
            sheet.write(sheet_iterator, 3, "False")
1654
            sheet_iterator+=1
1655
 
12396 kshitij.so 1656
    filename = "/tmp/amazon-scraping.xls"
1657
    wbk.save(filename)
1658
 
12363 kshitij.so 1659
def main():
1660
    parser = optparse.OptionParser()
1661
    parser.add_option("-t", "--type", dest="runType",
1662
                   default="FULL", type="string",
1663
                   help="Run type FULL or FAVOURITE")
1664
    (options, args) = parser.parse_args()
1665
    if options.runType not in ('FULL','FAVOURITE'):
1666
        print "Run type argument illegal."
1667
        sys.exit(1)
1668
    time.sleep(5)
1669
    timestamp = datetime.now()
1670
    fetchFbaSale()
1671
    itemInfo = populateStuff(timestamp,options.runType)
1672
    itemsToPopulate = 0
12430 kshitij.so 1673
    toSync = 0
1674
    lenItems = len(itemInfo)
1675
    while(toSync < lenItems):
1676
        oldSync = toSync
1677
        if lenItems >= 20:
1678
            toSync = 20
1679
        else:
1680
            toSync = lenItems - oldSync
1681
        getPriceAndAsin(itemInfo[oldSync:toSync+oldSync])
1682
        toSync = oldSync + toSync
1683
 
12363 kshitij.so 1684
    while (len(itemInfo)>0):
12430 kshitij.so 1685
        if len(itemInfo) >= 20:
1686
            itemsToPopulate = 20
12363 kshitij.so 1687
        else:
1688
            itemsToPopulate = len(itemInfo)
12370 kshitij.so 1689
        print itemsToPopulate
12363 kshitij.so 1690
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate])
1691
        itemInfo[0:itemsToPopulate] = []
1692
        commitExceptionList(exceptionList,timestamp,options.runType)
1693
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
1694
        commitCheapest(cheapest,timestamp,options.runType)
1695
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
1696
        commitCanCompete(canCompete,timestamp,options.runType)
1697
        commitAlmostCompete(almostCompete,timestamp,options.runType)
1698
        commitCantCompete(cantCompete, timestamp,options.runType)
12396 kshitij.so 1699
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1700
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1701
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1702
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
12444 kshitij.so 1703
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav,options.runType)
12363 kshitij.so 1704
if __name__=='__main__':
1705
    main()