Fix
This commit is contained in:
1 parent
486502852e
commit
0e48ea427b
23 files changed
+386
-78
No files matched your search
@@ -1,6 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { i18n } from "$lib/i18n";
|
||||
import { failureMessage } from "$lib/api";
|
||||
import { textExportBlob } from "$lib/export-unicode";
|
||||
import type { Cat } from "$lib/categories/types";
|
||||
import { Dialog, Button, Input, Label, Select, Tabs, TabsList, TabsTrigger, TabsContent } from "$lib/components/ui";
|
||||
import { Upload, Download } from "@lucide/svelte";
|
||||
@@ -96,7 +97,7 @@
|
||||
|
||||
function downloadTemplate() {
|
||||
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 a = document.createElement("a");
|
||||
a.href = url;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { textExportBlob } from "$lib/export-unicode";
|
||||
|
||||
/** Full Descrybe sample feed templates (download + preview). */
|
||||
|
||||
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 {
|
||||
const isXml = kind === "xml";
|
||||
const blob = new Blob([isXml ? SAMPLE_FEED_XML : SAMPLE_FEED_CSV], {
|
||||
type: isXml ? "application/xml;charset=utf-8" : "text/csv;charset=utf-8"
|
||||
});
|
||||
const blob = textExportBlob(
|
||||
isXml ? SAMPLE_FEED_XML : SAMPLE_FEED_CSV,
|
||||
isXml ? "application/xml" : "text/csv"
|
||||
);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
|
||||
@@ -55,33 +55,62 @@
|
||||
let open = $state(false);
|
||||
let confirmProcessOpen = $state(false);
|
||||
let pendingTypes = $state<ProcessingType[]>([]);
|
||||
let pendingCredits = $state(0);
|
||||
let pendingCredits = $state<number | null>(null);
|
||||
let pendingCount = $state(0);
|
||||
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 processingMode = $state<"outputs" | "product">("outputs");
|
||||
let processingMode = $state<"outputs" | "product" | "unknown">("unknown");
|
||||
let pricingReady = $state(false);
|
||||
let pricingLoading = $state(true);
|
||||
let pricingError = $state(false);
|
||||
let requestSerial = 0;
|
||||
const processProductTypes: ProcessingType[] = ["title", "description", "seo_meta"];
|
||||
onMount(() => {
|
||||
void api<{ mode: "outputs" | "product"; credits: Record<ProcessingType | "product", number> }>("/api/billing/processing-costs")
|
||||
.then((result) => {
|
||||
if (result?.credits) effectiveCosts = result.credits;
|
||||
processingMode = result?.mode === "product" ? "product" : "outputs";
|
||||
pricingReady = true;
|
||||
})
|
||||
.catch(() => { pricingError = true; });
|
||||
});
|
||||
|
||||
// Credit pricing is about the company's billing plan, not the product's
|
||||
// selling price or stock. A failed estimate must not disable enrichment.
|
||||
// When the mode cannot be verified, offer full enrichment only so callers
|
||||
// cannot inadvertently expect a per-output price on a flat-rate plan.
|
||||
async function loadProcessingCosts() {
|
||||
const serial = ++requestSerial;
|
||||
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(
|
||||
(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).
|
||||
const totalCredits = $derived(processingMode === "product"
|
||||
? (effectiveCosts.product ?? 0.45) * selectedCount
|
||||
const totalCredits = $derived(!pricingReady ? null : processingMode === "product"
|
||||
? effectiveCosts.product * selectedCount
|
||||
: PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
|
||||
(sum, option) => sum + (effectiveCosts[option.type] ?? option.credits),
|
||||
(sum, option) => sum + effectiveCosts[option.type],
|
||||
0
|
||||
) * selectedCount
|
||||
);
|
||||
@@ -101,9 +130,9 @@
|
||||
}
|
||||
|
||||
function processSelected() {
|
||||
if (!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0)) return;
|
||||
if (pricingLoading || (processingMode === "outputs" && selectedTypes.length === 0)) return;
|
||||
if (selectedAILocked) return;
|
||||
pendingTypes = processingMode === "product" ? [...processProductTypes] : [...selectedTypes];
|
||||
pendingTypes = processingMode !== "outputs" ? [...processProductTypes] : [...selectedTypes];
|
||||
pendingCredits = totalCredits;
|
||||
pendingCount = selectedCount;
|
||||
open = false;
|
||||
@@ -113,7 +142,7 @@
|
||||
function cancelProcessConfirm() {
|
||||
confirmProcessOpen = false;
|
||||
pendingTypes = [];
|
||||
pendingCredits = 0;
|
||||
pendingCredits = null;
|
||||
pendingCount = 0;
|
||||
}
|
||||
|
||||
@@ -124,7 +153,7 @@
|
||||
}
|
||||
const types = pendingTypes;
|
||||
pendingTypes = [];
|
||||
pendingCredits = 0;
|
||||
pendingCredits = null;
|
||||
pendingCount = 0;
|
||||
confirmProcessOpen = false;
|
||||
selectedTypes = [];
|
||||
@@ -132,10 +161,12 @@
|
||||
}
|
||||
|
||||
const processConfirmDescription = $derived(
|
||||
i18n.t("processing.actions.confirmBody", {
|
||||
count: pendingCount,
|
||||
credits: pendingCredits.toFixed(2)
|
||||
})
|
||||
pendingCredits === null
|
||||
? i18n.t("processing.actions.confirmWithoutEstimate", { count: pendingCount })
|
||||
: i18n.t("processing.actions.confirmBody", {
|
||||
count: pendingCount,
|
||||
credits: pendingCredits.toFixed(2)
|
||||
})
|
||||
);
|
||||
</script>
|
||||
|
||||
@@ -166,14 +197,19 @@
|
||||
|
||||
{#if activeTab !== "processed"}
|
||||
{#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}
|
||||
<div class="relative">
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
mutation
|
||||
disabled={selectedCount === 0 || isProcessing || !pricingReady}
|
||||
disabled={selectedCount === 0 || isProcessing || pricingLoading}
|
||||
loading={isProcessing}
|
||||
data-assistant-target="start-processing"
|
||||
data-tour="start-processing"
|
||||
@@ -208,13 +244,15 @@
|
||||
</div>
|
||||
</div>
|
||||
{/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>
|
||||
<p class="text-sm font-semibold">Product processing</p>
|
||||
<p class="text-xs text-muted-foreground">AI title, description and SEO metadata together. No individual output selection.</p>
|
||||
<p class="text-sm font-semibold">{i18n.t("processing.actions.fullEnrichment")}</p>
|
||||
<p class="text-xs text-muted-foreground">{i18n.t("processing.actions.fullEnrichmentBody")}</p>
|
||||
</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>
|
||||
{:else}
|
||||
<button
|
||||
@@ -277,13 +315,13 @@
|
||||
{/if}
|
||||
<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-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>
|
||||
<Button
|
||||
size="sm"
|
||||
class="w-full"
|
||||
mutation
|
||||
disabled={!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
|
||||
disabled={pricingLoading || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
|
||||
loading={isProcessing}
|
||||
onclick={processSelected}
|
||||
>
|
||||
|
||||
@@ -8,10 +8,12 @@ const plan = readFileSync(fileURLToPath(new URL('../../../routes/admin/billing/+
|
||||
|
||||
test('per-product plan hides individual output choices', () => {
|
||||
assert.match(actions, /processingMode === "product"/);
|
||||
assert.match(actions, /\{#if processingMode === "product"\}[\s\S]*?\{:else\}[\s\S]*?\{#each PROCESSING_OPTIONS as option\}/);
|
||||
assert.match(actions, /pendingTypes = processingMode === "product" \? \[\.\.\.processProductTypes\]/);
|
||||
assert.match(actions, /\{#if processingMode !== "outputs"\}[\s\S]*?\{:else\}[\s\S]*?\{#each PROCESSING_OPTIONS as option\}/);
|
||||
assert.match(actions, /pendingTypes = processingMode !== "outputs" \? \[\.\.\.processProductTypes\]/);
|
||||
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', () => {
|
||||
|
||||
@@ -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",
|
||||
"processing.actions.aiLocked":
|
||||
"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.processCount": "Process {count} on this page",
|
||||
"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). */
|
||||
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.",
|
||||
"admin.users.cloneCatalog": "Copy to my company",
|
||||
"admin.users.cloneCatalogAria": "Copy {name} catalog into your sandbox company",
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { onMount } from "svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
import { api, ApiError, failureMessage } from "$lib/api";
|
||||
import { textExportBlob } from "$lib/export-unicode";
|
||||
import { unwrapList, unwrapTotal } from "$lib/list";
|
||||
import { isCompanyAdmin } from "$lib/company-admin";
|
||||
import { authSession } from "$lib/auth-session.svelte";
|
||||
@@ -160,7 +161,7 @@
|
||||
}
|
||||
|
||||
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 a = document.createElement("a");
|
||||
a.href = url;
|
||||
|
||||
Reference in new issue
Block a user