Files
tenant-registry/internal/invoiceintake/datev.go
T
sharang 286f50c5fb
ci / shared (push) Successful in 12s
ci / test (push) Successful in 26m6s
ci / image (push) Successful in 39s
feat(invoiceintake): send every invoice mail on to DATEV from invoice@ (#110)
2026-11-02 11:59:00 +00:00

166 lines
5.1 KiB
Go

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
}