Files
tenant-registry/internal/erpmock/server.go
T
sharang cf23f65ce8
ci / shared (push) Successful in 12s
ci / test (push) Successful in 8m10s
ci / image (push) Successful in 58s
feat(pruefwerk): Monitor plan (CRA-CSA-CLD-MON) (#152)
2026-11-30 08:18:01 +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-CSA-CLD-MON",
"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
}