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 { Button } from "$lib/components/ui";
import { buttonClasses } from "$lib/components/ui/button-variants";
import ConfirmationDialog from "$lib/components/categories/formula/ConfirmationDialog.svelte";
import { cn } from "$lib/utils";
import { i18n } from "$lib/i18n";
import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types";
@@ -10,6 +9,7 @@
let {
selectedCount,
initialOpen = false,
selectedProducts = [],
products = [],
activeTab = "processed",
@@ -28,6 +28,7 @@
onResetToUnprocessed
}: {
selectedCount: number;
initialOpen?: boolean;
selectedProducts?: Array<string | number>;
products?: ProductRow[];
activeTab?: string;
@@ -42,7 +43,7 @@
onClear: () => void;
primaryLanguage?: string;
contentLanguages?: string[];
onProcess: (types: ProcessingType[], language: string) => void;
onProcess: (types: ProcessingType[], language: string) => Promise<void> | void;
onExport: () => void;
onMarkAsProcessed?: () => void;
onResetToUnprocessed?: () => void;
@@ -55,25 +56,20 @@
return !opt?.requiresAI || canUseAI;
}
let open = $state(false);
let confirmProcessOpen = $state(false);
let pendingTypes = $state<ProcessingType[]>([]);
let pendingCredits = $state<number | null>(null);
let pendingCount = $state(0);
let open = $state(initialOpen);
let submitting = $state(false);
let selectedTypes = $state<ProcessingType[]>(["title", "description", "seo_meta"]);
let selectedLanguage = $state("");
const languageOptions = $derived([primaryLanguage, ...contentLanguages].filter(
(lang, index, all) => all.indexOf(lang) === index
));
const targetLanguage = $derived(languageOptions.includes(selectedLanguage) ? selectedLanguage : primaryLanguage);
let pendingLanguage = $state("");
const selectedAILocked = $derived(selectedTypes.some(
(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
// of the three outputs are selected. Show only the total charge.
// A single product in one language costs 1 credit regardless of outputs.
const totalCredits = $derived(selectedTypes.length === 0 ? 0 : selectedCount);
function toggleType(type: ProcessingType) {
@@ -90,49 +86,21 @@
selectedTypes = all.every((t) => selectedTypes.includes(t)) ? [] : all;
}
function processSelected() {
if (selectedTypes.length === 0) return;
if (selectedAILocked) return;
pendingTypes = [...selectedTypes];
pendingLanguage = targetLanguage;
pendingCredits = totalCredits;
pendingCount = selectedCount;
// Start immediately. The parent owns the API request, success toast and
// selection reset. Never clear selection before a job was accepted.
async function processSelected() {
if (selectedTypes.length === 0 || selectedAILocked || isProcessing || submitting) return;
const outputs = [...selectedTypes];
const language = targetLanguage;
submitting = true;
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>
<div
@@ -151,7 +119,7 @@
variant="ghost"
size="sm"
onclick={onClear}
disabled={selectedCount === 0 || isProcessing}
disabled={selectedCount === 0 || isProcessing || submitting}
class="h-8 px-2 text-xs"
aria-label={i18n.t("processing.actions.clearSelection")}
>
@@ -160,15 +128,13 @@
</Button>
{/if}
{#if activeTab !== "processed"}
<div class="relative">
<Button
variant="default"
size="sm"
mutation
disabled={selectedCount === 0 || isProcessing}
loading={isProcessing}
disabled={selectedCount === 0 || isProcessing || submitting}
loading={isProcessing || submitting}
data-assistant-target="start-processing"
data-tour="start-processing"
onclick={() => (open = !open)}
@@ -280,11 +246,11 @@
size="sm"
class="w-full"
mutation
disabled={selectedTypes.length === 0 || isProcessing || selectedAILocked}
loading={isProcessing}
onclick={processSelected}
disabled={selectedTypes.length === 0 || isProcessing || submitting || selectedAILocked}
loading={isProcessing || submitting}
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>
</div>
</div>
@@ -292,7 +258,6 @@
></button>
{/if}
</div>
{/if}
{#if activeTab === "needs_review" && onMarkAsProcessed}
<Button
@@ -300,7 +265,7 @@
size="sm"
mutation
onclick={onMarkAsProcessed}
disabled={selectedCount === 0 || isProcessing}
disabled={selectedCount === 0 || isProcessing || submitting}
>
<Check class="mr-2 h-4 w-4" />
<span class="sm:hidden">{i18n.t("processing.actions.accept")}</span>
@@ -313,7 +278,7 @@
class={buttonClasses("outline", "sm")}
aria-label={i18n.t("products.actions.exportSelected")}
data-testid="export-selected"
disabled={selectedCount === 0 || isProcessing}
disabled={selectedCount === 0 || isProcessing || submitting}
onclick={() => onExport()}
>
<FileUp class="mr-2 h-4 w-4" />
@@ -327,7 +292,7 @@
size="sm"
mutation
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"
>
<RotateCcw class="mr-2 h-4 w-4" />
@@ -336,13 +301,3 @@
</Button>
{/if}
</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 plan = readFileSync(fileURLToPath(new URL('../../../routes/admin/billing/+page.svelte', import.meta.url)), 'utf8');
test('per-product plan hides individual output choices', () => {
assert.match(actions, /processingMode === "product"/);
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, /processingMode !== "outputs"/);
assert.match(actions, /pricingLoading/);
assert.match(actions, /processing.actions.confirmWithoutEstimate/);
test('catalog menu charges one credit per selected product without per-output prices', () => {
assert.match(actions, /selectedTypes\.length === 0 \? 0 : selectedCount/);
assert.match(actions, /"Total credits"/);
assert.doesNotMatch(actions, /effectiveCosts|pricingLoading|creditPriceMap/);
});
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 selectedIds = $state<Array<string | number>>([]);
let openProcessingAfterSelect = $state(false);
let editOpen = $state(false);
let showKeyboardTip = $state(false);
let editing = $state<ProductRow | null>(null);
@@ -599,13 +600,24 @@
}
function toggleSelect(id: string | number, selected: boolean) {
openProcessingAfterSelect = false;
selectedIds = setProductSelected(selectedIds, id, selected);
}
function toggleSelectAll() {
openProcessingAfterSelect = false;
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[] {
return selectedRawProductIds(products, selectedIds, kind);
}
@@ -685,6 +697,7 @@
duration: 12000
});
selectedIds = [];
openProcessingAfterSelect = false;
void loadProducts({ soft: true });
} catch (err) {
error = notifyApiError(err, i18n.t("toast.products.startJobFailed"), {
@@ -1149,6 +1162,9 @@
const selectableOnPage = $derived(
products.filter((p) => p.processing_status !== "processing")
);
const processableOnPage = $derived(
selectableOnPage.filter((p) => kind === "raw" || Boolean(p.raw_product_id))
);
const allPageSelected = $derived(
selectableOnPage.length > 0 &&
selectableOnPage.every((p) => selectedIds.some((id) => String(id) === String(p.id)))
@@ -1345,6 +1361,13 @@
/>
</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}
<div class="border-b border-border bg-card">
<div
@@ -1366,6 +1389,7 @@
<div class="min-w-0 w-full sm:w-auto">
<ProductProcessingActions
selectedCount={selectedIds.length}
initialOpen={openProcessingAfterSelect}
selectedProducts={selectedIds}
products={products}
{activeTab}
@@ -1375,10 +1399,10 @@
{canUseAI}
{canProcessAITitles}
{canProcessAIDescriptions}
onClear={() => (selectedIds = [])}
onClear={() => { selectedIds = []; openProcessingAfterSelect = false; }}
primaryLanguage={primaryProcessingLanguage}
contentLanguages={enabledProcessingLanguages}
onProcess={(types, language) => void startProcessing(types, language)}
onProcess={(types, language) => startProcessing(types, language)}
onExport={openExportDialog}
onMarkAsProcessed={requestMarkAsProcessed}
onResetToUnprocessed={canAdmin ? requestResetToUnprocessed : undefined}