198 lines
6.0 KiB
Go
198 lines
6.0 KiB
Go
// 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
|
|
}
|