Files
tenant-registry/internal/erp/erp.go
T
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

267 lines
8.4 KiB
Go

// Package erp is the ERPNext (Frappe REST) client the registry uses for the
// always-on customer ⇄ ERP link (ERP/02, decision 3 + 12): Customer upsert on
// tenant creation, Subscription reads for the reconcile job, Usage Record
// pushes from the outbox and CRM leads from catalog requests. On staging the
// endpoint is cmd/erpmock (decision 18); prod talks to erp.breakpilot.com.
//
// Authentication is Frappe's `Authorization: token <key>:<secret>`.
package erp
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Doctypes. LeadDoctype is ERPNext v15's "Lead"; the Frappe CRM app names it
// "CRM Lead" — configurable via Config.LeadDoctype.
const (
CustomerDoctype = "Customer"
SubscriptionDoctype = "Subscription"
UsageRecordDoctype = "Usage Record"
SalesInvoiceDoctype = "Sales Invoice"
DefaultLeadDoctype = "Lead"
)
// ErrUnavailable wraps transport / 5xx failures so the outbox retries them.
var ErrUnavailable = errors.New("erp: unavailable")
// ErrNotFound — a GET by name returned 404.
var ErrNotFound = errors.New("erp: not found")
type Config struct {
BaseURL string
APIKey string
APISecret string
LeadDoctype string
Timeout time.Duration
}
type Client struct {
cfg Config
http *http.Client
}
// New returns a client; Enabled() is false when BaseURL is empty.
func New(cfg Config) *Client {
if cfg.Timeout <= 0 {
cfg.Timeout = 10 * time.Second
}
if cfg.LeadDoctype == "" {
cfg.LeadDoctype = DefaultLeadDoctype
}
cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/")
return &Client{cfg: cfg, http: &http.Client{Timeout: cfg.Timeout}}
}
func (c *Client) Enabled() bool { return c != nil && c.cfg.BaseURL != "" }
// Customer — the ERPNext Customer doc subset we read/write. TenantID is the
// custom field `tenant_id` (ERP/03 live configuration).
type Customer struct {
Name string `json:"name,omitempty"`
CustomerName string `json:"customer_name"`
CustomerType string `json:"customer_type,omitempty"`
CustomerGroup string `json:"customer_group,omitempty"`
Territory string `json:"territory,omitempty"`
TenantID string `json:"tenant_id"`
TenantSlug string `json:"tenant_slug,omitempty"`
}
// Subscription — Subscription doc subset. Plans carry the SKU (Subscription
// Plan name == Item code == platform SKU) and the quantity (seats/runners).
type Subscription struct {
Name string `json:"name"`
Party string `json:"party"`
Status string `json:"status"` // Trialling | Active | Past Due Date | Unpaid | Cancelled | Completed
SalesOrder string `json:"sales_order,omitempty"`
StartDate string `json:"start_date,omitempty"`
EndDate string `json:"end_date,omitempty"`
Plans []SubscriptionPlan `json:"plans"`
}
type SubscriptionPlan struct {
Plan string `json:"plan"`
Qty float64 `json:"qty"`
}
// UsageRecord — one metered fact (custom doctype, ERP/02 §usage).
type UsageRecord struct {
Customer string `json:"customer"`
TenantID string `json:"tenant_id"`
Product string `json:"product"`
Metric string `json:"metric"`
Qty float64 `json:"qty"`
OccurredAt string `json:"occurred_at"`
IdempotencyKey string `json:"idempotency_key"`
}
// Lead — a CRM lead from a catalog request.
type Lead struct {
LeadName string `json:"lead_name"`
CompanyName string `json:"company_name,omitempty"`
EmailID string `json:"email_id,omitempty"`
Source string `json:"source,omitempty"`
Notes string `json:"notes,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
Product string `json:"requested_product,omitempty"`
}
// FindCustomerByTenant returns the Customer whose tenant_id equals tenantID
// ("" when none).
func (c *Client) FindCustomerByTenant(ctx context.Context, tenantID string) (*Customer, error) {
filters := fmt.Sprintf(`[["tenant_id","=",%q]]`, tenantID)
var out struct {
Data []Customer `json:"data"`
}
q := url.Values{"filters": {filters}, "fields": {`["name","customer_name","tenant_id","tenant_slug"]`}, "limit_page_length": {"1"}}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(CustomerDoctype)+"?"+q.Encode(), nil, &out); err != nil {
return nil, err
}
if len(out.Data) == 0 {
return nil, nil
}
return &out.Data[0], nil
}
// UpsertCustomer creates the Customer for a tenant unless one already carries
// its tenant_id. Returns the ERP customer name (the id the registry stores).
func (c *Client) UpsertCustomer(ctx context.Context, in Customer) (string, error) {
if in.TenantID == "" {
return "", errors.New("erp: tenant_id required")
}
if existing, err := c.FindCustomerByTenant(ctx, in.TenantID); err != nil {
return "", err
} else if existing != nil {
return existing.Name, nil
}
if in.CustomerType == "" {
in.CustomerType = "Company"
}
if in.CustomerGroup == "" {
in.CustomerGroup = "Commercial"
}
if in.Territory == "" {
in.Territory = "All Territories"
}
var out struct {
Data Customer `json:"data"`
}
if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(CustomerDoctype), in, &out); err != nil {
return "", err
}
return out.Data.Name, nil
}
// ListSubscriptions returns every Subscription of the customer (any status).
func (c *Client) ListSubscriptions(ctx context.Context, customer string) ([]Subscription, error) {
filters := fmt.Sprintf(`[["party","=",%q]]`, customer)
var names struct {
Data []struct {
Name string `json:"name"`
} `json:"data"`
}
q := url.Values{"filters": {filters}, "fields": {`["name"]`}, "limit_page_length": {"200"}}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(SubscriptionDoctype)+"?"+q.Encode(), nil, &names); err != nil {
return nil, err
}
out := make([]Subscription, 0, len(names.Data))
for _, n := range names.Data {
var doc struct {
Data Subscription `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(SubscriptionDoctype)+"/"+url.PathEscape(n.Name), nil, &doc); err != nil {
return nil, err
}
out = append(out, doc.Data)
}
return out, nil
}
// CreateUsageRecord pushes one usage record (idempotency is the registry's
// job: it only sends each event once, via the outbox).
func (c *Client) CreateUsageRecord(ctx context.Context, rec UsageRecord) (string, error) {
var out struct {
Data struct {
Name string `json:"name"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(UsageRecordDoctype), rec, &out); err != nil {
return "", err
}
return out.Data.Name, nil
}
// CreateLead files a CRM lead.
func (c *Client) CreateLead(ctx context.Context, lead Lead) (string, error) {
var out struct {
Data struct {
Name string `json:"name"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(c.cfg.LeadDoctype), lead, &out); err != nil {
return "", err
}
return out.Data.Name, nil
}
func (c *Client) do(ctx context.Context, method, path string, body any, into any) error {
if !c.Enabled() {
return fmt.Errorf("%w: ERP_BASE_URL not configured", ErrUnavailable)
}
var reader io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return err
}
reader = bytes.NewReader(buf)
}
req, err := http.NewRequestWithContext(ctx, method, c.cfg.BaseURL+path, reader)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.cfg.APIKey != "" {
req.Header.Set("Authorization", "token "+c.cfg.APIKey+":"+c.cfg.APISecret)
}
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("%w: %v", ErrUnavailable, err)
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
switch {
case resp.StatusCode == http.StatusNotFound:
return ErrNotFound
case resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests:
return fmt.Errorf("%w: %s %s → %d %s", ErrUnavailable, method, path, resp.StatusCode, truncate(raw))
case resp.StatusCode/100 != 2:
return fmt.Errorf("erp: %s %s → %d %s", method, path, resp.StatusCode, truncate(raw))
}
if into != nil && len(raw) > 0 {
if err := json.Unmarshal(raw, into); err != nil {
return fmt.Errorf("erp: decode %s %s: %w", method, path, err)
}
}
return nil
}
func truncate(b []byte) string {
s := strings.TrimSpace(string(b))
if len(s) > 200 {
return s[:200] + "…"
}
return s
}