fix(erp): webhook templates and usage datetimes for the live ERPNext #49

Merged
sharang merged 3 commits from fix/erp-live-templates into main 2026-09-30 08:43:18 +00:00
6 changed files with 257 additions and 16 deletions

No files matched your search

+23
View File
@@ -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")
}
+14
View File
@@ -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)
}
}
}
+18
View File
@@ -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")}
}
+66 -2
View File
@@ -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)
@@ -144,7 +188,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 +200,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")
+128 -12
View File
@@ -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()
@@ -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)
@@ -52,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)
@@ -61,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:
@@ -84,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" {
@@ -101,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") {
@@ -142,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"])
}
}
@@ -259,3 +286,92 @@ 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)
}
_, 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)
}
}
+8 -2
View File
@@ -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": <the document as a dict>, "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",