Subversion Repositories SmartDukaan

Rev

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