Oxinto-AI / services /offer.py
Ahsan
Initial deploy: Oxinto AI FastAPI backend
bd1531f
Raw History Blame Contribute Delete
3.02 kB
"""
Offer Service — builds 3-tier recommendations.
Basic: top 2 CHEAPEST products with score >= 50
Intermediate: top 4 by score, excluding Basic products
Premium: highest scorer not in Basic or Intermediate + optional bundle
"""
from typing import List, Dict, Optional, Set
TIER_THRESHOLDS = {"basic": 50, "premium": 85}
BUNDLE_DISCOUNT_PERCENT = 10
ACCESSORIES = {
"en": ["Premium carry case", "3-year extended warranty", "Extra cable set", "Audio adapter kit"],
"pt": ["Estojo de transporte premium", "Garantia estendida 3 anos", "Kit de cabos extras", "Kit adaptador de áudio"],
}
def build_basic_tier(scored: List[Dict], used_ids: Set[int]) -> List[Dict]:
"""Top 2 cheapest products with score >= 50."""
eligible = [p for p in scored if p.get("score", 0) >= TIER_THRESHOLDS["basic"]]
eligible.sort(key=lambda p: p.get("price", 0))
result = eligible[:2]
for p in result:
used_ids.add(p["id"])
return result
def build_intermediate_tier(scored: List[Dict], used_ids: Set[int]) -> List[Dict]:
"""Top 4 by score, excluding Basic products."""
eligible = [
p for p in scored
if p.get("score", 0) >= TIER_THRESHOLDS["basic"] and p["id"] not in used_ids
]
result = eligible[:4]
for p in result:
used_ids.add(p["id"])
return result
def build_premium_tier(scored: List[Dict], context: Dict, lang: str, used_ids: Set[int]) -> Optional[Dict]:
"""Highest scorer not already in Basic or Intermediate."""
best = next((p for p in scored if p["id"] not in used_ids), None)
if not best:
return None
used_ids.add(best["id"])
is_high_confidence = best.get("score", 0) >= TIER_THRESHOLDS["premium"]
accessories = ACCESSORIES.get(lang, ACCESSORIES["en"])
bundle_items = accessories[:2]
base_price = best.get("price", 0)
accessory_value = base_price * 0.3
bundle_total = base_price + accessory_value
discounted = round(bundle_total * (1 - BUNDLE_DISCOUNT_PERCENT / 100), 2)
premium: Dict = {"product": {**best, "is_high_confidence": is_high_confidence}}
wants_bundle = context.get("wants_bundle", False)
if wants_bundle or is_high_confidence:
premium["bundle"] = {
"items": bundle_items,
"original_price": round(bundle_total, 2),
"discount_percent": BUNDLE_DISCOUNT_PERCENT,
"total_price": discounted,
"savings": round(bundle_total - discounted, 2),
}
return premium
def build_tiered_offers(scored: List[Dict], context: Dict, lang: str = "en") -> Dict:
"""
Build the 3-tier offer structure.
No product can appear in more than one tier.
"""
used_ids: Set[int] = set()
basic = build_basic_tier(scored, used_ids)
intermediate = build_intermediate_tier(scored, used_ids)
premium = build_premium_tier(scored, context, lang, used_ids)
return {
"basic": basic,
"intermediate": intermediate,
"premium": premium,
}