feat(erpsetup): outgoing e-invoices, payment by transfer, discount line #84
No files matched your search
@@ -177,10 +177,11 @@ var documentHTML = brand.Replace(`{%- set is_inv = doc.doctype == "Sales Invoice
|
||||
{%- set cust = doc.customer if doc.doctype != "Quotation" else doc.party_name -%}
|
||||
{%- set mandate = frappe.db.get_value("Customer", cust, ["sepa_mandate_reference", "sepa_mandate_type"], as_dict=1) if doc.doctype != "Quotation" or doc.quotation_to == "Customer" else None -%}
|
||||
{%- set sepa = doc.payment_schedule and doc.payment_schedule[0].mode_of_payment == "SEPA-Lastschrift" -%}
|
||||
{%- set transfer = doc.payment_schedule and doc.payment_schedule[0].mode_of_payment == "Überweisung" -%}
|
||||
{%- set tpl = doc.taxes_and_charges or "" -%}
|
||||
{%- set order_no = (doc.items[0].get("sales_order") if is_inv and doc.items else None) -%}
|
||||
{%- set service_start = doc.get("from_date") or doc.get("delivery_date") -%}
|
||||
{%- set units = doc.items | map(attribute="uom") | list if doc.items else [] -%}
|
||||
{%- set units = doc.items | selectattr("rate", "ge", 0) | map(attribute="uom") | list if doc.items else [] -%}
|
||||
{%- set interval = "monatlich" if units and units | select("equalto", "Monat") | list | length == units | length else ("jährlich" if units and units | select("equalto", "Jahr") | list | length == units | length else "") -%}
|
||||
{%- set has_mandate = mandate and mandate.sepa_mandate_reference -%}
|
||||
{%- set period_from = doc.get("from_date") or (doc.items[0].get("service_start_date") if doc.items else None) -%}
|
||||
@@ -295,6 +296,9 @@ Bitte sorgen Sie für ausreichende Kontodeckung.</p>
|
||||
{%- elif not is_inv and sepa %}
|
||||
{%- set term = frappe.db.get_value("Payment Term", doc.payment_schedule[0].payment_term, ["credit_days", "due_date_based_on"], as_dict=1) if doc.payment_schedule[0].payment_term else None -%}
|
||||
<p>Zahlungsart: SEPA-Lastschrift{% if term and term.credit_days and term.due_date_based_on == "Day(s) after invoice date" %}, Einzug {{ term.credit_days }} Tage nach Rechnungsdatum{% endif %}, {{ "gemäß erteiltem SEPA-Lastschriftmandat" if has_mandate else "nach Erteilung eines gültigen SEPA-Lastschriftmandats" }}.</p>
|
||||
{%- elif not is_inv and transfer %}
|
||||
{%- set term = frappe.db.get_value("Payment Term", doc.payment_schedule[0].payment_term, ["credit_days", "due_date_based_on"], as_dict=1) if doc.payment_schedule[0].payment_term else None -%}
|
||||
<p>Zahlungsart: Überweisung{% if term and term.credit_days and term.due_date_based_on == "Day(s) after invoice date" %}, zahlbar innerhalb von {{ term.credit_days }} Tagen nach Rechnungsdatum{% endif %}.</p>
|
||||
{%- endif %}
|
||||
{%- if doc.get("terms") %}<div class="muted">{{ doc.terms }}</div>{% endif %}
|
||||
<p class="muted">Vielen Dank für Ihr Vertrauen.</p>
|
||||
@@ -312,7 +316,7 @@ Bitte sorgen Sie für ausreichende Kontodeckung.</p>
|
||||
var invoiceMailHTML = brand.Replace(`<div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.6;color:$INK;">
|
||||
<p>Guten Tag,</p>
|
||||
<p>anbei erhalten Sie unsere Rechnung <b>{{ name }}</b> vom {{ frappe.utils.formatdate(posting_date) }} über <b>{{ frappe.utils.fmt_money(grand_total, currency=currency) }}</b>.</p>
|
||||
{% if payment_schedule and payment_schedule[0].mode_of_payment == "SEPA-Lastschrift" -%}
|
||||
{% if payment_schedule and payment_schedule[0].mode_of_payment == "SEPA-Lastschrift" and frappe.db.get_value("Customer", customer, "sepa_mandate_reference") -%}
|
||||
<p>Den Betrag ziehen wir am {{ frappe.utils.formatdate(due_date) }} per SEPA-Lastschrift ein. Die Einzelheiten stehen auf der Rechnung.</p>
|
||||
{%- else -%}
|
||||
<p>Bitte überweisen Sie den Betrag bis zum {{ frappe.utils.formatdate(due_date) }}.</p>
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
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 reverse-charge and export templates (AE, G with their VATEX code).
|
||||
// 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"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// commonCodes maps our records to codes. eu, export: the tax templates whose
|
||||
// names mark them as reverse charge (EU business) or export.
|
||||
func commonCodes(eu, export []string) []commonCode {
|
||||
var ae, g []link
|
||||
for _, t := range eu {
|
||||
ae = append(ae, link{"Sales Taxes and Charges Template", t})
|
||||
}
|
||||
for _, t := range export {
|
||||
g = append(g, link{"Sales Taxes and Charges Template", t})
|
||||
}
|
||||
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, "G", "Free export item, VAT not charged", g},
|
||||
{listVATEX, "vatex-eu-ae", "Reverse charge", ae},
|
||||
{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
|
||||
}
|
||||
}
|
||||
eu, export, err := r.taxTemplates(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range commonCodes(eu, export) {
|
||||
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 into reverse charge
|
||||
// (EU business) and export, by name.
|
||||
func (r *runner) taxTemplates(ctx context.Context) (eu, export []string, err error) {
|
||||
rows, err := r.list(ctx, "Sales Taxes and Charges Template", [][]any{{"company", "=", companyName}}, []string{"name"})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
name := fmt.Sprint(row["name"])
|
||||
switch {
|
||||
case strings.Contains(name, euTemplate):
|
||||
eu = append(eu, name)
|
||||
case strings.Contains(name, thirdCountry):
|
||||
export = append(export, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(eu)
|
||||
sort.Strings(export)
|
||||
return eu, export, 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
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package erpsetup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// codes returns list → code → sorted "doctype:name" links of the fake's Common Codes.
|
||||
func codes(f *fakeFrappe) map[string]map[string][]string {
|
||||
out := map[string]map[string][]string{}
|
||||
for _, d := range f.docs["Common Code"] {
|
||||
list, code := fmt.Sprint(d["code_list"]), fmt.Sprint(d["common_code"])
|
||||
if out[list] == nil {
|
||||
out[list] = map[string][]string{}
|
||||
}
|
||||
links := []string{}
|
||||
for _, row := range d["applies_to"].([]any) {
|
||||
m := row.(map[string]any)
|
||||
links = append(links, fmt.Sprintf("%s:%s", m["link_doctype"], m["link_name"]))
|
||||
}
|
||||
sort.Strings(links)
|
||||
out[list][code] = links
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestEInvoiceSetup(t *testing.T) {
|
||||
f := newFake()
|
||||
srv := httptest.NewServer(f)
|
||||
defer srv.Close()
|
||||
if _, err := Run(context.Background(), cfg(srv.URL)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := codes(f)
|
||||
want := map[string]map[string]string{
|
||||
listUnits: {"MON": "UOM:Monat", "ANN": "UOM:Jahr", "C62": "UOM:Prüfung,UOM:Stück"},
|
||||
listPayment: {"58": "Mode of Payment:Überweisung,Payment Terms Template:Überweisung 21 Tage", "59": "Mode of Payment:SEPA-Lastschrift,Payment Terms Template:SEPA-Lastschrift 21 Tage"},
|
||||
listTaxCat: {"AE": "Sales Taxes and Charges Template:Reverse Charge an Unternehmen in der EU - BG", "G": "Sales Taxes and Charges Template:Leistung an Unternehmen im Drittland - BG"},
|
||||
listVATEX: {"vatex-eu-ae": "Sales Taxes and Charges Template:Reverse Charge an Unternehmen in der EU - BG", "vatex-eu-g": "Sales Taxes and Charges Template:Leistung an Unternehmen im Drittland - BG"},
|
||||
}
|
||||
for list, byCode := range want {
|
||||
if f.docs["Code List"][list] == nil {
|
||||
t.Errorf("code list %s missing", list)
|
||||
}
|
||||
for code, links := range byCode {
|
||||
w := strings.Split(links, ",")
|
||||
sort.Strings(w)
|
||||
if strings.Join(got[list][code], ",") != strings.Join(w, ",") {
|
||||
t.Errorf("%s %s: got %v, want %v", list, code, got[list][code], w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mop := f.docs["Mode of Payment"][modeTransfer]
|
||||
if mop == nil || mop["type"] != "Bank" {
|
||||
t.Fatalf("mode of payment %v", mop)
|
||||
}
|
||||
accts := mop["accounts"].([]any)
|
||||
if len(accts) != 1 || accts[0].(map[string]any)["default_account"] != "1800 - Bank - BG" {
|
||||
t.Errorf("transfer account rows %v", accts)
|
||||
}
|
||||
tpl := f.docs["Payment Terms Template"][paymentTransfer21]
|
||||
term := tpl["terms"].([]any)[0].(map[string]any)
|
||||
if term["credit_days"] != float64(21) || term["mode_of_payment"] != modeTransfer {
|
||||
t.Errorf("transfer terms %v", term)
|
||||
}
|
||||
|
||||
item := f.docs["Item"][discountItem]
|
||||
if item["is_sales_item"] != float64(1) || item["is_stock_item"] != float64(0) {
|
||||
t.Errorf("discount item %v", item)
|
||||
}
|
||||
row := item["item_defaults"].([]any)[0].(map[string]any)
|
||||
if row["income_account"] != "4700 - Erlösschmälerungen - BG" || row["selling_cost_center"] != "Verwaltung - BG" {
|
||||
t.Errorf("discount item defaults %v", row)
|
||||
}
|
||||
|
||||
s := f.docs["E Invoice Settings"]["E Invoice Settings"]
|
||||
if s["error_action_on_save"] != "Warning Message" || s["error_action_on_submit"] != "Error Message" ||
|
||||
fmt.Sprint(s["validate_sales_invoice_on_submit"]) != "1" {
|
||||
t.Errorf("settings %v", s)
|
||||
}
|
||||
if ps := f.docs["Property Setter"]["Customer-einvoice_profile-default"]; ps == nil || ps["value"] != "EN 16931" {
|
||||
t.Errorf("profile default %v", ps)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEInvoiceWithoutBankAccountIsReported(t *testing.T) {
|
||||
f := newFake()
|
||||
delete(f.docs, "Bank Account")
|
||||
delete(f.docs["Account"], "4700 - Erlösschmälerungen - BG")
|
||||
srv := httptest.NewServer(f)
|
||||
defer srv.Close()
|
||||
steps, err := Run(context.Background(), cfg(srv.URL))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
results := map[string]string{}
|
||||
for _, s := range steps {
|
||||
results[s.What] = s.Result
|
||||
}
|
||||
if r := results["mode of payment "+modeTransfer+" → company bank account"]; !strings.HasPrefix(r, "missing") {
|
||||
t.Errorf("bank account step: %q", r)
|
||||
}
|
||||
if r := results["item "+discountItem+" income account "+discountAccount]; r != "missing (not created)" {
|
||||
t.Errorf("discount account step: %q", r)
|
||||
}
|
||||
if f.docs["Mode of Payment"][modeTransfer]["accounts"] != nil {
|
||||
t.Error("no account row without a bank account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangedTaxTemplatesUpdateTheCodes(t *testing.T) {
|
||||
f := newFake()
|
||||
srv := httptest.NewServer(f)
|
||||
defer srv.Close()
|
||||
if _, err := Run(context.Background(), cfg(srv.URL)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.docs["Sales Taxes and Charges Template"]["EU B2B an Unternehmen in der EU 2 - BG"] = map[string]any{"name": "EU B2B an Unternehmen in der EU 2 - BG", "company": companyName}
|
||||
steps, err := Run(context.Background(), cfg(srv.URL))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated := 0
|
||||
for _, s := range steps {
|
||||
if s.Result == "updated" {
|
||||
updated++
|
||||
if !strings.HasPrefix(s.What, "code AE") && !strings.HasPrefix(s.What, "code vatex-eu-ae") {
|
||||
t.Errorf("unexpected update %s", s.What)
|
||||
}
|
||||
}
|
||||
}
|
||||
if updated != 2 || len(codes(f)[listTaxCat]["AE"]) != 2 {
|
||||
t.Errorf("updated %d, AE links %v", updated, codes(f)[listTaxCat]["AE"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintAndMailKnowTheTransfer(t *testing.T) {
|
||||
if !strings.Contains(documentHTML, `Zahlungsart: Überweisung`) || !strings.Contains(documentHTML, `"Überweisung"`) {
|
||||
t.Error("offers and orders print no transfer line")
|
||||
}
|
||||
// The discount line (negative rate) must not turn "monatlich" off.
|
||||
if !strings.Contains(documentHTML, `selectattr("rate", "ge", 0) | map(attribute="uom")`) {
|
||||
t.Error("billing interval counts the discount line")
|
||||
}
|
||||
// Without a mandate the mail asks for a transfer, even when SEPA is the mode.
|
||||
if !strings.Contains(invoiceMailHTML, `frappe.db.get_value("Customer", customer, "sepa_mandate_reference")`) {
|
||||
t.Error("invoice mail announces a debit without a mandate")
|
||||
}
|
||||
}
|
||||
@@ -176,6 +176,11 @@ func Run(ctx context.Context, cfg Config) ([]Step, error) {
|
||||
if err := r.intake(ctx); err != nil {
|
||||
return r.steps, err
|
||||
}
|
||||
// Outgoing e-invoices: codes, payment by transfer, the discount line,
|
||||
// validation (einvoice.go). After intake: it uses the unit Stück.
|
||||
if err := r.einvoice(ctx); err != nil {
|
||||
return r.steps, err
|
||||
}
|
||||
for _, w := range webhooks(cfg.WebhookURL, cfg.WebhookSecret) {
|
||||
if err := r.ensureWebhook(ctx, w); err != nil {
|
||||
return r.steps, err
|
||||
|
||||
@@ -25,14 +25,24 @@ type fakeFrappe struct {
|
||||
}
|
||||
|
||||
// newFake starts with what every ERPNext site has: the company (with its
|
||||
// abbreviation) and the SKR04 accounts erpsetup looks up (3900, 6300).
|
||||
// abbreviation), the SKR04 accounts erpsetup looks up (3900, 6300, 4700),
|
||||
// the company bank account, the tax templates and the e-invoice settings.
|
||||
func newFake() *fakeFrappe {
|
||||
return &fakeFrappe{docs: map[string]map[string]map[string]any{
|
||||
"Company": {companyName: {"name": companyName, "company_name": companyName, "abbr": "BG"}},
|
||||
"Account": {
|
||||
"3900 - Passive Rechnungsabgrenzung - BG": {"name": "3900 - Passive Rechnungsabgrenzung - BG", "account_number": "3900", "company": companyName},
|
||||
"6300 - Sonstige betriebliche Aufwendungen - BG": {"name": "6300 - Sonstige betriebliche Aufwendungen - BG", "account_number": "6300", "company": companyName},
|
||||
"4700 - Erlösschmälerungen - BG": {"name": "4700 - Erlösschmälerungen - BG", "account_number": "4700", "company": companyName},
|
||||
},
|
||||
"Bank Account": {"Geschäftskonto - Sparkasse": {"name": "Geschäftskonto - Sparkasse", "company": companyName, "is_company_account": 1, "disabled": 0,
|
||||
"account": "1800 - Bank - BG", "iban": "DE00TEST"}},
|
||||
"Sales Taxes and Charges Template": {
|
||||
"Umsatzsteuer 19% - BG": {"name": "Umsatzsteuer 19% - BG", "company": companyName},
|
||||
"Reverse Charge an Unternehmen in der EU - BG": {"name": "Reverse Charge an Unternehmen in der EU - BG", "company": companyName},
|
||||
"Leistung an Unternehmen im Drittland - BG": {"name": "Leistung an Unternehmen im Drittland - BG", "company": companyName},
|
||||
},
|
||||
"E Invoice Settings": {"E Invoice Settings": {"name": "E Invoice Settings"}},
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -87,7 +97,11 @@ func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
if match {
|
||||
out = append(out, map[string]any{"name": name})
|
||||
row := map[string]any{"name": name}
|
||||
for k, v := range d {
|
||||
row[k] = v
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": out})
|
||||
|
||||
Reference in new issue
Block a user