feat(invoiceintake): invoice@ mails become draft Eingangsrechnungen #82

Merged
sharang merged 3 commits from feat/invoice-intake into main 2026-10-20 08:15:33 +00:00
9 changed files with 1288 additions and 4 deletions

No files matched your search

+4 -2
View File
@@ -15,7 +15,8 @@ ARG COMMIT=
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w -X git.breakpilot.com/platform/tenant-registry/internal/buildinfo.Version=${VERSION} -X git.breakpilot.com/platform/tenant-registry/internal/buildinfo.Commit=${COMMIT}" -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/erpsetup ./cmd/erpsetup
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/erpsetup ./cmd/erpsetup && \
CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/invoiceintake ./cmd/invoiceintake
FROM gcr.io/distroless/static-debian12:nonroot
WORKDIR /
@@ -23,8 +24,9 @@ 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
COPY --from=build /out/invoiceintake /invoiceintake
USER nonroot:nonroot
EXPOSE 8090
# CMD (not ENTRYPOINT) so orca's `cmd` can select /erpmock or /migrate in the
# CMD (not ENTRYPOINT) so orca's `cmd` can select /erpmock, /migrate or /invoiceintake in the
# same image. The server applies migrations itself with MIGRATE_ON_START=true.
CMD ["/tenant-registry"]
+123
View File
@@ -0,0 +1,123 @@
// invoiceintake — turns the mails of ERPNext's Email Account
// "Eingangsrechnung" (invoice@) into drafts: E Invoice Imports for
// e-invoices, draft Purchase Invoices with the original attached for other
// PDFs, ToDos for everything it cannot place (internal/invoiceintake). It
// never submits anything. erpsetup must have run first (custom field
// intake_communication, placeholder item EINGANGSRECHNUNG).
//
// ERP_BASE_URL=https://erp.breakpilot.com ERP_API_KEY=… ERP_API_SECRET=… \
// invoiceintake -once -dry-run
//
// Without -once it runs every INTAKE_INTERVAL (default 10m). The API user
// needs the roles Accounts User (Purchase Invoice drafts), Purchase User
// (E Invoice Import) and Inbox User, with the Email Account under its
// User Emails so it can read the mails.
package main
import (
"context"
"flag"
"fmt"
"log/slog"
"os"
"os/signal"
"strings"
"syscall"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/invoiceintake"
)
func main() {
once := flag.Bool("once", false, "one run, then exit")
dry := flag.Bool("dry-run", false, "report what would be created, create nothing (implies -once)")
flag.Parse()
if *dry {
*once = true
}
logf := func(f string, a ...any) { fmt.Printf(f+"\n", a...) }
if !*once {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo})))
logf = func(f string, a ...any) { slog.Info(fmt.Sprintf(f, a...)) }
}
since := time.Time{}
if s := os.Getenv("INTAKE_SINCE"); s != "" {
t, err := time.Parse("2006-01-02", s)
if err != nil {
fail(*once, "INTAKE_SINCE: %v", err)
}
since = t
}
interval := 10 * time.Minute
if s := os.Getenv("INTAKE_INTERVAL"); s != "" {
d, err := time.ParseDuration(s)
if err != nil || d < time.Minute {
fail(*once, "INTAKE_INTERVAL: want a duration of at least 1m, got %q", s)
}
interval = d
}
in, err := invoiceintake.New(invoiceintake.Config{
BaseURL: os.Getenv("ERP_BASE_URL"),
APIKey: os.Getenv("ERP_API_KEY"),
APISecret: os.Getenv("ERP_API_SECRET"),
EmailAccount: envOr("INTAKE_EMAIL_ACCOUNT", "Eingangsrechnung"),
Company: envOr("INTAKE_COMPANY", "Breakpilot GmbH"),
Since: since,
AssignTo: os.Getenv("INTAKE_ASSIGN_TO"),
OwnDomains: strings.Fields(strings.ReplaceAll(envOr("INTAKE_OWN_DOMAINS", "breakpilot.com"), ",", " ")),
DryRun: *dry,
Log: logf,
})
if err != nil {
fail(*once, "%v", err)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
for {
res, err := in.Run(ctx)
counts := map[string]int{}
for _, r := range res {
counts[r.Outcome]++
}
if err != nil {
if *once {
fail(true, "%v", err)
}
slog.Error("intake run failed", "err", err, "handled", len(res))
} else if *once {
fmt.Printf("%d mails handled: %d e-invoice imports, %d draft purchase invoices, %d todos%s\n",
len(res), counts[invoiceintake.EInvoice], counts[invoiceintake.Draft], counts[invoiceintake.Review],
map[bool]string{true: " (dry run, nothing created)", false: ""}[*dry])
} else if len(res) > 0 {
slog.Info("intake run", "handled", len(res), "einvoice", counts[invoiceintake.EInvoice],
"draft", counts[invoiceintake.Draft], "todo", counts[invoiceintake.Review])
}
if *once {
return
}
select {
case <-ctx.Done():
return
case <-time.After(interval):
}
}
}
func fail(plain bool, f string, a ...any) {
if plain {
fmt.Fprintf(os.Stderr, f+"\n", a...)
} else {
slog.Error(fmt.Sprintf(f, a...))
}
os.Exit(1)
}
func envOr(k, d string) string {
if v := os.Getenv(k); v != "" {
return v
}
return d
}
+4
View File
@@ -172,6 +172,10 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) {
return r.steps, err
}
}
// Incoming invoices: what cmd/invoiceintake writes into (intake.go).
if err := r.intake(ctx); 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
+5 -2
View File
@@ -25,11 +25,14 @@ type fakeFrappe struct {
}
// newFake starts with what every ERPNext site has: the company (with its
// abbreviation) and the SKR04 deferred revenue account.
// abbreviation) and the SKR04 accounts erpsetup looks up (3900, 6300).
func newFake() *fakeFrappe {
return &fakeFrappe{docs: map[string]map[string]map[string]any{
"Company": {companyName: {"name": companyName, "company_name": companyName, "abbr": "BG"}},
"Account": {"3900 - Passive Rechnungsabgrenzung - BG": {"name": "3900 - Passive Rechnungsabgrenzung - BG", "account_number": "3900", "company": companyName}},
"Account": {
"3900 - Passive Rechnungsabgrenzung - BG": {"name": "3900 - Passive Rechnungsabgrenzung - BG", "account_number": "3900", "company": companyName},
"6300 - Sonstige betriebliche Aufwendungen - BG": {"name": "6300 - Sonstige betriebliche Aufwendungen - BG", "account_number": "6300", "company": companyName},
},
}}
}
+135
View File
@@ -0,0 +1,135 @@
package erpsetup
// Incoming invoices (orca-infra #121, Collectives ERP/08): the mailbox
// invoice@ is read by ERPNext's Email Account "Eingangsrechnung"; Strato
// forwards the originals to DATEV Unternehmen Online. cmd/invoiceintake turns
// each received mail into a draft: an E Invoice Import for e-invoices, else a
// draft Purchase Invoice with the original attached. What it needs here:
// - intake_communication on both doctypes: the mail a draft came from. It is
// unique, so a mail never yields two drafts, and it is the service's only
// memory of what it has done.
// - a placeholder purchase item: a Purchase Invoice cannot be saved without
// a line, and the amounts are taken from the attachment by the person who
// checks the draft. Its default expense account is SKR04 6300 (Sonstige
// betriebliche Aufwendungen), changed per invoice when checking.
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
const (
intakeItem = "EINGANGSRECHNUNG"
intakeItemGroup = "Eingangsrechnungen"
intakeUOM = "Stück"
intakeAccountNum = "6300"
)
func intakeFields() []map[string]any {
// A Link, so the draft leads to the mail. Frappe stores an empty unique
// field as NULL, so hand-made invoices without a mail don't collide.
pi := customField("Purchase Invoice", "intake_communication", "Aus E-Mail", "Link", "bill_date", true)
ei := customField("E Invoice Import", "intake_communication", "Aus E-Mail", "Link", "einvoice", true)
for _, f := range []map[string]any{pi, ei} {
f["options"] = "Communication"
f["read_only"] = 1
f["description"] = "Vom Rechnungseingang gesetzt: die E-Mail (Communication), aus der dieser Entwurf stammt. Nicht ändern."
}
return []map[string]any{pi, ei}
}
func intakeItemDoc() map[string]any {
return map[string]any{
"doctype": "Item", "name": intakeItem, "item_code": intakeItem,
"item_name": "Eingangsrechnung (zu prüfen)",
"description": "Platzhalter des Rechnungseingangs. Beim Prüfen durch die Positionen der Rechnung ersetzen oder Betrag, Konto und Steuer anpassen.",
"item_group": intakeItemGroup, "stock_uom": intakeUOM,
"is_stock_item": 0, "is_sales_item": 0, "is_purchase_item": 1, "include_item_in_manufacturing": 0,
}
}
func (r *runner) intake(ctx context.Context) error {
for _, f := range intakeFields() {
if err := r.ensure(ctx, "Custom Field", f["name"].(string), fmt.Sprintf("custom field %s.%s", f["dt"], f["fieldname"]), f); err != nil {
return err
}
}
if err := r.ensure(ctx, "UOM", intakeUOM, "unit "+intakeUOM,
map[string]any{"doctype": "UOM", "name": intakeUOM, "uom_name": intakeUOM, "must_be_whole_number": 1}); err != nil {
return err
}
if err := r.ensure(ctx, "Item Group", intakeItemGroup, "item group "+intakeItemGroup,
map[string]any{"doctype": "Item Group", "name": intakeItemGroup, "item_group_name": intakeItemGroup, "parent_item_group": "All Item Groups", "is_group": 0}); err != nil {
return err
}
if err := r.ensure(ctx, "Item", intakeItem, "item "+intakeItem+" (placeholder for incoming invoices)", intakeItemDoc()); err != nil {
return err
}
account, err := r.findAccount(ctx, intakeAccountNum)
if err != nil {
return err
}
if account == "" {
// Without it ERPNext refuses to save the draft ("Expense account is
// mandatory"), unless the company has a default expense account.
r.record("item "+intakeItem+" expense account "+intakeAccountNum, "missing (not created)")
return nil
}
return r.ensureItemExpenseAccount(ctx, account)
}
// ensureItemExpenseAccount sets the company's Item Defaults row of the
// placeholder item to the expense account; other rows and fields are kept.
func (r *runner) ensureItemExpenseAccount(ctx context.Context, account string) error {
what := "item " + intakeItem + " expense account " + intakeAccountNum
path := "/api/resource/Item/" + url.PathEscape(intakeItem)
status, body, err := r.call(ctx, http.MethodGet, path, nil)
if err != nil {
return err
}
if status == http.StatusNotFound && r.cfg.DryRun {
r.record(what, "would update") // the item is created by the step before
return nil
}
if status != http.StatusOK {
return fmt.Errorf("erpsetup: GET Item %q: HTTP %d", intakeItem, status)
}
var cur struct {
Data struct {
ItemDefaults []map[string]any `json:"item_defaults"`
} `json:"data"`
}
_ = json.Unmarshal(body, &cur)
rows, found, changed := cur.Data.ItemDefaults, false, false
for _, row := range rows {
if row["company"] == companyName {
found = true
if row["expense_account"] != account {
row["expense_account"], changed = account, true
}
}
}
if !found {
rows, changed = append(rows, map[string]any{"company": companyName, "expense_account": account}), true
}
if !changed {
r.record(what, "exists")
return nil
}
if r.cfg.DryRun {
r.record(what, "would update")
return nil
}
status, body, err = r.call(ctx, http.MethodPut, path, map[string]any{"item_defaults": rows})
if err != nil {
return err
}
if status/100 != 2 {
return fmt.Errorf("erpsetup: update %s: HTTP %d %s", what, status, truncate(body))
}
r.record(what, "updated")
return nil
}
+51
View File
@@ -0,0 +1,51 @@
package erpsetup
import (
"context"
"fmt"
"net/http/httptest"
"testing"
)
func TestIntakeSetup(t *testing.T) {
f := newFake()
srv := httptest.NewServer(f)
defer srv.Close()
if _, err := Run(context.Background(), cfg(srv.URL)); err != nil {
t.Fatal(err)
}
for _, name := range []string{"Purchase Invoice-intake_communication", "E Invoice Import-intake_communication"} {
cf := f.docs["Custom Field"][name]
if cf == nil || cf["unique"] != float64(1) || cf["read_only"] != float64(1) || cf["fieldtype"] != "Link" || cf["options"] != "Communication" {
t.Errorf("custom field %s: %v", name, cf)
}
}
item := f.docs["Item"][intakeItem]
if item == nil || item["is_purchase_item"] != float64(1) || item["is_stock_item"] != float64(0) || item["stock_uom"] != intakeUOM {
t.Fatalf("placeholder item: %v", item)
}
rows, _ := item["item_defaults"].([]any)
if len(rows) != 1 || fmt.Sprint(rows[0].(map[string]any)["expense_account"]) != "6300 - Sonstige betriebliche Aufwendungen - BG" {
t.Errorf("placeholder expense account: %v", rows)
}
}
func TestIntakeWithoutExpenseAccountIsReported(t *testing.T) {
f := newFake()
delete(f.docs["Account"], "6300 - Sonstige betriebliche Aufwendungen - BG")
srv := httptest.NewServer(f)
defer srv.Close()
steps, err := Run(context.Background(), cfg(srv.URL))
if err != nil {
t.Fatal(err)
}
for _, s := range steps {
if s.What == "item "+intakeItem+" expense account "+intakeAccountNum {
if s.Result != "missing (not created)" {
t.Errorf("result %q", s.Result)
}
return
}
}
t.Error("no step for the expense account")
}
+154
View File
@@ -0,0 +1,154 @@
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 {
q := url.Values{"filters": {string(f)}, "fields": {string(fl)}, "order_by": {"creation asc"},
"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
}
+421
View File
@@ -0,0 +1,421 @@
// Package invoiceintake turns the mails of ERPNext's Email Account
// "Eingangsrechnung" (invoice@) into drafts a person checks and books
// (orca-infra #121, Collectives ERP/08):
//
// - an e-invoice (XRechnung XML, ZUGFeRD/Factur-X PDF) becomes an E Invoice
// Import draft; eu_einvoice reads and validates it, the person maps the
// supplier and lines and creates the Purchase Invoice from it.
// - any other PDF becomes a draft Purchase Invoice for the supplier found by
// the sender address, with one placeholder line and the original attached.
// - a mail without a PDF/XML, from an unknown sender, or one ERPNext refuses
// as a draft becomes a ToDo ("prüfen").
//
// Automation stops at the draft (GoBD: check before booking). The service
// never submits, cancels, changes or deletes a document, and never touches the
// mail or its attachments: a draft gets the same file attached again. Which
// mails are done is read back from ERPNext (intake_communication, ToDo
// reference), so the service keeps no state and runs again safely.
package invoiceintake
import (
"context"
"errors"
"fmt"
"net/http"
"net/mail"
"path"
"strings"
"time"
)
// Names set up by erpsetup (internal/erpsetup/intake.go).
const (
markerField = "intake_communication"
placeholderItem = "EINGANGSRECHNUNG"
)
type Config struct {
BaseURL string // https://erp.breakpilot.com
APIKey string
APISecret string
EmailAccount string // "Eingangsrechnung"
Company string // "Breakpilot GmbH"
Since time.Time // mails received before are left alone
AssignTo string // ERPNext user who gets the ToDos; empty: unassigned
OwnDomains []string // our own domains: a forwarded mail never names the supplier
DryRun bool // report what would happen, create nothing
HTTP *http.Client
Log func(format string, args ...any)
}
// Outcome of one mail.
const (
EInvoice = "e-invoice import"
Draft = "draft purchase invoice"
Review = "todo"
)
// Result is one handled mail: the Communication, what became of it and the
// document created. Reason says why a ToDo was needed. No sender, subject or
// amounts: results are logged.
type Result struct {
Communication string
Outcome string
Document string
Reason string
}
type communication struct {
Name string `json:"name"`
Sender string `json:"sender"`
Date string `json:"communication_date"`
Creation string `json:"creation"`
}
type file struct {
Name string `json:"name"`
FileURL string `json:"file_url"`
FileName string `json:"file_name"`
IsPrivate int `json:"is_private"`
}
// Intake runs the intake; keep one per process (it remembers transient
// failures between runs).
type Intake struct {
cfg Config
c *frappe
retries map[string]int // e-invoice attempts that failed with a server error
}
// maxEInvoiceRetries: after that many server errors on the e-invoice import
// (a broken XML can make eu_einvoice fail with 500 instead of 417) the mail
// is treated as a plain PDF.
const maxEInvoiceRetries = 3
func New(cfg Config) (*Intake, error) {
if cfg.BaseURL == "" || cfg.APIKey == "" || cfg.APISecret == "" {
return nil, errors.New("invoiceintake: base URL, API key and API secret are required")
}
if cfg.EmailAccount == "" || cfg.Company == "" {
return nil, errors.New("invoiceintake: email account and company are required")
}
if cfg.HTTP == nil {
cfg.HTTP = &http.Client{Timeout: 60 * time.Second}
}
if cfg.Log == nil {
cfg.Log = func(string, ...any) {}
}
base := strings.TrimRight(cfg.BaseURL, "/")
return &Intake{cfg: cfg, c: &frappe{base: base, key: cfg.APIKey, secret: cfg.APISecret, http: cfg.HTTP}, retries: map[string]int{}}, nil
}
// Run handles every received mail that has no draft or ToDo yet.
func (in *Intake) Run(ctx context.Context) ([]Result, error) {
filters := [][]any{
{"email_account", "=", in.cfg.EmailAccount},
{"sent_or_received", "=", "Received"},
{"communication_medium", "=", "Email"},
}
if !in.cfg.Since.IsZero() {
filters = append(filters, []any{"creation", ">=", in.cfg.Since.Format("2006-01-02")})
}
var mails []communication
if err := in.c.list(ctx, "Communication", filters, []string{"name", "sender", "communication_date", "creation"}, &mails); err != nil {
return nil, err
}
if len(mails) == 0 {
return nil, nil
}
done, err := in.handled(ctx, mails)
if err != nil {
return nil, err
}
var out []Result
for _, m := range mails {
if done[m.Name] {
continue
}
r, err := in.one(ctx, m)
if err != nil {
return out, fmt.Errorf("invoiceintake: %s: %w", m.Name, err)
}
if r.Outcome != "" {
out = append(out, r)
in.cfg.Log("%s → %s %s %s", r.Communication, r.Outcome, r.Document, r.Reason)
}
}
return out, nil
}
// handled returns the mails that already have a draft or an open (or done)
// ToDo. A cancelled ToDo is the way to ask for another try.
func (in *Intake) handled(ctx context.Context, mails []communication) (map[string]bool, error) {
done := map[string]bool{}
// in chunks: the names travel in the URL of a GET
for start := 0; start < len(mails); start += chunk {
end := min(start+chunk, len(mails))
names := make([]any, 0, end-start)
for _, m := range mails[start:end] {
names = append(names, m.Name)
}
for _, dt := range []string{"Purchase Invoice", "E Invoice Import"} {
var rows []map[string]any
if err := in.c.list(ctx, dt, [][]any{{markerField, "in", names}}, []string{markerField}, &rows); err != nil {
return nil, err
}
for _, r := range rows {
done[fmt.Sprint(r[markerField])] = true
}
}
var todos []map[string]any
if err := in.c.list(ctx, "ToDo", [][]any{{"reference_type", "=", "Communication"}, {"reference_name", "in", names}, {"status", "!=", "Cancelled"}},
[]string{"reference_name"}, &todos); err != nil {
return nil, err
}
for _, r := range todos {
done[fmt.Sprint(r["reference_name"])] = true
}
}
return done, nil
}
const chunk = 100
func (in *Intake) one(ctx context.Context, m communication) (Result, error) {
res := Result{Communication: m.Name}
var files []file
if err := in.c.list(ctx, "File", [][]any{{"attached_to_doctype", "=", "Communication"}, {"attached_to_name", "=", m.Name}},
[]string{"name", "file_url", "file_name", "is_private"}, &files); err != nil {
return res, err
}
invoices := invoiceFiles(files)
if len(invoices) == 0 {
return in.todo(ctx, res, "Keine PDF- oder XML-Anlage. Ist es eine Rechnung (z. B. nur ein Download-Link), die Rechnung herunterladen und als Eingangsrechnung erfassen; sonst diese Aufgabe schließen.")
}
if name, tried, err := in.einvoice(ctx, m, invoices); err != nil || name != "" || tried {
if name != "" {
res.Outcome, res.Document = EInvoice, name
}
return res, err
}
supplier, how, err := in.supplierFor(ctx, m.Sender)
if err != nil {
return res, err
}
if supplier == "" {
return in.todo(ctx, res, "Lieferant nicht erkannt ("+how+"). Lieferanten anlegen oder seine E-Mail-Adresse am Kontakt eintragen, dann diese Aufgabe abbrechen: der nächste Lauf legt den Entwurf an. Oder die Eingangsrechnung von Hand erfassen und die Aufgabe schließen.")
}
if in.cfg.DryRun {
res.Outcome, res.Reason = Draft, "(dry run: e-invoice import not tried) supplier by "+how
return res, nil
}
date := mailDate(m)
name, err := in.c.create(ctx, "Purchase Invoice", map[string]any{
"supplier": supplier,
"company": in.cfg.Company,
"set_posting_time": 1,
"posting_date": date,
"items": []map[string]any{{"item_code": placeholderItem, "qty": 1, "rate": 0}},
markerField: m.Name,
"remarks": "Entwurf aus dem Rechnungseingang (E-Mail vom " + date + "). Rechnungsnummer, Datum, Positionen, Steuer und Konto aus der Anlage übernehmen, dann buchen.",
})
switch {
case statusOf(err) == http.StatusConflict:
return res, nil // a run before this one created it
case statusOf(err) == http.StatusExpectationFailed:
return in.todo(ctx, res, "ERPNext hat den Entwurf abgelehnt: "+messageOf(err))
case err != nil:
return res, err
}
res.Outcome, res.Document, res.Reason = Draft, name, "supplier by "+how
if err := in.attach(ctx, "Purchase Invoice", name, invoices); err != nil {
_, terr := in.todo(ctx, Result{Communication: m.Name}, "Der Entwurf "+name+" ist angelegt, aber die Anlage fehlt: das Original aus der E-Mail von Hand anhängen.")
return res, errors.Join(err, terr)
}
return res, nil
}
// einvoice offers the XML files, then the PDFs, to eu_einvoice. It returns the
// import's name when one was accepted, and tried=true when the mail should be
// left for a later run (a server error, or a dry run).
func (in *Intake) einvoice(ctx context.Context, m communication, invoices []file) (string, bool, error) {
if in.cfg.DryRun {
return "", false, nil // creating the import is the only way to know
}
if in.retries[m.Name] >= maxEInvoiceRetries {
return "", false, nil
}
for i, f := range invoices {
name, err := in.c.create(ctx, "E Invoice Import", map[string]any{
"einvoice": f.FileURL, "company": in.cfg.Company, markerField: m.Name,
})
switch s := statusOf(err); {
case err == nil:
// eu_einvoice attaches the e-invoice itself; the other files too.
rest := append(append([]file{}, invoices[:i]...), invoices[i+1:]...)
return name, false, in.attach(ctx, "E Invoice Import", name, rest)
case s == http.StatusConflict:
return "", true, nil
case s == http.StatusUnauthorized || s == http.StatusForbidden:
return "", true, err // the API user's roles, not the file
case s/100 == 4:
continue // not an e-invoice ("No machine-readable data …")
case s/100 == 5:
in.retries[m.Name]++
in.cfg.Log("%s: e-invoice import failed (%v), try %d of %d", m.Name, err, in.retries[m.Name], maxEInvoiceRetries)
return "", true, nil
default:
return "", true, err
}
}
return "", false, nil
}
func (in *Intake) attach(ctx context.Context, doctype, name string, files []file) error {
var errs []error
for _, f := range files {
if _, err := in.c.create(ctx, "File", map[string]any{
"file_url": f.FileURL, "file_name": f.FileName, "is_private": f.IsPrivate,
"attached_to_doctype": doctype, "attached_to_name": name,
}); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
func (in *Intake) todo(ctx context.Context, res Result, reason string) (Result, error) {
res.Outcome, res.Reason = Review, reason
if in.cfg.DryRun {
return res, nil
}
doc := map[string]any{
"description": "Rechnungseingang: " + reason,
"reference_type": "Communication",
"reference_name": res.Communication,
"priority": "Medium",
}
if in.cfg.AssignTo != "" {
doc["allocated_to"] = in.cfg.AssignTo
}
name, err := in.c.create(ctx, "ToDo", doc)
res.Document = name
return res, err
}
// supplierFor finds the one supplier that sender belongs to: first by the
// exact address (Supplier e-mail, or a Contact linked to a Supplier), then by
// its domain unless that is a freemail or our own one. how says which, or why
// none was found; it never contains the address itself.
func (in *Intake) supplierFor(ctx context.Context, sender string) (string, string, error) {
addr, err := mail.ParseAddress(sender)
if err != nil {
return "", "sender unreadable", nil
}
email := strings.ToLower(addr.Address)
domain := email[strings.LastIndex(email, "@")+1:]
for _, own := range in.cfg.OwnDomains {
if domain == strings.ToLower(own) {
return "", "weitergeleitet aus eigener Domain", nil
}
}
s, err := in.suppliersMatching(ctx, "=", email)
if err != nil {
return "", "", err
}
if len(s) == 1 {
return s[0], "address", nil
}
if len(s) > 1 {
return "", "Adresse passt zu mehreren Lieferanten", nil
}
if freemail[domain] {
return "", "Freemail-Absender", nil
}
s, err = in.suppliersMatching(ctx, "like", "%@"+domain)
if err != nil {
return "", "", err
}
switch len(s) {
case 1:
return s[0], "domain", nil
case 0:
return "", "Absender-Domain " + domain + " keinem Lieferanten zugeordnet", nil
}
return "", "Domain " + domain + " passt zu mehreren Lieferanten", nil
}
func (in *Intake) suppliersMatching(ctx context.Context, op, value string) ([]string, error) {
found := map[string]bool{}
var sup []map[string]any
if err := in.c.list(ctx, "Supplier", [][]any{{"email_id", op, value}, {"disabled", "=", 0}}, []string{"name"}, &sup); err != nil {
return nil, err
}
for _, r := range sup {
found[fmt.Sprint(r["name"])] = true
}
var contacts []map[string]any
if err := in.c.list(ctx, "Contact", [][]any{{"Contact Email", "email_id", op, value}}, []string{"name"}, &contacts); err != nil {
return nil, err
}
for _, ct := range contacts {
var doc struct {
Links []struct {
LinkDoctype string `json:"link_doctype"`
LinkName string `json:"link_name"`
} `json:"links"`
}
if err := in.c.get(ctx, "Contact", fmt.Sprint(ct["name"]), &doc); err != nil {
return nil, err
}
for _, l := range doc.Links {
if l.LinkDoctype == "Supplier" {
found[l.LinkName] = true
}
}
}
out := make([]string, 0, len(found))
for s := range found {
out = append(out, s)
}
return out, nil
}
// invoiceFiles keeps the PDF and XML attachments, XML first: an XRechnung
// often comes with a PDF rendering, and the XML is the invoice.
func invoiceFiles(files []file) []file {
var xml, pdf []file
for _, f := range files {
name := f.FileName
if name == "" {
name = f.FileURL
}
switch strings.ToLower(path.Ext(name)) {
case ".xml":
xml = append(xml, f)
case ".pdf":
pdf = append(pdf, f)
}
}
return append(xml, pdf...)
}
// mailDate is the day the mail arrived, as the draft's posting date; the
// person checking sets the invoice date.
func mailDate(m communication) string {
for _, d := range []string{m.Date, m.Creation} {
if len(d) >= 10 {
return d[:10]
}
}
return time.Now().Format("2006-01-02")
}
var freemail = map[string]bool{
"gmail.com": true, "googlemail.com": true, "gmx.de": true, "gmx.net": true, "web.de": true,
"outlook.com": true, "outlook.de": true, "hotmail.com": true, "hotmail.de": true, "live.com": true,
"yahoo.com": true, "yahoo.de": true, "icloud.com": true, "me.com": true, "t-online.de": true,
"posteo.de": true, "mailbox.org": true, "proton.me": true, "protonmail.com": true, "freenet.de": true,
}
+391
View File
@@ -0,0 +1,391 @@
package invoiceintake
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"sync"
"testing"
)
// fakeERP holds docs per doctype and answers like Frappe: 417 when eu_einvoice
// finds no e-invoice in a file, 409 on a second draft for the same mail.
type fakeERP struct {
mu sync.Mutex
docs map[string][]map[string]any
writes []string // "POST <doctype>" in order
einvErr int // status for E Invoice Import of a file without "einv" in its name
failPI int // status for every Purchase Invoice create, 0 = accept
}
func newFakeERP() *fakeERP {
return &fakeERP{einvErr: http.StatusExpectationFailed, docs: map[string][]map[string]any{
"Supplier": {{"name": "Hetzner Online GmbH", "email_id": "billing@hetzner.example", "disabled": 0}},
"Contact": {
{"name": "OVH Buchhaltung", "email_ids": []any{map[string]any{"email_id": "invoice@ovh.example"}},
"links": []any{map[string]any{"link_doctype": "Supplier", "link_name": "OVH GmbH"}}},
{"name": "Private Person", "email_ids": []any{map[string]any{"email_id": "someone@gmail.com"}},
"links": []any{map[string]any{"link_doctype": "Supplier", "link_name": "Freelancer"}}},
},
}}
}
func (f *fakeERP) mail(name, sender string, attachments ...string) {
f.docs["Communication"] = append(f.docs["Communication"], map[string]any{
"name": name, "sender": sender, "communication_date": "2026-10-20 09:13:00", "creation": "2026-10-20 09:13:01",
"email_account": "Eingangsrechnung", "sent_or_received": "Received", "communication_medium": "Email",
})
for i, a := range attachments {
f.docs["File"] = append(f.docs["File"], map[string]any{
"name": fmt.Sprintf("%s-f%d", name, i), "file_url": "/private/files/" + a, "file_name": a, "is_private": 1,
"attached_to_doctype": "Communication", "attached_to_name": name,
})
}
}
func (f *fakeERP) find(doctype string, filters [][]any) []map[string]any {
var out []map[string]any
for _, d := range f.docs[doctype] {
if matches(d, filters) {
out = append(out, d)
}
}
return out
}
func matches(d map[string]any, filters [][]any) bool {
for _, c := range filters {
field, op, want := c[0], c[1], c[2]
vals := []any{d[fmt.Sprint(field)]}
if len(c) == 4 { // child table: ["Contact Email", "email_id", op, value]
field, op, want = c[1], c[2], c[3]
vals = nil
for _, row := range d["email_ids"].([]any) {
vals = append(vals, row.(map[string]any)[fmt.Sprint(field)])
}
}
ok := false
for _, v := range vals {
got := fmt.Sprint(v)
switch op {
case "=":
ok = ok || got == fmt.Sprint(want)
case "!=":
ok = ok || got != fmt.Sprint(want)
case "in":
for _, w := range want.([]any) {
ok = ok || got == fmt.Sprint(w)
}
case "like":
ok = ok || strings.HasSuffix(got, strings.TrimPrefix(fmt.Sprint(want), "%"))
case ">=":
ok = ok || got >= fmt.Sprint(want)
}
}
if !ok {
return false
}
}
return true
}
func (f *fakeERP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
if r.Header.Get("Authorization") != "token k:s" {
w.WriteHeader(http.StatusUnauthorized)
return
}
parts := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/api/resource/"), "/", 2)
doctype, _ := url.PathUnescape(parts[0])
reply := func(status int, v any) {
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
switch {
case r.Method == http.MethodGet && len(parts) == 1:
var filters [][]any
_ = json.Unmarshal([]byte(r.URL.Query().Get("filters")), &filters)
rows := f.find(doctype, filters)
start, _ := strconv.Atoi(r.URL.Query().Get("limit_start"))
n, _ := strconv.Atoi(r.URL.Query().Get("limit_page_length"))
rows = rows[min(start, len(rows)):min(start+n, len(rows))]
reply(200, map[string]any{"data": rows})
case r.Method == http.MethodGet:
name, _ := url.PathUnescape(parts[1])
for _, d := range f.docs[doctype] {
if d["name"] == name {
reply(200, map[string]any{"data": d})
return
}
}
w.WriteHeader(http.StatusNotFound)
case r.Method == http.MethodPost:
var doc map[string]any
_ = json.NewDecoder(r.Body).Decode(&doc)
f.writes = append(f.writes, "POST "+doctype)
if m, ok := doc[markerField]; ok && len(f.find(doctype, [][]any{{markerField, "=", m}})) > 0 {
reply(http.StatusConflict, map[string]any{"exc_type": "DuplicateEntryError"})
return
}
if doctype == "E Invoice Import" && !strings.Contains(fmt.Sprint(doc["einvoice"]), "einv") {
reply(f.einvErr, map[string]any{"exception": "frappe.exceptions.ValidationError: No machine-readable data was found in the PDF file."})
return
}
if doctype == "Purchase Invoice" && f.failPI != 0 {
reply(f.failPI, map[string]any{"exception": "frappe.exceptions.ValidationError: Expense account is mandatory for item EINGANGSRECHNUNG"})
return
}
doc["name"] = fmt.Sprintf("%s-%d", strings.ReplaceAll(doctype, " ", ""), len(f.docs[doctype])+1)
f.docs[doctype] = append(f.docs[doctype], doc)
reply(200, map[string]any{"data": doc})
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func setup(t *testing.T) (*fakeERP, *Intake) {
t.Helper()
f := newFakeERP()
srv := httptest.NewServer(f)
t.Cleanup(srv.Close)
in, err := New(Config{BaseURL: srv.URL + "/", APIKey: "k", APISecret: "s", EmailAccount: "Eingangsrechnung",
Company: "Breakpilot GmbH", AssignTo: "finance@company.example", OwnDomains: []string{"breakpilot.com"}})
if err != nil {
t.Fatal(err)
}
return f, in
}
func run(t *testing.T, in *Intake) []Result {
t.Helper()
res, err := in.Run(context.Background())
if err != nil {
t.Fatal(err)
}
return res
}
func TestEInvoiceBecomesImportDraft(t *testing.T) {
f, in := setup(t)
f.mail("c1", "Strato <rechnung@strato.example>", "rendering.pdf", "xrechnung-einv.xml")
res := run(t, in)
if len(res) != 1 || res[0].Outcome != EInvoice {
t.Fatalf("results %+v", res)
}
imp := f.docs["E Invoice Import"][0]
if imp["einvoice"] != "/private/files/xrechnung-einv.xml" || imp[markerField] != "c1" || imp["company"] != "Breakpilot GmbH" {
t.Errorf("import %v", imp)
}
// the XML is tried first; the PDF rendering is attached to the import too
files := f.find("File", [][]any{{"attached_to_doctype", "=", "E Invoice Import"}})
if len(files) != 1 || files[0]["file_url"] != "/private/files/rendering.pdf" {
t.Errorf("attachments %v", files)
}
if len(f.docs["Purchase Invoice"]) != 0 || len(f.docs["ToDo"]) != 0 {
t.Error("an e-invoice must not also become a purchase invoice or todo")
}
}
func TestPlainPDFBecomesDraftForKnownSupplier(t *testing.T) {
f, in := setup(t)
f.mail("c1", "billing@hetzner.example", "Rechnung.PDF")
f.mail("c2", "OVH <invoice@ovh.example>", "facture.pdf", "agb.txt")
res := run(t, in)
if len(res) != 2 || res[0].Outcome != Draft || res[1].Outcome != Draft {
t.Fatalf("results %+v", res)
}
pis := f.docs["Purchase Invoice"]
if pis[0]["supplier"] != "Hetzner Online GmbH" || pis[1]["supplier"] != "OVH GmbH" {
t.Errorf("suppliers %v / %v", pis[0]["supplier"], pis[1]["supplier"])
}
pi := pis[0]
if pi[markerField] != "c1" || pi["posting_date"] != "2026-10-20" || pi["set_posting_time"] != float64(1) {
t.Errorf("draft %v", pi)
}
items := pi["items"].([]any)
if len(items) != 1 || items[0].(map[string]any)["item_code"] != placeholderItem {
t.Errorf("items %v", items)
}
for _, d := range pis {
if _, ok := d["docstatus"]; ok {
t.Error("draft carries docstatus")
}
}
att := f.find("File", [][]any{{"attached_to_doctype", "=", "Purchase Invoice"}, {"attached_to_name", "=", pi["name"]}})
if len(att) != 1 || att[0]["file_url"] != "/private/files/Rechnung.PDF" {
t.Errorf("attachment %v", att)
}
att = f.find("File", [][]any{{"attached_to_doctype", "=", "Purchase Invoice"}, {"attached_to_name", "=", pis[1]["name"]}})
if len(att) != 1 {
t.Errorf("only the PDF is attached, got %v", att)
}
}
func TestSupplierByDomain(t *testing.T) {
f, in := setup(t)
f.mail("c1", "noreply@hetzner.example", "r.pdf")
res := run(t, in)
if len(res) != 1 || res[0].Outcome != Draft || !strings.Contains(res[0].Reason, "domain") {
t.Fatalf("results %+v", res)
}
}
func TestUnplaceableMailsBecomeTodos(t *testing.T) {
f, in := setup(t)
f.mail("c1", "news@shop.example", "r.pdf") // unknown domain
f.mail("c2", "billing@hetzner.example") // no attachment
f.mail("c3", "other@gmail.com", "r.pdf") // freemail, no exact match
f.mail("c4", "Me <someone.else@breakpilot.com>", "r.pdf") // forwarded by us
res := run(t, in)
if len(res) != 4 {
t.Fatalf("results %+v", res)
}
for _, r := range res {
if r.Outcome != Review || r.Document == "" {
t.Errorf("%+v", r)
}
}
todo := f.docs["ToDo"][0]
if todo["reference_type"] != "Communication" || todo["reference_name"] != "c1" || todo["allocated_to"] != "finance@company.example" {
t.Errorf("todo %v", todo)
}
if len(f.docs["Purchase Invoice"]) != 0 {
t.Error("no draft without a supplier")
}
for _, r := range res {
if strings.Contains(r.Reason, "@") {
t.Errorf("reason leaks an address: %q", r.Reason)
}
}
}
func TestFreemailExactAddressStillMatches(t *testing.T) {
f, in := setup(t)
f.mail("c1", "someone@gmail.com", "r.pdf")
res := run(t, in)
if len(res) != 1 || res[0].Outcome != Draft || f.docs["Purchase Invoice"][0]["supplier"] != "Freelancer" {
t.Fatalf("results %+v", res)
}
}
func TestSecondRunDoesNothing(t *testing.T) {
f, in := setup(t)
f.mail("c1", "billing@hetzner.example", "r.pdf")
f.mail("c2", "x@unknown.example", "r.pdf")
f.mail("c3", "a@strato.example", "einv.xml")
run(t, in)
n := len(f.writes)
if res := run(t, in); len(res) != 0 || len(f.writes) != n {
t.Fatalf("second run: %+v, %d new writes", res, len(f.writes)-n)
}
// a fresh process (no memory) agrees: the state is in ERPNext
in2, _ := New(in.cfg)
if res, err := in2.Run(context.Background()); err != nil || len(res) != 0 {
t.Fatalf("fresh process: %+v %v", res, err)
}
}
func TestCancelledTodoIsRetried(t *testing.T) {
f, in := setup(t)
f.mail("c1", "x@newsupplier.example", "r.pdf")
run(t, in)
f.docs["ToDo"][0]["status"] = "Cancelled"
f.docs["Supplier"] = append(f.docs["Supplier"], map[string]any{"name": "New Supplier", "email_id": "x@newsupplier.example", "disabled": 0})
res := run(t, in)
if len(res) != 1 || res[0].Outcome != Draft {
t.Fatalf("retry %+v", res)
}
}
func TestRefusedDraftBecomesTodo(t *testing.T) {
f, in := setup(t)
f.failPI = http.StatusExpectationFailed
f.mail("c1", "billing@hetzner.example", "r.pdf")
res := run(t, in)
if len(res) != 1 || res[0].Outcome != Review || !strings.Contains(res[0].Reason, "Expense account is mandatory") {
t.Fatalf("results %+v", res)
}
if strings.Contains(res[0].Reason, "Traceback") || strings.Contains(res[0].Reason, "frappe.exceptions") {
t.Errorf("reason %q", res[0].Reason)
}
}
func TestEInvoiceServerErrorIsRetriedThenPlain(t *testing.T) {
f, in := setup(t)
f.einvErr = http.StatusInternalServerError
f.mail("c1", "billing@hetzner.example", "broken.xml")
for i := 0; i < maxEInvoiceRetries; i++ {
if res := run(t, in); len(res) != 0 {
t.Fatalf("try %d: %+v", i, res)
}
}
res := run(t, in)
if len(res) != 1 || res[0].Outcome != Draft {
t.Fatalf("after retries: %+v", res)
}
}
func TestDryRunCreatesNothing(t *testing.T) {
f, in := setup(t)
in.cfg.DryRun = true
f.mail("c1", "billing@hetzner.example", "r.pdf")
f.mail("c2", "x@unknown.example")
res := run(t, in)
if len(res) != 2 || len(f.writes) != 0 {
t.Fatalf("dry run: %+v, writes %v", res, f.writes)
}
}
func TestPermissionErrorStopsTheRun(t *testing.T) {
f, in := setup(t)
f.mail("c1", "billing@hetzner.example", "r.pdf")
in.c.secret = "wrong"
if _, err := in.Run(context.Background()); err == nil {
t.Fatal("want an error")
}
if len(f.writes) != 0 {
t.Error("wrote with a bad key")
}
}
func TestOnlyDraftDoctypesAreWritten(t *testing.T) {
f, in := setup(t)
f.mail("c1", "billing@hetzner.example", "r.pdf")
f.mail("c2", "a@strato.example", "einv.xml")
f.mail("c3", "x@unknown.example")
run(t, in)
allowed := map[string]bool{"POST Purchase Invoice": true, "POST E Invoice Import": true, "POST File": true, "POST ToDo": true}
for _, w := range f.writes {
if !allowed[w] {
t.Errorf("unexpected write %s", w)
}
}
}
func TestRequiredConfig(t *testing.T) {
if _, err := New(Config{BaseURL: "x", APIKey: "k", APISecret: "s"}); err == nil {
t.Error("want an error without email account and company")
}
if _, err := New(Config{EmailAccount: "e", Company: "c"}); err == nil {
t.Error("want an error without credentials")
}
}
func TestManyMailsArePagedAndChunked(t *testing.T) {
f, in := setup(t)
for i := range 1234 {
f.mail(fmt.Sprintf("c%04d", i), "billing@hetzner.example", "r.pdf")
}
if res := run(t, in); len(res) != 1234 {
t.Fatalf("first run handled %d", len(res))
}
if res := run(t, in); len(res) != 0 {
t.Fatalf("second run handled %d", len(res))
}
}