Subversion Repositories SmartDukaan

Rev

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