Files
sharang 209524e5ac
ci / shared (push) Successful in 14s
ci / test (push) Successful in 22m28s
ci / image (push) Successful in 28s
feat(erp): always-on ERP link, usage events, outbox, CLI licences (#25)
2026-09-12 08:35:13 +00:00

198 lines
6.7 KiB
Go

package erpmock
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"git.breakpilot.com/platform/tenant-registry/internal/erp"
)
// fireReq is the body of POST /_mock/fire/{trigger}. Either customer (ERP
// name) or tenant_id (looked up on the Customer docs) identifies the tenant.
type fireReq struct {
Customer string `json:"customer"`
TenantID string `json:"tenant_id"`
Items []erp.WebhookItem `json:"items"`
DaysOverdue int `json:"days_overdue"`
Subscription string `json:"subscription"`
Invoice string `json:"invoice"`
Amount float64 `json:"amount"`
}
// fire simulates the ERPNext business event AND delivers the webhook the
// live Frappe Webhook configuration (ERP/03) would send.
func (s *Server) fire(w http.ResponseWriter, r *http.Request) {
var in fireReq
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if len(body) > 0 {
if err := json.Unmarshal(body, &in); err != nil {
writeJSON(w, 400, map[string]any{"message": "invalid JSON"})
return
}
}
cust, tenantID := s.resolveCustomer(in.Customer, in.TenantID)
if cust == "" {
writeJSON(w, 404, map[string]any{"message": "customer not found (create it via POST /api/resource/Customer or pass tenant_id of an existing one)"})
return
}
ev := erp.WebhookEvent{Customer: cust, TenantID: tenantID}
s.mu.Lock()
switch r.PathValue("trigger") {
case "sales-order-submit":
if len(in.Items) == 0 {
s.mu.Unlock()
writeJSON(w, 400, map[string]any{"message": "items required"})
return
}
items := make([]any, 0, len(in.Items))
plans := make([]any, 0, len(in.Items))
for _, it := range in.Items {
q := it.Qty
if q <= 0 {
q = 1
}
items = append(items, map[string]any{"item_code": it.ItemCode, "qty": q})
plans = append(plans, map[string]any{"plan": it.ItemCode, "qty": q})
}
so := s.put("Sales Order", Doc{"customer": cust, "tenant_id": tenantID, "docstatus": 1, "status": "To Deliver and Bill",
"transaction_date": today(0), "delivery_date": today(0), "items": items})
sub := s.put("Subscription", Doc{"party_type": "Customer", "party": cust, "status": "Active", "sales_order": so["name"],
"start_date": today(0), "current_invoice_start": today(0), "current_invoice_end": today(30), "plans": plans})
ev.Event, ev.Doctype, ev.Name = erp.EventSalesOrderSubmit, "Sales Order", fmt.Sprint(so["name"])
ev.Modified = fmt.Sprint(so["modified"])
ev.Items = in.Items
ev.Subscription = fmt.Sprint(sub["name"])
case "invoice-overdue":
days := in.DaysOverdue
if days <= 0 {
days = 1
}
inv := s.put("Sales Invoice", Doc{"customer": cust, "tenant_id": tenantID, "docstatus": 1, "status": "Overdue",
"posting_date": today(-days - 14), "due_date": today(-days), "grand_total": in.Amount, "outstanding_amount": in.Amount})
ev.Event, ev.Doctype, ev.Name = erp.EventInvoiceOverdue, "Sales Invoice", fmt.Sprint(inv["name"])
ev.Modified = fmt.Sprint(inv["modified"])
ev.DaysOverdue = days
ev.Invoice = fmt.Sprint(inv["name"])
ev.Amount = in.Amount
case "payment-entry":
if in.Invoice != "" {
if inv, ok := s.docs["Sales Invoice"][in.Invoice]; ok {
inv["status"] = "Paid"
inv["outstanding_amount"] = 0
s.put("Sales Invoice", inv)
}
} else {
for _, inv := range s.docs["Sales Invoice"] {
if inv["customer"] == cust && inv["status"] == "Overdue" {
inv["status"] = "Paid"
inv["outstanding_amount"] = 0
s.put("Sales Invoice", inv)
}
}
}
pe := s.put("Payment Entry", Doc{"party_type": "Customer", "party": cust, "tenant_id": tenantID, "docstatus": 1,
"payment_type": "Receive", "paid_amount": in.Amount, "reference_no": in.Invoice})
ev.Event, ev.Doctype, ev.Name = erp.EventPaymentEntrySubmit, "Payment Entry", fmt.Sprint(pe["name"])
ev.Modified = fmt.Sprint(pe["modified"])
ev.Invoice = in.Invoice
ev.Amount = in.Amount
case "subscription-cancel":
var target Doc
if in.Subscription != "" {
target = s.docs["Subscription"][in.Subscription]
} else {
for _, sub := range s.docs["Subscription"] {
if sub["party"] == cust && sub["status"] != "Cancelled" {
target = sub
break
}
}
}
if target == nil {
s.mu.Unlock()
writeJSON(w, 404, map[string]any{"message": "no active subscription for customer"})
return
}
target["status"] = "Cancelled"
target["cancelation_date"] = today(0)
s.put("Subscription", target)
ev.Event, ev.Doctype, ev.Name = erp.EventSubscriptionCancel, "Subscription", fmt.Sprint(target["name"])
ev.Modified = fmt.Sprint(target["modified"])
ev.Subscription = fmt.Sprint(target["name"])
default:
s.mu.Unlock()
writeJSON(w, 404, map[string]any{"message": "unknown trigger; use sales-order-submit | invoice-overdue | payment-entry | subscription-cancel"})
return
}
s.mu.Unlock()
d := s.deliver(r.Context(), ev)
code := 200
if d.Status == 0 || d.Status >= 400 {
code = 502
}
writeJSON(w, code, map[string]any{"event": ev, "delivery": d})
}
// resolveCustomer maps (customer | tenant_id) → (customer name, tenant_id).
func (s *Server) resolveCustomer(customer, tenantID string) (string, string) {
s.mu.Lock()
defer s.mu.Unlock()
if customer != "" {
if d, ok := s.docs["Customer"][customer]; ok {
return customer, fmt.Sprint(d["tenant_id"])
}
return "", ""
}
for name, d := range s.docs["Customer"] {
if fmt.Sprint(d["tenant_id"]) == tenantID && tenantID != "" {
return name, tenantID
}
}
return "", ""
}
// deliver POSTs the signed webhook to the registry and records the attempt.
func (s *Server) deliver(ctx context.Context, ev erp.WebhookEvent) Delivery {
payload, _ := json.Marshal(ev)
d := Delivery{At: time.Now().UTC(), Event: ev.Event, EventID: uuid.NewString(), Payload: payload}
if s.cfg.WebhookURL == "" {
d.Error = "ERP_WEBHOOK_URL not configured — event simulated, nothing delivered"
} else {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.cfg.WebhookURL, bytes.NewReader(payload))
if err == nil {
req.Header.Set("Content-Type", "application/json")
req.Header.Set(erp.HeaderSignature, erp.Sign(s.cfg.WebhookSecret, payload))
req.Header.Set(erp.HeaderEventID, d.EventID)
req.Header.Set(erp.HeaderEvent, ev.Event)
resp, rerr := s.http.Do(req)
if rerr != nil {
d.Error = rerr.Error()
} else {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()
d.Status = resp.StatusCode
d.Response = strings.TrimSpace(string(b))
}
} else {
d.Error = err.Error()
}
}
s.mu.Lock()
s.deliveries = append(s.deliveries, d)
s.mu.Unlock()
return d
}
func today(offsetDays int) string {
return time.Now().UTC().AddDate(0, 0, offsetDays).Format("2006-01-02")
}