Subversion Repositories SmartDukaan

Rev

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