Subversion Repositories SmartDukaan

Rev

Rev 12419 | Rev 12421 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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