feat(erpsetup): BreakPilot document layout and list prices (#51)
ci / shared (push) Successful in 13s
ci / test (push) Successful in 23m50s
ci / image (push) Successful in 36s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit was merged in pull request #51.
This commit is contained in:
sharangandClaude Opus 5.5 committed 2026-09-30 10:44:03 +00:00
1 parent c33ae65342
commit 40a198c56f
5 files changed
+530 -32

No files matched your search

+3 -2
View File
@@ -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=… \
+280
View File
@@ -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" // as in the Handelsregister (small p)
// 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<br>Amtsgericht Freiburg, HRB 736403",
"$DIRECTORS_BR", "Geschäftsführer:<br>Benjamin Bönisch<br>Sharang Deepak Parnerkar",
"$REGISTER", legalRegister, "$DIRECTORS", legalDirectors,
)
// logoSVG is the chevron from the portal favicon, inline so wkhtmltopdf needs
// no network access.
const logoSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="8.75 2.25 46.5 45" width="30" height="29" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M12 44 L32 20 L52 44" stroke="$ACCENT" stroke-width="6.5"/><path d="M24 13 L32 5 L40 13" stroke="$ACCENT2" stroke-width="5.5"/></svg>`
// 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}
<table style="width:100%;border-collapse:collapse;font-family:Arial,Helvetica,sans-serif;">
<tr>
<td style="vertical-align:middle;padding:0 0 6px 0;">
<table style="border-collapse:collapse;"><tr>
<td style="vertical-align:middle;padding-right:8px;">`+logoSVG+`</td>
<td style="vertical-align:middle;font-size:20px;font-weight:bold;letter-spacing:-0.4px;color:$INK;">Break<span style="color:$ACCENT;">Pilot</span></td>
</tr></table>
</td>
<td style="vertical-align:top;text-align:right;font-size:8.5pt;line-height:1.45;color:$MUTED;">
<b style="color:$INK;">{{ doc.company }}</b><br>
{{ bp_addr.address_line1 }}<br>{{ bp_addr.pincode }} {{ bp_addr.city }}<br>
{{ bp_addr.email_id or "kontakt@breakpilot.com" }} · www.breakpilot.com
</td>
</tr>
</table>
<div style="border-bottom:1.5px solid $ACCENT;margin:2px 0 0 0;"></div>`, "${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 "" -%}
<table style="width:100%;border-collapse:collapse;border-top:0.5px solid $LINE;font-family:Arial,Helvetica,sans-serif;color:$FAINT;">
<tr>
<td style="vertical-align:top;padding:5px 8px 0 0;width:22%;font-size:6.5pt;line-height:1.45;"><b style="color:$MUTED;">{{ doc.company }}</b><br>{{ bp_addr.address_line1 }}<br>{{ bp_addr.pincode }} {{ bp_addr.city }}</td>
<td style="vertical-align:top;padding:5px 8px 0 0;width:26%;font-size:6.5pt;line-height:1.45;">$REGISTER_BR<br>USt-IdNr. {{ frappe.db.get_value("Company", doc.company, "tax_id") or "" }}</td>
<td style="vertical-align:top;padding:5px 8px 0 0;width:26%;font-size:6.5pt;line-height:1.45;">$DIRECTORS_BR</td>
<td style="vertical-align:top;padding:5px 0 0 0;width:26%;font-size:6.5pt;line-height:1.45;">{% if bp_bank.iban %}{{ bp_bank.bank }}<br>IBAN {{ bp_bank.iban }}{% if bp_bic %}<br>BIC {{ bp_bic }}{% endif %}{% endif %}</td>
</tr>
</table>`, "${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) -%}
<style>
.bp { font-family: Arial, Helvetica, sans-serif; font-size: 9.5pt; color: $INK; line-height: 1.45; }
.bp table { border-collapse: collapse; font-size: 9.5pt; }
.bp td, .bp th { font-size: 9.5pt; }
.bp .sender { font-size: 7pt; color: $FAINT; border-bottom: 0.5px solid $LINE; padding-bottom: 2px; margin-bottom: 6px; }
.bp .meta td { padding: 1px 0; font-size: 8.5pt; vertical-align: top; }
.bp .meta td.k { color: $MUTED; padding-right: 12px; }
.bp h1 { font-size: 16pt; margin: 26px 0 4px 0; color: $INK; font-weight: bold; }
.bp .items { width: 100%; margin-top: 14px; }
.bp .items th { font-size: 8pt; color: $MUTED; font-weight: normal; text-align: left; border-bottom: 1px solid $INK; padding: 4px 6px 4px 0; }
.bp .items td { vertical-align: top; border-bottom: 0.5px solid $LINE; padding: 6px 6px 6px 0; }
.bp .r { text-align: right; }
.bp .desc { font-size: 7.5pt; color: $MUTED; }
.bp .nw { white-space: nowrap; }
.bp .totals { margin-left: auto; margin-top: 10px; min-width: 45%; }
.bp .totals td { padding: 2px 0 2px 16px; }
.bp .totals tr.grand td { border-top: 1px solid $INK; font-weight: bold; font-size: 10.5pt; padding-top: 5px; }
.bp .note { margin-top: 18px; font-size: 8.5pt; }
.bp .muted { color: $MUTED; }
</style>
<div class="bp">
<table style="width:100%;margin-top:18px;"><tr>
<td style="vertical-align:top;width:58%;">
<div class="sender">{{ doc.company }} · {{ bp_addr.address_line1 }} · {{ bp_addr.pincode }} {{ bp_addr.city }}</div>
<b>{{ doc.customer_name }}</b><br>
{{ doc.address_display or "" }}
</td>
<td style="vertical-align:top;">
<table class="meta" style="margin-left:auto;">
<tr><td class="k">Nummer</td><td class="nw"><b>{{ doc.name }}</b></td></tr>
<tr><td class="k">Datum</td><td>{{ frappe.utils.formatdate(doc_date) }}</td></tr>
<tr><td class="k">Kundennummer</td><td>{{ cust }}</td></tr>
{%- if doc.get("tax_id") %}<tr><td class="k">Ihre USt-IdNr.</td><td>{{ doc.tax_id }}</td></tr>{% endif %}
{%- if is_inv and not doc.is_return %}<tr><td class="k">Fällig am</td><td>{{ frappe.utils.formatdate(doc.due_date) }}</td></tr>{% endif %}
{%- if doc.doctype == "Quotation" and doc.valid_till %}<tr><td class="k">Gültig bis</td><td>{{ frappe.utils.formatdate(doc.valid_till) }}</td></tr>{% endif %}
{%- if doc.get("po_no") %}<tr><td class="k">Ihre Bestellung</td><td>{{ doc.po_no }}</td></tr>{% endif %}
</table>
</td>
</tr></table>
<h1>{{ title }}</h1>
{%- if is_inv and doc.is_return and doc.return_against %}<div class="muted">zu Rechnung {{ doc.return_against }}</div>{% endif %}
{%- if is_inv %}
<div class="muted">Leistungszeitraum: {% if period_from and period_to %}{{ frappe.utils.formatdate(period_from) }} – {{ frappe.utils.formatdate(period_to) }}{% else %}Das Leistungsdatum entspricht dem Rechnungsdatum.{% endif %}</div>
{%- endif %}
<table class="items">
<thead><tr>
<th style="width:5%;">Pos.</th><th>Leistung</th><th class="r" style="width:12%;">Menge</th><th class="r" style="width:15%;">Einzelpreis</th><th class="r" style="width:15%;">Betrag</th>
</tr></thead>
<tbody>
{%- for it in doc.items %}
<tr>
<td>{{ loop.index }}</td>
<td><b>{{ it.item_name }}</b><br><span class="desc">{{ 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") %}<br>Zeitraum {{ frappe.utils.formatdate(it.service_start_date) }} – {{ frappe.utils.formatdate(it.service_end_date) }}{% endif %}</span></td>
<td class="r nw">{{ ("%g"|format(it.qty)) | replace(".", ",") }} {{ it.uom }}</td>
<td class="r nw">{{ it.get_formatted("rate", doc) }}</td>
<td class="r nw">{{ it.get_formatted("amount", doc) }}</td>
</tr>
{%- endfor %}
</tbody>
</table>
<table class="totals">
<tr><td>Summe netto</td><td class="r">{{ doc.get_formatted("net_total") }}</td></tr>
{%- if doc.discount_amount %}<tr><td>Rabatt</td><td class="r">− {{ doc.get_formatted("discount_amount") }}</td></tr>{% endif %}
{%- for t in doc.taxes %}{% if t.tax_amount %}
<tr><td>{{ t.description }}{% if t.rate and "%" not in t.description %} ({{ ("%g"|format(t.rate)) | replace(".", ",") }} %){% endif %}</td><td class="r">{{ t.get_formatted("tax_amount", doc) }}</td></tr>
{%- endif %}{% endfor %}
<tr class="grand"><td>Gesamtbetrag</td><td class="r">{{ doc.get_formatted("rounded_total" if doc.rounded_total else "grand_total") }}</td></tr>
</table>
<div class="note">
{%- if "an Unternehmen in der EU" in tpl %}
<p><b>Steuerschuldnerschaft des Leistungsempfängers</b> (Reverse Charge, § 13b UStG / Art. 196 MwStSystRL).</p>
{%- elif "Drittland" in tpl %}
<p>Nicht im Inland steuerbare Leistung.</p>
{%- endif %}
{%- if is_inv and not doc.is_return %}
{%- if sepa %}
{%- set creditor = frappe.db.get_value("Company", doc.company, "sepa_creditor_id") %}
<p>Wir ziehen den Rechnungsbetrag von&nbsp;<b>{{ doc.get_formatted("rounded_total" if doc.rounded_total else "grand_total") }}</b> am <b>{{ frappe.utils.formatdate(doc.due_date) }}</b> 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.</p>
{%- else %}
<p>Bitte überweisen Sie den Rechnungsbetrag bis zum <b>{{ frappe.utils.formatdate(doc.due_date) }}</b> unter Angabe der Rechnungsnummer <b>{{ doc.name }}</b>.</p>
{%- endif %}
{%- elif not is_inv and sepa %}
<p>Zahlung per SEPA-Lastschrift nach Rechnungsstellung.</p>
{%- endif %}
{%- if doc.get("terms") %}<div class="muted">{{ doc.terms }}</div>{% endif %}
<p class="muted">Vielen Dank für Ihr Vertrauen.</p>
</div>
</div>`)
// 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(`<div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.6;color:$INK;">
<p>Guten Tag,</p>
<p>anbei erhalten Sie unsere Rechnung <b>{{ name }}</b> vom {{ frappe.utils.formatdate(posting_date) }} über <b>{{ frappe.utils.fmt_money(grand_total, currency=currency) }}</b>.</p>
{% if payment_schedule and payment_schedule[0].mode_of_payment == "SEPA-Lastschrift" -%}
<p>Den Betrag ziehen wir am {{ frappe.utils.formatdate(due_date) }} per SEPA-Lastschrift ein. Die Einzelheiten stehen auf der Rechnung.</p>
{%- else -%}
<p>Bitte überweisen Sie den Betrag bis zum {{ frappe.utils.formatdate(due_date) }}.</p>
{%- endif %}
<p>Bei Fragen zur Rechnung antworten Sie einfach auf diese E-Mail.</p>
<table style="font-size:13px;line-height:1.5;color:$INK;border-collapse:collapse;margin-top:18px;"><tr><td>
<div style="font-size:12px;color:#71769B;">Mit freundlichen Grüßen</div>
<div style="font-size:16px;font-weight:bold;margin:1px 0 10px;">Ihr BreakPilot-Team</div>
<div style="font-weight:bold;">{{ company }}</div>
<div style="color:#43466A;">In Steinäckern 16, 78351 Bodman-Ludwigshafen</div>
<div style="color:#43466A;"><a href="mailto:kontakt@breakpilot.com" style="color:$ACCENT;text-decoration:none;">kontakt@breakpilot.com</a> · <a href="https://www.breakpilot.com" style="color:$ACCENT;text-decoration:none;">www.breakpilot.com</a></div>
<div style="border-top:1px solid #E1E1EA;margin:12px 0 9px;width:300px;max-width:100%;font-size:0;line-height:0;">&nbsp;</div>
<div style="font-size:11px;color:$FAINT;">USt-IdNr. DE464808363 · $REGISTER</div>
<div style="font-size:11px;color:$FAINT;">$DIRECTORS</div>
</td></tr></table>
</div>`)
+35 -23
View File
@@ -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,
}
}
+119 -2
View File
@@ -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)
+93 -5
View File
@@ -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")
}
}
}