feat(invoiceintake): send every invoice mail on to DATEV from invoice@ #110

Merged
sharang merged 1 commits from feat/intake-datev-forward into main 2026-11-02 11:59:01 +00:00
4 changed files with 387 additions and 16 deletions

No files matched your search

+20 -3
View File
@@ -12,6 +12,12 @@
// 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.
//
// With INTAKE_DATEV_ADDRESS (DATEV Upload Mail) set, every invoice mail
// received on or after INTAKE_DATEV_SINCE (YYYY-MM-DD, required then) is
// also sent there from INTAKE_DATEV_SENDER (default invoice@breakpilot.com).
// That address must be registered as a sender in DATEV Unternehmen Online,
// and its ERPNext Email Account must have outgoing mail enabled.
package main
import (
@@ -58,6 +64,14 @@ func main() {
}
interval = d
}
var datevSince time.Time
if s := os.Getenv("INTAKE_DATEV_SINCE"); s != "" {
t, err := time.Parse("2006-01-02", s)
if err != nil {
fail(*once, "INTAKE_DATEV_SINCE: %v", err)
}
datevSince = t
}
in, err := invoiceintake.New(invoiceintake.Config{
BaseURL: os.Getenv("ERP_BASE_URL"),
APIKey: os.Getenv("ERP_API_KEY"),
@@ -67,6 +81,9 @@ func main() {
Since: since,
AssignTo: os.Getenv("INTAKE_ASSIGN_TO"),
OwnDomains: strings.Fields(strings.ReplaceAll(envOr("INTAKE_OWN_DOMAINS", "breakpilot.com"), ",", " ")),
DatevAddress: os.Getenv("INTAKE_DATEV_ADDRESS"),
DatevSender: envOr("INTAKE_DATEV_SENDER", "invoice@breakpilot.com"),
DatevSince: datevSince,
DryRun: *dry,
Log: logf,
})
@@ -88,12 +105,12 @@ func main() {
}
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],
fmt.Printf("%d results: %d e-invoice imports, %d draft purchase invoices, %d todos, %d forwarded to DATEV%s\n",
len(res), counts[invoiceintake.EInvoice], counts[invoiceintake.Draft], counts[invoiceintake.Review], counts[invoiceintake.Forward],
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])
"draft", counts[invoiceintake.Draft], "todo", counts[invoiceintake.Review], "datev", counts[invoiceintake.Forward])
}
if *once {
return
+165
View File
@@ -0,0 +1,165 @@
package invoiceintake
import (
"context"
"fmt"
"net/http"
"net/mail"
"strings"
)
// DATEV Unternehmen Online takes receipts by mail only from registered
// senders, and invoice@ receives most invoices straight from the supplier
// (backlog t60). So the intake sends every invoice mail on to the DATEV
// upload address itself, from invoice@, through ERPNext: the outgoing mail
// is a Communication with in_reply_to = the received one. That is also the
// "already forwarded" marker, a visible entry in the mail's timeline, and
// ERPNext's Email Queue retries a failed send.
// Forward is the outcome of a mail sent on to DATEV.
const Forward = "forwarded to DATEV"
const makeMail = "/api/method/frappe.core.doctype.communication.email.make"
// forward sends each invoice mail received since DatevSince that has no
// forward yet. Mails without a PDF or XML, and DATEV's own answers and
// bounces, are never forwarded.
func (in *Intake) forward(ctx context.Context, mails []communication) ([]Result, error) {
if in.cfg.DatevAddress == "" {
return nil, nil
}
since := in.cfg.DatevSince.Format("2006-01-02")
var due []communication
for _, m := range mails {
if mailDate(m) >= since && in.forwardable(m.Sender) {
due = append(due, m)
}
}
if len(due) == 0 {
return nil, nil
}
sent, err := in.forwarded(ctx, due)
if err != nil {
return nil, err
}
var out []Result
for _, m := range due {
if sent[m.Name] {
continue
}
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 out, err
}
receipts := datevFiles(files)
if len(receipts) == 0 {
continue
}
res := Result{Communication: m.Name, Outcome: Forward, Reason: fmt.Sprintf("%d Anlage(n)", len(receipts))}
if in.cfg.DryRun {
res.Reason += " (dry run)"
out = append(out, res)
continue
}
names := make([]string, len(receipts))
for i, f := range receipts {
names[i] = f.Name
}
var resp struct {
Message struct {
Name string `json:"name"`
} `json:"message"`
}
err := in.c.do(ctx, http.MethodPost, makeMail, map[string]any{
"recipients": in.cfg.DatevAddress,
"sender": in.cfg.DatevSender,
"subject": "Beleg aus dem Rechnungseingang (" + m.Name + ")",
"content": "Beleg aus dem Rechnungseingang von BreakPilot, E-Mail vom " + mailDate(m) + ".",
"communication_medium": "Email",
"sent_or_received": "Sent",
"send_email": 1,
"attachments": names,
"in_reply_to": m.Name,
}, &resp)
if err != nil {
return out, fmt.Errorf("forward to DATEV: %w", err)
}
res.Document = resp.Message.Name
out = append(out, res)
in.cfg.Log("%s → %s %s %s", res.Communication, res.Outcome, res.Document, res.Reason)
}
return out, nil
}
// forwarded returns the mails that already have a sent mail to the DATEV
// address replying to them.
func (in *Intake) forwarded(ctx context.Context, mails []communication) (map[string]bool, error) {
sent := map[string]bool{}
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)
}
var rows []map[string]any
if err := in.c.list(ctx, "Communication", [][]any{
{"in_reply_to", "in", names}, {"sent_or_received", "=", "Sent"}, {"recipients", "=", in.cfg.DatevAddress},
}, []string{"in_reply_to"}, &rows); err != nil {
return nil, err
}
for _, r := range rows {
sent[fmt.Sprint(r["in_reply_to"])] = true
}
}
return sent, nil
}
// forwardable is false for DATEV's own mails (confirmations, rejected
// receipts), bounces, and mails from our own forwarding address: sending
// those on would loop.
func (in *Intake) forwardable(sender string) bool {
return answerFrom(sender) == "" && !strings.EqualFold(address(sender), in.cfg.DatevSender)
}
// answerFrom says what kind of automatic answer a sender is: "datev" for
// DATEV's mails, "bounce" for a mailer daemon, "" for anything else.
func answerFrom(sender string) string {
a := address(sender)
at := strings.LastIndex(a, "@")
if at < 0 {
return ""
}
local, domain := a[:at], a[at+1:]
switch {
case domain == "datev.de" || strings.HasSuffix(domain, ".datev.de"):
return "datev"
case local == "mailer-daemon" || local == "postmaster":
return "bounce"
}
return ""
}
func address(sender string) string {
if a, err := mail.ParseAddress(sender); err == nil {
return strings.ToLower(a.Address)
}
return strings.ToLower(strings.TrimSpace(sender))
}
// datevFiles: an XRechnung's XML is the invoice and DATEV reads it; its PDF
// rendering would become a second receipt. Without XML, every PDF goes
// (a ZUGFeRD PDF carries its XML inside).
func datevFiles(files []file) []file {
all := invoiceFiles(files) // XML first
var xml []file
for _, f := range all {
if strings.EqualFold(pathExt(f), ".xml") {
xml = append(xml, f)
}
}
if len(xml) > 0 {
return xml
}
return all
}
+38 -7
View File
@@ -9,12 +9,15 @@
// 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").
// - with DatevAddress set, every invoice mail is also sent on to DATEV
// Unternehmen Online from invoice@ (datev.go).
//
// 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.
// reference, the forward's in_reply_to), so the service keeps no state and
// runs again safely.
package invoiceintake
import (
@@ -44,6 +47,11 @@ type Config struct {
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
// DATEV forwarding (datev.go); off while DatevAddress is empty.
DatevAddress string // DATEV Upload Mail address of the client
DatevSender string // invoice@: the Email Account with outgoing mail on, registered in DATEV
DatevSince time.Time // mails received before are not forwarded (sent by hand)
HTTP *http.Client
Log func(format string, args ...any)
}
@@ -100,6 +108,9 @@ func New(cfg Config) (*Intake, error) {
if cfg.EmailAccount == "" || cfg.Company == "" {
return nil, errors.New("invoiceintake: email account and company are required")
}
if cfg.DatevAddress != "" && (cfg.DatevSender == "" || cfg.DatevSince.IsZero()) {
return nil, errors.New("invoiceintake: DATEV forwarding needs a sender and a start date")
}
if cfg.HTTP == nil {
cfg.HTTP = &http.Client{Timeout: 60 * time.Second}
}
@@ -110,7 +121,9 @@ func New(cfg Config) (*Intake, error) {
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.
// Run handles every received mail that has no draft or ToDo yet, and sends
// on to DATEV what isn't there yet. A failure in one part doesn't stop the
// other.
func (in *Intake) Run(ctx context.Context) ([]Result, error) {
filters := [][]any{
{"email_account", "=", in.cfg.EmailAccount},
@@ -127,6 +140,15 @@ func (in *Intake) Run(ctx context.Context) ([]Result, error) {
if len(mails) == 0 {
return nil, nil
}
out, err := in.drafts(ctx, mails)
fwd, ferr := in.forward(ctx, mails)
if ferr != nil {
ferr = fmt.Errorf("invoiceintake: %w", ferr)
}
return append(out, fwd...), errors.Join(err, ferr)
}
func (in *Intake) drafts(ctx context.Context, mails []communication) ([]Result, error) {
done, err := in.handled(ctx, mails)
if err != nil {
return nil, err
@@ -184,6 +206,12 @@ const chunk = 100
func (in *Intake) one(ctx context.Context, m communication) (Result, error) {
res := Result{Communication: m.Name}
switch answerFrom(m.Sender) {
case "datev":
return in.todo(ctx, res, "Nachricht von DATEV (z. B. ein abgelehnter Beleg oder eine Absender-Freigabe): lesen und erledigen, dann diese Aufgabe schließen.")
case "bounce":
return in.todo(ctx, res, "Unzustellbar-Meldung: prüfen, welche Mail nicht angekommen ist (z. B. die Weiterleitung an DATEV), dann diese Aufgabe schließen.")
}
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 {
@@ -431,11 +459,7 @@ func (in *Intake) suppliersMatching(ctx context.Context, op, value string) ([]st
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)) {
switch strings.ToLower(pathExt(f)) {
case ".xml":
xml = append(xml, f)
case ".pdf":
@@ -445,6 +469,13 @@ func invoiceFiles(files []file) []file {
return append(xml, pdf...)
}
func pathExt(f file) string {
if f.FileName != "" {
return path.Ext(f.FileName)
}
return path.Ext(f.FileURL)
}
// 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 {
+164 -6
View File
@@ -11,17 +11,19 @@ import (
"strings"
"sync"
"testing"
"time"
)
// 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
einvMsg string // its exception text, "" = eu_einvoice's "no machine-readable data"
failPI int // status for every Purchase Invoice create, 0 = accept
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
einvMsg string // its exception text, "" = eu_einvoice's "no machine-readable data"
failPI int // status for every Purchase Invoice create, 0 = accept
failMail int // status for every email.make call, 0 = accept
}
func newFakeERP() *fakeERP {
@@ -106,6 +108,10 @@ func (f *fakeERP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{"message": "bot@company.example"})
return
}
if r.URL.Path == makeMail {
f.sendMail(w, r)
return
}
parts := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/api/resource/"), "/", 2)
doctype, _ := url.PathUnescape(parts[0])
reply := func(status int, v any) {
@@ -173,6 +179,32 @@ func (f *fakeERP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
// sendMail answers frappe.core.doctype.communication.email.make: a sent
// Communication, with copies of the named Files attached to it.
func (f *fakeERP) sendMail(w http.ResponseWriter, r *http.Request) {
var args map[string]any
_ = json.NewDecoder(r.Body).Decode(&args)
f.writes = append(f.writes, "POST email.make")
if f.failMail != 0 {
w.WriteHeader(f.failMail)
_ = json.NewEncoder(w).Encode(map[string]any{"exception": "frappe.exceptions.OutgoingEmailError: Unable to send mail because of a missing email account."})
return
}
name := fmt.Sprintf("Sent-%d", len(f.docs["Communication"])+1)
f.docs["Communication"] = append(f.docs["Communication"], map[string]any{
"name": name, "sender": args["sender"], "recipients": args["recipients"], "subject": args["subject"],
"in_reply_to": args["in_reply_to"], "sent_or_received": args["sent_or_received"], "send_email": args["send_email"],
"email_account": "Eingangsrechnung", "communication_medium": "Email", "communication_date": "2026-10-20 10:00:00",
})
for _, a := range args["attachments"].([]any) {
for _, src := range f.find("File", [][]any{{"name", "=", a}}) {
f.docs["File"] = append(f.docs["File"], map[string]any{"name": fmt.Sprintf("%s-copy", a), "file_url": src["file_url"],
"file_name": src["file_name"], "attached_to_doctype": "Communication", "attached_to_name": name})
}
}
_ = json.NewEncoder(w).Encode(map[string]any{"message": map[string]any{"name": name, "emails_not_sent_to": ""}})
}
func setup(t *testing.T) (*fakeERP, *Intake) {
t.Helper()
f := newFakeERP()
@@ -446,3 +478,129 @@ func TestForwardedMailsSayEnterByHand(t *testing.T) {
t.Errorf("unknown supplier: %q", res[2].Reason)
}
}
const datevAddr = "upload@datev.example"
func setupDatev(t *testing.T) (*fakeERP, *Intake) {
t.Helper()
f, in := setup(t)
in.cfg.DatevAddress = datevAddr
in.cfg.DatevSender = "invoice@breakpilot.com"
in.cfg.DatevSince = time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)
return f, in
}
func forwards(res []Result) map[string]Result {
out := map[string]Result{}
for _, r := range res {
if r.Outcome == Forward {
out[r.Communication] = r
}
}
return out
}
func TestForwardSendsEachInvoiceMailToDatevOnce(t *testing.T) {
f, in := setupDatev(t)
f.mail("c1", "billing@hetzner.example", "r.pdf")
f.mail("c2", "Me <someone.else@breakpilot.com>", "forwarded.pdf")
f.mail("c3", "a@strato.example", "rendering.pdf", "xrechnung-einv.xml")
f.mail("c4", "billing@hetzner.example") // no PDF/XML
f.mail("c5", "DATEV <noreply@service.datev.de>", "a.pdf") // DATEV's answer
f.mail("c6", "MAILER-DAEMON@mx.example", "bounced.pdf") // bounce
f.mail("c7", "billing@hetzner.example", "old.pdf") // before DatevSince
f.docs["Communication"][6]["communication_date"] = "2026-10-10 08:00:00"
fw := forwards(run(t, in))
if len(fw) != 3 || fw["c1"].Document == "" || fw["c2"].Document == "" || fw["c3"].Document == "" {
t.Fatalf("forwards %+v", fw)
}
sent := f.find("Communication", [][]any{{"sent_or_received", "=", "Sent"}})
for _, m := range sent {
if m["recipients"] != datevAddr || m["sender"] != "invoice@breakpilot.com" || m["send_email"] != float64(1) {
t.Errorf("sent mail %v", m)
}
}
// the XRechnung goes as XML only: its PDF rendering would be a second receipt
c3 := f.find("Communication", [][]any{{"in_reply_to", "=", "c3"}})[0]
files := f.find("File", [][]any{{"attached_to_doctype", "=", "Communication"}, {"attached_to_name", "=", c3["name"]}})
if len(files) != 1 || files[0]["file_name"] != "xrechnung-einv.xml" {
t.Errorf("c3 attachments %v", files)
}
n := len(f.writes)
if fw := forwards(run(t, in)); len(fw) != 0 || len(f.writes) != n {
t.Fatalf("second run forwarded %+v", fw)
}
in2, _ := New(in.cfg) // the marker is in ERPNext, not in the process
if res, err := in2.Run(context.Background()); err != nil || len(forwards(res)) != 0 {
t.Fatalf("fresh process: %+v %v", res, err)
}
}
func TestForwardOffWithoutAddress(t *testing.T) {
f, in := setup(t)
f.mail("c1", "billing@hetzner.example", "r.pdf")
if fw := forwards(run(t, in)); len(fw) != 0 {
t.Fatalf("forwards %+v", fw)
}
for _, w := range f.writes {
if w == "POST email.make" {
t.Error("sent a mail without a DATEV address")
}
}
}
func TestForwardDryRunSendsNothing(t *testing.T) {
f, in := setupDatev(t)
in.cfg.DryRun = true
f.mail("c1", "billing@hetzner.example", "r.pdf")
res := run(t, in)
if fw := forwards(res); len(fw) != 1 || len(f.writes) != 0 {
t.Fatalf("dry run %+v, writes %v", res, f.writes)
}
}
func TestForwardFailureKeepsDrafts(t *testing.T) {
f, in := setupDatev(t)
f.failMail = http.StatusExpectationFailed
f.mail("c1", "billing@hetzner.example", "r.pdf")
res, err := in.Run(context.Background())
if err == nil || !strings.Contains(err.Error(), "forward to DATEV") {
t.Fatalf("want the forward error, got %v", err)
}
if len(res) != 1 || res[0].Outcome != Draft || len(f.docs["Purchase Invoice"]) != 1 {
t.Fatalf("the draft must still be made: %+v", res)
}
f.failMail = 0 // next run: the forward goes, the draft isn't made twice
if fw := forwards(run(t, in)); len(fw) != 1 || len(f.docs["Purchase Invoice"]) != 1 {
t.Fatalf("retry %+v", fw)
}
}
func TestDatevAnswersAndBouncesBecomeTodos(t *testing.T) {
f, in := setupDatev(t)
f.mail("c1", "DATEV <noreply@service.datev.de>")
f.mail("c2", "Mail Delivery System <MAILER-DAEMON@mx.example>", "r.pdf")
res := run(t, in)
if len(res) != 2 {
t.Fatalf("results %+v", res)
}
if !strings.HasPrefix(res[0].Reason, "Nachricht von DATEV") || !strings.HasPrefix(res[1].Reason, "Unzustellbar") {
t.Errorf("reasons %q / %q", res[0].Reason, res[1].Reason)
}
if len(f.docs["Purchase Invoice"]) != 0 || len(f.docs["E Invoice Import"]) != 0 {
t.Error("no drafts for automatic answers")
}
}
func TestDatevConfigNeedsSenderAndStart(t *testing.T) {
base := Config{BaseURL: "x", APIKey: "k", APISecret: "s", EmailAccount: "e", Company: "c", DatevAddress: datevAddr}
if _, err := New(base); err == nil {
t.Error("want an error without sender and start date")
}
base.DatevSender, base.DatevSince = "invoice@breakpilot.com", time.Now()
if _, err := New(base); err != nil {
t.Error(err)
}
}