Subversion Repositories SmartDukaan

Rev

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