Files
tenant-registry/internal/erpmock/server.go
T
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

434 lines
12 KiB
Go

// Package erpmock is the staging stand-in for ERPNext (decision 18): the
// Frappe REST surface the registry uses (/api/resource/{doctype}), a request
// log for test assertions and /_mock/fire/* triggers that send HMAC-signed
// webhooks in the shape the registry's receiver expects. State is in memory.
package erpmock
import (
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// Doc is a Frappe document: a JSON object with at least "name".
type Doc map[string]any
// Request is one logged inbound API call.
type Request struct {
At time.Time `json:"at"`
Method string `json:"method"`
Path string `json:"path"`
Doctype string `json:"doctype,omitempty"`
Body json.RawMessage `json:"body,omitempty"`
Status int `json:"status"`
}
// Delivery is one outbound webhook attempt.
type Delivery struct {
At time.Time `json:"at"`
Event string `json:"event"`
EventID string `json:"event_id"`
Payload json.RawMessage `json:"payload"`
Status int `json:"status"`
Error string `json:"error,omitempty"`
Response string `json:"response,omitempty"`
}
type Config struct {
APIKey string
APISecret string
WebhookURL string
WebhookSecret string
// SKUs seeded as Item + Subscription Plan docs.
SKUs []string
// NameToken goes into every name the mock assigns (CUST-<token>-00001).
// The mock keeps its docs in memory, so after a restart its counter
// starts again; without a token a new customer would get a name an older
// tenant in the registry is still linked to (unique erp_customer_id).
// Empty in tests: plain CUST-00001.
NameToken string
}
type Server struct {
cfg Config
mux *http.ServeMux
http *http.Client
mu sync.Mutex
docs map[string]map[string]Doc // doctype → name → doc
seq map[string]int
requests []Request
deliveries []Delivery
}
// DefaultSKUs mirrors the Phase-1 SKU sheet (ERP/02).
var DefaultSKUs = []string{
"PLT-CORE-CLD-STD", "PLT-CORE-CLD-BUS", "PLT-CORE-CLD-ENT", "PLT-BNDL-CLD-STD", "PLT-BNDL-CLD-ADD",
"CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN", "CRA-CSA-CLD-TGT", "CRA-CSA-CLD-DAY",
"CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT",
"DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT",
"DEV-FWK-CLD-STD", "DEV-FWK-CLD-BUS", "DEV-FWK-CLD-ENT", "DEV-FWK-OPR-STD", "DEV-FWK-OPR-BUS", "DEV-FWK-OPR-ENT",
}
func New(cfg Config) *Server {
if len(cfg.SKUs) == 0 {
cfg.SKUs = DefaultSKUs
}
s := &Server{cfg: cfg, mux: http.NewServeMux(), http: &http.Client{Timeout: 10 * time.Second}}
s.reset()
s.mux.HandleFunc("GET /api/method/ping", func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, 200, map[string]any{"message": "pong"}) })
s.mux.HandleFunc("GET /api/resource/{doctype}", s.withAuth(s.list))
s.mux.HandleFunc("POST /api/resource/{doctype}", s.withAuth(s.create))
s.mux.HandleFunc("GET /api/resource/{doctype}/{name}", s.withAuth(s.get))
s.mux.HandleFunc("PUT /api/resource/{doctype}/{name}", s.withAuth(s.update))
s.mux.HandleFunc("DELETE /api/resource/{doctype}/{name}", s.withAuth(s.del))
s.mux.HandleFunc("GET /_mock/requests", s.listRequests)
s.mux.HandleFunc("DELETE /_mock/requests", s.clearRequests)
s.mux.HandleFunc("GET /_mock/deliveries", s.listDeliveries)
s.mux.HandleFunc("GET /_mock/docs/{doctype}", s.dumpDocs)
s.mux.HandleFunc("POST /_mock/reset", s.resetHandler)
s.mux.HandleFunc("POST /_mock/fire/{trigger}", s.fire)
s.mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, 200, map[string]string{"status": "ok"}) })
return s
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mux.ServeHTTP(w, r) }
func (s *Server) reset() {
s.mu.Lock()
defer s.mu.Unlock()
s.docs = map[string]map[string]Doc{}
s.seq = map[string]int{}
s.requests = nil
s.deliveries = nil
for _, sku := range s.cfg.SKUs {
s.put("Item", Doc{"name": sku, "item_code": sku, "item_name": sku, "item_group": "Services", "is_stock_item": 0})
s.put("Subscription Plan", Doc{"name": sku, "plan_name": sku, "item": sku, "billing_interval": "Month"})
}
}
// put stores a doc under doctype (assigning a name when absent). Caller holds mu.
func (s *Server) put(doctype string, d Doc) Doc {
if s.docs[doctype] == nil {
s.docs[doctype] = map[string]Doc{}
}
name, _ := d["name"].(string)
if name == "" {
s.seq[doctype]++
if s.cfg.NameToken != "" {
name = fmt.Sprintf("%s-%s-%05d", prefix(doctype), s.cfg.NameToken, s.seq[doctype])
} else {
name = fmt.Sprintf("%s-%05d", prefix(doctype), s.seq[doctype])
}
d["name"] = name
}
now := time.Now().UTC().Format("2006-01-02 15:04:05.000000")
if _, ok := d["creation"]; !ok {
d["creation"] = now
}
d["modified"] = now
d["doctype"] = doctype
s.docs[doctype][name] = d
return d
}
func prefix(doctype string) string {
switch doctype {
case "Customer":
return "CUST"
case "Subscription":
return "SUB"
case "Sales Order":
return "SAL-ORD"
case "Sales Invoice":
return "ACC-SINV"
case "Payment Entry":
return "ACC-PAY"
case "Usage Record":
return "USG"
case "Lead", "CRM Lead":
return "CRM-LEAD"
}
return strings.ToUpper(strings.ReplaceAll(doctype, " ", "-"))
}
func (s *Server) withAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
want := "token " + s.cfg.APIKey + ":" + s.cfg.APISecret
if s.cfg.APIKey != "" && r.Header.Get("Authorization") != want {
s.log(r, nil, http.StatusUnauthorized)
writeJSON(w, http.StatusUnauthorized, map[string]any{"exc_type": "AuthenticationError", "message": "Invalid API key"})
return
}
next(w, r)
}
}
func (s *Server) log(r *http.Request, body []byte, status int) {
s.mu.Lock()
defer s.mu.Unlock()
req := Request{At: time.Now().UTC(), Method: r.Method, Path: r.URL.RequestURI(), Doctype: r.PathValue("doctype"), Status: status}
if len(body) > 0 && json.Valid(body) {
req.Body = json.RawMessage(body)
}
s.requests = append(s.requests, req)
}
// ─── /api/resource ────────────────────────────────────────────────────────
type filter struct {
Field, Op string
Value any
}
func parseFilters(raw string) ([]filter, error) {
if strings.TrimSpace(raw) == "" {
return nil, nil
}
var arr [][]any
if err := json.Unmarshal([]byte(raw), &arr); err != nil {
return nil, err
}
out := make([]filter, 0, len(arr))
for _, f := range arr {
if len(f) == 3 {
out = append(out, filter{Field: fmt.Sprint(f[0]), Op: fmt.Sprint(f[1]), Value: f[2]})
} else if len(f) == 4 { // [doctype, field, op, value]
out = append(out, filter{Field: fmt.Sprint(f[1]), Op: fmt.Sprint(f[2]), Value: f[3]})
}
}
return out, nil
}
func matches(d Doc, fs []filter) bool {
for _, f := range fs {
got := fmt.Sprint(d[f.Field])
want := fmt.Sprint(f.Value)
switch f.Op {
case "=", "==":
if got != want {
return false
}
case "!=":
if got == want {
return false
}
case "<", ">":
if !compare(got, want, f.Op) {
return false
}
case "like":
if !strings.Contains(strings.ToLower(got), strings.ToLower(strings.Trim(want, "%"))) {
return false
}
case "in":
ok := false
if arr, isArr := f.Value.([]any); isArr {
for _, v := range arr {
if fmt.Sprint(v) == got {
ok = true
}
}
}
if !ok {
return false
}
}
}
return true
}
func (s *Server) list(w http.ResponseWriter, r *http.Request) {
doctype := r.PathValue("doctype")
fs, err := parseFilters(r.URL.Query().Get("filters"))
if err != nil {
s.log(r, nil, 400)
writeJSON(w, 400, map[string]any{"message": "invalid filters"})
return
}
var fields []string
_ = json.Unmarshal([]byte(r.URL.Query().Get("fields")), &fields)
s.mu.Lock()
out := []Doc{}
names := make([]string, 0, len(s.docs[doctype]))
for n := range s.docs[doctype] {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
d := s.docs[doctype][n]
if matches(d, fs) {
out = append(out, project(d, fields))
}
}
s.mu.Unlock()
s.log(r, nil, 200)
writeJSON(w, 200, map[string]any{"data": out})
}
func project(d Doc, fields []string) Doc {
if len(fields) == 0 {
return Doc{"name": d["name"]}
}
for _, f := range fields {
if f == "*" {
return d
}
}
out := Doc{}
for _, f := range fields {
if v, ok := d[f]; ok {
out[f] = v
}
}
return out
}
func (s *Server) create(w http.ResponseWriter, r *http.Request) {
doctype := r.PathValue("doctype")
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
var d Doc
if err := json.Unmarshal(body, &d); err != nil || d == nil {
s.log(r, body, 400)
writeJSON(w, 400, map[string]any{"message": "invalid JSON"})
return
}
delete(d, "name") // ERP assigns names
s.mu.Lock()
d = s.put(doctype, d)
s.mu.Unlock()
s.log(r, body, 200)
writeJSON(w, 200, map[string]any{"data": d})
}
func (s *Server) get(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
d, ok := s.docs[r.PathValue("doctype")][r.PathValue("name")]
s.mu.Unlock()
if !ok {
s.log(r, nil, 404)
writeJSON(w, 404, map[string]any{"exc_type": "DoesNotExistError"})
return
}
s.log(r, nil, 200)
writeJSON(w, 200, map[string]any{"data": d})
}
func (s *Server) update(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
var patch Doc
if err := json.Unmarshal(body, &patch); err != nil {
s.log(r, body, 400)
writeJSON(w, 400, map[string]any{"message": "invalid JSON"})
return
}
s.mu.Lock()
d, ok := s.docs[r.PathValue("doctype")][r.PathValue("name")]
if ok {
for k, v := range patch {
if k != "name" && k != "doctype" && k != "creation" {
d[k] = v
}
}
d = s.put(r.PathValue("doctype"), d)
}
s.mu.Unlock()
if !ok {
s.log(r, body, 404)
writeJSON(w, 404, map[string]any{"exc_type": "DoesNotExistError"})
return
}
s.log(r, body, 200)
writeJSON(w, 200, map[string]any{"data": d})
}
func (s *Server) del(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
_, ok := s.docs[r.PathValue("doctype")][r.PathValue("name")]
delete(s.docs[r.PathValue("doctype")], r.PathValue("name"))
s.mu.Unlock()
if !ok {
s.log(r, nil, 404)
writeJSON(w, 404, map[string]any{"exc_type": "DoesNotExistError"})
return
}
s.log(r, nil, 202)
writeJSON(w, 202, map[string]any{"message": "ok"})
}
// ─── /_mock ───────────────────────────────────────────────────────────────
func (s *Server) listRequests(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
out := make([]Request, 0, len(s.requests))
for _, q := range s.requests {
if dt := r.URL.Query().Get("doctype"); dt != "" && q.Doctype != dt {
continue
}
if m := r.URL.Query().Get("method"); m != "" && q.Method != m {
continue
}
out = append(out, q)
}
s.mu.Unlock()
writeJSON(w, 200, map[string]any{"requests": out})
}
func (s *Server) clearRequests(w http.ResponseWriter, _ *http.Request) {
s.mu.Lock()
s.requests = nil
s.mu.Unlock()
writeJSON(w, 200, map[string]string{"status": "cleared"})
}
func (s *Server) listDeliveries(w http.ResponseWriter, _ *http.Request) {
s.mu.Lock()
out := append([]Delivery(nil), s.deliveries...)
s.mu.Unlock()
writeJSON(w, 200, map[string]any{"deliveries": out})
}
func (s *Server) dumpDocs(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
out := []Doc{}
for _, d := range s.docs[r.PathValue("doctype")] {
out = append(out, d)
}
s.mu.Unlock()
sort.Slice(out, func(i, j int) bool { return fmt.Sprint(out[i]["name"]) < fmt.Sprint(out[j]["name"]) })
writeJSON(w, 200, map[string]any{"data": out})
}
func (s *Server) resetHandler(w http.ResponseWriter, _ *http.Request) {
s.reset()
writeJSON(w, 200, map[string]string{"status": "reset"})
}
func writeJSON(w http.ResponseWriter, code int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(body)
}
// compare orders numbers numerically and anything else (dates) as strings.
func compare(got, want, op string) bool {
g, err1 := strconv.ParseFloat(got, 64)
w, err2 := strconv.ParseFloat(want, 64)
if err1 == nil && err2 == nil {
if op == "<" {
return g < w
}
return g > w
}
if op == "<" {
return got < want
}
return got > want
}