From 8e2d8db4bf19b3696b623fdf5078c15f9dd2952d Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar Date: Tue, 13 Oct 2026 09:02:58 +0000 Subject: [PATCH] feat(erpsetup): cost centers per product, deferred revenue for yearly items (#67) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What erpsetup gets two accounting steps (new `internal/erpsetup/accounting.go`), run after the contract-basis fields: **A1: cost centers** - Creates Plattform, Prüfwerk, Firmwerk, Werkpilot, Infrastruktur and Verwaltung below the company's root cost center. - Makes **Verwaltung** the company default. `Main` is kept, not renamed. - Gives every SKU its product's **selling cost center** in its Item Defaults row for the company: - PLT → Plattform - CRA (Prüfwerk + Werkbank) → Prüfwerk - DEV-FWK → Firmwerk - DEV-WP → Werkpilot - INF (Managed Git + build runners) → Infrastruktur - Other Item Defaults rows and other fields of the company's row (e.g. an income account) are kept. **A2: deferred revenue** - The 12 yearly items (`Jahr`: Werkpilot, Firmwerk, Managed Git and build-runner On-Prem) get `enable_deferred_revenue` over **12 months**. - The company's default deferred revenue account becomes **SKR04 3900** (looked up by account number, never created). If it's missing, the deferral steps are skipped and reported as `missing (not created)`. - Accounts Settings release the deferral **monthly as Journal Entries that stay drafts** (`submit_journal_entries = 0`): a person checks and submits them. ## Why These follow the decisions with the tax advisor on 2026-10-12 (Collectives ERP/07): - Cost centers live in ERPNext only, with no KOST1 in DATEV. They give a P&L per product. - Yearly licences are deferred, so the monthly ERPNext P&L can be compared with her BWA. She books the RAP at year end in DATEV. ## How - The cost-center and account names carry the company abbreviation, which is read from the Company. - Item Defaults are PUT as the full table, because rows left out would be deleted. - Idempotent and dry-run capable like the other steps; nothing is submitted. ## Test plan - [x] Unit tests (fake Frappe): - cost centers and their parent - company defaults - Accounts Settings - cost center per SKU, deferral only on yearly items - existing Item Defaults rows and fields are kept - a missing 3900 skips the deferral - a missing company stops the run - [x] Second run is a no-op; the dry run writes nothing. - [ ] `erpsetup -dry-run` against live ERPNext (user): check that `deferred revenue account 3900` resolves, and expect 6 cost centers, 2 company fields, the Accounts Settings and 34 items as `would create`/`would update`. - [ ] Apply, then spot-check one Werkpilot On-Prem item and one Prüfwerk item in ERPNext. ## Risk **Blast radius:** live ERPNext master data: cost centers, company defaults, Accounts Settings, Item Defaults and deferral flags on the 34 SKU items. No transactions are touched. **What could break:** - New Sales Invoices for yearly items now need a service start and end date (ERPNext fills them from the posting date and the 12 months). Monthly items are unchanged. - A Journal Entry draft appears each month for open deferrals. **Rollback plan:** in ERPNext: - set the company default cost center back to Main - untick deferred revenue on the 12 yearly items Cost centers can stay. Nothing is submitted by this change. ## Checklist - [x] Docs updated (package doc; Collectives ERP/06 gets the cost-center note after the apply) - [x] Audit events emitted for state changes (n/a: ERP master data) - [x] Secrets via Infisical, never in repo (no secrets) - [x] Migration is forward-only + idempotent (no migration; erpsetup is idempotent) - [x] Tenant scoping enforced on every DB query (no DB access) 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Reviewed-on: https://git.breakpilot.com/platform/tenant-registry/pulls/67 --- internal/erpsetup/accounting.go | 233 +++++++++++++++++++++++++++ internal/erpsetup/accounting_test.go | 131 +++++++++++++++ internal/erpsetup/erpsetup.go | 10 +- internal/erpsetup/erpsetup_test.go | 24 ++- 4 files changed, 389 insertions(+), 9 deletions(-) create mode 100644 internal/erpsetup/accounting.go create mode 100644 internal/erpsetup/accounting_test.go diff --git a/internal/erpsetup/accounting.go b/internal/erpsetup/accounting.go new file mode 100644 index 0000000..5056ecc --- /dev/null +++ b/internal/erpsetup/accounting.go @@ -0,0 +1,233 @@ +package erpsetup + +// Accounting set-up decided with the tax advisor on 2026-10-12 (Collectives +// ERP/07): cost centers per product, kept in ERPNext only (no KOST1 in the +// DATEV export), and deferred revenue for the yearly licences, so the monthly +// P&L shows a twelfth of a Jahreslizenz per month. ERPNext books the release +// each month as draft Journal Entries, which a person checks and submits. + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" +) + +// Cost centers below the company's root cost center. Verwaltung is the +// company default (administration, everything not tied to a product); the +// ERPNext default "Main" stays and is no longer used for new documents. +const ( + ccPlattform = "Plattform" + ccPruefwerk = "Prüfwerk" + ccFirmwerk = "Firmwerk" + ccWerkpilot = "Werkpilot" + ccInfrastruktur = "Infrastruktur" + ccVerwaltung = "Verwaltung" +) + +func costCenters() []string { + return []string{ccPlattform, ccPruefwerk, ccFirmwerk, ccWerkpilot, ccInfrastruktur, ccVerwaltung} +} + +// costCenterFor maps an SKU to the product cost center its revenue belongs to. +func costCenterFor(code string) string { + switch { + case strings.HasPrefix(code, "PLT-"): + return ccPlattform + case strings.HasPrefix(code, "CRA-"): // Prüfwerk and its Werkbank runners + return ccPruefwerk + case strings.HasPrefix(code, "DEV-FWK-"): + return ccFirmwerk + case strings.HasPrefix(code, "DEV-WP-"): + return ccWerkpilot + case strings.HasPrefix(code, "INF-"): // Managed Git and build runners + return ccInfrastruktur + } + return ccVerwaltung +} + +// deferredRevenueAccountNumber is SKR04 3900 "Passive Rechnungsabgrenzung". +// The account comes with the chart of accounts and is never created here. +const deferredRevenueAccountNumber = "3900" + +// deferredMonths: yearly items ("Jahr") are released over twelve months. +const deferredMonths = 12 + +func costCenterDoc(name, abbr string) map[string]any { + return map[string]any{ + "doctype": "Cost Center", "name": name + " - " + abbr, "cost_center_name": name, + "parent_cost_center": companyName + " - " + abbr, "company": companyName, "is_group": 0, + } +} + +// accountsSettingsDoc: deferred revenue is released per calendar month as +// Journal Entries that stay drafts until a person submits them. +func accountsSettingsDoc() map[string]any { + return map[string]any{ + "doctype": "Accounts Settings", "name": "Accounts Settings", + "automatically_process_deferred_accounting_entry": 1, + "book_deferred_entries_based_on": "Months", + "book_deferred_entries_via_journal_entry": 1, + "submit_journal_entries": 0, + } +} + +// accounting runs the cost-center and deferred-revenue steps. +func (r *runner) accounting(ctx context.Context) error { + abbr, err := r.companyAbbr(ctx) + if err != nil { + return err + } + for _, cc := range costCenters() { + if err := r.ensure(ctx, "Cost Center", cc+" - "+abbr, "cost center "+cc, costCenterDoc(cc, abbr)); err != nil { + return err + } + } + if err := r.ensureFields(ctx, "Company", companyName, "company default cost center "+ccVerwaltung, + map[string]any{"doctype": "Company", "name": companyName, "cost_center": ccVerwaltung + " - " + abbr}, "cost_center"); err != nil { + return err + } + + account, err := r.findAccount(ctx, deferredRevenueAccountNumber) + if err != nil { + return err + } + deferred := account != "" + if !deferred { + // Without the account ERPNext cannot book a deferred invoice, so the + // yearly items are left as they are until the account exists. + r.record("deferred revenue account "+deferredRevenueAccountNumber, "missing (not created)") + } else { + if err := r.ensureFields(ctx, "Company", companyName, "company deferred revenue account "+account, + map[string]any{"doctype": "Company", "name": companyName, "default_deferred_revenue_account": account}, "default_deferred_revenue_account"); err != nil { + return err + } + if err := r.ensureFields(ctx, "Accounts Settings", "Accounts Settings", "deferred revenue monthly, as draft journal entries", + accountsSettingsDoc(), "automatically_process_deferred_accounting_entry", "book_deferred_entries_based_on", + "book_deferred_entries_via_journal_entry", "submit_journal_entries"); err != nil { + return err + } + } + for _, s := range skus() { + if err := r.ensureItemAccounting(ctx, s, costCenterFor(s.Code)+" - "+abbr, deferred && s.UOM == "Jahr"); err != nil { + return err + } + } + return nil +} + +// companyAbbr reads the company abbreviation ERPNext appends to cost center +// and account names. +func (r *runner) companyAbbr(ctx context.Context) (string, error) { + status, body, err := r.call(ctx, http.MethodGet, "/api/resource/Company/"+url.PathEscape(companyName), nil) + if err != nil { + return "", err + } + if status != http.StatusOK { + return "", fmt.Errorf("erpsetup: company %q: HTTP %d", companyName, status) + } + var cur struct { + Data struct { + Abbr string `json:"abbr"` + } `json:"data"` + } + _ = json.Unmarshal(body, &cur) + if cur.Data.Abbr == "" { + return "", fmt.Errorf("erpsetup: company %q has no abbreviation", companyName) + } + return cur.Data.Abbr, nil +} + +// findAccount returns the name of the company's account with that number, or "". +func (r *runner) findAccount(ctx context.Context, number string) (string, error) { + f, _ := json.Marshal([][]any{{"account_number", "=", number}, {"company", "=", companyName}}) + q := url.Values{"filters": {string(f)}, "fields": {`["name"]`}, "limit_page_length": {"1"}} + status, body, err := r.call(ctx, http.MethodGet, "/api/resource/Account?"+q.Encode(), nil) + if err != nil { + return "", err + } + if status != http.StatusOK { + return "", fmt.Errorf("erpsetup: list Account: HTTP %d %s", status, truncate(body)) + } + var list struct { + Data []struct { + Name string `json:"name"` + } `json:"data"` + } + if err := json.Unmarshal(body, &list); err != nil { + return "", fmt.Errorf("erpsetup: decode Account list: %w", err) + } + if len(list.Data) == 0 { + return "", nil + } + return list.Data[0].Name, nil +} + +// ensureItemAccounting sets the item's selling cost center for the company +// (Item Defaults row) and, for yearly items, deferred revenue over twelve +// months. Other Item Defaults rows and fields of the company's row are kept. +func (r *runner) ensureItemAccounting(ctx context.Context, s sku, costCenter string, deferred bool) error { + what := fmt.Sprintf("item %s cost center %s", s.Code, strings.SplitN(costCenter, " - ", 2)[0]) + if deferred { + what += fmt.Sprintf(", deferred %d months", deferredMonths) + } + path := "/api/resource/Item/" + url.PathEscape(s.Code) + status, body, err := r.call(ctx, http.MethodGet, path, nil) + if err != nil { + return err + } + if status == http.StatusNotFound && r.cfg.DryRun { + r.record(what, "would update") // the item itself is created by an earlier step + return nil + } + if status != http.StatusOK { + return fmt.Errorf("erpsetup: GET Item %q: HTTP %d", s.Code, status) + } + var cur struct { + Data struct { + EnableDeferredRevenue any `json:"enable_deferred_revenue"` + NoOfMonths any `json:"no_of_months"` + ItemDefaults []map[string]any `json:"item_defaults"` + } `json:"data"` + } + _ = json.Unmarshal(body, &cur) + + patch := map[string]any{} + rows, found, changed := cur.Data.ItemDefaults, false, false + for _, row := range rows { + if row["company"] == companyName { + found = true + if row["selling_cost_center"] != costCenter { + row["selling_cost_center"], changed = costCenter, true + } + } + } + if !found { + rows, changed = append(rows, map[string]any{"company": companyName, "selling_cost_center": costCenter}), true + } + if changed { + patch["item_defaults"] = rows // the full table: rows left out would be deleted + } + if deferred && (fmt.Sprint(cur.Data.EnableDeferredRevenue) != "1" || fmt.Sprint(cur.Data.NoOfMonths) != fmt.Sprint(deferredMonths)) { + patch["enable_deferred_revenue"], patch["no_of_months"] = 1, deferredMonths + } + if len(patch) == 0 { + 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, patch) + 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 +} diff --git a/internal/erpsetup/accounting_test.go b/internal/erpsetup/accounting_test.go new file mode 100644 index 0000000..fc31738 --- /dev/null +++ b/internal/erpsetup/accounting_test.go @@ -0,0 +1,131 @@ +package erpsetup + +import ( + "context" + "fmt" + "net/http/httptest" + "strings" + "testing" +) + +func itemRow(t *testing.T, f *fakeFrappe, code string) (map[string]any, []any) { + t.Helper() + item := f.docs["Item"][code] + rows, _ := item["item_defaults"].([]any) + return item, rows +} + +func TestEverySKUHasAProductCostCenter(t *testing.T) { + for _, s := range skus() { + if cc := costCenterFor(s.Code); cc == ccVerwaltung { + t.Errorf("%s falls back to %s", s.Code, cc) + } + } + if costCenterFor("XYZ-1") != ccVerwaltung { + t.Error("unknown SKU should go to Verwaltung") + } +} + +func TestCostCentersAndDeferredRevenue(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) + } + for _, cc := range costCenters() { + d, ok := f.docs["Cost Center"][cc+" - BG"] + if !ok || d["parent_cost_center"] != companyName+" - BG" || d["is_group"] != float64(0) { + t.Errorf("cost center %s: %v", cc, d) + } + } + co := f.docs["Company"][companyName] + if co["cost_center"] != "Verwaltung - BG" || co["default_deferred_revenue_account"] != "3900 - Passive Rechnungsabgrenzung - BG" { + t.Errorf("company defaults: %v", co) + } + as := f.docs["Accounts Settings"]["Accounts Settings"] + if as["submit_journal_entries"] != float64(0) || as["book_deferred_entries_based_on"] != "Months" || as["book_deferred_entries_via_journal_entry"] != float64(1) { + t.Errorf("accounts settings: %v", as) + } + for _, s := range skus() { + item, rows := itemRow(t, f, s.Code) + if len(rows) != 1 || rows[0].(map[string]any)["selling_cost_center"] != costCenterFor(s.Code)+" - BG" { + t.Errorf("%s item defaults: %v", s.Code, rows) + } + yearly := s.UOM == "Jahr" + if got := fmt.Sprint(item["enable_deferred_revenue"]) == "1"; got != yearly { + t.Errorf("%s (%s): deferred=%v", s.Code, s.UOM, item["enable_deferred_revenue"]) + } + if yearly && fmt.Sprint(item["no_of_months"]) != "12" { + t.Errorf("%s: no_of_months=%v", s.Code, item["no_of_months"]) + } + } +} + +func TestItemDefaultsAreKept(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) + } + // Someone set an income account on the row and added a row for another company. + item, rows := itemRow(t, f, "DEV-WP-OPR-STD") + row := rows[0].(map[string]any) + row["name"], row["income_account"], row["selling_cost_center"] = "ROW-1", "4400 - Erlöse - BG", "Main - BG" + item["item_defaults"] = append(rows, map[string]any{"name": "ROW-2", "company": "Other GmbH", "selling_cost_center": "Main - OG"}) + + if _, err := Run(context.Background(), cfg(srv.URL)); err != nil { + t.Fatal(err) + } + _, rows = itemRow(t, f, "DEV-WP-OPR-STD") + if len(rows) != 2 { + t.Fatalf("rows: %v", rows) + } + own, other := rows[0].(map[string]any), rows[1].(map[string]any) + if own["name"] != "ROW-1" || own["income_account"] != "4400 - Erlöse - BG" || own["selling_cost_center"] != "Werkpilot - BG" { + t.Errorf("own row: %v", own) + } + if other["selling_cost_center"] != "Main - OG" { + t.Errorf("other company's row changed: %v", other) + } +} + +func TestMissingDeferredAccountSkipsDeferral(t *testing.T) { + f := newFake() + delete(f.docs, "Account") + srv := httptest.NewServer(f) + defer srv.Close() + steps, err := Run(context.Background(), cfg(srv.URL)) + if err != nil { + t.Fatal(err) + } + var missing bool + for _, s := range steps { + if strings.HasPrefix(s.What, "deferred revenue account") && s.Result == "missing (not created)" { + missing = true + } + } + if !missing { + t.Error("missing account not reported") + } + if _, ok := f.docs["Accounts Settings"]; ok { + t.Error("accounts settings written without the account") + } + if item, _ := itemRow(t, f, "DEV-WP-OPR-STD"); item["enable_deferred_revenue"] != nil { + t.Errorf("yearly item deferred without the account: %v", item["enable_deferred_revenue"]) + } + if _, ok := f.docs["Cost Center"]["Werkpilot - BG"]; !ok { + t.Error("cost centers must not depend on the account") + } +} + +func TestMissingCompanyStops(t *testing.T) { + f := newFake() + delete(f.docs, "Company") + srv := httptest.NewServer(f) + defer srv.Close() + if _, err := Run(context.Background(), cfg(srv.URL)); err == nil || !strings.Contains(err.Error(), "company") { + t.Fatalf("want a company error, got %v", err) + } +} diff --git a/internal/erpsetup/erpsetup.go b/internal/erpsetup/erpsetup.go index 381f05e..7f35b0c 100644 --- a/internal/erpsetup/erpsetup.go +++ b/internal/erpsetup/erpsetup.go @@ -3,8 +3,10 @@ // Usage Record doctype the outbox writes, the sales catalogue (SKU items, units, // SEPA mandate fields, payment method, list prices), the document layout // (letter head, print formats, invoice e-mail) and the Frappe Webhooks that -// drive the tenant ladder. Every step checks first and creates only what is missing, -// so it can run again at any time; with DryRun it only reports. +// drive the tenant ladder, plus the cost centers per product and deferred +// revenue for yearly items (accounting.go). Every step checks first and +// creates only what is missing, so it can run again at any time; with DryRun +// it only reports. // // It never submits, cancels or deletes an ERP document. package erpsetup @@ -135,6 +137,10 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) { return r.steps, err } } + // Cost centers per product and deferred revenue for yearly items. + if err := r.accounting(ctx); err != nil { + return r.steps, err + } // Documents in the BreakPilot look: creditor id field, company address, // letter head, print formats, invoice e-mail and the defaults. for _, f := range brandingFields() { diff --git a/internal/erpsetup/erpsetup_test.go b/internal/erpsetup/erpsetup_test.go index d8a983d..3f56857 100644 --- a/internal/erpsetup/erpsetup_test.go +++ b/internal/erpsetup/erpsetup_test.go @@ -24,7 +24,14 @@ type fakeFrappe struct { auth string } -func newFake() *fakeFrappe { return &fakeFrappe{docs: map[string]map[string]map[string]any{}} } +// 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() @@ -136,11 +143,14 @@ func TestRunCreatesThenIsIdempotent(t *testing.T) { if err != nil { t.Fatal(err) } - if len(steps) != 108 || f.posts != 108 { - t.Fatalf("first run: %d steps, %d creates; want 108/108: %+v", len(steps), f.posts, steps) + first := f.posts + if first != len(steps) { + t.Fatalf("first run: %d steps, %d writes: %+v", len(steps), first, steps) } for _, s := range steps { - if s.Result != "created" { + // 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) } } @@ -153,8 +163,8 @@ func TestRunCreatesThenIsIdempotent(t *testing.T) { if err != nil { t.Fatal(err) } - if f.posts != 108 { - t.Fatalf("second run created %d more docs", f.posts-108) + 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") { @@ -179,7 +189,7 @@ func TestDryRunChangesNothing(t *testing.T) { t.Fatalf("dry run posted %d docs, logged %d of %d", f.posts, logged, len(steps)) } for _, s := range steps { - if s.Result != "would create" { + if !strings.HasPrefix(s.Result, "would ") { t.Errorf("%s: %s", s.What, s.Result) } }