Fix
This commit is contained in:
1 parent
486502852e
commit
0e48ea427b
23 files changed
+386
-78
No files matched your search
@@ -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.
|
||||||
@@ -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) {
|
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)
|
cw := csv.NewWriter(w)
|
||||||
headers := make([]string, len(tpl.Fields))
|
headers := make([]string, len(tpl.Fields))
|
||||||
for i, f := range tpl.Fields {
|
for i, f := range tpl.Fields {
|
||||||
|
|||||||
@@ -335,7 +335,10 @@ func TestStreamCSVUsesProductSeqWithoutCollecting(t *testing.T) {
|
|||||||
if n != 1 {
|
if n != 1 {
|
||||||
t.Fatalf("count=%d", n)
|
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 {
|
if len(lines) != 2 {
|
||||||
t.Fatalf("lines=%v", lines)
|
t.Fatalf("lines=%v", lines)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/csv"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"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-Type", "text/csv; charset=utf-8")
|
||||||
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-ai-usage-costs.csv"`)
|
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-ai-usage-costs.csv"`)
|
||||||
w.Header().Set("Cache-Control", "private, no-store")
|
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"})
|
_ = 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) }
|
v := func(row map[string]any, key string) string { return strconv.FormatInt(int64(row[key].(int64)), 10) }
|
||||||
for _, row := range result {
|
for _, row := range result {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/csv"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"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-Type", "text/csv; charset=utf-8")
|
||||||
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-stripe-invoices.csv"`)
|
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-stripe-invoices.csv"`)
|
||||||
w.Header().Set("Cache-Control", "private, no-store")
|
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"})
|
_ = 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 {
|
for _, row := range rows {
|
||||||
_ = out.Write([]string{id.String(), row.ID, row.Number, row.Status, row.Currency,
|
_ = out.Write([]string{id.String(), row.ID, row.Number, row.Status, row.Currency,
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"math"
|
"math"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/descrybe/descrybe-v2/apps/api/internal/platformsettings"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,11 +20,11 @@ var editableCostFeatures = map[string]bool{
|
|||||||
|
|
||||||
func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) {
|
func (s *Server) handleAdminGetProcessingCosts(w http.ResponseWriter, r *http.Request) {
|
||||||
rows, err := s.Pool.Query(r.Context(), `
|
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
|
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
|
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`)
|
ORDER BY 1, 2, 3`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
LogAndError(w, http.StatusInternalServerError, "could not load processing costs", err)
|
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()
|
defer rows.Close()
|
||||||
out := make([]map[string]any, 0, 16)
|
out := make([]map[string]any, 0, 16)
|
||||||
for rows.Next() {
|
for rows.Next() {
|
||||||
var scope, id, feature string
|
var scope, id, feature, costText string
|
||||||
var cost float64
|
if err := rows.Scan(&scope, &id, &feature, &costText); err != nil {
|
||||||
if err := rows.Scan(&scope, &id, &feature, &cost); err != nil {
|
|
||||||
LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err)
|
LogAndError(w, http.StatusInternalServerError, "could not scan processing costs", err)
|
||||||
return
|
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})
|
out = append(out, map[string]any{"scope": scope, "id": id, "feature": feature, "cost_per_unit": cost})
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
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
|
// Monetary credit valuation is an admin reference rate. Stripe invoices, pack
|
||||||
// checkout prices and historic wallet ledger values are not changed by it.
|
// 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) {
|
func (s *Server) handleAdminCreditValueEUR(w http.ResponseWriter, r *http.Request) {
|
||||||
if s.PlatformSettings == nil {
|
if s.PlatformSettings == nil {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/csv"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"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-Type", "text/csv; charset=utf-8")
|
||||||
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-usage.csv"`)
|
w.Header().Set("Content-Disposition", `attachment; filename="descrybe-usage.csv"`)
|
||||||
w.Header().Set("Cache-Control", "private, no-store")
|
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"})
|
_ = out.Write([]string{"company_id", "range", "metric", "value", "notes"})
|
||||||
rows := []struct {
|
rows := []struct {
|
||||||
label string
|
label string
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -35,6 +35,8 @@ const (
|
|||||||
KeyEPRELAPIKey = "eprel.api_key"
|
KeyEPRELAPIKey = "eprel.api_key"
|
||||||
|
|
||||||
KeyFeedPrivateAllowlist = "feeds.private_url_allowlist"
|
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"
|
KeyPineconeAPIKey = "pinecone.api_key"
|
||||||
KeyPineconeHost = "pinecone.host"
|
KeyPineconeHost = "pinecone.host"
|
||||||
@@ -55,30 +57,31 @@ func SecretValueKeys() map[string]struct{} {
|
|||||||
// AllowedValueKeys is the allowlist for Values bag writes (mass-assignment guard).
|
// AllowedValueKeys is the allowlist for Values bag writes (mass-assignment guard).
|
||||||
func AllowedValueKeys() map[string]struct{} {
|
func AllowedValueKeys() map[string]struct{} {
|
||||||
out := map[string]struct{}{
|
out := map[string]struct{}{
|
||||||
KeyStripeSecretKey: {},
|
KeyStripeSecretKey: {},
|
||||||
KeyStripeWebhookSecret: {},
|
KeyStripeWebhookSecret: {},
|
||||||
KeyStripeMock: {},
|
KeyStripeMock: {},
|
||||||
KeyStripePriceStarterMo: {},
|
KeyStripePriceStarterMo: {},
|
||||||
KeyStripePriceStarterYr: {},
|
KeyStripePriceStarterYr: {},
|
||||||
KeyStripePricePlusMo: {},
|
KeyStripePricePlusMo: {},
|
||||||
KeyStripePricePlusYr: {},
|
KeyStripePricePlusYr: {},
|
||||||
KeyStripePriceGrowthMo: {},
|
KeyStripePriceGrowthMo: {},
|
||||||
KeyStripePriceGrowthYr: {},
|
KeyStripePriceGrowthYr: {},
|
||||||
KeyStripePriceBizMo: {},
|
KeyStripePriceBizMo: {},
|
||||||
KeyStripePriceBizYr: {},
|
KeyStripePriceBizYr: {},
|
||||||
KeyStripePriceScaleMo: {},
|
KeyStripePriceScaleMo: {},
|
||||||
KeyStripePriceScaleYr: {},
|
KeyStripePriceScaleYr: {},
|
||||||
KeyEPRELEnabled: {},
|
KeyEPRELEnabled: {},
|
||||||
KeyEPRELBaseURL: {},
|
KeyEPRELBaseURL: {},
|
||||||
KeyEPRELTimeout: {},
|
KeyEPRELTimeout: {},
|
||||||
KeyEPRELFicheLanguage: {},
|
KeyEPRELFicheLanguage: {},
|
||||||
KeyEPRELAPIKey: {},
|
KeyEPRELAPIKey: {},
|
||||||
KeyFeedPrivateAllowlist: {},
|
KeyFeedPrivateAllowlist: {},
|
||||||
KeyPineconeAPIKey: {},
|
KeyBillingReferenceEURPerCredit: {},
|
||||||
KeyPineconeHost: {},
|
KeyPineconeAPIKey: {},
|
||||||
KeyPineconeNamespace: {},
|
KeyPineconeHost: {},
|
||||||
ValueKeyResendAPIKey: {},
|
KeyPineconeNamespace: {},
|
||||||
ValueKeyEmailDryRun: {},
|
ValueKeyResendAPIKey: {},
|
||||||
|
ValueKeyEmailDryRun: {},
|
||||||
}
|
}
|
||||||
for _, pack := range billing.DefaultCreditPacks() {
|
for _, pack := range billing.DefaultCreditPacks() {
|
||||||
out[billing.CreditPackSettingsKey(pack.ID)] = struct{}{}
|
out[billing.CreditPackSettingsKey(pack.ID)] = struct{}{}
|
||||||
|
|||||||
@@ -61,6 +61,12 @@ func TestSecretValueKeys(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAllowedValueKeys(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) {
|
if !isAllowedValueKey(KeyEPRELFicheLanguage) {
|
||||||
t.Fatal("eprel.fiche_language must be allowed")
|
t.Fatal("eprel.fiche_language must be allowed")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,3 +107,29 @@ func TestMapStockStatus_unknown(t *testing.T) {
|
|||||||
t.Fatal("expected empty for unknown")
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { i18n } from "$lib/i18n";
|
import { i18n } from "$lib/i18n";
|
||||||
import { failureMessage } from "$lib/api";
|
import { failureMessage } from "$lib/api";
|
||||||
|
import { textExportBlob } from "$lib/export-unicode";
|
||||||
import type { Cat } from "$lib/categories/types";
|
import type { Cat } from "$lib/categories/types";
|
||||||
import { Dialog, Button, Input, Label, Select, Tabs, TabsList, TabsTrigger, TabsContent } from "$lib/components/ui";
|
import { Dialog, Button, Input, Label, Select, Tabs, TabsList, TabsTrigger, TabsContent } from "$lib/components/ui";
|
||||||
import { Upload, Download } from "@lucide/svelte";
|
import { Upload, Download } from "@lucide/svelte";
|
||||||
@@ -96,7 +97,7 @@
|
|||||||
|
|
||||||
function downloadTemplate() {
|
function downloadTemplate() {
|
||||||
const csv = "name,unique_id,parent_unique_id,description\nElectronics,electronics,,Root category\n";
|
const csv = "name,unique_id,parent_unique_id,description\nElectronics,electronics,,Root category\n";
|
||||||
const blob = new Blob([csv], { type: "text/csv" });
|
const blob = textExportBlob(csv, "text/csv");
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement("a");
|
const a = document.createElement("a");
|
||||||
a.href = url;
|
a.href = url;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { textExportBlob } from "$lib/export-unicode";
|
||||||
|
|
||||||
/** Full Descrybe sample feed templates (download + preview). */
|
/** Full Descrybe sample feed templates (download + preview). */
|
||||||
|
|
||||||
export const SAMPLE_FEED_XML = `<?xml version="1.0" encoding="UTF-8"?>
|
export const SAMPLE_FEED_XML = `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
@@ -253,9 +255,10 @@ export const SAMPLE_CSV_PREVIEW = `gtin,title,brand,price,currency,net_height,ne
|
|||||||
|
|
||||||
export function downloadSampleFeed(kind: "xml" | "csv"): void {
|
export function downloadSampleFeed(kind: "xml" | "csv"): void {
|
||||||
const isXml = kind === "xml";
|
const isXml = kind === "xml";
|
||||||
const blob = new Blob([isXml ? SAMPLE_FEED_XML : SAMPLE_FEED_CSV], {
|
const blob = textExportBlob(
|
||||||
type: isXml ? "application/xml;charset=utf-8" : "text/csv;charset=utf-8"
|
isXml ? SAMPLE_FEED_XML : SAMPLE_FEED_CSV,
|
||||||
});
|
isXml ? "application/xml" : "text/csv"
|
||||||
|
);
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement("a");
|
const a = document.createElement("a");
|
||||||
a.href = url;
|
a.href = url;
|
||||||
|
|||||||
@@ -55,33 +55,62 @@
|
|||||||
let open = $state(false);
|
let open = $state(false);
|
||||||
let confirmProcessOpen = $state(false);
|
let confirmProcessOpen = $state(false);
|
||||||
let pendingTypes = $state<ProcessingType[]>([]);
|
let pendingTypes = $state<ProcessingType[]>([]);
|
||||||
let pendingCredits = $state(0);
|
let pendingCredits = $state<number | null>(null);
|
||||||
let pendingCount = $state(0);
|
let pendingCount = $state(0);
|
||||||
let selectedTypes = $state<ProcessingType[]>([]);
|
let selectedTypes = $state<ProcessingType[]>([]);
|
||||||
let effectiveCosts = $state<Record<ProcessingType | "product", number>>({ title: 0.10, description: 0.25, seo_meta: 0.10, product: 0.45 });
|
let effectiveCosts = $state<Record<ProcessingType | "product", number>>({ title: 0.10, description: 0.25, seo_meta: 0.10, product: 0.45 });
|
||||||
let processingMode = $state<"outputs" | "product">("outputs");
|
let processingMode = $state<"outputs" | "product" | "unknown">("unknown");
|
||||||
let pricingReady = $state(false);
|
let pricingReady = $state(false);
|
||||||
|
let pricingLoading = $state(true);
|
||||||
let pricingError = $state(false);
|
let pricingError = $state(false);
|
||||||
|
let requestSerial = 0;
|
||||||
const processProductTypes: ProcessingType[] = ["title", "description", "seo_meta"];
|
const processProductTypes: ProcessingType[] = ["title", "description", "seo_meta"];
|
||||||
onMount(() => {
|
|
||||||
void api<{ mode: "outputs" | "product"; credits: Record<ProcessingType | "product", number> }>("/api/billing/processing-costs")
|
// Credit pricing is about the company's billing plan, not the product's
|
||||||
.then((result) => {
|
// selling price or stock. A failed estimate must not disable enrichment.
|
||||||
if (result?.credits) effectiveCosts = result.credits;
|
// When the mode cannot be verified, offer full enrichment only so callers
|
||||||
processingMode = result?.mode === "product" ? "product" : "outputs";
|
// cannot inadvertently expect a per-output price on a flat-rate plan.
|
||||||
pricingReady = true;
|
async function loadProcessingCosts() {
|
||||||
})
|
const serial = ++requestSerial;
|
||||||
.catch(() => { pricingError = true; });
|
pricingLoading = true;
|
||||||
});
|
pricingError = false;
|
||||||
|
try {
|
||||||
|
const result = await api<{
|
||||||
|
mode: "outputs" | "product";
|
||||||
|
credits: Record<ProcessingType | "product", number>;
|
||||||
|
}>("/api/billing/processing-costs");
|
||||||
|
if (serial !== requestSerial) return;
|
||||||
|
const keys: Array<ProcessingType | "product"> = result?.mode === "product"
|
||||||
|
? ["product"]
|
||||||
|
: ["title", "description", "seo_meta"];
|
||||||
|
if (!result?.credits || keys.some((key) =>
|
||||||
|
typeof result.credits[key] !== "number" ||
|
||||||
|
!Number.isFinite(result.credits[key]) || result.credits[key] < 0
|
||||||
|
)) throw new Error("Invalid processing credit rates");
|
||||||
|
effectiveCosts = result.credits;
|
||||||
|
processingMode = result.mode;
|
||||||
|
pricingReady = true;
|
||||||
|
} catch {
|
||||||
|
if (serial !== requestSerial) return;
|
||||||
|
pricingReady = false;
|
||||||
|
processingMode = "unknown";
|
||||||
|
pricingError = true;
|
||||||
|
} finally {
|
||||||
|
if (serial === requestSerial) pricingLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => { void loadProcessingCosts(); });
|
||||||
|
|
||||||
const selectedAILocked = $derived(
|
const selectedAILocked = $derived(
|
||||||
(processingMode === "product" && !processProductTypes.every(aiAllowedForType)) || selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
|
(processingMode !== "outputs" && !processProductTypes.every(aiAllowedForType)) || selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
|
||||||
);
|
);
|
||||||
|
|
||||||
// Estimated cost from the effective company/plan rates (per selected output).
|
// Estimated cost from the effective company/plan rates (per selected output).
|
||||||
const totalCredits = $derived(processingMode === "product"
|
const totalCredits = $derived(!pricingReady ? null : processingMode === "product"
|
||||||
? (effectiveCosts.product ?? 0.45) * selectedCount
|
? effectiveCosts.product * selectedCount
|
||||||
: PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
|
: PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
|
||||||
(sum, option) => sum + (effectiveCosts[option.type] ?? option.credits),
|
(sum, option) => sum + effectiveCosts[option.type],
|
||||||
0
|
0
|
||||||
) * selectedCount
|
) * selectedCount
|
||||||
);
|
);
|
||||||
@@ -101,9 +130,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function processSelected() {
|
function processSelected() {
|
||||||
if (!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0)) return;
|
if (pricingLoading || (processingMode === "outputs" && selectedTypes.length === 0)) return;
|
||||||
if (selectedAILocked) return;
|
if (selectedAILocked) return;
|
||||||
pendingTypes = processingMode === "product" ? [...processProductTypes] : [...selectedTypes];
|
pendingTypes = processingMode !== "outputs" ? [...processProductTypes] : [...selectedTypes];
|
||||||
pendingCredits = totalCredits;
|
pendingCredits = totalCredits;
|
||||||
pendingCount = selectedCount;
|
pendingCount = selectedCount;
|
||||||
open = false;
|
open = false;
|
||||||
@@ -113,7 +142,7 @@
|
|||||||
function cancelProcessConfirm() {
|
function cancelProcessConfirm() {
|
||||||
confirmProcessOpen = false;
|
confirmProcessOpen = false;
|
||||||
pendingTypes = [];
|
pendingTypes = [];
|
||||||
pendingCredits = 0;
|
pendingCredits = null;
|
||||||
pendingCount = 0;
|
pendingCount = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +153,7 @@
|
|||||||
}
|
}
|
||||||
const types = pendingTypes;
|
const types = pendingTypes;
|
||||||
pendingTypes = [];
|
pendingTypes = [];
|
||||||
pendingCredits = 0;
|
pendingCredits = null;
|
||||||
pendingCount = 0;
|
pendingCount = 0;
|
||||||
confirmProcessOpen = false;
|
confirmProcessOpen = false;
|
||||||
selectedTypes = [];
|
selectedTypes = [];
|
||||||
@@ -132,10 +161,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
const processConfirmDescription = $derived(
|
const processConfirmDescription = $derived(
|
||||||
i18n.t("processing.actions.confirmBody", {
|
pendingCredits === null
|
||||||
count: pendingCount,
|
? i18n.t("processing.actions.confirmWithoutEstimate", { count: pendingCount })
|
||||||
credits: pendingCredits.toFixed(2)
|
: i18n.t("processing.actions.confirmBody", {
|
||||||
})
|
count: pendingCount,
|
||||||
|
credits: pendingCredits.toFixed(2)
|
||||||
|
})
|
||||||
);
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -166,14 +197,19 @@
|
|||||||
|
|
||||||
{#if activeTab !== "processed"}
|
{#if activeTab !== "processed"}
|
||||||
{#if pricingError}
|
{#if pricingError}
|
||||||
<p class="text-xs text-destructive" role="alert">Unable to load processing prices. Refresh before starting a job.</p>
|
<div class="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground" role="status">
|
||||||
|
<span>{i18n.t("processing.actions.estimateUnavailable")}</span>
|
||||||
|
<Button size="sm" variant="ghost" class="h-7 px-2 text-xs" disabled={pricingLoading} onclick={() => void loadProcessingCosts()}>
|
||||||
|
<RotateCcw class="mr-1 h-3 w-3" />{i18n.t("processing.retry")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
<div class="relative">
|
<div class="relative">
|
||||||
<Button
|
<Button
|
||||||
variant="default"
|
variant="default"
|
||||||
size="sm"
|
size="sm"
|
||||||
mutation
|
mutation
|
||||||
disabled={selectedCount === 0 || isProcessing || !pricingReady}
|
disabled={selectedCount === 0 || isProcessing || pricingLoading}
|
||||||
loading={isProcessing}
|
loading={isProcessing}
|
||||||
data-assistant-target="start-processing"
|
data-assistant-target="start-processing"
|
||||||
data-tour="start-processing"
|
data-tour="start-processing"
|
||||||
@@ -208,13 +244,15 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
{#if processingMode === "product"}
|
{#if processingMode !== "outputs"}
|
||||||
<div class="flex items-center justify-between gap-3 rounded-md border border-border/60 px-2 py-3">
|
<div class="flex items-center justify-between gap-3 rounded-md border border-border/60 px-2 py-3">
|
||||||
<div>
|
<div>
|
||||||
<p class="text-sm font-semibold">Product processing</p>
|
<p class="text-sm font-semibold">{i18n.t("processing.actions.fullEnrichment")}</p>
|
||||||
<p class="text-xs text-muted-foreground">AI title, description and SEO metadata together. No individual output selection.</p>
|
<p class="text-xs text-muted-foreground">{i18n.t("processing.actions.fullEnrichmentBody")}</p>
|
||||||
</div>
|
</div>
|
||||||
<span class="shrink-0 font-mono text-xs">{(effectiveCosts.product ?? 0.45).toFixed(4)} credits</span>
|
{#if totalCredits !== null}
|
||||||
|
<span class="shrink-0 font-mono text-xs">{effectiveCosts.product.toFixed(4)} {i18n.t("processing.actions.creditsUnit")}</span>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{:else}
|
{:else}
|
||||||
<button
|
<button
|
||||||
@@ -277,13 +315,13 @@
|
|||||||
{/if}
|
{/if}
|
||||||
<div class="flex items-center justify-between text-sm">
|
<div class="flex items-center justify-between text-sm">
|
||||||
<span class="font-medium text-foreground">{i18n.t("processing.actions.totalCredits", { count: selectedCount })}</span>
|
<span class="font-medium text-foreground">{i18n.t("processing.actions.totalCredits", { count: selectedCount })}</span>
|
||||||
<span class="font-mono font-medium text-primary">{totalCredits.toFixed(2)}</span>
|
<span class="font-mono font-medium text-primary">{totalCredits === null ? i18n.t("processing.actions.estimateUnknown") : totalCredits.toFixed(2)}</span>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
size="sm"
|
size="sm"
|
||||||
class="w-full"
|
class="w-full"
|
||||||
mutation
|
mutation
|
||||||
disabled={!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
|
disabled={pricingLoading || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
|
||||||
loading={isProcessing}
|
loading={isProcessing}
|
||||||
onclick={processSelected}
|
onclick={processSelected}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -8,10 +8,12 @@ const plan = readFileSync(fileURLToPath(new URL('../../../routes/admin/billing/+
|
|||||||
|
|
||||||
test('per-product plan hides individual output choices', () => {
|
test('per-product plan hides individual output choices', () => {
|
||||||
assert.match(actions, /processingMode === "product"/);
|
assert.match(actions, /processingMode === "product"/);
|
||||||
assert.match(actions, /\{#if processingMode === "product"\}[\s\S]*?\{:else\}[\s\S]*?\{#each PROCESSING_OPTIONS as option\}/);
|
assert.match(actions, /\{#if processingMode !== "outputs"\}[\s\S]*?\{:else\}[\s\S]*?\{#each PROCESSING_OPTIONS as option\}/);
|
||||||
assert.match(actions, /pendingTypes = processingMode === "product" \? \[\.\.\.processProductTypes\]/);
|
assert.match(actions, /pendingTypes = processingMode !== "outputs" \? \[\.\.\.processProductTypes\]/);
|
||||||
assert.match(actions, /effectiveCosts\.product/);
|
assert.match(actions, /effectiveCosts\.product/);
|
||||||
assert.match(actions, /!pricingReady/);
|
assert.match(actions, /processingMode !== "outputs"/);
|
||||||
|
assert.match(actions, /pricingLoading/);
|
||||||
|
assert.match(actions, /processing.actions.confirmWithoutEstimate/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('plan popup opts in explicitly to the one-price-per-product mode', () => {
|
test('plan popup opts in explicitly to the one-price-per-product mode', () => {
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import test from 'node:test';
|
||||||
|
|
||||||
|
const actions = readFileSync(fileURLToPath(new URL('./ProductProcessingActions.svelte', import.meta.url)), 'utf8');
|
||||||
|
const english = readFileSync(fileURLToPath(new URL('../../i18n/messages/en.ts', import.meta.url)), 'utf8');
|
||||||
|
|
||||||
|
test('billing credit lookup failure does not disable product processing', () => {
|
||||||
|
assert.match(actions, /processingMode = "unknown"/);
|
||||||
|
assert.match(actions, /pricingError = true/);
|
||||||
|
assert.match(actions, /disabled=\{selectedCount === 0 \|\| isProcessing \|\| pricingLoading\}/);
|
||||||
|
assert.doesNotMatch(actions, /disabled=\{selectedCount === 0 \|\| isProcessing \|\| !pricingReady\}/);
|
||||||
|
assert.match(actions, /processingMode !== "outputs" \? \[\.\.\.processProductTypes\]/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no unverified credit amount appears in the confirmation', () => {
|
||||||
|
assert.match(actions, /totalCredits = \$derived\(!pricingReady \? null/);
|
||||||
|
assert.match(actions, /pendingCredits === null/);
|
||||||
|
assert.match(actions, /processing.actions.confirmWithoutEstimate/);
|
||||||
|
assert.match(actions, /loadProcessingCosts\(\)/);
|
||||||
|
assert.match(english, /Actual credit charges follow your company's current billing rates/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { textExportBlob } from './export-unicode.ts';
|
||||||
|
|
||||||
|
test('CSV and TSV exports have one BOM and preserve all Unicode text', async () => {
|
||||||
|
const sample = 'name,description\nČrpalka,žarnica šoba 東京\n';
|
||||||
|
for (const mime of ['text/csv', 'text/tab-separated-values']) {
|
||||||
|
const blob = textExportBlob(sample, mime);
|
||||||
|
const raw = new Uint8Array(await blob.arrayBuffer());
|
||||||
|
assert.deepEqual(Array.from(raw.slice(0, 3)), [0xef, 0xbb, 0xbf]);
|
||||||
|
assert.equal(new TextDecoder('utf-8', { ignoreBOM: true }).decode(raw), `\ufeff${sample}`);
|
||||||
|
assert.equal(blob.type, `${mime};charset=utf-8`);
|
||||||
|
assert.deepEqual(
|
||||||
|
new Uint8Array(await textExportBlob(`\ufeff${sample}`, mime).arrayBuffer()),
|
||||||
|
raw
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('XML and JSON text exports are plain UTF-8 with no BOM', async () => {
|
||||||
|
for (const mime of ['application/xml', 'application/json']) {
|
||||||
|
const value = 'Črpalka šoba žarnica';
|
||||||
|
const blob = textExportBlob(value, mime);
|
||||||
|
assert.equal(await blob.text(), value);
|
||||||
|
assert.equal(blob.type, `${mime};charset=utf-8`);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
/** Ensure text exports retain Unicode and Excel recognizes UTF-8 CSV/TSV. */
|
||||||
|
export function textExportBlob(content: string, mime: string): Blob {
|
||||||
|
const mimeBase = mime.split(';', 1)[0].trim().toLowerCase();
|
||||||
|
const isSpreadsheetText = mimeBase === 'text/csv' || mimeBase === 'text/tab-separated-values';
|
||||||
|
const text = isSpreadsheetText && !content.startsWith('\ufeff') ? `\ufeff${content}` : content;
|
||||||
|
return new Blob([text], { type: `${mimeBase};charset=utf-8` });
|
||||||
|
}
|
||||||
@@ -4422,7 +4422,14 @@ export const en: MessageDict = {
|
|||||||
"{count} product(s) need categorization for {types} processing",
|
"{count} product(s) need categorization for {types} processing",
|
||||||
"processing.actions.aiLocked":
|
"processing.actions.aiLocked":
|
||||||
"AI options are locked on Free. Upgrade to process titles/descriptions.",
|
"AI options are locked on Free. Upgrade to process titles/descriptions.",
|
||||||
"processing.actions.totalCredits": "Total Credits ({count} on this page):",
|
"processing.actions.totalCredits": "Estimated credits ({count} products):",
|
||||||
|
"processing.actions.estimateUnavailable": "Credit estimate unavailable. Product price and stock are not required to process.",
|
||||||
|
"processing.actions.estimateUnknown": "Not available",
|
||||||
|
"processing.actions.creditsUnit": "credits",
|
||||||
|
"processing.actions.fullEnrichment": "Full product enrichment",
|
||||||
|
"processing.actions.fullEnrichmentBody": "AI title, description and SEO metadata together. No product selling price or stock needed.",
|
||||||
|
"processing.actions.confirmWithoutEstimate":
|
||||||
|
"Process {count} product(s) with full enrichment? The credit estimate is temporarily unavailable. Actual credit charges follow your company's current billing rates, which may be per product or per output. Continue only if you agree to those rates. Missing product prices and stock are allowed.",
|
||||||
"processing.actions.starting": "Starting…",
|
"processing.actions.starting": "Starting…",
|
||||||
"processing.actions.processCount": "Process {count} on this page",
|
"processing.actions.processCount": "Process {count} on this page",
|
||||||
"processing.actions.close": "Close",
|
"processing.actions.close": "Close",
|
||||||
|
|||||||
@@ -2,6 +2,14 @@ import type { MessageDict } from "./types.ts";
|
|||||||
|
|
||||||
/** Slovenian (sl) UI strings for admin Fix A1  ready pack. Not registered in UI_LOCALES yet (avoid inventing locale switcher). */
|
/** Slovenian (sl) UI strings for admin Fix A1  ready pack. Not registered in UI_LOCALES yet (avoid inventing locale switcher). */
|
||||||
export const sl: MessageDict = {
|
export const sl: MessageDict = {
|
||||||
|
"processing.actions.totalCredits": "Predvideni krediti ({count} izdelkov):",
|
||||||
|
"processing.actions.estimateUnavailable": "Ocena kreditov ni na voljo. Cena in zaloga izdelka za obdelavo nista obvezni.",
|
||||||
|
"processing.actions.estimateUnknown": "Ni na voljo",
|
||||||
|
"processing.actions.creditsUnit": "kreditov",
|
||||||
|
"processing.actions.fullEnrichment": "Celovita obdelava izdelka",
|
||||||
|
"processing.actions.fullEnrichmentBody": "AI naziv, opis in SEO podatki. Prodajna cena in zaloga nista obvezni.",
|
||||||
|
"processing.actions.confirmWithoutEstimate": "Obdelam {count} izdelkov? Ocena porabe kreditov trenutno ni na voljo. Znesek določa veljavni cenik vašega podjetja, na izdelek ali posamezno vsebino. Nadaljujte le, če se s cenikom strinjate. Cena in zaloga izdelka nista obvezni.",
|
||||||
|
|
||||||
"confirm.deleteFeed": "Izbrišem vir »{name}« in vse njegove neobdelane izdelke? Že obdelani izdelki in izdelki, povezani z drugimi viri, se ohranijo. Dejanja ni mogoče razveljaviti.",
|
"confirm.deleteFeed": "Izbrišem vir »{name}« in vse njegove neobdelane izdelke? Že obdelani izdelki in izdelki, povezani z drugimi viri, se ohranijo. Dejanja ni mogoče razveljaviti.",
|
||||||
"admin.users.cloneCatalog": "Copy to my company",
|
"admin.users.cloneCatalog": "Copy to my company",
|
||||||
"admin.users.cloneCatalogAria": "Copy {name} catalog into your sandbox company",
|
"admin.users.cloneCatalogAria": "Copy {name} catalog into your sandbox company",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { goto } from "$app/navigation";
|
import { goto } from "$app/navigation";
|
||||||
import { api, ApiError, failureMessage } from "$lib/api";
|
import { api, ApiError, failureMessage } from "$lib/api";
|
||||||
|
import { textExportBlob } from "$lib/export-unicode";
|
||||||
import { unwrapList, unwrapTotal } from "$lib/list";
|
import { unwrapList, unwrapTotal } from "$lib/list";
|
||||||
import { isCompanyAdmin } from "$lib/company-admin";
|
import { isCompanyAdmin } from "$lib/company-admin";
|
||||||
import { authSession } from "$lib/auth-session.svelte";
|
import { authSession } from "$lib/auth-session.svelte";
|
||||||
@@ -160,7 +161,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function downloadText(filename: string, content: string, mime: string) {
|
function downloadText(filename: string, content: string, mime: string) {
|
||||||
const blob = new Blob([content], { type: mime });
|
const blob = textExportBlob(content, mime);
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement("a");
|
const a = document.createElement("a");
|
||||||
a.href = url;
|
a.href = url;
|
||||||
|
|||||||
Reference in new issue
Block a user