Subversion Repositories SmartDukaan

Rev

Rev 12403 | Rev 12408 | 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:
12404 kshitij.so 395
        print "Trying to get details of ",val.sku
12379 kshitij.so 396
        if val.asin is None or len(val.asin)==0:
12363 kshitij.so 397
            continue
398
        scrapInfo = aggResponse.get(val.asin)
12404 kshitij.so 399
        print "Scraped info for asin is ",scrapInfo
12363 kshitij.so 400
        if val.sku in amazonLongTermActivePromotions:
401
            print "Sku in promotion, will handle it later.Moving to other..."
402
            continue
403
        if scrapInfo is None or val.nlc==0:
404
            temp = []
405
            temp.append(val)
406
            if val.nlc==0 or val.nlc is None:
407
                temp.append("WANLC is 0")
408
            else:
409
                temp.append("Not able to fetch")
410
            exceptionList.append(temp)
411
            continue
412
        iterator = 0
413
        sku, lowestSellerName,secondLowestSellerName, thirdLowestSellerName = ('',)*4
414
        ourSp, ourRank, lowestSellerSp, secondLowestSellerSp, thirdLowestSellerSp, ourTp, lowestPossibleSp, lowestPossibleTp = (0,)*8
415
        sku = val.sku
416
        scrapedSkuLocation = None
417
        multipleListings = False
418
        for info in scrapInfo:
12401 kshitij.so 419
            print "iterating scrap info"
12400 kshitij.so 420
            if (info['sellerName']).strip()=='Saholic':
12363 kshitij.so 421
                if ourRank>0:
422
                    multipleListings = True
12400 kshitij.so 423
                ourSp = info['sellerPrice']
12363 kshitij.so 424
                ourRank = iterator+1
425
                if val.state_id==1:
426
                    #It means sku starts with FBA
427
                    fbaPrice = (amazonAsinPrice.get(val.sku)).price
428
                    try:
429
                        if ourSp==fbaPrice:
430
                            scrapedSkuLocation = val.state_id
431
                    except:
432
                        scrapedSkuLocation = None
433
                elif val.state_id==2:
434
                    #It means sku starts with FBB
435
                    fbbPrice = (amazonAsinPrice.get(val.sku)).price
436
                    try:
437
                        if ourSp==fbbPrice:
438
                            scrapedSkuLocation = val.state_id
439
                    except:
440
                        scrapedSkuLocation = None
441
                else:
442
                    scrapedSkuLocation = None
443
                if scrapedSkuLocation is None:
444
                    print "fishy...confused for ", val.sku
445
 
446
            if iterator == 0:
12400 kshitij.so 447
                lowestSellerName = info['sellerName']
448
                lowestSellerSp = info['sellerPrice']
12363 kshitij.so 449
 
450
            if iterator == 1:
12400 kshitij.so 451
                secondLowestSellerName = info['sellerName']
452
                secondLowestSellerSp = info['sellerPrice']
12363 kshitij.so 453
 
454
            if iterator == 2:
12400 kshitij.so 455
                thirdLowestSellerName = info['sellerName']
456
                thirdLowestSellerSp = info['sellerPrice']
12363 kshitij.so 457
 
458
            iterator += 1
12401 kshitij.so 459
        print "terminating iterator"
12363 kshitij.so 460
        #if cheapestSkuLocation!=val.state_id
461
 
462
        if ourSp==0 or scrapedSkuLocation is None:
463
            print "Sku not present in top 3.Getting price from amazonAsinPrice...or multiple listings"
464
            if ourSp==0:
465
                ourRank = 999 #Due to pagination and large no of sellers.Taking it as dummy value, means we are not in top 3
466
                ourSp = (amazonAsinPrice.get(val.sku)).price
467
                if ourSp is None or ourSp==0:
468
                    temp = []
469
                    temp.append(val)
470
                    temp.append("Price not available")
471
                    exceptionList.append(temp)
472
                    continue
473
            else:
474
                #determine rank
475
                if ourSp <= lowestSellerSp or lowestSellerSp==0:
476
                    ourRank = 1
477
                elif ourSp > lowestSellerSp and (ourSp <= secondLowestSellerSp or secondLowestSellerSp==0):
478
                    ourRank = 2
479
                elif ourSp > secondLowestSellerSp and (ourSp<=thirdLowestSellerSp or thirdLowestSellerSp==0):
480
                    ourRank = 3
481
                else:
482
                    ourRank = 999
483
 
484
        if multipleListings:
485
            print "multiple listings..."
486
            ourSp = (amazonAsinPrice.get(val.sku)).price
487
            if ourSp is None or ourSp==0:
488
                temp = []
489
                temp.append(val)
490
                temp.append("Price not available")
491
                exceptionList.append(temp)
492
                continue
493
            if ourSp <= lowestSellerSp:
494
                    ourRank = 1
495
            elif ourSp > lowestSellerSp and (ourSp <= secondLowestSellerSp or secondLowestSellerSp==0):
496
                ourRank = 2
497
            elif ourSp > secondLowestSellerSp and (ourSp<=thirdLowestSellerSp or thirdLowestSellerSp==0):
498
                ourRank = 3
499
            else:
500
                ourRank = 999
501
 
502
 
503
        amDetails = __AmazonDetails(sku, ourSp, ourRank, lowestSellerName,lowestSellerSp,secondLowestSellerName, secondLowestSellerSp, thirdLowestSellerName, thirdLowestSellerSp,len(scrapInfo),multipleListings)
504
        try:
505
            val.vatRate = catalog_client.getVatPercentageForItem(int(val.sku[3:]), val.state_id, amDetails.ourSp)
506
        except:
507
            temp = []
508
            temp.append(val)
509
            temp.append("Vat not available")
510
            exceptionList.append(temp)
511
            continue
512
 
513
        ourTp = getOurTp(amDetails,val,val.sourcePercentage)
514
        lowestPossibleTp = getLowestPossibleTp(amDetails,val,val.sourcePercentage)
515
        lowestPossibleSp = getLowestPossibleSp(amDetails,val,val.sourcePercentage)
516
        amPricing = __AmazonPricing(ourSp,ourTp,lowestPossibleTp,lowestPossibleSp)
517
 
518
        if amPricing.ourTp < amPricing.lowestPossibleTp:
519
            temp = []
520
            temp.append(val)
521
            temp.append(amDetails)
522
            temp.append(amPricing)
523
            negativeMargin.append(temp)
524
            continue
525
 
526
        if amDetails.ourRank==1:
527
            temp = []
528
            temp.append(val)
529
            temp.append(amDetails)
530
            temp.append(amPricing)
531
            cheapest.append(temp)
532
            continue
533
 
534
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp) and ((((float(amDetails.ourSp - amDetails.lowestSellerSp))/amDetails.ourSp)<=.01) or ((amDetails.ourSp - amDetails.lowestSellerSp)<=25)):
535
            temp = []
536
            temp.append(val)
537
            temp.append(amDetails)
538
            temp.append(amPricing)
539
            amongCheapestAndCanCompete.append(temp)
540
            continue
541
 
542
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp):
543
            temp = []
544
            temp.append(val)
545
            temp.append(amDetails)
546
            temp.append(amPricing)
547
            canCompete.append(temp)
548
            continue
549
 
12403 kshitij.so 550
        if amDetails.lowestSellerSp*(1+.01) >= amPricing.lowestPossibleSp:
12396 kshitij.so 551
            temp = []
552
            temp.append(val)
553
            temp.append(amDetails)
554
            temp.append(amPricing)
555
            almostCompete.append(temp)
556
            continue
557
 
558
 
12363 kshitij.so 559
        temp = []
560
        temp.append(val)
561
        temp.append(amDetails)
562
        temp.append(amPricing)
563
        cantCompete.append(temp)
564
 
565
    itemInfo[:]=[]
566
    return exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete
12396 kshitij.so 567
 
12363 kshitij.so 568
def getOurTp(amazonDetails,val,spm):
569
    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));
570
    return round(ourTp,2)
571
 
572
def getLowestPossibleTp(amazonDetails,val,spm):
573
    vat = (amazonDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100)
574
    inHouseCost = 15+vat+(spm.returnProvision/100)*amazonDetails.ourSp
575
    lowest_possible_tp = val.nlc+inHouseCost
576
    return round(lowest_possible_tp,2)
577
 
578
def getLowestPossibleSp(amazonDetails,val,spm):
579
    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));
580
    return round(lowestPossibleSp,2)
581
 
582
def getTargetTp(targetSp,spm,val):
583
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(val.serviceTax/100))
584
    return round(targetTp,2)
585
 
586
def commitExceptionList(exceptionList,timestamp,runType):
587
    for exceptionItem in exceptionList:
588
        val = exceptionItem[0]
589
        reason = exceptionItem[1]
590
        amazonScrapingHistory = AmazonScrapingHistory()
591
        amazonScrapingHistory.item_id = val.sku[3:]
592
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 593
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 594
        amazonScrapingHistory.reason = reason
595
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
596
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.EXCEPTION
597
        amazonScrapingHistory.timestamp = timestamp
598
    session.commit()
599
 
600
def commitNegativeMargin(negativeMargin,timestamp,runType):
601
    for negativeMarginItem in negativeMargin:
602
        val = negativeMarginItem[0]
603
        amDetails = negativeMarginItem[1]
604
        amPricing = negativeMarginItem[2]
605
        spm = val.sourcePercentage
606
        amazonScrapingHistory = AmazonScrapingHistory()
607
        amazonScrapingHistory.item_id = val.sku[3:]
608
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 609
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 610
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
611
        amazonScrapingHistory.ourTp = amPricing.ourTp
612
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
613
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
614
        amazonScrapingHistory.ourRank = amDetails.ourRank
615
        amazonScrapingHistory.ourInventory = val.ourInventory
616
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
617
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
618
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
619
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
620
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
621
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
622
        amazonScrapingHistory.wanlc = val.nlc
623
        amazonScrapingHistory.commission = spm.commission
624
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
625
        amazonScrapingHistory.returnProvision = spm.returnProvision
626
        amazonScrapingHistory.courierCost = val.courierCost
627
        amazonScrapingHistory.risky = val.risky
628
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
629
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
630
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
631
        amazonScrapingHistory.timestamp = timestamp
632
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
633
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
634
    session.commit()
635
 
636
 
637
def commitCheapest(cheapest,timestamp,runType):
638
    for cheapestItem in cheapest:
639
        val = cheapestItem[0]
640
        amDetails = cheapestItem[1]
641
        amPricing = cheapestItem[2]
642
        spm = val.sourcePercentage
643
        amazonScrapingHistory = AmazonScrapingHistory()
644
        amazonScrapingHistory.item_id = val.sku[3:]
645
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 646
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 647
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
648
        amazonScrapingHistory.ourTp = amPricing.ourTp
649
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
650
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
651
        amazonScrapingHistory.ourRank = amDetails.ourRank
652
        amazonScrapingHistory.ourInventory = val.ourInventory
653
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
654
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
655
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
656
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
657
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
658
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
659
        amazonScrapingHistory.wanlc = val.nlc
660
        amazonScrapingHistory.commission = spm.commission
661
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
662
        amazonScrapingHistory.returnProvision = spm.returnProvision
663
        amazonScrapingHistory.courierCost = val.courierCost
664
        amazonScrapingHistory.risky = val.risky
665
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
666
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
667
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.BUY_BOX
668
        amazonScrapingHistory.timestamp = timestamp
669
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
670
        if amDetails.secondLowestSellerName!='Saholic':
671
            competitorSp = amDetails.secondLowestSellerSp
672
        else:
673
            competitorSp = amDetails.thirdLowestSellerSp
674
        proposed_sp = max(competitorSp - max((20, competitorSp*0.002)), amPricing.lowestPossibleSp)
675
        proposed_tp = getTargetTp(proposed_sp,spm,val)
676
        amazonScrapingHistory.proposedSp = proposed_sp
677
        amazonScrapingHistory.proposedTp = proposed_tp
678
        amazonScrapingHistory.marginIncreasedPotential = proposed_tp - amPricing.ourTp
679
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
680
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
681
    session.commit()
682
 
683
 
684
 
685
def commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,runType):
686
    for amongCheapestAndCanCompeteItem in amongCheapestAndCanCompete:
687
        val = amongCheapestAndCanCompeteItem[0]
688
        amDetails = amongCheapestAndCanCompeteItem[1]
689
        amPricing = amongCheapestAndCanCompeteItem[2]
690
        spm = val.sourcePercentage
691
        amazonScrapingHistory = AmazonScrapingHistory()
692
        amazonScrapingHistory.item_id = val.sku[3:]
693
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 694
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 695
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
696
        amazonScrapingHistory.ourTp = amPricing.ourTp
697
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
698
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
699
        amazonScrapingHistory.ourRank = amDetails.ourRank
700
        amazonScrapingHistory.ourInventory = val.ourInventory
701
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
702
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
703
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
704
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
705
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
706
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
707
        amazonScrapingHistory.wanlc = val.nlc
708
        amazonScrapingHistory.commission = spm.commission
709
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
710
        amazonScrapingHistory.returnProvision = spm.returnProvision
711
        amazonScrapingHistory.courierCost = val.courierCost
712
        amazonScrapingHistory.risky = val.risky
713
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
714
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
715
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE
716
        amazonScrapingHistory.timestamp = timestamp
717
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
718
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
719
        proposed_tp = getTargetTp(proposed_sp,spm,val)
720
        amazonScrapingHistory.proposedSp = proposed_sp
721
        amazonScrapingHistory.proposedTp = proposed_tp
722
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
723
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
724
    session.commit()
725
 
726
def commitCanCompete(canCompete,timestamp,runType):
727
    for canCompeteItem in canCompete:
728
        val = canCompeteItem[0]
729
        amDetails = canCompeteItem[1]
730
        amPricing = canCompeteItem[2]
731
        spm = val.sourcePercentage
732
        amazonScrapingHistory = AmazonScrapingHistory()
733
        amazonScrapingHistory.item_id = val.sku[3:]
734
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 735
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 736
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
737
        amazonScrapingHistory.ourTp = amPricing.ourTp
738
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
739
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
740
        amazonScrapingHistory.ourRank = amDetails.ourRank
741
        amazonScrapingHistory.ourInventory = val.ourInventory
742
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
743
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
744
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
745
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
746
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
747
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
748
        amazonScrapingHistory.wanlc = val.nlc
749
        amazonScrapingHistory.commission = spm.commission
750
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
751
        amazonScrapingHistory.returnProvision = spm.returnProvision
752
        amazonScrapingHistory.courierCost = val.courierCost
753
        amazonScrapingHistory.risky = val.risky
754
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
755
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
756
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
757
        amazonScrapingHistory.timestamp = timestamp
758
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
759
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
760
        proposed_tp = getTargetTp(proposed_sp,spm,val)
761
        amazonScrapingHistory.proposedSp = proposed_sp
762
        amazonScrapingHistory.proposedTp = proposed_tp
763
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
764
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
765
    session.commit()
766
 
12383 kshitij.so 767
def commitAlmostCompete(almostCompete,timestamp,runType):
12396 kshitij.so 768
    for almostCompeteItem in almostCompete:
769
        val = almostCompeteItem[0]
770
        amDetails = almostCompeteItem[1]
771
        amPricing = almostCompeteItem[2]
772
        spm = val.sourcePercentage
773
        amazonScrapingHistory = AmazonScrapingHistory()
774
        amazonScrapingHistory.item_id = val.sku[3:]
775
        amazonScrapingHistory.warehouseLocation = val.state_id
776
        amazonScrapingHistory.parentCategoryId = val.parent_category
777
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
778
        amazonScrapingHistory.ourTp = amPricing.ourTp
779
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
780
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
781
        amazonScrapingHistory.ourRank = amDetails.ourRank
782
        amazonScrapingHistory.ourInventory = val.ourInventory
783
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
784
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
785
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
786
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
787
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
788
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
789
        amazonScrapingHistory.wanlc = val.nlc
790
        amazonScrapingHistory.commission = spm.commission
791
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
792
        amazonScrapingHistory.returnProvision = spm.returnProvision
793
        amazonScrapingHistory.courierCost = val.courierCost
794
        amazonScrapingHistory.risky = val.risky
795
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
796
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
797
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.ALMOST_COMPETE
798
        amazonScrapingHistory.timestamp = timestamp
799
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
800
        proposed_sp = min(amDetails.lowestSellerSp(1+.01),amPricing.lowestPossibleSp)
801
        proposed_tp = getTargetTp(proposed_sp,spm,val)
802
        target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
803
        amazonScrapingHistory.proposedSp = proposed_sp
804
        amazonScrapingHistory.proposedTp = proposed_tp
805
        amazonScrapingHistory.targetNlc = target_nlc
806
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
807
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
808
    session.commit()
12363 kshitij.so 809
 
12396 kshitij.so 810
 
12363 kshitij.so 811
def commitCantCompete(cantCompete, timestamp,runType):
812
    for cantCompeteItem in cantCompete:
813
        val = cantCompeteItem[0]
814
        amDetails = cantCompeteItem[1]
815
        amPricing = cantCompeteItem[2]
816
        spm = val.sourcePercentage
817
        amazonScrapingHistory = AmazonScrapingHistory()
818
        amazonScrapingHistory.item_id = val.sku[3:]
819
        amazonScrapingHistory.warehouseLocation = val.state_id
12396 kshitij.so 820
        amazonScrapingHistory.parentCategoryId = val.parent_category
12363 kshitij.so 821
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
822
        amazonScrapingHistory.ourTp = amPricing.ourTp
823
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
824
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
825
        amazonScrapingHistory.ourRank = amDetails.ourRank
826
        amazonScrapingHistory.ourInventory = val.ourInventory
827
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
828
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
829
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
830
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
831
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
832
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
833
        amazonScrapingHistory.wanlc = val.nlc
834
        amazonScrapingHistory.commission = spm.commission
835
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
836
        amazonScrapingHistory.returnProvision = spm.returnProvision
837
        amazonScrapingHistory.courierCost = val.courierCost
838
        amazonScrapingHistory.risky = val.risky
839
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
840
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
841
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
842
        amazonScrapingHistory.timestamp = timestamp
843
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
844
        proposed_sp = amDetails.lowestSellerSp - max(5, amDetails.lowestSellerSp*0.001)
845
        proposed_tp = getTargetTp(proposed_sp,spm,val)
846
        target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
847
        amazonScrapingHistory.proposedSp = proposed_sp
848
        amazonScrapingHistory.proposedTp = proposed_tp
849
        amazonScrapingHistory.targetNlc = target_nlc
850
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
851
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
852
    session.commit()
853
 
12396 kshitij.so 854
def markAutoFavourites(time):
855
    nowAutoFav = []
856
    previouslyAutoFav = []
857
    stockList = []
858
    saleList = []
859
    items = session.query(func.sum(AmazonScrapingHistory.ourInventory),AmazonScrapingHistory.item_id).group_by(AmazonScrapingHistory.item_id).all()
860
    allItems = session.query(Amazonlisted).all()
861
    for item in items:
862
        reason = ""
863
        if item[0]>=5:
864
            stockList.append(item[1])
865
 
866
    for sku, val in saleMap.iteritems():
867
        totalSale = 0
868
        item_id = sku.replace('FBA','').replace('FBB','')
869
        val =saleMap.get('FBA'+str(item_id))
870
        if val is not None:
871
            for sale in val:
872
                totalSale += sale.totalOrderCount
873
        val =saleMap.get('FBB'+str(item_id))
874
        if val is not None:
875
            for sale in val:
876
                totalSale += sale.totalOrderCount
877
        if totalSale > 0:
878
            saleList.append(item_id)
879
 
880
    for aItem in allItems:
881
        reason = ""
882
        toMark = False
883
        if aItem.itemId in saleList:
884
            toMark = True
885
            reason+="Total FC sale is greater than 1 for last five days.."
886
        if aItem.itemId in stockList:
887
            toMark = True
888
            reason+="Item is present in buy box in last 3 days"
889
        if not aItem.autoFavourite:
890
            print "Item is not under auto favourite"
891
        if toMark:
892
            temp=[]
893
            temp.append(aItem.itemId)
894
            temp.append(reason)
895
            nowAutoFav.append(temp)
896
        if (not toMark) and aItem.autoFavourite:
897
            previouslyAutoFav.append(aItem.itemId)
898
        aItem.autoFavourite = toMark
899
    session.commit()
900
    return previouslyAutoFav, nowAutoFav
901
 
902
def writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav):
903
    wbk = xlwt.Workbook()
904
    sheet = wbk.add_sheet('Can\'t Compete')
905
    xstr = lambda s: s or ""
906
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
907
 
908
    excel_integer_format = '0'
909
    integer_style = xlwt.XFStyle()
910
    integer_style.num_format_str = excel_integer_format
911
 
912
    sheet.write(0, 0, "Item Id", heading_xf)
913
    sheet.write(0, 1, "Amazon Sku", heading_xf)
914
    sheet.write(0, 2, "Asin", heading_xf)
915
    sheet.write(0, 3, "Location", heading_xf)
916
    sheet.write(0, 4, "Brand", heading_xf)
917
    sheet.write(0, 5, "Product Name", heading_xf)
918
    sheet.write(0, 6, "Weight", heading_xf)
919
    sheet.write(0, 7, "Courier Cost", heading_xf)
920
    sheet.write(0, 8, "Our SP", heading_xf)
921
    sheet.write(0, 9, "Our Tp", heading_xf)
922
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
923
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
924
    sheet.write(0, 12, "Rank", heading_xf)
925
    sheet.write(0, 13, "Our Inventory", heading_xf)
926
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
927
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
928
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
929
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
930
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
931
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
932
    sheet.write(0, 20, "WANLC", heading_xf)
933
    sheet.write(0, 21, "Commission", heading_xf)
934
    sheet.write(0, 22, "Competitor Commission", heading_xf)
935
    sheet.write(0, 23, "Return Provision", heading_xf)
936
    sheet.write(0, 24, "Margin", heading_xf)
937
    sheet.write(0, 25, "Risky", heading_xf)
938
    sheet.write(0, 26, "Proposed Sp", heading_xf)
939
    sheet.write(0, 27, "Proposed Tp", heading_xf)
940
    sheet.write(0, 28, "Target Nlc", heading_xf)
941
    sheet.write(0, 29, "Avg Sale", heading_xf)
942
    sheet.write(0, 30, "Sales History", heading_xf)
943
 
944
    sheet_iterator = 1
945
    cantCompeteItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.CANT_COMPETE).all()
946
    for cantCompeteItem in cantCompeteItems:
947
        amScraping =  cantCompeteItem[0]
948
        item = cantCompeteItem[1]
949
        sheet.write(sheet_iterator, 0, amScraping.item_id)
950
        if amScraping.warehouseLocation == 1:
951
            sku = 'FBA'+str(amScraping.item_id)
952
            loc = 'MUMBAI'
953
        else:
954
            sku = 'FBB'+str(amScraping.item_id)
955
            loc = 'BANGLORE'
956
        sheet.write(sheet_iterator, 1, sku)
957
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
958
        sheet.write(sheet_iterator, 3, loc)
959
        sheet.write(sheet_iterator, 4, item.brand)
960
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
961
        sheet.write(sheet_iterator, 6, item.weight)
962
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
963
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
964
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
965
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
966
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
967
        if amScraping.ourRank > 3:
968
            sheet.write(sheet_iterator, 12, 'Greater than 3')
969
        else:
970
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
971
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
972
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
973
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
974
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
975
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
976
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
977
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
978
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
979
        sheet.write(sheet_iterator, 21, amScraping.commission)
980
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
981
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
982
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
983
        sheet.write(sheet_iterator, 25, item.risky)
984
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
985
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
986
        sheet.write(sheet_iterator, 28, amScraping.targetNlc)
987
        sheet.write(sheet_iterator, 29, amScraping.avgSale)
988
        sheet.write(sheet_iterator, 30, getOosString(saleMap.get(sku)))
989
        sheet_iterator+=1
990
 
991
    sheet = wbk.add_sheet('Competitive')
992
    xstr = lambda s: s or ""
993
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
994
 
995
    excel_integer_format = '0'
996
    integer_style = xlwt.XFStyle()
997
    integer_style.num_format_str = excel_integer_format
998
 
999
    sheet.write(0, 0, "Item Id", heading_xf)
1000
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1001
    sheet.write(0, 2, "Asin", heading_xf)
1002
    sheet.write(0, 3, "Location", heading_xf)
1003
    sheet.write(0, 4, "Brand", heading_xf)
1004
    sheet.write(0, 5, "Product Name", heading_xf)
1005
    sheet.write(0, 6, "Weight", heading_xf)
1006
    sheet.write(0, 7, "Courier Cost", heading_xf)
1007
    sheet.write(0, 8, "Our SP", heading_xf)
1008
    sheet.write(0, 9, "Our Tp", heading_xf)
1009
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1010
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1011
    sheet.write(0, 12, "Rank", heading_xf)
1012
    sheet.write(0, 13, "Our Inventory", heading_xf)
1013
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1014
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1015
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1016
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1017
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1018
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1019
    sheet.write(0, 20, "WANLC", heading_xf)
1020
    sheet.write(0, 21, "Commission", heading_xf)
1021
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1022
    sheet.write(0, 23, "Return Provision", heading_xf)
1023
    sheet.write(0, 24, "Margin", heading_xf)
1024
    sheet.write(0, 25, "Risky", heading_xf)
1025
    sheet.write(0, 26, "Proposed Sp", heading_xf)
1026
    sheet.write(0, 27, "Proposed Tp", heading_xf)
1027
    sheet.write(0, 28, "Avg Sale", heading_xf)
1028
    sheet.write(0, 29, "Sales History", heading_xf)
1029
 
1030
    sheet_iterator = 1
1031
    competitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.COMPETITIVE).all()
1032
    for competitiveItem in competitiveItems:
1033
        amScraping =  competitiveItem[0]
1034
        item = competitiveItem[1]
1035
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1036
        if amScraping.warehouseLocation == 1:
1037
            sku = 'FBA'+str(amScraping.item_id)
1038
            loc = 'MUMBAI'
1039
        else:
1040
            sku = 'FBB'+str(amScraping.item_id)
1041
            loc = 'BANGLORE'
1042
        sheet.write(sheet_iterator, 1, sku)
1043
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1044
        sheet.write(sheet_iterator, 3, loc)
1045
        sheet.write(sheet_iterator, 4, item.brand)
1046
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1047
        sheet.write(sheet_iterator, 6, item.weight)
1048
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1049
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1050
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1051
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1052
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1053
        if amScraping.ourRank > 3:
1054
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1055
        else:
1056
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1057
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1058
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1059
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1060
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1061
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1062
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1063
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1064
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1065
        sheet.write(sheet_iterator, 21, amScraping.commission)
1066
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1067
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1068
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1069
        sheet.write(sheet_iterator, 25, item.risky)
1070
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
1071
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
1072
        sheet.write(sheet_iterator, 28, amScraping.avgSale)
1073
        sheet.write(sheet_iterator, 29, getOosString(saleMap.get(sku)))
1074
        sheet_iterator+=1
1075
 
1076
    sheet = wbk.add_sheet('Almost Competitive')
1077
    xstr = lambda s: s or ""
1078
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1079
 
1080
    excel_integer_format = '0'
1081
    integer_style = xlwt.XFStyle()
1082
    integer_style.num_format_str = excel_integer_format
1083
 
1084
    sheet.write(0, 0, "Item Id", heading_xf)
1085
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1086
    sheet.write(0, 2, "Asin", heading_xf)
1087
    sheet.write(0, 3, "Location", heading_xf)
1088
    sheet.write(0, 4, "Brand", heading_xf)
1089
    sheet.write(0, 5, "Product Name", heading_xf)
1090
    sheet.write(0, 6, "Weight", heading_xf)
1091
    sheet.write(0, 7, "Courier Cost", heading_xf)
1092
    sheet.write(0, 8, "Our SP", heading_xf)
1093
    sheet.write(0, 9, "Our Tp", heading_xf)
1094
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1095
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1096
    sheet.write(0, 12, "Rank", heading_xf)
1097
    sheet.write(0, 13, "Our Inventory", heading_xf)
1098
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1099
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1100
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1101
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1102
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1103
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1104
    sheet.write(0, 20, "WANLC", heading_xf)
1105
    sheet.write(0, 21, "Commission", heading_xf)
1106
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1107
    sheet.write(0, 23, "Return Provision", heading_xf)
1108
    sheet.write(0, 24, "Margin", heading_xf)
1109
    sheet.write(0, 25, "Risky", heading_xf)
1110
    sheet.write(0, 26, "Proposed Sp", heading_xf)
1111
    sheet.write(0, 27, "Proposed Tp", heading_xf)
1112
    sheet.write(0, 28, "Avg Sale", heading_xf)
1113
    sheet.write(0, 29, "Sales History", heading_xf)
1114
 
1115
    sheet_iterator = 1
1116
    almostCompetitiveItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.ALMOST_COMPETE).all()
1117
    for almostCompetitiveItem in almostCompetitiveItems:
1118
        amScraping =  almostCompetitiveItem[0]
1119
        item = almostCompetitiveItem[1]
1120
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1121
        if amScraping.warehouseLocation == 1:
1122
            sku = 'FBA'+str(amScraping.item_id)
1123
            loc = 'MUMBAI'
1124
        else:
1125
            sku = 'FBB'+str(amScraping.item_id)
1126
            loc = 'BANGLORE'
1127
        sheet.write(sheet_iterator, 1, sku)
1128
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1129
        sheet.write(sheet_iterator, 3, loc)
1130
        sheet.write(sheet_iterator, 4, item.brand)
1131
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1132
        sheet.write(sheet_iterator, 6, item.weight)
1133
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1134
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1135
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1136
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1137
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1138
        if amScraping.ourRank > 3:
1139
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1140
        else:
1141
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1142
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1143
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1144
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1145
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1146
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1147
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1148
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1149
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1150
        sheet.write(sheet_iterator, 21, amScraping.commission)
1151
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1152
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1153
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1154
        sheet.write(sheet_iterator, 25, item.risky)
1155
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
1156
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
1157
        sheet.write(sheet_iterator, 28, amScraping.avgSale)
1158
        sheet.write(sheet_iterator, 29, getOosString(saleMap.get(sku)))
1159
        sheet_iterator+=1
1160
 
1161
    sheet = wbk.add_sheet('Among Cheapest')
1162
    xstr = lambda s: s or ""
1163
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1164
 
1165
    excel_integer_format = '0'
1166
    integer_style = xlwt.XFStyle()
1167
    integer_style.num_format_str = excel_integer_format
1168
 
1169
    sheet.write(0, 0, "Item Id", heading_xf)
1170
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1171
    sheet.write(0, 2, "Asin", heading_xf)
1172
    sheet.write(0, 3, "Location", heading_xf)
1173
    sheet.write(0, 4, "Brand", heading_xf)
1174
    sheet.write(0, 5, "Product Name", heading_xf)
1175
    sheet.write(0, 6, "Weight", heading_xf)
1176
    sheet.write(0, 7, "Courier Cost", heading_xf)
1177
    sheet.write(0, 8, "Our SP", heading_xf)
1178
    sheet.write(0, 9, "Our Tp", heading_xf)
1179
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1180
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1181
    sheet.write(0, 12, "Rank", heading_xf)
1182
    sheet.write(0, 13, "Our Inventory", heading_xf)
1183
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1184
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1185
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1186
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1187
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1188
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1189
    sheet.write(0, 20, "WANLC", heading_xf)
1190
    sheet.write(0, 21, "Commission", heading_xf)
1191
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1192
    sheet.write(0, 23, "Return Provision", heading_xf)
1193
    sheet.write(0, 24, "Margin", heading_xf)
1194
    sheet.write(0, 25, "Risky", heading_xf)
1195
    sheet.write(0, 26, "Proposed Sp", heading_xf)
1196
    sheet.write(0, 27, "Proposed Tp", heading_xf)
1197
    sheet.write(0, 28, "Avg Sale", heading_xf)
1198
    sheet.write(0, 29, "Sales History", heading_xf)
1199
 
1200
    sheet_iterator = 1
1201
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1202
    for amongCheapestItem in amongCheapestItems:
1203
        amScraping =  amongCheapestItem[0]
1204
        item = amongCheapestItem[1]
1205
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1206
        if amScraping.warehouseLocation == 1:
1207
            sku = 'FBA'+str(amScraping.item_id)
1208
            loc = 'MUMBAI'
1209
        else:
1210
            sku = 'FBB'+str(amScraping.item_id)
1211
            loc = 'BANGLORE'
1212
        sheet.write(sheet_iterator, 1, sku)
1213
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1214
        sheet.write(sheet_iterator, 3, loc)
1215
        sheet.write(sheet_iterator, 4, item.brand)
1216
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1217
        sheet.write(sheet_iterator, 6, item.weight)
1218
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1219
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1220
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1221
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1222
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1223
        if amScraping.ourRank > 3:
1224
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1225
        else:
1226
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1227
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1228
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1229
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1230
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1231
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1232
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1233
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1234
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1235
        sheet.write(sheet_iterator, 21, amScraping.commission)
1236
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1237
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1238
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1239
        sheet.write(sheet_iterator, 25, item.risky)
1240
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
1241
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
1242
        sheet.write(sheet_iterator, 28, amScraping.avgSale)
1243
        sheet.write(sheet_iterator, 29, getOosString(saleMap.get(sku)))
1244
        sheet_iterator+=1
1245
 
1246
    sheet = wbk.add_sheet('Cheapest')
1247
    xstr = lambda s: s or ""
1248
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1249
 
1250
    excel_integer_format = '0'
1251
    integer_style = xlwt.XFStyle()
1252
    integer_style.num_format_str = excel_integer_format
1253
 
1254
    sheet.write(0, 0, "Item Id", heading_xf)
1255
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1256
    sheet.write(0, 2, "Asin", heading_xf)
1257
    sheet.write(0, 3, "Location", heading_xf)
1258
    sheet.write(0, 4, "Brand", heading_xf)
1259
    sheet.write(0, 5, "Product Name", heading_xf)
1260
    sheet.write(0, 6, "Weight", heading_xf)
1261
    sheet.write(0, 7, "Courier Cost", heading_xf)
1262
    sheet.write(0, 8, "Our SP", heading_xf)
1263
    sheet.write(0, 9, "Our Tp", heading_xf)
1264
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1265
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1266
    sheet.write(0, 12, "Rank", heading_xf)
1267
    sheet.write(0, 13, "Our Inventory", heading_xf)
1268
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1269
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1270
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1271
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1272
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1273
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1274
    sheet.write(0, 20, "WANLC", heading_xf)
1275
    sheet.write(0, 21, "Commission", heading_xf)
1276
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1277
    sheet.write(0, 23, "Return Provision", heading_xf)
1278
    sheet.write(0, 24, "Margin", heading_xf)
1279
    sheet.write(0, 25, "Risky", heading_xf)
1280
    sheet.write(0, 26, "Proposed Sp", heading_xf)
1281
    sheet.write(0, 27, "Proposed Tp", heading_xf)
1282
    sheet.write(0, 28, "Margin Increased Potential", heading_xf)
1283
    sheet.write(0, 29, "Avg Sale", heading_xf)
1284
    sheet.write(0, 30, "Sales History", heading_xf)
1285
 
1286
    sheet_iterator = 1
1287
    cheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.BUY_BOX).all()
1288
    for cheapestItem in cheapestItems:
1289
        amScraping =  cheapestItem[0]
1290
        item = cheapestItem[1]
1291
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1292
        if amScraping.warehouseLocation == 1:
1293
            sku = 'FBA'+str(amScraping.item_id)
1294
            loc = 'MUMBAI'
1295
        else:
1296
            sku = 'FBB'+str(amScraping.item_id)
1297
            loc = 'BANGLORE'
1298
        sheet.write(sheet_iterator, 1, sku)
1299
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1300
        sheet.write(sheet_iterator, 3, loc)
1301
        sheet.write(sheet_iterator, 4, item.brand)
1302
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1303
        sheet.write(sheet_iterator, 6, item.weight)
1304
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1305
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1306
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1307
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1308
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1309
        if amScraping.ourRank > 3:
1310
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1311
        else:
1312
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1313
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1314
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1315
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1316
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1317
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1318
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1319
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1320
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1321
        sheet.write(sheet_iterator, 21, amScraping.commission)
1322
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1323
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1324
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1325
        sheet.write(sheet_iterator, 25, item.risky)
1326
        sheet.write(sheet_iterator, 26, amScraping.proposedSp)
1327
        sheet.write(sheet_iterator, 27, amScraping.proposedTp)
1328
        sheet.write(sheet_iterator, 28, amScraping.marginIncreasedPotential)
1329
        sheet.write(sheet_iterator, 29, amScraping.avgSale)
1330
        sheet.write(sheet_iterator, 30, getOosString(saleMap.get(sku)))
1331
        sheet_iterator+=1
1332
 
1333
    sheet = wbk.add_sheet('Negative Margin')
1334
    xstr = lambda s: s or ""
1335
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1336
 
1337
    excel_integer_format = '0'
1338
    integer_style = xlwt.XFStyle()
1339
    integer_style.num_format_str = excel_integer_format
1340
 
1341
    sheet.write(0, 0, "Item Id", heading_xf)
1342
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1343
    sheet.write(0, 2, "Asin", heading_xf)
1344
    sheet.write(0, 3, "Location", heading_xf)
1345
    sheet.write(0, 4, "Brand", heading_xf)
1346
    sheet.write(0, 5, "Product Name", heading_xf)
1347
    sheet.write(0, 6, "Weight", heading_xf)
1348
    sheet.write(0, 7, "Courier Cost", heading_xf)
1349
    sheet.write(0, 8, "Our SP", heading_xf)
1350
    sheet.write(0, 9, "Our Tp", heading_xf)
1351
    sheet.write(0, 10, "Lowest Possible SP", heading_xf)
1352
    sheet.write(0, 11, "Lowest Possible TP", heading_xf)
1353
    sheet.write(0, 12, "Rank", heading_xf)
1354
    sheet.write(0, 13, "Our Inventory", heading_xf)
1355
    sheet.write(0, 14, "Lowest Seller Name", heading_xf)
1356
    sheet.write(0, 15, "Lowest Seller SP", heading_xf)
1357
    sheet.write(0, 16, "Second Lowest Seller Name", heading_xf)
1358
    sheet.write(0, 17, "Second Lowest Seller SP", heading_xf)
1359
    sheet.write(0, 18, "Third Lowest Seller Name", heading_xf)
1360
    sheet.write(0, 19, "Third Lowest Seller SP", heading_xf)
1361
    sheet.write(0, 20, "WANLC", heading_xf)
1362
    sheet.write(0, 21, "Commission", heading_xf)
1363
    sheet.write(0, 22, "Competitor Commission", heading_xf)
1364
    sheet.write(0, 23, "Return Provision", heading_xf)
1365
    sheet.write(0, 24, "Margin", heading_xf)
1366
    sheet.write(0, 25, "Avg Sale", heading_xf)
1367
    sheet.write(0, 26, "Sales History", heading_xf)
1368
 
1369
    sheet_iterator = 1
1370
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1371
    for amongCheapestItem in amongCheapestItems:
1372
        amScraping =  amongCheapestItem[0]
1373
        item = amongCheapestItem[1]
1374
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1375
        if amScraping.warehouseLocation == 1:
1376
            sku = 'FBA'+str(amScraping.item_id)
1377
            loc = 'MUMBAI'
1378
        else:
1379
            sku = 'FBB'+str(amScraping.item_id)
1380
            loc = 'BANGLORE'
1381
        sheet.write(sheet_iterator, 1, sku)
1382
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1383
        sheet.write(sheet_iterator, 3, loc)
1384
        sheet.write(sheet_iterator, 4, item.brand)
1385
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1386
        sheet.write(sheet_iterator, 6, item.weight)
1387
        sheet.write(sheet_iterator, 7, amScraping.courierCost)
1388
        sheet.write(sheet_iterator, 8, amScraping.ourSellingPrice)
1389
        sheet.write(sheet_iterator, 9, amScraping.ourTp)
1390
        sheet.write(sheet_iterator, 10, amScraping.lowestPossibleSp)
1391
        sheet.write(sheet_iterator, 11, amScraping.lowestPossibleTp)
1392
        if amScraping.ourRank > 3:
1393
            sheet.write(sheet_iterator, 12, 'Greater than 3')
1394
        else:
1395
            sheet.write(sheet_iterator, 12, amScraping.ourRank)
1396
        sheet.write(sheet_iterator, 13, amScraping.ourInventory)
1397
        sheet.write(sheet_iterator, 14, amScraping.lowestSellerName)
1398
        sheet.write(sheet_iterator, 15, amScraping.lowestSellerSp)
1399
        sheet.write(sheet_iterator, 16, amScraping.secondLowestSellerName)
1400
        sheet.write(sheet_iterator, 17, amScraping.secondLowestSellerSp)
1401
        sheet.write(sheet_iterator, 18, amScraping.thirdLowestSellerName)
1402
        sheet.write(sheet_iterator, 19, amScraping.thirdLowestSellerSp)
1403
        sheet.write(sheet_iterator, 20, amScraping.wanlc)
1404
        sheet.write(sheet_iterator, 21, amScraping.commission)
1405
        sheet.write(sheet_iterator, 22, amScraping.competitorCommission)
1406
        sheet.write(sheet_iterator, 23, amScraping.returnProvision)
1407
        sheet.write(sheet_iterator, 24, round(amScraping.ourTp - amScraping.lowestPossibleTp))
1408
        sheet.write(sheet_iterator, 25, amScraping.avgSale)
1409
        sheet.write(sheet_iterator, 26, getOosString(saleMap.get(sku)))
1410
        sheet_iterator+=1
1411
 
1412
    sheet = wbk.add_sheet('Exception List')
1413
    xstr = lambda s: s or ""
1414
    heading_xf = xlwt.easyxf('font: bold on; align: wrap off, vert centre, horiz center')
1415
 
1416
    excel_integer_format = '0'
1417
    integer_style = xlwt.XFStyle()
1418
    integer_style.num_format_str = excel_integer_format
1419
 
1420
    sheet.write(0, 0, "Item Id", heading_xf)
1421
    sheet.write(0, 1, "Amazon Sku", heading_xf)
1422
    sheet.write(0, 2, "Asin", heading_xf)
1423
    sheet.write(0, 3, "Location", heading_xf)
1424
    sheet.write(0, 4, "Brand", heading_xf)
1425
    sheet.write(0, 5, "Product Name", heading_xf)
1426
    sheet.write(0, 6, "Reason", heading_xf)
1427
 
1428
    sheet_iterator = 1
1429
    amongCheapestItems = session.query(AmazonScrapingHistory,Item).join((Item,AmazonScrapingHistory.item_id==Item.id)).filter(AmazonScrapingHistory.competitiveCategory==CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE).all()
1430
    for amongCheapestItem in amongCheapestItems:
1431
        amScraping =  amongCheapestItem[0]
1432
        item = amongCheapestItem[1]
1433
        sheet.write(sheet_iterator, 0, amScraping.item_id)
1434
        if amScraping.warehouseLocation == 1:
1435
            sku = 'FBA'+str(amScraping.item_id)
1436
            loc = 'MUMBAI'
1437
        else:
1438
            sku = 'FBB'+str(amScraping.item_id)
1439
            loc = 'BANGLORE'
1440
        sheet.write(sheet_iterator, 1, sku)
1441
        sheet.write(sheet_iterator, 2, (amazonAsinPrice.get(sku).asin))
1442
        sheet.write(sheet_iterator, 3, loc)
1443
        sheet.write(sheet_iterator, 4, item.brand)
1444
        sheet.write(sheet_iterator, 5, xstr(item.brand)+" "+xstr(item.model_name)+" "+xstr(item.model_number)+" "+xstr(item.color))
1445
        sheet.write(sheet_iterator, 6, amScraping.reason)
1446
        sheet_iterator+=1      
1447
 
1448
    filename = "/tmp/amazon-scraping.xls"
1449
    wbk.save(filename)
1450
 
12363 kshitij.so 1451
def main():
1452
    parser = optparse.OptionParser()
1453
    parser.add_option("-t", "--type", dest="runType",
1454
                   default="FULL", type="string",
1455
                   help="Run type FULL or FAVOURITE")
1456
    (options, args) = parser.parse_args()
1457
    if options.runType not in ('FULL','FAVOURITE'):
1458
        print "Run type argument illegal."
1459
        sys.exit(1)
1460
    time.sleep(5)
1461
    timestamp = datetime.now()
1462
    syncAsin()
1463
    fetchFbaSale()
1464
    itemInfo = populateStuff(timestamp,options.runType)
1465
    itemsToPopulate = 0
12370 kshitij.so 1466
    print len(itemInfo)
12363 kshitij.so 1467
    while (len(itemInfo)>0):
12399 kshitij.so 1468
        if len(itemInfo) > 50:
1469
            itemsToPopulate = 50
12363 kshitij.so 1470
        else:
1471
            itemsToPopulate = len(itemInfo)
12370 kshitij.so 1472
        print itemsToPopulate
12363 kshitij.so 1473
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate])
1474
        itemInfo[0:itemsToPopulate] = []
1475
        commitExceptionList(exceptionList,timestamp,options.runType)
1476
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
1477
        commitCheapest(cheapest,timestamp,options.runType)
1478
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
1479
        commitCanCompete(canCompete,timestamp,options.runType)
1480
        commitAlmostCompete(almostCompete,timestamp,options.runType)
1481
        commitCantCompete(cantCompete, timestamp,options.runType)
12396 kshitij.so 1482
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[]
1483
    autoDecreaseItems = fetchItemsForAutoDecrease(timestamp)
1484
    autoIncreaseItems = fetchItemsForAutoIncrease(timestamp)
1485
    previousAutoFav, nowAutoFav = markAutoFavourites(timestamp)
1486
    writeReport(timestamp,autoDecreaseItems,autoIncreaseItems,previousAutoFav,nowAutoFav)
12363 kshitij.so 1487
if __name__=='__main__':
1488
    main()