Subversion Repositories SmartDukaan

Rev

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