Subversion Repositories SmartDukaan

Rev

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