Files
tenant-registry/internal/erpsetup/erpsetup_test.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

520 lines
16 KiB
Go

package erpsetup
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// fakeFrappe keeps named docs per doctype and a list of webhooks.
type fakeFrappe struct {
mu sync.Mutex
docs map[string]map[string]map[string]any
webhooks []map[string]any
posts int
auth string
}
// newFake starts with what every ERPNext site has: the company (with its
// abbreviation) and the SKR04 deferred revenue account.
func newFake() *fakeFrappe {
return &fakeFrappe{docs: map[string]map[string]map[string]any{
"Company": {companyName: {"name": companyName, "company_name": companyName, "abbr": "BG"}},
"Account": {"3900 - Passive Rechnungsabgrenzung - BG": {"name": "3900 - Passive Rechnungsabgrenzung - BG", "account_number": "3900", "company": companyName}},
}}
}
func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
f.auth = r.Header.Get("Authorization")
if r.Header.Get("Authorization") != "token k:s" {
w.WriteHeader(http.StatusUnauthorized)
return
}
rest := strings.TrimPrefix(r.URL.Path, "/api/resource/")
parts := strings.SplitN(rest, "/", 2)
doctype, _ := url.PathUnescape(parts[0])
switch {
case doctype == "Webhook" && r.Method == http.MethodGet:
out := []map[string]any{}
for _, wh := range f.webhooks {
out = append(out, map[string]any{"name": wh["name"], "webhook_json": wh["webhook_json"], "condition": wh["condition"]})
}
_ = json.NewEncoder(w).Encode(map[string]any{"data": out})
case doctype == "Webhook" && r.Method == http.MethodPut:
name, _ := url.PathUnescape(parts[1])
var patch map[string]any
_ = json.NewDecoder(r.Body).Decode(&patch)
for _, wh := range f.webhooks {
if wh["name"] == name {
for k, v := range patch {
wh[k] = v
}
}
}
f.posts++
_, _ = io.WriteString(w, `{"data":{}}`)
case doctype == "Webhook" && r.Method == http.MethodPost:
var doc map[string]any
_ = json.NewDecoder(r.Body).Decode(&doc)
doc["name"] = "HOOK-" + string(rune('A'+len(f.webhooks)))
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 {
_ = json.NewEncoder(w).Encode(map[string]any{"data": d})
return
}
w.WriteHeader(http.StatusNotFound)
case r.Method == http.MethodPost:
var doc map[string]any
_ = json.NewDecoder(r.Body).Decode(&doc)
if f.docs[doctype] == nil {
f.docs[doctype] = map[string]map[string]any{}
}
if doctype == "File" { // Frappe derives the URL from the name and privacy
doc["file_url"] = "/private/files/" + doc["file_name"].(string)
}
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:
name, _ := url.PathUnescape(parts[1])
d, ok := f.docs[doctype][name]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
var patch map[string]any
_ = json.NewDecoder(r.Body).Decode(&patch)
for k, v := range patch {
d[k] = v
}
f.posts++
_, _ = io.WriteString(w, `{"data":{}}`)
default:
w.WriteHeader(http.StatusTeapot)
}
}
func cfg(url string) Config {
return Config{BaseURL: url + "/", APIKey: "k", APISecret: "s", WebhookURL: "https://registry/v1/internal/erp/webhook", WebhookSecret: "whs"}
}
func TestRunCreatesThenIsIdempotent(t *testing.T) {
f := newFake()
srv := httptest.NewServer(f)
defer srv.Close()
steps, err := Run(context.Background(), cfg(srv.URL))
if err != nil {
t.Fatal(err)
}
first := f.posts
if first != len(steps) {
t.Fatalf("first run: %d steps, %d writes: %+v", len(steps), first, steps)
}
for _, s := range steps {
// The company exists on every site, so its fields are updated, as are
// the items the catalogue step created a moment before.
if s.Result != "created" && s.Result != "updated" {
t.Errorf("%s: %s", s.What, s.Result)
}
}
hook := f.webhooks[0]
if hook["enable_security"] != float64(1) || hook["webhook_secret"] != "whs" || hook["request_url"] != "https://registry/v1/internal/erp/webhook" {
t.Errorf("webhook security/url not set: %v", hook)
}
steps, err = Run(context.Background(), cfg(srv.URL))
if err != nil {
t.Fatal(err)
}
if f.posts != first {
t.Fatalf("second run wrote %d more docs", f.posts-first)
}
for _, s := range steps {
if !strings.HasPrefix(s.Result, "exists") {
t.Errorf("second run %s: %s", s.What, s.Result)
}
}
}
func TestDryRunChangesNothing(t *testing.T) {
f := newFake()
srv := httptest.NewServer(f)
defer srv.Close()
c := cfg(srv.URL)
c.DryRun = true
var logged int
c.Log = func(string, ...any) { logged++ }
steps, err := Run(context.Background(), c)
if err != nil {
t.Fatal(err)
}
if f.posts != 0 || logged != len(steps) {
t.Fatalf("dry run posted %d docs, logged %d of %d", f.posts, logged, len(steps))
}
for _, s := range steps {
if !strings.HasPrefix(s.Result, "would ") {
t.Errorf("%s: %s", s.What, s.Result)
}
}
}
func TestLeadDoctypeIsConfigurable(t *testing.T) {
f := newFake()
srv := httptest.NewServer(f)
defer srv.Close()
c := cfg(srv.URL)
c.LeadDoctype = "CRM Lead"
if _, err := Run(context.Background(), c); err != nil {
t.Fatal(err)
}
if _, ok := f.docs["Custom Field"]["CRM Lead-tenant_id"]; !ok {
t.Fatalf("no CRM Lead field: %v", f.docs["Custom Field"])
}
}
func TestRequiredConfigAndAuthErrors(t *testing.T) {
if _, err := Run(context.Background(), Config{}); err == nil {
t.Fatal("empty config accepted")
}
if _, err := Run(context.Background(), Config{BaseURL: "x", APIKey: "k", APISecret: "s"}); err == nil {
t.Fatal("missing webhook config accepted")
}
srv := httptest.NewServer(newFake())
defer srv.Close()
c := cfg(srv.URL)
c.APISecret = "wrong"
if _, err := Run(context.Background(), c); err == nil || !strings.Contains(err.Error(), "API key") {
t.Fatalf("want an auth error, got %v", err)
}
}
func TestUnexpectedStatusStops(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = io.WriteString(w, strings.Repeat("x", 400))
}))
defer srv.Close()
if _, err := Run(context.Background(), cfg(srv.URL)); err == nil {
t.Fatal("500 accepted")
}
}
func TestWebhookBodiesAreValidJSONShapes(t *testing.T) {
for _, w := range webhooks("u", "s") {
if !strings.Contains(w.JSON, `"event":"`+w.Event+`"`) || !strings.Contains(w.JSON, `"modified":"{{ doc.modified }}"`) {
t.Errorf("%s: template lacks event or modified: %s", w.Event, w.JSON)
}
if w.URL != "u" || w.Secret != "s" {
t.Errorf("%s: url/secret not filled", w.Event)
}
}
}
func TestWebhookDocIsNamed(t *testing.T) {
seen := map[string]bool{}
for _, w := range webhooks("https://r.test/hook", "s") {
name, _ := w.doc()["name"].(string)
if name != "breakpilot-"+w.Event || seen[name] {
t.Fatalf("webhook %s: name %q", w.Event, name)
}
seen[name] = true
}
}
// Every SKU the registry's catalogue sells exists as an item, with a unit that
// exists too, and the platform fee, Managed Git and its build runners are there for invoicing.
func TestCatalogueCoversTheRegistrySKUs(t *testing.T) {
want := []string{
"CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN",
"CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT",
"DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT",
"DEV-FWK-CLD-STD", "DEV-FWK-CLD-BUS", "DEV-FWK-CLD-ENT", "DEV-FWK-OPR-STD", "DEV-FWK-OPR-BUS", "DEV-FWK-OPR-ENT",
"PLT-CORE-CLD-STD", "PLT-CORE-CLD-BUS", "PLT-CORE-CLD-ENT",
"INF-GIT-CLD-STD", "INF-GIT-CLD-BUS", "INF-GIT-CLD-ENT", "INF-GIT-OPR-STD", "INF-GIT-OPR-BUS", "INF-GIT-OPR-ENT",
"INF-CI-CLD-STD", "INF-CI-CLD-BUS", "INF-CI-CLD-ENT", "INF-CI-OPR-STD", "INF-CI-OPR-BUS", "INF-CI-OPR-ENT",
}
units := map[string]bool{}
for _, u := range uoms() {
units[u["name"].(string)] = true
}
have := map[string]sku{}
for _, s := range skus() {
if _, dup := have[s.Code]; dup {
t.Errorf("duplicate %s", s.Code)
}
have[s.Code] = s
if !units[s.UOM] || s.Name == "" || s.Description == "" {
t.Errorf("incomplete item %+v", s)
}
d := itemDoc(s)
if d["is_stock_item"] != 0 || d["is_sales_item"] != 1 || d["item_group"] != itemGroup {
t.Errorf("item doc %v", d)
}
}
for _, code := range want {
if _, ok := have[code]; !ok {
t.Errorf("missing %s", code)
}
}
if len(have) != len(want) {
t.Errorf("%d items, want %d", len(have), len(want))
}
if f := sepaFields(); len(f) != 4 || f[3]["options"] != "\nBasislastschrift (CORE)\nFirmenlastschrift (B2B)" {
t.Errorf("sepa fields %v", f)
}
}
// A SKU added to the registry's catalogue must be added here too, or a sales
// order for it would find no item in ERPNext.
func TestCatalogueMatchesStoreDefaults(t *testing.T) {
have := map[string]bool{}
for _, s := range skus() {
have[s.Code] = true
}
for _, p := range store.DefaultProducts() {
for _, code := range p.SKUs {
if !have[code] {
t.Errorf("%s: SKU %s has no ERPNext item", p.Key, code)
}
}
for _, a := range p.Addons {
for _, code := range a.SKUs {
if !have[code] {
t.Errorf("%s/%s: SKU %s has no ERPNext item", p.Key, a.ID, code)
}
}
}
}
}
// A webhook created from an older template is updated in place, not
// duplicated; the dry run only reports it.
func TestOutdatedWebhookIsUpdated(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)
}
old := `{"event":"sales_order.submit","items":[{% for i in doc.items %}{% endfor %}]}`
f.webhooks[0]["webhook_json"] = old
hooks, posts := len(f.webhooks), f.posts
c := cfg(srv.URL)
c.DryRun = true
steps, err := Run(context.Background(), c)
if err != nil {
t.Fatal(err)
}
if f.posts != posts || f.webhooks[0]["webhook_json"] != old {
t.Fatal("dry run changed something")
}
var reported bool
for _, s := range steps {
if strings.HasPrefix(s.Result, "would update") {
reported = true
}
}
if !reported {
t.Fatalf("dry run did not report the update: %+v", steps)
}
_, err = Run(context.Background(), cfg(srv.URL))
if err != nil {
t.Fatal(err)
}
if len(f.webhooks) != hooks || f.posts != posts+1 {
t.Fatalf("webhooks %d (want %d), writes %d (want %d)", len(f.webhooks), hooks, f.posts, posts+1)
}
body := f.webhooks[0]["webhook_json"].(string)
if !strings.Contains(body, `doc["items"]`) || strings.Contains(body, "doc.items") {
t.Fatalf("not updated: %s", body)
}
}
// Frappe renders the templates with only doc (a dict) and utils.
func TestTemplatesUseOnlyDocAndUtils(t *testing.T) {
for _, w := range webhooks("u", "s") {
if strings.Contains(w.JSON, "frappe.") || strings.Contains(w.JSON, "doc.items") {
t.Errorf("%s: template uses names Frappe does not provide: %s", w.Event, w.JSON)
}
}
}
func TestInvoiceSeriesIsTheGoBDRange(t *testing.T) {
for _, ps := range invoiceSeriesSetters() {
if ps["value"] != "RE-.YYYY.-.####" || ps["doc_type"] != "Sales Invoice" || ps["field_name"] != "naming_series" {
t.Errorf("setter %v", ps)
}
}
}
// A number range someone changed back is set to RE-… again.
func TestInvoiceSeriesIsRestored(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["Property Setter"]["Sales Invoice-naming_series-options"]["value"] = "ACC-SINV-.YYYY.-"
steps, err := Run(context.Background(), cfg(srv.URL))
if err != nil {
t.Fatal(err)
}
if f.docs["Property Setter"]["Sales Invoice-naming_series-options"]["value"] != "RE-.YYYY.-.####" {
t.Fatal("not restored")
}
var updated int
for _, s := range steps {
if s.Result == "updated" {
updated++
}
}
if updated != 1 {
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-Identifikationsnummer", "Leistungsbeginn", "Abrechnungsintervall", "Vertragsgrundlage", "Auftragsnummer", "nach Erteilung eines gültigen SEPA-Lastschriftmandats", "gemäß erteiltem SEPA-Lastschriftmandat", "cust != doc.customer_name", "doc.customer_address", `ca.country != "Germany"`, "{{ letter_head }}", `id="footer-html"`} {
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") || strings.Contains(s, "data:") || strings.Contains(s, "<svg") {
t.Errorf("unreplaced colour token or flexbox in a template")
}
}
}
// portal#66/#67: no product is described as a legal CRA check (RDG boundary).
func TestProductWordingIsNoLegalCheck(t *testing.T) {
for _, s := range skus() {
if strings.Contains(s.Description, "CRA-Prüfung") || strings.Contains(s.Name, "CRA-Prüfung") {
t.Errorf("%s: %q", s.Code, s.Description)
}
}
}
func TestLetterHeadSourceIsRestoredAndTbodyIgnored(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)
}
lh := f.docs["Letter Head"][letterHeadName]
// Saved once in the UI: the editor added <tbody>, nothing else changed.
lh["content"] = strings.ReplaceAll(letterHeadHTML, "<tr>", "<tbody><tr>")
lh["footer"] = strings.ReplaceAll(letterFooterHTML, "</table>", "</tbody></table>")
steps, err := Run(context.Background(), cfg(srv.URL))
if err != nil {
t.Fatal(err)
}
for _, s := range steps {
if s.What == "letter head "+letterHeadName && s.Result != "exists" {
t.Fatalf("tbody alone must not count as a change: %s", s.Result)
}
}
// The source was switched to Image: that is a change and is put back.
lh["source"] = "Image"
if _, err := Run(context.Background(), cfg(srv.URL)); err != nil {
t.Fatal(err)
}
if lh["source"] != "HTML" {
t.Fatalf("source not restored: %v", lh["source"])
}
}