812 lines
30 KiB
Go
812 lines
30 KiB
Go
package erpsetup
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"net/url"
|
||
"strings"
|
||
"sync"
|
||
"testing"
|
||
|
||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||
)
|
||
|
||
// fakeFrappe keeps named docs per doctype and a list of webhooks.
|
||
type fakeFrappe struct {
|
||
mu sync.Mutex
|
||
docs map[string]map[string]map[string]any
|
||
webhooks []map[string]any
|
||
posts int
|
||
auth string
|
||
}
|
||
|
||
// newFake starts with what every ERPNext site has: the company (with its
|
||
// abbreviation), the SKR04 accounts erpsetup looks up (3900, 6300, 4700 and
|
||
// the travel expense accounts),
|
||
// 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},
|
||
"6663 - Reisekosten Arbeitnehmer Fahrtkosten - BG": {"name": "6663 - Reisekosten Arbeitnehmer Fahrtkosten - BG", "account_number": "6663", "company": companyName},
|
||
"6660 - Reisekosten Arbeitnehmer Übernachtungsaufwand - BG": {"name": "6660 - Reisekosten Arbeitnehmer Übernachtungsaufwand - BG", "account_number": "6660", "company": companyName},
|
||
"6650 - Reisekosten Arbeitnehmer - BG": {"name": "6650 - Reisekosten Arbeitnehmer - BG", "account_number": "6650", "company": companyName},
|
||
"6640 - Bewirtungskosten - BG": {"name": "6640 - Bewirtungskosten - BG", "account_number": "6640", "company": companyName},
|
||
"6600 - Werbekosten - BG": {"name": "6600 - Werbekosten - BG", "account_number": "6600", "company": companyName},
|
||
"6805 - Telefon - BG": {"name": "6805 - Telefon - BG", "account_number": "6805", "company": companyName},
|
||
"6815 - Bürobedarf - BG": {"name": "6815 - Bürobedarf - BG", "account_number": "6815", "company": companyName},
|
||
"6668 - Kilometergelderstattung Arbeitnehmer - BG": {"name": "6668 - Kilometergelderstattung Arbeitnehmer - BG", "account_number": "6668", "company": companyName},
|
||
"6664 - Reisekosten Arbeitnehmer Verpflegungsmehraufwand - BG": {"name": "6664 - Reisekosten Arbeitnehmer Verpflegungsmehraufwand - BG", "account_number": "6664", "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},
|
||
"Lieferung an Unternehmen in der EU - BG": {"name": "Lieferung an Unternehmen in der EU - BG", "company": companyName},
|
||
"Sonstige Leistung an Unternehmen in der EU - BG": {"name": "Sonstige Leistung an Unternehmen in der EU - BG", "company": companyName},
|
||
"Lieferung in Drittland - BG": {"name": "Lieferung in Drittland - BG", "company": companyName},
|
||
"Sonstige Leistung an Unternehmen in Drittland - BG": {"name": "Sonstige Leistung an Unternehmen in Drittland - BG", "company": companyName},
|
||
"Sonstige Leistung an nicht-Unternehmen in Drittland - BG": {"name": "Sonstige Leistung an nicht-Unternehmen in Drittland - BG", "company": companyName},
|
||
},
|
||
"E Invoice Settings": {"E Invoice Settings": {"name": "E Invoice Settings"}},
|
||
}}
|
||
}
|
||
|
||
func (f *fakeFrappe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||
f.mu.Lock()
|
||
defer f.mu.Unlock()
|
||
f.auth = r.Header.Get("Authorization")
|
||
if r.Header.Get("Authorization") != "token k:s" {
|
||
w.WriteHeader(http.StatusUnauthorized)
|
||
return
|
||
}
|
||
rest := strings.TrimPrefix(r.URL.Path, "/api/resource/")
|
||
parts := strings.SplitN(rest, "/", 2)
|
||
doctype, _ := url.PathUnescape(parts[0])
|
||
switch {
|
||
case doctype == "Webhook" && r.Method == http.MethodGet:
|
||
out := []map[string]any{}
|
||
for _, wh := range f.webhooks {
|
||
out = append(out, map[string]any{"name": wh["name"], "webhook_json": wh["webhook_json"], "condition": wh["condition"]})
|
||
}
|
||
_ = json.NewEncoder(w).Encode(map[string]any{"data": out})
|
||
case doctype == "Webhook" && r.Method == http.MethodPut:
|
||
name, _ := url.PathUnescape(parts[1])
|
||
var patch map[string]any
|
||
_ = json.NewDecoder(r.Body).Decode(&patch)
|
||
for _, wh := range f.webhooks {
|
||
if wh["name"] == name {
|
||
for k, v := range patch {
|
||
wh[k] = v
|
||
}
|
||
}
|
||
}
|
||
f.posts++
|
||
_, _ = io.WriteString(w, `{"data":{}}`)
|
||
case doctype == "Webhook" && r.Method == http.MethodPost:
|
||
var doc map[string]any
|
||
_ = json.NewDecoder(r.Body).Decode(&doc)
|
||
doc["name"] = "HOOK-" + string(rune('A'+len(f.webhooks)))
|
||
f.webhooks = append(f.webhooks, doc)
|
||
f.posts++
|
||
_ = json.NewEncoder(w).Encode(map[string]any{"data": doc})
|
||
case r.Method == http.MethodGet && len(parts) == 1:
|
||
// list with ["field", "=", value] filters
|
||
var filters [][]any
|
||
_ = json.Unmarshal([]byte(r.URL.Query().Get("filters")), &filters)
|
||
out := []map[string]any{}
|
||
for name, d := range f.docs[doctype] {
|
||
match := true
|
||
for _, c := range filters {
|
||
if fmt.Sprint(d[c[0].(string)]) != fmt.Sprint(c[2]) {
|
||
match = false
|
||
}
|
||
}
|
||
if match {
|
||
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})
|
||
case r.Method == http.MethodGet && len(parts) == 2:
|
||
name, _ := url.PathUnescape(parts[1])
|
||
if d, ok := f.docs[doctype][name]; ok {
|
||
_ = json.NewEncoder(w).Encode(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)
|
||
if f.docs[doctype] == nil {
|
||
f.docs[doctype] = map[string]map[string]any{}
|
||
}
|
||
if doctype == "File" { // Frappe derives the URL from the name and privacy
|
||
doc["file_url"] = "/private/files/" + doc["file_name"].(string)
|
||
}
|
||
name, _ := doc["name"].(string)
|
||
if name == "" {
|
||
name = fmt.Sprintf("%s-%d", doctype, len(f.docs[doctype])+1)
|
||
}
|
||
f.docs[doctype][name] = doc
|
||
f.posts++
|
||
_, _ = io.WriteString(w, `{"data":{}}`)
|
||
case r.Method == http.MethodPut && len(parts) == 2:
|
||
name, _ := url.PathUnescape(parts[1])
|
||
d, ok := f.docs[doctype][name]
|
||
if !ok {
|
||
w.WriteHeader(http.StatusNotFound)
|
||
return
|
||
}
|
||
var patch map[string]any
|
||
_ = json.NewDecoder(r.Body).Decode(&patch)
|
||
for k, v := range patch {
|
||
d[k] = v
|
||
}
|
||
f.posts++
|
||
_, _ = io.WriteString(w, `{"data":{}}`)
|
||
default:
|
||
w.WriteHeader(http.StatusTeapot)
|
||
}
|
||
}
|
||
|
||
func cfg(url string) Config {
|
||
return Config{BaseURL: url + "/", APIKey: "k", APISecret: "s", WebhookURL: "https://registry/v1/internal/erp/webhook", WebhookSecret: "whs"}
|
||
}
|
||
|
||
func TestRunCreatesThenIsIdempotent(t *testing.T) {
|
||
f := newFake()
|
||
srv := httptest.NewServer(f)
|
||
defer srv.Close()
|
||
|
||
steps, err := Run(context.Background(), cfg(srv.URL))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
first := f.posts
|
||
if first != len(steps) {
|
||
t.Fatalf("first run: %d steps, %d writes: %+v", len(steps), first, steps)
|
||
}
|
||
for _, s := range steps {
|
||
// The company exists on every site, so its fields are updated, as are
|
||
// the items the catalogue step created a moment before.
|
||
if s.Result != "created" && s.Result != "updated" {
|
||
t.Errorf("%s: %s", s.What, s.Result)
|
||
}
|
||
}
|
||
hook := f.webhooks[0]
|
||
if hook["enable_security"] != float64(1) || hook["webhook_secret"] != "whs" || hook["request_url"] != "https://registry/v1/internal/erp/webhook" {
|
||
t.Errorf("webhook security/url not set: %v", hook)
|
||
}
|
||
|
||
steps, err = Run(context.Background(), cfg(srv.URL))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if f.posts != first {
|
||
t.Fatalf("second run wrote %d more docs", f.posts-first)
|
||
}
|
||
for _, s := range steps {
|
||
if !strings.HasPrefix(s.Result, "exists") {
|
||
t.Errorf("second run %s: %s", s.What, s.Result)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestDryRunChangesNothing(t *testing.T) {
|
||
f := newFake()
|
||
srv := httptest.NewServer(f)
|
||
defer srv.Close()
|
||
c := cfg(srv.URL)
|
||
c.DryRun = true
|
||
var logged int
|
||
c.Log = func(string, ...any) { logged++ }
|
||
steps, err := Run(context.Background(), c)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if f.posts != 0 || logged != len(steps) {
|
||
t.Fatalf("dry run posted %d docs, logged %d of %d", f.posts, logged, len(steps))
|
||
}
|
||
for _, s := range steps {
|
||
if !strings.HasPrefix(s.Result, "would ") {
|
||
t.Errorf("%s: %s", s.What, s.Result)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestLeadDoctypeIsConfigurable(t *testing.T) {
|
||
f := newFake()
|
||
srv := httptest.NewServer(f)
|
||
defer srv.Close()
|
||
c := cfg(srv.URL)
|
||
c.LeadDoctype = "CRM Lead"
|
||
if _, err := Run(context.Background(), c); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, ok := f.docs["Custom Field"]["CRM Lead-tenant_id"]; !ok {
|
||
t.Fatalf("no CRM Lead field: %v", f.docs["Custom Field"])
|
||
}
|
||
}
|
||
|
||
func TestRequiredConfigAndAuthErrors(t *testing.T) {
|
||
if _, err := Run(context.Background(), Config{}); err == nil {
|
||
t.Fatal("empty config accepted")
|
||
}
|
||
if _, err := Run(context.Background(), Config{BaseURL: "x", APIKey: "k", APISecret: "s"}); err == nil {
|
||
t.Fatal("missing webhook config accepted")
|
||
}
|
||
srv := httptest.NewServer(newFake())
|
||
defer srv.Close()
|
||
c := cfg(srv.URL)
|
||
c.APISecret = "wrong"
|
||
if _, err := Run(context.Background(), c); err == nil || !strings.Contains(err.Error(), "API key") {
|
||
t.Fatalf("want an auth error, got %v", err)
|
||
}
|
||
}
|
||
|
||
func TestUnexpectedStatusStops(t *testing.T) {
|
||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
w.WriteHeader(http.StatusInternalServerError)
|
||
_, _ = io.WriteString(w, strings.Repeat("x", 400))
|
||
}))
|
||
defer srv.Close()
|
||
if _, err := Run(context.Background(), cfg(srv.URL)); err == nil {
|
||
t.Fatal("500 accepted")
|
||
}
|
||
}
|
||
|
||
func TestWebhookBodiesAreValidJSONShapes(t *testing.T) {
|
||
for _, w := range webhooks("u", "s") {
|
||
if !strings.Contains(w.JSON, `"event":"`+w.Event+`"`) || !strings.Contains(w.JSON, `"modified":"{{ doc.modified }}"`) {
|
||
t.Errorf("%s: template lacks event or modified: %s", w.Event, w.JSON)
|
||
}
|
||
if w.URL != "u" || w.Secret != "s" {
|
||
t.Errorf("%s: url/secret not filled", w.Event)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestWebhookDocIsNamed(t *testing.T) {
|
||
seen := map[string]bool{}
|
||
for _, w := range webhooks("https://r.test/hook", "s") {
|
||
name, _ := w.doc()["name"].(string)
|
||
if name != "breakpilot-"+w.Event || seen[name] {
|
||
t.Fatalf("webhook %s: name %q", w.Event, name)
|
||
}
|
||
seen[name] = true
|
||
}
|
||
}
|
||
|
||
// Every SKU the registry's catalogue sells exists as an item, with a unit that
|
||
// exists too, and the platform fee, Managed Git and its build runners are there for invoicing.
|
||
func TestCatalogueCoversTheRegistrySKUs(t *testing.T) {
|
||
want := []string{
|
||
"CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN", "CRA-CSA-CLD-TGT", "CRA-CSA-CLD-DAY",
|
||
"CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT",
|
||
"DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT",
|
||
"DEV-FWK-CLD-STD", "DEV-FWK-CLD-BUS", "DEV-FWK-CLD-ENT", "DEV-FWK-OPR-STD", "DEV-FWK-OPR-BUS", "DEV-FWK-OPR-ENT",
|
||
"PLT-CORE-CLD-STD", "PLT-CORE-CLD-BUS", "PLT-CORE-CLD-ENT", "PLT-BNDL-CLD-STD", "PLT-BNDL-CLD-ADD",
|
||
"INF-GIT-CLD-STD", "INF-GIT-CLD-BUS", "INF-GIT-CLD-ENT", "INF-GIT-CLD-USR", "INF-GIT-OPR-STD", "INF-GIT-OPR-BUS", "INF-GIT-OPR-ENT",
|
||
"INF-CI-CLD-STD", "INF-CI-CLD-BUS", "INF-CI-CLD-ENT", "INF-CI-OPR-STD", "INF-CI-OPR-BUS", "INF-CI-OPR-ENT",
|
||
}
|
||
units := map[string]bool{}
|
||
for _, u := range uoms() {
|
||
units[u["name"].(string)] = true
|
||
}
|
||
have := map[string]sku{}
|
||
for _, s := range skus() {
|
||
if _, dup := have[s.Code]; dup {
|
||
t.Errorf("duplicate %s", s.Code)
|
||
}
|
||
have[s.Code] = s
|
||
if !units[s.UOM] || s.Name == "" || s.Description == "" {
|
||
t.Errorf("incomplete item %+v", s)
|
||
}
|
||
d := itemDoc(s)
|
||
if d["is_stock_item"] != 0 || d["is_sales_item"] != 1 || d["item_group"] != itemGroup {
|
||
t.Errorf("item doc %v", d)
|
||
}
|
||
}
|
||
for _, code := range want {
|
||
if _, ok := have[code]; !ok {
|
||
t.Errorf("missing %s", code)
|
||
}
|
||
}
|
||
if len(have) != len(want) {
|
||
t.Errorf("%d items, want %d", len(have), len(want))
|
||
}
|
||
if f := sepaFields(); len(f) != 4 || f[3]["options"] != "\nBasislastschrift (CORE)\nFirmenlastschrift (B2B)" {
|
||
t.Errorf("sepa fields %v", f)
|
||
}
|
||
}
|
||
|
||
// A SKU added to the registry's catalogue must be added here too, or a sales
|
||
// order for it would find no item in ERPNext.
|
||
func TestCatalogueMatchesStoreDefaults(t *testing.T) {
|
||
have := map[string]bool{}
|
||
for _, s := range skus() {
|
||
have[s.Code] = true
|
||
}
|
||
for _, p := range store.DefaultProducts() {
|
||
for _, code := range p.SKUs {
|
||
if !have[code] {
|
||
t.Errorf("%s: SKU %s has no ERPNext item", p.Key, code)
|
||
}
|
||
}
|
||
for _, a := range p.Addons {
|
||
for _, code := range a.SKUs {
|
||
if !have[code] {
|
||
t.Errorf("%s/%s: SKU %s has no ERPNext item", p.Key, a.ID, code)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// A webhook created from an older template is updated in place, not
|
||
// duplicated; the dry run only reports it.
|
||
func TestOutdatedWebhookIsUpdated(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)
|
||
}
|
||
old := `{"event":"sales_order.submit","items":[{% for i in doc.items %}{% endfor %}]}`
|
||
f.webhooks[0]["webhook_json"] = old
|
||
hooks, posts := len(f.webhooks), f.posts
|
||
|
||
c := cfg(srv.URL)
|
||
c.DryRun = true
|
||
steps, err := Run(context.Background(), c)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if f.posts != posts || f.webhooks[0]["webhook_json"] != old {
|
||
t.Fatal("dry run changed something")
|
||
}
|
||
var reported bool
|
||
for _, s := range steps {
|
||
if strings.HasPrefix(s.Result, "would update") {
|
||
reported = true
|
||
}
|
||
}
|
||
if !reported {
|
||
t.Fatalf("dry run did not report the update: %+v", steps)
|
||
}
|
||
|
||
_, err = Run(context.Background(), cfg(srv.URL))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if len(f.webhooks) != hooks || f.posts != posts+1 {
|
||
t.Fatalf("webhooks %d (want %d), writes %d (want %d)", len(f.webhooks), hooks, f.posts, posts+1)
|
||
}
|
||
body := f.webhooks[0]["webhook_json"].(string)
|
||
if !strings.Contains(body, `doc["items"]`) || strings.Contains(body, "doc.items") {
|
||
t.Fatalf("not updated: %s", body)
|
||
}
|
||
}
|
||
|
||
// Frappe renders the templates with only doc (a dict) and utils.
|
||
func TestTemplatesUseOnlyDocAndUtils(t *testing.T) {
|
||
for _, w := range webhooks("u", "s") {
|
||
if strings.Contains(w.JSON, "frappe.") || strings.Contains(w.JSON, "doc.items") {
|
||
t.Errorf("%s: template uses names Frappe does not provide: %s", w.Event, w.JSON)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestInvoiceSeriesIsTheGoBDRange(t *testing.T) {
|
||
for _, ps := range invoiceSeriesSetters() {
|
||
if ps["value"] != "RE-.YYYY.-.####" || ps["doc_type"] != "Sales Invoice" || ps["field_name"] != "naming_series" {
|
||
t.Errorf("setter %v", ps)
|
||
}
|
||
}
|
||
}
|
||
|
||
// A number range someone changed back is set to RE-… again.
|
||
func TestInvoiceSeriesIsRestored(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["Property Setter"]["Sales Invoice-naming_series-options"]["value"] = "ACC-SINV-.YYYY.-"
|
||
steps, err := Run(context.Background(), cfg(srv.URL))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if f.docs["Property Setter"]["Sales Invoice-naming_series-options"]["value"] != "RE-.YYYY.-.####" {
|
||
t.Fatal("not restored")
|
||
}
|
||
var updated int
|
||
for _, s := range steps {
|
||
if s.Result == "updated" {
|
||
updated++
|
||
}
|
||
}
|
||
if updated != 1 {
|
||
t.Fatalf("updated %d steps: %+v", updated, steps)
|
||
}
|
||
}
|
||
|
||
func TestChangedTemplateIsUpdatedAndPricesKept(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["Print Format"][printFormatRE]["html"] = "old"
|
||
for _, p := range f.docs["Item Price"] {
|
||
p["price_list_rate"] = 1.0 // changed in ERPNext by hand
|
||
}
|
||
c := cfg(srv.URL)
|
||
c.DryRun = true
|
||
steps, err := Run(context.Background(), c)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
var changes []string
|
||
for _, s := range steps {
|
||
if !strings.HasPrefix(s.Result, "exists") {
|
||
changes = append(changes, s.What+": "+s.Result)
|
||
}
|
||
}
|
||
if len(changes) != 1 || !strings.Contains(changes[0], "print format "+printFormatRE) || !strings.HasSuffix(changes[0], "would update") {
|
||
t.Fatalf("dry run changes: %v", changes)
|
||
}
|
||
if _, err := Run(context.Background(), cfg(srv.URL)); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if f.docs["Print Format"][printFormatRE]["html"] != documentHTML {
|
||
t.Fatal("print format not updated")
|
||
}
|
||
for _, p := range f.docs["Item Price"] {
|
||
if p["price_list_rate"] != 1.0 {
|
||
t.Fatalf("price overwritten: %v", p)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Every SKU has a list price; only Prüfwerk Enterprise is 0 (Preis nach
|
||
// Vereinbarung).
|
||
func TestEverySKUHasAListPrice(t *testing.T) {
|
||
for _, s := range skus() {
|
||
if s.Price < 0 || (s.Price == 0) != (s.Code == "CRA-CSA-CLD-ENT") {
|
||
t.Errorf("%s: price %v", s.Code, s.Price)
|
||
}
|
||
}
|
||
}
|
||
|
||
// The catalogue after the freeze of the Leistungsbeschreibungen 1.0.0: list
|
||
// prices, the disabled items (still there for old documents), the new unit
|
||
// and the brand spelling.
|
||
func TestCatalogueFollowsLeistungsbeschreibung(t *testing.T) {
|
||
prices := map[string]float64{
|
||
"PLT-CORE-CLD-STD": 290, "PLT-CORE-CLD-BUS": 790, "PLT-CORE-CLD-ENT": 1990,
|
||
"PLT-BNDL-CLD-STD": 990, "PLT-BNDL-CLD-ADD": 499,
|
||
"CRA-CSA-CLD-STD": 490, "CRA-CSA-CLD-BUS": 1290, "CRA-CSA-CLD-ENT": 0,
|
||
"CRA-CSA-CLD-TGT": 5.99, "CRA-CSA-CLD-DAY": 9.99,
|
||
"DEV-WP-CLD-STD": 59, "DEV-FWK-CLD-STD": 89,
|
||
"INF-GIT-CLD-STD": 190, "INF-GIT-CLD-BUS": 390, "INF-GIT-CLD-ENT": 790, "INF-GIT-CLD-USR": 19,
|
||
"INF-CI-CLD-STD": 149, "INF-CI-CLD-BUS": 290, "INF-CI-CLD-ENT": 590,
|
||
}
|
||
disabled := map[string]bool{
|
||
"CRA-CSA-CLD-SCAN": true, "CRA-WBK-CLD-STD": true, "CRA-WBK-CLD-BUS": true, "CRA-WBK-CLD-ENT": true,
|
||
"DEV-WP-CLD-BUS": true, "DEV-WP-CLD-ENT": true, "DEV-FWK-CLD-BUS": true, "DEV-FWK-CLD-ENT": true,
|
||
}
|
||
units := map[string]bool{}
|
||
for _, u := range uoms() {
|
||
units[u["name"].(string)] = true
|
||
if u["must_be_whole_number"] != 1 {
|
||
t.Errorf("unit %v", u)
|
||
}
|
||
}
|
||
have := map[string]sku{}
|
||
for _, s := range skus() {
|
||
if _, dup := have[s.Code]; dup {
|
||
t.Errorf("duplicate %s", s.Code)
|
||
}
|
||
have[s.Code] = s
|
||
if !units[s.UOM] {
|
||
t.Errorf("%s: unit %q is not created", s.Code, s.UOM)
|
||
}
|
||
if s.Disabled != disabled[s.Code] {
|
||
t.Errorf("%s: disabled %v", s.Code, s.Disabled)
|
||
}
|
||
if want := boolInt(s.Disabled); itemDoc(s)["disabled"] != want {
|
||
t.Errorf("%s: item doc disabled %v", s.Code, itemDoc(s)["disabled"])
|
||
}
|
||
if strings.Contains(s.Name+s.Description, "BreakPilot") {
|
||
t.Errorf("%s: old brand spelling in %q / %q", s.Code, s.Name, s.Description)
|
||
}
|
||
// LB Plattform §2(3): the portal provides no invoices.
|
||
if strings.Contains(s.Name+s.Description, "Rechnung") {
|
||
t.Errorf("%s: item text mentions invoices: %q", s.Code, s.Description)
|
||
}
|
||
}
|
||
for code := range disabled {
|
||
if _, ok := have[code]; !ok {
|
||
t.Errorf("disabled %s is gone; old documents need it", code)
|
||
}
|
||
}
|
||
for code, want := range prices {
|
||
if s, ok := have[code]; !ok || s.Price != want {
|
||
t.Errorf("%s: price %v, want %v", code, s.Price, want)
|
||
}
|
||
}
|
||
if s := have["CRA-CSA-CLD-DAY"]; s.UOM != "Prüftag" {
|
||
t.Errorf("Prüftag unit: %+v", s)
|
||
}
|
||
if itemGroup != "BreakPilot Abonnements" {
|
||
t.Errorf("item group renamed: %q", itemGroup)
|
||
}
|
||
}
|
||
|
||
// fakeItemPrice is the list price (no customer) the fake holds for code.
|
||
func fakeItemPrice(f *fakeFrappe, code string) map[string]any {
|
||
for _, p := range f.docs["Item Price"] {
|
||
if p["item_code"] == code && p["customer"] == nil {
|
||
return p
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// -sync-catalog: the dry run reports every field it would change and writes
|
||
// nothing; the run updates name, description, disabled and the list price
|
||
// (not a customer's price) and is idempotent. Without it, only the
|
||
// description follows the catalogue.
|
||
func TestSyncCatalog(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)
|
||
}
|
||
// The ERP as before the freeze.
|
||
std, scan := f.docs["Item"]["CRA-CSA-CLD-STD"], f.docs["Item"]["CRA-CSA-CLD-SCAN"]
|
||
std["item_name"], std["description"] = "Prüfwerk alt", "alt"
|
||
scan["disabled"] = 0.0
|
||
fakeItemPrice(f, "CRA-CSA-CLD-STD")["price_list_rate"] = 1490.0
|
||
f.docs["Item Price"]["customer-price"] = map[string]any{"name": "customer-price", "item_code": "CRA-CSA-CLD-BUS",
|
||
"price_list": priceList, "price_list_rate": 100.0, "customer": "CUST-TEST"}
|
||
|
||
// Without the flag: the description is written, as on every run; name,
|
||
// disabled flag and price stay.
|
||
if _, err := Run(context.Background(), cfg(srv.URL)); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if std["description"] != have(t, "CRA-CSA-CLD-STD").Description || std["item_name"] != "Prüfwerk alt" || scan["disabled"] != 0.0 ||
|
||
fakeItemPrice(f, "CRA-CSA-CLD-STD")["price_list_rate"] != 1490.0 {
|
||
t.Fatalf("run without -sync-catalog: %v %v %v", std, scan, fakeItemPrice(f, "CRA-CSA-CLD-STD"))
|
||
}
|
||
std["description"] = "alt"
|
||
|
||
c := cfg(srv.URL)
|
||
c.SyncCatalog, c.DryRun = true, true
|
||
posts := f.posts
|
||
steps, err := Run(context.Background(), c)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if f.posts != posts || std["item_name"] != "Prüfwerk alt" || fakeItemPrice(f, "CRA-CSA-CLD-STD")["price_list_rate"] != 1490.0 {
|
||
t.Fatal("dry run changed something")
|
||
}
|
||
reports := map[string]string{}
|
||
for _, s := range steps {
|
||
if !strings.HasPrefix(s.Result, "exists") {
|
||
reports[s.What] = s.Result
|
||
}
|
||
}
|
||
for what, want := range map[string]string{
|
||
"item CRA-CSA-CLD-STD (Prüfwerk Cloud – Standard)": `would update: item_name "Prüfwerk alt" → "Prüfwerk Cloud – Standard"; description "alt" → "Automatisierte`,
|
||
"item CRA-CSA-CLD-SCAN (Prüfwerk – Zusätzliche Prüfung)": "would update: disabled 0 → 1",
|
||
"price CRA-CSA-CLD-STD (Standard Selling, 490.00 EUR/Monat)": "price_list_rate 1490 → 490",
|
||
} {
|
||
if !strings.Contains(reports[what], want) {
|
||
t.Errorf("%s: %q, want %q", what, reports[what], want)
|
||
}
|
||
delete(reports, what)
|
||
}
|
||
if len(reports) != 0 {
|
||
t.Errorf("unexpected changes: %v", reports)
|
||
}
|
||
|
||
c.DryRun = false
|
||
if _, err := Run(context.Background(), c); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if std["item_name"] != "Prüfwerk Cloud – Standard" || std["description"] != have(t, "CRA-CSA-CLD-STD").Description || scan["disabled"] != float64(1) {
|
||
t.Fatalf("items not synced: %v %v", std, scan)
|
||
}
|
||
if p := fakeItemPrice(f, "CRA-CSA-CLD-STD")["price_list_rate"]; p != 490.0 {
|
||
t.Fatalf("price not synced: %v", p)
|
||
}
|
||
if p := f.docs["Item Price"]["customer-price"]["price_list_rate"]; p != 100.0 {
|
||
t.Fatalf("customer price changed: %v", p)
|
||
}
|
||
|
||
posts = f.posts
|
||
steps, err = Run(context.Background(), c)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if f.posts != posts {
|
||
t.Fatalf("second sync wrote %d docs", f.posts-posts)
|
||
}
|
||
for _, s := range steps {
|
||
if !strings.HasPrefix(s.Result, "exists") {
|
||
t.Errorf("second sync %s: %s", s.What, s.Result)
|
||
}
|
||
}
|
||
}
|
||
|
||
func have(t *testing.T, code string) sku {
|
||
t.Helper()
|
||
for _, s := range skus() {
|
||
if s.Code == code {
|
||
return s
|
||
}
|
||
}
|
||
t.Fatalf("no sku %s", code)
|
||
return sku{}
|
||
}
|
||
|
||
// The quote's Mehrverbrauch row: Prüfwerk's extra Prüfobjekte and Prüftage
|
||
// at their list rates (or the price list), extra users for Managed Git and
|
||
// the Starter bundle; the retired per-check price is gone.
|
||
func TestQuoteOverageRow(t *testing.T) {
|
||
for _, want := range []string{
|
||
`"item_code": "CRA-CSA-CLD-TGT"`, `"item_code": "CRA-CSA-CLD-DAY"`,
|
||
"Zusätzliche Prüfobjekte werden ", " netto je Monat", "Prüftage nach verbrauchtem Monatskontingent ",
|
||
"gemäß der jeweils gültigen Preisliste", "(Leistungsbeschreibung Prüfwerk, Abschnitt 7).",
|
||
`" INF-GIT-CLD-STD " in item_codes`, `" PLT-BNDL-" in item_codes`, `" CRA-CSA-CLD-ENT " not in item_codes`,
|
||
"Weitere Nutzer über die enthaltenen Nutzer hinaus werden je Modul nach Preisliste berechnet (Leistungsbeschreibung Breakpilot Plattform, Abschnitt 4).",
|
||
} {
|
||
if !strings.Contains(documentHTML, want) {
|
||
t.Errorf("quote template lacks %q", want)
|
||
}
|
||
}
|
||
if strings.Contains(documentHTML, "CRA-CSA-CLD-SCAN") || strings.Contains(documentHTML, "je zusätzlicher Prüfung") {
|
||
t.Error("quote template still prices single Prüfungen")
|
||
}
|
||
if strings.Count(documentHTML, "{%") != strings.Count(documentHTML, "%}") {
|
||
t.Error("unbalanced Jinja tags")
|
||
}
|
||
}
|
||
|
||
// § 14 Abs. 4 UStG and § 35a GmbHG: what the documents must show.
|
||
func TestDocumentsCarryTheLegalDetails(t *testing.T) {
|
||
for _, want := range []string{"Leistungszeitraum", "Leistungsdatum entspricht dem Rechnungsdatum", "USt-IdN‌r.", "doc.taxes", "net_total", "grand_total", "Reverse Charge", "Mandatsreferenz", "Gläubiger-Identifikationsnummer", "Leistungsbeginn", "Abrechnungsintervall", "Vertragsgrundlage", "Auftragsnummer", "nach Erteilung eines gültigen SEPA-Lastschriftmandats", "gemäß erteiltem SEPA-Lastschriftmandat", "cust != doc.customer_name", "doc.customer_address", `ca.country != "Germany"`, "{{ letter_head }}", `id="footer-html"`} {
|
||
if !strings.Contains(documentHTML, want) {
|
||
t.Errorf("document template lacks %q", want)
|
||
}
|
||
}
|
||
for _, want := range []string{"HRB 736403", "Amtsgericht Freiburg", "Geschäftsführer", "USt-IdN‌r.", "tax_id", "IBAN"} {
|
||
if !strings.Contains(letterFooterHTML, want) {
|
||
t.Errorf("letter footer lacks %q", want)
|
||
}
|
||
}
|
||
for _, s := range []string{documentHTML, letterHeadHTML, letterFooterHTML, invoiceMailHTML} {
|
||
if strings.Contains(s, "$") || strings.Contains(s, "display:flex") || strings.Contains(s, "data:") || strings.Contains(s, "<svg") {
|
||
t.Errorf("unreplaced colour token or flexbox in a template")
|
||
}
|
||
}
|
||
}
|
||
|
||
// portal#66/#67: no product is described as a legal CRA check (RDG boundary).
|
||
func TestProductWordingIsNoLegalCheck(t *testing.T) {
|
||
for _, s := range skus() {
|
||
if strings.Contains(s.Description, "CRA-Prüfung") || strings.Contains(s.Name, "CRA-Prüfung") {
|
||
t.Errorf("%s: %q", s.Code, s.Description)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestLetterHeadSourceIsRestoredAndTbodyIgnored(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)
|
||
}
|
||
lh := f.docs["Letter Head"][letterHeadName]
|
||
// Saved once in the UI: the editor added <tbody>, nothing else changed.
|
||
lh["content"] = strings.ReplaceAll(letterHeadHTML, "<tr>", "<tbody><tr>")
|
||
lh["footer"] = strings.ReplaceAll(letterFooterHTML, "</table>", "</tbody></table>")
|
||
steps, err := Run(context.Background(), cfg(srv.URL))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
for _, s := range steps {
|
||
if s.What == "letter head "+letterHeadName && s.Result != "exists" {
|
||
t.Fatalf("tbody alone must not count as a change: %s", s.Result)
|
||
}
|
||
}
|
||
// The source was switched to Image: that is a change and is put back.
|
||
lh["source"] = "Image"
|
||
if _, err := Run(context.Background(), cfg(srv.URL)); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if lh["source"] != "HTML" {
|
||
t.Fatalf("source not restored: %v", lh["source"])
|
||
}
|
||
}
|
||
|
||
// With a discount (above all one on the grand total) ERPNext lowers net_total
|
||
// but keeps tax_amount at the pre-discount value; the printed VAT must be the
|
||
// amount after the discount, and the lines must add up to the total.
|
||
func TestTotalsPrintTheTaxAfterDiscount(t *testing.T) {
|
||
if strings.Contains(documentHTML, `get_formatted("tax_amount", doc)`) || strings.Contains(documentHTML, `get_formatted("discount_amount")`) {
|
||
t.Fatal("totals print the pre-discount tax or the gross discount")
|
||
}
|
||
for _, want := range []string{`tax_amount_after_discount_amount`, `Zwischensumme`, `doc.total`, `Einzug {{ term.credit_days }} Tage`} {
|
||
if !strings.Contains(documentHTML, want) {
|
||
t.Errorf("document template lacks %q", want)
|
||
}
|
||
}
|
||
}
|
||
|
||
// The quote names the Leistungsbeschreibungen by module and version: each LB
|
||
// says the version named in the quote applies.
|
||
func TestQuoteNamesLBVersions(t *testing.T) {
|
||
for _, want := range []string{
|
||
`{%- set lb_versions = "Breakpilot Plattform 1.0.0" ~ (", Prüfwerk 1.0.3" if " CRA-CSA-CLD-" in item_codes else "")`,
|
||
`(", Managed Git 1.0.0" if " INF-GIT-CLD-" in item_codes else "")`,
|
||
`(", Build-Runner 1.0.0" if " INF-CI-CLD-" in item_codes else "")`,
|
||
`(", Werkpilot 1.0.0" if " DEV-WP-" in item_codes else "")`,
|
||
`(", Firmwerk 1.0.0" if " DEV-FWK-" in item_codes else "")`,
|
||
`"Es gelten die SaaS-Vertragsbedingungen, die Leistungsbeschreibungen (" ~ lb_versions ~ "), das SLA`,
|
||
"im Breakpilot-Kundenportal zum Abruf bereit.",
|
||
} {
|
||
if !strings.Contains(documentHTML, want) {
|
||
t.Errorf("quote template lacks %q", want)
|
||
}
|
||
}
|
||
if strings.Contains(documentHTML, "$LB_VERSIONS") || strings.Contains(documentHTML, "BreakPilot-Kundenportal") {
|
||
t.Error("placeholder left or old brand spelling in the Vertragsgrundlagen")
|
||
}
|
||
// item_codes must be set before the Vertragsgrundlagen row reads it.
|
||
if strings.Index(documentHTML, "{%- set item_codes") > strings.Index(documentHTML, "{%- set lb_versions") {
|
||
t.Error("lb_versions is computed before item_codes is set")
|
||
}
|
||
for _, lb := range lbVersions {
|
||
if !strings.Contains(documentHTML, lb.Module+" "+lb.Version) {
|
||
t.Errorf("quote template lacks %s %s", lb.Module, lb.Version)
|
||
}
|
||
}
|
||
if !strings.Contains(have(t, "CRA-CSA-CLD-STD").Description, "Codegraph") {
|
||
t.Error("Prüfwerk Standard description does not name the code graph (LB Prüfwerk 1.0.3 § 4 Abs. 4)")
|
||
}
|
||
}
|
||
|
||
// What customers read is spelled "Breakpilot": the documents, the letter
|
||
// head and footer, and the invoice e-mail with its subject. ERPNext record
|
||
// names (print formats, letter head, item group) keep the old spelling,
|
||
// because renaming them would create new records.
|
||
func TestCustomerTextSpellsBreakpilot(t *testing.T) {
|
||
for name, s := range map[string]string{
|
||
"document": documentHTML, "letter head": letterHeadHTML, "letter footer": letterFooterHTML,
|
||
"invoice mail": invoiceMailHTML, "logo": logoSVG, "mail subject": emailTemplateDoc()["subject"].(string),
|
||
} {
|
||
if strings.Contains(s, "BreakPilot") {
|
||
t.Errorf("%s still spells BreakPilot", name)
|
||
}
|
||
}
|
||
}
|