fix(invoiceintake): ToDos assigned by the intake user; forwarded invoices entered by hand (#83)
ci / shared (push) Successful in 14s
ci / test (push) Successful in 25m36s
ci / image (push) Successful in 36s

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>
This commit was merged in pull request #83.
This commit is contained in:
sharangandClaude Opus 5.5 committed 2026-10-20 09:01:45 +00:00
1 parent cee669d2bd
commit 8600c92e96
2 files changed
+74 -13

No files matched your search

+46 -13
View File
@@ -85,6 +85,7 @@ 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
@@ -200,10 +201,15 @@ func (in *Intake) one(ctx context.Context, m communication) (Result, error) {
return res, err
}
supplier, how, err := in.supplierFor(ctx, m.Sender)
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.")
}
@@ -291,11 +297,18 @@ func (in *Intake) todo(ctx context.Context, res Result, reason string) (Result,
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
@@ -305,46 +318,66 @@ func (in *Intake) todo(ctx context.Context, res Result, reason string) (Result,
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.
func (in *Intake) supplierFor(ctx context.Context, sender string) (string, string, error) {
// 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 "", "sender unreadable", 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 "", "weitergeleitet aus eigener Domain", nil
return "", "aus eigener Domain", true, nil
}
}
s, err := in.suppliersMatching(ctx, "=", email)
if err != nil {
return "", "", err
return "", "", false, err
}
if len(s) == 1 {
return s[0], "address", nil
return s[0], "address", false, nil
}
if len(s) > 1 {
return "", "Adresse passt zu mehreren Lieferanten", nil
return "", "Adresse passt zu mehreren Lieferanten", false, nil
}
if freemail[domain] {
return "", "Freemail-Absender", nil
return "", "von einer Freemail-Adresse", true, nil
}
s, err = in.suppliersMatching(ctx, "like", "%@"+domain)
if err != nil {
return "", "", err
return "", "", false, err
}
switch len(s) {
case 1:
return s[0], "domain", nil
return s[0], "domain", false, nil
case 0:
return "", "Absender-Domain " + domain + " keinem Lieferanten zugeordnet", nil
return "", "Absender-Domain " + domain + " keinem Lieferanten zugeordnet", false, nil
}
return "", "Domain " + domain + " passt zu mehreren Lieferanten", nil
return "", "Domain " + domain + " passt zu mehreren Lieferanten", false, nil
}
func (in *Intake) suppliersMatching(ctx context.Context, op, value string) ([]string, error) {
+28
View File
@@ -101,6 +101,10 @@ func (f *fakeERP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.URL.Path == "/api/method/frappe.auth.get_logged_user" {
_ = json.NewEncoder(w).Encode(map[string]any{"message": "bot@company.example"})
return
}
parts := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/api/resource/"), "/", 2)
doctype, _ := url.PathUnescape(parts[0])
reply := func(status int, v any) {
@@ -129,6 +133,11 @@ func (f *fakeERP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var doc map[string]any
_ = json.NewDecoder(r.Body).Decode(&doc)
f.writes = append(f.writes, "POST "+doctype)
// Frappe 15.112: a ToDo must be assigned to or by the creating user
if doctype == "ToDo" && doc["assigned_by"] != "bot@company.example" && doc["allocated_to"] != "bot@company.example" {
reply(http.StatusForbidden, map[string]any{"exc_type": "PermissionError"})
return
}
if m, ok := doc[markerField]; ok && len(f.find(doctype, [][]any{{markerField, "=", m}})) > 0 {
reply(http.StatusConflict, map[string]any{"exc_type": "DuplicateEntryError"})
return
@@ -389,3 +398,22 @@ func TestManyMailsArePagedAndChunked(t *testing.T) {
t.Fatalf("second run handled %d", len(res))
}
}
func TestForwardedMailsSayEnterByHand(t *testing.T) {
f, in := setup(t)
f.mail("c1", "Me <someone.else@breakpilot.com>", "r.pdf")
f.mail("c2", "other@gmail.com", "r.pdf")
f.mail("c3", "news@shop.example", "r.pdf")
res := run(t, in)
if len(res) != 3 {
t.Fatalf("results %+v", res)
}
for _, r := range res[:2] {
if !strings.HasPrefix(r.Reason, "Weitergeleitete Rechnung") || strings.Contains(r.Reason, "abbrechen") {
t.Errorf("%s: %q", r.Communication, r.Reason)
}
}
if !strings.HasPrefix(res[2].Reason, "Lieferant nicht erkannt") {
t.Errorf("unknown supplier: %q", res[2].Reason)
}
}