From 834178b86955ff3a373a819b60906c058309a44d Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 30 Sep 2026 12:11:36 +0200 Subject: [PATCH] feat(erpsetup): BreakPilot document layout and list prices MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Letter head "BreakPilot" (chevron, sender block, legal footer with register, directors, USt-IdNr. and bank), company address, one print format for Angebot / Auftragsbestätigung / Rechnung (§ 14 UStG details, Leistungszeitraum, reverse-charge note, SEPA pre-notification) set as default, and the invoice e-mail template. - Company.sepa_creditor_id for the Gläubiger-ID on invoices. - List prices from the SKU sheet on Standard Selling, created only where missing; prices changed in ERPNext are never overwritten. - ensureFields updates templates we own when they drift; ensureListed handles autonamed docs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- cmd/erpsetup/main.go | 5 +- internal/erpsetup/branding.go | 280 +++++++++++++++++++++++++++++ internal/erpsetup/catalog.go | 58 +++--- internal/erpsetup/erpsetup.go | 121 ++++++++++++- internal/erpsetup/erpsetup_test.go | 98 +++++++++- 5 files changed, 530 insertions(+), 32 deletions(-) create mode 100644 internal/erpsetup/branding.go diff --git a/cmd/erpsetup/main.go b/cmd/erpsetup/main.go index 700fc3e..f09a718 100644 --- a/cmd/erpsetup/main.go +++ b/cmd/erpsetup/main.go @@ -1,6 +1,7 @@ // erpsetup — applies the live-ERPNext configuration the tenant-registry needs -// (custom fields, the Usage Record doctype, the sales catalogue with SKU items -// and SEPA mandate fields, the Frappe Webhooks). Idempotent; +// (custom fields, the Usage Record doctype, the sales catalogue with SKU items, +// list prices and SEPA mandate fields, the document layout, the Frappe +// Webhooks). Idempotent; // run with -dry-run first. It never submits, cancels or deletes ERP documents. // // ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… \ diff --git a/internal/erpsetup/branding.go b/internal/erpsetup/branding.go new file mode 100644 index 0000000..4c3e03e --- /dev/null +++ b/internal/erpsetup/branding.go @@ -0,0 +1,280 @@ +package erpsetup + +// The BreakPilot look of the documents ERPNext sends: the company address, +// the letter head (logo, sender block, legal footer), one print format for +// offers, order confirmations and invoices, and the invoice e-mail. The +// templates read their data from ERPNext (company, address, bank account, +// customer mandate), so a change there needs no new run. +// +// Print formats are rendered by wkhtmltopdf: tables for layout, no flexbox. + +import "strings" + +// companyName is the ERPNext Company the documents belong to. +const companyName = "BreakPilot GmbH" + +// Legal lines every business letter of a GmbH carries (§ 35a GmbHG) that +// ERPNext has no field for. Same text as the platform mails. +const ( + legalRegister = "Sitz Bodman-Ludwigshafen · Amtsgericht Freiburg, HRB 736403" + legalDirectors = "Geschäftsführer: Benjamin Bönisch, Sharang Deepak Parnerkar" +) + +const ( + letterHeadName = "BreakPilot" + emailTemplateRE = "BreakPilot Rechnung" + printFormatRE = "BreakPilot Rechnung" + printFormatSO = "BreakPilot Auftragsbestätigung" + printFormatQuote = "BreakPilot Angebot" +) + +// brandingFields: the SEPA creditor identifier on the Company. It is printed +// on every invoice paid by direct debit (pre-notification). +func brandingFields() []map[string]any { + f := customField("Company", "sepa_creditor_id", "Gläubiger-Identifikationsnummer (SEPA)", "Data", "tax_id", false) + f["description"] = "Von der Deutschen Bundesbank vergeben, z. B. DE98ZZZ09999999999. Erscheint auf Rechnungen mit SEPA-Lastschrift." + return []map[string]any{f} +} + +// companyAddressDoc is the registered office, marked as the company's own +// address so ERPNext puts it on every sales document. +func companyAddressDoc() map[string]any { + return map[string]any{ + "doctype": "Address", "address_title": companyName, "address_type": "Billing", + "address_line1": "In Steinäckern 16", "pincode": "78351", "city": "Bodman-Ludwigshafen", + "country": "Germany", "email_id": "kontakt@breakpilot.com", + "is_your_company_address": 1, "is_primary_address": 1, + "links": []map[string]any{{"link_doctype": "Company", "link_name": companyName}}, + } +} + +func letterHeadDoc() map[string]any { + return map[string]any{ + "doctype": "Letter Head", "name": letterHeadName, "letter_head_name": letterHeadName, + "source": "HTML", "footer_source": "HTML", "is_default": 1, "disabled": 0, + "content": letterHeadHTML, "footer": letterFooterHTML, + } +} + +func printFormatDoc(name, doctype, module string) map[string]any { + return map[string]any{ + "doctype": "Print Format", "name": name, "doc_type": doctype, "module": module, + "standard": "No", "custom_format": 1, "print_format_type": "Jinja", "disabled": 0, + "pdf_generator": "wkhtmltopdf", "default_print_language": "de", + "margin_top": 12, "margin_bottom": 28, "margin_left": 18, "margin_right": 15, + "html": documentHTML, + } +} + +func printFormats() []map[string]any { + return []map[string]any{ + printFormatDoc(printFormatRE, "Sales Invoice", "Accounts"), + printFormatDoc(printFormatSO, "Sales Order", "Selling"), + printFormatDoc(printFormatQuote, "Quotation", "Selling"), + } +} + +// docTypeSetter sets a DocType-level property (default print format, default +// e-mail template) through a Property Setter. +func docTypeSetter(doctype, prop, value string) map[string]any { + return map[string]any{ + "doctype": "Property Setter", "name": doctype + "-main-" + prop, + "doctype_or_field": "DocType", "doc_type": doctype, + "property": prop, "property_type": "Data", "value": value, + } +} + +func brandingSetters() []map[string]any { + return []map[string]any{ + docTypeSetter("Sales Invoice", "default_print_format", printFormatRE), + docTypeSetter("Sales Order", "default_print_format", printFormatSO), + docTypeSetter("Quotation", "default_print_format", printFormatQuote), + docTypeSetter("Sales Invoice", "default_email_template", emailTemplateRE), + } +} + +func emailTemplateDoc() map[string]any { + return map[string]any{ + "doctype": "Email Template", "name": emailTemplateRE, "enabled": 1, + "reference_doctype": "Sales Invoice", + "subject": "Rechnung {{ name }} – BreakPilot", + "use_html": 1, "response_html": invoiceMailHTML, + } +} + +// Brand colours (as in the platform mails and the portal). +var brand = strings.NewReplacer( + "$INK", "#14162B", "$MUTED", "#5E6384", "$FAINT", "#8B8FAE", + "$ACCENT", "#4F46E5", "$ACCENT2", "#7C3AED", "$LINE", "#E4E6F0", + "$REGISTER_BR", "Sitz Bodman-Ludwigshafen
Amtsgericht Freiburg, HRB 736403", + "$DIRECTORS_BR", "Geschäftsführer:
Benjamin Bönisch
Sharang Deepak Parnerkar", + "$REGISTER", legalRegister, "$DIRECTORS", legalDirectors, +) + +// logoSVG is the chevron from the portal favicon, inline so wkhtmltopdf needs +// no network access. +const logoSVG = `` + +// Shared Jinja: the company's own address and its bank account. +const companyVars = `{%- set bp_addr = frappe.db.get_value("Address", {"is_your_company_address": 1, "is_primary_address": 1, "disabled": 0}, ["address_line1", "pincode", "city", "email_id"], as_dict=1) or {"address_line1": "In Steinäckern 16", "pincode": "78351", "city": "Bodman-Ludwigshafen", "email_id": "kontakt@breakpilot.com"} -%} +{%- set bp_bank = frappe.db.get_value("Bank Account", {"is_company_account": 1, "company": doc.company}, ["bank", "iban"], as_dict=1) or {} -%}` + +var letterHeadHTML = brand.Replace(strings.ReplaceAll(`${companyVars} + + + + + +
+ + + +
`+logoSVG+`BreakPilot
+
+{{ doc.company }}
+{{ bp_addr.address_line1 }}
{{ bp_addr.pincode }} {{ bp_addr.city }}
+{{ bp_addr.email_id or "kontakt@breakpilot.com" }} · www.breakpilot.com +
+
`, "${companyVars}", companyVars)) + +var letterFooterHTML = brand.Replace(strings.ReplaceAll(`${companyVars} +{%- set bp_bic = frappe.db.get_value("Bank", bp_bank.bank, "swift_number") if bp_bank.bank else "" -%} + + + + + + + +
{{ doc.company }}
{{ bp_addr.address_line1 }}
{{ bp_addr.pincode }} {{ bp_addr.city }}
$REGISTER_BR
USt-IdNr. {{ frappe.db.get_value("Company", doc.company, "tax_id") or "" }}
$DIRECTORS_BR{% if bp_bank.iban %}{{ bp_bank.bank }}
IBAN {{ bp_bank.iban }}{% if bp_bic %}
BIC {{ bp_bic }}{% endif %}{% endif %}
`, "${companyVars}", companyVars)) + +// documentHTML is the body of the offer, the order confirmation and the +// invoice. § 14 Abs. 4 UStG: supplier and recipient, tax numbers, date, +// number, items with quantity and unit, service period, net by rate, tax +// rate and amount, gross; reverse-charge note where it applies. +var documentHTML = brand.Replace(`{%- set is_inv = doc.doctype == "Sales Invoice" -%} +{%- set is_so = doc.doctype == "Sales Order" -%} +{%- set title = ("Rechnungskorrektur" if doc.is_return else "Rechnung") if is_inv else ("Auftragsbestätigung" if is_so else "Angebot") -%} +{%- set doc_date = doc.posting_date if is_inv else doc.transaction_date -%} +{%- set bp_addr = frappe.db.get_value("Address", {"is_your_company_address": 1, "is_primary_address": 1, "disabled": 0}, ["address_line1", "pincode", "city", "email_id"], as_dict=1) or {"address_line1": "In Steinäckern 16", "pincode": "78351", "city": "Bodman-Ludwigshafen", "email_id": "kontakt@breakpilot.com"} -%} +{%- set cust = doc.customer if doc.doctype != "Quotation" else doc.party_name -%} +{%- set mandate = frappe.db.get_value("Customer", cust, ["sepa_mandate_reference", "sepa_mandate_type"], as_dict=1) if doc.doctype != "Quotation" or doc.quotation_to == "Customer" else None -%} +{%- set sepa = doc.payment_schedule and doc.payment_schedule[0].mode_of_payment == "SEPA-Lastschrift" -%} +{%- set tpl = doc.taxes_and_charges or "" -%} +{%- set period_from = doc.get("from_date") or (doc.items[0].get("service_start_date") if doc.items else None) -%} +{%- set period_to = doc.get("to_date") or (doc.items[0].get("service_end_date") if doc.items else None) -%} + +
+ + + +
+
{{ doc.company }} · {{ bp_addr.address_line1 }} · {{ bp_addr.pincode }} {{ bp_addr.city }}
+{{ doc.customer_name }}
+{{ doc.address_display or "" }} +
+ + + + +{%- if doc.get("tax_id") %}{% endif %} +{%- if is_inv and not doc.is_return %}{% endif %} +{%- if doc.doctype == "Quotation" and doc.valid_till %}{% endif %} +{%- if doc.get("po_no") %}{% endif %} +
Nummer{{ doc.name }}
Datum{{ frappe.utils.formatdate(doc_date) }}
Kundennummer{{ cust }}
Ihre USt-IdNr.{{ doc.tax_id }}
Fällig am{{ frappe.utils.formatdate(doc.due_date) }}
Gültig bis{{ frappe.utils.formatdate(doc.valid_till) }}
Ihre Bestellung{{ doc.po_no }}
+
+ +

{{ title }}

+{%- if is_inv and doc.is_return and doc.return_against %}
zu Rechnung {{ doc.return_against }}
{% endif %} +{%- if is_inv %} +
Leistungszeitraum: {% if period_from and period_to %}{{ frappe.utils.formatdate(period_from) }} – {{ frappe.utils.formatdate(period_to) }}{% else %}Das Leistungsdatum entspricht dem Rechnungsdatum.{% endif %}
+{%- endif %} + + + + + + +{%- for it in doc.items %} + + + + + + + +{%- endfor %} + +
Pos.LeistungMengeEinzelpreisBetrag
{{ loop.index }}{{ it.item_name }}
{{ it.item_code }}{% if it.description and it.description != it.item_name %} · {{ it.description | striptags }}{% endif %}{% if it.get("service_start_date") and it.get("service_end_date") and not doc.get("from_date") %}
Zeitraum {{ frappe.utils.formatdate(it.service_start_date) }} – {{ frappe.utils.formatdate(it.service_end_date) }}{% endif %}
{{ ("%g"|format(it.qty)) | replace(".", ",") }} {{ it.uom }}{{ it.get_formatted("rate", doc) }}{{ it.get_formatted("amount", doc) }}
+ + + +{%- if doc.discount_amount %}{% endif %} +{%- for t in doc.taxes %}{% if t.tax_amount %} + +{%- endif %}{% endfor %} + +
Summe netto{{ doc.get_formatted("net_total") }}
Rabatt− {{ doc.get_formatted("discount_amount") }}
{{ t.description }}{% if t.rate and "%" not in t.description %} ({{ ("%g"|format(t.rate)) | replace(".", ",") }} %){% endif %}{{ t.get_formatted("tax_amount", doc) }}
Gesamtbetrag{{ doc.get_formatted("rounded_total" if doc.rounded_total else "grand_total") }}
+ +
+{%- if "an Unternehmen in der EU" in tpl %} +

Steuerschuldnerschaft des Leistungsempfängers (Reverse Charge, § 13b UStG / Art. 196 MwStSystRL).

+{%- elif "Drittland" in tpl %} +

Nicht im Inland steuerbare Leistung.

+{%- endif %} +{%- if is_inv and not doc.is_return %} +{%- if sepa %} +{%- set creditor = frappe.db.get_value("Company", doc.company, "sepa_creditor_id") %} +

Wir ziehen den Rechnungsbetrag von {{ doc.get_formatted("rounded_total" if doc.rounded_total else "grand_total") }} am {{ frappe.utils.formatdate(doc.due_date) }} per SEPA-{{ "Firmenlastschrift" if mandate and mandate.sepa_mandate_type and "B2B" in mandate.sepa_mandate_type else "Lastschrift" }} von Ihrem Konto ein{% if creditor or (mandate and mandate.sepa_mandate_reference) %} (Gläubiger-ID {{ creditor or "–" }}, Mandatsreferenz {{ (mandate and mandate.sepa_mandate_reference) or "–" }}){% endif %}. Bitte sorgen Sie für ausreichende Deckung.

+{%- else %} +

Bitte überweisen Sie den Rechnungsbetrag bis zum {{ frappe.utils.formatdate(doc.due_date) }} unter Angabe der Rechnungsnummer {{ doc.name }}.

+{%- endif %} +{%- elif not is_inv and sepa %} +

Zahlung per SEPA-Lastschrift nach Rechnungsstellung.

+{%- endif %} +{%- if doc.get("terms") %}
{{ doc.terms }}
{% endif %} +

Vielen Dank für Ihr Vertrauen.

+
+
`) + +// invoiceMailHTML goes with the PDF when an invoice is sent from ERPNext. +// Email templates render with the document's fields as top-level names. +var invoiceMailHTML = brand.Replace(`
+

Guten Tag,

+

anbei erhalten Sie unsere Rechnung {{ name }} vom {{ frappe.utils.formatdate(posting_date) }} über {{ frappe.utils.fmt_money(grand_total, currency=currency) }}.

+{% if payment_schedule and payment_schedule[0].mode_of_payment == "SEPA-Lastschrift" -%} +

Den Betrag ziehen wir am {{ frappe.utils.formatdate(due_date) }} per SEPA-Lastschrift ein. Die Einzelheiten stehen auf der Rechnung.

+{%- else -%} +

Bitte überweisen Sie den Betrag bis zum {{ frappe.utils.formatdate(due_date) }}.

+{%- endif %} +

Bei Fragen zur Rechnung antworten Sie einfach auf diese E-Mail.

+
+
Mit freundlichen Grüßen
+
Ihr BreakPilot-Team
+
{{ company }}
+
In Steinäckern 16, 78351 Bodman-Ludwigshafen
+ +
 
+
USt-IdNr. DE464808363 · $REGISTER
+
$DIRECTORS
+
+
`) diff --git a/internal/erpsetup/catalog.go b/internal/erpsetup/catalog.go index 0267777..dd8b2d8 100644 --- a/internal/erpsetup/catalog.go +++ b/internal/erpsetup/catalog.go @@ -3,41 +3,46 @@ 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. -// Prices are not set here: they live in ERPNext (price list or quotation). +// 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. const itemGroup = "BreakPilot Abonnements" type sku struct { Code, Name, UOM, Description string + Price float64 // list price, net EUR per UOM } +// 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. 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."}, - {"PLT-CORE-CLD-BUS", "BreakPilot Plattform – Growth", "Monat", "Arbeitsbereich für bis 100 Nutzer, beliebig viele Produkte, monatlicher Nutzungsbericht, vorrangiger Support."}, - {"PLT-CORE-CLD-ENT", "BreakPilot Plattform – Enterprise", "Monat", "Arbeitsbereich ohne Nutzergrenze, persönliche Betreuung, individuelle Verträge (AVV), Wahl der EU-Region."}, - {"CRA-CSA-CLD-STD", "Prüfwerk Cloud – Standard", "Monat", "Automatische CRA-Prüfung von Quellcode, Firmware und SPS-Programmen: 5 Prüfobjekte, 50 Prüfungen im Monat, monatliches Nachweispaket."}, - {"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."}, - {"CRA-CSA-CLD-ENT", "Prüfwerk Cloud – Enterprise", "Monat", "Prüfwerk ohne Obergrenzen, eigener Kontrollkatalog, Nachweisexport für abgeschottete Umgebungen."}, - {"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."}, - {"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."}, - {"CRA-WBK-CLD-BUS", "Werkbank Runner Cloud – Business", "Monat", "Prüfmaschine mit parallelen Prüfungen (2 vCPU / 4 GB); Zusatz zu Prüfwerk."}, - {"CRA-WBK-CLD-ENT", "Werkbank Runner Cloud – Enterprise", "Monat", "Prüfmaschine mit eigenen Prüfmodulen (4 vCPU / 8 GB); Zusatz zu Prüfwerk."}, - {"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."}, - {"DEV-WP-CLD-BUS", "Werkpilot Cloud – Business", "Monat", "Werkpilot mit reservierter KI-Kapazität und Single Sign-on; je Nutzer und Monat."}, - {"DEV-WP-CLD-ENT", "Werkpilot Cloud – Enterprise", "Monat", "Werkpilot auf eigener KI-Instanz, optional auf Ihren Code abgestimmt; je Nutzer und Monat."}, - {"DEV-WP-OPR-STD", "Werkpilot On-Prem – Standard", "Jahr", "Werkpilot im eigenen Netz, ohne dass Quellcode das Haus verlässt; Jahreslizenz."}, - {"DEV-WP-OPR-BUS", "Werkpilot On-Prem – Business", "Jahr", "Werkpilot im eigenen Netz für mittlere Teams; Jahreslizenz."}, - {"DEV-WP-OPR-ENT", "Werkpilot On-Prem – Enterprise", "Jahr", "Werkpilot im eigenen Netz für große Entwicklungsorganisationen; Jahreslizenz."}, - {"DEV-FWK-CLD-STD", "Firmwerk Cloud – Standard", "Monat", "Reproduzierbare Firmware-Builds mit Stückliste und Nachweis, 10 Umgebungen je Nutzer; je Nutzer und Monat."}, - {"DEV-FWK-CLD-BUS", "Firmwerk Cloud – Business", "Monat", "Firmwerk mit beliebig vielen Umgebungen und Team-Freigabe; je Nutzer und Monat."}, - {"DEV-FWK-CLD-ENT", "Firmwerk Cloud – Enterprise", "Monat", "Firmwerk mit eigenen Toolchains und LTS-Stand; je Nutzer und Monat."}, - {"DEV-FWK-OPR-STD", "Firmwerk On-Prem – Standard", "Jahr", "Firmwerk im eigenen Netz; Jahreslizenz."}, - {"DEV-FWK-OPR-BUS", "Firmwerk On-Prem – Business", "Jahr", "Firmwerk im eigenen Netz für größere Teams; Jahreslizenz."}, - {"DEV-FWK-OPR-ENT", "Firmwerk On-Prem – Enterprise", "Jahr", "Firmwerk im eigenen Netz für große Organisationen; Jahreslizenz."}, + {"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", "Automatische CRA-Prüfung von Quellcode, Firmware und SPS-Programmen: 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}, } } @@ -97,3 +102,10 @@ func invoiceSeriesSetters() []map[string]any { } return []map[string]any{setter("options", "Text"), setter("default", "Text")} } + +func itemPriceDoc(s sku) map[string]any { + return map[string]any{ + "doctype": "Item Price", "item_code": s.Code, "price_list": priceList, "uom": s.UOM, + "price_list_rate": s.Price, "currency": "EUR", "selling": 1, + } +} diff --git a/internal/erpsetup/erpsetup.go b/internal/erpsetup/erpsetup.go index 0238e59..0fd6086 100644 --- a/internal/erpsetup/erpsetup.go +++ b/internal/erpsetup/erpsetup.go @@ -1,8 +1,9 @@ // Package erpsetup applies the live-ERPNext configuration the registry relies // on (ERP/03 "live configuration"): custom fields that carry the tenant id, the // Usage Record doctype the outbox writes, the sales catalogue (SKU items, units, -// SEPA mandate fields, payment method) and the Frappe Webhooks that drive the -// tenant ladder. Every step checks first and creates only what is missing, +// SEPA mandate fields, payment method, list prices), the document layout +// (letter head, print formats, invoice e-mail) and the Frappe Webhooks that +// drive the tenant ladder. Every step checks first and creates only what is missing, // so it can run again at any time; with DryRun it only reports. // // It never submits, cancels or deletes an ERP document. @@ -101,6 +102,39 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) { return r.steps, err } } + 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 { + return r.steps, err + } + } + // Documents in the BreakPilot look: creditor id field, company address, + // letter head, print formats, invoice e-mail and the defaults. + for _, f := range brandingFields() { + if err := r.ensure(ctx, "Custom Field", f["name"].(string), fmt.Sprintf("custom field %s.%s", f["dt"], f["fieldname"]), f); err != nil { + return r.steps, err + } + } + if err := r.ensureListed(ctx, "Address", "company address "+companyName, + [][]any{{"is_your_company_address", "=", 1}}, companyAddressDoc()); err != nil { + return r.steps, err + } + if err := r.ensureFields(ctx, "Letter Head", letterHeadName, "letter head "+letterHeadName, letterHeadDoc(), "content", "footer"); err != nil { + return r.steps, err + } + for _, pf := range printFormats() { + if err := r.ensureFields(ctx, "Print Format", pf["name"].(string), fmt.Sprintf("print format %s (%s)", pf["name"], pf["doc_type"]), pf, "html"); err != nil { + return r.steps, err + } + } + if err := r.ensureFields(ctx, "Email Template", emailTemplateRE, "email template "+emailTemplateRE, emailTemplateDoc(), "subject", "response_html"); err != nil { + return r.steps, err + } + for _, ps := range brandingSetters() { + if err := r.ensureValue(ctx, "Property Setter", ps["name"].(string), fmt.Sprintf("%s %s → %s", ps["doc_type"], ps["property"], ps["value"]), ps); err != nil { + return r.steps, err + } + } for _, w := range webhooks(cfg.WebhookURL, cfg.WebhookSecret) { if err := r.ensureWebhook(ctx, w); err != nil { return r.steps, err @@ -180,6 +214,89 @@ func (r *runner) ensureValue(ctx context.Context, doctype, name, what string, do return nil } +// ensureFields is ensure for a doc whose content we own (templates): an +// existing doc whose listed fields differ gets them set again. +func (r *runner) ensureFields(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{} + for _, k := range keys { + if fmt.Sprint(cur.Data[k]) != fmt.Sprint(doc[k]) { + patch[k] = doc[k] + } + } + if len(patch) == 0 { + r.record(what, "exists") + return nil + } + if r.cfg.DryRun { + r.record(what, "would update") + 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") + return nil +} + +// 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). +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"}} + status, body, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(doctype)+"?"+q.Encode(), nil) + if err != nil { + return err + } + if status != http.StatusOK { + return fmt.Errorf("erpsetup: list %s: HTTP %d %s", doctype, status, truncate(body)) + } + var list struct { + Data []struct { + Name string `json:"name"` + } `json:"data"` + } + if err := json.Unmarshal(body, &list); err != nil { + return fmt.Errorf("erpsetup: decode %s list: %w", doctype, err) + } + if len(list.Data) > 0 { + r.record(what, "exists ("+list.Data[0].Name+")") + return nil + } + if r.cfg.DryRun { + r.record(what, "would create") + return nil + } + status, body, err = r.call(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(doctype), doc) + 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 +} + // 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 5f0c6bd..dd9c29c 100644 --- a/internal/erpsetup/erpsetup_test.go +++ b/internal/erpsetup/erpsetup_test.go @@ -3,6 +3,7 @@ package erpsetup import ( "context" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -63,6 +64,23 @@ func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.webhooks = append(f.webhooks, doc) f.posts++ _ = json.NewEncoder(w).Encode(map[string]any{"data": doc}) + case r.Method == http.MethodGet && len(parts) == 1: + // list with ["field", "=", value] filters + var filters [][]any + _ = json.Unmarshal([]byte(r.URL.Query().Get("filters")), &filters) + out := []map[string]any{} + for name, d := range f.docs[doctype] { + match := true + for _, c := range filters { + if fmt.Sprint(d[c[0].(string)]) != fmt.Sprint(c[2]) { + match = false + } + } + if match { + out = append(out, map[string]any{"name": name}) + } + } + _ = json.NewEncoder(w).Encode(map[string]any{"data": out}) case r.Method == http.MethodGet && len(parts) == 2: name, _ := url.PathUnescape(parts[1]) if d, ok := f.docs[doctype][name]; ok { @@ -76,7 +94,11 @@ func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) { if f.docs[doctype] == nil { f.docs[doctype] = map[string]map[string]any{} } - f.docs[doctype][doc["name"].(string)] = doc + name, _ := doc["name"].(string) + if name == "" { + name = fmt.Sprintf("%s-%d", doctype, len(f.docs[doctype])+1) + } + f.docs[doctype][name] = doc f.posts++ _, _ = io.WriteString(w, `{"data":{}}`) case r.Method == http.MethodPut && len(parts) == 2: @@ -111,8 +133,8 @@ func TestRunCreatesThenIsIdempotent(t *testing.T) { if err != nil { t.Fatal(err) } - if len(steps) != 42 || f.posts != 42 { - t.Fatalf("first run: %d steps, %d creates; want 42/42: %+v", len(steps), f.posts, steps) + if len(steps) != 75 || f.posts != 75 { + t.Fatalf("first run: %d steps, %d creates; want 75/75: %+v", len(steps), f.posts, steps) } for _, s := range steps { if s.Result != "created" { @@ -128,8 +150,8 @@ func TestRunCreatesThenIsIdempotent(t *testing.T) { if err != nil { t.Fatal(err) } - if f.posts != 42 { - t.Fatalf("second run created %d more docs", f.posts-42) + if f.posts != 75 { + t.Fatalf("second run created %d more docs", f.posts-75) } for _, s := range steps { if !strings.HasPrefix(s.Result, "exists") { @@ -375,3 +397,69 @@ func TestInvoiceSeriesIsRestored(t *testing.T) { t.Fatalf("updated %d steps: %+v", updated, steps) } } + +func TestChangedTemplateIsUpdatedAndPricesKept(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) + } + f.docs["Print Format"][printFormatRE]["html"] = "old" + for _, p := range f.docs["Item Price"] { + p["price_list_rate"] = 1.0 // changed in ERPNext by hand + } + c := cfg(srv.URL) + c.DryRun = true + steps, err := Run(context.Background(), c) + if err != nil { + t.Fatal(err) + } + var changes []string + for _, s := range steps { + if !strings.HasPrefix(s.Result, "exists") { + changes = append(changes, s.What+": "+s.Result) + } + } + if len(changes) != 1 || !strings.Contains(changes[0], "print format "+printFormatRE) || !strings.HasSuffix(changes[0], "would update") { + t.Fatalf("dry run changes: %v", changes) + } + if _, err := Run(context.Background(), cfg(srv.URL)); err != nil { + t.Fatal(err) + } + if f.docs["Print Format"][printFormatRE]["html"] != documentHTML { + t.Fatal("print format not updated") + } + for _, p := range f.docs["Item Price"] { + if p["price_list_rate"] != 1.0 { + t.Fatalf("price overwritten: %v", p) + } + } +} + +func TestEverySKUHasAListPrice(t *testing.T) { + for _, s := range skus() { + if s.Price <= 0 { + t.Errorf("%s has no price", s.Code) + } + } +} + +// § 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-IdNr.", "doc.taxes", "net_total", "grand_total", "Reverse Charge", "Mandatsreferenz", "Gläubiger-ID", "doc.address_display"} { + if !strings.Contains(documentHTML, want) { + t.Errorf("document template lacks %q", want) + } + } + for _, want := range []string{"HRB 736403", "Amtsgericht Freiburg", "Geschäftsführer", "tax_id", "IBAN"} { + if !strings.Contains(letterFooterHTML, want) { + t.Errorf("letter footer lacks %q", want) + } + } + for _, s := range []string{documentHTML, letterHeadHTML, letterFooterHTML, invoiceMailHTML} { + if strings.Contains(s, "$") || strings.Contains(s, "display:flex") { + t.Errorf("unreplaced colour token or flexbox in a template") + } + } +}