Files
Sharang ParnerkarandClaude Opus 5.5 b02bf254bc feat(erpsetup): registry user may read dunning, read only
The late-payment ladder (#134) reads Dunnings, which ERPNext lets only the Accounts roles read. The registry's API user holds Sales User only. erpsetup now adds a level-0 read rule for Sales User on Dunning through Frappe's permission manager (which first copies the standard rules, as the Role Permissions Manager UI does) and cuts a broader rule back to read only. The spec.go comment no longer claims Accounts User. Live ERP: the same rule was added by hand on 17.11.; the next run reports it as existing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:55:28 +01:00

614 lines
21 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
// 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.
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; 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
}
}
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() {
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
}
}
// 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
}
}
// Incoming invoices: what cmd/invoiceintake writes into (intake.go).
if err := r.intake(ctx); err != nil {
return r.steps, err
}
// Outgoing e-invoices: codes, payment by transfer, the discount line,
// validation (einvoice.go). After intake: it uses the unit Stück.
if err := r.einvoice(ctx); err != nil {
return r.steps, err
}
// Travel expenses: Expense Claim Types with SKR04 accounts (reisekosten.go).
if err := r.reisekosten(ctx); err != nil {
return r.steps, err
}
// What the registry's API user must read beyond its role (permissions.go).
for _, dt := range registryReads() {
if err := r.ensureReadPerm(ctx, dt, registryRole); 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; 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"}}
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
}
// 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)
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
}