Subversion Repositories SmartDukaan

Rev

Rev 9912 | Rev 9914 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
9881 kshitij.so 1
from elixir import *
2
from shop2020.config.client.ConfigClient import ConfigClient
3
from shop2020.model.v1.catalog.impl import DataService
4
from shop2020.model.v1.catalog.impl.DataService import SnapdealItem, MarketplaceItems, Item, \
5
Category, SourcePercentageMaster, MarketPlaceHistory
6
from shop2020.thriftpy.model.v1.order.ttypes import OrderSource
9897 kshitij.so 7
from shop2020.thriftpy.model.v1.catalog.ttypes import CompetitionCategory, CompetitionBasis, SalesPotential,\
8
Decision
9881 kshitij.so 9
from shop2020.clients.CatalogClient import CatalogClient
10
from shop2020.clients.InventoryClient import InventoryClient
11
import urllib2
12
import time
13
from datetime import date, datetime
14
import simplejson as json
15
import sys
16
 
17
config_client = ConfigClient()
18
host = config_client.get_property('staging_hostname')
19
DataService.initialize(db_hostname=host)
9897 kshitij.so 20
import logging
21
lgr = logging.getLogger()
22
lgr.setLevel(logging.DEBUG)
23
fh = logging.FileHandler('snapdeal-history.log')
24
fh.setLevel(logging.INFO)
25
frmt = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
26
fh.setFormatter(frmt)
27
lgr.addHandler(fh)
9881 kshitij.so 28
 
29
class __Exception:
30
    SERVER_SIDE=1
31
 
32
 
33
class __SnapdealDetails:
34
    def __init__(self, ourSp, ourInventory, otherInventory, rank, lowestSellerName, lowestSellerCode,lowestSp,secondLowestSellerName, secondLowestSellerCode,secondLowestSellerSp,secondLowestSellerInventory,lowestOfferPrice,secondLowestSellerOfferPrice,ourOfferPrice, totalSeller):
35
        self.ourSp = ourSp
36
        self.ourOfferPrice = ourOfferPrice
37
        self.ourInventory = ourInventory
38
        self.otherInventory = otherInventory
39
        self.rank = rank
40
        self.lowestSellerName = lowestSellerName
41
        self.lowestSellerCode = lowestSellerCode 
42
        self.lowestSp = lowestSp
43
        self.lowestOfferPrice = lowestOfferPrice
44
        self.secondLowestSellerName = secondLowestSellerName
45
        self.secondLowestSellerCode = secondLowestSellerCode
46
        self.secondLowestSellerSp = secondLowestSellerSp
47
        self.secondLowestSellerOfferPrice = secondLowestSellerOfferPrice
48
        self.secondLowestSellerInventory = secondLowestSellerInventory
49
        self.totalSeller = totalSeller
50
 
51
class __SnapdealItemInfo:
52
 
53
    def __init__(self, supc, nlc, courierCost, item_id, product_group, brand, model_name, model_number, color, weight, parent_category, risky, warehouseId, vatRate):
54
        self.supc = supc
55
        self.nlc = nlc
56
        self.courierCost = courierCost
57
        self.item_id = item_id
58
        self.product_group = product_group
59
        self.brand = brand
60
        self.model_name = model_name
61
        self.model_number = model_number
62
        self.color = color
63
        self.weight = weight
64
        self.parent_category = parent_category
65
        self.risky = risky
66
        self.warehouseId = warehouseId
67
        self.vatRate = vatRate
68
 
69
class __SnapdealPricing:
70
 
71
    def __init__(self, ourSp, ourTp, lowestTp, lowestPossibleTp, competitionBasis, secondLowestSellerTp, lowestPossibleSp):
72
        self.ourTp = ourTp
73
        self.lowestTp = lowestTp
74
        self.lowestPossibleTp = lowestPossibleTp
75
        self.competitionBasis = competitionBasis
76
        self.ourSp = ourSp
77
        self.secondLowestSellerTp = secondLowestSellerTp
78
        self.lowestPossibleSp = lowestPossibleSp
79
 
9897 kshitij.so 80
def fetchItemsForAutoDecrease(time):
9911 kshitij.so 81
    autoDecrementItems = MarketplaceItems.query.filter(MarketplaceItems.autoDecrement==True).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
9897 kshitij.so 82
    inventory_client = InventoryClient().get_client()
83
    inventoryMap = inventory_client.getInventorySnapshot(0)
84
    for autoDecrementItem in autoDecrementItems:
85
        mpHistory = MarketPlaceHistory.get_by(source=OrderSource.SNAPDEAL,item_id=autoDecrementItem.itemId,timestamp=time)
86
        if not mpHistory.risky:
87
            markReasonForMpItem(mpHistory,'Item is not risky',Decision.AUTO_DECREMENT_FAILED)
88
            continue
89
        if mpHistory.proposedSellingPrice >= mpHistory.ourSellingPrice:
90
            markReasonForMpItem(mpHistory,'Proposed SP greater than current SP',Decision.AUTO_DECREMENT_FAILED)
91
            continue
92
        if not mpHistory.competitiveCategory == CompetitionCategory.COMPETITIVE:
93
            markReasonForMpItem(mpHistory,'Category is '+CompetitionCategory._VALUES_TO_NAMES.get(mpHistory.competitiveCategory),Decision.AUTO_DECREMENT_FAILED)
94
            continue
95
        if mpHistory.otherInventory < 3:
96
            markReasonForMpItem(mpHistory,'Competition stock is not enough',Decision.AUTO_DECREMENT_FAILED)
97
            continue
98
        oosStatus = inventory_client.getOosStatusesForXDaysForItem(autoDecrementItem.itemId,0,3)
99
        count,sale,daysOfStock = 0,0,0
100
        for obj in oosStatus:
101
            if not obj.is_oos:
102
                count+=1
103
                sale = sale+obj.num_orders
104
        avgSalePerDay=0 if count==0 else (float(sale)/count)
105
        totalAvailability, totalReserved = 0,0
9913 kshitij.so 106
        if (not inventoryMap.has_key(autoDecrementItem.itemId)):
107
            markReasonForMpItem(mpHistory,'Average sale per day is zero',Decision.AUTO_DECREMENT_FAILED)
108
            continue
9897 kshitij.so 109
        itemInventory=inventoryMap[autoDecrementItem.itemId]
110
        availableMap  = itemInventory.availability
111
        reserveMap = itemInventory.reserved
112
        for warehouse,availability in availableMap.iteritems():
113
            if warehouse==16:
114
                continue
115
            totalAvailability = totalAvailability+availability
116
        for warehouse,reserve in reserveMap.iteritems():
117
            if warehouse==16:
118
                continue
119
            totalReserved = totalReserved+reserve
120
        if (totalAvailability-totalReserved)<=0:
121
            markReasonForMpItem(mpHistory,'Our stock is not enough',Decision.AUTO_DECREMENT_FAILED)
122
            continue
9912 kshitij.so 123
        if (avgSalePerDay==0):
124
            markReasonForMpItem(mpHistory,'Average sale per day is zero',Decision.AUTO_DECREMENT_FAILED)
125
            continue
9897 kshitij.so 126
        daysOfStock = (float(totalAvailability-totalReserved))/avgSalePerDay
127
        if daysOfStock<2:
128
            markReasonForMpItem(mpHistory,'Our stock is not enough',Decision.AUTO_DECREMENT_FAILED)
129
            continue
130
 
131
        mpHistory.competitorEnoughStock = True
132
        mpHistory.ourEnoughStock = True
133
        mpHistory.avgSales = avgSalePerDay
134
        mpHistory.decision = Decision.AUTO_DECREMENT_SUCCESS
135
        mpHistory.reason = 'All conditions for auto decrement true'
136
        lgr.info("Auto decrement success for itemId "+str(autoDecrementItem.itemId)+" Days of stock "+str(daysOfStock)+" avg sales "+str(avgSalePerDay))
137
    session.commit()
138
 
139
def fetchItemsForAutoIncrease(time):
9911 kshitij.so 140
    autoIncrementItems = MarketplaceItems.query.filter(MarketplaceItems.autoIncrement==True).filter(MarketplaceItems.source==OrderSource.SNAPDEAL).all()
9897 kshitij.so 141
    inventory_client = InventoryClient().get_client()
142
    inventoryMap = inventory_client.getInventorySnapshot(0)
143
    for autoIncrementItem in autoIncrementItems:
144
        mpHistory = MarketPlaceHistory.get_by(source=OrderSource.SNAPDEAL,item_id=autoIncrementItem.itemId,timestamp=time)
145
        if mpHistory.proposedSellingPrice <= mpHistory.ourSellingPrice:
146
            markReasonForMpItem(mpHistory,'Proposed SP less than current SP',Decision.AUTO_INCREMENT_FAILED)
147
            continue
148
        if mpHistory.totalSeller==1 and mpHistory.ourRank==1:
149
            markReasonForMpItem(mpHistory,'We are the only seller',Decision.AUTO_INCREMENT_FAILED)
150
            continue
151
        oosStatus = inventory_client.getOosStatusesForXDaysForItem(autoIncrementItem.itemId,0,3)
152
        count,sale,daysOfStock = 0,0,0
153
        for obj in oosStatus:
154
            if not obj.is_oos:
155
                count+=1
156
                sale = sale+obj.num_orders
157
        avgSalePerDay=0 if count==0 else (float(sale)/count)
158
        totalAvailability, totalReserved = 0,0
9913 kshitij.so 159
        if (not inventoryMap.has_key(autoIncrementItem.itemId)):
160
            markReasonForMpItem(mpHistory,'Average sale per day is zero',Decision.AUTO_INCREMENT_FAILED)
161
            continue
9897 kshitij.so 162
        itemInventory=inventoryMap[autoIncrementItem.itemId]
163
        availableMap  = itemInventory.availability
164
        reserveMap = itemInventory.reserved
165
        for warehouse,availability in availableMap.iteritems():
166
            if warehouse==16:
167
                continue
168
            totalAvailability = totalAvailability+availability
169
        for warehouse,reserve in reserveMap.iteritems():
170
            if warehouse==16:
171
                continue
172
            totalReserved = totalReserved+reserve
173
        if (totalAvailability-totalReserved)<=0:
174
            markReasonForMpItem(mpHistory,'Our stock is 0',Decision.AUTO_INCREMENT_FAILED)
175
            continue
9912 kshitij.so 176
        if (avgSalePerDay==0):
9913 kshitij.so 177
            markReasonForMpItem(mpHistory,'Average sale per day is zero',Decision.AUTO_INCREMENT_FAILED)
9912 kshitij.so 178
            continue
9897 kshitij.so 179
        daysOfStock = (float(totalAvailability-totalReserved))/avgSalePerDay
180
        if daysOfStock>5:
181
            markReasonForMpItem(mpHistory,'Our stock is enough',Decision.AUTO_INCREMENT_FAILED)
182
            continue
183
 
184
        mpHistory.ourEnoughStock = False
185
        mpHistory.avgSales = avgSalePerDay
186
        mpHistory.decision = Decision.AUTO_INCREMENT_SUCCESS
187
        mpHistory.reason = 'All conditions for auto increment true'
188
        lgr.info("Auto increment success for itemId "+str(autoIncrementItem.itemId)+" Days of stock "+str(daysOfStock)+" avg sales "+str(avgSalePerDay))
189
    session.commit()
190
 
191
 
192
def markReasonForMpItem(mpHistory,reason,decision):
193
    mpHistory.decision = decision
194
    mpHistory.reason = reason
195
 
9881 kshitij.so 196
def fetchDetails(supc_code):
197
    url="http://www.snapdeal.com/json/gvbps?supc=%s&catId=91"%(supc_code)
198
    print url
199
    time.sleep(1)
200
    req = urllib2.Request(url)
201
    response = urllib2.urlopen(req)
202
    json_input = response.read()
203
    vendorInfo = json.loads(json_input)
204
    rank ,otherInventory ,ourInventory, ourOfferPrice, ourSp, iterator, secondLowestSellerSp, secondLowestSellerInventory, \
205
    lowestOfferPrice,  secondLowestSellerOfferPrice = (0,)*10
206
    lowestSellerName , lowestSellerCode, secondLowestSellerName, secondLowestSellerCode=('',)*4
207
    for vendor in vendorInfo:
208
        if iterator == 0:
209
            lowestSellerName = vendor['vendorDisplayName']
210
            lowestSellerCode = vendor['vendorCode']
211
            try:
212
                lowestSp = vendor['sellingPriceBefIntCashBack']
213
            except:
214
                lowestSp = vendor['sellingPrice']
215
            lowestOfferPrice = vendor['sellingPrice']
216
 
217
        if iterator ==1:
218
            secondLowestSellerName = vendor['vendorDisplayName']
219
            secondLowestSellerCode =vendor['vendorCode']
220
            try:
221
                secondLowestSellerSp = vendor['sellingPriceBefIntCashBack']
222
            except:
223
                secondLowestSellerSp = vendor['sellingPrice'] 
224
            secondLowestSellerOfferPrice = vendor['sellingPrice'] 
225
            secondLowestSellerInventory = vendor['buyableInventory']
226
 
227
        if vendor['vendorDisplayName'] == 'MobilesnMore':
228
            ourInventory = vendor['buyableInventory']
229
            try:
230
                ourSp = vendor['sellingPriceBefIntCashBack']
231
            except:
232
                ourSp = vendor['sellingPrice']
233
            ourOfferPrice = vendor['sellingPrice']
234
            rank = iterator +1
235
        else:
236
            if rank==0:
237
                otherInventory = otherInventory +vendor['buyableInventory']
238
        iterator+=1
239
    snapdealDetails = __SnapdealDetails(ourSp,ourInventory,otherInventory,rank,lowestSellerName, lowestSellerCode,lowestSp,secondLowestSellerName,secondLowestSellerCode,secondLowestSellerSp,secondLowestSellerInventory,lowestOfferPrice,secondLowestSellerOfferPrice,ourOfferPrice,len(vendorInfo))
240
    return snapdealDetails        
241
 
242
 
243
def populateStuff():
244
    itemInfo = []
245
    items = session.query(SnapdealItem).all()
246
    spm = SourcePercentageMaster.get_by(source=OrderSource.SNAPDEAL)
247
    for snapdeal_item in items:
248
        it = Item.query.filter_by(id=snapdeal_item.item_id).one()
249
        category = Category.query.filter_by(id=it.category).one()
250
        snapdealItemInfo = __SnapdealItemInfo(snapdeal_item.supc, snapdeal_item.maxNlc,snapdeal_item.courierCost, it.id, it.product_group, it.brand, it.model_name, it.model_number, it.color, it.weight, category.parent_category_id, it.risky, snapdeal_item.warehouseId, None)
251
        itemInfo.append(snapdealItemInfo)
252
    return itemInfo, spm
253
 
254
 
255
def decideCategory(itemInfo,spm):
256
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin = [],[],[],[],[],[]
257
    catalog_client = CatalogClient().get_client()
258
    inventory_client = InventoryClient().get_client()
259
 
260
    for val in itemInfo:
261
        try:
262
            snapdealDetails = fetchDetails(val.supc)
263
        except:
264
            exceptionItems.append(val)
265
            continue
266
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.SNAPDEAL)
267
        warehouse = inventory_client.getWarehouse(val.warehouseId)
268
        if snapdealDetails.rank==0:
269
            snapdealDetails.ourSp = mpItem.currentSp
270
            snapdealDetails.ourOfferPrice = mpItem.currentSp
271
            ourSp = mpItem.currentSp
272
        else:
273
            ourSp = snapdealDetails.ourSp
274
        vatRate = catalog_client.getVatPercentageForItem(val.item_id, warehouse.stateId, snapdealDetails.ourSp)
275
        val.vatRate = vatRate
276
        if (snapdealDetails.rank==1):
277
            temp=[]
278
            temp.append(snapdealDetails)
279
            temp.append(val)
280
            if (snapdealDetails.secondLowestSellerOfferPrice == snapdealDetails.secondLowestSellerSp) and snapdealDetails.ourOfferPrice==snapdealDetails.ourSp:
281
                competitionBasis = 'SP'
282
            else:
283
                competitionBasis = 'TP'
284
            secondLowestTp=0 if snapdealDetails.totalSeller==1 else getOtherTp(snapdealDetails,val,spm)
285
            snapdealPricing = __SnapdealPricing(snapdealDetails.ourSp,getOurTp(snapdealDetails,val,spm,mpItem),None,getLowestPossibleTp(snapdealDetails,val,spm,mpItem),competitionBasis,secondLowestTp,getLowestPossibleSp(snapdealDetails,val,spm,mpItem))
286
            temp.append(snapdealPricing)
287
            temp.append(mpItem)
288
            buyBoxItems.append(temp)
289
            continue
290
 
291
 
292
        lowestTp = getOtherTp(snapdealDetails,val,spm)
293
        ourTp = getOurTp(snapdealDetails,val,spm,mpItem)
294
        lowestPossibleTp = getLowestPossibleTp(snapdealDetails,val,spm,mpItem)
295
        lowestPossibleSp = getLowestPossibleSp(snapdealDetails,val,spm,mpItem)
296
 
297
        if (ourTp<lowestPossibleTp):
298
            temp=[]
299
            temp.append(snapdealDetails)
300
            temp.append(val)
301
            snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,None,None)
302
            temp.append(snapdealPricing)
303
            negativeMargin.append(temp)
304
            continue
305
 
306
        if (snapdealDetails.lowestOfferPrice == snapdealDetails.lowestSp) and snapdealDetails.ourOfferPrice == snapdealDetails.ourSp:
307
            competitionBasis ='SP'
308
        else:
309
            competitionBasis ='TP'
310
 
311
        if competitionBasis=='SP':
312
            if snapdealDetails.lowestSp > lowestPossibleSp and snapdealDetails.ourInventory!=0:
313
                temp=[]
314
                temp.append(snapdealDetails)
315
                temp.append(val)
316
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'SP',None,lowestPossibleSp)
317
                temp.append(snapdealPricing)
318
                temp.append(mpItem)
319
                competitive.append(temp)
320
                continue
321
        else:
322
            if lowestTp > lowestPossibleTp and snapdealDetails.ourInventory!=0:
323
                temp=[]
324
                temp.append(snapdealDetails)
325
                temp.append(val)
326
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'TP',None,lowestPossibleSp)
327
                temp.append(snapdealPricing)
328
                temp.append(mpItem)
329
                competitive.append(temp)
330
                continue
331
 
332
        if competitionBasis=='SP':
333
            if snapdealDetails.lowestSp > lowestPossibleSp and snapdealDetails.ourInventory==0:
334
                temp=[]
335
                temp.append(snapdealDetails)
336
                temp.append(val)
337
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'SP',None,lowestPossibleSp)
338
                temp.append(snapdealPricing)
339
                temp.append(mpItem)
340
                competitiveNoInventory.append(temp)
341
                continue
342
        else:
343
            if lowestTp > lowestPossibleTp and snapdealDetails.ourInventory==0:
344
                temp=[]
345
                temp.append(snapdealDetails)
346
                temp.append(val)
347
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'TP',None,lowestPossibleSp)
348
                temp.append(snapdealPricing)
349
                temp.append(mpItem)
350
                competitiveNoInventory.append(temp)
351
                continue
352
 
353
        temp=[]
354
        temp.append(snapdealDetails)
355
        temp.append(val)
356
        snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,competitionBasis,None,lowestPossibleSp)
357
        temp.append(snapdealPricing)
358
        temp.append(mpItem)
359
        cantCompete.append(temp)
360
 
361
    return cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin    
362
 
363
 
364
def commitExceptionList(exceptionList,timestamp):
365
    for item in exceptionList:
366
        mpHistory = MarketPlaceHistory()
367
        mpHistory.item_id =item.item_id
368
        mpHistory.source = OrderSource.SNAPDEAL 
369
        mpHistory.competitiveCategory = CompetitionCategory.EXCEPTION
370
        mpHistory.risky = item.risky
371
        mpHistory.timestamp = timestamp
372
    session.commit()
373
 
374
def commitNegativeMargin(negativeMargin,timestamp):
375
    for item in negativeMargin:
376
        snapdealDetails = item[0]
377
        snapdealItemInfo = item[1]
378
        snapdealPricing = item[2]
379
        mpHistory = MarketPlaceHistory()
380
        mpHistory.item_id = snapdealItemInfo.item_id
381
        mpHistory.source = OrderSource.SNAPDEAL
382
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
383
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
384
        mpHistory.ourTp = snapdealPricing.ourTp
385
        mpHistory.ourNlc = snapdealItemInfo.nlc
386
        mpHistory.ourInventory = snapdealDetails.ourInventory
387
        mpHistory.otherInventory = snapdealDetails.otherInventory
388
        mpHistory.ourRank = snapdealDetails.rank
389
        mpHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
390
        mpHistory.totalSeller = snapdealDetails.totalSeller
391
        mpHistory.timestamp = timestamp
392
    session.commit()
393
 
394
def commitCompetitive(competitive,timestamp):
395
    for item in competitive:
396
        snapdealDetails = item[0]
397
        snapdealItemInfo = item[1]
398
        snapdealPricing = item[2]
399
        mpItem = item[3]
400
        mpHistory = MarketPlaceHistory()
401
        mpHistory.item_id = snapdealItemInfo.item_id
402
        mpHistory.source = OrderSource.SNAPDEAL
403
        mpHistory.lowestTp = snapdealPricing.lowestTp
404
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
405
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
406
        mpHistory.ourInventory = snapdealDetails.ourInventory
407
        mpHistory.otherInventory = snapdealDetails.otherInventory
408
        mpHistory.ourRank = snapdealDetails.rank
409
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
410
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
411
        mpHistory.risky = snapdealItemInfo.risky
412
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
413
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
414
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
415
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
416
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
417
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
418
        mpHistory.ourTp = snapdealPricing.ourTp
419
        mpHistory.ourNlc = snapdealItemInfo.nlc
420
        if (snapdealPricing.competitionBasis=='SP'):
421
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
422
            proposed_tp = getTargetTp(proposed_sp,mpItem)
423
            mpHistory.proposedSellingPrice = proposed_sp
424
            mpHistory.proposedTp = proposed_tp
425
        else:
426
            proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
427
            proposed_sp = getTargetSp(proposed_tp,mpItem)
428
            mpHistory.proposedSellingPrice = proposed_sp
429
            mpHistory.proposedTp = proposed_tp
430
        mpHistory.totalSeller = snapdealDetails.totalSeller
431
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
432
        mpHistory.timestamp = timestamp
433
    session.commit()
434
 
435
def commitCompetitiveNoInventory(competitiveNoInventory,timestamp):
436
    for item in competitiveNoInventory:
437
        snapdealDetails = item[0]
438
        snapdealItemInfo = item[1]
439
        snapdealPricing = item[2]
440
        mpItem = item[3]
441
        mpHistory = MarketPlaceHistory()
442
        mpHistory.item_id = snapdealItemInfo.item_id
443
        mpHistory.source = OrderSource.SNAPDEAL
444
        mpHistory.lowestTp = snapdealPricing.lowestTp
445
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
446
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
447
        mpHistory.ourInventory = snapdealDetails.ourInventory
448
        mpHistory.otherInventory = snapdealDetails.otherInventory
449
        mpHistory.ourRank = snapdealDetails.rank
450
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
451
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE_NO_INVENTORY
452
        mpHistory.risky = snapdealItemInfo.risky
453
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
454
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
455
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
456
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
457
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
458
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
459
        mpHistory.ourTp = snapdealPricing.ourTp
460
        mpHistory.ourNlc = snapdealItemInfo.nlc
461
        if (snapdealPricing.competitionBasis=='SP'):
462
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
463
            proposed_tp = getTargetTp(proposed_sp,mpItem)
464
            mpHistory.proposedSellingPrice = proposed_sp
465
            mpHistory.proposedTp = proposed_tp
466
        else:
467
            proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
468
            proposed_sp = getTargetSp(proposed_tp,mpItem)
469
            mpHistory.proposedSellingPrice = proposed_sp
470
            mpHistory.proposedTp = proposed_tp
471
        mpHistory.totalSeller = snapdealDetails.totalSeller
472
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
473
        mpHistory.timestamp = timestamp
474
    session.commit()
475
 
476
def commitCantCompete(cantCompete,timestamp):
477
    for item in cantCompete:
478
        snapdealDetails = item[0]
479
        snapdealItemInfo = item[1]
480
        snapdealPricing = item[2]
481
        mpItem = item[3]
482
        mpHistory = MarketPlaceHistory()
483
        mpHistory.item_id = snapdealItemInfo.item_id
484
        mpHistory.source = OrderSource.SNAPDEAL
485
        mpHistory.lowestTp = snapdealPricing.lowestTp
486
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
487
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
488
        mpHistory.ourInventory = snapdealDetails.ourInventory
489
        mpHistory.otherInventory = snapdealDetails.otherInventory
490
        mpHistory.ourRank = snapdealDetails.rank
491
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
492
        mpHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
493
        mpHistory.risky = snapdealItemInfo.risky
494
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
495
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
496
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
497
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
498
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
499
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
500
        mpHistory.ourTp = snapdealPricing.ourTp
501
        mpHistory.ourNlc = snapdealItemInfo.nlc
502
        if (snapdealPricing.competitionBasis=='SP'):
503
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
504
            proposed_tp = getTargetTp(proposed_sp,mpItem)
505
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
506
            mpHistory.proposedSellingPrice = proposed_sp
507
            mpHistory.proposedTp = proposed_tp
508
            mpHistory.targetNlc = target_nlc
509
        else:
510
            proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
511
            proposed_sp = getTargetSp(proposed_tp,mpItem)
512
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
513
            mpHistory.proposedSellingPrice = proposed_sp
514
            mpHistory.proposedTp = proposed_tp
515
            mpHistory.targetNlc = target_nlc
516
        mpHistory.totalSeller = snapdealDetails.totalSeller
517
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
518
        mpHistory.timestamp = timestamp
519
    session.commit()
520
 
521
def commitBuyBox(buyBoxItems,timestamp):
522
    for item in buyBoxItems:
523
        snapdealDetails = item[0]
524
        snapdealItemInfo = item[1]
525
        snapdealPricing = item[2]
526
        mpItem = item[3]
527
        mpHistory = MarketPlaceHistory()
528
        mpHistory.item_id = snapdealItemInfo.item_id
529
        mpHistory.source = OrderSource.SNAPDEAL
530
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
531
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
532
        mpHistory.ourInventory = snapdealDetails.ourInventory
533
        mpHistory.secondLowestInventory = snapdealDetails.secondLowestSellerInventory
534
        mpHistory.ourRank = snapdealDetails.rank
535
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
536
        mpHistory.competitiveCategory = CompetitionCategory.BUY_BOX
537
        mpHistory.risky = snapdealItemInfo.risky
538
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
539
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
540
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
541
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
542
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
543
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
544
        mpHistory.ourTp = snapdealPricing.ourTp
545
        mpHistory.ourNlc = snapdealItemInfo.nlc
546
        mpHistory.secondLowestSellerName = snapdealDetails.secondLowestSellerName
547
        mpHistory.secondLowestSellerCode = snapdealDetails.secondLowestSellerCode
9885 kshitij.so 548
        mpHistory.secondLowestSellingPrice = snapdealDetails.secondLowestSellerSp
9888 kshitij.so 549
        mpHistory.secondLowestOfferPrice = snapdealDetails.secondLowestSellerOfferPrice
9881 kshitij.so 550
        mpHistory.secondLowestTp = snapdealPricing.secondLowestSellerTp
551
        if (snapdealPricing.competitionBasis=='SP'):
552
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)), snapdealPricing.lowestPossibleSp)
553
            proposed_tp = getTargetTp(proposed_sp,mpItem)
554
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
555
            mpHistory.proposedSellingPrice = proposed_sp
556
            mpHistory.proposedTp = proposed_tp
557
            #mpHistory.targetNlc = target_nlc
558
        else:
559
            proposed_tp  = max(snapdealPricing.secondLowestSellerTp - max((20, snapdealPricing.secondLowestSellerTp*0.002)), snapdealPricing.lowestPossibleTp)
560
            proposed_sp = getTargetSp(proposed_tp,mpItem)
561
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
562
            mpHistory.proposedSellingPrice = proposed_sp
563
            mpHistory.proposedTp = proposed_tp
564
            #mpHistory.targetNlc = target_nlc
565
        mpHistory.marginIncreasedPotential = proposed_tp - snapdealPricing.ourTp
566
        mpHistory.totalSeller = snapdealDetails.totalSeller
567
        mpHistory.timestamp = timestamp
568
    session.commit()
569
 
570
 
571
def getOtherTp(snapdealDetails,val,spm):
572
    if val.parent_category==10011:
573
        commissionPercentage = spm.competitorCommissionAccessory
574
    else:
575
        commissionPercentage = spm.competitorCommissionOther
576
    if snapdealDetails.rank==1:
577
        return snapdealDetails.secondLowestSellerSp- snapdealDetails.secondLowestSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100));  
578
    return snapdealDetails.lowestSp- snapdealDetails.lowestSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100));
579
 
580
def getLowestPossibleTp(snapdealDetails,val,spm,mpItem):
581
    if snapdealDetails.rank==0:
582
        return mpItem.minimumPossibleTp
583
    vat = (snapdealDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100);
584
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*snapdealDetails.ourSp+mpItem.otherCost;
585
    lowest_possible_tp = val.nlc+inHouseCost;
586
    return lowest_possible_tp
587
 
588
def getOurTp(snapdealDetails,val,spm,mpItem):
589
    if snapdealDetails.rank==0:
590
        return mpItem.currentTp
591
    return snapdealDetails.ourSp- snapdealDetails.ourSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(val.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100));
592
 
593
def getLowestPossibleSp(snapdealDetails,val,spm,mpItem):
594
    if snapdealDetails.rank==0:
595
        return mpItem.minimumPossibleSp
596
    return (val.nlc+(val.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100))*(1+(val.vatRate/100))+(15+mpItem.otherCost)*(1+(val.vatRate)/100))/(1-(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))*(1+(val.vatRate)/100)-(mpItem.returnProvision/100)*(1+(val.vatRate)/100));    
597
 
598
def getTargetTp(targetSp,mpItem):
599
    return targetSp- targetSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100));
600
 
601
def getTargetSp(targetTp,mpItem):
9897 kshitij.so 602
    return float(targetTp+(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100)))/(1-((mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))))
9881 kshitij.so 603
 
604
def getSalesPotential(lowestOfferPrice,ourNlc):
605
    if lowestOfferPrice - ourNlc < 0:
606
        return 'HIGH'
9897 kshitij.so 607
    elif (float(lowestOfferPrice - ourNlc))/lowestOfferPrice >=0 and (float(lowestOfferPrice - ourNlc))/lowestOfferPrice <=.02:
9881 kshitij.so 608
        return 'MEDIUM'
609
    else:
610
        return 'LOW'  
611
 
612
def main():
613
    itemInfo,spm= populateStuff()
614
    cantCompete, buyBoxItems, competitive, \
615
    competitiveNoInventory, exceptionItems, negativeMargin = decideCategory(itemInfo,spm)
616
    timestamp = datetime.now()
617
    commitExceptionList(exceptionItems,timestamp)
618
    commitCantCompete(cantCompete,timestamp)
619
    commitBuyBox(buyBoxItems,timestamp)
620
    commitCompetitive(competitive,timestamp)
621
    commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
622
    commitNegativeMargin(negativeMargin,timestamp)
9897 kshitij.so 623
    fetchItemsForAutoDecrease(timestamp)
624
    fetchItemsForAutoIncrease(timestamp)
625
 
626
 
9881 kshitij.so 627
if __name__ == '__main__':
628
    main()