Files
sharangandClaude Opus 5.5 f024a4042d
ci / shared (push) Successful in 15s
ci / test (push) Successful in 25m38s
ci / image (push) Successful in 37s
fix(erpsetup): deliveries of goods to EU businesses are K, not AE (#86)
Lieferung an Unternehmen in der EU is an intra-community supply: tax category K with VATEX vatex-eu-ic; Sonstige Leistung an Unternehmen in der EU (services) stays AE. Found in the live dry run of 2026-10-20.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:25:58 +00:00

457 lines
16 KiB
Go

package erpsetup
// Outgoing e-invoices (backlog #16, VD-04) with eu_einvoice v15.16.2 on
// ERPNext 15.112. The app looks codes up in ERPNext's Code Lists by their
// URN; anything unmapped falls back to a default (unit C62, payment means
// ZZZ, tax category S). What is set here:
// - the codes our documents use, mapped to our records: units (Monat →
// MON, Jahr → ANN, Prüfung/Stück → C62), payment means (Überweisung →
// 58 SEPA credit transfer, SEPA-Lastschrift → 59) and tax categories of
// the EU and non-EU templates with their VATEX code: services to EU
// businesses AE (reverse charge), goods to EU businesses K
// (intra-community supply), non-EU G.
// G for services to non-EU businesses is a stand-in: the precise "O"
// (not subject to VAT) forbids the seller VAT ID, which eu_einvoice
// always sends (BR-O-02). Ask the tax advisor before the first one.
// Only these codes are created, not the full lists (ERPNext 15.112 no
// longer imports a list from a URL).
// - "Überweisung 21 Tage": bank transfer with the same 21 days as the
// direct debit, for customers without a signed mandate (decided
// 2026-10-20). Its Mode of Payment points at the company bank account,
// so the e-invoice carries our IBAN (required for code 58).
// - the item RABATT: a discount is a negative line, not a document
// discount, which eu_einvoice cannot carry (it would fold it into the
// line prices, so XML and PDF would disagree). Revenue reduction on
// SKR04 4700 when the chart has it.
// - E Invoice Settings: check on save (warning), block on submit.
// - new customers default to the profile EN 16931 (eu_einvoice: EXTENDED).
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
)
const (
modeTransfer = "Überweisung"
paymentTransfer21 = "Überweisung 21 Tage"
discountItem = "RABATT"
discountAccount = "4700" // SKR04 Erlösschmälerungen
defaultProfile = "EN 16931"
listUnits = "urn:xoev-de:kosit:codeliste:rec20_3"
listPayment = "urn:xoev-de:xrechnung:codeliste:untdid.4461_3"
listTaxCat = "urn:xoev-de:kosit:codeliste:untdid.5305_3"
listVATEX = "urn:xoev-de:kosit:codeliste:vatex_1"
euTemplate = "an Unternehmen in der EU" // as the print format reads the tax templates
thirdCountry = "Drittland"
delivery = "Lieferung" // goods, as opposed to "Sonstige Leistung" (services)
)
type codeList struct{ Name, Title string }
func codeLists() []codeList {
return []codeList{
{listUnits, "Rec 20 Units of Measure"},
{listPayment, "UNTDID 4461 Payment means"},
{listTaxCat, "UNTDID 5305 Duty/tax/fee category"},
{listVATEX, "VAT exemption reason (VATEX)"},
}
}
// link is one row of a Common Code's Applies To table.
type link struct{ Doctype, Name string }
type commonCode struct {
List, Code, Title string
AppliesTo []link
}
// taxGroups are the company's sales tax templates that are not the domestic
// standard rate (code S, eu_einvoice's default), sorted by what their names
// say: services to EU businesses (reverse charge, AE), deliveries of goods
// to EU businesses (intra-community supply, K) and anything to non-EU
// countries (G).
type taxGroups struct{ reverse, intraEU, export []string }
func templateLinks(names []string) []link {
out := make([]link, 0, len(names))
for _, t := range names {
out = append(out, link{"Sales Taxes and Charges Template", t})
}
return out
}
// commonCodes maps our records to codes.
func commonCodes(t taxGroups) []commonCode {
ae, k, g := templateLinks(t.reverse), templateLinks(t.intraEU), templateLinks(t.export)
return []commonCode{
{listUnits, "MON", "month", []link{{"UOM", "Monat"}}},
{listUnits, "ANN", "year", []link{{"UOM", "Jahr"}}},
{listUnits, "C62", "one", []link{{"UOM", "Prüfung"}, {"UOM", intakeUOM}}},
{listPayment, "58", "SEPA credit transfer", []link{{"Mode of Payment", modeTransfer}, {"Payment Terms Template", paymentTransfer21}}},
{listPayment, "59", "SEPA direct debit", []link{{"Mode of Payment", "SEPA-Lastschrift"}, {"Payment Terms Template", paymentTerms21}}},
{listTaxCat, "AE", "VAT Reverse Charge", ae},
{listTaxCat, "K", "VAT exempt for EEA intra-community supply of goods and services", k},
{listTaxCat, "G", "Free export item, VAT not charged", g},
{listVATEX, "vatex-eu-ae", "Reverse charge", ae},
{listVATEX, "vatex-eu-ic", "Intra-community supply", k},
{listVATEX, "vatex-eu-g", "Export outside the EU", g},
}
}
func transferTermDoc() map[string]any {
return map[string]any{
"doctype": "Payment Term", "name": paymentTransfer21, "payment_term_name": paymentTransfer21,
"invoice_portion": 100, "mode_of_payment": modeTransfer,
"due_date_based_on": "Day(s) after invoice date", "credit_days": 21,
"description": "Zahlbar per Überweisung innerhalb von 21 Tagen nach Rechnungsdatum.",
}
}
func transferTemplateDoc() map[string]any {
return map[string]any{
"doctype": "Payment Terms Template", "name": paymentTransfer21, "template_name": paymentTransfer21,
"terms": []map[string]any{{
"payment_term": paymentTransfer21, "invoice_portion": 100, "mode_of_payment": modeTransfer,
"due_date_based_on": "Day(s) after invoice date", "credit_days": 21,
"description": "Zahlbar per Überweisung innerhalb von 21 Tagen nach Rechnungsdatum.",
}},
}
}
func discountItemDoc() map[string]any {
return map[string]any{
"doctype": "Item", "name": discountItem, "item_code": discountItem, "item_name": "Rabatt",
"description": "Rabatt", "item_group": itemGroup, "stock_uom": intakeUOM,
"is_stock_item": 0, "is_sales_item": 1, "is_purchase_item": 0, "include_item_in_manufacturing": 0,
}
}
func einvoiceSettingsDoc() map[string]any {
return map[string]any{
"doctype": "E Invoice Settings", "name": "E Invoice Settings",
"validate_sales_invoice_on_save": 1, "error_action_on_save": "Warning Message",
"validate_sales_invoice_on_submit": 1, "error_action_on_submit": "Error Message",
}
}
func profileDefaultSetter() map[string]any {
return map[string]any{
"doctype": "Property Setter", "name": "Customer-einvoice_profile-default",
"doctype_or_field": "DocField", "doc_type": "Customer", "field_name": "einvoice_profile",
"property": "default", "property_type": "Text", "value": defaultProfile,
}
}
func (r *runner) einvoice(ctx context.Context) error {
// Payment by transfer.
if err := r.ensure(ctx, "Mode of Payment", modeTransfer, "mode of payment "+modeTransfer,
map[string]any{"doctype": "Mode of Payment", "name": modeTransfer, "mode_of_payment": modeTransfer, "type": "Bank", "enabled": 1}); err != nil {
return err
}
if err := r.transferAccount(ctx); err != nil {
return err
}
if err := r.ensure(ctx, "Payment Term", paymentTransfer21, "payment term "+paymentTransfer21, transferTermDoc()); err != nil {
return err
}
if err := r.ensure(ctx, "Payment Terms Template", paymentTransfer21, "payment terms template "+paymentTransfer21, transferTemplateDoc()); err != nil {
return err
}
// Discount as a line.
if err := r.ensure(ctx, "Item", discountItem, "item "+discountItem+" (discount line)", discountItemDoc()); err != nil {
return err
}
if err := r.discountAccounting(ctx); err != nil {
return err
}
// Codes.
for _, l := range codeLists() {
if err := r.ensure(ctx, "Code List", l.Name, "code list "+l.Title,
map[string]any{"doctype": "Code List", "name": l.Name, "__newname": l.Name, "title": l.Title}); err != nil {
return err
}
}
groups, err := r.taxTemplates(ctx)
if err != nil {
return err
}
for _, c := range commonCodes(groups) {
if err := r.ensureCommonCode(ctx, c); err != nil {
return err
}
}
if err := r.ensureFields(ctx, "E Invoice Settings", "E Invoice Settings", "e-invoice validation (warn on save, block on submit)", einvoiceSettingsDoc(),
"validate_sales_invoice_on_save", "error_action_on_save", "validate_sales_invoice_on_submit", "error_action_on_submit"); err != nil {
return err
}
ps := profileDefaultSetter()
return r.ensureValue(ctx, "Property Setter", ps["name"].(string), "new customers' e-invoice profile "+defaultProfile, ps)
}
// list returns the rows matching filters (first page of 500).
func (r *runner) list(ctx context.Context, doctype string, filters [][]any, fields []string) ([]map[string]any, error) {
f, _ := json.Marshal(filters)
fl, _ := json.Marshal(fields)
q := url.Values{"filters": {string(f)}, "fields": {string(fl)}, "limit_page_length": {"500"}}
status, body, err := r.call(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(doctype)+"?"+q.Encode(), nil)
if err != nil {
return nil, err
}
if status != http.StatusOK {
return nil, fmt.Errorf("erpsetup: list %s: HTTP %d %s", doctype, status, truncate(body))
}
var out struct {
Data []map[string]any `json:"data"`
}
if err := json.Unmarshal(body, &out); err != nil {
return nil, fmt.Errorf("erpsetup: decode %s list: %w", doctype, err)
}
return out.Data, nil
}
// taxTemplates sorts the company's sales tax templates by name (taxGroups).
func (r *runner) taxTemplates(ctx context.Context) (taxGroups, error) {
var t taxGroups
rows, err := r.list(ctx, "Sales Taxes and Charges Template", [][]any{{"company", "=", companyName}}, []string{"name"})
if err != nil {
return t, err
}
for _, row := range rows {
name := fmt.Sprint(row["name"])
switch {
case strings.Contains(name, euTemplate) && strings.HasPrefix(name, delivery):
t.intraEU = append(t.intraEU, name)
case strings.Contains(name, euTemplate):
t.reverse = append(t.reverse, name)
case strings.Contains(name, thirdCountry):
t.export = append(t.export, name)
}
}
sort.Strings(t.reverse)
sort.Strings(t.intraEU)
sort.Strings(t.export)
return t, nil
}
// transferAccount links the Mode of Payment Überweisung to the GL account of
// the company's bank account, which is how eu_einvoice finds our IBAN.
func (r *runner) transferAccount(ctx context.Context) error {
what := "mode of payment " + modeTransfer + " → company bank account"
banks, err := r.list(ctx, "Bank Account", [][]any{{"company", "=", companyName}, {"is_company_account", "=", 1}, {"disabled", "=", 0}},
[]string{"name", "account", "iban"})
if err != nil {
return err
}
var account string
for _, b := range banks {
if s := fmt.Sprint(b["account"]); b["account"] != nil && s != "" && b["iban"] != nil && fmt.Sprint(b["iban"]) != "" {
if account != "" && account != s {
r.record(what, "ambiguous (several company bank accounts; not set)")
return nil
}
account = s
}
}
if account == "" {
// Without it the e-invoice has no IBAN, which code 58 requires.
r.record(what, "missing (no company Bank Account with IBAN and GL account)")
return nil
}
return r.ensureChildRow(ctx, "Mode of Payment", modeTransfer, "accounts", what,
map[string]any{"company": companyName}, map[string]any{"default_account": account})
}
// discountAccounting puts the discount on the revenue-reduction account and
// the administration cost center.
func (r *runner) discountAccounting(ctx context.Context) error {
abbr, err := r.companyAbbr(ctx)
if err != nil {
return err
}
want := map[string]any{"selling_cost_center": ccVerwaltung + " - " + abbr}
what := "item " + discountItem + " cost center " + ccVerwaltung
account, err := r.findAccount(ctx, discountAccount)
if err != nil {
return err
}
if account == "" {
r.record("item "+discountItem+" income account "+discountAccount, "missing (not created)")
} else {
want["income_account"] = account
what += ", income account " + discountAccount
}
return r.ensureChildRow(ctx, "Item", discountItem, "item_defaults", what, map[string]any{"company": companyName}, want)
}
// ensureChildRow makes the row of a child table that matches key carry the
// wanted values, adding the row if there is none. Other rows and fields stay.
func (r *runner) ensureChildRow(ctx context.Context, doctype, name, table, what string, key, want map[string]any) error {
path := "/api/resource/" + url.PathEscape(doctype) + "/" + url.PathEscape(name)
status, body, err := r.call(ctx, http.MethodGet, path, nil)
if err != nil {
return err
}
if status == http.StatusNotFound && r.cfg.DryRun {
r.record(what, "would update") // the doc is created by a step before
return nil
}
if status != http.StatusOK {
return fmt.Errorf("erpsetup: GET %s %q: HTTP %d", doctype, name, status)
}
var cur struct {
Data map[string]any `json:"data"`
}
_ = json.Unmarshal(body, &cur)
var rows []map[string]any
if raw, ok := cur.Data[table].([]any); ok {
for _, x := range raw {
if m, ok := x.(map[string]any); ok {
rows = append(rows, m)
}
}
}
matches := func(row map[string]any) bool {
for k, v := range key {
if fmt.Sprint(row[k]) != fmt.Sprint(v) {
return false
}
}
return true
}
found, changed := false, false
for _, row := range rows {
if matches(row) {
found = true
for k, v := range want {
if fmt.Sprint(row[k]) != fmt.Sprint(v) {
row[k], changed = v, true
}
}
}
}
if !found {
row := map[string]any{}
for k, v := range key {
row[k] = v
}
for k, v := range want {
row[k] = v
}
rows, changed = append(rows, row), true
}
if !changed {
r.record(what, "exists")
return nil
}
if r.cfg.DryRun {
r.record(what, "would update")
return nil
}
status, body, err = r.call(ctx, http.MethodPut, path, map[string]any{table: rows}) // the full table: rows left out would be deleted
if err != nil {
return err
}
if status/100 != 2 {
return fmt.Errorf("erpsetup: update %s: HTTP %d %s", what, status, truncate(body))
}
r.record(what, "updated")
return nil
}
// ensureCommonCode creates the code in its list, or sets its Applies To to
// exactly our links. Common Codes are hash-named, so they are found by list
// and code. A code without links is still created (it may serve as default).
func (r *runner) ensureCommonCode(ctx context.Context, c commonCode) error {
what := fmt.Sprintf("code %s %s", c.Code, c.Title)
if len(c.AppliesTo) > 0 {
var names []string
for _, l := range c.AppliesTo {
names = append(names, l.Name)
}
what += " → " + strings.Join(names, ", ")
}
rows := make([]map[string]any, 0, len(c.AppliesTo))
for _, l := range c.AppliesTo {
rows = append(rows, map[string]any{"link_doctype": l.Doctype, "link_name": l.Name})
}
found, err := r.list(ctx, "Common Code", [][]any{{"code_list", "=", c.List}, {"common_code", "=", c.Code}}, []string{"name"})
if err != nil {
return err
}
if len(found) == 0 {
if r.cfg.DryRun {
r.record(what, "would create")
return nil
}
status, body, err := r.call(ctx, http.MethodPost, "/api/resource/Common%20Code", map[string]any{
"doctype": "Common Code", "code_list": c.List, "common_code": c.Code, "title": c.Title, "applies_to": rows,
})
if err != nil {
return err
}
if status/100 != 2 {
return fmt.Errorf("erpsetup: create %s: HTTP %d %s", what, status, truncate(body))
}
r.record(what, "created")
return nil
}
name := fmt.Sprint(found[0]["name"])
path := "/api/resource/Common%20Code/" + url.PathEscape(name)
status, body, err := r.call(ctx, http.MethodGet, path, nil)
if err != nil {
return err
}
if status != http.StatusOK {
return fmt.Errorf("erpsetup: GET Common Code %q: HTTP %d", name, status)
}
var cur struct {
Data struct {
AppliesTo []map[string]any `json:"applies_to"`
} `json:"data"`
}
_ = json.Unmarshal(body, &cur)
if sameLinks(cur.Data.AppliesTo, c.AppliesTo) {
r.record(what, "exists")
return nil
}
if r.cfg.DryRun {
r.record(what, "would update")
return nil
}
status, body, err = r.call(ctx, http.MethodPut, path, map[string]any{"applies_to": rows})
if err != nil {
return err
}
if status/100 != 2 {
return fmt.Errorf("erpsetup: update %s: HTTP %d %s", what, status, truncate(body))
}
r.record(what, "updated")
return nil
}
func sameLinks(rows []map[string]any, want []link) bool {
key := func(dt, n any) string { return fmt.Sprint(dt) + "\x00" + fmt.Sprint(n) }
got := map[string]bool{}
for _, row := range rows {
got[key(row["link_doctype"], row["link_name"])] = true
}
if len(got) != len(want) {
return false
}
for _, l := range want {
if !got[key(l.Doctype, l.Name)] {
return false
}
}
return true
}