diff --git a/config/urls.py b/config/urls.py index 308cc4b..0db6d66 100644 --- a/config/urls.py +++ b/config/urls.py @@ -73,6 +73,7 @@ urlpatterns = [ path("bestand//loeschen/", views.inventory_delete, name="inventory_delete"), path("bestand//anbieten/", views.marketplace_offer, name="marketplace_offer"), path("bestellung/", views.orders, name="orders"), + path("bestellung/bambu-warenkorb/", views.bambu_order_cart, name="bambu_order_cart"), path("bestellung/historie/", views.order_history, name="order_history"), path( "bestellung/historie//uebergabe-rueckgaengig/", diff --git a/filament/bambu_cart.py b/filament/bambu_cart.py new file mode 100644 index 0000000..2c6dd2c --- /dev/null +++ b/filament/bambu_cart.py @@ -0,0 +1,171 @@ +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 diff --git a/filament/bambu_eu_variant_ids.py b/filament/bambu_eu_variant_ids.py new file mode 100644 index 0000000..4274618 --- /dev/null +++ b/filament/bambu_eu_variant_ids.py @@ -0,0 +1,377 @@ +"""Bambu Lab EU Shopify variant IDs and EU product links.""" + +# Shopify catalog verified against the Bambu Lab EU filament collection products.json. +# Product, then (colour code, spool type, grams, diameter in mm, Shopify variant ID). +BAMBU_SHOPIFY_VARIANT_IDS = { + "ABS": ( + ("40100", "refill", 1000, "1.75", 42917259083995), + ("40100", "spool", 1000, "1.75", 46963746046300), + ("40101", "refill", 1000, "1.75", 42917259051227), + ("40101", "spool", 1000, "1.75", 46963744145756), + ("40102", "refill", 1000, "1.75", 49503790596444), + ("40102", "spool", 1000, "1.75", 46841277022556), + ("40200", "refill", 1000, "1.75", 42917259116763), + ("40300", "refill", 1000, "1.75", 48953684394332), + ("40402", "refill", 1000, "1.75", 49130709418332), + ("40500", "refill", 1000, "1.75", 48953688850780), + ("40502", "refill", 1000, "1.75", 49037506216284), + ("40600", "refill", 1000, "1.75", 42917259182299), + ("40601", "refill", 1000, "1.75", 49130708730204), + ("40602", "refill", 1000, "1.75", 49130708009308), + ), + "ABS-GF": ( + ("41100", "spool", 1000, "1.75", 48011475845468), + ("41101", "spool", 1000, "1.75", 48011475911004), + ("41102", "spool", 1000, "1.75", 48011475878236), + ("41200", "spool", 1000, "1.75", 48011475779932), + ("41300", "spool", 1000, "1.75", 48011475714396), + ("41400", "spool", 1000, "1.75", 48011475812700), + ("41500", "spool", 1000, "1.75", 48011475747164), + ("41600", "spool", 1000, "1.75", 48725868872028), + ), + "ASA": ( + ("45100", "spool", 1000, "1.75", 46930444353884), + ("45101", "spool", 1000, "1.75", 46930444222812), + ("45102", "spool", 1000, "1.75", 46930444255580), + ("45200", "spool", 1000, "1.75", 46930444288348), + ("45500", "spool", 1000, "1.75", 46930444386652), + ("45600", "spool", 1000, "1.75", 46930444321116), + ), + "ASA Aero": (("46100", "spool", 1000, "1.75", 47966894096732),), + "ASA-CF": (("46101", "spool", 1000, "1.75", 49410590409052),), + "PA6-CF (1 kg)": (("72100", "spool", 1000, "1.75", 47023571534172),), + "PA6-CF (500 g)": (("72100", "spool", 500, "1.75", 47023571468636),), + "PA6-GF": ( + ("72102", "spool", 1000, "1.75", 47833416270172), + ("72103", "spool", 1000, "1.75", 47833416302940), + ("72104", "spool", 1000, "1.75", 47833416335708), + ("72200", "spool", 1000, "1.75", 47833416139100), + ("72400", "spool", 1000, "1.75", 47833416171868), + ("72500", "spool", 1000, "1.75", 47833416204636), + ("72600", "spool", 1000, "1.75", 47833416106332), + ("72800", "spool", 1000, "1.75", 47833416237404), + ), + "PAHT-CF (1 kg)": (("70100", "spool", 1000, "1.75", 43923846889691),), + "PAHT-CF (500 g)": (("70100", "spool", 500, "1.75", 43923846856923),), + "PC": ( + ("60100", "spool", 1000, "1.75", 43408627138779), + ("60101", "spool", 1000, "1.75", 46673173807452), + ("60102", "spool", 1000, "1.75", 43408627106011), + ("60103", "spool", 1000, "1.75", 46673173774684), + ), + "PC FR": ( + ("63100", "spool", 1000, "1.75", 53649920950620), + ("63101", "spool", 1000, "1.75", 53649920983388), + ("63102", "spool", 1000, "1.75", 53649921016156), + ), + "PET-CF (1 kg)": (("71100", "spool", 1000, "1.75", 44012072763611),), + "PET-CF (500 g)": (("71100", "spool", 500, "1.75", 44012072730843),), + "PETG HF": ( + ("33100", "refill", 1000, "1.75", 49068714623324), + ("33100", "spool", 1000, "1.75", 49068714787164), + ("33101", "refill", 1000, "1.75", 49068714688860), + ("33101", "spool", 1000, "1.75", 49068714852700), + ("33102", "refill", 1000, "1.75", 49068714590556), + ("33102", "spool", 1000, "1.75", 49068714754396), + ("33103", "refill", 1000, "1.75", 49503342920028), + ("33200", "refill", 1000, "1.75", 49068714557788), + ("33200", "spool", 1000, "1.75", 49068714721628), + ("33300", "refill", 1000, "1.75", 49068714492252), + ("33400", "refill", 1000, "1.75", 49068714459484), + ("33401", "refill", 1000, "1.75", 49503344034140), + ("33500", "refill", 1000, "1.75", 49068714525020), + ("33501", "refill", 1000, "1.75", 49503344427356), + ("33502", "refill", 1000, "1.75", 49503341511004), + ("33600", "refill", 1000, "1.75", 49068714656092), + ("33600", "spool", 1000, "1.75", 49068714819932), + ("33601", "refill", 1000, "1.75", 49503345246556), + ("33801", "refill", 1000, "1.75", 49503342625116), + ), + "PETG Translucent": ( + ("32100", "refill", 1000, "1.75", 49271784472924), + ("32101", "refill", 1000, "1.75", 48786708922716), + ("32101", "spool", 1000, "1.75", 48055896047964), + ("32200", "refill", 1000, "1.75", 49074123145564), + ("32300", "refill", 1000, "1.75", 49130706469212), + ("32500", "refill", 1000, "1.75", 49130705977692), + ("32501", "refill", 1000, "1.75", 49074122162524), + ("32501", "spool", 1000, "1.75", 47502089290076), + ("32600", "refill", 1000, "1.75", 49192018149724), + ("32600", "spool", 1000, "1.75", 47502089191772), + ("32700", "refill", 1000, "1.75", 49130706829660), + ("32800", "refill", 1000, "1.75", 49192019788124), + ), + "PETG-CF": ( + ("31100", "refill", 1000, "1.75", 49238020686172), + ("31100", "spool", 1000, "1.75", 43982559412443), + ("31101", "spool", 1000, "1.75", 47228683714908), + ("31200", "spool", 1000, "1.75", 46935828300124), + ("31500", "spool", 1000, "1.75", 46935828365660), + ("31600", "spool", 1000, "1.75", 46935828332892), + ("31700", "spool", 1000, "1.75", 46935828267356), + ), + "PLA Aero": ( + ("14102", "spool", 1000, "1.75", 46953506505052), + ("14104", "spool", 1000, "1.75", 49078101279068), + ), + "PLA Basic": ( + ("10100", "refill", 1000, "1.75", 42911327846619), + ("10100", "spool", 1000, "1.75", 43992829919451), + ("10101", "refill", 1000, "1.75", 43923829129435), + ("10101", "spool", 1000, "1.75", 43992830017755), + ("10102", "refill", 1000, "1.75", 42911328010459), + ("10103", "refill", 1000, "1.75", 42911327944923), + ("10103", "spool", 1000, "1.75", 46956524241244), + ("10104", "refill", 1000, "1.75", 49299256148316), + ("10105", "refill", 1000, "1.75", 49299261423964), + ("10200", "refill", 1000, "1.75", 42911328239835), + ("10200", "spool", 1000, "1.75", 43992829952219), + ("10201", "refill", 1000, "1.75", 42911327977691), + ("10202", "refill", 1000, "1.75", 47794655068508), + ("10203", "refill", 1000, "1.75", 42911328141531), + ("10204", "refill", 1000, "1.75", 49636028285276), + ("10204", "spool", 1000, "1.75", 53951742509404), + ("10205", "refill", 1000, "1.75", 49636008395100), + ("10300", "refill", 1000, "1.75", 42911327879387), + ("10301", "refill", 1000, "1.75", 49636029530460), + ("10301", "spool", 1000, "1.75", 53951744213340), + ("10400", "refill", 1000, "1.75", 42911328043227), + ("10401", "refill", 1000, "1.75", 47794656706908), + ("10402", "refill", 1000, "1.75", 49636014031196), + ("10402", "spool", 1000, "1.75", 53951741002076), + ("10501", "refill", 1000, "1.75", 47794655461724), + ("10501", "spool", 1000, "1.75", 46673378607452), + ("10502", "refill", 1000, "1.75", 47794656477532), + ("10502", "spool", 1000, "1.75", 54004770537820), + ("10503", "refill", 1000, "1.75", 49636024353116), + ("10601", "refill", 1000, "1.75", 42911327912155), + ("10601", "spool", 1000, "1.75", 46738546622812), + ("10602", "refill", 1000, "1.75", 42911328075995), + ("10603", "refill", 1000, "1.75", 47794657329500), + ("10603", "spool", 1000, "1.75", 54004785217884), + ("10604", "refill", 1000, "1.75", 49636029006172), + ("10605", "refill", 1000, "1.75", 49636016783708), + ("10700", "refill", 1000, "1.75", 47794657362268), + ("10701", "refill", 1000, "1.75", 49636021436764), + ("10701", "spool", 1000, "1.75", 53951741821276), + ("10800", "refill", 1000, "1.75", 42911328207067), + ("10801", "refill", 1000, "1.75", 47794655101276), + ("10802", "refill", 1000, "1.75", 49636027236700), + ("10802", "spool", 1000, "1.75", 53951748702556), + ), + "PLA Basic Gradient": ( + ("10900", "spool", 1000, "1.75", 46901930492252), + ("10901", "spool", 1000, "1.75", 46901930525020), + ("10902", "spool", 1000, "1.75", 46901930557788), + ("10903", "spool", 1000, "1.75", 53638219071836), + ("10904", "spool", 1000, "1.75", 53638219104604), + ("10905", "spool", 1000, "1.75", 53638219006300), + ("10906", "spool", 1000, "1.75", 53687078420828), + ("10907", "spool", 1000, "1.75", 53638219039068), + ), + "PLA Galaxy": ( + ("13203", "spool", 1000, "1.75", 47730388074844), + ("13503", "spool", 1000, "1.75", 47730388107612), + ("13504", "spool", 1000, "1.75", 47730388140380), + ("13602", "spool", 1000, "1.75", 47730388173148), + ), + "PLA Glow": ( + ("15200", "spool", 1000, "1.75", 47396823630172), + ("15300", "spool", 1000, "1.75", 47396823531868), + ("15400", "spool", 1000, "1.75", 47396823662940), + ("15500", "spool", 1000, "1.75", 47396823597404), + ("15600", "spool", 1000, "1.75", 47396823564636), + ), + "PLA Marble": ( + ("13103", "spool", 1000, "1.75", 43964050964699), + ("13201", "spool", 1000, "1.75", 46756997333340), + ), + "PLA Matte": ( + ("11100", "refill", 1000, "1.75", 42996742586587), + ("11100", "spool", 1000, "1.75", 43992833229019), + ("11101", "refill", 1000, "1.75", 42996742750427), + ("11101", "spool", 1000, "1.75", 43992833261787), + ("11102", "refill", 1000, "1.75", 42996742619355), + ("11102", "spool", 1000, "1.75", 43992833327323), + ("11103", "refill", 1000, "1.75", 53926028607836), + ("11104", "refill", 1000, "1.75", 53926028837212), + ("11200", "refill", 1000, "1.75", 42996742848731), + ("11200", "spool", 1000, "1.75", 43992833294555), + ("11201", "refill", 1000, "1.75", 42996742684891), + ("11202", "refill", 1000, "1.75", 47794659164508), + ("11203", "refill", 1000, "1.75", 53926028804444), + ("11204", "refill", 1000, "1.75", 53926028640604), + ("11300", "refill", 1000, "1.75", 42996742652123), + ("11300", "spool", 1000, "1.75", 46893218038108), + ("11400", "refill", 1000, "1.75", 42996742717659), + ("11401", "refill", 1000, "1.75", 48612736401756), + ("11500", "refill", 1000, "1.75", 42996742783195), + ("11501", "refill", 1000, "1.75", 47794659656028), + ("11502", "refill", 1000, "1.75", 53926028706140), + ("11600", "refill", 1000, "1.75", 42996751073499), + ("11600", "spool", 1000, "1.75", 43992833360091), + ("11601", "refill", 1000, "1.75", 42996742881499), + ("11602", "refill", 1000, "1.75", 47794659688796), + ("11603", "refill", 1000, "1.75", 53926028673372), + ("11700", "refill", 1000, "1.75", 42996742914267), + ("11800", "refill", 1000, "1.75", 42996742815963), + ("11801", "refill", 1000, "1.75", 47794659426652), + ("11802", "refill", 1000, "1.75", 53926028738908), + ("11803", "refill", 1000, "1.75", 53926028771676), + ), + "PLA Metal": ( + ("13100", "spool", 1000, "1.75", 46797850902876), + ("13400", "spool", 1000, "1.75", 46797851099484), + ("13500", "spool", 1000, "1.75", 43959185277147), + ("13600", "spool", 1000, "1.75", 43959185244379), + ("13800", "spool", 1000, "1.75", 43959185015003), + ), + "PLA Silk Multi-Color": ( + ("13901", "spool", 1000, "1.75", 47489270776156), + ("13902", "spool", 1000, "1.75", 47489270808924), + ("13903", "spool", 1000, "1.75", 47489270841692), + ("13904", "spool", 1000, "1.75", 47489270874460), + ("13905", "spool", 1000, "1.75", 53515458085212), + ), + "PLA Silk+": ( + ("13108", "spool", 1000, "1.75", 53583205925212), + ("13109", "spool", 1000, "1.75", 53583205826908), + ("13110", "spool", 1000, "1.75", 53583205794140), + ("13205", "spool", 1000, "1.75", 53583205663068), + ("13206", "spool", 1000, "1.75", 53583205957980), + ("13207", "spool", 1000, "1.75", 53583205761372), + ("13404", "spool", 1000, "1.75", 53583205990748), + ("13405", "spool", 1000, "1.75", 53583205859676), + ("13506", "spool", 1000, "1.75", 53583205630300), + ("13507", "spool", 1000, "1.75", 53583205892444), + ("13603", "spool", 1000, "1.75", 53583206023516), + ("13604", "spool", 1000, "1.75", 53583205695836), + ("13702", "spool", 1000, "1.75", 53583205728604), + ), + "PLA Sparkle": ( + ("13101", "spool", 1000, "1.75", 43959190946011), + ("13102", "spool", 1000, "1.75", 46797853163868), + ("13200", "spool", 1000, "1.75", 43959190913243), + ("13402", "spool", 1000, "1.75", 48725896266076), + ("13501", "spool", 1000, "1.75", 43959190880475), + ("13700", "spool", 1000, "1.75", 46797853032796), + ), + "PLA Translucent": ( + ("13210", "spool", 1000, "1.75", 54345716695388), + ("13211", "spool", 1000, "1.75", 54407223050588), + ("13301", "spool", 1000, "1.75", 54345716662620), + ("13410", "spool", 1000, "1.75", 54407223017820), + ("13510", "spool", 1000, "1.75", 54407222985052), + ("13610", "spool", 1000, "1.75", 54407223083356), + ("13611", "spool", 1000, "1.75", 54345716597084), + ("13612", "spool", 1000, "1.75", 54345716564316), + ("13710", "spool", 1000, "1.75", 54345716629852), + ("13711", "spool", 1000, "1.75", 54407223116124), + ), + "PLA Wood": ( + ("13106", "spool", 1000, "1.75", 53441583186268), + ("13107", "spool", 1000, "1.75", 53441583055196), + ("13204", "spool", 1000, "1.75", 53441583087964), + ("13403", "spool", 1000, "1.75", 53441583219036), + ("13505", "spool", 1000, "1.75", 53441583153500), + ("13801", "spool", 1000, "1.75", 53441583120732), + ), + "PLA-CF": ( + ("14100", "refill", 1000, "1.75", 49200517448028), + ("14100", "spool", 1000, "1.75", 43944001994971), + ("14101", "refill", 1000, "1.75", 49238028845404), + ("14101", "spool", 1000, "1.75", 46702306296156), + ("14200", "spool", 1000, "1.75", 46702306230620), + ("14500", "spool", 1000, "1.75", 46797856342364), + ("14600", "spool", 1000, "1.75", 46702306263388), + ("14601", "spool", 1000, "1.75", 47068316565852), + ("14700", "spool", 1000, "1.75", 47068316598620), + ), + "PPA-CF": (("73100", "spool", 750, "1.75", 49237640642908),), + "PPS-CF": (("76100", "spool", 750, "1.75", 49259815731548),), + "PVA": (("66400", "spool", 500, "1.75", 47790189281628),), + "Support for ABS": (("66100", "spool", 500, "1.75", 49063577420124),), + "Support for PA/PET": (("65500", "spool", 500, "1.75", 43050119364827),), + "Support for PLA (New Version)": (("65104", "spool", 500, "1.75", 54200625725788),), + "Support for PLA/PETG": ( + ("65102", "spool", 500, "1.75", 48921550553436), + ("65103", "spool", 500, "1.75", 53534477320540), + ), + "TPU 85A": ( + ("51305", "spool", 1000, "1.75", 54085774410076), + ("51500", "spool", 1000, "1.75", 54085774442844), + ), + "TPU 90A": ( + ("51103", "spool", 1000, "1.75", 54085774541148), + ("51105", "spool", 1000, "1.75", 54085774475612), + ("51900", "spool", 1000, "1.75", 54085774508380), + ("51901", "spool", 1000, "1.75", 54084062511452), + ), + "TPU 95A HF": ( + ("51100", "spool", 1000, "1.75", 47305218687324), + ("51101", "spool", 1000, "1.75", 47305218785628), + ("51102", "spool", 1000, "1.75", 47305218752860), + ("51200", "spool", 1000, "1.75", 47305218883932), + ("51400", "spool", 1000, "1.75", 47305218818396), + ("51600", "spool", 1000, "1.75", 47305218851164), + ), + "TPU for AMS": ( + ("53100", "spool", 1000, "1.75", 53421837320540), + ("53101", "spool", 1000, "1.75", 53421837386076), + ("53102", "spool", 1000, "1.75", 53421837353308), + ("53200", "spool", 1000, "1.75", 53421837189468), + ("53400", "spool", 1000, "1.75", 53421837222236), + ("53500", "spool", 1000, "1.75", 53421837287772), + ("53600", "spool", 1000, "1.75", 53421837255004), + ), +} + +BAMBU_EU_PRODUCT_SLUGS = { + "abs": "abs-filament", + "abs-gf": "abs-gf", + "asa": "asa-filament", + "asa aero": "asa-aero", + "asa-cf": "asa-cf", + "pa6-cf (1 kg)": "pa6-cf", + "pa6-cf (500 g)": "pa6-cf", + "pa6-gf": "pa6-gf", + "paht-cf (1 kg)": "paht-cf", + "paht-cf (500 g)": "paht-cf", + "pc": "pc-filament", + "pc fr": "pc-fr", + "pet-cf (1 kg)": "pet-cf", + "pet-cf (500 g)": "pet-cf", + "petg basic": "petg-basic", + "petg matte": "petg-matte", + "petg translucent": "petg-translucent", + "petg-cf": "petg-cf", + "pla aero": "pla-aero", + "pla basic": "pla-basic-filament", + "pla basic gradient": "pla-basic-gradient", + "pla galaxy": "pla-galaxy", + "pla glow": "pla-glow", + "pla marble": "pla-marble", + "pla matte": "pla-matte", + "pla metal": "pla-metal", + "pla palette": "pla-palette", + "pla pure": "pla-pure", + "pla silk multi-color": "pla-silk-multi-color", + "pla silk+": "pla-silk-upgrade", + "pla sparkle": "pla-sparkle", + "pla tough+": "pla-tough-upgrade", + "pla translucent": "pla-translucent", + "pla wood": "pla-wood", + "pla-cf": "pla-cf", + "ppa-cf": "ppa-cf", + "pps-cf": "pps-cf", + "pva": "pva", + "support for abs": "support-for-abs", + "support for pa/pet": "support-for-pa-pet", + "support for pla (new version)": "support-for-pla-new", + "support for pla/petg": "support-for-pla-petg", + "tpu 75a (2.85mm)": "tpu-75a-2-85mm", + "tpu 85a": "tpu-85a-tpu-90a", + "tpu 90a": "tpu-85a-tpu-90a", + "tpu 95a hf": "tpu-95a-hf", + "tpu for ams": "tpu-for-ams", +} diff --git a/filament/migrations/0023_order_bambu_quote.py b/filament/migrations/0023_order_bambu_quote.py new file mode 100644 index 0000000..54dd8e5 --- /dev/null +++ b/filament/migrations/0023_order_bambu_quote.py @@ -0,0 +1,32 @@ +# Generated by Django 5.2.19 on 2026-11-26 19:48 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("filament", "0022_marketplace_keep_history_on_seller_delete"), + ] + + operations = [ + migrations.AddField( + model_name="orderitem", + name="bambu_quote_cents", + field=models.PositiveIntegerField(editable=False, null=True), + ), + migrations.AddField( + model_name="orderitem", + name="bambu_quote_quantity", + field=models.PositiveSmallIntegerField(editable=False, null=True), + ), + migrations.AddField( + model_name="orderitem", + name="bambu_quote_signature", + field=models.CharField(blank=True, editable=False, max_length=64), + ), + migrations.AddField( + model_name="orderitem", + name="bambu_quoted_at", + field=models.DateTimeField(editable=False, null=True), + ), + ] diff --git a/filament/models.py b/filament/models.py index 3920393..58e9a93 100644 --- a/filament/models.py +++ b/filament/models.py @@ -424,6 +424,10 @@ class OrderItem(QuantityPosition): handover_remainder = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="+" ) + bambu_quote_cents = models.PositiveIntegerField(null=True, editable=False) + bambu_quote_quantity = models.PositiveSmallIntegerField(null=True, editable=False) + bambu_quote_signature = models.CharField(max_length=64, blank=True, editable=False) + bambu_quoted_at = models.DateTimeField(null=True, editable=False) class Meta(QuantityPosition.Meta): constraints = [ @@ -448,6 +452,17 @@ class OrderItem(QuantityPosition): def is_pending(self): return self.status in self.PENDING_STATUSES + @property + def bambu_line_total(self): + if self.bambu_quote_cents is not None and self.quantity == self.bambu_quote_quantity: + return Decimal(self.bambu_quote_cents) / 100 + return None + + @property + def bambu_unit_price(self): + total = self.bambu_line_total + return total / self.quantity if total is not None else None + class Printer(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) diff --git a/filament/static/filament/app.css b/filament/static/filament/app.css index 88631c7..341f522 100644 --- a/filament/static/filament/app.css +++ b/filament/static/filament/app.css @@ -738,6 +738,27 @@ td.quantity { .actions a + a { margin-left: 14px; } +.order-cart-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; +} +.order-person-total { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: space-between; + gap: 6px 20px; + border-top: 1px solid var(--line); + padding: 14px 22px; + background: var(--table-heading); + font-size: 13px; +} +.order-person-total strong { + margin-left: 4px; + color: var(--green); + font-variant-numeric: tabular-nums; +} .danger-link, .warning { color: var(--danger); diff --git a/filament/tests/test_bambu_cart.py b/filament/tests/test_bambu_cart.py new file mode 100644 index 0000000..a28a4fc --- /dev/null +++ b/filament/tests/test_bambu_cart.py @@ -0,0 +1,157 @@ +from unittest.mock import patch + +from django.test import Client +from django.urls import reverse + +from filament.bambu_cart import plan_cart +from filament.models import OrderItem + +from .base import CatalogTestCase + +WHITE_SPOOL = 43992829919451 +COBALT_REFILL = 49636029006172 + + +def shop_line(shop_id, quantity, cents): + return {"variant_id": shop_id, "quantity": quantity, "final_line_price": cents} + + +class BambuCartTests(CatalogTestCase): + def setUp(self): + self.product.name = "PLA Basic" + self.product.save() + self.spool.manufacturer_color_code = "10100" + self.refill.manufacturer_color_code = "10604" + for variant in (self.spool, self.refill): + variant.net_weight_g = 1000 + variant.diameter_mm = "1.75" + variant.save() + self.first = OrderItem.objects.create(owner=self.alice, variant=self.spool, quantity=1) + self.second = OrderItem.objects.create(owner=self.bob, variant=self.spool, quantity=2) + self.third = OrderItem.objects.create(owner=self.bob, variant=self.refill, quantity=1) + self.client.force_login(self.alice) + self.url = reverse("bambu_order_cart") + self.cart = { + "currency": "EUR", + "items": [shop_line(WHITE_SPOOL, 3, 7797), shop_line(COBALT_REFILL, 1, 2299)], + "total_price": 10096, + } + + @patch("filament.views.fetch_cart") + def test_open_cart_aggregates_open_wishes_and_persists_prices_per_person(self, fetch): + fetch.return_value = self.cart | {"total_price": 9501} + ordered = OrderItem.objects.create( + owner=self.alice, variant=self.refill, quantity=2, status=OrderItem.Status.ORDERED + ) + unavailable = OrderItem.objects.create( + owner=self.alice, variant=self.refill, quantity=4, status=OrderItem.Status.UNAVAILABLE + ) + response = self.client.post(self.url) + self.assertEqual(response.status_code, 302) + self.assertEqual( + response["Location"], + f"https://bambulab-eu.myshopify.com/cart/{WHITE_SPOOL}:3,{COBALT_REFILL}:1?storefront=true", + ) + for entry in (self.first, self.second, self.third, ordered, unavailable): + entry.refresh_from_db() + self.assertEqual( + sum(entry.bambu_quote_cents for entry in (self.first, self.second, self.third)), 9501 + ) + self.assertEqual(self.first.bambu_quote_cents, 2446) + self.assertEqual(self.second.bambu_quote_cents, 4891) + self.assertEqual(self.third.bambu_quote_cents, 2164) + self.assertIsNone(ordered.bambu_quote_cents) + self.assertIsNone(unavailable.bambu_quote_cents) + self.assertEqual(self.first.status, OrderItem.Status.OPEN) + self.client.force_login(self.bob) + page = self.client.get(reverse("orders")) + self.assertContains( + page, "
Zwischensumme 24,46 €
", html=True + ) + self.assertContains( + page, "
Gesamtbetrag 70,55 €
", html=True + ) + self.assertContains(page, "Für 1 Position fehlt der Preis.", count=1) + for section in page.content.decode().split('class="order-table"')[1:]: + self.assertIn('class="order-person-total"', section.split("", 1)[1]) + + self.third.status = OrderItem.Status.UNAVAILABLE + self.third.save(update_fields=["status"]) + page = self.client.get(reverse("orders")) + self.assertContains( + page, "
Gesamtbetrag 48,91 €
", html=True + ) + self.assertNotContains(page, "70,55 €") + self.assertContains(page, "Preise vor der letzten Listenänderung.") + + @patch("filament.views.fetch_cart") + def test_preview_warns_about_unmapped_variants_and_keeps_price_for_mapped_rows(self, fetch): + OrderItem.objects.create(owner=self.bob, variant=self.black_spool, quantity=5) + fetch.return_value = self.cart + page = self.client.post(self.url) + self.assertContains(page, "Keine eindeutige Shop-Variante") + self.assertContains(page, "Warenkorb im Shop prüfen") + self.first.refresh_from_db() + self.assertEqual(self.first.bambu_quote_cents, 2599) + + @patch("filament.views.fetch_cart") + def test_stock_shortage_leaves_existing_prices_intact(self, fetch): + fetch.return_value = self.cart + self.assertRedirects(self.client.post(self.url, {"action": "prices"}), reverse("orders")) + fetch.return_value = self.cart | { + "items": [shop_line(WHITE_SPOOL, 2, 4000), shop_line(COBALT_REFILL, 1, 1000)], + "total_price": 5000, + } + page = self.client.post(self.url) + self.assertContains(page, "2 von 3 im Shop") + self.first.refresh_from_db() + self.assertEqual(self.first.bambu_quote_cents, 2599) + + @patch("filament.views.fetch_cart") + def test_concurrent_change_prevents_overwriting_prices_or_opening_old_cart(self, fetch): + def shop_response(plan): + OrderItem.objects.filter(pk=self.second.pk).update(quantity=1) + return self.cart + + fetch.side_effect = shop_response + page = self.client.post(self.url) + self.assertContains(page, "Die Bestellliste hat sich geändert") + self.assertNotContains(page, "Warenkorb im Shop prüfen") + self.first.refresh_from_db() + self.assertIsNone(self.first.bambu_quote_cents) + + @patch("filament.views.fetch_cart") + def test_a_changed_cart_marks_other_open_prices_as_stale(self, fetch): + fetch.return_value = self.cart + self.client.post(self.url) + OrderItem.objects.filter(pk=self.second.pk).update(quantity=1) + page = self.client.get(reverse("orders")) + self.assertContains(page, "Bestellliste geändert", count=2) + self.assertNotContains(page, "51,98 €") + + @patch("filament.views.fetch_cart") + def test_cart_action_requires_login_post_and_csrf(self, fetch): + self.assertEqual(self.client.get(self.url).status_code, 405) + self.client.logout() + self.assertEqual(self.client.post(self.url).status_code, 302) + csrf = Client(enforce_csrf_checks=True) + csrf.force_login(self.alice) + self.assertEqual(csrf.post(self.url).status_code, 403) + fetch.assert_not_called() + + def test_silk_dual_uses_the_shop_multi_color_listing(self): + self.product.name = "PLA Silk Dual Color" + self.product.save(update_fields=["name"]) + self.spool.manufacturer_color_code = "13901" + self.spool.save(update_fields=["manufacturer_color_code"]) + plan = plan_cart(OrderItem.objects.filter(pk=self.first.pk)) + self.assertEqual(len(plan.entries), 1) + self.assertEqual(plan.excluded, []) + + self.spool.manufacturer_color_code = "13909" + self.spool.save(update_fields=["manufacturer_color_code"]) + plan = plan_cart(OrderItem.objects.filter(pk=self.first.pk)) + self.assertFalse(plan.entries) + self.assertEqual( + plan.excluded[0][2], "https://eu.store.bambulab.com/products/pla-silk-multi-color" + ) diff --git a/filament/tests/test_orders.py b/filament/tests/test_orders.py index 3b025b1..46c31ec 100644 --- a/filament/tests/test_orders.py +++ b/filament/tests/test_orders.py @@ -106,7 +106,7 @@ class SharedOrderTests(CatalogTestCase): self.client.post("/bestellung/hinzufuegen/", self.selection(self.refill, 4)) response = self.client.get("/bestellung/") self.assertEqual(response.status_code, 200) - groups = dict(response.context["groups"]) + groups = {group["username"]: group["entries"] for group in response.context["groups"]} self.assertEqual( {name: {e.variant_id: e.quantity for e in entries} for name, entries in groups.items()}, {"michael": {self.spool.pk: 2}, "person-zwei": {self.spool.pk: 1, self.refill.pk: 4}}, diff --git a/filament/views.py b/filament/views.py index 2723d75..fb0624f 100644 --- a/filament/views.py +++ b/filament/views.py @@ -14,8 +14,10 @@ from django.db.models.functions import Coalesce from django.http import FileResponse, Http404, HttpResponse, JsonResponse from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse +from django.utils import timezone from django.views.decorators.http import require_http_methods +from .bambu_cart import CartQuoteError, fetch_cart, plan_cart, quote_cart from .forms import ( ArticleLookupForm, AssignEmptySpoolForm, @@ -924,10 +926,30 @@ def orders(request): "pk", ) ) - groups = [ - (username, list(items)) - for username, items in groupby(entries, key=lambda e: e.owner.username) - ] + plan = plan_cart(entries) + signature = plan.signature + groups = [] + for username, items in groupby(entries, key=lambda e: e.owner.username): + positions = list(items) + priced = [entry for entry in positions if entry.bambu_line_total is not None] + for entry in priced: + entry.bambu_quote_stale = entry.status in OrderItem.PENDING_STATUSES and ( + entry.status != OrderItem.Status.OPEN or entry.bambu_quote_signature != signature + ) + payable_count = sum(entry.status != OrderItem.Status.UNAVAILABLE for entry in positions) + priced_payable = [entry for entry in priced if entry.status != OrderItem.Status.UNAVAILABLE] + groups.append( + { + "username": username, + "entries": positions, + "payable_count": payable_count, + "missing_prices": payable_count - len(priced_payable), + "amount": sum(entry.bambu_line_total for entry in priced_payable) + if priced_payable + else None, + "stale_prices": any(entry.bambu_quote_stale for entry in priced_payable), + } + ) return render( request, "filament/orders.html", @@ -936,6 +958,75 @@ def orders(request): "total": sum(entry.quantity for entry in entries), "variant_count": len({entry.variant_id for entry in entries}), "status_choices": OrderItem.Status.choices, + "has_bambu_cart": bool(plan.entries or plan.excluded), + "has_bambu_prices": any(entry.bambu_line_total is not None for entry in entries), + }, + ) + + +def _open_bambu_orders(): + return OrderItem.objects.filter( + status=OrderItem.Status.OPEN, variant__product_type__manufacturer__name__iexact="Bambu Lab" + ).select_related("variant__product_type__manufacturer", "variant__color", "owner") + + +@login_required +@require_http_methods(["POST"]) +def bambu_order_cart(request): + plan = plan_cart(_open_bambu_orders()) + cart_url = plan.url + error = "" + prices_saved = False + if cart_url: + try: + prices = quote_cart(plan, fetch_cart(plan)) + signature = plan.signature + with transaction.atomic(): + current = plan_cart(_open_bambu_orders()) + if current.signature != signature: + raise CartQuoteError( + "Die Bestellliste hat sich geändert. Erstelle den Warenkorb erneut." + ) + now = timezone.now() + positions = [entry for rows in current.entries.values() for entry in rows] + for entry in positions: + entry.bambu_quote_cents = prices[entry.pk] + entry.bambu_quote_quantity = entry.quantity + entry.bambu_quote_signature = signature + entry.bambu_quoted_at = now + OrderItem.objects.bulk_update( + positions, + ( + "bambu_quote_cents", + "bambu_quote_quantity", + "bambu_quote_signature", + "bambu_quoted_at", + ), + ) + prices_saved = True + except CartQuoteError as exc: + error = str(exc) + current = plan_cart(_open_bambu_orders()) + if current.signature != plan.signature: + cart_url = "" + prices_saved = False + error = "Die Bestellliste hat sich geändert. Erstelle den Warenkorb erneut." + plan = current + + prices_only = request.POST.get("action") == "prices" + if prices_saved and not plan.excluded: + messages.success( + request, "Bambu-Lab-Warenkorbpreise wurden für die Sammelbestellung gespeichert." + ) + return redirect("orders" if prices_only else cart_url) + return render( + request, + "filament/bambu_order_cart.html", + { + "cart_url": "" if prices_only else cart_url, + "excluded": plan.excluded, + "error": error, + "prices_saved": prices_saved, }, ) diff --git a/templates/filament/bambu_order_cart.html b/templates/filament/bambu_order_cart.html new file mode 100644 index 0000000..6196505 --- /dev/null +++ b/templates/filament/bambu_order_cart.html @@ -0,0 +1,24 @@ +{% extends "base.html" %} +{% block title %}Bambu-Lab-Warenkorb · Fil-A-Management{% endblock %} +{% block content %} +← Zur Sammelbestellung +

Bambu-Lab-Warenkorb

+
+ {% if error %}

{{ error }}

{% endif %} + {% if prices_saved %}

Die Preise für die zugeordneten Rollen stehen in der Sammelbestellung.

{% endif %} + {% if excluded %} +

Positionen ohne Übernahme

+
    + {% for entry, reason, product_url in excluded %} +
  • {{ entry.owner.username }} · {{ entry.quantity }} × {{ entry.variant }} · {{ reason }}{% if product_url %} · Im aktuellen EU-Shop ansehen{% endif %}
  • + {% endfor %} +
+ {% elif not error and not prices_saved %} +

Es gibt keine offenen Bambu-Lab-Wünsche für den Warenkorb.

+ {% endif %} + +
+{% endblock %} diff --git a/templates/filament/orders.html b/templates/filament/orders.html index 5f7e371..87c0eee 100644 --- a/templates/filament/orders.html +++ b/templates/filament/orders.html @@ -5,18 +5,32 @@

Sammelbestellung

Bestellwünsche und Lieferstatus pro Person.

+ Bestellwunsch hinzufügen +{% if has_bambu_cart %} +
+
+ {% csrf_token %} +
+ + +
+

Für offene Bambu-Lab-Wünsche aller Personen. Beim Öffnen wird ein vorhandener Warenkorb im Shopify-Shop ersetzt.

+
+
+{% endif %}
Rollen insgesamt{{ total }}
Verschiedene Varianten{{ variant_count }}
Personen mit Bestellwünschen{{ groups|length }}
-{% for username, entries in groups %} +{% if has_bambu_prices %}

Shoppreise stammen aus dem Warenkorb zum angegebenen Zeitpunkt. Der Rollenpreis ist der gerundete Durchschnitt je Position. Versand und Preisänderungen beim Bezahlen können den Endbetrag verändern.

{% endif %} +{% for group in groups %} +{% with username=group.username entries=group.entries %}

Bestellwunsch · {{ username }}

- {% if entries.0.owner_id == user.pk %}{% endif %} + {% if has_bambu_prices %}{% endif %}{% if entries.0.owner_id == user.pk %}{% endif %} {% for entry in entries %} @@ -26,6 +40,10 @@ + {% if has_bambu_prices %} + + + {% endif %}
StückProduktartFarbeArtikelnr.SpulenausführungStatusAktionen
StückProduktartFarbeArtikelnr.SpulenausführungPro RollePosition gesamtStatusAktionen
{% include "filament/variant_thumbnail.html" with variant=entry.variant only %}{{ entry.variant.color_label }}
{{ entry.variant.manufacturer_color_code|default:"–" }} {{ entry.variant.get_spool_type_display }}{% if not entry.variant.is_active %}Deaktiviert · Katalogvariante{% endif %}{% if entry.bambu_unit_price is not None %}{{ entry.bambu_unit_price|floatformat:2 }} €{% else %}–{% endif %}{% if entry.bambu_line_total is not None %}{{ entry.bambu_line_total|floatformat:2 }} €{{ entry.bambu_quoted_at|date:"d.m.Y H:i" }}{% if entry.bambu_quote_stale %}Bestellliste geändert{% endif %}{% else %}–{% endif %}
{% csrf_token %} @@ -53,7 +71,23 @@
+
+ {% if group.amount is not None %} +
{% if group.missing_prices %}Zwischensumme{% else %}Gesamtbetrag{% endif %} {{ group.amount|floatformat:2 }} €
+ {% elif group.payable_count %} + Gesamtbetrag offen + {% else %} + Keine verfügbaren Positionen + {% endif %} + {% if group.missing_prices or group.stale_prices %} +
+ {% if group.missing_prices == 1 %}Für 1 Position fehlt der Preis.{% elif group.missing_prices %}Für {{ group.missing_prices }} Positionen fehlen die Preise.{% endif %} + {% if group.stale_prices %}Preise vor der letzten Listenänderung.{% endif %} +
+ {% endif %} +
+{% endwith %} {% empty %}

Keine laufenden Bestellwünsche

Neue Wünsche erscheinen hier nach Person sortiert.

Bestellwunsch hinzufügen
{% endfor %}