Subversion Repositories SmartDukaan

Rev

Rev 12378 | Rev 12380 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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