This commit is contained in:
greeneclipse committed 2026-10-16 13:48:51 +02:00
1 parent feebf7d3c1
commit 486502852e
41 files changed
+1311 -259

No files matched your search

@@ -0,0 +1,22 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
const plan = readFileSync(fileURLToPath(new URL('../routes/admin/billing/+page.svelte', import.meta.url)), 'utf8');
const actions = readFileSync(fileURLToPath(new URL('./components/products/ProductProcessingActions.svelte', import.meta.url)), 'utf8');
const features = plan.split('const creditFeatures = [', 2)[1]?.split('] as const', 1)[0] ?? '';
test('plan processing costs show only the three selectable product outputs', () => {
assert.match(features, /key: 'title_ai'|key: "title_ai"/);
assert.match(features, /key: 'description_ai'|key: "description_ai"/);
assert.match(features, /key: 'seo_meta_ai'|key: "seo_meta_ai"/);
assert.doesNotMatch(features, /openai_token_k|campaign_copy|product_processing/);
});
test('decimal values are allowed and loaded from company-effective pricing', () => {
assert.match(plan, /step="0\.0001"/);
assert.match(plan, /\\d\{1,4\}/);
assert.match(actions, /\/api\/billing\/processing-costs/);
assert.match(actions, /effectiveCosts\[option\.type\]/);
});
@@ -1,15 +1,16 @@
<script lang="ts">
import { api, failureMessage } from "$lib/api";
import { notifySuccess } from "$lib/notify";
import { CONTENT_LANGUAGES } from "$lib/content-languages";
let {kind,onComplete}:{kind:"categories"|"attributes"|"products";onComplete:()=>void|Promise<void>}=$props();
let url=$state(""); let token=$state(""); let authMode=$state("bearer"); let headerName=$state("X-API-Key");let extra=$state("");let busy=$state(false);let error=$state("");
let language=$state(""); let url=$state(""); let token=$state(""); let authMode=$state("bearer"); let headerName=$state("X-API-Key");let extra=$state("");let busy=$state(false);let error=$state("");
async function submit(event:SubmitEvent){
event.preventDefault();busy=true;error="";
try{
const headers:Record<string,string>=extra.trim()?JSON.parse(extra):{};
if (!headers||Array.isArray(headers)||typeof headers!=="object"||Object.values(headers).some(v=>typeof v!=="string"))throw new Error("Headers must be a JSON object of strings");
if(token.trim())headers[authMode==="bearer"?"Authorization":headerName.trim()||"X-API-Key"]=authMode==="bearer"?`Bearer ${token.trim()}`:token.trim();
const result=await api<{import?:{created?:number;updated?:number;skipped?:number}}>(`/api/${kind}/import`,{method:"POST",body:{url:url.trim(),format:"json",request_headers:headers}});
const result=await api<{import?:{created?:number;updated?:number;skipped?:number}}>(`/api/${kind}/import`,{method:"POST",body:{url:url.trim(),format:"json",language,request_headers:headers}});
notifySuccess(`Imported ${result.import?.created??0} new and ${result.import?.updated??0} updated ${kind}`);
await onComplete();
}catch(e){error=failureMessage(e,"JSON import failed")}finally{busy=false}
@@ -18,6 +19,11 @@
<form class="space-y-2 rounded-md border border-border p-3" onsubmit={submit}>
<p class="text-sm font-medium">Import {kind} from JSON URL</p>
<input class="w-full rounded-md border bg-background p-2 text-sm" type="url" required bind:value={url} placeholder="https://supplier.example/api/products?format=json" />
<label class="block text-xs font-medium" for="remote-import-language">Import language</label>
<select id="remote-import-language" class="w-full rounded-md border bg-background p-2 text-sm" bind:value={language}>
<option value="">Company primary language (default)</option>
{#each CONTENT_LANGUAGES as lang}<option value={lang.value}>{lang.label}</option>{/each}
</select>
<select class="w-full rounded-md border bg-background p-2 text-sm" bind:value={authMode}><option value="bearer">Bearer token (optional)</option><option value="header">Custom API key header</option></select>
{#if authMode==="header"}<input class="w-full rounded-md border bg-background p-2 text-sm" bind:value={headerName} placeholder="X-API-Key" />{/if}
<input class="w-full rounded-md border bg-background p-2 text-sm" type="password" autocomplete="off" bind:value={token} placeholder="API key / token (optional)" />
@@ -5,6 +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";
let {
@@ -56,15 +58,30 @@
let pendingCredits = $state(0);
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 pricingReady = $state(false);
let pricingError = $state(false);
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; });
});
const selectedAILocked = $derived(
selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
(processingMode === "product" && !processProductTypes.every(aiAllowedForType)) || selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
);
// Estimated cost only; actual AI usage is billed from provider tokens.
const totalCredits = $derived(
PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
(sum, option) => sum + option.credits,
// Estimated cost from the effective company/plan rates (per selected output).
const totalCredits = $derived(processingMode === "product"
? (effectiveCosts.product ?? 0.45) * selectedCount
: PROCESSING_OPTIONS.filter((option) => selectedTypes.includes(option.type)).reduce(
(sum, option) => sum + (effectiveCosts[option.type] ?? option.credits),
0
) * selectedCount
);
@@ -84,8 +101,9 @@
}
function processSelected() {
if (selectedTypes.length === 0) return;
pendingTypes = [...selectedTypes];
if (!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0)) return;
if (selectedAILocked) return;
pendingTypes = processingMode === "product" ? [...processProductTypes] : [...selectedTypes];
pendingCredits = totalCredits;
pendingCount = selectedCount;
open = false;
@@ -147,12 +165,15 @@
{/if}
{#if activeTab !== "processed"}
{#if pricingError}
<p class="text-xs text-destructive" role="alert">Unable to load processing prices. Refresh before starting a job.</p>
{/if}
<div class="relative">
<Button
variant="default"
size="sm"
mutation
disabled={selectedCount === 0 || isProcessing}
disabled={selectedCount === 0 || isProcessing || !pricingReady}
loading={isProcessing}
data-assistant-target="start-processing"
data-tour="start-processing"
@@ -187,6 +208,15 @@
</div>
</div>
{/if}
{#if processingMode === "product"}
<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>
</div>
<span class="shrink-0 font-mono text-xs">{(effectiveCosts.product ?? 0.45).toFixed(4)} credits</span>
</div>
{:else}
<button
type="button"
class="mb-3 flex items-center space-x-2 border-b border-border/50 pb-3"
@@ -230,12 +260,13 @@
</label>
<span class="font-mono text-xs text-muted-foreground"
>{option.requiresAI
? i18n.t("products.actions.credits", { credits: option.credits.toFixed(2) })
? 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">
@@ -252,7 +283,7 @@
size="sm"
class="w-full"
mutation
disabled={selectedTypes.length === 0 || isProcessing || selectedAILocked}
disabled={!pricingReady || (processingMode === "outputs" && selectedTypes.length === 0) || isProcessing || selectedAILocked}
loading={isProcessing}
onclick={processSelected}
>
@@ -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 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 === "product"\}[\s\S]*?\{:else\}[\s\S]*?\{#each PROCESSING_OPTIONS as option\}/);
assert.match(actions, /pendingTypes = processingMode === "product" \? \[\.\.\.processProductTypes\]/);
assert.match(actions, /effectiveCosts\.product/);
assert.match(actions, /!pricingReady/);
});
test('plan popup opts in explicitly to the one-price-per-product mode', () => {
assert.match(plan, /<option value="outputs">/);
assert.match(plan, /<option value="product">/);
assert.match(plan, /feature: "product_ai"/);
assert.match(plan, /step="0\.0001" bind:value=\{perProductPrice\}/);
assert.match(plan, /planProcessingMode === "product" \? String\(perProductPrice/);
});