Subversion Repositories SmartDukaan

Rev

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