Files
tenant-registry/internal/erpsetup/erpsetup.go
T
Sharang ParnerkarandClaude Opus 5.5 c0a7db4e56
ci / shared (pull_request) Successful in 13s
ci / test (pull_request) Successful in 25m56s
ci / image (pull_request) Skipped
fix(erpsetup): restore the letter head source, ignore <tbody> from UI saves
The live letter head had source "Image" (saved in the UI on 2026-10-06), so
documents printed an image header instead of the HTML one. erpsetup compared
only content and footer and would never have put it back; it now also
compares source and footer_source.

The same UI save wrapped the table rows in <tbody>, which made content and
footer look changed on every run. Field comparison now ignores <tbody>.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-13 11:07:50 +02:00

448 lines
16 KiB
Go

// 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, list prices), the document layout
// (letter head, print formats, invoice e-mail) and the Frappe Webhooks that
// drive the tenant ladder, plus the cost centers per product and deferred
// revenue for yearly items (accounting.go). 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.
package erpsetup
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Config for one run.
type Config struct {
BaseURL string // https://erp.breakpilot.com
APIKey string
APISecret string
WebhookURL string // https://registry.breakpilot.com/v1/internal/erp/webhook
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)
}
// Step is one reported action.
type Step struct {
What string // e.g. "custom field Customer.tenant_id"
Result string // "exists", "created", "would create", "missing (not created)"
}
type runner struct {
cfg Config
steps []Step
}
// Run applies (or, with DryRun, reports) the configuration.
func Run(ctx context.Context, cfg Config) ([]Step, error) {
if cfg.BaseURL == "" || cfg.APIKey == "" || cfg.APISecret == "" {
return nil, errors.New("erpsetup: base URL, API key and API secret are required")
}
if cfg.WebhookURL == "" || cfg.WebhookSecret == "" {
return nil, errors.New("erpsetup: webhook URL and webhook secret are required")
}
if cfg.LeadDoctype == "" {
cfg.LeadDoctype = "Lead"
}
if cfg.HTTP == nil {
cfg.HTTP = &http.Client{Timeout: 30 * time.Second}
}
if cfg.Log == nil {
cfg.Log = func(string, ...any) {}
}
cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/")
r := &runner{cfg: cfg}
for _, f := range customFields(cfg.LeadDoctype) {
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.ensure(ctx, "DocType", "Usage Record", "doctype Usage Record", usageRecordDoctype()); err != nil {
return r.steps, err
}
// Sales catalogue: units, item group, the SKU items, SEPA mandate fields
// on the Customer and the payment method.
for _, u := range uoms() {
if err := r.ensure(ctx, "UOM", u["name"].(string), "unit "+u["name"].(string), u); err != nil {
return r.steps, err
}
}
if err := r.ensure(ctx, "Item Group", itemGroup, "item group "+itemGroup, itemGroupDoc()); err != nil {
return r.steps, err
}
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 {
return r.steps, err
}
}
for _, f := range sepaFields() {
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.ensure(ctx, "Mode of Payment", "SEPA-Lastschrift", "mode of payment SEPA-Lastschrift", modeOfPaymentDoc()); err != nil {
return r.steps, err
}
for _, ps := range invoiceSeriesSetters() {
if err := r.ensureValue(ctx, "Property Setter", ps["name"].(string), "invoice number range ("+ps["property"].(string)+") "+invoiceSeries, ps); err != nil {
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
}
}
// Customer numbers, payment terms and the contract basis (portal#66/#67).
settings, custSetters := customerNumbering()
if err := r.ensureFields(ctx, "Selling Settings", "Selling Settings", "customer naming by series "+customerSeries, settings, "cust_master_name"); err != nil {
return r.steps, err
}
for _, ps := range custSetters {
if err := r.ensureValue(ctx, "Property Setter", ps["name"].(string), "customer number range ("+ps["property"].(string)+") "+customerSeries, ps); err != nil {
return r.steps, err
}
}
if err := r.ensure(ctx, "Payment Term", paymentTerms21, "payment term "+paymentTerms21, paymentTermDoc()); err != nil {
return r.steps, err
}
if err := r.ensure(ctx, "Payment Terms Template", paymentTerms21, "payment terms template "+paymentTerms21, paymentTemplateDoc()); err != nil {
return r.steps, err
}
if err := r.ensureFields(ctx, "Company", companyName, "company default payment terms "+paymentTerms21,
map[string]any{"doctype": "Company", "name": companyName, "payment_terms": paymentTerms21}, "payment_terms"); err != nil {
return r.steps, err
}
for _, f := range contractBasisFields() {
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
}
}
// Cost centers per product and deferred revenue for yearly items.
if err := r.accounting(ctx); 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.ensureListed(ctx, "File", "logo "+logoFileURL,
[][]any{{"file_url", "=", logoFileURL}}, logoFileDoc()); err != nil {
return r.steps, err
}
if err := r.ensureFields(ctx, "Letter Head", letterHeadName, "letter head "+letterHeadName, letterHeadDoc(), "source", "footer_source", "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
}
}
return r.steps, nil
}
func (r *runner) record(what, result string) {
r.steps = append(r.steps, Step{What: what, Result: result})
r.cfg.Log("%-55s %s", what, result)
}
// ensure creates doc when GET /api/resource/<doctype>/<name> is 404.
func (r *runner) ensure(ctx context.Context, doctype, name, what string, doc map[string]any) error {
status, _, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(doctype)+"/"+url.PathEscape(name), nil)
if err != nil {
return err
}
switch {
case status == http.StatusOK:
r.record(what, "exists")
return nil
case status != http.StatusNotFound:
return fmt.Errorf("erpsetup: GET %s %q: HTTP %d", doctype, name, status)
case 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
}
// ensureValue is ensure for a doc whose "value" matters: an existing one with
// another value is set to the wanted value (dry run: "would update").
func (r *runner) ensureValue(ctx context.Context, doctype, name, what string, doc map[string]any) 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 struct {
Value string `json:"value"`
} `json:"data"`
}
_ = json.Unmarshal(body, &cur)
if cur.Data.Value == doc["value"] {
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, map[string]any{"value": doc["value"]})
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
}
// 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 !sameValue(cur.Data[k], 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)
filters, _ := json.Marshal([][]string{
{"webhook_doctype", "=", w.Doctype},
{"webhook_docevent", "=", w.DocEvent},
{"request_url", "=", w.URL},
})
q := url.Values{"filters": {string(filters)}, "fields": {`["name","webhook_json","condition"]`}, "limit_page_length": {"50"}}
status, body, err := r.call(ctx, http.MethodGet, "/api/resource/Webhook?"+q.Encode(), nil)
if err != nil {
return err
}
if status != http.StatusOK {
return fmt.Errorf("erpsetup: list webhooks: HTTP %d %s", status, truncate(body))
}
var list struct {
Data []struct {
Name string `json:"name"`
WebhookJSON string `json:"webhook_json"`
Condition string `json:"condition"`
} `json:"data"`
}
if err := json.Unmarshal(body, &list); err != nil {
return fmt.Errorf("erpsetup: decode webhooks: %w", err)
}
for _, d := range list.Data {
if !strings.Contains(d.WebhookJSON, `"event":"`+w.Event+`"`) {
continue
}
// An older template is brought up to date in place (same name,
// secret and URL); only the body and the condition change.
if d.WebhookJSON == w.JSON && d.Condition == w.Condition {
r.record(what, "exists ("+d.Name+")")
return nil
}
if r.cfg.DryRun {
r.record(what, "would update ("+d.Name+")")
return nil
}
status, body, err := r.call(ctx, http.MethodPut, "/api/resource/Webhook/"+url.PathEscape(d.Name),
map[string]any{"webhook_json": w.JSON, "condition": w.Condition})
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 ("+d.Name+")")
return nil
}
if r.cfg.DryRun {
r.record(what, "would create")
return nil
}
status, body, err = r.call(ctx, http.MethodPost, "/api/resource/Webhook", w.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
}
func (r *runner) call(ctx context.Context, method, path string, body any) (int, []byte, error) {
var rd io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return 0, nil, err
}
rd = bytes.NewReader(buf)
}
req, err := http.NewRequestWithContext(ctx, method, r.cfg.BaseURL+path, rd)
if err != nil {
return 0, nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "token "+r.cfg.APIKey+":"+r.cfg.APISecret)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := r.cfg.HTTP.Do(req)
if err != nil {
return 0, nil, fmt.Errorf("erpsetup: %s %s: %w", method, path, err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
return resp.StatusCode, raw, fmt.Errorf("erpsetup: %s %s: HTTP %d — check the API key and the user's roles", method, path, resp.StatusCode)
}
return resp.StatusCode, raw, nil
}
// sameValue compares a stored field with the wanted one. Frappe's HTML
// editor wraps table rows in <tbody> when a document is saved in the UI;
// that is not a change of ours and must not show up as one on every run.
func sameValue(got, want any) bool {
norm := strings.NewReplacer("<tbody>", "", "</tbody>", "")
return norm.Replace(fmt.Sprint(got)) == norm.Replace(fmt.Sprint(want))
}
func truncate(b []byte) string {
s := strings.TrimSpace(string(b))
if len(s) > 300 {
return s[:300] + "…"
}
return s
}