Files
Fil-A-Management/filament/bambu_cart.py
T

172 lines
6.5 KiB
Python

import hashlib
import json
from collections import Counter, defaultdict
from dataclasses import dataclass
from http.cookiejar import CookieJar
from urllib.error import URLError
from urllib.parse import urlsplit
from urllib.request import HTTPCookieProcessor, HTTPRedirectHandler, Request, build_opener
from .bambu_eu_variant_ids import BAMBU_EU_PRODUCT_SLUGS, BAMBU_SHOPIFY_VARIANT_IDS
from .models import OrderItem
SHOP_HOST = "bambulab-eu.myshopify.com"
SHOP_URL = f"https://{SHOP_HOST}"
SHOP_VARIANTS = {
(product.casefold(), code, spool, grams, diameter): shop_id
for product, rows in BAMBU_SHOPIFY_VARIANT_IDS.items()
for code, spool, grams, diameter, shop_id in rows
}
SHOP_PRODUCT_NAMES = {"pla silk dual color": "pla silk multi-color"}
class CartQuoteError(Exception):
pass
@dataclass
class CartPlan:
entries: dict
excluded: list
@property
def quantities(self):
return {
shop_id: sum(entry.quantity for entry in rows) for shop_id, rows in self.entries.items()
}
@property
def signature(self):
rows = [
(shop_id, entry.pk, entry.variant_id, entry.quantity)
for shop_id, entries in self.entries.items()
for entry in entries
]
return hashlib.sha256(json.dumps(sorted(rows)).encode()).hexdigest()
@property
def url(self):
if not self.entries:
return ""
items = ",".join(f"{shop_id}:{qty}" for shop_id, qty in sorted(self.quantities.items()))
return f"{SHOP_URL}/cart/{items}?storefront=true"
def plan_cart(entries):
mapped = defaultdict(list)
excluded = []
for entry in entries:
variant = entry.variant
if (
entry.status != OrderItem.Status.OPEN
or variant.manufacturer.name.casefold() != "bambu lab"
):
continue
product = variant.product_type.name.strip().casefold()
product = SHOP_PRODUCT_NAMES.get(product, product)
shop_id = SHOP_VARIANTS.get(
(
product,
variant.manufacturer_color_code.strip(),
variant.spool_type,
variant.net_weight_g,
str(variant.diameter_mm),
)
)
if shop_id and variant.is_active:
mapped[shop_id].append(entry)
continue
reason = (
"Keine eindeutige Shop-Variante" if variant.is_active else "Katalogvariante deaktiviert"
)
slug = BAMBU_EU_PRODUCT_SLUGS.get(product) if variant.is_active else None
product_url = f"https://eu.store.bambulab.com/products/{slug}" if slug else ""
excluded.append((entry, reason, product_url))
return CartPlan(dict(mapped), excluded)
class CartRedirectHandler(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
target = urlsplit(newurl)
if (target.scheme, target.netloc, target.path) != ("https", SHOP_HOST, "/cart"):
raise CartQuoteError("Der Shop hat auf eine andere Seite weitergeleitet.")
return super().redirect_request(req, fp, code, msg, headers, newurl)
def fetch_cart(plan):
browser = build_opener(HTTPCookieProcessor(CookieJar()), CartRedirectHandler())
headers = {"User-Agent": "Mozilla/5.0", "Cache-Control": "no-cache"}
try:
with browser.open(Request(plan.url, headers=headers), timeout=8):
pass
with browser.open(Request(f"{SHOP_URL}/cart.js", headers=headers), timeout=8) as response:
return json.loads(response.read(1024 * 1024))
except (URLError, OSError, ValueError) as error:
raise CartQuoteError(
"Die Warenkorbpreise konnten beim Shop nicht abgerufen werden."
) from error
def _allocate_cents(total, weights):
if not total:
return [0] * len(weights)
divisor = sum(weights)
shares, remainders = zip(*(divmod(total * weight, divisor) for weight in weights), strict=True)
allocations = list(shares)
remaining = total - sum(shares)
for index in sorted(range(len(weights)), key=lambda index: -remainders[index])[:remaining]:
allocations[index] += 1
return allocations
def quote_cart(plan, cart):
if not isinstance(cart, dict) or cart.get("currency") != "EUR":
raise CartQuoteError("Der Shop hat keinen Warenkorb in Euro geliefert.")
if not isinstance(cart.get("items"), list) or type(cart.get("total_price")) is not int:
raise CartQuoteError("Der Shop hat unvollständige Preisdaten geliefert.")
quantities = Counter()
prices = Counter()
for line in cart["items"]:
if not isinstance(line, dict):
raise CartQuoteError("Der Shop hat unvollständige Preisdaten geliefert.")
shop_id, quantity, cents = (
line.get(key) for key in ("variant_id", "quantity", "final_line_price")
)
if (
any(type(value) is not int for value in (shop_id, quantity, cents))
or quantity < 1
or cents < 0
):
raise CartQuoteError("Der Shop hat unvollständige Preisdaten geliefert.")
quantities[shop_id] += quantity
prices[shop_id] += cents
requested = plan.quantities
if quantities != requested:
missing = []
for shop_id, entries in plan.entries.items():
if quantities[shop_id] != requested[shop_id]:
missing.append(
f"{entries[0].variant} ({quantities[shop_id]} von {requested[shop_id]} im Shop)"
)
extra = (
" Der Shop hat weitere Artikel hinzugefügt."
if quantities.keys() - plan.entries.keys()
else ""
)
raise CartQuoteError(
"Der Inhalt des Shop-Warenkorbs weicht von der Liste ab. " + ", ".join(missing) + extra
)
shop_ids = sorted(prices)
total = cart["total_price"]
if not 0 <= total <= sum(prices.values()) or total > 2_147_483_647:
raise CartQuoteError("Die Warensumme aus dem Shop konnte nicht abgeglichen werden.")
# Some discounts are applied to the whole cart and not included in the line prices.
shop_totals = _allocate_cents(total, [prices[shop_id] for shop_id in shop_ids])
result = {}
for shop_id, cents in zip(shop_ids, shop_totals, strict=True):
entries = sorted(plan.entries[shop_id], key=lambda entry: entry.pk)
per_order = _allocate_cents(cents, [entry.quantity for entry in entries])
result.update((entry.pk, price) for entry, price in zip(entries, per_order, strict=True))
return result