Subversion Repositories SmartDukaan

Rev

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