From 0ba5f381220e8746584366f28c213e9f4e605778 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:40:24 +0200 Subject: [PATCH 1/3] fix(erp): webhook templates and usage datetimes for the live ERPNext Found in the first sales-order test on the live ERPNext (the staging mock renders no Jinja and takes any date): - Frappe renders webhook bodies with only {doc: , utils}: doc.items is the dict's items() method, so the sales-order webhook failed before it was sent; the overdue template used frappe.utils, which is not there. Now doc["items"] and utils.date_diff; checked by rendering all four on the live ERPNext against the submitted order. - erpsetup updates an existing webhook whose body or condition differs (in place; dry run reports "would update"). - Usage Record occurred_at is sent as "YYYY-MM-DD HH:MM:SS" in Europe/Berlin; MariaDB refused RFC 3339, so usage records have not reached ERPNext since go-live (the outbox kept retrying). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/erp/erp.go | 23 ++++++++++ internal/erp/erp_test.go | 14 ++++++ internal/erpsetup/erpsetup.go | 24 ++++++++++- internal/erpsetup/erpsetup_test.go | 69 +++++++++++++++++++++++++++++- internal/erpsetup/spec.go | 10 ++++- 5 files changed, 135 insertions(+), 5 deletions(-) diff --git a/internal/erp/erp.go b/internal/erp/erp.go index 944bcd7..68a2e36 100644 --- a/internal/erp/erp.go +++ b/internal/erp/erp.go @@ -18,6 +18,8 @@ import ( "net/url" "strings" "time" + // The image is distroless: carry the zone database for Europe/Berlin. + _ "time/tzdata" ) // Doctypes. LeadDoctype is ERPNext v15's "Lead"; the Frappe CRM app names it @@ -188,6 +190,7 @@ func (c *Client) ListSubscriptions(ctx context.Context, customer string) ([]Subs // CreateUsageRecord pushes one usage record (idempotency is the registry's // job: it only sends each event once, via the outbox). func (c *Client) CreateUsageRecord(ctx context.Context, rec UsageRecord) (string, error) { + rec.OccurredAt = FrappeDatetime(rec.OccurredAt) var out struct { Data struct { Name string `json:"name"` @@ -264,3 +267,23 @@ func truncate(b []byte) string { } return s } + +// frappeZone is the ERPNext system time zone; Datetime fields are stored as +// naive local times in it. +var frappeZone = func() *time.Location { + if loc, err := time.LoadLocation("Europe/Berlin"); err == nil { + return loc + } + return time.UTC +}() + +// FrappeDatetime turns an RFC 3339 time into the "YYYY-MM-DD HH:MM:SS" form a +// Frappe Datetime field accepts (MariaDB refuses "2026-09-30T06:03:53Z"), +// in the ERP's time zone. Anything else is passed through unchanged. +func FrappeDatetime(s string) string { + t, err := time.Parse(time.RFC3339Nano, s) + if err != nil { + return s + } + return t.In(frappeZone).Format("2006-01-02 15:04:05") +} diff --git a/internal/erp/erp_test.go b/internal/erp/erp_test.go index c3a0a8f..ba7bc2b 100644 --- a/internal/erp/erp_test.go +++ b/internal/erp/erp_test.go @@ -67,3 +67,17 @@ func TestSignature(t *testing.T) { t.Fatal("bad hex must fail") } } + +func TestFrappeDatetime(t *testing.T) { + for in, want := range map[string]string{ + "2026-09-30T06:03:53Z": "2026-09-30 08:03:53", // CEST + "2026-12-01T12:00:00Z": "2026-12-01 13:00:00", // CET + "2026-09-30T06:03:53.123+02:00": "2026-09-30 06:03:53", + "2026-09-30 06:03:53": "2026-09-30 06:03:53", // already Frappe form + "": "", + } { + if got := FrappeDatetime(in); got != want { + t.Errorf("FrappeDatetime(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/erpsetup/erpsetup.go b/internal/erpsetup/erpsetup.go index 816f7e3..a7972d1 100644 --- a/internal/erpsetup/erpsetup.go +++ b/internal/erpsetup/erpsetup.go @@ -144,7 +144,7 @@ func (r *runner) ensureWebhook(ctx context.Context, w webhook) error { {"webhook_docevent", "=", w.DocEvent}, {"request_url", "=", w.URL}, }) - q := url.Values{"filters": {string(filters)}, "fields": {`["name","webhook_json"]`}, "limit_page_length": {"50"}} + 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 @@ -156,16 +156,36 @@ func (r *runner) ensureWebhook(ctx context.Context, w webhook) error { 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+`"`) { + 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") diff --git a/internal/erpsetup/erpsetup_test.go b/internal/erpsetup/erpsetup_test.go index 8bea5a3..3fb7171 100644 --- a/internal/erpsetup/erpsetup_test.go +++ b/internal/erpsetup/erpsetup_test.go @@ -40,9 +40,22 @@ func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) { 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"]}) + 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) @@ -259,3 +272,57 @@ func TestCatalogueMatchesStoreDefaults(t *testing.T) { } } } + +// 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) + } + + 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) + } + } +} diff --git a/internal/erpsetup/spec.go b/internal/erpsetup/spec.go index 199b62f..287c89d 100644 --- a/internal/erpsetup/spec.go +++ b/internal/erpsetup/spec.go @@ -100,16 +100,22 @@ func (w webhook) doc() map[string]any { // The body templates render erp.WebhookEvent. "modified" makes the receiver's // fallback event id unique per document version (live Frappe sends no // X-Frappe-Event-Id). +// +// Frappe renders them with {"doc": , "utils": +// frappe.utils} and nothing else: doc.items is the dict's items() method, not +// the order lines (hence doc["items"]), and there is no "frappe" (hence +// utils.date_diff). Both broke on the live ERPNext; the staging mock never +// renders Jinja. func webhooks(url, secret string) []webhook { ws := []webhook{ { Doctype: "Sales Order", DocEvent: "on_submit", Event: "sales_order.submit", - JSON: `{"event":"sales_order.submit","doctype":"Sales Order","name":"{{ doc.name }}","modified":"{{ doc.modified }}","customer":"{{ doc.customer }}","items":[{% for i in doc.items %}{"item_code":"{{ i.item_code }}","qty":{{ i.qty }}}{% if not loop.last %},{% endif %}{% endfor %}]}`, + JSON: `{"event":"sales_order.submit","doctype":"Sales Order","name":"{{ doc.name }}","modified":"{{ doc.modified }}","customer":"{{ doc.customer }}","items":[{% for i in doc["items"] %}{"item_code":"{{ i.item_code }}","qty":{{ i.qty }}}{% if not loop.last %},{% endif %}{% endfor %}]}`, }, { Doctype: "Sales Invoice", DocEvent: "on_update_after_submit", Event: "sales_invoice.overdue", Condition: `doc.status == "Overdue"`, - JSON: `{"event":"sales_invoice.overdue","doctype":"Sales Invoice","name":"{{ doc.name }}","modified":"{{ doc.modified }}","customer":"{{ doc.customer }}","invoice":"{{ doc.name }}","days_overdue":{{ frappe.utils.date_diff(frappe.utils.nowdate(), doc.due_date) }}}`, + JSON: `{"event":"sales_invoice.overdue","doctype":"Sales Invoice","name":"{{ doc.name }}","modified":"{{ doc.modified }}","customer":"{{ doc.customer }}","invoice":"{{ doc.name }}","days_overdue":{{ utils.date_diff(utils.nowdate(), doc.due_date) }}}`, }, { Doctype: "Payment Entry", DocEvent: "on_submit", Event: "payment_entry.submit", -- 2.54.1 From 12a43c0c4c74cf81722b5827a34656618568658c Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:53:18 +0200 Subject: [PATCH 2/3] feat(erpsetup): GoBD invoice number range RE-JJJJ-NNNN MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The GoBD Verfahrensdokumentation (§ 9) fixes the outgoing-invoice number range at RE-JJJJ-NNNN, one range per calendar year for invoices and returns. ERPNext shipped ACC-SINV-.YYYY.-. erpsetup now makes RE-.YYYY.-.#### the only and the default Sales Invoice series (Property Setters) and sets it back if it was changed; the dry run reports "would update". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/erpsetup/catalog.go | 18 ++++++++ internal/erpsetup/erpsetup.go | 44 ++++++++++++++++++ internal/erpsetup/erpsetup_test.go | 71 +++++++++++++++++++++++++----- 3 files changed, 122 insertions(+), 11 deletions(-) diff --git a/internal/erpsetup/catalog.go b/internal/erpsetup/catalog.go index bd060bc..0267777 100644 --- a/internal/erpsetup/catalog.go +++ b/internal/erpsetup/catalog.go @@ -79,3 +79,21 @@ func sepaFields() []map[string]any { func modeOfPaymentDoc() map[string]any { return map[string]any{"doctype": "Mode of Payment", "name": "SEPA-Lastschrift", "mode_of_payment": "SEPA-Lastschrift", "type": "Bank", "enabled": 1} } + +// invoiceSeries is the outgoing-invoice number range from the GoBD +// Verfahrensdokumentation (§ 9): RE-JJJJ-NNNN, a new range each calendar year +// (the year is part of the series key), one range for invoices and returns. +const invoiceSeries = "RE-.YYYY.-.####" + +// invoiceSeriesSetters make it the only and the default naming series of the +// Sales Invoice (ERPNext ships ACC-SINV-.YYYY.- and ACC-SINV-RET-.YYYY.-). +func invoiceSeriesSetters() []map[string]any { + setter := func(prop, typ string) map[string]any { + return map[string]any{ + "doctype": "Property Setter", "name": "Sales Invoice-naming_series-" + prop, + "doctype_or_field": "DocField", "doc_type": "Sales Invoice", "field_name": "naming_series", + "property": prop, "property_type": typ, "value": invoiceSeries, + } + } + return []map[string]any{setter("options", "Text"), setter("default", "Text")} +} diff --git a/internal/erpsetup/erpsetup.go b/internal/erpsetup/erpsetup.go index a7972d1..0238e59 100644 --- a/internal/erpsetup/erpsetup.go +++ b/internal/erpsetup/erpsetup.go @@ -96,6 +96,11 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) { 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 _, w := range webhooks(cfg.WebhookURL, cfg.WebhookSecret) { if err := r.ensureWebhook(ctx, w); err != nil { return r.steps, err @@ -136,6 +141,45 @@ func (r *runner) ensure(ctx context.Context, doctype, name, what string, doc map 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 +} + // 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 3fb7171..e0716f7 100644 --- a/internal/erpsetup/erpsetup_test.go +++ b/internal/erpsetup/erpsetup_test.go @@ -17,13 +17,13 @@ import ( // fakeFrappe keeps named docs per doctype and a list of webhooks. type fakeFrappe struct { mu sync.Mutex - docs map[string]map[string]bool + docs map[string]map[string]map[string]any webhooks []map[string]any posts int auth string } -func newFake() *fakeFrappe { return &fakeFrappe{docs: map[string]map[string]bool{}} } +func newFake() *fakeFrappe { return &fakeFrappe{docs: map[string]map[string]map[string]any{}} } func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.mu.Lock() @@ -65,8 +65,8 @@ func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(map[string]any{"data": doc}) case r.Method == http.MethodGet && len(parts) == 2: name, _ := url.PathUnescape(parts[1]) - if f.docs[doctype][name] { - _, _ = io.WriteString(w, `{"data":{}}`) + if d, ok := f.docs[doctype][name]; ok { + _ = json.NewEncoder(w).Encode(map[string]any{"data": d}) return } w.WriteHeader(http.StatusNotFound) @@ -74,9 +74,23 @@ func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) { var doc map[string]any _ = json.NewDecoder(r.Body).Decode(&doc) if f.docs[doctype] == nil { - f.docs[doctype] = map[string]bool{} + f.docs[doctype] = map[string]map[string]any{} + } + f.docs[doctype][doc["name"].(string)] = 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.docs[doctype][doc["name"].(string)] = true f.posts++ _, _ = io.WriteString(w, `{"data":{}}`) default: @@ -97,8 +111,8 @@ func TestRunCreatesThenIsIdempotent(t *testing.T) { if err != nil { t.Fatal(err) } - if len(steps) != 40 || f.posts != 40 { - t.Fatalf("first run: %d steps, %d creates; want 40/40: %+v", len(steps), f.posts, steps) + if len(steps) != 42 || f.posts != 42 { + t.Fatalf("first run: %d steps, %d creates; want 42/42: %+v", len(steps), f.posts, steps) } for _, s := range steps { if s.Result != "created" { @@ -114,8 +128,8 @@ func TestRunCreatesThenIsIdempotent(t *testing.T) { if err != nil { t.Fatal(err) } - if f.posts != 40 { - t.Fatalf("second run created %d more docs", f.posts-40) + if f.posts != 42 { + t.Fatalf("second run created %d more docs", f.posts-42) } for _, s := range steps { if !strings.HasPrefix(s.Result, "exists") { @@ -155,7 +169,7 @@ func TestLeadDoctypeIsConfigurable(t *testing.T) { if _, err := Run(context.Background(), c); err != nil { t.Fatal(err) } - if !f.docs["Custom Field"]["CRM Lead-tenant_id"] { + if _, ok := f.docs["Custom Field"]["CRM Lead-tenant_id"]; !ok { t.Fatalf("no CRM Lead field: %v", f.docs["Custom Field"]) } } @@ -326,3 +340,38 @@ func TestTemplatesUseOnlyDocAndUtils(t *testing.T) { } } } + +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) + } +} -- 2.54.1 From fc7407ba4285686ccdf7362b05f6622666a7be37 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 30 Sep 2026 10:18:52 +0200 Subject: [PATCH 3/3] test(erpsetup): drop unused result (ineffassign) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/erpsetup/erpsetup_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/erpsetup/erpsetup_test.go b/internal/erpsetup/erpsetup_test.go index e0716f7..5f0c6bd 100644 --- a/internal/erpsetup/erpsetup_test.go +++ b/internal/erpsetup/erpsetup_test.go @@ -319,7 +319,7 @@ func TestOutdatedWebhookIsUpdated(t *testing.T) { t.Fatalf("dry run did not report the update: %+v", steps) } - steps, err = Run(context.Background(), cfg(srv.URL)) + _, err = Run(context.Background(), cfg(srv.URL)) if err != nil { t.Fatal(err) } -- 2.54.1