Subversion Repositories SmartDukaan

Rev

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