diff --git a/README_FIX_2026-10-20.md b/README_FIX_2026-10-20.md new file mode 100644 index 0000000..5e00402 --- /dev/null +++ b/README_FIX_2026-10-20.md @@ -0,0 +1,26 @@ +# Descrybe: processing credit settings and Unicode exports (2026-10-20) + +## Changes + +- Fixed `PUT /api/admin/credit-value-eur` failing with `unknown settings key`. The platform-settings allowlist now permits the `billing.reference_eur_per_credit` value (not a secret). +- Fixed `GET /api/admin/processing-costs` reporting `could not scan processing costs` by reading PostgreSQL numeric/integer costs as text, then explicitly parsing into the JSON response. This avoids driver conversion problems across schema revisions. +- Product Management can still start a valid full-enrichment request when the *credit estimate* endpoint is temporarily unavailable, without displaying an invented credit estimate. A retry action is provided. Permission and billing checks still happen on the API/worker side. +- Price, stock and availability remain optional supplier/product inputs; missing values are not fabricated or used to block enrichment. +- All server-generated CSV downloads (product exports, public feed CSV, usage, Stripe invoices, AI costs) now use UTF-8 plus a single BOM (`EF BB BF`) for direct Microsoft Excel compatibility. +- Browser-generated CSV/TSV downloads (categories, attribute templates, sample feed) use UTF-8 with BOM. XML and JSON exports remain standard UTF-8 **without** a BOM. +- Added tests for credit reference-setting permission, price/stock-optional enrichment, CSV/TSV Unicode and XML/JSON preservation. + +## Deploy + +1. Backup your database and deploy **both** the updated Go API/worker and SvelteKit web client. Don't just upload the web files. +2. Apply existing database migrations through `054_catalog_import_languages.sql`, especially `049_processing_cost_overrides.sql` and `053_content_credit_rates.sql`. From the project root, `npm run migrate` after setting up the database environment. +3. Rebuild/restart API and web; refresh the UI. +4. In Admin > Billing, save the EUR-per-credit **reference value**. Set the actual product/output credit costs on the plan separately; **EUR reference value does not set processing charges**. +5. Check `GET /api/admin/processing-costs` and `GET /api/billing/processing-costs` with appropriate authenticated roles. +6. Try an imported product with no price/stock information, and export `Črpalka, šoba, Žarnica` to CSV. A CSV file should begin `EF BB BF` and decode as UTF-8. + +## Validation in this environment + +- Focused JS tests (pricing fallback, plan mode, UTF-8 exports): **6 passed, 0 failed**. +- Full web test suite: **299 passed, 6 failed**, due to unrelated existing translation key discrepancies, an absent source file and missing dependencies in the supplied archive. +- Go source was formatted/parsed by `gofmt`. Full Go tests/build could not be run here: project requires Go 1.25, host has Go 1.23.2, and external downloads are unavailable. Run `go test ./internal/platformsettings ./internal/feeds ./internal/httpapi ./internal/billing ./internal/processing` from `apps/api` in your Go 1.25 environment. diff --git a/apps/api/internal/feeds/export.go b/apps/api/internal/feeds/export.go index b2f690f..c552a48 100644 --- a/apps/api/internal/feeds/export.go +++ b/apps/api/internal/feeds/export.go @@ -874,6 +874,11 @@ func writeXMLProduct(w io.Writer, item string, tpl exportTemplate, p exportProdu } func streamCSV(w io.Writer, seq exportProductSeq, tpl exportTemplate) (int, error) { + // UTF-8 BOM makes Excel detect Unicode without its locale-dependent CSV import. + // The BOM is emitted once per file and does not change the exported field data. + if _, err := io.WriteString(w, "\ufeff"); err != nil { + return 0, err + } cw := csv.NewWriter(w) headers := make([]string, len(tpl.Fields)) for i, f := range tpl.Fields { diff --git a/apps/api/internal/feeds/export_test.go b/apps/api/internal/feeds/export_test.go index ede943e..26c080a 100644 --- a/apps/api/internal/feeds/export_test.go +++ b/apps/api/internal/feeds/export_test.go @@ -335,7 +335,10 @@ func TestStreamCSVUsesProductSeqWithoutCollecting(t *testing.T) { if n != 1 { t.Fatalf("count=%d", n) } - lines := strings.Split(strings.TrimSpace(buf.String()), "\n") + if !strings.HasPrefix(buf.String(), "\ufeff") { + t.Fatalf("downloadable CSV must start with UTF-8 BOM: %q", buf.Bytes()[:min(buf.Len(), 8)]) + } + lines := strings.Split(strings.TrimSpace(strings.TrimPrefix(buf.String(), "\ufeff")), "\n") if len(lines) != 2 { t.Fatalf("lines=%v", lines) } diff --git a/apps/api/internal/feeds/export_unicode_test.go b/apps/api/internal/feeds/export_unicode_test.go new file mode 100644 index 0000000..6c383f1 --- /dev/null +++ b/apps/api/internal/feeds/export_unicode_test.go @@ -0,0 +1,63 @@ +package feeds + +import ( + "bytes" + "encoding/csv" + "encoding/json" + "encoding/xml" + "strings" + "testing" + "unicode/utf8" +) + +func TestExportUnicodeSurvivesEveryFormat(t *testing.T) { + name := "Črpalka, šoba Žuža – München 東京 Привет" + tpl := exportTemplate{Fields: []exportField{{Key: "Naziv č š ž", Source: "name"}}} + seq := func(yield func(exportProduct) error) error { + return yield(exportProduct{Name: &name}) + } + for _, format := range []string{"csv", "xml", "json"} { + var buf bytes.Buffer + var n int + var err error + switch format { + case "csv": + n, err = streamCSV(&buf, seq, tpl) + case "xml": + n, err = streamXML(&buf, seq, tpl, "Izvoz") + case "json": + n, err = streamJSON(&buf, seq, tpl) + } + if err != nil || n != 1 { + t.Fatalf("%s: count=%d err=%v", format, n, err) + } + if !utf8.Valid(buf.Bytes()) { + t.Fatalf("%s: invalid UTF-8", format) + } + switch format { + case "csv": + if !bytes.HasPrefix(buf.Bytes(), []byte("\ufeff")) { + t.Fatal("CSV has no UTF-8 BOM") + } + r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(buf.Bytes(), []byte("\ufeff")))) + rows, err := r.ReadAll() + if err != nil || len(rows) != 2 || rows[0][0] != "Naziv č š ž" || rows[1][0] != name { + t.Fatalf("CSV data lost Unicode: %v, %v", rows, err) + } + case "xml": + var out struct { + Name string `xml:"Naziv_č_š_ž"` + } + if !strings.Contains(buf.String(), name) { + t.Fatalf("XML missing Unicode: %s", buf.String()) + } + if err := xml.Unmarshal(buf.Bytes(), &out); err != nil { + t.Fatalf("XML invalid: %v", err) + } + case "json": + if !json.Valid(buf.Bytes()) || !bytes.Contains(buf.Bytes(), []byte(name)) { + t.Fatalf("JSON invalid or data lost: %s", buf.String()) + } + } + } +} diff --git a/apps/api/internal/httpapi/admin_ai_cost_export_handlers.go b/apps/api/internal/httpapi/admin_ai_cost_export_handlers.go index ec8fa0a..29128aa 100644 --- a/apps/api/internal/httpapi/admin_ai_cost_export_handlers.go +++ b/apps/api/internal/httpapi/admin_ai_cost_export_handlers.go @@ -1,7 +1,6 @@ package httpapi import ( - "encoding/csv" "net/http" "strconv" "strings" @@ -37,7 +36,10 @@ func (s *Server) handleAdminExportAICosts(w http.ResponseWriter, r *http.Request w.Header().Set("Content-Type", "text/csv; charset=utf-8") w.Header().Set("Content-Disposition", `attachment; filename="descrybe-ai-usage-costs.csv"`) w.Header().Set("Cache-Control", "private, no-store") - out := csv.NewWriter(w) + out, err := newUTF8CSVWriter(w) + if err != nil { + return + } _ = out.Write([]string{"from", "to", "company_id", "company", "calls", "failed_calls", "input_tokens", "cached_input_tokens", "output_tokens", "total_tokens", "provider_cost_usd", "notice"}) v := func(row map[string]any, key string) string { return strconv.FormatInt(int64(row[key].(int64)), 10) } for _, row := range result { diff --git a/apps/api/internal/httpapi/admin_invoice_export_handlers.go b/apps/api/internal/httpapi/admin_invoice_export_handlers.go index 0ad8eea..cffbe95 100644 --- a/apps/api/internal/httpapi/admin_invoice_export_handlers.go +++ b/apps/api/internal/httpapi/admin_invoice_export_handlers.go @@ -1,7 +1,6 @@ package httpapi import ( - "encoding/csv" "net/http" "strconv" "strings" @@ -25,7 +24,10 @@ func (s *Server) handleAdminExportCompanyInvoices(w http.ResponseWriter, r *http w.Header().Set("Content-Type", "text/csv; charset=utf-8") w.Header().Set("Content-Disposition", `attachment; filename="descrybe-stripe-invoices.csv"`) w.Header().Set("Cache-Control", "private, no-store") - out := csv.NewWriter(w) + out, err := newUTF8CSVWriter(w) + if err != nil { + return + } _ = out.Write([]string{"company_id", "invoice_id", "number", "status", "currency", "created_unix", "amount_due_minor", "amount_paid_minor", "amount_remaining_minor", "hosted_invoice_url", "invoice_pdf"}) for _, row := range rows { _ = out.Write([]string{id.String(), row.ID, row.Number, row.Status, row.Currency, diff --git a/apps/api/internal/httpapi/admin_processing_costs_handlers.go b/apps/api/internal/httpapi/admin_processing_costs_handlers.go index cae099b..26d0259 100644 --- a/apps/api/internal/httpapi/admin_processing_costs_handlers.go +++ b/apps/api/internal/httpapi/admin_processing_costs_handlers.go @@ -1,11 +1,13 @@ package httpapi import ( + "errors" "math" "net/http" "strconv" "strings" + "github.com/descrybe/descrybe-v2/apps/api/internal/platformsettings" "github.com/google/uuid" ) @@ -18,11 +20,11 @@ var editableCostFeatures = map[string]bool{ func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) { rows, err := s.Pool.Query(r.Context(), ` - SELECT 'default', '', feature_name, cost_per_unit FROM processing_costs WHERE is_active = true AND feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') + SELECT 'default', '', feature_name, cost_per_unit::text FROM processing_costs WHERE is_active = true AND feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') UNION ALL - SELECT 'plan', plan_id::text, feature_name, cost_per_unit FROM plan_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') + SELECT 'plan', plan_id::text, feature_name, cost_per_unit::text FROM plan_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') UNION ALL - SELECT 'company', company_id::text, feature_name, cost_per_unit FROM company_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') + SELECT 'company', company_id::text, feature_name, cost_per_unit::text FROM company_processing_costs WHERE feature_name IN ('title_ai','description_ai','seo_meta_ai','product_ai') ORDER BY 1, 2, 3`) if err != nil { LogAndError(w, http.StatusInternalServerError, "could not load processing costs", err) @@ -31,12 +33,19 @@ func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Re defer rows.Close() out := make([]map[string]any, 0, 16) for rows.Next() { - var scope, id, feature string - var cost float64 - if err := rows.Scan(&scope, &id, &feature, &cost); err != nil { + var scope, id, feature, costText string + if err := rows.Scan(&scope, &id, &feature, &costText); err != nil { LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err) return } + cost, parseErr := strconv.ParseFloat(costText, 64) + if parseErr != nil || math.IsNaN(cost) || math.IsInf(cost, 0) { + if parseErr == nil { + parseErr = errors.New("non-finite cost value") + } + LogAndError(w, http.StatusInternalServerError, "invalid stored processing cost", parseErr) + return + } out = append(out, map[string]any{"scope": scope, "id": id, "feature": feature, "cost_per_unit": cost}) } if err := rows.Err(); err != nil { @@ -130,7 +139,7 @@ func (s *Server) handleCompanyContentCosts(w http.ResponseWriter, r *http.Reques // Monetary credit valuation is an admin reference rate. Stripe invoices, pack // checkout prices and historic wallet ledger values are not changed by it. -const creditValueEURSetting = "billing.reference_eur_per_credit" +const creditValueEURSetting = platformsettings.KeyBillingReferenceEURPerCredit func (s *Server) handleAdminCreditValueEUR(w http.ResponseWriter, r *http.Request) { if s.PlatformSettings == nil { diff --git a/apps/api/internal/httpapi/billing_usage_export_handlers.go b/apps/api/internal/httpapi/billing_usage_export_handlers.go index 2fcd15f..6beb71e 100644 --- a/apps/api/internal/httpapi/billing_usage_export_handlers.go +++ b/apps/api/internal/httpapi/billing_usage_export_handlers.go @@ -1,7 +1,6 @@ package httpapi import ( - "encoding/csv" "net/http" "strconv" @@ -23,7 +22,10 @@ func (s *Server) handleBillingUsageExport(w http.ResponseWriter, r *http.Request w.Header().Set("Content-Type", "text/csv; charset=utf-8") w.Header().Set("Content-Disposition", `attachment; filename="descrybe-usage.csv"`) w.Header().Set("Cache-Control", "private, no-store") - out := csv.NewWriter(w) + out, err := newUTF8CSVWriter(w) + if err != nil { + return + } _ = out.Write([]string{"company_id", "range", "metric", "value", "notes"}) rows := []struct { label string diff --git a/apps/api/internal/httpapi/csv_export.go b/apps/api/internal/httpapi/csv_export.go new file mode 100644 index 0000000..3183a58 --- /dev/null +++ b/apps/api/internal/httpapi/csv_export.go @@ -0,0 +1,15 @@ +package httpapi + +import ( + "encoding/csv" + "io" +) + +// newUTF8CSVWriter writes the UTF-8 signature so Excel can recognize characters +// such as č, š and ž when opening exported CSVs directly. +func newUTF8CSVWriter(w io.Writer) (*csv.Writer, error) { + if _, err := io.WriteString(w, "\ufeff"); err != nil { + return nil, err + } + return csv.NewWriter(w), nil +} diff --git a/apps/api/internal/httpapi/csv_export_test.go b/apps/api/internal/httpapi/csv_export_test.go new file mode 100644 index 0000000..70cabce --- /dev/null +++ b/apps/api/internal/httpapi/csv_export_test.go @@ -0,0 +1,29 @@ +package httpapi + +import ( + "bytes" + "encoding/csv" + "testing" +) + +func TestUTF8CSVWriterPreservesSlovenianText(t *testing.T) { + var b bytes.Buffer + w, err := newUTF8CSVWriter(&b) + if err != nil { + t.Fatal(err) + } + if err := w.Write([]string{"Opis", "Žarnica, črpalka, šoba"}); err != nil { + t.Fatal(err) + } + w.Flush() + if err := w.Error(); err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(b.Bytes(), []byte("\ufeff")) { + t.Fatalf("no UTF-8 BOM: %v", b.Bytes()) + } + rows, err := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(b.Bytes(), []byte("\ufeff")))).ReadAll() + if err != nil || len(rows) != 1 || rows[0][1] != "Žarnica, črpalka, šoba" { + t.Fatalf("round trip failed: %v: %v", rows, err) + } +} diff --git a/apps/api/internal/platformsettings/keys.go b/apps/api/internal/platformsettings/keys.go index e1a7ea5..3f30ffa 100644 --- a/apps/api/internal/platformsettings/keys.go +++ b/apps/api/internal/platformsettings/keys.go @@ -35,6 +35,8 @@ const ( KeyEPRELAPIKey = "eprel.api_key" KeyFeedPrivateAllowlist = "feeds.private_url_allowlist" + // Admin reference valuation for one processing credit; not a Stripe price. + KeyBillingReferenceEURPerCredit = "billing.reference_eur_per_credit" KeyPineconeAPIKey = "pinecone.api_key" KeyPineconeHost = "pinecone.host" @@ -55,30 +57,31 @@ func SecretValueKeys() map[string]struct{} { // AllowedValueKeys is the allowlist for Values bag writes (mass-assignment guard). func AllowedValueKeys() map[string]struct{} { out := map[string]struct{}{ - KeyStripeSecretKey: {}, - KeyStripeWebhookSecret: {}, - KeyStripeMock: {}, - KeyStripePriceStarterMo: {}, - KeyStripePriceStarterYr: {}, - KeyStripePricePlusMo: {}, - KeyStripePricePlusYr: {}, - KeyStripePriceGrowthMo: {}, - KeyStripePriceGrowthYr: {}, - KeyStripePriceBizMo: {}, - KeyStripePriceBizYr: {}, - KeyStripePriceScaleMo: {}, - KeyStripePriceScaleYr: {}, - KeyEPRELEnabled: {}, - KeyEPRELBaseURL: {}, - KeyEPRELTimeout: {}, - KeyEPRELFicheLanguage: {}, - KeyEPRELAPIKey: {}, - KeyFeedPrivateAllowlist: {}, - KeyPineconeAPIKey: {}, - KeyPineconeHost: {}, - KeyPineconeNamespace: {}, - ValueKeyResendAPIKey: {}, - ValueKeyEmailDryRun: {}, + KeyStripeSecretKey: {}, + KeyStripeWebhookSecret: {}, + KeyStripeMock: {}, + KeyStripePriceStarterMo: {}, + KeyStripePriceStarterYr: {}, + KeyStripePricePlusMo: {}, + KeyStripePricePlusYr: {}, + KeyStripePriceGrowthMo: {}, + KeyStripePriceGrowthYr: {}, + KeyStripePriceBizMo: {}, + KeyStripePriceBizYr: {}, + KeyStripePriceScaleMo: {}, + KeyStripePriceScaleYr: {}, + KeyEPRELEnabled: {}, + KeyEPRELBaseURL: {}, + KeyEPRELTimeout: {}, + KeyEPRELFicheLanguage: {}, + KeyEPRELAPIKey: {}, + KeyFeedPrivateAllowlist: {}, + KeyBillingReferenceEURPerCredit: {}, + KeyPineconeAPIKey: {}, + KeyPineconeHost: {}, + KeyPineconeNamespace: {}, + ValueKeyResendAPIKey: {}, + ValueKeyEmailDryRun: {}, } for _, pack := range billing.DefaultCreditPacks() { out[billing.CreditPackSettingsKey(pack.ID)] = struct{}{} diff --git a/apps/api/internal/platformsettings/service_test.go b/apps/api/internal/platformsettings/service_test.go index db30d52..6ac3ede 100644 --- a/apps/api/internal/platformsettings/service_test.go +++ b/apps/api/internal/platformsettings/service_test.go @@ -61,6 +61,12 @@ func TestSecretValueKeys(t *testing.T) { } func TestAllowedValueKeys(t *testing.T) { + if !isAllowedValueKey(KeyBillingReferenceEURPerCredit) { + t.Fatal("admin EUR per credit reference must be writable") + } + if isSecretValueKey(KeyBillingReferenceEURPerCredit) { + t.Fatal("EUR per credit reference is not a secret") + } if !isAllowedValueKey(KeyEPRELFicheLanguage) { t.Fatal("eprel.fiche_language must be allowed") } diff --git a/apps/api/internal/processing/enrich_test.go b/apps/api/internal/processing/enrich_test.go index ff5605c..e159b26 100644 --- a/apps/api/internal/processing/enrich_test.go +++ b/apps/api/internal/processing/enrich_test.go @@ -107,3 +107,29 @@ func TestMapStockStatus_unknown(t *testing.T) { t.Fatal("expected empty for unknown") } } + +// Price, stock and availability are optional supplier attributes. A product +// must remain eligible for enrichment when the feed omits all of them. +func TestEnrichMappedWithoutSellingPriceOrStock(t *testing.T) { + raw := map[string]any{"EAN": "4005176605550", "name": "VitalioFlex Trend shower hose"} + got := EnrichMapped(raw) + for _, key := range []string{"price", "sale_price", "stock", "availability", "stock_status"} { + if value, ok := got[key]; ok { + t.Fatalf("invented %s=%v: %#v", key, value, got) + } + } + if got["gtin"] != "4005176605550" || got["title"] != raw["name"] { + t.Fatalf("product with optional fields missing was not enriched: %#v", got) + } + if _, ok := raw["price"]; ok { + t.Fatal("source modified") + } + + normalized := NormalizeMapped(map[string]any{"name": "Shower hose", "price": "", "stock": nil}, nil) + if _, ok := normalized["price"]; ok { + t.Fatalf("empty price must remain absent: %#v", normalized) + } + if _, ok := normalized["stock"]; ok { + t.Fatalf("missing stock must remain absent: %#v", normalized) + } +} diff --git a/apps/web/src/lib/components/categories/AddCategoryDialog.svelte b/apps/web/src/lib/components/categories/AddCategoryDialog.svelte index ab75d62..0eee364 100644 --- a/apps/web/src/lib/components/categories/AddCategoryDialog.svelte +++ b/apps/web/src/lib/components/categories/AddCategoryDialog.svelte @@ -1,6 +1,7 @@ @@ -166,14 +197,19 @@ {#if activeTab !== "processed"} {#if pricingError} - +
+ {i18n.t("processing.actions.estimateUnavailable")} + +
{/if}
{/if} - {#if processingMode === "product"} + {#if processingMode !== "outputs"}
-

Product processing

-

AI title, description and SEO metadata together. No individual output selection.

+

{i18n.t("processing.actions.fullEnrichment")}

+

{i18n.t("processing.actions.fullEnrichmentBody")}

- {(effectiveCosts.product ?? 0.45).toFixed(4)} credits + {#if totalCredits !== null} + {effectiveCosts.product.toFixed(4)} {i18n.t("processing.actions.creditsUnit")} + {/if}
{:else}