Subversion Repositories SmartDukaan

Rev

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

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