Merge pull request 'fix: erpsetup dunning read rule, migration seed test, usage events 500' (#137) from fix/erpsetup-dunning-and-small into main
ci / shared (push) Successful in 12s
ci / test (push) Successful in 7m22s
ci / image (push) Successful in 38s

This commit was merged in pull request #137.
This commit is contained in:
sharang committed 2026-11-17 12:10:38 +00:00
commit 9d6b5d48cf
7 files changed
+200 -13

No files matched your search

+6
View File
@@ -205,6 +205,12 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) {
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
+67
View File
@@ -67,6 +67,20 @@ func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.URL.Path == "/api/method/frappe.core.page.permission_manager.permission_manager.add" && r.Method == http.MethodPost {
// Frappe copies the standard rules first, then adds the role with read only.
var in map[string]any
_ = json.NewDecoder(r.Body).Decode(&in)
if f.docs["Custom DocPerm"] == nil {
f.docs["Custom DocPerm"] = map[string]map[string]any{}
}
name := fmt.Sprintf("perm-%d", len(f.docs["Custom DocPerm"])+1)
f.docs["Custom DocPerm"][name] = map[string]any{"name": name, "parent": in["parent"], "role": in["role"], "permlevel": in["permlevel"],
"read": 1, "write": 0, "create": 0, "submit": 0, "cancel": 0, "delete": 0, "amend": 0}
f.posts++
_, _ = io.WriteString(w, `{"message":"`+name+`"}`)
return
}
rest := strings.TrimPrefix(r.URL.Path, "/api/resource/")
parts := strings.SplitN(rest, "/", 2)
doctype, _ := url.PathUnescape(parts[0])
@@ -809,3 +823,56 @@ func TestCustomerTextSpellsBreakpilot(t *testing.T) {
}
}
}
// The registry's API user may read Dunning (Mahnungen) and nothing more: a
// missing rule is created through the permission manager, a broader one is
// cut back to read only, a correct one is left alone.
func TestRegistryReadPermission(t *testing.T) {
f := newFake()
srv := httptest.NewServer(f)
defer srv.Close()
find := func() map[string]any {
for _, d := range f.docs["Custom DocPerm"] {
if d["parent"] == "Dunning" && d["role"] == registryRole {
return d
}
}
return nil
}
result := func(steps []Step) string {
for _, s := range steps {
if strings.HasPrefix(s.What, "permission Dunning") {
return s.Result
}
}
return "(no step)"
}
dry := cfg(srv.URL)
dry.DryRun = true
steps, err := Run(t.Context(), dry)
if err != nil || result(steps) != "would create" || find() != nil {
t.Fatalf("dry run: %v %q", err, result(steps))
}
steps, err = Run(t.Context(), cfg(srv.URL))
if err != nil || result(steps) != "created" {
t.Fatalf("first run: %v %q", err, result(steps))
}
if d := find(); d == nil || fmt.Sprint(d["read"]) != "1" || fmt.Sprint(d["write"]) != "0" {
t.Fatalf("rule: %v", d)
}
steps, _ = Run(t.Context(), cfg(srv.URL))
if !strings.HasPrefix(result(steps), "exists") {
t.Fatalf("second run: %q", result(steps))
}
// someone ticked more in the UI: the next run cuts it back to read only
d := find()
d["write"], d["create"] = 1, 1
steps, _ = Run(t.Context(), cfg(srv.URL))
if r := result(steps); !strings.HasPrefix(r, "updated") || !strings.Contains(r, "write 1 → 0") || !strings.Contains(r, "create 1 → 0") {
t.Fatalf("broader rule: %q", r)
}
if fmt.Sprint(find()["write"]) != "0" || fmt.Sprint(find()["read"]) != "1" {
t.Fatalf("after cut back: %v", find())
}
}
+79
View File
@@ -0,0 +1,79 @@
package erpsetup
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// registryRole is the role of the registry's API user (platform-registry@):
// it appends usage records and reads invoices. It is not Accounts User, which
// could also create and submit bookings and payments.
const registryRole = "Sales User"
// registryReads are the doctypes the registry must read beyond what its role
// gets by default. Dunning: the late-payment ladder counts from the Mahnung
// (AGB § 10, tenant-registry #134); ERPNext gives read only to the Accounts
// roles. The child table (Overdue Payment) follows its parent.
func registryReads() []string { return []string{"Dunning"} }
// grantFlags are the rights a read-only rule must not carry.
var grantFlags = []string{"write", "create", "submit", "cancel", "delete", "amend"}
// ensureReadPerm makes sure `role` may read `doctype` and nothing more, at
// permission level 0. A missing rule is added through Frappe's permission
// manager, which first copies the doctype's standard rules into Custom DocPerm
// (as the Role Permissions Manager UI does), so the other roles keep theirs.
// An existing rule is corrected to read-only.
func (r *runner) ensureReadPerm(ctx context.Context, doctype, role string) error {
what := fmt.Sprintf("permission %s: %s may read (level 0, read only)", doctype, role)
filters, _ := json.Marshal([][]any{{"parent", "=", doctype}, {"role", "=", role}, {"permlevel", "=", 0}})
fields, _ := json.Marshal(append([]string{"name", "read"}, grantFlags...))
q := url.Values{"filters": {string(filters)}, "fields": {string(fields)}, "limit_page_length": {"1"}}
status, body, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape("Custom DocPerm")+"?"+q.Encode(), nil)
if err != nil {
return err
}
if status != http.StatusOK {
return fmt.Errorf("erpsetup: list Custom DocPerm: HTTP %d %s", status, truncate(body))
}
var list struct {
Data []map[string]any `json:"data"`
}
if err := json.Unmarshal(body, &list); err != nil {
return fmt.Errorf("erpsetup: decode Custom DocPerm list: %w", err)
}
if len(list.Data) == 0 {
if r.cfg.DryRun {
r.record(what, "would create")
return nil
}
status, body, err = r.call(ctx, http.MethodPost, "/api/method/frappe.core.page.permission_manager.permission_manager.add",
map[string]any{"parent": doctype, "role": role, "permlevel": 0})
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
}
row := list.Data[0]
name := fmt.Sprint(row["name"])
patch := map[string]any{}
var changes []string
if fmt.Sprint(row["read"]) != "1" {
patch["read"] = 1
changes = append(changes, change("read", row["read"], 1))
}
for _, f := range grantFlags {
if v := fmt.Sprint(row[f]); v != "0" && v != "<nil>" {
patch[f] = 0
changes = append(changes, change(f, row[f], 0))
}
}
return r.applyPatch(ctx, "/api/resource/"+url.PathEscape("Custom DocPerm")+"/"+url.PathEscape(name), what, " ("+name+")", patch, changes)
}
+3 -2
View File
@@ -60,8 +60,9 @@ func usageRecordDoctype() map[string]any {
{"role": "System Manager", "read": 1, "write": 1, "create": 1, "delete": 1, "report": 1, "export": 1},
{"role": "Accounts Manager", "read": 1, "report": 1, "export": 1},
{"role": "Sales Manager", "read": 1, "report": 1, "export": 1},
// The registry's API user (platform-registry) holds Sales User and
// Accounts User, not System Manager: it only appends usage.
// The registry's API user (platform-registry) holds Sales User
// only, not System Manager: it appends usage. Its extra reads are
// in permissions.go.
{"role": "Sales User", "read": 1, "create": 1},
},
}
+13
View File
@@ -154,3 +154,16 @@ func TestUsageSummary_emptyAndBadInput(t *testing.T) {
}
})
}
// The event list answers a malformed tenant id like an unknown one: an empty
// list. Postgres reports the bad UUID only once the rows are read.
func TestUsageEvents_malformedTenantIsEmpty(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
for _, id := range []string{"not-a-uuid", "00000000-0000-0000-0000-0000000000ff"} {
resp, raw := h.do("GET", "/v1/usage/events?tenant_id="+id, nil)
if resp.StatusCode != 200 || !bytes.Contains(raw, []byte(`[]`)) {
t.Fatalf("events %s: %d %s", id, resp.StatusCode, raw)
}
}
})
}
+9 -1
View File
@@ -173,7 +173,15 @@ func (p *Postgres) ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageE
}
out = append(out, *u)
}
return out, rows.Err()
// pgx reports a malformed tenant id only once the rows are read, not
// from Query: a tenant id that is not a UUID matches no events.
if err := rows.Err(); err != nil {
if isInvalidUUID(err) {
return []UsageEvent{}, nil
}
return nil, err
}
return out, nil
}
func (p *Postgres) MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error {
+23 -10
View File
@@ -340,17 +340,22 @@ func TestSeed_canInsertAndQuery(t *testing.T) {
}
// 0028: the R1 intake, insert-only, one capture per report, one
// settling receipt per entry.
// settling receipt per entry. On a workspace of its own: since 0030 a
// workspace with intake reports cannot be deleted (checked below).
var itid string
if err := db.QueryRowContext(ctx, `INSERT INTO tenants (slug, name, plan, status, kind) VALUES ('intake-co', 'Intake Co', 'professional', 'active', 'customer') RETURNING id`).Scan(&itid); err != nil {
t.Fatalf("insert intake tenant: %v", err)
}
if _, err := db.ExecContext(ctx, `INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger)
VALUES ($1, 'SH-2026-00001', 1, now(), 'portal', 'u-1', 'product', 'no')`, tid); err != nil {
VALUES ($1, 'SH-2026-00001', 1, now(), 'portal', 'u-1', 'product', 'no')`, itid); err != nil {
t.Fatalf("insert intake report: %v", err)
}
insEntry := `INSERT INTO intake_entries (tenant_id, reference, kind, content, by_sub, at) VALUES ($1, 'SH-2026-00001', $2, '{"what":"x"}', 'u-1', now()) RETURNING id`
var entryID int64
if err := db.QueryRowContext(ctx, insEntry, tid, "capture").Scan(&entryID); err != nil {
if err := db.QueryRowContext(ctx, insEntry, itid, "capture").Scan(&entryID); err != nil {
t.Fatalf("insert intake capture: %v", err)
}
if _, err := db.ExecContext(ctx, insEntry, tid, "capture"); err == nil {
if _, err := db.ExecContext(ctx, insEntry, itid, "capture"); err == nil {
t.Error("a second capture of the same report was stored")
}
insReceipt := `INSERT INTO intake_receipts (entry_id, status, by_client, at) VALUES ($1, $2, 'werkmeister-svc', now())`
@@ -359,7 +364,7 @@ func TestSeed_canInsertAndQuery(t *testing.T) {
}
for name, stmt := range map[string]string{
"second settling receipt": `INSERT INTO intake_receipts (entry_id, status, by_client, at) VALUES (` + strconv.FormatInt(entryID, 10) + `, 'refused', 'w', now())`,
"bad reference": `INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger) VALUES ('` + tid + `', 'X-1', 2, now(), 'portal', 'u', 'product', 'no')`,
"bad reference": `INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger) VALUES ('` + itid + `', 'X-1', 2, now(), 'portal', 'u', 'product', 'no')`,
"changed report": `UPDATE intake_reports SET danger = 'yes'`,
"changed entry": `UPDATE intake_entries SET content = '{}'`,
"changed receipt": `UPDATE intake_receipts SET status = 'refused'`,
@@ -369,15 +374,23 @@ func TestSeed_canInsertAndQuery(t *testing.T) {
}
}
// 0030: security reports outlive their workspace, so the database
// refuses to delete a workspace that has intake reports.
if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, itid); err == nil {
t.Error("a workspace with intake reports was deleted")
}
var nReports, nEntries int
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM intake_reports WHERE tenant_id = $1`, itid).Scan(&nReports)
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM intake_entries WHERE tenant_id = $1`, itid).Scan(&nEntries)
if nReports != 1 || nEntries != 1 {
t.Errorf("intake after a refused delete: reports=%d entries=%d, want 1/1", nReports, nEntries)
}
// FK cascade — delete tenant, projects/products/keys/audit_log handling.
if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, tid); err != nil {
t.Fatalf("delete tenant: %v", err)
}
var nServices, nSettings, nContractDocs, nIntake int
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM intake_entries WHERE tenant_id = $1`, tid).Scan(&nIntake)
if nIntake != 0 {
t.Errorf("FK cascade incomplete: intake_entries=%d", nIntake)
}
var nServices, nSettings, nContractDocs int
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM managed_services WHERE tenant_id = $1`, tid).Scan(&nServices)
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_product_settings WHERE tenant_id = $1`, tid).Scan(&nSettings)
_ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_contract_documents WHERE tenant_id = $1`, tid).Scan(&nContractDocs)