Subversion Repositories SmartDukaan

Rev

Rev 9914 | Rev 9920 | 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)
9914 kshitij.so 86
        if not mpHistory.competitiveCategory == CompetitionCategory.COMPETITIVE:
87
            markReasonForMpItem(mpHistory,'Category is '+CompetitionCategory._VALUES_TO_NAMES.get(mpHistory.competitiveCategory),Decision.AUTO_DECREMENT_FAILED)
88
            continue
9897 kshitij.so 89
        if not mpHistory.risky:
90
            markReasonForMpItem(mpHistory,'Item is not risky',Decision.AUTO_DECREMENT_FAILED)
91
            continue
92
        if mpHistory.proposedSellingPrice >= mpHistory.ourSellingPrice:
93
            markReasonForMpItem(mpHistory,'Proposed SP greater than current SP',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)
9919 kshitij.so 145
        if not mpHistory.competitiveCategory == CompetitionCategory.BUY_BOX:
146
            markReasonForMpItem(mpHistory,'Category is '+CompetitionCategory._VALUES_TO_NAMES.get(mpHistory.competitiveCategory),Decision.AUTO_DECREMENT_FAILED)
9897 kshitij.so 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
9919 kshitij.so 151
        if mpHistory.proposedSellingPrice <= mpHistory.ourSellingPrice:
152
            markReasonForMpItem(mpHistory,'Proposed SP less than current SP',Decision.AUTO_INCREMENT_FAILED)
153
            continue
9897 kshitij.so 154
        oosStatus = inventory_client.getOosStatusesForXDaysForItem(autoIncrementItem.itemId,0,3)
155
        count,sale,daysOfStock = 0,0,0
156
        for obj in oosStatus:
157
            if not obj.is_oos:
158
                count+=1
159
                sale = sale+obj.num_orders
160
        avgSalePerDay=0 if count==0 else (float(sale)/count)
161
        totalAvailability, totalReserved = 0,0
9913 kshitij.so 162
        if (not inventoryMap.has_key(autoIncrementItem.itemId)):
163
            markReasonForMpItem(mpHistory,'Average sale per day is zero',Decision.AUTO_INCREMENT_FAILED)
164
            continue
9897 kshitij.so 165
        itemInventory=inventoryMap[autoIncrementItem.itemId]
166
        availableMap  = itemInventory.availability
167
        reserveMap = itemInventory.reserved
168
        for warehouse,availability in availableMap.iteritems():
169
            if warehouse==16:
170
                continue
171
            totalAvailability = totalAvailability+availability
172
        for warehouse,reserve in reserveMap.iteritems():
173
            if warehouse==16:
174
                continue
175
            totalReserved = totalReserved+reserve
176
        if (totalAvailability-totalReserved)<=0:
177
            markReasonForMpItem(mpHistory,'Our stock is 0',Decision.AUTO_INCREMENT_FAILED)
178
            continue
9912 kshitij.so 179
        if (avgSalePerDay==0):
9913 kshitij.so 180
            markReasonForMpItem(mpHistory,'Average sale per day is zero',Decision.AUTO_INCREMENT_FAILED)
9912 kshitij.so 181
            continue
9897 kshitij.so 182
        daysOfStock = (float(totalAvailability-totalReserved))/avgSalePerDay
183
        if daysOfStock>5:
184
            markReasonForMpItem(mpHistory,'Our stock is enough',Decision.AUTO_INCREMENT_FAILED)
185
            continue
186
 
187
        mpHistory.ourEnoughStock = False
188
        mpHistory.avgSales = avgSalePerDay
189
        mpHistory.decision = Decision.AUTO_INCREMENT_SUCCESS
190
        mpHistory.reason = 'All conditions for auto increment true'
191
        lgr.info("Auto increment success for itemId "+str(autoIncrementItem.itemId)+" Days of stock "+str(daysOfStock)+" avg sales "+str(avgSalePerDay))
192
    session.commit()
193
 
194
 
195
def markReasonForMpItem(mpHistory,reason,decision):
196
    mpHistory.decision = decision
197
    mpHistory.reason = reason
198
 
9881 kshitij.so 199
def fetchDetails(supc_code):
200
    url="http://www.snapdeal.com/json/gvbps?supc=%s&catId=91"%(supc_code)
201
    print url
202
    time.sleep(1)
203
    req = urllib2.Request(url)
204
    response = urllib2.urlopen(req)
205
    json_input = response.read()
206
    vendorInfo = json.loads(json_input)
207
    rank ,otherInventory ,ourInventory, ourOfferPrice, ourSp, iterator, secondLowestSellerSp, secondLowestSellerInventory, \
208
    lowestOfferPrice,  secondLowestSellerOfferPrice = (0,)*10
209
    lowestSellerName , lowestSellerCode, secondLowestSellerName, secondLowestSellerCode=('',)*4
210
    for vendor in vendorInfo:
211
        if iterator == 0:
212
            lowestSellerName = vendor['vendorDisplayName']
213
            lowestSellerCode = vendor['vendorCode']
214
            try:
215
                lowestSp = vendor['sellingPriceBefIntCashBack']
216
            except:
217
                lowestSp = vendor['sellingPrice']
218
            lowestOfferPrice = vendor['sellingPrice']
219
 
220
        if iterator ==1:
221
            secondLowestSellerName = vendor['vendorDisplayName']
222
            secondLowestSellerCode =vendor['vendorCode']
223
            try:
224
                secondLowestSellerSp = vendor['sellingPriceBefIntCashBack']
225
            except:
226
                secondLowestSellerSp = vendor['sellingPrice'] 
227
            secondLowestSellerOfferPrice = vendor['sellingPrice'] 
228
            secondLowestSellerInventory = vendor['buyableInventory']
229
 
230
        if vendor['vendorDisplayName'] == 'MobilesnMore':
231
            ourInventory = vendor['buyableInventory']
232
            try:
233
                ourSp = vendor['sellingPriceBefIntCashBack']
234
            except:
235
                ourSp = vendor['sellingPrice']
236
            ourOfferPrice = vendor['sellingPrice']
237
            rank = iterator +1
238
        else:
239
            if rank==0:
240
                otherInventory = otherInventory +vendor['buyableInventory']
241
        iterator+=1
242
    snapdealDetails = __SnapdealDetails(ourSp,ourInventory,otherInventory,rank,lowestSellerName, lowestSellerCode,lowestSp,secondLowestSellerName,secondLowestSellerCode,secondLowestSellerSp,secondLowestSellerInventory,lowestOfferPrice,secondLowestSellerOfferPrice,ourOfferPrice,len(vendorInfo))
243
    return snapdealDetails        
244
 
245
 
246
def populateStuff():
247
    itemInfo = []
248
    items = session.query(SnapdealItem).all()
249
    spm = SourcePercentageMaster.get_by(source=OrderSource.SNAPDEAL)
250
    for snapdeal_item in items:
251
        it = Item.query.filter_by(id=snapdeal_item.item_id).one()
252
        category = Category.query.filter_by(id=it.category).one()
253
        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)
254
        itemInfo.append(snapdealItemInfo)
255
    return itemInfo, spm
256
 
257
 
258
def decideCategory(itemInfo,spm):
259
    cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin = [],[],[],[],[],[]
260
    catalog_client = CatalogClient().get_client()
261
    inventory_client = InventoryClient().get_client()
262
 
263
    for val in itemInfo:
264
        try:
265
            snapdealDetails = fetchDetails(val.supc)
266
        except:
267
            exceptionItems.append(val)
268
            continue
269
        mpItem = MarketplaceItems.get_by(itemId=val.item_id,source=OrderSource.SNAPDEAL)
270
        warehouse = inventory_client.getWarehouse(val.warehouseId)
271
        if snapdealDetails.rank==0:
272
            snapdealDetails.ourSp = mpItem.currentSp
273
            snapdealDetails.ourOfferPrice = mpItem.currentSp
274
            ourSp = mpItem.currentSp
275
        else:
276
            ourSp = snapdealDetails.ourSp
277
        vatRate = catalog_client.getVatPercentageForItem(val.item_id, warehouse.stateId, snapdealDetails.ourSp)
278
        val.vatRate = vatRate
279
        if (snapdealDetails.rank==1):
280
            temp=[]
281
            temp.append(snapdealDetails)
282
            temp.append(val)
283
            if (snapdealDetails.secondLowestSellerOfferPrice == snapdealDetails.secondLowestSellerSp) and snapdealDetails.ourOfferPrice==snapdealDetails.ourSp:
284
                competitionBasis = 'SP'
285
            else:
286
                competitionBasis = 'TP'
287
            secondLowestTp=0 if snapdealDetails.totalSeller==1 else getOtherTp(snapdealDetails,val,spm)
288
            snapdealPricing = __SnapdealPricing(snapdealDetails.ourSp,getOurTp(snapdealDetails,val,spm,mpItem),None,getLowestPossibleTp(snapdealDetails,val,spm,mpItem),competitionBasis,secondLowestTp,getLowestPossibleSp(snapdealDetails,val,spm,mpItem))
289
            temp.append(snapdealPricing)
290
            temp.append(mpItem)
291
            buyBoxItems.append(temp)
292
            continue
293
 
294
 
295
        lowestTp = getOtherTp(snapdealDetails,val,spm)
296
        ourTp = getOurTp(snapdealDetails,val,spm,mpItem)
297
        lowestPossibleTp = getLowestPossibleTp(snapdealDetails,val,spm,mpItem)
298
        lowestPossibleSp = getLowestPossibleSp(snapdealDetails,val,spm,mpItem)
299
 
300
        if (ourTp<lowestPossibleTp):
301
            temp=[]
302
            temp.append(snapdealDetails)
303
            temp.append(val)
304
            snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,None,None,None)
305
            temp.append(snapdealPricing)
306
            negativeMargin.append(temp)
307
            continue
308
 
309
        if (snapdealDetails.lowestOfferPrice == snapdealDetails.lowestSp) and snapdealDetails.ourOfferPrice == snapdealDetails.ourSp:
310
            competitionBasis ='SP'
311
        else:
312
            competitionBasis ='TP'
313
 
314
        if competitionBasis=='SP':
315
            if snapdealDetails.lowestSp > lowestPossibleSp and snapdealDetails.ourInventory!=0:
316
                temp=[]
317
                temp.append(snapdealDetails)
318
                temp.append(val)
319
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'SP',None,lowestPossibleSp)
320
                temp.append(snapdealPricing)
321
                temp.append(mpItem)
322
                competitive.append(temp)
323
                continue
324
        else:
325
            if lowestTp > lowestPossibleTp and snapdealDetails.ourInventory!=0:
326
                temp=[]
327
                temp.append(snapdealDetails)
328
                temp.append(val)
329
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'TP',None,lowestPossibleSp)
330
                temp.append(snapdealPricing)
331
                temp.append(mpItem)
332
                competitive.append(temp)
333
                continue
334
 
335
        if competitionBasis=='SP':
336
            if snapdealDetails.lowestSp > lowestPossibleSp and snapdealDetails.ourInventory==0:
337
                temp=[]
338
                temp.append(snapdealDetails)
339
                temp.append(val)
340
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'SP',None,lowestPossibleSp)
341
                temp.append(snapdealPricing)
342
                temp.append(mpItem)
343
                competitiveNoInventory.append(temp)
344
                continue
345
        else:
346
            if lowestTp > lowestPossibleTp and snapdealDetails.ourInventory==0:
347
                temp=[]
348
                temp.append(snapdealDetails)
349
                temp.append(val)
350
                snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,'TP',None,lowestPossibleSp)
351
                temp.append(snapdealPricing)
352
                temp.append(mpItem)
353
                competitiveNoInventory.append(temp)
354
                continue
355
 
356
        temp=[]
357
        temp.append(snapdealDetails)
358
        temp.append(val)
359
        snapdealPricing = __SnapdealPricing(ourSp,ourTp,lowestTp,lowestPossibleTp,competitionBasis,None,lowestPossibleSp)
360
        temp.append(snapdealPricing)
361
        temp.append(mpItem)
362
        cantCompete.append(temp)
363
 
364
    return cantCompete, buyBoxItems, competitive, competitiveNoInventory, exceptionItems, negativeMargin    
365
 
366
 
367
def commitExceptionList(exceptionList,timestamp):
368
    for item in exceptionList:
369
        mpHistory = MarketPlaceHistory()
370
        mpHistory.item_id =item.item_id
371
        mpHistory.source = OrderSource.SNAPDEAL 
372
        mpHistory.competitiveCategory = CompetitionCategory.EXCEPTION
373
        mpHistory.risky = item.risky
374
        mpHistory.timestamp = timestamp
375
    session.commit()
376
 
377
def commitNegativeMargin(negativeMargin,timestamp):
378
    for item in negativeMargin:
379
        snapdealDetails = item[0]
380
        snapdealItemInfo = item[1]
381
        snapdealPricing = item[2]
382
        mpHistory = MarketPlaceHistory()
383
        mpHistory.item_id = snapdealItemInfo.item_id
384
        mpHistory.source = OrderSource.SNAPDEAL
385
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
386
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
387
        mpHistory.ourTp = snapdealPricing.ourTp
9919 kshitij.so 388
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
9881 kshitij.so 389
        mpHistory.ourNlc = snapdealItemInfo.nlc
390
        mpHistory.ourInventory = snapdealDetails.ourInventory
391
        mpHistory.otherInventory = snapdealDetails.otherInventory
392
        mpHistory.ourRank = snapdealDetails.rank
9919 kshitij.so 393
        mpHistory.risky = snapdealItemInfo.risky
394
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp  
9881 kshitij.so 395
        mpHistory.competitiveCategory = CompetitionCategory.NEGATIVE_MARGIN
396
        mpHistory.totalSeller = snapdealDetails.totalSeller
397
        mpHistory.timestamp = timestamp
398
    session.commit()
399
 
400
def commitCompetitive(competitive,timestamp):
401
    for item in competitive:
402
        snapdealDetails = item[0]
403
        snapdealItemInfo = item[1]
404
        snapdealPricing = item[2]
405
        mpItem = item[3]
406
        mpHistory = MarketPlaceHistory()
407
        mpHistory.item_id = snapdealItemInfo.item_id
408
        mpHistory.source = OrderSource.SNAPDEAL
409
        mpHistory.lowestTp = snapdealPricing.lowestTp
410
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
411
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
412
        mpHistory.ourInventory = snapdealDetails.ourInventory
413
        mpHistory.otherInventory = snapdealDetails.otherInventory
414
        mpHistory.ourRank = snapdealDetails.rank
415
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
416
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE
417
        mpHistory.risky = snapdealItemInfo.risky
418
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
419
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
420
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
421
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
422
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
423
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
424
        mpHistory.ourTp = snapdealPricing.ourTp
425
        mpHistory.ourNlc = snapdealItemInfo.nlc
426
        if (snapdealPricing.competitionBasis=='SP'):
427
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
428
            proposed_tp = getTargetTp(proposed_sp,mpItem)
429
            mpHistory.proposedSellingPrice = proposed_sp
430
            mpHistory.proposedTp = proposed_tp
431
        else:
432
            proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
433
            proposed_sp = getTargetSp(proposed_tp,mpItem)
434
            mpHistory.proposedSellingPrice = proposed_sp
435
            mpHistory.proposedTp = proposed_tp
9919 kshitij.so 436
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 437
        mpHistory.totalSeller = snapdealDetails.totalSeller
438
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
439
        mpHistory.timestamp = timestamp
440
    session.commit()
441
 
442
def commitCompetitiveNoInventory(competitiveNoInventory,timestamp):
443
    for item in competitiveNoInventory:
444
        snapdealDetails = item[0]
445
        snapdealItemInfo = item[1]
446
        snapdealPricing = item[2]
447
        mpItem = item[3]
448
        mpHistory = MarketPlaceHistory()
449
        mpHistory.item_id = snapdealItemInfo.item_id
450
        mpHistory.source = OrderSource.SNAPDEAL
451
        mpHistory.lowestTp = snapdealPricing.lowestTp
452
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
453
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
454
        mpHistory.ourInventory = snapdealDetails.ourInventory
455
        mpHistory.otherInventory = snapdealDetails.otherInventory
456
        mpHistory.ourRank = snapdealDetails.rank
457
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
458
        mpHistory.competitiveCategory = CompetitionCategory.COMPETITIVE_NO_INVENTORY
459
        mpHistory.risky = snapdealItemInfo.risky
460
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
461
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
462
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
463
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
464
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
465
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
466
        mpHistory.ourTp = snapdealPricing.ourTp
467
        mpHistory.ourNlc = snapdealItemInfo.nlc
468
        if (snapdealPricing.competitionBasis=='SP'):
469
            proposed_sp = max(snapdealDetails.lowestSp - max((10, snapdealDetails.lowestSp*0.001)), snapdealPricing.lowestPossibleSp)
470
            proposed_tp = getTargetTp(proposed_sp,mpItem)
471
            mpHistory.proposedSellingPrice = proposed_sp
472
            mpHistory.proposedTp = proposed_tp
473
        else:
474
            proposed_tp  = max(snapdealPricing.lowestTp - max((10, snapdealPricing.lowestTp*0.001)), snapdealPricing.lowestPossibleTp)
475
            proposed_sp = getTargetSp(proposed_tp,mpItem)
476
            mpHistory.proposedSellingPrice = proposed_sp
477
            mpHistory.proposedTp = proposed_tp
9919 kshitij.so 478
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 479
        mpHistory.totalSeller = snapdealDetails.totalSeller
480
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
481
        mpHistory.timestamp = timestamp
482
    session.commit()
483
 
484
def commitCantCompete(cantCompete,timestamp):
485
    for item in cantCompete:
486
        snapdealDetails = item[0]
487
        snapdealItemInfo = item[1]
488
        snapdealPricing = item[2]
489
        mpItem = item[3]
490
        mpHistory = MarketPlaceHistory()
491
        mpHistory.item_id = snapdealItemInfo.item_id
492
        mpHistory.source = OrderSource.SNAPDEAL
493
        mpHistory.lowestTp = snapdealPricing.lowestTp
494
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
495
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
496
        mpHistory.ourInventory = snapdealDetails.ourInventory
497
        mpHistory.otherInventory = snapdealDetails.otherInventory
498
        mpHistory.ourRank = snapdealDetails.rank
499
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
500
        mpHistory.competitiveCategory = CompetitionCategory.CANT_COMPETE
501
        mpHistory.risky = snapdealItemInfo.risky
502
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
503
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
504
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
505
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
506
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
507
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
508
        mpHistory.ourTp = snapdealPricing.ourTp
509
        mpHistory.ourNlc = snapdealItemInfo.nlc
510
        if (snapdealPricing.competitionBasis=='SP'):
511
            proposed_sp = snapdealDetails.lowestSp - max(10, snapdealDetails.lowestSp*0.001)
512
            proposed_tp = getTargetTp(proposed_sp,mpItem)
513
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
514
            mpHistory.proposedSellingPrice = proposed_sp
515
            mpHistory.proposedTp = proposed_tp
516
            mpHistory.targetNlc = target_nlc
517
        else:
518
            proposed_tp  = snapdealPricing.lowestTp - max(10, snapdealPricing.lowestTp*0.001)
519
            proposed_sp = getTargetSp(proposed_tp,mpItem)
520
            target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
521
            mpHistory.proposedSellingPrice = proposed_sp
522
            mpHistory.proposedTp = proposed_tp
523
            mpHistory.targetNlc = target_nlc
9919 kshitij.so 524
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 525
        mpHistory.totalSeller = snapdealDetails.totalSeller
526
        mpHistory.salesPotential = SalesPotential._NAMES_TO_VALUES.get(getSalesPotential(snapdealDetails.lowestOfferPrice,snapdealItemInfo.nlc))
527
        mpHistory.timestamp = timestamp
528
    session.commit()
529
 
530
def commitBuyBox(buyBoxItems,timestamp):
531
    for item in buyBoxItems:
532
        snapdealDetails = item[0]
533
        snapdealItemInfo = item[1]
534
        snapdealPricing = item[2]
535
        mpItem = item[3]
536
        mpHistory = MarketPlaceHistory()
537
        mpHistory.item_id = snapdealItemInfo.item_id
538
        mpHistory.source = OrderSource.SNAPDEAL
539
        mpHistory.lowestPossibleTp = snapdealPricing.lowestPossibleTp
540
        mpHistory.lowestPossibleSp = snapdealPricing.lowestPossibleSp
541
        mpHistory.ourInventory = snapdealDetails.ourInventory
542
        mpHistory.secondLowestInventory = snapdealDetails.secondLowestSellerInventory
543
        mpHistory.ourRank = snapdealDetails.rank
544
        mpHistory.competitionBasis = CompetitionBasis._NAMES_TO_VALUES.get(snapdealPricing.competitionBasis)
545
        mpHistory.competitiveCategory = CompetitionCategory.BUY_BOX
546
        mpHistory.risky = snapdealItemInfo.risky
547
        mpHistory.lowestOfferPrice = snapdealDetails.lowestOfferPrice
548
        mpHistory.lowestSellingPrice = snapdealDetails.lowestSp
549
        mpHistory.lowestSellerName = snapdealDetails.lowestSellerName
550
        mpHistory.lowestSellerCode = snapdealDetails.lowestSellerCode
551
        mpHistory.ourOfferPrice = snapdealDetails.ourOfferPrice
552
        mpHistory.ourSellingPrice = snapdealPricing.ourSp
553
        mpHistory.ourTp = snapdealPricing.ourTp
554
        mpHistory.ourNlc = snapdealItemInfo.nlc
555
        mpHistory.secondLowestSellerName = snapdealDetails.secondLowestSellerName
556
        mpHistory.secondLowestSellerCode = snapdealDetails.secondLowestSellerCode
9885 kshitij.so 557
        mpHistory.secondLowestSellingPrice = snapdealDetails.secondLowestSellerSp
9888 kshitij.so 558
        mpHistory.secondLowestOfferPrice = snapdealDetails.secondLowestSellerOfferPrice
9881 kshitij.so 559
        mpHistory.secondLowestTp = snapdealPricing.secondLowestSellerTp
560
        if (snapdealPricing.competitionBasis=='SP'):
561
            proposed_sp = max(snapdealDetails.secondLowestSellerSp - max((20, snapdealDetails.secondLowestSellerSp*0.002)), snapdealPricing.lowestPossibleSp)
562
            proposed_tp = getTargetTp(proposed_sp,mpItem)
563
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
564
            mpHistory.proposedSellingPrice = proposed_sp
565
            mpHistory.proposedTp = proposed_tp
566
            #mpHistory.targetNlc = target_nlc
567
        else:
568
            proposed_tp  = max(snapdealPricing.secondLowestSellerTp - max((20, snapdealPricing.secondLowestSellerTp*0.002)), snapdealPricing.lowestPossibleTp)
569
            proposed_sp = getTargetSp(proposed_tp,mpItem)
570
            #target_nlc = proposed_tp - snapdealPricing.lowestPossibleTp + snapdealItemInfo.nlc
571
            mpHistory.proposedSellingPrice = proposed_sp
572
            mpHistory.proposedTp = proposed_tp
573
            #mpHistory.targetNlc = target_nlc
9919 kshitij.so 574
        mpHistory.margin = mpHistory.ourTp - mpHistory.lowestPossibleTp
9881 kshitij.so 575
        mpHistory.marginIncreasedPotential = proposed_tp - snapdealPricing.ourTp
576
        mpHistory.totalSeller = snapdealDetails.totalSeller
577
        mpHistory.timestamp = timestamp
578
    session.commit()
579
 
580
 
581
def getOtherTp(snapdealDetails,val,spm):
582
    if val.parent_category==10011:
583
        commissionPercentage = spm.competitorCommissionAccessory
584
    else:
585
        commissionPercentage = spm.competitorCommissionOther
586
    if snapdealDetails.rank==1:
587
        return snapdealDetails.secondLowestSellerSp- snapdealDetails.secondLowestSellerSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100));  
588
    return snapdealDetails.lowestSp- snapdealDetails.lowestSp*(commissionPercentage/100+spm.emiFee/100)*(1+(spm.serviceTax/100))-(val.courierCost+spm.closingFee)*(1+(spm.serviceTax/100));
589
 
590
def getLowestPossibleTp(snapdealDetails,val,spm,mpItem):
591
    if snapdealDetails.rank==0:
592
        return mpItem.minimumPossibleTp
593
    vat = (snapdealDetails.ourSp/(1+(val.vatRate/100))-(val.nlc/(1+(val.vatRate/100))))*(val.vatRate/100);
594
    inHouseCost = 15+vat+(mpItem.returnProvision/100)*snapdealDetails.ourSp+mpItem.otherCost;
595
    lowest_possible_tp = val.nlc+inHouseCost;
596
    return lowest_possible_tp
597
 
598
def getOurTp(snapdealDetails,val,spm,mpItem):
599
    if snapdealDetails.rank==0:
600
        return mpItem.currentTp
601
    return snapdealDetails.ourSp- snapdealDetails.ourSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(val.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100));
602
 
603
def getLowestPossibleSp(snapdealDetails,val,spm,mpItem):
604
    if snapdealDetails.rank==0:
605
        return mpItem.minimumPossibleSp
606
    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));    
607
 
608
def getTargetTp(targetSp,mpItem):
609
    return targetSp- targetSp*(mpItem.commission/100+mpItem.emiFee/100)*(1+(mpItem.serviceTax/100))-(mpItem.courierCost+mpItem.closingFee)*(1+(mpItem.serviceTax/100));
610
 
611
def getTargetSp(targetTp,mpItem):
9897 kshitij.so 612
    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 613
 
614
def getSalesPotential(lowestOfferPrice,ourNlc):
615
    if lowestOfferPrice - ourNlc < 0:
616
        return 'HIGH'
9897 kshitij.so 617
    elif (float(lowestOfferPrice - ourNlc))/lowestOfferPrice >=0 and (float(lowestOfferPrice - ourNlc))/lowestOfferPrice <=.02:
9881 kshitij.so 618
        return 'MEDIUM'
619
    else:
620
        return 'LOW'  
621
 
622
def main():
623
    itemInfo,spm= populateStuff()
624
    cantCompete, buyBoxItems, competitive, \
625
    competitiveNoInventory, exceptionItems, negativeMargin = decideCategory(itemInfo,spm)
626
    timestamp = datetime.now()
627
    commitExceptionList(exceptionItems,timestamp)
628
    commitCantCompete(cantCompete,timestamp)
629
    commitBuyBox(buyBoxItems,timestamp)
630
    commitCompetitive(competitive,timestamp)
631
    commitCompetitiveNoInventory(competitiveNoInventory,timestamp)
632
    commitNegativeMargin(negativeMargin,timestamp)
9897 kshitij.so 633
    fetchItemsForAutoDecrease(timestamp)
634
    fetchItemsForAutoIncrease(timestamp)
635
 
636
 
9881 kshitij.so 637
if __name__ == '__main__':
638
    main()