Subversion Repositories SmartDukaan

Rev

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