Files
tenant-registry/internal/erpmock/server.go
T
Sharang ParnerkarandClaude Fable 5.1 7b02cd1c21
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Failing after 14m32s
ci / image (pull_request) Skipped
feat(erp): always-on ERP link, usage events, outbox, CLI licences
M-MIG-7 (ERP/02, decisions 3, 12, 13, 18):

- migration 0004: subscriptions, usage_events, erp_outbox,
  erp_webhook_receipts, licences; tenants.status_changed_at (trigger)
- internal/erp: Frappe REST client (Customer upsert by tenant_id,
  Subscription list, Usage Record, Lead) + webhook signing/verification
- internal/erpmock + cmd/erpmock: ERPNext stand-in for staging —
  /api/resource/{doctype} with token auth, request log, /_mock/fire/*
  triggers that mutate docs and deliver signed webhooks
- POST /v1/internal/erp/webhook (HMAC, idempotent by event id):
  sales_order.submit → subscriptions + entitlements (SKU → product/plan,
  add-on SKUs → limits) + active; sales_invoice.overdue → warning /
  restricted / halted by days overdue; payment_entry.submit → active;
  subscription.cancel → halted
- outbox worker (customer.upsert on tenant create, usage.record,
  lead.create on catalog request) with backoff; reconcile job mirrors
  ERP subscriptions and applies the time-based ladder (trial expiry,
  warning→restricted 14 d, restricted→halted 30 d, halted→archived 30 d)
- POST/GET /v1/usage/events (idempotency_key, batch), GET
  /v1/subscriptions, GET /v1/internal/erp/status, POST
  /v1/internal/erp/reconcile
- CLI licences: Ed25519 signer (LICENCE_SIGNING_KEY), POST /v1/licences
  (entitlement-gated, expiry capped by the entitlement), GET
  /.well-known/licence-keys.json, POST /v1/licences/heartbeat (grace
  ladder, renewal past half-life, revoked), revoke/list
- authn Principal carries tenant-context claims (user tokens scope usage
  and licence calls to their own tenant); authz groups usage(.read)
- tests for every path (both stores), erpmock, erp client, licence pkg;
  openapi.yaml + README updated; Dockerfile ships /erpmock

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-12 09:45:05 +02:00

403 lines
11 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"
"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
}
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",
"CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN",
"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]++
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 "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)
}