Files
sharangandSharang Parnerkar 1332ad7bc5
ci / shared (push) Successful in 15s
ci / test (push) Successful in 26m35s
ci / image (push) Successful in 53s
feat(erpsetup): catalogue for Leistungsbeschreibung 1.0.0, opt-in -sync-catalog (#115)
Brings the ERPNext sales catalogue in line with the frozen Leistungsbeschreibungen 1.0.0. This PR changes code and tests only. No ERP was called; the live run is yours, using the erpsetup CLI.

## Dry run first (with the flag; only this path prints `field old → new`)

```sh
ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… ERP_WEBHOOK_SECRET=… \
  go run ./cmd/erpsetup -webhook-url https://registry.breakpilot.com/v1/internal/erp/webhook -sync-catalog -dry-run
```

(`ERP_LEAD_DOCTYPE` is optional, as before.) Leave out `-dry-run` for the real run.

## What a run does with and without `-sync-catalog`

| | without the flag (as today) | with `-sync-catalog` |
|---|---|---|
| New items, unit "Prüftag", their list prices | created | created |
| Item **description** | **updated (this already happens on every run today)** | updated |
| Item `item_name`, `disabled` | untouched | updated when they differ |
| Standard Selling `price_list_rate` (rows without a customer) | set once, never changed | updated when it differs |
| Customer-specific Item Prices | untouched | untouched |
| Quote print format (Mehrverbrauch row) | updated | updated |

**A plain run is not inert.** It creates the 5 new items, the new unit and 5 new prices, rewrites every changed description, and updates the quote template. Only names, the disabled flags and price changes wait for the flag. Nothing is ever deleted. Only the doctypes Item, Item Price and UOM are touched beyond what erpsetup already manages.

## Catalogue changes

| Code | Status | Price old → new (EUR) |
|---|---|---|
| PLT-CORE-CLD-STD/BUS/ENT | keep (name "Breakpilot …", new text) | 290 / 790 / 1990 (unchanged) |
| PLT-BNDL-CLD-STD | **new** Starter-Modulpaket | 990 |
| PLT-BNDL-CLD-ADD | **new** Weiteres Modul | 499 |
| CRA-CSA-CLD-STD | keep | **1490 → 490** |
| CRA-CSA-CLD-BUS | keep | **3990 → 1290** |
| CRA-CSA-CLD-ENT | keep | **9900 → 0** (Preis nach Vereinbarung: a quote shows 0,00 € unless the rate is entered by hand) |
| CRA-CSA-CLD-TGT | **new** extra Prüfobjekt / Monat | 5.99 |
| CRA-CSA-CLD-DAY | **new** Prüftag (unit Prüftag) | 9.99 |
| CRA-CSA-CLD-SCAN | **disable** | 12 (unchanged) |
| CRA-WBK-CLD-STD/BUS/ENT | **disable** | unchanged |
| DEV-WP-CLD-STD | keep ("Werkpilot Cloud") | 59 |
| DEV-WP-CLD-BUS/ENT | **disable** | unchanged |
| DEV-WP-OPR-*, DEV-FWK-OPR-*, INF-GIT-OPR-*, INF-CI-OPR-* | keep, new texts | unchanged |
| DEV-FWK-CLD-STD | keep ("Firmwerk Cloud") | 89 |
| DEV-FWK-CLD-BUS/ENT | **disable** | unchanged |
| INF-GIT-CLD-STD/BUS/ENT | keep, new texts | 190 / 390 / 790 |
| INF-GIT-CLD-USR | **new** extra user | 19 |
| INF-CI-CLD-STD/BUS/ENT | keep, new texts | 149 / 290 / 590 |

The item group stays "BreakPilot Abonnements".

Correction to the spec, applied here: PLT-CORE-CLD-STD no longer mentions "Rechnungen", because LB Plattform §2(3) says the portal provides no invoices. The text is now "Arbeitsbereich mit Anmeldung und Team für bis 25 Nutzer, Standard-Support. Module werden einzeln gebucht." No other item text mentions invoices, and a test now checks that none does.

## Other changes

- `sku.Disabled` is sent to ERPNext as the Item field `disabled: 1`. Disabled items stay in ERPNext so old documents keep working. Since the disabled items already exist on prod, their flag only changes with `-sync-catalog`.
- **Quote, Mehrverbrauch row:** "Zusätzliche Prüfobjekte werden mit {TGT} netto je Monat berechnet, Prüftage nach verbrauchtem Monatskontingent mit {DAY} netto (Leistungsbeschreibung Prüfwerk, Abschnitt 7)." If a rate is missing, the text says "gemäß der jeweils gültigen Preisliste" instead, per rate. If both are missing, one combined sentence is printed. Quotes with INF-GIT-CLD-STD/BUS/ENT or PLT-BNDL-* add the sentence on extra users (Leistungsbeschreibung Breakpilot Plattform, Abschnitt 4). The Jinja was parsed and rendered locally with jinja2 against mocks for eight item mixes.
- **Migration 0026** adds CRA-CSA-CLD-TGT and -DAY to the `pruefwerk` product. SCAN stays so old orders still map. The up is guarded so it can run twice; the down removes the two SKUs. `DefaultProducts` and the ERP mock's SKU list follow. **Run `migrate-up` with the deploy.** Without it, TGT/DAY lines on an order log "sales order item without catalog product".
- **0 € module lines:** nothing needed fixing. Neither the webhook path nor reconcile reads the rate: the webhook template sends only `item_code` and `qty`, and `SubscriptionPlan` has no rate. A new test covers both paths: a bundle order with modules at rate 0 and qty 15 gives an active tenant, plan standard, and seats 15 per module.

## Decisions the spec did not cover

1. **No Prüfwerk Mehrverbrauch sentence on Enterprise quotes.** CRA-CSA-CLD-ENT is "ohne Begrenzung". Edge case: a quote with both -STD and -ENT also prints no Prüfwerk sentence. The extra-users sentence is not affected.
2. The run without the flag still writes descriptions, as `Run` has done until now (see the table).
3. `-sync-catalog` only changes Item Price rows without a `customer`. If there are several such rows for an item, the run reports "not synced". If there are none, it creates the list price.
4. The quote template's Item Price lookup still has no customer filter (unchanged from before).
5. INF-GIT-OPR texts: STD uses the spec text exactly, so "kein Quellcode verlässt das Haus" is gone. BUS keeps "für mittelgroße Teams" and loses "schnellerer Patch-Rhythmus", like CI. ENT says "für große Entwicklungsorganisationen".
6. INF-CI-OPR texts differ only by size ("mindestens 2 vCPU / 4 GB" etc.); "für größere/umfangreiche Builds" was dropped.
7. DEV-WP-OPR and DEV-FWK-OPR texts: the tier phrase sits after "im eigenen Netz", e.g. "Werkpilot im eigenen Netz für mittlere Teams, mit einem vom Kunden betriebenen KI-Modell; …".
8. TGT/DAY quantities on an order or subscription count toward Prüfwerk `seats`, exactly as SCAN already does. Not changed here.
9. Bundle revenue goes to cost center Plattform (PLT-*). Module lines at 0 € book nothing on Prüfwerk, Firmwerk or Werkpilot. Whether to allocate it is an accounting decision for you.
10. The dry run prints texts in full (no truncation), so the wording can be read before it goes live.
11. `TestEverySKUHasAListPrice` now allows exactly one item at 0: CRA-CSA-CLD-ENT.
12. The ERP mock's `DefaultSKUs` now also lists PLT-BNDL-* and CRA-CSA-CLD-TGT/DAY.

## Tests

`go build ./... && go vet ./... && go test ./...` all pass. The Postgres testcontainers suites ran (podman socket) with no skips: server 463 s, migrations 32 s. New tests:

- catalogue consistency: unique codes, units, disabled set, prices including 5.99/9.99, brand spelling
- `TestSyncCatalog`: the dry run writes nothing and names every change; the run updates name, description, disabled and price and keeps the customer price; a second run makes no updates; without the flag only the description changes
- quote template phrases
- `TestMigrate_productsSeedMatchesDefaults`: seed equals `DefaultProducts`, 0026 applied twice, down
- `TestErp_zeroRateModuleLinesEntitle`: webhook and reconcile, memory and Postgres

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #115
2026-11-06 16:20:22 +00:00

608 lines
21 KiB
Go

// Package erpsetup applies the live-ERPNext configuration the registry relies
// on (ERP/03 "live configuration"): custom fields that carry the tenant id, the
// 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, 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
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Config for one run.
type Config struct {
BaseURL string // https://erp.breakpilot.com
APIKey string
APISecret string
WebhookURL string // https://registry.breakpilot.com/v1/internal/erp/webhook
WebhookSecret string // same value as the registry's ERP_WEBHOOK_SECRET
LeadDoctype string // "Lead" (ERPNext) or "CRM Lead" (Frappe CRM)
DryRun bool
// SyncCatalog also brings existing catalogue items (name, description,
// disabled) and their Standard Selling list prices to the values in
// catalog.go. Off: items are created when missing and only their
// description is kept current; a list price is set once.
SyncCatalog bool
HTTP *http.Client
Log func(format string, args ...any)
}
// Step is one reported action.
type Step struct {
What string // e.g. "custom field Customer.tenant_id"
Result string // "exists", "created", "would create", "missing (not created)"
}
type runner struct {
cfg Config
steps []Step
}
// Run applies (or, with DryRun, reports) the configuration.
func Run(ctx context.Context, cfg Config) ([]Step, error) {
if cfg.BaseURL == "" || cfg.APIKey == "" || cfg.APISecret == "" {
return nil, errors.New("erpsetup: base URL, API key and API secret are required")
}
if cfg.WebhookURL == "" || cfg.WebhookSecret == "" {
return nil, errors.New("erpsetup: webhook URL and webhook secret are required")
}
if cfg.LeadDoctype == "" {
cfg.LeadDoctype = "Lead"
}
if cfg.HTTP == nil {
cfg.HTTP = &http.Client{Timeout: 30 * time.Second}
}
if cfg.Log == nil {
cfg.Log = func(string, ...any) {}
}
cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/")
r := &runner{cfg: cfg}
for _, f := range customFields(cfg.LeadDoctype) {
if err := r.ensure(ctx, "Custom Field", f["name"].(string), fmt.Sprintf("custom field %s.%s", f["dt"], f["fieldname"]), f); err != nil {
return r.steps, err
}
}
if err := r.ensure(ctx, "DocType", "Usage Record", "doctype Usage Record", usageRecordDoctype()); err != nil {
return r.steps, err
}
// Sales catalogue: units, item group, the SKU items, SEPA mandate fields
// on the Customer and the payment method.
for _, u := range uoms() {
if err := r.ensure(ctx, "UOM", u["name"].(string), "unit "+u["name"].(string), u); err != nil {
return r.steps, err
}
}
if err := r.ensure(ctx, "Item Group", itemGroup, "item group "+itemGroup, itemGroupDoc()); err != nil {
return r.steps, err
}
for _, s := range skus() {
// The description is the product wording on every document (Angebot,
// Auftragsbestätigung, Rechnung) and follows the catalogue here; with
// SyncCatalog so do the name and the disabled flag.
what := "item " + s.Code + " (" + s.Name + ")"
var err error
if cfg.SyncCatalog {
err = r.syncFields(ctx, "Item", s.Code, what, itemDoc(s), "item_name", "description", "disabled")
} else {
err = r.ensureFields(ctx, "Item", s.Code, what, itemDoc(s), "description")
}
if err != nil {
return r.steps, err
}
}
for _, f := range sepaFields() {
if err := r.ensure(ctx, "Custom Field", f["name"].(string), fmt.Sprintf("custom field %s.%s", f["dt"], f["fieldname"]), f); err != nil {
return r.steps, err
}
}
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 _, s := range skus() {
what := fmt.Sprintf("price %s (%s, %.2f EUR/%s)", s.Code, priceList, s.Price, s.UOM)
var err error
if cfg.SyncCatalog {
err = r.syncPrice(ctx, what, s)
} else {
err = r.ensureListed(ctx, "Item Price", what,
[][]any{{"item_code", "=", s.Code}, {"price_list", "=", priceList}}, itemPriceDoc(s))
}
if err != nil {
return r.steps, err
}
}
// Customer numbers, payment terms and the contract basis (portal#66/#67).
settings, custSetters := customerNumbering()
if err := r.ensureFields(ctx, "Selling Settings", "Selling Settings", "customer naming by series "+customerSeries, settings, "cust_master_name"); err != nil {
return r.steps, err
}
for _, ps := range custSetters {
if err := r.ensureValue(ctx, "Property Setter", ps["name"].(string), "customer number range ("+ps["property"].(string)+") "+customerSeries, ps); err != nil {
return r.steps, err
}
}
if err := r.ensure(ctx, "Payment Term", paymentTerms21, "payment term "+paymentTerms21, paymentTermDoc()); err != nil {
return r.steps, err
}
if err := r.ensure(ctx, "Payment Terms Template", paymentTerms21, "payment terms template "+paymentTerms21, paymentTemplateDoc()); err != nil {
return r.steps, err
}
if err := r.ensureFields(ctx, "Company", companyName, "company default payment terms "+paymentTerms21,
map[string]any{"doctype": "Company", "name": companyName, "payment_terms": paymentTerms21}, "payment_terms"); err != nil {
return r.steps, err
}
for _, f := range contractBasisFields() {
if err := r.ensure(ctx, "Custom Field", f["name"].(string), fmt.Sprintf("custom field %s.%s", f["dt"], f["fieldname"]), f); err != nil {
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() {
if err := r.ensure(ctx, "Custom Field", f["name"].(string), fmt.Sprintf("custom field %s.%s", f["dt"], f["fieldname"]), f); err != nil {
return r.steps, err
}
}
if err := r.ensureListed(ctx, "Address", "company address "+companyName,
[][]any{{"is_your_company_address", "=", 1}}, companyAddressDoc()); err != nil {
return r.steps, err
}
if err := r.ensureListed(ctx, "File", "logo "+logoFileURL,
[][]any{{"file_url", "=", logoFileURL}}, logoFileDoc()); err != nil {
return r.steps, err
}
if err := r.ensureFields(ctx, "Letter Head", letterHeadName, "letter head "+letterHeadName, letterHeadDoc(), "source", "footer_source", "content", "footer"); err != nil {
return r.steps, err
}
for _, pf := range printFormats() {
if err := r.ensureFields(ctx, "Print Format", pf["name"].(string), fmt.Sprintf("print format %s (%s)", pf["name"], pf["doc_type"]), pf, "html"); err != nil {
return r.steps, err
}
}
if err := r.ensureFields(ctx, "Email Template", emailTemplateRE, "email template "+emailTemplateRE, emailTemplateDoc(), "subject", "response_html"); err != nil {
return r.steps, err
}
for _, ps := range brandingSetters() {
if err := r.ensureValue(ctx, "Property Setter", ps["name"].(string), fmt.Sprintf("%s %s → %s", ps["doc_type"], ps["property"], ps["value"]), ps); err != nil {
return r.steps, err
}
}
// Incoming invoices: what cmd/invoiceintake writes into (intake.go).
if err := r.intake(ctx); err != nil {
return r.steps, err
}
// Outgoing e-invoices: codes, payment by transfer, the discount line,
// validation (einvoice.go). After intake: it uses the unit Stück.
if err := r.einvoice(ctx); err != nil {
return r.steps, err
}
// Travel expenses: Expense Claim Types with SKR04 accounts (reisekosten.go).
if err := r.reisekosten(ctx); 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
}
}
return r.steps, nil
}
func (r *runner) record(what, result string) {
r.steps = append(r.steps, Step{What: what, Result: result})
r.cfg.Log("%-55s %s", what, result)
}
// ensure creates doc when GET /api/resource/<doctype>/<name> is 404.
func (r *runner) ensure(ctx context.Context, doctype, name, what string, doc map[string]any) error {
status, _, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(doctype)+"/"+url.PathEscape(name), nil)
if err != nil {
return err
}
switch {
case status == http.StatusOK:
r.record(what, "exists")
return nil
case status != http.StatusNotFound:
return fmt.Errorf("erpsetup: GET %s %q: HTTP %d", doctype, name, status)
case r.cfg.DryRun:
r.record(what, "would create")
return nil
}
status, body, err := r.call(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(doctype), doc)
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
}
// 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
}
// ensureFields is ensure for a doc whose content we own (templates): an
// existing doc whose listed fields differ gets them set again.
func (r *runner) ensureFields(ctx context.Context, doctype, name, what string, doc map[string]any, keys ...string) 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 map[string]any `json:"data"`
}
_ = json.Unmarshal(body, &cur)
patch := map[string]any{}
for _, k := range keys {
if !sameValue(cur.Data[k], doc[k]) {
patch[k] = doc[k]
}
}
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
}
// ensureListed is ensure for autonamed docs: it looks for any doc matching
// filters and creates doc only when there is none. An existing one is never
// changed (prices and addresses are maintained in ERPNext; list prices are
// brought back to the catalogue only by syncPrice, with SyncCatalog).
func (r *runner) ensureListed(ctx context.Context, doctype, what string, filters [][]any, doc map[string]any) error {
f, _ := json.Marshal(filters)
q := url.Values{"filters": {string(f)}, "fields": {`["name"]`}, "limit_page_length": {"1"}}
status, body, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(doctype)+"?"+q.Encode(), nil)
if err != nil {
return err
}
if status != http.StatusOK {
return fmt.Errorf("erpsetup: list %s: HTTP %d %s", doctype, 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 %s list: %w", doctype, err)
}
if len(list.Data) > 0 {
r.record(what, "exists ("+list.Data[0].Name+")")
return nil
}
if r.cfg.DryRun {
r.record(what, "would create")
return nil
}
status, body, err = r.call(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(doctype), doc)
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
}
// syncFields is ensureFields for the catalogue sync (-sync-catalog): the
// report names each changed field with its old and new value.
func (r *runner) syncFields(ctx context.Context, doctype, name, what string, doc map[string]any, keys ...string) 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 map[string]any `json:"data"`
}
_ = json.Unmarshal(body, &cur)
patch := map[string]any{}
var changes []string
for _, k := range keys {
if !sameValue(cur.Data[k], doc[k]) {
patch[k] = doc[k]
changes = append(changes, change(k, cur.Data[k], doc[k]))
}
}
return r.applyPatch(ctx, path, what, "", patch, changes)
}
// syncPrice is ensureListed for a list price with -sync-catalog: the item's
// Standard Selling price (the one without a customer; customer prices are
// left alone) gets the catalogue rate.
func (r *runner) syncPrice(ctx context.Context, what string, s sku) error {
f, _ := json.Marshal([][]any{{"item_code", "=", s.Code}, {"price_list", "=", priceList}})
q := url.Values{"filters": {string(f)}, "fields": {`["name","price_list_rate","customer"]`}, "limit_page_length": {"50"}}
status, body, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape("Item Price")+"?"+q.Encode(), nil)
if err != nil {
return err
}
if status != http.StatusOK {
return fmt.Errorf("erpsetup: list Item Price: HTTP %d %s", status, truncate(body))
}
var list struct {
Data []struct {
Name string `json:"name"`
PriceListRate float64 `json:"price_list_rate"`
Customer string `json:"customer"`
} `json:"data"`
}
if err := json.Unmarshal(body, &list); err != nil {
return fmt.Errorf("erpsetup: decode Item Price list: %w", err)
}
var general []string
var rate float64
for _, p := range list.Data {
if p.Customer == "" {
general = append(general, p.Name)
rate = p.PriceListRate
}
}
switch {
case len(general) == 0:
if r.cfg.DryRun {
r.record(what, "would create")
return nil
}
status, body, err := r.call(ctx, http.MethodPost, "/api/resource/"+url.PathEscape("Item Price"), itemPriceDoc(s))
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
case len(general) > 1:
r.record(what, fmt.Sprintf("exists (%d list prices %s, not synced)", len(general), strings.Join(general, ", ")))
return nil
}
patch := map[string]any{}
var changes []string
if !sameValue(rate, s.Price) {
patch["price_list_rate"] = s.Price
changes = append(changes, change("price_list_rate", rate, s.Price))
}
return r.applyPatch(ctx, "/api/resource/"+url.PathEscape("Item Price")+"/"+url.PathEscape(general[0]), what, " ("+general[0]+")", patch, changes)
}
// applyPatch writes patch to the doc at path and reports the changes;
// nothing to change is "exists", a dry run "would update".
func (r *runner) applyPatch(ctx context.Context, path, what, ref string, patch map[string]any, changes []string) error {
if len(patch) == 0 {
r.record(what, "exists"+ref)
return nil
}
detail := ref + ": " + strings.Join(changes, "; ")
if r.cfg.DryRun {
r.record(what, "would update"+detail)
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"+detail)
return nil
}
// change is one field of a sync report: field old → new. Texts are shown in
// full: the dry run is where the new wording is read before it goes live.
func change(field string, old, want any) string {
show := func(v any) string {
switch x := v.(type) {
case nil:
return `""`
case string:
return fmt.Sprintf("%q", x)
}
return fmt.Sprint(v)
}
return field + " " + show(old) + " → " + show(want)
}
// 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)
filters, _ := json.Marshal([][]string{
{"webhook_doctype", "=", w.Doctype},
{"webhook_docevent", "=", w.DocEvent},
{"request_url", "=", w.URL},
})
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
}
if status != http.StatusOK {
return fmt.Errorf("erpsetup: list webhooks: HTTP %d %s", status, truncate(body))
}
var list struct {
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+`"`) {
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")
return nil
}
status, body, err = r.call(ctx, http.MethodPost, "/api/resource/Webhook", w.doc())
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
}
func (r *runner) call(ctx context.Context, method, path string, body any) (int, []byte, error) {
var rd io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return 0, nil, err
}
rd = bytes.NewReader(buf)
}
req, err := http.NewRequestWithContext(ctx, method, r.cfg.BaseURL+path, rd)
if err != nil {
return 0, nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "token "+r.cfg.APIKey+":"+r.cfg.APISecret)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := r.cfg.HTTP.Do(req)
if err != nil {
return 0, nil, fmt.Errorf("erpsetup: %s %s: %w", method, path, err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
return resp.StatusCode, raw, fmt.Errorf("erpsetup: %s %s: HTTP %d — check the API key and the user's roles", method, path, resp.StatusCode)
}
return resp.StatusCode, raw, nil
}
// sameValue compares a stored field with the wanted one. Frappe's HTML
// editor wraps table rows in <tbody> when a document is saved in the UI;
// that is not a change of ours and must not show up as one on every run.
func sameValue(got, want any) bool {
norm := strings.NewReplacer("<tbody>", "", "</tbody>", "")
return norm.Replace(fmt.Sprint(got)) == norm.Replace(fmt.Sprint(want))
}
func truncate(b []byte) string {
s := strings.TrimSpace(string(b))
if len(s) > 300 {
return s[:300] + "…"
}
return s
}