This commit is contained in:
greeneclipse committed 2026-10-20 18:03:58 +02:00
1 parent edbbf127ba
commit c347d2418f
4 files changed
+98 -83

No files matched your search

@@ -2,7 +2,6 @@
import { Check, CheckSquare, ChevronDown, FileUp, RotateCcw, X } from "@lucide/svelte"; import { Check, CheckSquare, ChevronDown, FileUp, RotateCcw, X } from "@lucide/svelte";
import { Button } from "$lib/components/ui"; import { Button } from "$lib/components/ui";
import { buttonClasses } from "$lib/components/ui/button-variants"; import { buttonClasses } from "$lib/components/ui/button-variants";
import ConfirmationDialog from "$lib/components/categories/formula/ConfirmationDialog.svelte";
import { cn } from "$lib/utils"; import { cn } from "$lib/utils";
import { i18n } from "$lib/i18n"; import { i18n } from "$lib/i18n";
import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types"; import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types";
@@ -10,6 +9,7 @@
let { let {
selectedCount, selectedCount,
initialOpen = false,
selectedProducts = [], selectedProducts = [],
products = [], products = [],
activeTab = "processed", activeTab = "processed",
@@ -28,6 +28,7 @@
onResetToUnprocessed onResetToUnprocessed
}: { }: {
selectedCount: number; selectedCount: number;
initialOpen?: boolean;
selectedProducts?: Array<string | number>; selectedProducts?: Array<string | number>;
products?: ProductRow[]; products?: ProductRow[];
activeTab?: string; activeTab?: string;
@@ -42,7 +43,7 @@
onClear: () => void; onClear: () => void;
primaryLanguage?: string; primaryLanguage?: string;
contentLanguages?: string[]; contentLanguages?: string[];
onProcess: (types: ProcessingType[], language: string) => void; onProcess: (types: ProcessingType[], language: string) => Promise<void> | void;
onExport: () => void; onExport: () => void;
onMarkAsProcessed?: () => void; onMarkAsProcessed?: () => void;
onResetToUnprocessed?: () => void; onResetToUnprocessed?: () => void;
@@ -55,25 +56,20 @@
return !opt?.requiresAI || canUseAI; return !opt?.requiresAI || canUseAI;
} }
let open = $state(false); let open = $state(initialOpen);
let confirmProcessOpen = $state(false); let submitting = $state(false);
let pendingTypes = $state<ProcessingType[]>([]);
let pendingCredits = $state<number | null>(null);
let pendingCount = $state(0);
let selectedTypes = $state<ProcessingType[]>(["title", "description", "seo_meta"]); let selectedTypes = $state<ProcessingType[]>(["title", "description", "seo_meta"]);
let selectedLanguage = $state(""); let selectedLanguage = $state("");
const languageOptions = $derived([primaryLanguage, ...contentLanguages].filter( const languageOptions = $derived([primaryLanguage, ...contentLanguages].filter(
(lang, index, all) => all.indexOf(lang) === index (lang, index, all) => all.indexOf(lang) === index
)); ));
const targetLanguage = $derived(languageOptions.includes(selectedLanguage) ? selectedLanguage : primaryLanguage); const targetLanguage = $derived(languageOptions.includes(selectedLanguage) ? selectedLanguage : primaryLanguage);
let pendingLanguage = $state("");
const selectedAILocked = $derived(selectedTypes.some( const selectedAILocked = $derived(selectedTypes.some(
(t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t) (t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t)
)); ));
// A single product in a single language costs 1 credit, no matter how many // A single product in one language costs 1 credit regardless of outputs.
// of the three outputs are selected. Show only the total charge.
const totalCredits = $derived(selectedTypes.length === 0 ? 0 : selectedCount); const totalCredits = $derived(selectedTypes.length === 0 ? 0 : selectedCount);
function toggleType(type: ProcessingType) { function toggleType(type: ProcessingType) {
@@ -90,49 +86,21 @@
selectedTypes = all.every((t) => selectedTypes.includes(t)) ? [] : all; selectedTypes = all.every((t) => selectedTypes.includes(t)) ? [] : all;
} }
function processSelected() { // Start immediately. The parent owns the API request, success toast and
if (selectedTypes.length === 0) return; // selection reset. Never clear selection before a job was accepted.
if (selectedAILocked) return; async function processSelected() {
pendingTypes = [...selectedTypes]; if (selectedTypes.length === 0 || selectedAILocked || isProcessing || submitting) return;
pendingLanguage = targetLanguage; const outputs = [...selectedTypes];
pendingCredits = totalCredits; const language = targetLanguage;
pendingCount = selectedCount; submitting = true;
open = false; open = false;
confirmProcessOpen = true; try {
await onProcess(outputs, language);
} finally {
submitting = false;
}
} }
function cancelProcessConfirm() {
confirmProcessOpen = false;
pendingTypes = [];
pendingLanguage = "";
pendingCredits = null;
pendingCount = 0;
}
function confirmProcess() {
if (pendingTypes.length === 0) {
cancelProcessConfirm();
return;
}
const types = pendingTypes;
const language = pendingLanguage;
pendingTypes = [];
pendingLanguage = "";
pendingCredits = null;
pendingCount = 0;
confirmProcessOpen = false;
selectedTypes = [...processProductTypes];
onProcess(types, language);
}
const processConfirmDescription = $derived(
pendingCredits === null
? i18n.t("processing.actions.confirmWithoutEstimate", { count: pendingCount })
: i18n.t("processing.actions.confirmBody", {
count: pendingCount,
credits: String(pendingCredits)
})
);
</script> </script>
<div <div
@@ -151,7 +119,7 @@
variant="ghost" variant="ghost"
size="sm" size="sm"
onclick={onClear} onclick={onClear}
disabled={selectedCount === 0 || isProcessing} disabled={selectedCount === 0 || isProcessing || submitting}
class="h-8 px-2 text-xs" class="h-8 px-2 text-xs"
aria-label={i18n.t("processing.actions.clearSelection")} aria-label={i18n.t("processing.actions.clearSelection")}
> >
@@ -160,15 +128,13 @@
</Button> </Button>
{/if} {/if}
{#if activeTab !== "processed"}
<div class="relative"> <div class="relative">
<Button <Button
variant="default" variant="default"
size="sm" size="sm"
mutation mutation
disabled={selectedCount === 0 || isProcessing} disabled={selectedCount === 0 || isProcessing || submitting}
loading={isProcessing} loading={isProcessing || submitting}
data-assistant-target="start-processing" data-assistant-target="start-processing"
data-tour="start-processing" data-tour="start-processing"
onclick={() => (open = !open)} onclick={() => (open = !open)}
@@ -280,11 +246,11 @@
size="sm" size="sm"
class="w-full" class="w-full"
mutation mutation
disabled={selectedTypes.length === 0 || isProcessing || selectedAILocked} disabled={selectedTypes.length === 0 || isProcessing || submitting || selectedAILocked}
loading={isProcessing} loading={isProcessing || submitting}
onclick={processSelected} onclick={() => void processSelected()}
> >
{isProcessing ? i18n.t("processing.actions.starting") : i18n.t("processing.actions.processCount", { count: selectedCount })} {(isProcessing || submitting) ? i18n.t("processing.actions.starting") : i18n.t("processing.actions.processCount", { count: selectedCount })}
</Button> </Button>
</div> </div>
</div> </div>
@@ -292,7 +258,6 @@
></button> ></button>
{/if} {/if}
</div> </div>
{/if}
{#if activeTab === "needs_review" && onMarkAsProcessed} {#if activeTab === "needs_review" && onMarkAsProcessed}
<Button <Button
@@ -300,7 +265,7 @@
size="sm" size="sm"
mutation mutation
onclick={onMarkAsProcessed} onclick={onMarkAsProcessed}
disabled={selectedCount === 0 || isProcessing} disabled={selectedCount === 0 || isProcessing || submitting}
> >
<Check class="mr-2 h-4 w-4" /> <Check class="mr-2 h-4 w-4" />
<span class="sm:hidden">{i18n.t("processing.actions.accept")}</span> <span class="sm:hidden">{i18n.t("processing.actions.accept")}</span>
@@ -313,7 +278,7 @@
class={buttonClasses("outline", "sm")} class={buttonClasses("outline", "sm")}
aria-label={i18n.t("products.actions.exportSelected")} aria-label={i18n.t("products.actions.exportSelected")}
data-testid="export-selected" data-testid="export-selected"
disabled={selectedCount === 0 || isProcessing} disabled={selectedCount === 0 || isProcessing || submitting}
onclick={() => onExport()} onclick={() => onExport()}
> >
<FileUp class="mr-2 h-4 w-4" /> <FileUp class="mr-2 h-4 w-4" />
@@ -327,7 +292,7 @@
size="sm" size="sm"
mutation mutation
onclick={onResetToUnprocessed} onclick={onResetToUnprocessed}
disabled={selectedCount === 0 || isProcessing} disabled={selectedCount === 0 || isProcessing || submitting}
class="border-chart-amber/50 text-chart-amber hover:bg-chart-amber/15 hover:text-foreground" class="border-chart-amber/50 text-chart-amber hover:bg-chart-amber/15 hover:text-foreground"
> >
<RotateCcw class="mr-2 h-4 w-4" /> <RotateCcw class="mr-2 h-4 w-4" />
@@ -336,13 +301,3 @@
</Button> </Button>
{/if} {/if}
</div> </div>
<ConfirmationDialog
bind:open={confirmProcessOpen}
title={i18n.t("products.processing.confirm")}
description={processConfirmDescription}
confirmLabel={i18n.t("processing.actions.confirmStart")}
confirmVariant="default"
onClose={cancelProcessConfirm}
onConfirm={confirmProcess}
/>
@@ -6,14 +6,10 @@ import test from 'node:test';
const actions = readFileSync(fileURLToPath(new URL('./ProductProcessingActions.svelte', import.meta.url)), 'utf8'); const actions = readFileSync(fileURLToPath(new URL('./ProductProcessingActions.svelte', import.meta.url)), 'utf8');
const plan = readFileSync(fileURLToPath(new URL('../../../routes/admin/billing/+page.svelte', import.meta.url)), 'utf8'); const plan = readFileSync(fileURLToPath(new URL('../../../routes/admin/billing/+page.svelte', import.meta.url)), 'utf8');
test('per-product plan hides individual output choices', () => { test('catalog menu charges one credit per selected product without per-output prices', () => {
assert.match(actions, /processingMode === "product"/); assert.match(actions, /selectedTypes\.length === 0 \? 0 : selectedCount/);
assert.match(actions, /\{#if processingMode !== "outputs"\}[\s\S]*?\{:else\}[\s\S]*?\{#each PROCESSING_OPTIONS as option\}/); assert.match(actions, /"Total credits"/);
assert.match(actions, /pendingTypes = processingMode !== "outputs" \? \[\.\.\.processProductTypes\]/); assert.doesNotMatch(actions, /effectiveCosts|pricingLoading|creditPriceMap/);
assert.match(actions, /effectiveCosts\.product/);
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,40 @@
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 page = readFileSync(fileURLToPath(new URL('../../../routes/products/+page.svelte', import.meta.url)), 'utf8');
test('start button sends selected outputs and language without a second confirmation', () => {
assert.match(actions, /async function processSelected\(\)/);
assert.match(actions, /const outputs = \[\.\.\.selectedTypes\]/);
assert.match(actions, /const language = targetLanguage/);
assert.match(actions, /await onProcess\(outputs, language\)/);
assert.match(actions, /onclick=\{\(\) => void processSelected\(\)\}/);
assert.doesNotMatch(actions, /processProductTypes|confirmProcessOpen|<ConfirmationDialog/);
});
test('start button prevents duplicate submission until the API call finishes', () => {
assert.match(actions, /isProcessing \|\| submitting\) return/);
assert.match(actions, /submitting = true/);
assert.match(actions, /finally \{\s*submitting = false;/);
assert.match(page, /onProcess=\{\(types, language\) => startProcessing\(types, language\)\}/);
});
test('all shown products are selected, with the processing menu opened', () => {
assert.match(page, /function selectShownForProcessing\(\) \{[\s\S]*?selectableProductIds\(processableOnPage\)/);
assert.match(page, /openProcessingAfterSelect = true;\s*selectedIds = ids;/);
assert.match(page, /initialOpen=\{openProcessingAfterSelect\}/);
assert.match(page, /Process all shown \(\{processableOnPage\.length\}\)/);
});
test('a successful accepted processing job triggers notification and clears selection', () => {
const start = page.split('async function startProcessing(')[1]?.split('\n\tfunction requestMarkAsProcessed', 1)[0] ?? '';
assert.match(start, /await api<[\s\S]*?\("\/api\/processing\/jobs",\s*\{/);
assert.match(start, /processing_types: types/);
assert.match(start, /notifySuccess\(i18n\.t\("toast\.products\.jobStarted"\)/);
assert.match(start, /notifySuccess[\s\S]*?selectedIds = \[\];/);
assert.match(start, /catch \(err\) \{[\s\S]*?notifyApiError/);
assert.doesNotMatch(start.split('catch (err)')[1] ?? '', /selectedIds = \[\]/);
});
+26 -2
View File
@@ -152,6 +152,7 @@
let productsFetchGen = 0; let productsFetchGen = 0;
let selectedIds = $state<Array<string | number>>([]); let selectedIds = $state<Array<string | number>>([]);
let openProcessingAfterSelect = $state(false);
let editOpen = $state(false); let editOpen = $state(false);
let showKeyboardTip = $state(false); let showKeyboardTip = $state(false);
let editing = $state<ProductRow | null>(null); let editing = $state<ProductRow | null>(null);
@@ -599,13 +600,24 @@
} }
function toggleSelect(id: string | number, selected: boolean) { function toggleSelect(id: string | number, selected: boolean) {
openProcessingAfterSelect = false;
selectedIds = setProductSelected(selectedIds, id, selected); selectedIds = setProductSelected(selectedIds, id, selected);
} }
function toggleSelectAll() { function toggleSelectAll() {
openProcessingAfterSelect = false;
selectedIds = toggleSelectAllIds(selectedIds, selectableProductIds(products)); selectedIds = toggleSelectAllIds(selectedIds, selectableProductIds(products));
} }
// Process exactly the currently displayed, eligible products. This deliberately
// does not enqueue unseen pages or products already processing.
function selectShownForProcessing() {
const ids = selectableProductIds(processableOnPage);
if (ids.length === 0) return;
openProcessingAfterSelect = true;
selectedIds = ids;
}
function selectedRawIds(): string[] { function selectedRawIds(): string[] {
return selectedRawProductIds(products, selectedIds, kind); return selectedRawProductIds(products, selectedIds, kind);
} }
@@ -685,6 +697,7 @@
duration: 12000 duration: 12000
}); });
selectedIds = []; selectedIds = [];
openProcessingAfterSelect = false;
void loadProducts({ soft: true }); void loadProducts({ soft: true });
} catch (err) { } catch (err) {
error = notifyApiError(err, i18n.t("toast.products.startJobFailed"), { error = notifyApiError(err, i18n.t("toast.products.startJobFailed"), {
@@ -1149,6 +1162,9 @@
const selectableOnPage = $derived( const selectableOnPage = $derived(
products.filter((p) => p.processing_status !== "processing") products.filter((p) => p.processing_status !== "processing")
); );
const processableOnPage = $derived(
selectableOnPage.filter((p) => kind === "raw" || Boolean(p.raw_product_id))
);
const allPageSelected = $derived( const allPageSelected = $derived(
selectableOnPage.length > 0 && selectableOnPage.length > 0 &&
selectableOnPage.every((p) => selectedIds.some((id) => String(id) === String(p.id))) selectableOnPage.every((p) => selectedIds.some((id) => String(id) === String(p.id)))
@@ -1345,6 +1361,13 @@
/> />
</div> </div>
{#if selectedIds.length === 0 && processableOnPage.length > 0}
<div class="flex justify-end border-b border-border px-3 py-2 sm:px-6">
<Button variant="outline" size="sm" onclick={selectShownForProcessing} disabled={startingJob || fetching}>
Process all shown ({processableOnPage.length})…
</Button>
</div>
{/if}
{#if selectedIds.length > 0} {#if selectedIds.length > 0}
<div class="border-b border-border bg-card"> <div class="border-b border-border bg-card">
<div <div
@@ -1366,6 +1389,7 @@
<div class="min-w-0 w-full sm:w-auto"> <div class="min-w-0 w-full sm:w-auto">
<ProductProcessingActions <ProductProcessingActions
selectedCount={selectedIds.length} selectedCount={selectedIds.length}
initialOpen={openProcessingAfterSelect}
selectedProducts={selectedIds} selectedProducts={selectedIds}
products={products} products={products}
{activeTab} {activeTab}
@@ -1375,10 +1399,10 @@
{canUseAI} {canUseAI}
{canProcessAITitles} {canProcessAITitles}
{canProcessAIDescriptions} {canProcessAIDescriptions}
onClear={() => (selectedIds = [])} onClear={() => { selectedIds = []; openProcessingAfterSelect = false; }}
primaryLanguage={primaryProcessingLanguage} primaryLanguage={primaryProcessingLanguage}
contentLanguages={enabledProcessingLanguages} contentLanguages={enabledProcessingLanguages}
onProcess={(types, language) => void startProcessing(types, language)} onProcess={(types, language) => startProcessing(types, language)}
onExport={openExportDialog} onExport={openExportDialog}
onMarkAsProcessed={requestMarkAsProcessed} onMarkAsProcessed={requestMarkAsProcessed}
onResetToUnprocessed={canAdmin ? requestResetToUnprocessed : undefined} onResetToUnprocessed={canAdmin ? requestResetToUnprocessed : undefined}