Subversion Repositories SmartDukaan

Rev

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