From 1332ad7bc50ff74c229e0ee34e74ed4b19bfe340 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Fri, 6 Nov 2026 16:20:22 +0000 Subject: [PATCH] feat(erpsetup): catalogue for Leistungsbeschreibung 1.0.0, opt-in -sync-catalog (#115) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brings the ERPNext sales catalogue in line with the frozen Leistungsbeschreibungen 1.0.0. This PR changes code and tests only. No ERP was called; the live run is yours, using the erpsetup CLI. ## Dry run first (with the flag; only this path prints `field old → new`) ```sh ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… ERP_WEBHOOK_SECRET=… \ go run ./cmd/erpsetup -webhook-url https://registry.breakpilot.com/v1/internal/erp/webhook -sync-catalog -dry-run ``` (`ERP_LEAD_DOCTYPE` is optional, as before.) Leave out `-dry-run` for the real run. ## What a run does with and without `-sync-catalog` | | without the flag (as today) | with `-sync-catalog` | |---|---|---| | New items, unit "Prüftag", their list prices | created | created | | Item **description** | **updated (this already happens on every run today)** | updated | | Item `item_name`, `disabled` | untouched | updated when they differ | | Standard Selling `price_list_rate` (rows without a customer) | set once, never changed | updated when it differs | | Customer-specific Item Prices | untouched | untouched | | Quote print format (Mehrverbrauch row) | updated | updated | **A plain run is not inert.** It creates the 5 new items, the new unit and 5 new prices, rewrites every changed description, and updates the quote template. Only names, the disabled flags and price changes wait for the flag. Nothing is ever deleted. Only the doctypes Item, Item Price and UOM are touched beyond what erpsetup already manages. ## Catalogue changes | Code | Status | Price old → new (EUR) | |---|---|---| | PLT-CORE-CLD-STD/BUS/ENT | keep (name "Breakpilot …", new text) | 290 / 790 / 1990 (unchanged) | | PLT-BNDL-CLD-STD | **new** Starter-Modulpaket | 990 | | PLT-BNDL-CLD-ADD | **new** Weiteres Modul | 499 | | CRA-CSA-CLD-STD | keep | **1490 → 490** | | CRA-CSA-CLD-BUS | keep | **3990 → 1290** | | CRA-CSA-CLD-ENT | keep | **9900 → 0** (Preis nach Vereinbarung: a quote shows 0,00 € unless the rate is entered by hand) | | CRA-CSA-CLD-TGT | **new** extra Prüfobjekt / Monat | 5.99 | | CRA-CSA-CLD-DAY | **new** Prüftag (unit Prüftag) | 9.99 | | CRA-CSA-CLD-SCAN | **disable** | 12 (unchanged) | | CRA-WBK-CLD-STD/BUS/ENT | **disable** | unchanged | | DEV-WP-CLD-STD | keep ("Werkpilot Cloud") | 59 | | DEV-WP-CLD-BUS/ENT | **disable** | unchanged | | DEV-WP-OPR-*, DEV-FWK-OPR-*, INF-GIT-OPR-*, INF-CI-OPR-* | keep, new texts | unchanged | | DEV-FWK-CLD-STD | keep ("Firmwerk Cloud") | 89 | | DEV-FWK-CLD-BUS/ENT | **disable** | unchanged | | INF-GIT-CLD-STD/BUS/ENT | keep, new texts | 190 / 390 / 790 | | INF-GIT-CLD-USR | **new** extra user | 19 | | INF-CI-CLD-STD/BUS/ENT | keep, new texts | 149 / 290 / 590 | The item group stays "BreakPilot Abonnements". Correction to the spec, applied here: PLT-CORE-CLD-STD no longer mentions "Rechnungen", because LB Plattform §2(3) says the portal provides no invoices. The text is now "Arbeitsbereich mit Anmeldung und Team für bis 25 Nutzer, Standard-Support. Module werden einzeln gebucht." No other item text mentions invoices, and a test now checks that none does. ## Other changes - `sku.Disabled` is sent to ERPNext as the Item field `disabled: 1`. Disabled items stay in ERPNext so old documents keep working. Since the disabled items already exist on prod, their flag only changes with `-sync-catalog`. - **Quote, Mehrverbrauch row:** "Zusätzliche Prüfobjekte werden mit {TGT} netto je Monat berechnet, Prüftage nach verbrauchtem Monatskontingent mit {DAY} netto (Leistungsbeschreibung Prüfwerk, Abschnitt 7)." If a rate is missing, the text says "gemäß der jeweils gültigen Preisliste" instead, per rate. If both are missing, one combined sentence is printed. Quotes with INF-GIT-CLD-STD/BUS/ENT or PLT-BNDL-* add the sentence on extra users (Leistungsbeschreibung Breakpilot Plattform, Abschnitt 4). The Jinja was parsed and rendered locally with jinja2 against mocks for eight item mixes. - **Migration 0026** adds CRA-CSA-CLD-TGT and -DAY to the `pruefwerk` product. SCAN stays so old orders still map. The up is guarded so it can run twice; the down removes the two SKUs. `DefaultProducts` and the ERP mock's SKU list follow. **Run `migrate-up` with the deploy.** Without it, TGT/DAY lines on an order log "sales order item without catalog product". - **0 € module lines:** nothing needed fixing. Neither the webhook path nor reconcile reads the rate: the webhook template sends only `item_code` and `qty`, and `SubscriptionPlan` has no rate. A new test covers both paths: a bundle order with modules at rate 0 and qty 15 gives an active tenant, plan standard, and seats 15 per module. ## Decisions the spec did not cover 1. **No Prüfwerk Mehrverbrauch sentence on Enterprise quotes.** CRA-CSA-CLD-ENT is "ohne Begrenzung". Edge case: a quote with both -STD and -ENT also prints no Prüfwerk sentence. The extra-users sentence is not affected. 2. The run without the flag still writes descriptions, as `Run` has done until now (see the table). 3. `-sync-catalog` only changes Item Price rows without a `customer`. If there are several such rows for an item, the run reports "not synced". If there are none, it creates the list price. 4. The quote template's Item Price lookup still has no customer filter (unchanged from before). 5. INF-GIT-OPR texts: STD uses the spec text exactly, so "kein Quellcode verlässt das Haus" is gone. BUS keeps "für mittelgroße Teams" and loses "schnellerer Patch-Rhythmus", like CI. ENT says "für große Entwicklungsorganisationen". 6. INF-CI-OPR texts differ only by size ("mindestens 2 vCPU / 4 GB" etc.); "für größere/umfangreiche Builds" was dropped. 7. DEV-WP-OPR and DEV-FWK-OPR texts: the tier phrase sits after "im eigenen Netz", e.g. "Werkpilot im eigenen Netz für mittlere Teams, mit einem vom Kunden betriebenen KI-Modell; …". 8. TGT/DAY quantities on an order or subscription count toward Prüfwerk `seats`, exactly as SCAN already does. Not changed here. 9. Bundle revenue goes to cost center Plattform (PLT-*). Module lines at 0 € book nothing on Prüfwerk, Firmwerk or Werkpilot. Whether to allocate it is an accounting decision for you. 10. The dry run prints texts in full (no truncation), so the wording can be read before it goes live. 11. `TestEverySKUHasAListPrice` now allows exactly one item at 0: CRA-CSA-CLD-ENT. 12. The ERP mock's `DefaultSKUs` now also lists PLT-BNDL-* and CRA-CSA-CLD-TGT/DAY. ## Tests `go build ./... && go vet ./... && go test ./...` all pass. The Postgres testcontainers suites ran (podman socket) with no skips: server 463 s, migrations 32 s. New tests: - catalogue consistency: unique codes, units, disabled set, prices including 5.99/9.99, brand spelling - `TestSyncCatalog`: the dry run writes nothing and names every change; the run updates name, description, disabled and price and keeps the customer price; a second run makes no updates; without the flag only the description changes - quote template phrases - `TestMigrate_productsSeedMatchesDefaults`: seed equals `DefaultProducts`, 0026 applied twice, down - `TestErp_zeroRateModuleLinesEntitle`: webhook and reconcile, memory and Postgres 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Reviewed-on: https://git.breakpilot.com/platform/tenant-registry/pulls/115 --- cmd/erpsetup/main.go | 9 + internal/erpmock/server.go | 4 +- internal/erpsetup/branding.go | 24 +- internal/erpsetup/catalog.go | 105 +++++---- internal/erpsetup/erpsetup.go | 161 +++++++++++++- internal/erpsetup/erpsetup_test.go | 210 +++++++++++++++++- internal/server/erp_test.go | 73 ++++++ internal/store/products.go | 7 +- .../0026_pruefwerk_tgt_day_skus.down.sql | 3 + migrations/0026_pruefwerk_tgt_day_skus.up.sql | 6 + migrations/migrations_test.go | 67 ++++++ 11 files changed, 607 insertions(+), 62 deletions(-) create mode 100644 migrations/0026_pruefwerk_tgt_day_skus.down.sql create mode 100644 migrations/0026_pruefwerk_tgt_day_skus.up.sql diff --git a/cmd/erpsetup/main.go b/cmd/erpsetup/main.go index f09a718..6b9c412 100644 --- a/cmd/erpsetup/main.go +++ b/cmd/erpsetup/main.go @@ -7,6 +7,13 @@ // ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… \ // ERP_WEBHOOK_SECRET=… erpsetup -webhook-url https://registry.breakpilot.com/v1/internal/erp/webhook -dry-run // +// Catalogue items are created when missing and their description is kept +// current; a list price is set once, and later changes in ERPNext stay. With +// -sync-catalog the run also sets existing items' name, description and +// disabled flag and the Standard Selling list prices (not customer prices) +// to the catalogue in internal/erpsetup/catalog.go; with -dry-run it lists +// each change as "field old → new". It never deletes an item or a price. +// // The API user needs System Manager for this run (it creates a DocType, // Webhooks, items and custom fields); the registry's day-to-day key can then have a narrower role. package main @@ -25,6 +32,7 @@ func main() { dry := flag.Bool("dry-run", false, "report what would be created, change nothing") hook := flag.String("webhook-url", "", "registry webhook receiver, e.g. https://registry.breakpilot.com/v1/internal/erp/webhook") lead := flag.String("lead-doctype", envOr("ERP_LEAD_DOCTYPE", "Lead"), `"Lead" (ERPNext) or "CRM Lead" (Frappe CRM)`) + syncCatalog := flag.Bool("sync-catalog", false, "also update existing items (name, description, disabled) and Standard Selling list prices to the catalogue") flag.Parse() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) @@ -37,6 +45,7 @@ func main() { WebhookSecret: os.Getenv("ERP_WEBHOOK_SECRET"), LeadDoctype: *lead, DryRun: *dry, + SyncCatalog: *syncCatalog, Log: func(f string, a ...any) { fmt.Printf(f+"\n", a...) }, }) if err != nil { diff --git a/internal/erpmock/server.go b/internal/erpmock/server.go index c5ba439..e28b2ff 100644 --- a/internal/erpmock/server.go +++ b/internal/erpmock/server.go @@ -69,8 +69,8 @@ type Server struct { // DefaultSKUs mirrors the Phase-1 SKU sheet (ERP/02). var DefaultSKUs = []string{ - "PLT-CORE-CLD-STD", "PLT-CORE-CLD-BUS", "PLT-CORE-CLD-ENT", - "CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN", + "PLT-CORE-CLD-STD", "PLT-CORE-CLD-BUS", "PLT-CORE-CLD-ENT", "PLT-BNDL-CLD-STD", "PLT-BNDL-CLD-ADD", + "CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN", "CRA-CSA-CLD-TGT", "CRA-CSA-CLD-DAY", "CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT", "DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT", "DEV-FWK-CLD-STD", "DEV-FWK-CLD-BUS", "DEV-FWK-CLD-ENT", "DEV-FWK-OPR-STD", "DEV-FWK-OPR-BUS", "DEV-FWK-OPR-ENT", diff --git a/internal/erpsetup/branding.go b/internal/erpsetup/branding.go index f6361c6..04d6b62 100644 --- a/internal/erpsetup/branding.go +++ b/internal/erpsetup/branding.go @@ -300,12 +300,24 @@ var documentHTML = brand.Replace(`{%- set is_inv = doc.doctype == "Sales Invoice Laufzeit / KündigungKeine Mindestlaufzeit; der Vertrag läuft auf unbestimmte Zeit. Monatlich kündbar mit einer Frist von einem Monat zum Monatsende. AbrechnungMonatlich, jeweils zu Beginn des Leistungszeitraums. {% if interval == "monatlich" %}Monatliche Vergütung{% else %}Vergütung{% endif %}{{ doc.get_formatted("net_total") }} netto zzgl. gesetzlicher Umsatzsteuer.{% if total_discount > 0.005 %} Der darin enthaltene monatliche Nachlass von {{ frappe.utils.fmt_money(total_discount, currency=doc.currency) }} gilt dauerhaft, einschließlich etwaiger Verlängerungen.{% endif %} -{#- Overage only applies to Prüfwerk; the per-check price is the catalogue's - CRA-CSA-CLD-SCAN on the quote's price list. -#} -{%- set item_codes = " " ~ ((doc.items or []) | map(attribute="item_code") | join(" ")) -%} -{%- if " CRA-CSA-" in item_codes %} -{%- set scan_rate = frappe.db.get_value("Item Price", {"item_code": "CRA-CSA-CLD-SCAN", "price_list": doc.selling_price_list or "Standard Selling", "selling": 1}, "price_list_rate") %} -MehrverbrauchPrüfungen über das gebuchte Monatskontingent hinaus werden {% if scan_rate %}mit {{ frappe.utils.fmt_money(scan_rate, currency=doc.currency) }} netto je zusätzlicher Prüfung{% else %}je zusätzlicher Prüfung gemäß der jeweils gültigen Preisliste{% endif %} berechnet. +{#- Mehrverbrauch: for Prüfwerk the extra Prüfobjekte (CRA-CSA-CLD-TGT) and + Prüftage (CRA-CSA-CLD-DAY) at the rates on the quote's price list, except + on an Enterprise quote (no limits); for Managed Git and the Starter bundle + the users beyond the included ones. A missing rate reads "gemäß der + jeweils gültigen Preisliste". -#} +{%- set item_codes = " " ~ ((doc.items or []) | map(attribute="item_code") | join(" ")) ~ " " -%} +{%- set pw_overage = " CRA-CSA-" in item_codes and " CRA-CSA-CLD-ENT " not in item_codes -%} +{%- set more_users = " INF-GIT-CLD-STD " in item_codes or " INF-GIT-CLD-BUS " in item_codes or " INF-GIT-CLD-ENT " in item_codes or " PLT-BNDL-" in item_codes -%} +{%- if pw_overage or more_users %} +{%- set price_list = doc.selling_price_list or "Standard Selling" %} +Mehrverbrauch +{%- if pw_overage %} +{%- set tgt_rate = frappe.db.get_value("Item Price", {"item_code": "CRA-CSA-CLD-TGT", "price_list": price_list, "selling": 1}, "price_list_rate") %} +{%- set day_rate = frappe.db.get_value("Item Price", {"item_code": "CRA-CSA-CLD-DAY", "price_list": price_list, "selling": 1}, "price_list_rate") %} +{%- if tgt_rate or day_rate %}Zusätzliche Prüfobjekte werden {% if tgt_rate %}mit {{ frappe.utils.fmt_money(tgt_rate, currency=doc.currency) }} netto je Monat{% else %}gemäß der jeweils gültigen Preisliste{% endif %} berechnet, Prüftage nach verbrauchtem Monatskontingent {% if day_rate %}mit {{ frappe.utils.fmt_money(day_rate, currency=doc.currency) }} netto{% else %}gemäß der jeweils gültigen Preisliste{% endif %} +{%- else %}Zusätzliche Prüfobjekte und Prüftage nach verbrauchtem Monatskontingent werden gemäß der jeweils gültigen Preisliste berechnet{% endif %} (Leistungsbeschreibung Prüfwerk, Abschnitt 7). +{%- endif %} +{%- if more_users %}{% if pw_overage %} {% endif %}Weitere Nutzer über die enthaltenen Nutzer hinaus werden je Modul nach Preisliste berechnet (Leistungsbeschreibung Breakpilot Plattform, Abschnitt 4).{% endif %} {%- endif %} Vertragsgrundlagen{{ doc.get("vertragsgrundlage") or "Es gelten die SaaS-Vertragsbedingungen, die Leistungsbeschreibungen, das SLA und die AVV (Art. 28 DSGVO) in der jeweils vereinbarten Fassung. Auf Anfrage erhalten Sie die Dokumente vorab; nach Vertragsschluss stehen sie im BreakPilot-Kundenportal zum Abruf bereit." }} AnnahmeDurch schriftliche oder elektronische Annahme dieses Angebots{% if doc.valid_till %} bis zum {{ frappe.utils.formatdate(doc.valid_till) }}{% endif %}. diff --git a/internal/erpsetup/catalog.go b/internal/erpsetup/catalog.go index d727a21..efbc2f5 100644 --- a/internal/erpsetup/catalog.go +++ b/internal/erpsetup/catalog.go @@ -3,66 +3,84 @@ package erpsetup // The sales catalogue in ERPNext: the SKU items (codes as in the registry's // products table and the "Breakpilot SKU + SLA" sheet), their units and item // group, the SEPA direct-debit mandate on the Customer and the payment method. -// List prices (net EUR, from the SKU sheet) go on the Standard Selling price -// list once; later changes are made in ERPNext and never overwritten here. +// Names, descriptions and list prices follow the Leistungsbeschreibungen +// 1.0.0. Every run writes the item description and creates what is missing; +// a list price (net EUR) goes on the Standard Selling price list once. Only a +// run with -sync-catalog (Config.SyncCatalog) brings existing items' name, +// description and disabled flag and the list prices back to these values; +// without it, price changes made in ERPNext stay. +// itemGroup keeps its old spelling: renaming it would touch every item. const itemGroup = "BreakPilot Abonnements" type sku struct { Code, Name, UOM, Description string Price float64 // list price, net EUR per UOM + // Disabled items are no longer sold; they stay in ERPNext (disabled: 1) + // so documents that carry them keep working. + Disabled bool } // priceList carries the list prices. const priceList = "Standard Selling" // skus lists every item a sales order may carry. The registry unlocks a -// product for the product SKUs; the platform fee (PLT-CORE-*) is billed but -// unlocks nothing on its own, and so are Managed Git (INF-GIT-*) and its build +// product for the product SKUs; the platform fee (PLT-CORE-*) and the Starter +// bundle (PLT-BNDL-*) are billed but unlock nothing on their own: a bundle's +// modules are their own lines at 0,00 €, and those unlock the products. So +// are Managed Git (INF-GIT-*, with extra users INF-GIT-CLD-USR) and its build // runners (INF-CI-*) until the registry has a `git` product (instances and // runners are provisioned by hand, v0). Runner prices are per runner. func skus() []sku { return []sku{ - {"PLT-CORE-CLD-STD", "BreakPilot Plattform – Starter", "Monat", "Arbeitsbereich mit Anmeldung, Team und Rechnungen: bis 25 Nutzer, bis 3 Produkte, Standard-Support.", 290}, - {"PLT-CORE-CLD-BUS", "BreakPilot Plattform – Growth", "Monat", "Arbeitsbereich für bis 100 Nutzer, beliebig viele Produkte, monatlicher Nutzungsbericht, vorrangiger Support.", 790}, - {"PLT-CORE-CLD-ENT", "BreakPilot Plattform – Enterprise", "Monat", "Arbeitsbereich ohne Nutzergrenze, persönliche Betreuung, individuelle Verträge (AVV), Wahl der EU-Region.", 1990}, - {"CRA-CSA-CLD-STD", "Prüfwerk Cloud – Standard", "Monat", "Automatisierte Cybersecurity-Analyse von Quellcode, Firmware und SPS-Programmen für CRA-bezogene Compliance-Prozesse: 5 Prüfobjekte, 50 Prüfungen im Monat, monatliches Nachweispaket.", 1490}, - {"CRA-CSA-CLD-BUS", "Prüfwerk Cloud – Business", "Monat", "Prüfwerk für 25 Prüfobjekte und 500 Prüfungen im Monat, mit Schnittstelle (MCP) für eigene Werkzeuge.", 3990}, - {"CRA-CSA-CLD-ENT", "Prüfwerk Cloud – Enterprise", "Monat", "Prüfwerk ohne Obergrenzen, eigener Kontrollkatalog, Nachweisexport für abgeschottete Umgebungen.", 9900}, - {"CRA-CSA-CLD-SCAN", "Prüfwerk – Zusätzliche Prüfung", "Prüfung", "Einzelne Prüfung über das Monatskontingent hinaus; nur zu einem aktiven Prüfwerk-Abonnement.", 12}, - {"CRA-WBK-CLD-STD", "Werkbank Runner Cloud – Standard", "Monat", "Prüfmaschine für aktive Tests externer Systeme (1 vCPU / 2 GB); Zusatz zu Prüfwerk.", 490}, - {"CRA-WBK-CLD-BUS", "Werkbank Runner Cloud – Business", "Monat", "Prüfmaschine mit parallelen Prüfungen (2 vCPU / 4 GB); Zusatz zu Prüfwerk.", 990}, - {"CRA-WBK-CLD-ENT", "Werkbank Runner Cloud – Enterprise", "Monat", "Prüfmaschine mit eigenen Prüfmodulen (4 vCPU / 8 GB); Zusatz zu Prüfwerk.", 1990}, - {"DEV-WP-CLD-STD", "Werkpilot Cloud – Standard", "Monat", "KI-Assistent für Code und SPS-Programme, gemeinsame KI-Kapazität in der EU; je Nutzer und Monat.", 59}, - {"DEV-WP-CLD-BUS", "Werkpilot Cloud – Business", "Monat", "Werkpilot mit reservierter KI-Kapazität und Single Sign-on; je Nutzer und Monat.", 119}, - {"DEV-WP-CLD-ENT", "Werkpilot Cloud – Enterprise", "Monat", "Werkpilot auf eigener KI-Instanz, optional auf Ihren Code abgestimmt; je Nutzer und Monat.", 249}, - {"DEV-WP-OPR-STD", "Werkpilot On-Prem – Standard", "Jahr", "Werkpilot im eigenen Netz, ohne dass Quellcode das Haus verlässt; Jahreslizenz.", 7900}, - {"DEV-WP-OPR-BUS", "Werkpilot On-Prem – Business", "Jahr", "Werkpilot im eigenen Netz für mittlere Teams; Jahreslizenz.", 19900}, - {"DEV-WP-OPR-ENT", "Werkpilot On-Prem – Enterprise", "Jahr", "Werkpilot im eigenen Netz für große Entwicklungsorganisationen; Jahreslizenz.", 49900}, - {"DEV-FWK-CLD-STD", "Firmwerk Cloud – Standard", "Monat", "Reproduzierbare Firmware-Builds mit Stückliste und Nachweis, 10 Umgebungen je Nutzer; je Nutzer und Monat.", 89}, - {"DEV-FWK-CLD-BUS", "Firmwerk Cloud – Business", "Monat", "Firmwerk mit beliebig vielen Umgebungen und Team-Freigabe; je Nutzer und Monat.", 149}, - {"DEV-FWK-CLD-ENT", "Firmwerk Cloud – Enterprise", "Monat", "Firmwerk mit eigenen Toolchains und LTS-Stand; je Nutzer und Monat.", 299}, - {"DEV-FWK-OPR-STD", "Firmwerk On-Prem – Standard", "Jahr", "Firmwerk im eigenen Netz; Jahreslizenz.", 6900}, - {"DEV-FWK-OPR-BUS", "Firmwerk On-Prem – Business", "Jahr", "Firmwerk im eigenen Netz für größere Teams; Jahreslizenz.", 15900}, - {"DEV-FWK-OPR-ENT", "Firmwerk On-Prem – Enterprise", "Jahr", "Firmwerk im eigenen Netz für große Organisationen; Jahreslizenz.", 39900}, - {"INF-GIT-CLD-STD", "Managed Git Cloud – Standard", "Monat", "Eigene Gitea-Instanz für Ihr Unternehmen, betrieben von BreakPilot in Deutschland: Anmeldung über Ihr BreakPilot-Konto, Sicherung und Updates inklusive; für Teams bis ca. 50 Entwickler.", 190}, - {"INF-GIT-CLD-BUS", "Managed Git Cloud – Business", "Monat", "Eigene Gitea-Instanz für mittelgroße Entwicklerteams (bis ca. 200 Entwickler) mit Business-SLA.", 390}, - {"INF-GIT-CLD-ENT", "Managed Git Cloud – Enterprise", "Monat", "Eigene Gitea-Instanz für große Entwicklungsorganisationen, unbegrenzter Speicher, Enterprise-SLA und persönliche Betreuung.", 790}, - {"INF-GIT-OPR-STD", "Managed Git On-Prem – Standard", "Jahr", "Gitea im eigenen Netz, kein Quellcode verlässt das Haus; Installation, Patches und Überwachung durch BreakPilot; Jahreslizenz.", 4900}, - {"INF-GIT-OPR-BUS", "Managed Git On-Prem – Business", "Jahr", "Gitea im eigenen Netz für mittelgroße Teams, schnellerer Patch-Rhythmus; Jahreslizenz.", 9900}, - {"INF-GIT-OPR-ENT", "Managed Git On-Prem – Enterprise", "Jahr", "Gitea im eigenen Netz mit Hochverfügbarkeit und Enterprise-SLA; Jahreslizenz.", 19900}, - {"INF-CI-CLD-STD", "Build-Runner Cloud – Standard", "Monat", "Eigene Build-Maschine für Ihr Unternehmen zu Managed Git, betrieben von BreakPilot in Deutschland und nie mit anderen Kunden geteilt (2 vCPU / 4 GB); Preis je Runner.", 149}, - {"INF-CI-CLD-BUS", "Build-Runner Cloud – Business", "Monat", "Eigene Build-Maschine für größere Builds und parallele Jobs, nie geteilt (4 vCPU / 8 GB); Preis je Runner.", 290}, - {"INF-CI-CLD-ENT", "Build-Runner Cloud – Enterprise", "Monat", "Eigene Build-Maschine für umfangreiche Builds, nie geteilt (8 vCPU / 16 GB), Enterprise-SLA; Preis je Runner.", 590}, - {"INF-CI-OPR-STD", "Build-Runner On-Prem – Standard", "Jahr", "Build-Maschine im eigenen Netz, ausschließlich für Ihre Builds, kein Quellcode verlässt das Haus (2 vCPU / 4 GB); Einrichtung, Patches und Überwachung durch BreakPilot; Jahreslizenz je Runner.", 2900}, - {"INF-CI-OPR-BUS", "Build-Runner On-Prem – Business", "Jahr", "Build-Maschine im eigenen Netz für größere Builds (4 vCPU / 8 GB), schnellerer Patch-Rhythmus; Jahreslizenz je Runner.", 5900}, - {"INF-CI-OPR-ENT", "Build-Runner On-Prem – Enterprise", "Jahr", "Build-Maschine im eigenen Netz für umfangreiche Builds (8 vCPU / 16 GB) mit Enterprise-SLA; Jahreslizenz je Runner.", 11900}, + {Code: "PLT-CORE-CLD-STD", Name: "Breakpilot Plattform – Starter", UOM: "Monat", Description: "Arbeitsbereich mit Anmeldung und Team für bis 25 Nutzer, Standard-Support. Module werden einzeln gebucht.", Price: 290}, + {Code: "PLT-CORE-CLD-BUS", Name: "Breakpilot Plattform – Growth", UOM: "Monat", Description: "Arbeitsbereich für bis 100 Nutzer, Business-Support.", Price: 790}, + {Code: "PLT-CORE-CLD-ENT", Name: "Breakpilot Plattform – Enterprise", UOM: "Monat", Description: "Arbeitsbereich ohne Nutzergrenze, Enterprise-Support und benannte Ansprechperson.", Price: 1990}, + {Code: "PLT-BNDL-CLD-STD", Name: "Breakpilot Starter-Modulpaket", UOM: "Monat", Description: "Plattform Starter (bis 25 Nutzer) mit drei Modulen nach Wahl, je bis 15 Nutzer. Die gewählten Module stehen im Angebot als eigene Positionen zu 0,00 €.", Price: 990}, + {Code: "PLT-BNDL-CLD-ADD", Name: "Weiteres Modul im Starter-Modulpaket", UOM: "Monat", Description: "Ein weiteres Modul zum Starter-Modulpaket, bis 15 Nutzer. Das Modul steht im Angebot als eigene Position zu 0,00 €.", Price: 499}, + {Code: "CRA-CSA-CLD-STD", Name: "Prüfwerk Cloud – Standard", UOM: "Monat", Description: "Automatisierte Sicherheitsanalyse von Quellcode, Firmware und SPS-Programmen: 5 enthaltene Prüfobjekte mit unbegrenzten Prüfungen nach Änderungen, dazu 100 weitere Prüfungen im Monat.", Price: 490}, + {Code: "CRA-CSA-CLD-BUS", Name: "Prüfwerk Cloud – Business", UOM: "Monat", Description: "Prüfwerk mit 25 enthaltenen Prüfobjekten und 500 weiteren Prüfungen im Monat.", Price: 1290}, + {Code: "CRA-CSA-CLD-ENT", Name: "Prüfwerk Cloud – Enterprise", UOM: "Monat", Description: "Prüfwerk ohne Begrenzung der Prüfobjekte und Prüfungen. Preis nach Vereinbarung.", Price: 0}, + {Code: "CRA-CSA-CLD-TGT", Name: "Prüfwerk – Zusätzliches Prüfobjekt", UOM: "Monat", Description: "Prüfobjekt über die im Leistungspaket enthaltenen hinaus; seine Prüfungen zählen zum Monatskontingent. Berechnet wird die höchste Zahl gleichzeitig angelegter zusätzlicher Prüfobjekte im Monat.", Price: 5.99}, + {Code: "CRA-CSA-CLD-DAY", Name: "Prüfwerk – Prüftag", UOM: "Prüftag", Description: "Nach verbrauchtem Monatskontingent: bis zu 6 weitere Prüfungen eines Prüfobjekts am selben Kalendertag.", Price: 9.99}, + // Replaced by CRA-CSA-CLD-TGT and -DAY. + {Code: "CRA-CSA-CLD-SCAN", Name: "Prüfwerk – Zusätzliche Prüfung", UOM: "Prüfung", Description: "Einzelne Prüfung über das Monatskontingent hinaus; nur zu einem aktiven Prüfwerk-Abonnement.", Price: 12, Disabled: true}, + // Werkbank is not on prod. + {Code: "CRA-WBK-CLD-STD", Name: "Werkbank Runner Cloud – Standard", UOM: "Monat", Description: "Prüfmaschine für aktive Tests externer Systeme (1 vCPU / 2 GB); Zusatz zu Prüfwerk.", Price: 490, Disabled: true}, + {Code: "CRA-WBK-CLD-BUS", Name: "Werkbank Runner Cloud – Business", UOM: "Monat", Description: "Prüfmaschine mit parallelen Prüfungen (2 vCPU / 4 GB); Zusatz zu Prüfwerk.", Price: 990, Disabled: true}, + {Code: "CRA-WBK-CLD-ENT", Name: "Werkbank Runner Cloud – Enterprise", UOM: "Monat", Description: "Prüfmaschine mit eigenen Prüfmodulen (4 vCPU / 8 GB); Zusatz zu Prüfwerk.", Price: 1990, Disabled: true}, + {Code: "DEV-WP-CLD-STD", Name: "Werkpilot Cloud", UOM: "Monat", Description: "KI-Assistent für Code und SPS-Programme in der Kommandozeile, KI-Modelle des Anbieters; je Nutzer und Monat.", Price: 59}, + // Werkpilot and Firmwerk Cloud: no real tier difference yet. + {Code: "DEV-WP-CLD-BUS", Name: "Werkpilot Cloud – Business", UOM: "Monat", Description: "Werkpilot mit reservierter KI-Kapazität und Single Sign-on; je Nutzer und Monat.", Price: 119, Disabled: true}, + {Code: "DEV-WP-CLD-ENT", Name: "Werkpilot Cloud – Enterprise", UOM: "Monat", Description: "Werkpilot auf eigener KI-Instanz, optional auf Ihren Code abgestimmt; je Nutzer und Monat.", Price: 249, Disabled: true}, + {Code: "DEV-WP-OPR-STD", Name: "Werkpilot On-Prem – Standard", UOM: "Jahr", Description: "Werkpilot im eigenen Netz für kleine Teams, mit einem vom Kunden betriebenen KI-Modell; kein Quellcode verlässt das Haus; Jahreslizenz.", Price: 7900}, + {Code: "DEV-WP-OPR-BUS", Name: "Werkpilot On-Prem – Business", UOM: "Jahr", Description: "Werkpilot im eigenen Netz für mittlere Teams, mit einem vom Kunden betriebenen KI-Modell; kein Quellcode verlässt das Haus; Jahreslizenz.", Price: 19900}, + {Code: "DEV-WP-OPR-ENT", Name: "Werkpilot On-Prem – Enterprise", UOM: "Jahr", Description: "Werkpilot im eigenen Netz für große Entwicklungsorganisationen, mit einem vom Kunden betriebenen KI-Modell; kein Quellcode verlässt das Haus; Jahreslizenz.", Price: 49900}, + {Code: "DEV-FWK-CLD-STD", Name: "Firmwerk Cloud", UOM: "Monat", Description: "Reproduzierbare Firmware-Builds mit Software-Stückliste (SBOM) und signiertem Herkunftsnachweis; je Nutzer und Monat.", Price: 89}, + {Code: "DEV-FWK-CLD-BUS", Name: "Firmwerk Cloud – Business", UOM: "Monat", Description: "Firmwerk mit beliebig vielen Umgebungen und Team-Freigabe; je Nutzer und Monat.", Price: 149, Disabled: true}, + {Code: "DEV-FWK-CLD-ENT", Name: "Firmwerk Cloud – Enterprise", UOM: "Monat", Description: "Firmwerk mit eigenen Toolchains und LTS-Stand; je Nutzer und Monat.", Price: 299, Disabled: true}, + {Code: "DEV-FWK-OPR-STD", Name: "Firmwerk On-Prem – Standard", UOM: "Jahr", Description: "Firmwerk im eigenen Netz für kleine Teams; Jahreslizenz.", Price: 6900}, + {Code: "DEV-FWK-OPR-BUS", Name: "Firmwerk On-Prem – Business", UOM: "Jahr", Description: "Firmwerk im eigenen Netz für größere Teams; Jahreslizenz.", Price: 15900}, + {Code: "DEV-FWK-OPR-ENT", Name: "Firmwerk On-Prem – Enterprise", UOM: "Jahr", Description: "Firmwerk im eigenen Netz für große Organisationen; Jahreslizenz.", Price: 39900}, + {Code: "INF-GIT-CLD-STD", Name: "Managed Git Cloud – Standard", UOM: "Monat", Description: "Eigene Gitea-Instanz, betrieben von Breakpilot in Deutschland: Anmeldung über das Breakpilot-Konto, Sicherung und Updates inklusive; bis 5 Nutzer.", Price: 190}, + {Code: "INF-GIT-CLD-BUS", Name: "Managed Git Cloud – Business", UOM: "Monat", Description: "Eigene Gitea-Instanz wie Standard, bis 25 Nutzer.", Price: 390}, + {Code: "INF-GIT-CLD-ENT", Name: "Managed Git Cloud – Enterprise", UOM: "Monat", Description: "Eigene Gitea-Instanz wie Standard, bis 100 Nutzer.", Price: 790}, + {Code: "INF-GIT-CLD-USR", Name: "Managed Git – Weiterer Nutzer", UOM: "Monat", Description: "Nutzer über die enthaltenen Nutzer hinaus; je Nutzer und Monat.", Price: 19}, + {Code: "INF-GIT-OPR-STD", Name: "Managed Git On-Prem – Standard", UOM: "Jahr", Description: "Gitea im eigenen Netz; Installation, Sicherheitsaktualisierungen und Überwachung durch Breakpilot; Jahreslizenz.", Price: 4900}, + {Code: "INF-GIT-OPR-BUS", Name: "Managed Git On-Prem – Business", UOM: "Jahr", Description: "Gitea im eigenen Netz für mittelgroße Teams; Installation, Sicherheitsaktualisierungen und Überwachung durch Breakpilot; Jahreslizenz.", Price: 9900}, + {Code: "INF-GIT-OPR-ENT", Name: "Managed Git On-Prem – Enterprise", UOM: "Jahr", Description: "Gitea im eigenen Netz für große Entwicklungsorganisationen; Installation, Sicherheitsaktualisierungen und Überwachung durch Breakpilot; Jahreslizenz.", Price: 19900}, + {Code: "INF-CI-CLD-STD", Name: "Build-Runner Cloud – Standard", UOM: "Monat", Description: "Eigene Build-Maschine zu Managed Git, betrieben von Breakpilot in Deutschland und nicht mit anderen Kunden geteilt: mindestens 2 vCPU / 4 GB; Preis je Runner.", Price: 149}, + {Code: "INF-CI-CLD-BUS", Name: "Build-Runner Cloud – Business", UOM: "Monat", Description: "Wie Standard, mindestens 4 vCPU / 8 GB; Preis je Runner.", Price: 290}, + {Code: "INF-CI-CLD-ENT", Name: "Build-Runner Cloud – Enterprise", UOM: "Monat", Description: "Wie Standard, mindestens 8 vCPU / 16 GB; Preis je Runner.", Price: 590}, + {Code: "INF-CI-OPR-STD", Name: "Build-Runner On-Prem – Standard", UOM: "Jahr", Description: "Build-Maschine im eigenen Netz (mindestens 2 vCPU / 4 GB); Einrichtung, Sicherheitsaktualisierungen und Überwachung durch Breakpilot; Jahreslizenz je Runner.", Price: 2900}, + {Code: "INF-CI-OPR-BUS", Name: "Build-Runner On-Prem – Business", UOM: "Jahr", Description: "Build-Maschine im eigenen Netz (mindestens 4 vCPU / 8 GB); Einrichtung, Sicherheitsaktualisierungen und Überwachung durch Breakpilot; Jahreslizenz je Runner.", Price: 5900}, + {Code: "INF-CI-OPR-ENT", Name: "Build-Runner On-Prem – Enterprise", UOM: "Jahr", Description: "Build-Maschine im eigenen Netz (mindestens 8 vCPU / 16 GB); Einrichtung, Sicherheitsaktualisierungen und Überwachung durch Breakpilot; Jahreslizenz je Runner.", Price: 11900}, } } func uoms() []map[string]any { out := []map[string]any{} - for _, u := range []string{"Monat", "Jahr", "Prüfung"} { + for _, u := range []string{"Monat", "Jahr", "Prüfung", "Prüftag"} { out = append(out, map[string]any{"doctype": "UOM", "name": u, "uom_name": u, "must_be_whole_number": 1}) } return out @@ -77,9 +95,18 @@ func itemDoc(s sku) map[string]any { "doctype": "Item", "name": s.Code, "item_code": s.Code, "item_name": s.Name, "item_group": itemGroup, "stock_uom": s.UOM, "description": s.Description, "is_stock_item": 0, "is_sales_item": 1, "is_purchase_item": 0, "include_item_in_manufacturing": 0, + "disabled": boolInt(s.Disabled), } } +// boolInt is a Frappe Check value. +func boolInt(b bool) int { + if b { + return 1 + } + return 0 +} + // sepaFields put the direct-debit mandate on the Customer: reference, date of // signature and type (Basislastschrift/CORE or Firmenlastschrift/B2B). func sepaFields() []map[string]any { diff --git a/internal/erpsetup/erpsetup.go b/internal/erpsetup/erpsetup.go index d984bcf..a46f12a 100644 --- a/internal/erpsetup/erpsetup.go +++ b/internal/erpsetup/erpsetup.go @@ -33,8 +33,13 @@ type Config struct { WebhookSecret string // same value as the registry's ERP_WEBHOOK_SECRET LeadDoctype string // "Lead" (ERPNext) or "CRM Lead" (Frappe CRM) DryRun bool - HTTP *http.Client - Log func(format string, args ...any) + // SyncCatalog also brings existing catalogue items (name, description, + // disabled) and their Standard Selling list prices to the values in + // catalog.go. Off: items are created when missing and only their + // description is kept current; a list price is set once. + SyncCatalog bool + HTTP *http.Client + Log func(format string, args ...any) } // Step is one reported action. @@ -88,8 +93,16 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) { } for _, s := range skus() { // The description is the product wording on every document (Angebot, - // Auftragsbestätigung, Rechnung) and follows the catalogue here. - if err := r.ensureFields(ctx, "Item", s.Code, "item "+s.Code+" ("+s.Name+")", itemDoc(s), "description"); err != nil { + // Auftragsbestätigung, Rechnung) and follows the catalogue here; with + // SyncCatalog so do the name and the disabled flag. + what := "item " + s.Code + " (" + s.Name + ")" + var err error + if cfg.SyncCatalog { + err = r.syncFields(ctx, "Item", s.Code, what, itemDoc(s), "item_name", "description", "disabled") + } else { + err = r.ensureFields(ctx, "Item", s.Code, what, itemDoc(s), "description") + } + if err != nil { return r.steps, err } } @@ -107,8 +120,15 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) { } } for _, s := range skus() { - if err := r.ensureListed(ctx, "Item Price", fmt.Sprintf("price %s (%s, %.2f EUR/%s)", s.Code, priceList, s.Price, s.UOM), - [][]any{{"item_code", "=", s.Code}, {"price_list", "=", priceList}}, itemPriceDoc(s)); err != nil { + what := fmt.Sprintf("price %s (%s, %.2f EUR/%s)", s.Code, priceList, s.Price, s.UOM) + var err error + if cfg.SyncCatalog { + err = r.syncPrice(ctx, what, s) + } else { + err = r.ensureListed(ctx, "Item Price", what, + [][]any{{"item_code", "=", s.Code}, {"price_list", "=", priceList}}, itemPriceDoc(s)) + } + if err != nil { return r.steps, err } } @@ -309,7 +329,8 @@ func (r *runner) ensureFields(ctx context.Context, doctype, name, what string, d // ensureListed is ensure for autonamed docs: it looks for any doc matching // filters and creates doc only when there is none. An existing one is never -// changed (prices and addresses are maintained in ERPNext). +// changed (prices and addresses are maintained in ERPNext; list prices are +// brought back to the catalogue only by syncPrice, with SyncCatalog). func (r *runner) ensureListed(ctx context.Context, doctype, what string, filters [][]any, doc map[string]any) error { f, _ := json.Marshal(filters) q := url.Values{"filters": {string(f)}, "fields": {`["name"]`}, "limit_page_length": {"1"}} @@ -347,6 +368,132 @@ func (r *runner) ensureListed(ctx context.Context, doctype, what string, filters return nil } +// syncFields is ensureFields for the catalogue sync (-sync-catalog): the +// report names each changed field with its old and new value. +func (r *runner) syncFields(ctx context.Context, doctype, name, what string, doc map[string]any, keys ...string) error { + path := "/api/resource/" + url.PathEscape(doctype) + "/" + url.PathEscape(name) + status, body, err := r.call(ctx, http.MethodGet, path, nil) + if err != nil { + return err + } + if status == http.StatusNotFound { + return r.ensure(ctx, doctype, name, what, doc) + } + if status != http.StatusOK { + return fmt.Errorf("erpsetup: GET %s %q: HTTP %d", doctype, name, status) + } + var cur struct { + Data map[string]any `json:"data"` + } + _ = json.Unmarshal(body, &cur) + patch := map[string]any{} + var changes []string + for _, k := range keys { + if !sameValue(cur.Data[k], doc[k]) { + patch[k] = doc[k] + changes = append(changes, change(k, cur.Data[k], doc[k])) + } + } + return r.applyPatch(ctx, path, what, "", patch, changes) +} + +// syncPrice is ensureListed for a list price with -sync-catalog: the item's +// Standard Selling price (the one without a customer; customer prices are +// left alone) gets the catalogue rate. +func (r *runner) syncPrice(ctx context.Context, what string, s sku) error { + f, _ := json.Marshal([][]any{{"item_code", "=", s.Code}, {"price_list", "=", priceList}}) + q := url.Values{"filters": {string(f)}, "fields": {`["name","price_list_rate","customer"]`}, "limit_page_length": {"50"}} + status, body, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape("Item Price")+"?"+q.Encode(), nil) + if err != nil { + return err + } + if status != http.StatusOK { + return fmt.Errorf("erpsetup: list Item Price: HTTP %d %s", status, truncate(body)) + } + var list struct { + Data []struct { + Name string `json:"name"` + PriceListRate float64 `json:"price_list_rate"` + Customer string `json:"customer"` + } `json:"data"` + } + if err := json.Unmarshal(body, &list); err != nil { + return fmt.Errorf("erpsetup: decode Item Price list: %w", err) + } + var general []string + var rate float64 + for _, p := range list.Data { + if p.Customer == "" { + general = append(general, p.Name) + rate = p.PriceListRate + } + } + switch { + case len(general) == 0: + if r.cfg.DryRun { + r.record(what, "would create") + return nil + } + status, body, err := r.call(ctx, http.MethodPost, "/api/resource/"+url.PathEscape("Item Price"), itemPriceDoc(s)) + if err != nil { + return err + } + if status/100 != 2 { + return fmt.Errorf("erpsetup: create %s: HTTP %d %s", what, status, truncate(body)) + } + r.record(what, "created") + return nil + case len(general) > 1: + r.record(what, fmt.Sprintf("exists (%d list prices %s, not synced)", len(general), strings.Join(general, ", "))) + return nil + } + patch := map[string]any{} + var changes []string + if !sameValue(rate, s.Price) { + patch["price_list_rate"] = s.Price + changes = append(changes, change("price_list_rate", rate, s.Price)) + } + return r.applyPatch(ctx, "/api/resource/"+url.PathEscape("Item Price")+"/"+url.PathEscape(general[0]), what, " ("+general[0]+")", patch, changes) +} + +// applyPatch writes patch to the doc at path and reports the changes; +// nothing to change is "exists", a dry run "would update". +func (r *runner) applyPatch(ctx context.Context, path, what, ref string, patch map[string]any, changes []string) error { + if len(patch) == 0 { + r.record(what, "exists"+ref) + return nil + } + detail := ref + ": " + strings.Join(changes, "; ") + if r.cfg.DryRun { + r.record(what, "would update"+detail) + return nil + } + status, body, err := r.call(ctx, http.MethodPut, path, patch) + if err != nil { + return err + } + if status/100 != 2 { + return fmt.Errorf("erpsetup: update %s: HTTP %d %s", what, status, truncate(body)) + } + r.record(what, "updated"+detail) + return nil +} + +// change is one field of a sync report: field old → new. Texts are shown in +// full: the dry run is where the new wording is read before it goes live. +func change(field string, old, want any) string { + show := func(v any) string { + switch x := v.(type) { + case nil: + return `""` + case string: + return fmt.Sprintf("%q", x) + } + return fmt.Sprint(v) + } + return field + " " + show(old) + " → " + show(want) +} + // Webhooks are autonamed, so they are found by (doctype, event, URL, marker). func (r *runner) ensureWebhook(ctx context.Context, w webhook) error { what := fmt.Sprintf("webhook %s %s → %s", w.Doctype, w.DocEvent, w.Event) diff --git a/internal/erpsetup/erpsetup_test.go b/internal/erpsetup/erpsetup_test.go index eae8cc5..5188c94 100644 --- a/internal/erpsetup/erpsetup_test.go +++ b/internal/erpsetup/erpsetup_test.go @@ -292,12 +292,12 @@ func TestWebhookDocIsNamed(t *testing.T) { // exists too, and the platform fee, Managed Git and its build runners are there for invoicing. func TestCatalogueCoversTheRegistrySKUs(t *testing.T) { want := []string{ - "CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN", + "CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN", "CRA-CSA-CLD-TGT", "CRA-CSA-CLD-DAY", "CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT", "DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT", "DEV-FWK-CLD-STD", "DEV-FWK-CLD-BUS", "DEV-FWK-CLD-ENT", "DEV-FWK-OPR-STD", "DEV-FWK-OPR-BUS", "DEV-FWK-OPR-ENT", - "PLT-CORE-CLD-STD", "PLT-CORE-CLD-BUS", "PLT-CORE-CLD-ENT", - "INF-GIT-CLD-STD", "INF-GIT-CLD-BUS", "INF-GIT-CLD-ENT", "INF-GIT-OPR-STD", "INF-GIT-OPR-BUS", "INF-GIT-OPR-ENT", + "PLT-CORE-CLD-STD", "PLT-CORE-CLD-BUS", "PLT-CORE-CLD-ENT", "PLT-BNDL-CLD-STD", "PLT-BNDL-CLD-ADD", + "INF-GIT-CLD-STD", "INF-GIT-CLD-BUS", "INF-GIT-CLD-ENT", "INF-GIT-CLD-USR", "INF-GIT-OPR-STD", "INF-GIT-OPR-BUS", "INF-GIT-OPR-ENT", "INF-CI-CLD-STD", "INF-CI-CLD-BUS", "INF-CI-CLD-ENT", "INF-CI-OPR-STD", "INF-CI-OPR-BUS", "INF-CI-OPR-ENT", } units := map[string]bool{} @@ -482,14 +482,214 @@ func TestChangedTemplateIsUpdatedAndPricesKept(t *testing.T) { } } +// Every SKU has a list price; only Prüfwerk Enterprise is 0 (Preis nach +// Vereinbarung). func TestEverySKUHasAListPrice(t *testing.T) { for _, s := range skus() { - if s.Price <= 0 { - t.Errorf("%s has no price", s.Code) + if s.Price < 0 || (s.Price == 0) != (s.Code == "CRA-CSA-CLD-ENT") { + t.Errorf("%s: price %v", s.Code, s.Price) } } } +// The catalogue after the freeze of the Leistungsbeschreibungen 1.0.0: list +// prices, the disabled items (still there for old documents), the new unit +// and the brand spelling. +func TestCatalogueFollowsLeistungsbeschreibung(t *testing.T) { + prices := map[string]float64{ + "PLT-CORE-CLD-STD": 290, "PLT-CORE-CLD-BUS": 790, "PLT-CORE-CLD-ENT": 1990, + "PLT-BNDL-CLD-STD": 990, "PLT-BNDL-CLD-ADD": 499, + "CRA-CSA-CLD-STD": 490, "CRA-CSA-CLD-BUS": 1290, "CRA-CSA-CLD-ENT": 0, + "CRA-CSA-CLD-TGT": 5.99, "CRA-CSA-CLD-DAY": 9.99, + "DEV-WP-CLD-STD": 59, "DEV-FWK-CLD-STD": 89, + "INF-GIT-CLD-STD": 190, "INF-GIT-CLD-BUS": 390, "INF-GIT-CLD-ENT": 790, "INF-GIT-CLD-USR": 19, + "INF-CI-CLD-STD": 149, "INF-CI-CLD-BUS": 290, "INF-CI-CLD-ENT": 590, + } + disabled := map[string]bool{ + "CRA-CSA-CLD-SCAN": true, "CRA-WBK-CLD-STD": true, "CRA-WBK-CLD-BUS": true, "CRA-WBK-CLD-ENT": true, + "DEV-WP-CLD-BUS": true, "DEV-WP-CLD-ENT": true, "DEV-FWK-CLD-BUS": true, "DEV-FWK-CLD-ENT": true, + } + units := map[string]bool{} + for _, u := range uoms() { + units[u["name"].(string)] = true + if u["must_be_whole_number"] != 1 { + t.Errorf("unit %v", u) + } + } + have := map[string]sku{} + for _, s := range skus() { + if _, dup := have[s.Code]; dup { + t.Errorf("duplicate %s", s.Code) + } + have[s.Code] = s + if !units[s.UOM] { + t.Errorf("%s: unit %q is not created", s.Code, s.UOM) + } + if s.Disabled != disabled[s.Code] { + t.Errorf("%s: disabled %v", s.Code, s.Disabled) + } + if want := boolInt(s.Disabled); itemDoc(s)["disabled"] != want { + t.Errorf("%s: item doc disabled %v", s.Code, itemDoc(s)["disabled"]) + } + if strings.Contains(s.Name+s.Description, "BreakPilot") { + t.Errorf("%s: old brand spelling in %q / %q", s.Code, s.Name, s.Description) + } + // LB Plattform §2(3): the portal provides no invoices. + if strings.Contains(s.Name+s.Description, "Rechnung") { + t.Errorf("%s: item text mentions invoices: %q", s.Code, s.Description) + } + } + for code := range disabled { + if _, ok := have[code]; !ok { + t.Errorf("disabled %s is gone; old documents need it", code) + } + } + for code, want := range prices { + if s, ok := have[code]; !ok || s.Price != want { + t.Errorf("%s: price %v, want %v", code, s.Price, want) + } + } + if s := have["CRA-CSA-CLD-DAY"]; s.UOM != "Prüftag" { + t.Errorf("Prüftag unit: %+v", s) + } + if itemGroup != "BreakPilot Abonnements" { + t.Errorf("item group renamed: %q", itemGroup) + } +} + +// fakeItemPrice is the list price (no customer) the fake holds for code. +func fakeItemPrice(f *fakeFrappe, code string) map[string]any { + for _, p := range f.docs["Item Price"] { + if p["item_code"] == code && p["customer"] == nil { + return p + } + } + return nil +} + +// -sync-catalog: the dry run reports every field it would change and writes +// nothing; the run updates name, description, disabled and the list price +// (not a customer's price) and is idempotent. Without it, only the +// description follows the catalogue. +func TestSyncCatalog(t *testing.T) { + f := newFake() + srv := httptest.NewServer(f) + defer srv.Close() + if _, err := Run(context.Background(), cfg(srv.URL)); err != nil { + t.Fatal(err) + } + // The ERP as before the freeze. + std, scan := f.docs["Item"]["CRA-CSA-CLD-STD"], f.docs["Item"]["CRA-CSA-CLD-SCAN"] + std["item_name"], std["description"] = "Prüfwerk alt", "alt" + scan["disabled"] = 0.0 + fakeItemPrice(f, "CRA-CSA-CLD-STD")["price_list_rate"] = 1490.0 + f.docs["Item Price"]["customer-price"] = map[string]any{"name": "customer-price", "item_code": "CRA-CSA-CLD-BUS", + "price_list": priceList, "price_list_rate": 100.0, "customer": "CUST-TEST"} + + // Without the flag: the description is written, as on every run; name, + // disabled flag and price stay. + if _, err := Run(context.Background(), cfg(srv.URL)); err != nil { + t.Fatal(err) + } + if std["description"] != have(t, "CRA-CSA-CLD-STD").Description || std["item_name"] != "Prüfwerk alt" || scan["disabled"] != 0.0 || + fakeItemPrice(f, "CRA-CSA-CLD-STD")["price_list_rate"] != 1490.0 { + t.Fatalf("run without -sync-catalog: %v %v %v", std, scan, fakeItemPrice(f, "CRA-CSA-CLD-STD")) + } + std["description"] = "alt" + + c := cfg(srv.URL) + c.SyncCatalog, c.DryRun = true, true + posts := f.posts + steps, err := Run(context.Background(), c) + if err != nil { + t.Fatal(err) + } + if f.posts != posts || std["item_name"] != "Prüfwerk alt" || fakeItemPrice(f, "CRA-CSA-CLD-STD")["price_list_rate"] != 1490.0 { + t.Fatal("dry run changed something") + } + reports := map[string]string{} + for _, s := range steps { + if !strings.HasPrefix(s.Result, "exists") { + reports[s.What] = s.Result + } + } + for what, want := range map[string]string{ + "item CRA-CSA-CLD-STD (Prüfwerk Cloud – Standard)": `would update: item_name "Prüfwerk alt" → "Prüfwerk Cloud – Standard"; description "alt" → "Automatisierte`, + "item CRA-CSA-CLD-SCAN (Prüfwerk – Zusätzliche Prüfung)": "would update: disabled 0 → 1", + "price CRA-CSA-CLD-STD (Standard Selling, 490.00 EUR/Monat)": "price_list_rate 1490 → 490", + } { + if !strings.Contains(reports[what], want) { + t.Errorf("%s: %q, want %q", what, reports[what], want) + } + delete(reports, what) + } + if len(reports) != 0 { + t.Errorf("unexpected changes: %v", reports) + } + + c.DryRun = false + if _, err := Run(context.Background(), c); err != nil { + t.Fatal(err) + } + if std["item_name"] != "Prüfwerk Cloud – Standard" || std["description"] != have(t, "CRA-CSA-CLD-STD").Description || scan["disabled"] != float64(1) { + t.Fatalf("items not synced: %v %v", std, scan) + } + if p := fakeItemPrice(f, "CRA-CSA-CLD-STD")["price_list_rate"]; p != 490.0 { + t.Fatalf("price not synced: %v", p) + } + if p := f.docs["Item Price"]["customer-price"]["price_list_rate"]; p != 100.0 { + t.Fatalf("customer price changed: %v", p) + } + + posts = f.posts + steps, err = Run(context.Background(), c) + if err != nil { + t.Fatal(err) + } + if f.posts != posts { + t.Fatalf("second sync wrote %d docs", f.posts-posts) + } + for _, s := range steps { + if !strings.HasPrefix(s.Result, "exists") { + t.Errorf("second sync %s: %s", s.What, s.Result) + } + } +} + +func have(t *testing.T, code string) sku { + t.Helper() + for _, s := range skus() { + if s.Code == code { + return s + } + } + t.Fatalf("no sku %s", code) + return sku{} +} + +// The quote's Mehrverbrauch row: Prüfwerk's extra Prüfobjekte and Prüftage +// at their list rates (or the price list), extra users for Managed Git and +// the Starter bundle; the retired per-check price is gone. +func TestQuoteOverageRow(t *testing.T) { + for _, want := range []string{ + `"item_code": "CRA-CSA-CLD-TGT"`, `"item_code": "CRA-CSA-CLD-DAY"`, + "Zusätzliche Prüfobjekte werden ", " netto je Monat", "Prüftage nach verbrauchtem Monatskontingent ", + "gemäß der jeweils gültigen Preisliste", "(Leistungsbeschreibung Prüfwerk, Abschnitt 7).", + `" INF-GIT-CLD-STD " in item_codes`, `" PLT-BNDL-" in item_codes`, `" CRA-CSA-CLD-ENT " not in item_codes`, + "Weitere Nutzer über die enthaltenen Nutzer hinaus werden je Modul nach Preisliste berechnet (Leistungsbeschreibung Breakpilot Plattform, Abschnitt 4).", + } { + if !strings.Contains(documentHTML, want) { + t.Errorf("quote template lacks %q", want) + } + } + if strings.Contains(documentHTML, "CRA-CSA-CLD-SCAN") || strings.Contains(documentHTML, "je zusätzlicher Prüfung") { + t.Error("quote template still prices single Prüfungen") + } + if strings.Count(documentHTML, "{%") != strings.Count(documentHTML, "%}") { + t.Error("unbalanced Jinja tags") + } +} + // § 14 Abs. 4 UStG and § 35a GmbHG: what the documents must show. func TestDocumentsCarryTheLegalDetails(t *testing.T) { for _, want := range []string{"Leistungszeitraum", "Leistungsdatum entspricht dem Rechnungsdatum", "USt-IdN‌r.", "doc.taxes", "net_total", "grand_total", "Reverse Charge", "Mandatsreferenz", "Gläubiger-Identifikationsnummer", "Leistungsbeginn", "Abrechnungsintervall", "Vertragsgrundlage", "Auftragsnummer", "nach Erteilung eines gültigen SEPA-Lastschriftmandats", "gemäß erteiltem SEPA-Lastschriftmandat", "cust != doc.customer_name", "doc.customer_address", `ca.country != "Germany"`, "{{ letter_head }}", `id="footer-html"`} { diff --git a/internal/server/erp_test.go b/internal/server/erp_test.go index 6814a36..6343888 100644 --- a/internal/server/erp_test.go +++ b/internal/server/erp_test.go @@ -334,6 +334,79 @@ func mockRequests(t *testing.T, base string) map[string]int { return counts } +// A Starter bundle (PLT-BNDL-CLD-STD) carries its modules as their own lines +// at 0,00 €. A module line at rate 0 still grants the product, with its +// quantity as seats, on both paths: the sales-order webhook and the reconcile +// of ERP Subscriptions. Neither reads the rate. +func TestErp_zeroRateModuleLinesEntitle(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + // Webhook: the body as ERPNext might send it, with rates. + tn := newTenant(t, h, "bundle-so") + body := []byte(`{"event":"sales_order.submit","doctype":"Sales Order","name":"SAL-ORD-BNDL","tenant_id":"` + tn.ID + `","subscription":"SUB-BNDL", + "items":[{"item_code":"PLT-BNDL-CLD-STD","qty":1,"rate":990},{"item_code":"CRA-CSA-CLD-STD","qty":15,"rate":0},{"item_code":"DEV-FWK-CLD-STD","qty":15,"rate":0}]}`) + req, _ := http.NewRequest("POST", h.srv.URL+"/v1/internal/erp/webhook", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set(erp.HeaderSignature, erp.Sign(testWebhookSecret, body)) + req.Header.Set(erp.HeaderEventID, "evt-bndl") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != 200 { + t.Fatalf("sales order: %d", resp.StatusCode) + } + if got := getTenant(t, h, tn.ID); got.Status != "active" || got.Plan != "standard" { + t.Fatalf("after bundle SO: status=%s plan=%s", got.Status, got.Plan) + } + for _, p := range []string{"pruefwerk", "firmwerk"} { + if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": p}); !chk.Allowed || toF(chk.Limits["seats"]) != 15 { + t.Fatalf("%s from a 0 € line: %+v", p, chk) + } + } + + // Reconcile: an ERP Subscription with a 0 € module plan. + mock := erpmock.New(erpmock.Config{APIKey: "k", APISecret: "s", WebhookURL: h.srv.URL + "/v1/internal/erp/webhook", WebhookSecret: testWebhookSecret}) + ms := httptest.NewServer(mock) + defer ms.Close() + h.app.ERP = erp.New(erp.Config{BaseURL: ms.URL, APIKey: "k", APISecret: "s"}) + tr := newTenant(t, h, "bundle-sub") + if _, err := h.store.UpdateTenant(t.Context(), tr.ID, store.TenantUpdate{ErpCustomerID: ptr("CUST-BNDL")}); err != nil { + t.Fatal(err) + } + buf, _ := json.Marshal(map[string]any{"party": "CUST-BNDL", "status": "Active", "sales_order": "SAL-ORD-BNDL2", "plans": []map[string]any{ + {"plan": "PLT-BNDL-CLD-STD", "qty": 1, "rate": 990}, {"plan": "CRA-CSA-CLD-STD", "qty": 15, "rate": 0}, + }}) + sreq, _ := http.NewRequest("POST", ms.URL+"/api/resource/Subscription", bytes.NewReader(buf)) + sreq.Header.Set("Authorization", "token k:s") + sresp, err := http.DefaultClient.Do(sreq) + if err != nil { + t.Fatal(err) + } + _ = sresp.Body.Close() + if sresp.StatusCode != 200 { + t.Fatalf("mock subscription: %d", sresp.StatusCode) + } + if _, raw := h.do("POST", "/v1/internal/erp/reconcile", nil); !bytes.Contains(raw, []byte(`"bundle-sub"`)) { + t.Fatalf("reconcile: %s", raw) + } + if got := getTenant(t, h, tr.ID); got.Status != "active" { + t.Fatalf("after reconcile: %s", got.Status) + } + if chk := check(t, h, map[string]any{"tenant_id": tr.ID, "product": "pruefwerk"}); !chk.Allowed || toF(chk.Limits["seats"]) != 15 { + t.Fatalf("pruefwerk from a 0 € plan: %+v", chk) + } + _, raw := h.do("GET", "/v1/subscriptions?tenant_id="+tr.ID, nil) + subs := decode[struct { + Items []store.Subscription `json:"items"` + }](t, raw).Items + // The bundle fee unlocks nothing and is not mirrored. + if len(subs) != 1 || subs[0].SKU != "CRA-CSA-CLD-STD" || subs[0].Seats != 15 || subs[0].Status != store.SubscriptionActive { + t.Fatalf("subscriptions: %+v", subs) + } + }) +} + func TestReconcile_ladderEscalation(t *testing.T) { eachStore(t, func(t *testing.T, h *testHarness) { warn := newTenant(t, h, "esc-warning") diff --git a/internal/store/products.go b/internal/store/products.go index 5a965b6..d5eb3f7 100644 --- a/internal/store/products.go +++ b/internal/store/products.go @@ -7,8 +7,8 @@ import ( "time" ) -// DefaultProducts mirrors the seed rows of migrations/0003_products.up.sql -// and 0014_werkmeister_product.up.sql +// DefaultProducts mirrors the seed rows of migrations/0003_products.up.sql, +// 0014_werkmeister_product.up.sql and 0026_pruefwerk_tgt_day_skus.up.sql // for the Memory store. Keep the two in sync. func DefaultProducts() []Product { now := time.Now().UTC() @@ -19,7 +19,8 @@ func DefaultProducts() []Product { Description: "Compliance scanner for CRA / IEC 62443 style assessments: SBOM, DAST, pentest orchestration, PLC provisioning tests.", LaunchURLs: map[string]string{"stage": "https://pruefwerk-stage.breakpilot.com", "prod": "https://pruefwerk.breakpilot.com"}, ProvisionURLs: map[string]string{}, - SKUs: []string{"CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN"}, + // SCAN is no longer sold (TGT and DAY replace it) but old orders still map. + SKUs: []string{"CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN", "CRA-CSA-CLD-TGT", "CRA-CSA-CLD-DAY"}, Addons: []ProductAddon{{ID: "werkbank", Name: "Werkbank runner", LimitKey: "runners", SKUs: []string{"CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT"}}}, PlansRequired: plans, SupportsTrial: true, TrialDays: 14, Enabled: true, SortOrder: 10, CreatedAt: now, UpdatedAt: now, }, diff --git a/migrations/0026_pruefwerk_tgt_day_skus.down.sql b/migrations/0026_pruefwerk_tgt_day_skus.down.sql new file mode 100644 index 0000000..def95c1 --- /dev/null +++ b/migrations/0026_pruefwerk_tgt_day_skus.down.sql @@ -0,0 +1,3 @@ +UPDATE products +SET skus = skus - 'CRA-CSA-CLD-TGT' - 'CRA-CSA-CLD-DAY' +WHERE key = 'pruefwerk'; diff --git a/migrations/0026_pruefwerk_tgt_day_skus.up.sql b/migrations/0026_pruefwerk_tgt_day_skus.up.sql new file mode 100644 index 0000000..6e73dc8 --- /dev/null +++ b/migrations/0026_pruefwerk_tgt_day_skus.up.sql @@ -0,0 +1,6 @@ +-- Leistungsbeschreibung Prüfwerk 1.0.0: extra Prüfobjekte (CRA-CSA-CLD-TGT) +-- and Prüftage (CRA-CSA-CLD-DAY) replace the single extra Prüfung +-- (CRA-CSA-CLD-SCAN). SCAN stays in the list so old orders still map. +UPDATE products +SET skus = skus || '["CRA-CSA-CLD-TGT", "CRA-CSA-CLD-DAY"]'::jsonb +WHERE key = 'pruefwerk' AND NOT skus @> '["CRA-CSA-CLD-TGT"]'::jsonb; diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index c15b196..ef51d93 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -3,6 +3,7 @@ package migrations import ( "context" "database/sql" + "encoding/json" "errors" "fmt" "strings" @@ -14,6 +15,8 @@ import ( "github.com/golang-migrate/migrate/v4/source/iofs" _ "github.com/jackc/pgx/v5/stdlib" // pgx stdlib driver for database/sql tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres" + + "git.breakpilot.com/platform/tenant-registry/internal/store" ) // startPostgres spins a fresh postgres:16-alpine container and returns its @@ -498,3 +501,67 @@ func TestMigrate_0023MovesOwnDocumentsIntoTheStore(t *testing.T) { t.Errorf("after down: %v", got) } } + +// The seeded products match store.DefaultProducts (the Memory store's copy), +// and 0026 adds the Prüfwerk SKUs TGT and DAY once, keeping SCAN; its down +// takes them out again. +func TestMigrate_productsSeedMatchesDefaults(t *testing.T) { + if testing.Short() { + t.Skip("skipping integration test under -short") + } + dsn, stop := startPostgres(t) + defer stop() + m := newMigrator(t, dsn) + if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { + t.Fatalf("up: %v", err) + } + db, err := sql.Open("pgx", dsn) + if err != nil { + t.Fatal(err) + } + defer func() { _ = db.Close() }() + + seeded := func(key string) ([]string, []store.ProductAddon) { + t.Helper() + var skus, addons []byte + if err := db.QueryRow(`SELECT skus, addons FROM products WHERE key = $1`, key).Scan(&skus, &addons); err != nil { + t.Fatalf("product %s: %v", key, err) + } + var s []string + var a []store.ProductAddon + if err := json.Unmarshal(skus, &s); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(addons, &a); err != nil { + t.Fatal(err) + } + return s, a + } + for _, p := range store.DefaultProducts() { + skus, addons := seeded(p.Key) + if fmt.Sprint(skus) != fmt.Sprint(p.SKUs) { + t.Errorf("%s: seeded SKUs %v, DefaultProducts %v", p.Key, skus, p.SKUs) + } + if fmt.Sprint(addons) != fmt.Sprint(p.Addons) { + t.Errorf("%s: seeded add-ons %v, DefaultProducts %v", p.Key, addons, p.Addons) + } + } + + // Applied again (e.g. after a manual fix), 0026 adds nothing twice. + up, err := FS.ReadFile("0026_pruefwerk_tgt_day_skus.up.sql") + if err != nil { + t.Fatal(err) + } + if _, err := db.Exec(string(up)); err != nil { + t.Fatal(err) + } + if skus, _ := seeded("pruefwerk"); fmt.Sprint(skus) != "[CRA-CSA-CLD-STD CRA-CSA-CLD-BUS CRA-CSA-CLD-ENT CRA-CSA-CLD-SCAN CRA-CSA-CLD-TGT CRA-CSA-CLD-DAY]" { + t.Errorf("0026 twice: %v", skus) + } + if err := m.Migrate(25); err != nil { + t.Fatalf("down to 25: %v", err) + } + if skus, _ := seeded("pruefwerk"); fmt.Sprint(skus) != "[CRA-CSA-CLD-STD CRA-CSA-CLD-BUS CRA-CSA-CLD-ENT CRA-CSA-CLD-SCAN]" { + t.Errorf("after down: %v", skus) + } +}