Subversion Repositories SmartDukaan

Rev

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