Subversion Repositories SmartDukaan

Rev

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