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 }