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>
420 lines
14 KiB
Go
420 lines
14 KiB
Go
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
|
|
}
|
|
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) {
|
|
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)
|
|
// 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
|
|
}
|
|
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))
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|