This commit is contained in:
greeneclipse committed 2026-10-20 17:50:32 +02:00
1 parent fd83a7c523
commit edbbf127ba
12 files changed
+246 -207

No files matched your search

@@ -5,9 +5,8 @@
import ConfirmationDialog from "$lib/components/categories/formula/ConfirmationDialog.svelte";
import { cn } from "$lib/utils";
import { i18n } from "$lib/i18n";
import { onMount } from "svelte";
import { api } from "$lib/api";
import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types";
import { PROCESSING_OPTIONS, type ProcessingType, type ProductRow } from "./types";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
let {
selectedCount,
@@ -17,7 +16,9 @@
isProcessing = false,
inline = false,
hideClear = false,
canUseAI = true,
primaryLanguage = "en",
contentLanguages = ["en"],
canUseAI = true,
canProcessAITitles = canUseAI,
canProcessAIDescriptions = canUseAI,
onClear,
@@ -39,7 +40,9 @@
/** When set, overrides canUseAI for the description AI option. */
canProcessAIDescriptions?: boolean;
onClear: () => void;
onProcess: (types: ProcessingType[]) => void;
primaryLanguage?: string;
contentLanguages?: string[];
onProcess: (types: ProcessingType[], language: string) => void;
onExport: () => void;
onMarkAsProcessed?: () => void;
onResetToUnprocessed?: () => void;
@@ -57,63 +60,21 @@
let pendingTypes = $state<ProcessingType[]>([]);
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" | "unknown">("unknown");
let pricingReady = $state(false);
let pricingLoading = $state(true);
let pricingError = $state(false);
let requestSerial = 0;
const processProductTypes: ProcessingType[] = ["title", "description", "seo_meta"];
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("");
// 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;
}
}
const selectedAILocked = $derived(selectedTypes.some(
(t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t)
));
onMount(() => { void loadProcessingCosts(); });
const selectedAILocked = $derived(
(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(!pricingReady ? null : processingMode === "product"
? effectiveCosts.product * selectedCount
: PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
(sum, option) => sum + effectiveCosts[option.type],
0
) * selectedCount
);
// 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.
const totalCredits = $derived(selectedTypes.length === 0 ? 0 : selectedCount);
function toggleType(type: ProcessingType) {
if (!aiAllowedForType(type) && PROCESSING_OPTIONS.find((o) => o.type === type)?.requiresAI) return;
@@ -130,9 +91,10 @@
}
function processSelected() {
if (pricingLoading || (processingMode === "outputs" && selectedTypes.length === 0)) return;
if (selectedTypes.length === 0) return;
if (selectedAILocked) return;
pendingTypes = processingMode !== "outputs" ? [...processProductTypes] : [...selectedTypes];
pendingTypes = [...selectedTypes];
pendingLanguage = targetLanguage;
pendingCredits = totalCredits;
pendingCount = selectedCount;
open = false;
@@ -142,6 +104,7 @@
function cancelProcessConfirm() {
confirmProcessOpen = false;
pendingTypes = [];
pendingLanguage = "";
pendingCredits = null;
pendingCount = 0;
}
@@ -152,12 +115,14 @@
return;
}
const types = pendingTypes;
const language = pendingLanguage;
pendingTypes = [];
pendingLanguage = "";
pendingCredits = null;
pendingCount = 0;
confirmProcessOpen = false;
selectedTypes = [];
onProcess(types);
selectedTypes = [...processProductTypes];
onProcess(types, language);
}
const processConfirmDescription = $derived(
@@ -165,7 +130,7 @@
? i18n.t("processing.actions.confirmWithoutEstimate", { count: pendingCount })
: i18n.t("processing.actions.confirmBody", {
count: pendingCount,
credits: pendingCredits.toFixed(2)
credits: String(pendingCredits)
})
);
</script>
@@ -196,20 +161,13 @@
{/if}
{#if activeTab !== "processed"}
{#if pricingError}
<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 || pricingLoading}
disabled={selectedCount === 0 || isProcessing}
loading={isProcessing}
data-assistant-target="start-processing"
data-tour="start-processing"
@@ -232,6 +190,23 @@
>
<div class="px-2 py-1.5 text-sm font-semibold text-foreground">{i18n.t("processing.actions.whatToProcess")}</div>
<div class="my-1 h-px bg-border"></div>
<div class="px-2 pt-2">
<label for="process-language" class="mb-1 block text-xs font-medium text-muted-foreground">Processing language</label>
<select
id="process-language"
class="w-full rounded-md border border-border bg-background px-2 py-2 text-sm text-foreground"
value={targetLanguage}
onchange={(event) => (selectedLanguage = event.currentTarget.value)}
>
{#each languageOptions as lang}
<option value={lang}>
{CONTENT_LANGUAGES.find((option) => option.value === lang)?.label ?? lang}
{lang === primaryLanguage ? " (Primary)" : ""}
</option>
{/each}
</select>
<p class="mt-1 text-xs text-muted-foreground">Only this language will be generated.</p>
</div>
<div class="p-2">
{#if !canProcessAITitles || !canProcessAIDescriptions}
<div class="mb-3 rounded border border-chart-amber/40 bg-chart-amber/15 p-2 text-xs">
@@ -244,17 +219,7 @@
</div>
</div>
{/if}
{#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">{i18n.t("processing.actions.fullEnrichment")}</p>
<p class="text-xs text-muted-foreground">{i18n.t("processing.actions.fullEnrichmentBody")}</p>
</div>
{#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
type="button"
class="mb-3 flex items-center space-x-2 border-b border-border/50 pb-3"
@@ -296,15 +261,9 @@
: ""}</span
>
</label>
<span class="font-mono text-xs text-muted-foreground"
>{option.requiresAI
? i18n.t("products.actions.credits", { credits: (effectiveCosts[option.type] ?? option.credits).toFixed(2) })
: i18n.t("products.actions.free")}</span
>
</div>
{/each}
</div>
{/if}
</div>
<div class="my-1 h-px bg-border"></div>
<div class="space-y-2 p-2">
@@ -314,14 +273,14 @@
</div>
{/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 === null ? i18n.t("processing.actions.estimateUnknown") : totalCredits.toFixed(2)}</span>
<span class="font-medium text-foreground">{"Total credits"}</span>
<span class="font-mono font-medium text-primary">{totalCredits} {i18n.t("processing.actions.creditsUnit")}</span>
</div>
<Button
size="sm"
class="w-full"
mutation
disabled={pricingLoading || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
disabled={selectedTypes.length === 0 || isProcessing || selectedAILocked}
loading={isProcessing}
onclick={processSelected}
>
@@ -4,20 +4,22 @@ 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');
const page = readFileSync(fileURLToPath(new URL('../../../routes/products/+page.svelte', 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('processing can select each output without per-output prices', () => {
assert.match(actions, /PROCESSING_OPTIONS as option/);
assert.doesNotMatch(actions, /effectiveCosts\[option\.type\]/);
assert.match(actions, /selectedTypes\.length === 0/);
});
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/);
test('one credit per selected product regardless of chosen outputs', () => {
assert.match(actions, /selectedCount\);/);
assert.match(actions, /onProcess\(types, language\)/);
});
test('language defaults to company primary and flows to job request', () => {
assert.match(actions, /targetLanguage/);
assert.match(actions, /contentLanguages/);
assert.match(page, /primaryProcessingLanguage/);
assert.match(page, /processing_types: types,\s*language/);
});
+13 -3
View File
@@ -30,6 +30,7 @@
import { authSession } from "$lib/auth-session.svelte";
import { planCapabilities } from "$lib/plan-capabilities.svelte";
import type { Category, Feed, ListResponse, MeResponse } from "$lib/types";
import { parseContentLanguage } from "$lib/content-languages";
import {
canUseAIFromCredits,
upgradeCtaForRole,
@@ -90,6 +91,8 @@
let upgradePrompt = $state(false);
let creditsAllowAI = $state(true);
let isFreePlan = $state(false);
let primaryProcessingLanguage = $state("en");
let enabledProcessingLanguages = $state<string[]>(["en"]);
const canUseAI = $derived(
creditsAllowAI &&
planCapabilities.can("capability.ai_processing") &&
@@ -453,6 +456,10 @@
upgradeCta = upgradeCtaForRole(canAdmin);
creditsAllowAI = canUseAIFromCredits(me.credits);
isFreePlan = Boolean(me.credits?.is_free_plan);
primaryProcessingLanguage = parseContentLanguage(me.company?.language);
enabledProcessingLanguages = [primaryProcessingLanguage, ...
(me.company?.content_languages ?? []).map((lang) => parseContentLanguage(lang, primaryProcessingLanguage))
].filter((lang, index, all) => all.indexOf(lang) === index);
} catch {
/* keep defaults */
}
@@ -603,7 +610,7 @@
return selectedRawProductIds(products, selectedIds, kind);
}
async function startProcessing(types: ProcessingType[]) {
async function startProcessing(types: ProcessingType[], language: string) {
startingJob = true;
error = "";
success = "";
@@ -647,7 +654,8 @@
body: {
raw_product_ids: rawIds,
processing_type: processingType,
processing_types: types
processing_types: types,
language
}
});
const queued = job.total_products_queued ?? job.total_products ?? rawIds.length;
@@ -1368,7 +1376,9 @@
{canProcessAITitles}
{canProcessAIDescriptions}
onClear={() => (selectedIds = [])}
onProcess={(types) => void startProcessing(types)}
primaryLanguage={primaryProcessingLanguage}
contentLanguages={enabledProcessingLanguages}
onProcess={(types, language) => void startProcessing(types, language)}
onExport={openExportDialog}
onMarkAsProcessed={requestMarkAsProcessed}
onResetToUnprocessed={canAdmin ? requestResetToUnprocessed : undefined}