250 lines
12 KiB
Python
250 lines
12 KiB
Python
import logging
|
|
from dataclasses import dataclass
|
|
from typing import Optional
|
|
from sqlalchemy.orm import Session
|
|
from app.services.base_service import BaseService
|
|
from app.models.inventory_management import InventoryItem, MarketplaceListing, PhysicalItem
|
|
from app.models.tcgplayer_inventory import TCGPlayerInventory
|
|
from app.models.tcgplayer_products import TCGPlayerPriceHistory, TCGPlayerProduct, MTGJSONSKU
|
|
from app.models.pricing import PricingEvent
|
|
from app.db.database import transaction
|
|
from decimal import Decimal
|
|
from datetime import datetime
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
@dataclass
|
|
class PriceData:
|
|
cost_basis: Optional[Decimal]
|
|
market_price: Optional[Decimal]
|
|
tcg_low: Optional[Decimal]
|
|
tcg_mid: Optional[Decimal]
|
|
direct_low: Optional[Decimal]
|
|
listed_price: Optional[Decimal]
|
|
quantity: int
|
|
lowest_price_for_qty: Optional[Decimal]
|
|
velocity: Optional[Decimal]
|
|
age_of_inventory: Optional[int]
|
|
|
|
|
|
class PricingService(BaseService):
|
|
def __init__(self):
|
|
super().__init__(None)
|
|
|
|
async def get_unmanaged_inventory(self, db: Session):
|
|
#select * from tcgplayer_inventory ti where ti.tcgplayer_sku_id not in (select pi2.tcgplayer_sku_id from marketplace_listings ml
|
|
# join inventory_items ii on ml.inventory_item_id = ii.id
|
|
# join physical_items pi2 on ii.physical_item_id = pi2.id
|
|
# where ml.delisting_date is null and ml.deleted_at is null and ii.deleted_at is null and pi2.deleted_at is null);
|
|
unmanaged_inventory = db.query(TCGPlayerInventory).filter(
|
|
TCGPlayerInventory.tcgplayer_sku_id.notin_(
|
|
db.query(MarketplaceListing.inventory_item.physical_item.tcgplayer_sku_id).join(
|
|
InventoryItem, MarketplaceListing.inventory_item_id == InventoryItem.id
|
|
).join(
|
|
PhysicalItem, InventoryItem.physical_item_id == PhysicalItem.id
|
|
).filter(
|
|
MarketplaceListing.delisting_date.is_(None),
|
|
MarketplaceListing.deleted_at.is_(None),
|
|
InventoryItem.deleted_at.is_(None),
|
|
PhysicalItem.deleted_at.is_(None)
|
|
)
|
|
)
|
|
).all()
|
|
return unmanaged_inventory
|
|
|
|
async def update_prices_for_unmanaged_inventory(self, db: Session):
|
|
unmanaged_inventory = await self.get_unmanaged_inventory(db)
|
|
for inventory in unmanaged_inventory:
|
|
inventory.tcg_marketplace_price = await self.set_price_for_unmanaged_inventory(db, inventory)
|
|
|
|
async def set_price_for_unmanaged_inventory(self, db: Session, inventory: TCGPlayerInventory):
|
|
# available columns
|
|
# id, tcgplayer_sku_id, product_line, set_name, product_name, title,
|
|
# number, rarity, condition, tcg_market_price, tcg_direct_low,
|
|
# tcg_low_price_with_shipping, tcg_low_price, total_quantity, add_to_quantity,
|
|
# tcg_marketplace_price, photo_url, created_at, updated_at
|
|
# get mtgjson sku
|
|
mtgjson_sku = db.query(MTGJSONSKU).filter(
|
|
MTGJSONSKU.tcgplayer_sku_id == inventory.tcgplayer_sku_id
|
|
).first()
|
|
if mtgjson_sku:
|
|
tcgplayer_product = mtgjson_sku.product
|
|
price_data = PriceData(
|
|
cost_basis=None,
|
|
market_price=Decimal(str(tcgplayer_product.most_recent_tcgplayer_price.market_price)) if tcgplayer_product.most_recent_tcgplayer_price else None,
|
|
tcg_low=Decimal(str(tcgplayer_product.most_recent_tcgplayer_price.low_price)) if tcgplayer_product.most_recent_tcgplayer_price else None,
|
|
tcg_mid=Decimal(str(tcgplayer_product.most_recent_tcgplayer_price.mid_price)) if tcgplayer_product.most_recent_tcgplayer_price else None,
|
|
direct_low=Decimal(str(tcgplayer_product.most_recent_tcgplayer_price.direct_low_price)) if tcgplayer_product.most_recent_tcgplayer_price else None,
|
|
listed_price=inventory.tcg_marketplace_price,
|
|
quantity=inventory.total_quantity,
|
|
lowest_price_for_qty=None,
|
|
velocity=None,
|
|
age_of_inventory=None
|
|
)
|
|
return await self.set_price(db, price_data)
|
|
else:
|
|
return None
|
|
|
|
async def set_price_for_inventory_item(self, db: Session, inventory_item: InventoryItem):
|
|
price_data = PriceData(
|
|
cost_basis=Decimal(str(inventory_item.cost_basis)),
|
|
market_price=Decimal(str(inventory_item.physical_item.sku.product.most_recent_tcgplayer_price.market_price)),
|
|
tcg_low=Decimal(str(inventory_item.physical_item.sku.product.most_recent_tcgplayer_price.low_price)),
|
|
tcg_mid=Decimal(str(inventory_item.physical_item.sku.product.most_recent_tcgplayer_price.mid_price)),
|
|
direct_low=Decimal(str(inventory_item.physical_item.sku.product.most_recent_tcgplayer_price.direct_low_price)),
|
|
listed_price=Decimal(str(inventory_item.marketplace_listing.listed_price)),
|
|
quantity=db.query(TCGPlayerInventory).filter(
|
|
TCGPlayerInventory.tcgplayer_sku_id == inventory_item.physical_item.tcgplayer_sku_id
|
|
).first().total_quantity if db.query(TCGPlayerInventory).filter(
|
|
TCGPlayerInventory.tcgplayer_sku_id == inventory_item.physical_item.tcgplayer_sku_id
|
|
).first() else 0,
|
|
lowest_price_for_qty=None,
|
|
velocity=None,
|
|
age_of_inventory=None
|
|
)
|
|
return await self.set_price(db, price_data, inventory_item)
|
|
|
|
async def set_price(self, db: Session, price_data: PriceData, inventory_item: InventoryItem=None):
|
|
"""
|
|
TODO This sets listed_price per inventory_item but listed_price can only be applied to a product
|
|
however, this may be desired on other marketplaces
|
|
when generating pricing file for tcgplayer, give the option to set min, max, avg price for product?
|
|
"""
|
|
# Fetch base pricing data
|
|
cost_basis = price_data.cost_basis
|
|
market_price = price_data.market_price
|
|
tcg_low = price_data.tcg_low
|
|
tcg_mid = price_data.tcg_mid
|
|
listed_price = price_data.listed_price
|
|
|
|
logger.info(f"listed_price: {listed_price}")
|
|
logger.info(f"market_price: {market_price}")
|
|
logger.info(f"tcg_low: {tcg_low}")
|
|
logger.info(f"tcg_mid: {tcg_mid}")
|
|
logger.info(f"cost_basis: {cost_basis}")
|
|
|
|
# TODO: Add logic to fetch lowest price for seller with same quantity in stock
|
|
# NOT IMPLEMENTED YET
|
|
lowest_price_for_quantity = Decimal('0.0')
|
|
|
|
# Hardcoded configuration values (should be parameterized later)
|
|
shipping_cost = Decimal('1.0')
|
|
tcgplayer_shipping_fee = Decimal('1.31')
|
|
average_cards_per_order = Decimal('3.0')
|
|
marketplace_fee_percentage = Decimal('0.20')
|
|
target_margin = Decimal('0.20')
|
|
velocity_multiplier = Decimal('0.0')
|
|
global_margin_multiplier = Decimal('0.00')
|
|
min_floor_price = Decimal('0.25')
|
|
price_drop_threshold = Decimal('0.20')
|
|
# TODO add age of inventory price decrease multiplier
|
|
age_of_inventory_multiplier = Decimal('0.0')
|
|
|
|
# card cost margin multiplier
|
|
if market_price > 0 and market_price < 2:
|
|
card_cost_margin_multiplier = Decimal('-0.033')
|
|
elif market_price >= 2 and market_price < 10:
|
|
card_cost_margin_multiplier = Decimal('0.0')
|
|
elif market_price >= 10 and market_price < 30:
|
|
card_cost_margin_multiplier = Decimal('0.0125')
|
|
elif market_price >= 30 and market_price < 50:
|
|
card_cost_margin_multiplier = Decimal('0.025')
|
|
elif market_price >= 50 and market_price < 100:
|
|
card_cost_margin_multiplier = Decimal('0.033')
|
|
elif market_price >= 100 and market_price < 200:
|
|
card_cost_margin_multiplier = Decimal('0.05')
|
|
|
|
# Fetch current total quantity in stock for SKU
|
|
quantity_in_stock = price_data.quantity
|
|
|
|
# Determine quantity multiplier based on stock levels
|
|
if quantity_in_stock < 4:
|
|
quantity_multiplier = Decimal('0.0')
|
|
elif quantity_in_stock == 4:
|
|
quantity_multiplier = Decimal('0.2')
|
|
elif 5 <= quantity_in_stock < 10:
|
|
quantity_multiplier = Decimal('0.3')
|
|
elif quantity_in_stock >= 10:
|
|
quantity_multiplier = Decimal('0.4')
|
|
else:
|
|
quantity_multiplier = Decimal('0.0')
|
|
|
|
# Calculate adjusted target margin from base and global multipliers
|
|
adjusted_target_margin = target_margin + global_margin_multiplier + card_cost_margin_multiplier
|
|
|
|
# limit shipping cost offset to 10% of market price
|
|
shipping_cost_offset = min(shipping_cost / average_cards_per_order, market_price * Decimal('0.1'))
|
|
|
|
if cost_basis is None:
|
|
cost_basis = tcg_low * Decimal('0.65')
|
|
# Calculate base price considering cost, shipping, fees, and margin targets
|
|
base_price = (cost_basis + shipping_cost_offset) / (
|
|
(Decimal('1.0') - marketplace_fee_percentage) - adjusted_target_margin
|
|
)
|
|
|
|
# Adjust base price by quantity and velocity multipliers, limit markup to amount of shipping fee
|
|
adjusted_price = min(
|
|
base_price * (Decimal('1.0') + quantity_multiplier + velocity_multiplier - age_of_inventory_multiplier),
|
|
base_price + tcgplayer_shipping_fee
|
|
)
|
|
|
|
# Enforce minimum floor price to ensure profitability
|
|
if adjusted_price < min_floor_price:
|
|
adjusted_price = min_floor_price
|
|
|
|
# Adjust price based on market prices (TCG low and TCG mid)
|
|
if adjusted_price < tcg_low:
|
|
adjusted_price = tcg_mid
|
|
price_used = "tcg mid"
|
|
price_reason = "adjusted price below tcg low"
|
|
elif adjusted_price > tcg_low and adjusted_price < (tcg_mid * Decimal('0.8')):
|
|
adjusted_price = tcg_mid
|
|
price_used = "tcg mid"
|
|
price_reason = f"adjusted price below 80% of tcg mid"
|
|
else:
|
|
price_used = "adjusted price"
|
|
price_reason = "valid price assigned based on margin targets"
|
|
|
|
# TODO: Add logic to adjust price to beat competitor price with same quantity
|
|
# NOT IMPLEMENTED YET
|
|
if adjusted_price < lowest_price_for_quantity:
|
|
adjusted_price = lowest_price_for_quantity - Decimal('0.01')
|
|
price_used = "lowest price for quantity"
|
|
price_reason = "adjusted price below lowest price for quantity"
|
|
|
|
# Fine-tune price to optimize for free shipping promotions
|
|
free_shipping_adjustment = False
|
|
for x in range(1, 5):
|
|
quantity = Decimal(str(x))
|
|
if Decimal('5.00') <= adjusted_price * quantity <= Decimal('5.15'):
|
|
adjusted_price = Decimal('4.99') / quantity
|
|
free_shipping_adjustment = True
|
|
break
|
|
|
|
# prevent price drop over price drop threshold
|
|
if listed_price and adjusted_price < (listed_price * (1 - price_drop_threshold)):
|
|
adjusted_price = listed_price
|
|
price_used = "listed price"
|
|
price_reason = "adjusted price below price drop threshold"
|
|
|
|
# Record pricing event in database transaction
|
|
if inventory_item:
|
|
with transaction(db):
|
|
pricing_event = PricingEvent(
|
|
inventory_item_id=inventory_item.id,
|
|
price=float(adjusted_price),
|
|
price_used=price_used,
|
|
price_reason=price_reason,
|
|
free_shipping_adjustment=free_shipping_adjustment
|
|
)
|
|
db.add(pricing_event)
|
|
|
|
# delete previous pricing events for inventory item
|
|
if inventory_item.marketplace_listing and inventory_item.marketplace_listing.listed_price:
|
|
inventory_item.marketplace_listing.listed_price.deleted_at = datetime.now()
|
|
|
|
return pricing_event
|
|
else:
|
|
return adjusted_price
|
|
# BAD BAD BAD FIX PLS TODO |