Subversion Repositories SmartDukaan

Rev

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