feat(erp): erpsetup for live ERPNext, reserved tenant slugs (#32)
This commit was merged in pull request #32.
This commit is contained in:
1 parent
13da983d1e
commit
ceeff16f26
8 files changed
+587
-2
No files matched your search
@@ -83,7 +83,7 @@ jobs:
|
||||
# own test binary — and including it triggers a covdata-tool error
|
||||
# on packages with no _test.go files. -coverpkg makes the server's
|
||||
# exercise of store/* count toward coverage.
|
||||
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/...
|
||||
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/...
|
||||
|
||||
- name: coverage gate
|
||||
run: |
|
||||
|
||||
+3
-1
@@ -11,13 +11,15 @@ RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/tenant-registry ./cmd/server && \
|
||||
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/migrate ./cmd/migrate && \
|
||||
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/erpmock ./cmd/erpmock
|
||||
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/erpmock ./cmd/erpmock && \
|
||||
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/erpsetup ./cmd/erpsetup
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
WORKDIR /
|
||||
COPY --from=build /out/tenant-registry /tenant-registry
|
||||
COPY --from=build /out/migrate /migrate
|
||||
COPY --from=build /out/erpmock /erpmock
|
||||
COPY --from=build /out/erpsetup /erpsetup
|
||||
USER nonroot:nonroot
|
||||
EXPOSE 8090
|
||||
# CMD (not ENTRYPOINT) so orca's `cmd` can select /erpmock or /migrate in the
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// erpsetup — applies the live-ERPNext configuration the tenant-registry needs
|
||||
// (custom fields, the Usage Record doctype, the Frappe Webhooks). Idempotent;
|
||||
// run with -dry-run first. It never submits, cancels or deletes ERP documents.
|
||||
//
|
||||
// ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… \
|
||||
// ERP_WEBHOOK_SECRET=… erpsetup -webhook-url https://registry.breakpilot.com/v1/internal/erp/webhook -dry-run
|
||||
//
|
||||
// The API user needs System Manager for this run (it creates a DocType and
|
||||
// Webhooks); the registry's day-to-day key can then have a narrower role.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/erpsetup"
|
||||
)
|
||||
|
||||
func main() {
|
||||
dry := flag.Bool("dry-run", false, "report what would be created, change nothing")
|
||||
hook := flag.String("webhook-url", "", "registry webhook receiver, e.g. https://registry.breakpilot.com/v1/internal/erp/webhook")
|
||||
lead := flag.String("lead-doctype", envOr("ERP_LEAD_DOCTYPE", "Lead"), `"Lead" (ERPNext) or "CRM Lead" (Frappe CRM)`)
|
||||
flag.Parse()
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
steps, err := erpsetup.Run(ctx, erpsetup.Config{
|
||||
BaseURL: os.Getenv("ERP_BASE_URL"),
|
||||
APIKey: os.Getenv("ERP_API_KEY"),
|
||||
APISecret: os.Getenv("ERP_API_SECRET"),
|
||||
WebhookURL: *hook,
|
||||
WebhookSecret: os.Getenv("ERP_WEBHOOK_SECRET"),
|
||||
LeadDoctype: *lead,
|
||||
DryRun: *dry,
|
||||
Log: func(f string, a ...any) { fmt.Printf(f+"\n", a...) },
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Printf("%d steps, done%s\n", len(steps), map[bool]string{true: " (dry run, nothing changed)", false: ""}[*dry])
|
||||
}
|
||||
|
||||
func envOr(k, d string) string {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// 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, and the Frappe Webhooks that drive
|
||||
// the tenant ladder. 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
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 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"]`}, "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"`
|
||||
} `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+`"`) {
|
||||
r.record(what, "exists ("+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
|
||||
}
|
||||
|
||||
func truncate(b []byte) string {
|
||||
s := strings.TrimSpace(string(b))
|
||||
if len(s) > 300 {
|
||||
return s[:300] + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package erpsetup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeFrappe keeps named docs per doctype and a list of webhooks.
|
||||
type fakeFrappe struct {
|
||||
mu sync.Mutex
|
||||
docs map[string]map[string]bool
|
||||
webhooks []map[string]any
|
||||
posts int
|
||||
auth string
|
||||
}
|
||||
|
||||
func newFake() *fakeFrappe { return &fakeFrappe{docs: map[string]map[string]bool{}} }
|
||||
|
||||
func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.auth = r.Header.Get("Authorization")
|
||||
if r.Header.Get("Authorization") != "token k:s" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
rest := strings.TrimPrefix(r.URL.Path, "/api/resource/")
|
||||
parts := strings.SplitN(rest, "/", 2)
|
||||
doctype, _ := url.PathUnescape(parts[0])
|
||||
switch {
|
||||
case doctype == "Webhook" && r.Method == http.MethodGet:
|
||||
out := []map[string]any{}
|
||||
for _, wh := range f.webhooks {
|
||||
out = append(out, map[string]any{"name": wh["name"], "webhook_json": wh["webhook_json"]})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": out})
|
||||
case doctype == "Webhook" && r.Method == http.MethodPost:
|
||||
var doc map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&doc)
|
||||
doc["name"] = "HOOK-" + string(rune('A'+len(f.webhooks)))
|
||||
f.webhooks = append(f.webhooks, doc)
|
||||
f.posts++
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": doc})
|
||||
case r.Method == http.MethodGet && len(parts) == 2:
|
||||
name, _ := url.PathUnescape(parts[1])
|
||||
if f.docs[doctype][name] {
|
||||
_, _ = io.WriteString(w, `{"data":{}}`)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
case r.Method == http.MethodPost:
|
||||
var doc map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&doc)
|
||||
if f.docs[doctype] == nil {
|
||||
f.docs[doctype] = map[string]bool{}
|
||||
}
|
||||
f.docs[doctype][doc["name"].(string)] = true
|
||||
f.posts++
|
||||
_, _ = io.WriteString(w, `{"data":{}}`)
|
||||
default:
|
||||
w.WriteHeader(http.StatusTeapot)
|
||||
}
|
||||
}
|
||||
|
||||
func cfg(url string) Config {
|
||||
return Config{BaseURL: url + "/", APIKey: "k", APISecret: "s", WebhookURL: "https://registry/v1/internal/erp/webhook", WebhookSecret: "whs"}
|
||||
}
|
||||
|
||||
func TestRunCreatesThenIsIdempotent(t *testing.T) {
|
||||
f := newFake()
|
||||
srv := httptest.NewServer(f)
|
||||
defer srv.Close()
|
||||
|
||||
steps, err := Run(context.Background(), cfg(srv.URL))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(steps) != 9 || f.posts != 9 {
|
||||
t.Fatalf("first run: %d steps, %d creates; want 9/9: %+v", len(steps), f.posts, steps)
|
||||
}
|
||||
for _, s := range steps {
|
||||
if s.Result != "created" {
|
||||
t.Errorf("%s: %s", s.What, s.Result)
|
||||
}
|
||||
}
|
||||
hook := f.webhooks[0]
|
||||
if hook["enable_security"] != float64(1) || hook["webhook_secret"] != "whs" || hook["request_url"] != "https://registry/v1/internal/erp/webhook" {
|
||||
t.Errorf("webhook security/url not set: %v", hook)
|
||||
}
|
||||
|
||||
steps, err = Run(context.Background(), cfg(srv.URL))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.posts != 9 {
|
||||
t.Fatalf("second run created %d more docs", f.posts-9)
|
||||
}
|
||||
for _, s := range steps {
|
||||
if !strings.HasPrefix(s.Result, "exists") {
|
||||
t.Errorf("second run %s: %s", s.What, s.Result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDryRunChangesNothing(t *testing.T) {
|
||||
f := newFake()
|
||||
srv := httptest.NewServer(f)
|
||||
defer srv.Close()
|
||||
c := cfg(srv.URL)
|
||||
c.DryRun = true
|
||||
var logged int
|
||||
c.Log = func(string, ...any) { logged++ }
|
||||
steps, err := Run(context.Background(), c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.posts != 0 || logged != len(steps) {
|
||||
t.Fatalf("dry run posted %d docs, logged %d of %d", f.posts, logged, len(steps))
|
||||
}
|
||||
for _, s := range steps {
|
||||
if s.Result != "would create" {
|
||||
t.Errorf("%s: %s", s.What, s.Result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeadDoctypeIsConfigurable(t *testing.T) {
|
||||
f := newFake()
|
||||
srv := httptest.NewServer(f)
|
||||
defer srv.Close()
|
||||
c := cfg(srv.URL)
|
||||
c.LeadDoctype = "CRM Lead"
|
||||
if _, err := Run(context.Background(), c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.docs["Custom Field"]["CRM Lead-tenant_id"] {
|
||||
t.Fatalf("no CRM Lead field: %v", f.docs["Custom Field"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequiredConfigAndAuthErrors(t *testing.T) {
|
||||
if _, err := Run(context.Background(), Config{}); err == nil {
|
||||
t.Fatal("empty config accepted")
|
||||
}
|
||||
if _, err := Run(context.Background(), Config{BaseURL: "x", APIKey: "k", APISecret: "s"}); err == nil {
|
||||
t.Fatal("missing webhook config accepted")
|
||||
}
|
||||
srv := httptest.NewServer(newFake())
|
||||
defer srv.Close()
|
||||
c := cfg(srv.URL)
|
||||
c.APISecret = "wrong"
|
||||
if _, err := Run(context.Background(), c); err == nil || !strings.Contains(err.Error(), "API key") {
|
||||
t.Fatalf("want an auth error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnexpectedStatusStops(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = io.WriteString(w, strings.Repeat("x", 400))
|
||||
}))
|
||||
defer srv.Close()
|
||||
if _, err := Run(context.Background(), cfg(srv.URL)); err == nil {
|
||||
t.Fatal("500 accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebhookBodiesAreValidJSONShapes(t *testing.T) {
|
||||
for _, w := range webhooks("u", "s") {
|
||||
if !strings.Contains(w.JSON, `"event":"`+w.Event+`"`) || !strings.Contains(w.JSON, `"modified":"{{ doc.modified }}"`) {
|
||||
t.Errorf("%s: template lacks event or modified: %s", w.Event, w.JSON)
|
||||
}
|
||||
if w.URL != "u" || w.Secret != "s" {
|
||||
t.Errorf("%s: url/secret not filled", w.Event)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package erpsetup
|
||||
|
||||
// What the registry expects in ERPNext. Keep in step with internal/erp
|
||||
// (Customer.tenant_id, Lead fields, UsageRecord) and the webhook receiver
|
||||
// (internal/server/erp.go, erp.WebhookEvent).
|
||||
|
||||
func customField(dt, fieldname, label, fieldtype, after string, unique bool) map[string]any {
|
||||
f := map[string]any{
|
||||
"doctype": "Custom Field",
|
||||
"name": dt + "-" + fieldname,
|
||||
"dt": dt,
|
||||
"fieldname": fieldname,
|
||||
"label": label,
|
||||
"fieldtype": fieldtype,
|
||||
"insert_after": after,
|
||||
"no_copy": 1,
|
||||
"description": "Set by the BreakPilot tenant-registry. Do not edit.",
|
||||
}
|
||||
if unique {
|
||||
f["unique"] = 1
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func customFields(leadDoctype string) []map[string]any {
|
||||
return []map[string]any{
|
||||
customField("Customer", "tenant_id", "Tenant ID", "Data", "customer_name", true),
|
||||
customField("Customer", "tenant_slug", "Tenant slug", "Data", "tenant_id", false),
|
||||
customField(leadDoctype, "tenant_id", "Tenant ID", "Data", "company_name", false),
|
||||
customField(leadDoctype, "requested_product", "Requested product", "Data", "tenant_id", false),
|
||||
}
|
||||
}
|
||||
|
||||
func usageRecordDoctype() map[string]any {
|
||||
field := func(name, label, typ string, extra map[string]any) map[string]any {
|
||||
f := map[string]any{"fieldname": name, "label": label, "fieldtype": typ, "in_list_view": 1}
|
||||
for k, v := range extra {
|
||||
f[k] = v
|
||||
}
|
||||
return f
|
||||
}
|
||||
return map[string]any{
|
||||
"doctype": "DocType",
|
||||
"name": "Usage Record",
|
||||
"module": "Selling",
|
||||
"custom": 1,
|
||||
"autoname": "hash",
|
||||
"track_changes": 0,
|
||||
"description": "Metered usage pushed by the BreakPilot tenant-registry (ERP/02).",
|
||||
"fields": []map[string]any{
|
||||
field("customer", "Customer", "Link", map[string]any{"options": "Customer", "reqd": 1}),
|
||||
field("tenant_id", "Tenant ID", "Data", map[string]any{"reqd": 1}),
|
||||
field("product", "Product", "Data", map[string]any{"reqd": 1}),
|
||||
field("metric", "Metric", "Data", map[string]any{"reqd": 1}),
|
||||
field("qty", "Quantity", "Float", map[string]any{"reqd": 1}),
|
||||
field("occurred_at", "Occurred at", "Datetime", map[string]any{"reqd": 1}),
|
||||
field("idempotency_key", "Idempotency key", "Data", map[string]any{"reqd": 1, "unique": 1, "in_list_view": 0}),
|
||||
},
|
||||
"permissions": []map[string]any{
|
||||
{"role": "System Manager", "read": 1, "write": 1, "create": 1, "delete": 1, "report": 1, "export": 1},
|
||||
{"role": "Accounts Manager", "read": 1, "report": 1, "export": 1},
|
||||
{"role": "Sales Manager", "read": 1, "report": 1, "export": 1},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type webhook struct {
|
||||
Doctype string
|
||||
DocEvent string
|
||||
Condition string
|
||||
Event string // the registry event the JSON carries
|
||||
JSON string // Jinja template of the body
|
||||
URL string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (w webhook) doc() map[string]any {
|
||||
return map[string]any{
|
||||
"doctype": "Webhook",
|
||||
"webhook_doctype": w.Doctype,
|
||||
"webhook_docevent": w.DocEvent,
|
||||
"condition": w.Condition,
|
||||
"request_url": w.URL,
|
||||
"request_method": "POST",
|
||||
"request_structure": "JSON",
|
||||
"webhook_json": w.JSON,
|
||||
"enable_security": 1,
|
||||
"webhook_secret": w.Secret,
|
||||
"enabled": 1,
|
||||
"webhook_headers": []map[string]any{{"key": "Content-Type", "value": "application/json"}},
|
||||
}
|
||||
}
|
||||
|
||||
// The body templates render erp.WebhookEvent. "modified" makes the receiver's
|
||||
// fallback event id unique per document version (live Frappe sends no
|
||||
// X-Frappe-Event-Id).
|
||||
func webhooks(url, secret string) []webhook {
|
||||
ws := []webhook{
|
||||
{
|
||||
Doctype: "Sales Order", DocEvent: "on_submit", Event: "sales_order.submit",
|
||||
JSON: `{"event":"sales_order.submit","doctype":"Sales Order","name":"{{ doc.name }}","modified":"{{ doc.modified }}","customer":"{{ doc.customer }}","items":[{% for i in doc.items %}{"item_code":"{{ i.item_code }}","qty":{{ i.qty }}}{% if not loop.last %},{% endif %}{% endfor %}]}`,
|
||||
},
|
||||
{
|
||||
Doctype: "Sales Invoice", DocEvent: "on_update_after_submit", Event: "sales_invoice.overdue",
|
||||
Condition: `doc.status == "Overdue"`,
|
||||
JSON: `{"event":"sales_invoice.overdue","doctype":"Sales Invoice","name":"{{ doc.name }}","modified":"{{ doc.modified }}","customer":"{{ doc.customer }}","invoice":"{{ doc.name }}","days_overdue":{{ frappe.utils.date_diff(frappe.utils.nowdate(), doc.due_date) }}}`,
|
||||
},
|
||||
{
|
||||
Doctype: "Payment Entry", DocEvent: "on_submit", Event: "payment_entry.submit",
|
||||
Condition: `doc.party_type == "Customer"`,
|
||||
JSON: `{"event":"payment_entry.submit","doctype":"Payment Entry","name":"{{ doc.name }}","modified":"{{ doc.modified }}","customer":"{{ doc.party }}","amount":{{ doc.paid_amount }}}`,
|
||||
},
|
||||
{
|
||||
Doctype: "Subscription", DocEvent: "on_update", Event: "subscription.cancel",
|
||||
Condition: `doc.status == "Cancelled"`,
|
||||
JSON: `{"event":"subscription.cancel","doctype":"Subscription","name":"{{ doc.name }}","modified":"{{ doc.modified }}","customer":"{{ doc.party }}","subscription":"{{ doc.name }}"}`,
|
||||
},
|
||||
}
|
||||
for i := range ws {
|
||||
ws[i].URL, ws[i].Secret = url, secret
|
||||
}
|
||||
return ws
|
||||
}
|
||||
@@ -17,6 +17,17 @@ import (
|
||||
// at the API boundary rather than waiting for the DB to do it.
|
||||
var slugRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$`)
|
||||
|
||||
// reservedSlugs are paths the portal or the platform serves itself
|
||||
// (app.breakpilot.com/<slug>): a tenant with one of these names would be
|
||||
// unreachable or would shadow a route. Mirrors the portal's src/lib/signup.ts,
|
||||
// except "demo", which the sales demo tenant itself uses.
|
||||
var reservedSlugs = map[string]bool{
|
||||
"admin": true, "api": true, "app": true, "auth": true, "billing": true,
|
||||
"docs": true, "help": true, "install": true, "login": true, "logout": true,
|
||||
"portal": true, "signin": true, "signout": true, "signup": true, "start": true,
|
||||
"static": true, "status": true, "support": true, "www": true, "breakpilot": true,
|
||||
}
|
||||
|
||||
type createTenantReq struct {
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
@@ -46,6 +57,10 @@ func (s *Server) createTenant(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$")
|
||||
return
|
||||
}
|
||||
if reservedSlugs[in.Slug] {
|
||||
writeError(w, http.StatusBadRequest, "reserved_slug", "this slug is reserved for a platform path")
|
||||
return
|
||||
}
|
||||
if in.Name == "" || len(in.Name) > 255 {
|
||||
writeError(w, http.StatusBadRequest, "invalid_name", "name must be 1..255 chars")
|
||||
return
|
||||
|
||||
@@ -2,6 +2,7 @@ package server_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -46,6 +47,17 @@ func TestCreateTenant_invalidSlug(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestCreateTenant_reservedSlug(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
resp, body := h.do("POST", "/v1/tenants", map[string]any{
|
||||
"slug": "admin", "name": "Shadow",
|
||||
})
|
||||
if resp.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "reserved_slug") {
|
||||
t.Fatalf("status = %d body = %s", resp.StatusCode, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCreateTenant_duplicateSlugConflict(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
// 'acme' is pre-seeded
|
||||
|
||||
Reference in new issue
Block a user