package invoiceintake import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "strconv" "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 " 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 { 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 } 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) { 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) // Like MariaDB: a filter on a child table joins it, and an unqualified // order_by column is then ambiguous (t53, "list Contact: HTTP 500"). if ob := r.URL.Query().Get("order_by"); !strings.HasPrefix(ob, "`tab"+doctype+"`.") { for _, flt := range filters { if len(flt) == 4 && flt[0] != doctype { reply(500, map[string]any{"exception": "pymysql.err.OperationalError: (1052, \"Column 'creation' in ORDER BY is ambiguous\")"}) return } } } 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") { msg := f.einvMsg if msg == "" { msg = "frappe.exceptions.ValidationError: No machine-readable data was found in the PDF file." } reply(f.einvErr, map[string]any{"exception": msg}) 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) } } // 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() 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 ", "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 ", "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 ", "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 TestEInvoiceWrongSyntaxIsPlainAtOnce(t *testing.T) { f, in := setup(t) f.einvErr = http.StatusInternalServerError f.einvMsg = "TypeError: Invalid XML, found tag {urn:oasis:names:specification:ubl:schema:xsd:Invoice-2}Invoice where {urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100}CrossIndustryInvoice was expected" f.mail("c1", "billing@hetzner.example", "ubl.xml") res := run(t, in) if len(res) != 1 || res[0].Outcome != Draft { t.Fatalf("results %+v", res) } if in.retries["c1"] != 0 { t.Errorf("retries %d", in.retries["c1"]) } } 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 ", "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) } } 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 ", "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 ", "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 ") f.mail("c2", "Mail Delivery System ", "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) } }