Subversion Repositories SmartDukaan

Rev

Rev 12377 | Rev 12379 | 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 = []
39
saleMap = {}
40
DataService.initialize(db_hostname=host)
41
 
42
amScraper = AmazonAsyncScraper.AmazonAsyncScraper()
43
 
44
class __AmazonAsinPrice:
45
    def __init__(self, asin, price):
46
        self.asin = asin
47
        self.price = price
48
 
49
class __AmazonItemInfo:
50
 
51
    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):
52
        self.supc = asin
53
        self.nlc = nlc
54
        self.courierCost = courierCost
55
        self.sku = sku
56
        self.product_group = product_group
57
        self.brand = brand
58
        self.model_name = model_name
59
        self.model_number = model_number
60
        self.color = color
61
        self.weight = weight
62
        self.parent_category = parent_category
63
        self.risky = risky
64
        self.vatRate = vatRate
65
        self.runType = runType
66
        self.parent_category_name = parent_category_name
67
        self.sourcePercentage = sourcePercentage
68
        self.ourInventory = ourInventory
69
        self.state_id = state_id
70
 
71
class __AmazonDetails:
72
    def __init__(self, sku, ourSp, ourRank, lowestSellerName,lowestSellerSp,secondLowestSellerName, secondLowestSellerSp, thirdLowestSellerName, thirdLowestSellerSp, totalSeller, multipleListings):
73
        self.sku =sku
74
        self.ourSp = ourSp
75
        self.ourRank = ourRank
76
        self.lowestSellerName = lowestSellerName
77
        self.lowestSellerSp = lowestSellerSp
78
        self.secondLowestSellerName = secondLowestSellerName
79
        self.secondLowestSellerSp = secondLowestSellerSp
80
        self.thirdLowestSellerName = thirdLowestSellerName
81
        self.thirdLowestSellerSp = thirdLowestSellerSp
82
        self.totalSeller = totalSeller
83
        self.multipleListings = multipleListings 
84
 
85
class __AmazonPricing:
86
 
87
    def __init__(self, ourSp, ourTp, lowestPossibleTp, lowestPossibleSp):
88
        self.ourTp = ourTp
89
        self.lowestPossibleTp = lowestPossibleTp
90
        self.ourSp = ourSp
91
        self.lowestPossibleSp = lowestPossibleSp
92
 
93
 
94
def syncAsin():
95
    notListedOnAmazon = []
96
    diffAsins = []
12372 kshitij.so 97
#    login_url = "https://sellercentral.amazon.in/gp/homepage.html"
98
#    br = SellerCentralInventoryReport.login(login_url)
99
#    report_url = "https://sellercentral.amazon.in/gp/upload-download-utils/requestReport.html?type=OpenListingReport&marketplaceID=44571&Request+Report="
100
#    br = SellerCentralInventoryReport.requestReport(br,report_url)
101
#    status_url="https://sellercentral.amazon.in/gp/upload-download-utils/reportStatusData.html"
102
#    br, page = SellerCentralInventoryReport.checkStatus(br,status_url)
103
#    br, batchId = SellerCentralInventoryReport.getReportBatchId(br,page)
104
#    print "*********************************"
105
#    print "Batch Id for request is ",batchId
106
#    print "*********************************"
107
#    ready = False
108
#    retryCount = 0
109
#    while not ready:
110
#        if retryCount == 10:
111
#            print "File not available for download after multiple retries"
112
#            sys.exit(1)
113
#        br, download_link = SellerCentralInventoryReport.downloadReport(br,batchId,status_url)
114
#        if download_link is not None:
115
#            ready= True
116
#            continue
117
#        print "File not ready for download yet.Will try again after 30 seconds."
118
#        retryCount+=1
119
#        time.sleep(30)
120
#    fPath = SellerCentralInventoryReport.fetchFile(download_link['href'],br,batchId)
121
    fPath = '/tmp/9921129430.txt'
12363 kshitij.so 122
    global amazonAsinPrice
123
    for line in open(fPath):
124
        l = line.split('\t')
125
        if (str(l[0]).startswith('FBA') or str(l[0]).startswith('FBB')):
126
            obj = __AmazonAsinPrice(l[1],l[2])
127
            amazonAsinPrice[l[0]] = obj
128
#    systemAsins = session.query(Item,Amazonlisted).join((Amazonlisted,Item.id==Amazonlisted.itemId)).all()
129
#    for systemAsin in systemAsins:
130
#        item = systemAsin[0]
131
#        amListed = systemAsin[1]
132
#        if amazonAsinPrice.get('FBA'+str(item.id)) is None:
133
#            temp=[]
134
#            temp.append(item)
135
#            temp.append(amListed)
136
#            notListedOnAmazon.append(temp)
137
#            continue
138
#        else:
139
#            temp=[]
140
#            temp.append(item)
141
#            temp.append(amListed)
142
#            if item.asin!=((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip():
143
#                diffAsins.append(temp)
144
#                continue
145
#            
146
#    for diffAsin in diffAsins:
147
#        item = diffAsin[0]
148
#        amListed = diffAsin[1]
149
#        item.asin = ((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip()
150
#        amListed.asin = ((amazonAsinPrice.get('FBA'+str(item.id))).asin).strip()
151
#    session.commit()
152
#    session.close()
153
 
154
def fetchFbaSale():
155
    global saleMap
156
    transaction_client = TransactionClient().get_client()
157
    fbaSaleSnapshot = transaction_client.getAmazonFbaSalesSnapshotForDays(4)
158
    for saleSnapshot in fbaSaleSnapshot:
159
        if saleSnapshot.fcLocation == 0:
160
            if saleMap.has_key('FBA'+str(saleSnapshot.item_id)):
161
                temp = []
12367 kshitij.so 162
                val = saleMap.get('FBA'+str(saleSnapshot.item_id))
163
                for l in val:
12363 kshitij.so 164
                    temp.append(l)
165
                temp.append(saleSnapshot)
12366 kshitij.so 166
                saleMap['FBA'+str(saleSnapshot.item_id)]=temp
12363 kshitij.so 167
            else:
12368 kshitij.so 168
                temp = []
169
                temp.append(saleSnapshot)
170
                saleMap['FBA'+str(saleSnapshot.item_id)] = temp
12363 kshitij.so 171
        else:
172
            if saleMap.has_key('FBB'+str(saleSnapshot.item_id)):
173
                temp = []
12367 kshitij.so 174
                val = saleMap.get('FBB'+str(saleSnapshot.item_id))
175
                for l in val:
12363 kshitij.so 176
                    temp.append(l)
12368 kshitij.so 177
                saleMap['FBB'+str(saleSnapshot.item_id)]=temp
12363 kshitij.so 178
                temp.append(saleSnapshot)
179
            else:
12368 kshitij.so 180
                temp = []
181
                temp.append(saleSnapshot)
182
                saleMap['FBB'+str(saleSnapshot.item_id)] = temp
12363 kshitij.so 183
 
184
def calculateAverageSale(sku):
185
    count,sale = 0,0
186
    oosStatus = saleMap.get(sku)
187
    for obj in oosStatus:
188
        if not obj.is_oos:
189
            count+=1
190
            sale = sale+obj.num_orders
191
    avgSalePerDay=0 if count==0 else (float(sale)/count)
192
    return round(avgSalePerDay,2)
193
 
194
def computeCourierCost(weight):
12378 kshitij.so 195
    try:
196
        cCost = 10.0;
197
        slabs = int((weight*1000)/500-.001)
198
        for slab in range(0,slabs):
199
            cCost = cCost + 10.0;
200
        return cCost;
201
    except:
202
        return 10.0
12363 kshitij.so 203
 
204
 
205
def populateStuff(time,runType):
206
    global amazonLongTermActivePromotions
207
    itemInfo = []
208
    inventory_client = InventoryClient().get_client()
209
    fbaAvailableInventorySnapshot = inventory_client.getAllAvailableAmazonFbaItemInventory()
210
    for fbaInventoryItem in fbaAvailableInventorySnapshot:
211
        d_amazon_listed = Amazonlisted.get_by(itemId=fbaInventoryItem.item_id)
212
        if d_amazon_listed is None:
213
            continue
214
        if d_amazon_listed.overrrideWanlc:
215
            wanlc = d_amazon_listed.exceptionalWanlc
216
        else:
217
            wanlc = inventory_client.getWanNlcForSource(fbaInventoryItem.item_id,OrderSource.AMAZON)
218
        it = Item.query.filter_by(id=fbaInventoryItem.item_id).one()
219
        category = Category.query.filter_by(id=it.category).one()
220
        parent_category = Category.query.filter_by(id=category.parent_category_id).first()
221
        scp = SourceCategoryPercentage.query.filter(SourceCategoryPercentage.category_id==it.category).filter(SourceCategoryPercentage.source==OrderSource.AMAZON).filter(SourceCategoryPercentage.startDate<=time).filter(SourceCategoryPercentage.expiryDate>=time).first()
222
        if scp is not None:
223
            sourcePercentage = scp
224
        else:
225
            spm = SourcePercentageMaster.get_by(source=OrderSource.AMAZON)
226
            sourcePercentage = spm
12375 kshitij.so 227
        print "$$$$$$$$$$$$$$$$$"
228
        print fbaInventoryItem
229
        if fbaInventoryItem.location==0:
12377 kshitij.so 230
            sku = 'FBA'+str(fbaInventoryItem.item_id)
12363 kshitij.so 231
            state_id = 1
12375 kshitij.so 232
        elif fbaInventoryItem.location==1:
12377 kshitij.so 233
            sku = 'FBB'+str(fbaInventoryItem.item_id)
12363 kshitij.so 234
            state_id = 2
235
        else:
12371 kshitij.so 236
            print "continue*****"
12363 kshitij.so 237
            continue
238
        cc = computeCourierCost(it.weight)
239
        if amazonAsinPrice.get(sku) is None:
240
            asin = None
12371 kshitij.so 241
            print "no asin****"
12363 kshitij.so 242
        amazonItemInfo = __AmazonItemInfo(amazonAsinPrice.get(sku).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 243
        print amazonItemInfo
12363 kshitij.so 244
        itemInfo.append(amazonItemInfo)
245
    amPromotions = AmazonPromotion.query.filter(AmazonPromotion.startDate<=time).filter(AmazonPromotion.endDate>=time).filter(AmazonPromotion.promotionType==AmazonPromotionType.LONGTERM).filter(AmazonPromotion.promotionActive==True) \
246
    .group_by(AmazonPromotion.sku).order_by(desc(AmazonPromotion.addedOn)).all()
247
    for amPromotion in amPromotions:
248
        amazonLongTermActivePromotions.append(amPromotion.sku)
249
    session.close()
250
    return itemInfo
251
 
252
def decideCategory(itemInfo):
253
    exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = [],[],[],[],[],[],[] 
254
    skuUrls = []
255
    #skuAsinMap = {}
256
    for item in itemInfo:
257
        if item.asin is None:
258
            temp = []
259
            temp.append(item)
260
            temp.append("Asin not available")
261
            exceptionList.append(temp)
262
            continue
263
        skuUrls.append('http://www.amazon.in/gp/offer-listing/'+item.asin+'/ref=olp_sort_ps')
264
    aggResponse = amScraper.read(skuUrls, True)
265
#    for asin, scrapInfo in aggResponse:
266
#        skuList = skuAsinMap.get(asin)
267
#        for sku in skuList:
268
#            amDetails = __AmazonDetails(None, None, None, None, None,secondLowestSellerName, secondLowestSellerSp, thirdLowestSellerName, thirdLowestSellerSp)
269
#            for info in scrapInfo:
270
    catalog_client = CatalogClient().get_client()
271
    for val in itemInfo:
272
        if val.asin is None:
273
            continue
274
        scrapInfo = aggResponse.get(val.asin)
275
        if val.sku in amazonLongTermActivePromotions:
276
            print "Sku in promotion, will handle it later.Moving to other..."
277
            continue
278
        if scrapInfo is None or val.nlc==0:
279
            temp = []
280
            temp.append(val)
281
            if val.nlc==0 or val.nlc is None:
282
                temp.append("WANLC is 0")
283
            else:
284
                temp.append("Not able to fetch")
285
            exceptionList.append(temp)
286
            continue
287
        iterator = 0
288
        sku, lowestSellerName,secondLowestSellerName, thirdLowestSellerName = ('',)*4
289
        ourSp, ourRank, lowestSellerSp, secondLowestSellerSp, thirdLowestSellerSp, ourTp, lowestPossibleSp, lowestPossibleTp = (0,)*8
290
        sku = val.sku
291
        scrapedSkuLocation = None
292
        multipleListings = False
293
        for info in scrapInfo:
294
            if (info.sellerName).strip()=='Saholic':
295
                if ourRank>0:
296
                    multipleListings = True
297
                ourSp = info.sellerPrice
298
                ourRank = iterator+1
299
                if val.state_id==1:
300
                    #It means sku starts with FBA
301
                    fbaPrice = (amazonAsinPrice.get(val.sku)).price
302
                    try:
303
                        if ourSp==fbaPrice:
304
                            scrapedSkuLocation = val.state_id
305
                    except:
306
                        scrapedSkuLocation = None
307
                elif val.state_id==2:
308
                    #It means sku starts with FBB
309
                    fbbPrice = (amazonAsinPrice.get(val.sku)).price
310
                    try:
311
                        if ourSp==fbbPrice:
312
                            scrapedSkuLocation = val.state_id
313
                    except:
314
                        scrapedSkuLocation = None
315
                else:
316
                    scrapedSkuLocation = None
317
                if scrapedSkuLocation is None:
318
                    print "fishy...confused for ", val.sku
319
 
320
            if iterator == 0:
321
                lowestSellerName = info.sellerName
322
                lowestSellerSp = info.sellerPrice
323
 
324
            if iterator == 1:
325
                secondLowestSellerName = info.sellerName
326
                secondLowestSellerSp = info.sellerPrice
327
 
328
            if iterator == 2:
329
                thirdLowestSellerName = info.sellerName
330
                thirdLowestSellerSp = info.sellerPrice
331
 
332
            iterator += 1
333
 
334
        #if cheapestSkuLocation!=val.state_id
335
 
336
        if ourSp==0 or scrapedSkuLocation is None:
337
            print "Sku not present in top 3.Getting price from amazonAsinPrice...or multiple listings"
338
            if ourSp==0:
339
                ourRank = 999 #Due to pagination and large no of sellers.Taking it as dummy value, means we are not in top 3
340
                ourSp = (amazonAsinPrice.get(val.sku)).price
341
                if ourSp is None or ourSp==0:
342
                    temp = []
343
                    temp.append(val)
344
                    temp.append("Price not available")
345
                    exceptionList.append(temp)
346
                    continue
347
            else:
348
                #determine rank
349
                if ourSp <= lowestSellerSp or lowestSellerSp==0:
350
                    ourRank = 1
351
                elif ourSp > lowestSellerSp and (ourSp <= secondLowestSellerSp or secondLowestSellerSp==0):
352
                    ourRank = 2
353
                elif ourSp > secondLowestSellerSp and (ourSp<=thirdLowestSellerSp or thirdLowestSellerSp==0):
354
                    ourRank = 3
355
                else:
356
                    ourRank = 999
357
 
358
        if multipleListings:
359
            print "multiple listings..."
360
            ourSp = (amazonAsinPrice.get(val.sku)).price
361
            if ourSp is None or ourSp==0:
362
                temp = []
363
                temp.append(val)
364
                temp.append("Price not available")
365
                exceptionList.append(temp)
366
                continue
367
            if ourSp <= lowestSellerSp:
368
                    ourRank = 1
369
            elif ourSp > lowestSellerSp and (ourSp <= secondLowestSellerSp or secondLowestSellerSp==0):
370
                ourRank = 2
371
            elif ourSp > secondLowestSellerSp and (ourSp<=thirdLowestSellerSp or thirdLowestSellerSp==0):
372
                ourRank = 3
373
            else:
374
                ourRank = 999
375
 
376
 
377
        amDetails = __AmazonDetails(sku, ourSp, ourRank, lowestSellerName,lowestSellerSp,secondLowestSellerName, secondLowestSellerSp, thirdLowestSellerName, thirdLowestSellerSp,len(scrapInfo),multipleListings)
378
        try:
379
            val.vatRate = catalog_client.getVatPercentageForItem(int(val.sku[3:]), val.state_id, amDetails.ourSp)
380
        except:
381
            temp = []
382
            temp.append(val)
383
            temp.append("Vat not available")
384
            exceptionList.append(temp)
385
            continue
386
 
387
        ourTp = getOurTp(amDetails,val,val.sourcePercentage)
388
        lowestPossibleTp = getLowestPossibleTp(amDetails,val,val.sourcePercentage)
389
        lowestPossibleSp = getLowestPossibleSp(amDetails,val,val.sourcePercentage)
390
        amPricing = __AmazonPricing(ourSp,ourTp,lowestPossibleTp,lowestPossibleSp)
391
 
392
        if amPricing.ourTp < amPricing.lowestPossibleTp:
393
            temp = []
394
            temp.append(val)
395
            temp.append(amDetails)
396
            temp.append(amPricing)
397
            negativeMargin.append(temp)
398
            continue
399
 
400
        if amDetails.ourRank==1:
401
            temp = []
402
            temp.append(val)
403
            temp.append(amDetails)
404
            temp.append(amPricing)
405
            cheapest.append(temp)
406
            continue
407
 
408
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp) and ((((float(amDetails.ourSp - amDetails.lowestSellerSp))/amDetails.ourSp)<=.01) or ((amDetails.ourSp - amDetails.lowestSellerSp)<=25)):
409
            temp = []
410
            temp.append(val)
411
            temp.append(amDetails)
412
            temp.append(amPricing)
413
            amongCheapestAndCanCompete.append(temp)
414
            continue
415
 
416
        if (amDetails.lowestSellerSp > amPricing.lowestPossibleSp):
417
            temp = []
418
            temp.append(val)
419
            temp.append(amDetails)
420
            temp.append(amPricing)
421
            canCompete.append(temp)
422
            continue
423
 
424
        temp = []
425
        temp.append(val)
426
        temp.append(amDetails)
427
        temp.append(amPricing)
428
        cantCompete.append(temp)
429
 
430
    itemInfo[:]=[]
431
    scrapInfo[:]=[]
432
    return exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete
433
 
434
def getOurTp(amazonDetails,val,spm):
435
    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));
436
    return round(ourTp,2)
437
 
438
def getLowestPossibleTp(amazonDetails,val,spm):
439
    vat = (amazonDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100)
440
    inHouseCost = 15+vat+(spm.returnProvision/100)*amazonDetails.ourSp
441
    lowest_possible_tp = val.nlc+inHouseCost
442
    return round(lowest_possible_tp,2)
443
 
444
def getLowestPossibleSp(amazonDetails,val,spm):
445
    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));
446
    return round(lowestPossibleSp,2)
447
 
448
def getTargetTp(targetSp,spm,val):
449
    targetTp = targetSp- targetSp*(spm.commission/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost)*(1+(val.serviceTax/100))
450
    return round(targetTp,2)
451
 
452
def commitExceptionList(exceptionList,timestamp,runType):
453
    for exceptionItem in exceptionList:
454
        val = exceptionItem[0]
455
        reason = exceptionItem[1]
456
        amazonScrapingHistory = AmazonScrapingHistory()
457
        amazonScrapingHistory.item_id = val.sku[3:]
458
        amazonScrapingHistory.warehouseLocation = val.state_id
459
        amazonScrapingHistory.reason = reason
460
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
461
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.EXCEPTION
462
        amazonScrapingHistory.timestamp = timestamp
463
    session.commit()
464
 
465
def commitNegativeMargin(negativeMargin,timestamp,runType):
466
    for negativeMarginItem in negativeMargin:
467
        val = negativeMarginItem[0]
468
        amDetails = negativeMarginItem[1]
469
        amPricing = negativeMarginItem[2]
470
        spm = val.sourcePercentage
471
        amazonScrapingHistory = AmazonScrapingHistory()
472
        amazonScrapingHistory.item_id = val.sku[3:]
473
        amazonScrapingHistory.warehouseLocation = val.state_id
474
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
475
        amazonScrapingHistory.ourTp = amPricing.ourTp
476
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
477
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
478
        amazonScrapingHistory.ourRank = amDetails.ourRank
479
        amazonScrapingHistory.ourInventory = val.ourInventory
480
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
481
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
482
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
483
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
484
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
485
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
486
        amazonScrapingHistory.wanlc = val.nlc
487
        amazonScrapingHistory.commission = spm.commission
488
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
489
        amazonScrapingHistory.returnProvision = spm.returnProvision
490
        amazonScrapingHistory.courierCost = val.courierCost
491
        amazonScrapingHistory.risky = val.risky
492
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
493
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
494
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
495
        amazonScrapingHistory.timestamp = timestamp
496
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
497
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
498
    session.commit()
499
 
500
 
501
def commitCheapest(cheapest,timestamp,runType):
502
    for cheapestItem in cheapest:
503
        val = cheapestItem[0]
504
        amDetails = cheapestItem[1]
505
        amPricing = cheapestItem[2]
506
        spm = val.sourcePercentage
507
        amazonScrapingHistory = AmazonScrapingHistory()
508
        amazonScrapingHistory.item_id = val.sku[3:]
509
        amazonScrapingHistory.warehouseLocation = val.state_id
510
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
511
        amazonScrapingHistory.ourTp = amPricing.ourTp
512
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
513
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
514
        amazonScrapingHistory.ourRank = amDetails.ourRank
515
        amazonScrapingHistory.ourInventory = val.ourInventory
516
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
517
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
518
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
519
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
520
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
521
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
522
        amazonScrapingHistory.wanlc = val.nlc
523
        amazonScrapingHistory.commission = spm.commission
524
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
525
        amazonScrapingHistory.returnProvision = spm.returnProvision
526
        amazonScrapingHistory.courierCost = val.courierCost
527
        amazonScrapingHistory.risky = val.risky
528
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
529
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
530
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.BUY_BOX
531
        amazonScrapingHistory.timestamp = timestamp
532
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
533
        if amDetails.secondLowestSellerName!='Saholic':
534
            competitorSp = amDetails.secondLowestSellerSp
535
        else:
536
            competitorSp = amDetails.thirdLowestSellerSp
537
        proposed_sp = max(competitorSp - max((20, competitorSp*0.002)), amPricing.lowestPossibleSp)
538
        proposed_tp = getTargetTp(proposed_sp,spm,val)
539
        amazonScrapingHistory.proposedSp = proposed_sp
540
        amazonScrapingHistory.proposedTp = proposed_tp
541
        amazonScrapingHistory.marginIncreasedPotential = proposed_tp - amPricing.ourTp
542
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
543
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
544
    session.commit()
545
 
546
 
547
 
548
def commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,runType):
549
    for amongCheapestAndCanCompeteItem in amongCheapestAndCanCompete:
550
        val = amongCheapestAndCanCompeteItem[0]
551
        amDetails = amongCheapestAndCanCompeteItem[1]
552
        amPricing = amongCheapestAndCanCompeteItem[2]
553
        spm = val.sourcePercentage
554
        amazonScrapingHistory = AmazonScrapingHistory()
555
        amazonScrapingHistory.item_id = val.sku[3:]
556
        amazonScrapingHistory.warehouseLocation = val.state_id
557
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
558
        amazonScrapingHistory.ourTp = amPricing.ourTp
559
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
560
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
561
        amazonScrapingHistory.ourRank = amDetails.ourRank
562
        amazonScrapingHistory.ourInventory = val.ourInventory
563
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
564
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
565
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
566
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
567
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
568
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
569
        amazonScrapingHistory.wanlc = val.nlc
570
        amazonScrapingHistory.commission = spm.commission
571
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
572
        amazonScrapingHistory.returnProvision = spm.returnProvision
573
        amazonScrapingHistory.courierCost = val.courierCost
574
        amazonScrapingHistory.risky = val.risky
575
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
576
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
577
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.AMONG_CHEAPEST_CAN_COMPETE
578
        amazonScrapingHistory.timestamp = timestamp
579
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
580
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
581
        proposed_tp = getTargetTp(proposed_sp,spm,val)
582
        amazonScrapingHistory.proposedSp = proposed_sp
583
        amazonScrapingHistory.proposedTp = proposed_tp
584
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
585
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
586
    session.commit()
587
 
588
 
589
 
590
def commitCanCompete(canCompete,timestamp,runType):
591
    for canCompeteItem in canCompete:
592
        val = canCompeteItem[0]
593
        amDetails = canCompeteItem[1]
594
        amPricing = canCompeteItem[2]
595
        spm = val.sourcePercentage
596
        amazonScrapingHistory = AmazonScrapingHistory()
597
        amazonScrapingHistory.item_id = val.sku[3:]
598
        amazonScrapingHistory.warehouseLocation = val.state_id
599
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
600
        amazonScrapingHistory.ourTp = amPricing.ourTp
601
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
602
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
603
        amazonScrapingHistory.ourRank = amDetails.ourRank
604
        amazonScrapingHistory.ourInventory = val.ourInventory
605
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
606
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
607
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
608
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
609
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
610
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
611
        amazonScrapingHistory.wanlc = val.nlc
612
        amazonScrapingHistory.commission = spm.commission
613
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
614
        amazonScrapingHistory.returnProvision = spm.returnProvision
615
        amazonScrapingHistory.courierCost = val.courierCost
616
        amazonScrapingHistory.risky = val.risky
617
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
618
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
619
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
620
        amazonScrapingHistory.timestamp = timestamp
621
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
622
        proposed_sp = max(amDetails.lowestSellerSp - max((5, amDetails.lowestSellerSp*0.001)), amPricing.lowestPossibleSp)
623
        proposed_tp = getTargetTp(proposed_sp,spm,val)
624
        amazonScrapingHistory.proposedSp = proposed_sp
625
        amazonScrapingHistory.proposedTp = proposed_tp
626
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
627
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
628
    session.commit()
629
 
630
def commitAlmostCompete(almostCompete,timestamp):
631
    return
632
 
633
def commitCantCompete(cantCompete, timestamp,runType):
634
    for cantCompeteItem in cantCompete:
635
        val = cantCompeteItem[0]
636
        amDetails = cantCompeteItem[1]
637
        amPricing = cantCompeteItem[2]
638
        spm = val.sourcePercentage
639
        amazonScrapingHistory = AmazonScrapingHistory()
640
        amazonScrapingHistory.item_id = val.sku[3:]
641
        amazonScrapingHistory.warehouseLocation = val.state_id
642
        amazonScrapingHistory.ourSellingPrice = amDetails.ourSp
643
        amazonScrapingHistory.ourTp = amPricing.ourTp
644
        amazonScrapingHistory.lowestPossibleTp = amPricing.lowestPossibleTp
645
        amazonScrapingHistory.lowestPossibleSp = amPricing.lowestPossibleSp
646
        amazonScrapingHistory.ourRank = amDetails.ourRank
647
        amazonScrapingHistory.ourInventory = val.ourInventory
648
        amazonScrapingHistory.lowestSellerName = amDetails.lowestSellerName
649
        amazonScrapingHistory.lowestSellerSp = amDetails.lowestSellerSp
650
        amazonScrapingHistory.secondLowestSellerName = amDetails.secondLowestSellerName
651
        amazonScrapingHistory.secondLowestSellerSp = amDetails.secondLowestSellerSp
652
        amazonScrapingHistory.thirdLowestSellerName = amDetails.thirdLowestSellerName
653
        amazonScrapingHistory.thirdLowestSellerSp = amDetails.thirdLowestSellerSp
654
        amazonScrapingHistory.wanlc = val.nlc
655
        amazonScrapingHistory.commission = spm.commission
656
        amazonScrapingHistory.competitorCommission = spm.competitorCommission
657
        amazonScrapingHistory.returnProvision = spm.returnProvision
658
        amazonScrapingHistory.courierCost = val.courierCost
659
        amazonScrapingHistory.risky = val.risky
660
        amazonScrapingHistory.runType = RunType._NAMES_TO_VALUES.get(runType)
661
        amazonScrapingHistory.totalSeller = amDetails.totalSeller
662
        amazonScrapingHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
663
        amazonScrapingHistory.timestamp = timestamp
664
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
665
        proposed_sp = amDetails.lowestSellerSp - max(5, amDetails.lowestSellerSp*0.001)
666
        proposed_tp = getTargetTp(proposed_sp,spm,val)
667
        target_nlc = proposed_tp - amPricing.lowestPossibleTp + val.nlc
668
        amazonScrapingHistory.proposedSp = proposed_sp
669
        amazonScrapingHistory.proposedTp = proposed_tp
670
        amazonScrapingHistory.targetNlc = target_nlc
671
        amazonScrapingHistory.multipleListings = amDetails.multipleListings
672
        amazonScrapingHistory.avgSale = calculateAverageSale(val.sku) #Last five days
673
    session.commit()
674
 
675
def main():
676
    parser = optparse.OptionParser()
677
    parser.add_option("-t", "--type", dest="runType",
678
                   default="FULL", type="string",
679
                   help="Run type FULL or FAVOURITE")
680
    (options, args) = parser.parse_args()
681
    if options.runType not in ('FULL','FAVOURITE'):
682
        print "Run type argument illegal."
683
        sys.exit(1)
684
    time.sleep(5)
685
    timestamp = datetime.now()
686
    syncAsin()
687
    fetchFbaSale()
688
    itemInfo = populateStuff(timestamp,options.runType)
689
    itemsToPopulate = 0
12370 kshitij.so 690
    print len(itemInfo)
12363 kshitij.so 691
    while (len(itemInfo)>0):
692
        if len(itemInfo) > 50:
693
            itemsToPopulate = 50
694
        else:
695
            itemsToPopulate = len(itemInfo)
12370 kshitij.so 696
        print itemsToPopulate
12363 kshitij.so 697
        exceptionList, negativeMargin, cheapest, amongCheapestAndCanCompete, canCompete, almostCompete, cantCompete = decideCategory(itemInfo[0:itemsToPopulate])
698
        itemInfo[0:itemsToPopulate] = []
699
        commitExceptionList(exceptionList,timestamp,options.runType)
700
        commitNegativeMargin(negativeMargin,timestamp,options.runType)
701
        commitCheapest(cheapest,timestamp,options.runType)
702
        commitAmongCheapestAndCanCompete(amongCheapestAndCanCompete,timestamp,options.runType)
703
        commitCanCompete(canCompete,timestamp,options.runType)
704
        commitAlmostCompete(almostCompete,timestamp,options.runType)
705
        commitCantCompete(cantCompete, timestamp,options.runType)
706
        exceptionList[:], negativeMargin[:], cheapest[:], amongCheapestAndCanCompete[:], canCompete[:], almostCompete[:], cantCompete[:] =[],[],[],[],[],[],[] 
707
 
708
if __name__=='__main__':
709
    main()