Subversion Repositories SmartDukaan

Rev

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