Files
tenant-registry/internal/invoiceintake/frappe.go
T
Sharang ParnerkarandClaude Opus 5.5 7857fb4f09
ci / shared (pull_request) Successful in 14s
ci / test (pull_request) Successful in 26m55s
ci / image (pull_request) Skipped
fix(invoiceintake): qualify order_by so Contact lookups by e-mail work
Every intake run failed with "list Contact: HTTP 500: (1052, Column
'creation' in ORDER BY is ambiguous)": the supplier lookup filters on the
child table Contact Email, Frappe joins it, and the bare order_by column
exists in both tables. Nothing sent to invoice@ became a draft (t53).
order_by is now `tab<Doctype>`.`creation`; the fake ERP in the tests
refuses an unqualified one with a child-table filter, like MariaDB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KYcAAeTw22GE9QPzDM8yc4
2026-10-29 12:34:12 +01:00

158 lines
4.3 KiB
Go

package invoiceintake
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
// frappe is the slice of the Frappe REST API the intake uses: list, create.
// It never updates, submits, cancels or deletes a document.
type frappe struct {
base, key, secret string
http *http.Client
}
// httpError is a non-2xx answer. Frappe answers 417 for a ValidationError and
// 409 for a DuplicateEntryError (here: the unique intake_communication).
type httpError struct {
Status int
Message string // Frappe's exception text, shortened; no document content
}
func (e *httpError) Error() string { return fmt.Sprintf("HTTP %d: %s", e.Status, e.Message) }
func messageOf(err error) string {
var he *httpError
if errors.As(err, &he) {
return he.Message
}
return err.Error()
}
func statusOf(err error) int {
var he *httpError
if errors.As(err, &he) {
return he.Status
}
return 0
}
// list returns every matching row, page by page.
func (c *frappe) list(ctx context.Context, doctype string, filters [][]any, fields []string, into any) error {
f, _ := json.Marshal(filters)
fl, _ := json.Marshal(fields)
var all []json.RawMessage
for start := 0; ; start += pageSize {
// Qualified: a filter on a child table (Contact Email) joins it, and
// MariaDB refuses a bare "creation" as ambiguous.
orderBy := fmt.Sprintf("`tab%s`.`creation` asc", doctype)
q := url.Values{"filters": {string(f)}, "fields": {string(fl)}, "order_by": {orderBy},
"limit_start": {fmt.Sprint(start)}, "limit_page_length": {fmt.Sprint(pageSize)}}
var out struct {
Data []json.RawMessage `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(doctype)+"?"+q.Encode(), nil, &out); err != nil {
return fmt.Errorf("list %s: %w", doctype, err)
}
all = append(all, out.Data...)
if len(out.Data) < pageSize {
break
}
}
buf, _ := json.Marshal(all)
return json.Unmarshal(buf, into)
}
const pageSize = 500
func (c *frappe) get(ctx context.Context, doctype, name string, into any) error {
var out struct {
Data json.RawMessage `json:"data"`
}
if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(doctype)+"/"+url.PathEscape(name), nil, &out); err != nil {
return fmt.Errorf("get %s: %w", doctype, err)
}
return json.Unmarshal(out.Data, into)
}
// create inserts a document and returns its name. Documents are created as
// drafts: the service never sets docstatus.
func (c *frappe) create(ctx context.Context, doctype string, doc map[string]any) (string, error) {
if _, ok := doc["docstatus"]; ok {
return "", errors.New("invoiceintake: refusing to set docstatus")
}
var out struct {
Data struct {
Name string `json:"name"`
} `json:"data"`
}
if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(doctype), doc, &out); err != nil {
return "", fmt.Errorf("create %s: %w", doctype, err)
}
return out.Data.Name, nil
}
func (c *frappe) do(ctx context.Context, method, path string, body, into any) error {
var rd io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return err
}
rd = bytes.NewReader(buf)
}
req, err := http.NewRequestWithContext(ctx, method, c.base+path, rd)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "token "+c.key+":"+c.secret)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if resp.StatusCode/100 != 2 {
return &httpError{Status: resp.StatusCode, Message: frappeMessage(raw)}
}
if into == nil {
return nil
}
return json.Unmarshal(raw, into)
}
// frappeMessage pulls the exception line out of a Frappe error body
// ("frappe.exceptions.ValidationError: …"), without the traceback.
func frappeMessage(raw []byte) string {
var e struct {
Exception string `json:"exception"`
ExcType string `json:"exc_type"`
}
_ = json.Unmarshal(raw, &e)
msg := e.Exception
if msg == "" {
msg = e.ExcType
}
if msg == "" {
msg = strings.TrimSpace(string(raw))
}
if i := strings.Index(msg, ": "); i > 0 && strings.HasPrefix(msg, "frappe.") {
msg = msg[i+2:]
}
if len(msg) > 200 {
msg = msg[:200] + "…"
}
return msg
}