Frappe 15.112 lets a user without System Manager create a ToDo only when it is assigned to or by that user, so the service sets assigned_by to its own user (asked once via frappe.auth.get_logged_user). Mails from our own domain or a freemail address no supplier has were forwarded by a person: their ToDo says to enter the invoice by hand instead of suggesting a retry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
455 lines
16 KiB
Go
455 lines
16 KiB
Go
// 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
|
|
user string // the API key's ERPNext user (ToDo assigned_by)
|
|
}
|
|
|
|
// 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, forwarded, err := in.supplierFor(ctx, m.Sender)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
if supplier == "" && forwarded {
|
|
// The sender is us (or a freemail address): no supplier record can
|
|
// ever match it, so a retry would only repeat this ToDo.
|
|
return in.todo(ctx, res, "Weitergeleitete Rechnung ("+how+"). Eingangsrechnung von Hand aus der Anlage erfassen, dann diese Aufgabe schließen.")
|
|
}
|
|
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
|
|
}
|
|
me, err := in.self(ctx)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
// Frappe 15.112 lets a user without System Manager create a ToDo only if
|
|
// it is assigned to or by that user; the creator alone is not enough.
|
|
doc := map[string]any{
|
|
"description": "Rechnungseingang: " + reason,
|
|
"reference_type": "Communication",
|
|
"reference_name": res.Communication,
|
|
"priority": "Medium",
|
|
"assigned_by": me,
|
|
}
|
|
if in.cfg.AssignTo != "" {
|
|
doc["allocated_to"] = in.cfg.AssignTo
|
|
}
|
|
name, err := in.c.create(ctx, "ToDo", doc)
|
|
res.Document = name
|
|
return res, err
|
|
}
|
|
|
|
// self is the ERPNext user the API key belongs to, asked once.
|
|
func (in *Intake) self(ctx context.Context) (string, error) {
|
|
if in.user != "" {
|
|
return in.user, nil
|
|
}
|
|
var out struct {
|
|
Message string `json:"message"`
|
|
}
|
|
if err := in.c.do(ctx, http.MethodGet, "/api/method/frappe.auth.get_logged_user", nil, &out); err != nil {
|
|
return "", fmt.Errorf("logged user: %w", err)
|
|
}
|
|
if out.Message == "" {
|
|
return "", errors.New("logged user: empty answer")
|
|
}
|
|
in.user = out.Message
|
|
return in.user, nil
|
|
}
|
|
|
|
// 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. forwarded is true
|
|
// when the sender is our own domain, or a freemail address no supplier has:
|
|
// then the mail was forwarded by a person, and no supplier will ever match.
|
|
func (in *Intake) supplierFor(ctx context.Context, sender string) (supplier, how string, forwarded bool, err error) {
|
|
addr, err := mail.ParseAddress(sender)
|
|
if err != nil {
|
|
return "", "Absender nicht lesbar", false, nil
|
|
}
|
|
email := strings.ToLower(addr.Address)
|
|
domain := email[strings.LastIndex(email, "@")+1:]
|
|
for _, own := range in.cfg.OwnDomains {
|
|
if domain == strings.ToLower(own) {
|
|
return "", "aus eigener Domain", true, nil
|
|
}
|
|
}
|
|
s, err := in.suppliersMatching(ctx, "=", email)
|
|
if err != nil {
|
|
return "", "", false, err
|
|
}
|
|
if len(s) == 1 {
|
|
return s[0], "address", false, nil
|
|
}
|
|
if len(s) > 1 {
|
|
return "", "Adresse passt zu mehreren Lieferanten", false, nil
|
|
}
|
|
if freemail[domain] {
|
|
return "", "von einer Freemail-Adresse", true, nil
|
|
}
|
|
s, err = in.suppliersMatching(ctx, "like", "%@"+domain)
|
|
if err != nil {
|
|
return "", "", false, err
|
|
}
|
|
switch len(s) {
|
|
case 1:
|
|
return s[0], "domain", false, nil
|
|
case 0:
|
|
return "", "Absender-Domain " + domain + " keinem Lieferanten zugeordnet", false, nil
|
|
}
|
|
return "", "Domain " + domain + " passt zu mehreren Lieferanten", false, 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,
|
|
}
|