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: <dict>, 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
This commit is contained in:
1 parent
8a03be188d
commit
0ba5f38122
5 files changed
+135
-5
No files matched your search
@@ -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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user