This commit is contained in:
greeneclipse committed 2026-10-15 21:22:43 +02:00
1 parent 04794aea54
commit cfd31f398c
61 files changed
+2062 -254

No files matched your search

@@ -169,7 +169,7 @@
{importing ? i18n.t("catalog.uploading") : i18n.t("categories.chooseCsv")}
<input
type="file"
accept=".csv,.tsv,text/csv,text/tab-separated-values"
accept=".csv,.tsv,.json,text/csv,text/tab-separated-values,application/json"
class="absolute inset-0 cursor-pointer opacity-0"
onchange={handleFile}
/>
@@ -0,0 +1,27 @@
<script lang="ts">
import { api, failureMessage } from "$lib/api";
import { notifySuccess } from "$lib/notify";
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("");
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}});
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}
}
</script>
<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" />
<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)" />
<textarea class="w-full rounded-md border bg-background p-2 font-mono text-xs" rows="2" bind:value={extra} placeholder='Additional headers JSON, e.g. {"X-Tenant":"my-store"}'></textarea>
{#if error}<p class="text-sm text-destructive">{error}</p>{/if}
<button class="rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50" disabled={busy}>{busy?"Importing...":"Import JSON"}</button>
</form>
@@ -61,7 +61,11 @@
const filtered = $derived.by(() => {
const q = filterText.trim().toLowerCase();
return schemaFields.filter((field) => {
return [...schemaFields].sort((a,b) => {
const ar=standardFields.find((f)=>f.value===mappings[a.path])?.isRequired || standardFields.find((f)=>f.value===suggestionBySource.get(a.path)?.target)?.isRequired;
const br=standardFields.find((f)=>f.value===mappings[b.path])?.isRequired || standardFields.find((f)=>f.value===suggestionBySource.get(b.path)?.target)?.isRequired;
return Number(Boolean(br))-Number(Boolean(ar));
}).filter((field) => {
const samples = field.sample_values ?? [];
const matchesText =
!q ||
@@ -23,7 +23,14 @@ export function leafKey(path: string): string {
* Matchers pick the first alias that exists in the enabled target set.
*/
const SOURCE_ALIASES: Record<string, string[]> = {
gtin: ["gtin"],
gtin: ["gtin"],
productno: ["sku"], productno2: ["mpn"],
product: ["title"], descriptionbasic: ["description"],
pricevat: ["price"], priceeshopvat: ["price"], pricevoc: ["purchase_price"],
imgurl: ["image_url","main_image"],
params: ["specifications","specs"],
categoryid: ["category_id"],
ean: ["gtin"],
upc: ["gtin"],
barcode: ["gtin"],
@@ -210,7 +217,9 @@ export function suggestMappings(
schemaFields.forEach((field, order) => {
const apiHint = (field.suggested_target || "").trim();
const keys = [
const isSpecDescription = leafKey(field.path) === "description" && (field.sample_values ?? []).some((v) => (v.match(/\|/g) ?? []).length > 2 && v.includes(":"));
const keys = [
...(isSpecDescription ? ["specifications"] : []),
normalizeKey(field.field_name || ""),
leafKey(field.path),
normalizeKey(field.path)
@@ -218,7 +227,13 @@ export function suggestMappings(
let hit: MappingSuggestion | null = null;
if (apiHint && enabled.has(apiHint) && !usedTargets.has(apiHint)) {
if (isSpecDescription) {
const specs = resolveAlias(["specifications", "specs"], enabled);
if (specs && !usedTargets.has(specs)) {
hit = { source: field.path, target: specs, confidence: "alias", score: 1.05 };
}
}
if (!hit && apiHint && enabled.has(apiHint) && !usedTargets.has(apiHint)) {
hit = { source: field.path, target: apiHint, confidence: "alias", score: 0.98 };
}
@@ -253,7 +268,11 @@ export function suggestMappings(
}
}
if (hit) scored.push({ ...hit, order });
if (hit) {
if ((field.path.toLowerCase() === "params" || field.path.toLowerCase() === "attributes") && ["specifications","specs"].includes(hit.target)) hit.score = 1.15;
if (field.path.toLowerCase() === "description" && ["specifications","specs"].includes(hit.target)) hit.score = 0.92;
scored.push({ ...hit, order });
}
});
scored.sort((a, b) => b.score - a.score || a.order - b.order);
@@ -327,7 +346,7 @@ export type MappingPreflightInput = {
function isCsvFeedType(feedType?: string | null): boolean {
const t = String(feedType ?? "").toLowerCase();
return t === "csv" || t === "excel";
return t === "csv" || t === "excel" || t === "json";
}
/** Active source→target pairs (excludes blank / none). */
@@ -57,30 +57,17 @@
let pendingCount = $state(0);
let selectedTypes = $state<ProcessingType[]>([]);
const selectedData = $derived(products.filter((p) => selectedProducts.some((id) => String(id) === String(p.id))));
const uncategorized = $derived(selectedData.filter((p) => !p.category));
const needingCategory = ["attributes", "title", "description"] as ProcessingType[];
const needsCategorization = $derived(
selectedTypes.some((t) => needingCategory.includes(t)) &&
uncategorized.length > 0 &&
!selectedTypes.includes("category")
);
const selectedAILocked = $derived(
selectedTypes.some((t) => PROCESSING_OPTIONS.find((o) => o.type === t)?.requiresAI && !aiAllowedForType(t))
);
const totalCredits = $derived.by(() => {
const selectedCredits = PROCESSING_OPTIONS.filter((o) => selectedTypes.includes(o.type)).reduce(
(sum, o) => sum + o.credits,
// 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,
0
);
const n = Math.max(selectedCount, selectedData.length);
const categorized = n - uncategorized.length;
if (selectedTypes.includes("category") || !needsCategorization) {
return selectedCredits * n;
}
return categorized * selectedCredits + uncategorized.length * (selectedCredits + 0.3);
});
) * selectedCount
);
function toggleType(type: ProcessingType) {
if (!aiAllowedForType(type) && PROCESSING_OPTIONS.find((o) => o.type === type)?.requiresAI) return;
@@ -98,10 +85,7 @@
function processSelected() {
if (selectedTypes.length === 0) return;
pendingTypes =
needsCategorization && !selectedTypes.includes("category")
? (["category", ...selectedTypes] as ProcessingType[])
: [...selectedTypes];
pendingTypes = [...selectedTypes];
pendingCredits = totalCredits;
pendingCount = selectedCount;
open = false;
@@ -255,21 +239,6 @@
</div>
<div class="my-1 h-px bg-border"></div>
<div class="space-y-2 p-2">
{#if needsCategorization && !selectedTypes.includes("category")}
<div class="mb-2 rounded border border-primary/20 bg-primary/5 p-2 text-xs">
<div class="font-medium text-foreground">
{i18n.t("products.actions.autoCategorizeTitle")}
</div>
<div class="text-muted-foreground">
{i18n.t("products.actions.autoCategorizeBody", {
count: uncategorized.length,
types: selectedTypes
.filter((t) => needingCategory.includes(t))
.join(", ")
})}
</div>
</div>
{/if}
{#if selectedAILocked}
<div class="mb-2 rounded border border-destructive/30 bg-destructive/5 p-2 text-xs text-muted-foreground">
{i18n.t("products.actions.aiLocked")}
@@ -0,0 +1,24 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
const typesFile = fileURLToPath(new URL('./types.ts', import.meta.url));
const processingFile = fileURLToPath(new URL('./ProductProcessingActions.svelte', import.meta.url));
const productsPage = fileURLToPath(new URL('../../../routes/products/+page.svelte', import.meta.url));
test('What to process lists title, description and SEO metadata only', () => {
const types = readFileSync(typesFile, 'utf8');
const options = types.split('export const PROCESSING_OPTIONS:', 2)[1]?.split('];', 1)[0] ?? '';
assert.match(options, /type: "title"/);
assert.match(options, /type: "description"/);
assert.match(options, /type: "seo_meta"/);
assert.doesNotMatch(options, /type: "category"|type: "attributes"/);
});
test('SEO Meta selected alone uses a dedicated processing mode', () => {
const code = readFileSync(productsPage, 'utf8');
assert.match(code, /selected\.has\("seo_meta"\)\s*\?\s*"seo_meta"/);
const processing = readFileSync(processingFile, 'utf8');
assert.doesNotMatch(processing, /pendingTypes =\s*needsCategorization/);
});
@@ -43,13 +43,13 @@ export {
tabToApiParams
} from "../../products-search";
export type ProcessingType = "title" | "description" | "category" | "attributes";
export type ProcessingType = "title" | "description" | "seo_meta";
/** Options that require AI credits / paid plan (titles & descriptions). */
export const AI_PROCESSING_TYPES: ProcessingType[] = ["title", "description"];
export const AI_PROCESSING_TYPES: ProcessingType[] = ["title", "description", "seo_meta"];
/** Options that work on Free without AI (normalize / specs / fill). */
export const FREE_PROCESSING_TYPES: ProcessingType[] = ["category", "attributes"];
export const FREE_PROCESSING_TYPES: ProcessingType[] = [];
export type CategoryOption = {
uniqueId: string;
@@ -140,10 +140,9 @@ export const PROCESSING_OPTIONS: {
credits: number;
requiresAI?: boolean;
}[] = [
{ type: "category", labelKey: "products.option.categories", credits: 0, requiresAI: false },
{ type: "attributes", labelKey: "products.option.attributes", credits: 0, requiresAI: false },
{ type: "title", labelKey: "products.option.titlesAi", credits: 0.1, requiresAI: true },
{ type: "description", labelKey: "products.option.descriptionsAi", credits: 0.25, requiresAI: true }
{ type: "description", labelKey: "products.option.descriptionsAi", credits: 0.25, requiresAI: true },
{ type: "seo_meta", labelKey: "products.option.seoMetaAi", credits: 0.1, requiresAI: true }
];
/** True when product is awaiting Accept / edit / reject after enrichment. */
+4 -4
View File
@@ -12,10 +12,10 @@ import { validateDocsGuideTree } from "./resolve";
*/
const AUTH_NOTE =
"Company API key (prefix dk_…). Prefer Authorization: Bearer; X-API-Key also works. Create keys in Settings → API keys. On /docs when logged in, use Use my API key for RapiDoc Try-it. Do not use dashboard session cookies on /api/v1.";
"Company API key (prefix dk_…). Prefer Authorization: Bearer; X-API-Key also works. Create keys in Settings → API keys if you have the API Keys management permission. On /docs when logged in, use Use my API key for RapiDoc Try-it. Do not use dashboard session cookies on /api/v1.";
const TRY_IT_TIP =
"In RapiDoc: open Authorize (/docs#auth), paste Bearer dk_… (or X-API-Key), then expand an operation and use TRY. Prefer the server that matches your environment.";
"In RapiDoc: open Authorize (/docs#auth), paste Bearer dk_… (or X-API-Key), then expand an operation and use TRY. Use the published production API server.";
export const DOCS_GUIDE_TREE: DocsGuideTree = {
version: 2,
@@ -65,8 +65,8 @@ export const DOCS_GUIDE_TREE: DocsGuideTree = {
choices: [
{
id: "pipeline",
label: "Feeds → process → export",
description: "Ingest, enrich, or outbound feeds",
label: "Import → enrich → export",
description: "Connect a supplier, generate content, and download results",
nextId: "q.pipeline"
},
{
+10 -6
View File
@@ -6,6 +6,7 @@ export type ExportField = { key: string; source: string };
export type ExportPresetId =
| "custom_xml"
| "custom_csv"
| "custom_json"
| "google_shopping_csv"
| "google_shopping_xml"
| "meta_csv";
@@ -17,7 +18,7 @@ export type ExportPreset = {
shortLabel: string;
description: string;
hint: string;
format: "csv" | "xml";
format: "csv" | "xml" | "json";
root?: string;
item?: string;
fields: ExportField[];
@@ -110,6 +111,9 @@ export const EXPORT_PRESETS: ExportPreset[] = [
item: "product",
fields: DEFAULT_CUSTOM_FIELDS
},
{
id:"custom_json",channel:"custom",label:"Custom JSON",shortLabel:"JSON",description:"Nested JSON product catalog",hint:"Publishes a JSON URL with a products array.",format:"json",root:"products",item:"product",fields:DEFAULT_CUSTOM_FIELDS
},
{
id: "custom_xml",
channel: "custom",
@@ -129,25 +133,25 @@ export function presetById(id: ExportPresetId | string | null | undefined): Expo
}
export function defaultNameForPreset(preset: ExportPreset): string {
return i18n.t(`exports.preset.${preset.id}.defaultName`);
return preset.id === "custom_json" ? "JSON product feed" : i18n.t(`exports.preset.${preset.id}.defaultName`);
}
export function presetLabel(preset: ExportPreset | ExportPresetId): string {
const id = typeof preset === "string" ? preset : preset.id;
return i18n.t(`exports.preset.${id}.label`);
return id === "custom_json" ? "Custom JSON" : i18n.t(`exports.preset.${id}.label`);
}
export function presetShortLabel(preset: ExportPreset | ExportPresetId): string {
const id = typeof preset === "string" ? preset : preset.id;
return i18n.t(`exports.preset.${id}.shortLabel`);
return id === "custom_json" ? "JSON" : i18n.t(`exports.preset.${id}.shortLabel`);
}
export function presetDescription(preset: ExportPreset | ExportPresetId): string {
const id = typeof preset === "string" ? preset : preset.id;
return i18n.t(`exports.preset.${id}.description`);
return id === "custom_json" ? "Export processed products as JSON." : i18n.t(`exports.preset.${id}.description`);
}
export function presetHint(preset: ExportPreset | ExportPresetId): string {
const id = typeof preset === "string" ? preset : preset.id;
return i18n.t(`exports.preset.${id}.hint`);
return id === "custom_json" ? "Share the JSON feed URL with a partner." : i18n.t(`exports.preset.${id}.hint`);
}
+1
View File
@@ -2766,6 +2766,7 @@ export const de: MessageDict = {
"products.option.attributes": "Attribute / Spezifikationen",
"products.option.titlesAi": "Titel (KI)",
"products.option.descriptionsAi": "Beschreibungen (KI)",
"products.option.seoMetaAi": "SEO-Metatitel und -beschreibung (KI)",
"products.enrichment.piece.name": "Bezeichnung",
"products.enrichment.piece.description": "Beschreibung",
"products.enrichment.piece.attributes": "Attribute",
+2 -1
View File
@@ -2571,7 +2571,7 @@ export const en: MessageDict = {
"confirm.defaultTitle": "Confirm Deletion",
"confirm.defaultDescription": "Are you sure?",
"confirm.defaultConfirm": "Confirm",
"confirm.deleteFeed": "Delete feed “{name}”? This cannot be undone.",
"confirm.deleteFeed": "Delete feed “{name}” and its unprocessed products? Previously processed content and products shared with other feeds are preserved. This cannot be undone.",
"confirm.deleteCampaign": "Delete campaign “{name}”? This cannot be undone.",
"confirm.deleteExportFeed":
"Are you sure you want to delete this export feed?",
@@ -3348,6 +3348,7 @@ export const en: MessageDict = {
"products.option.attributes": "Attributes / specs",
"products.option.titlesAi": "Titles (AI)",
"products.option.descriptionsAi": "Descriptions (AI)",
"products.option.seoMetaAi": "SEO meta title & description (AI)",
"products.enrichment.piece.name": "Name",
"products.enrichment.piece.description": "Description",
"products.enrichment.piece.attributes": "Attributes",
+1
View File
@@ -2766,6 +2766,7 @@ export const es: MessageDict = {
"products.option.attributes": "Atributos / especificaciones",
"products.option.titlesAi": "Títulos (IA)",
"products.option.descriptionsAi": "Descripciones (IA)",
"products.option.seoMetaAi": "Título y descripción SEO (IA)",
"products.enrichment.piece.name": "Nombre",
"products.enrichment.piece.description": "Descripción",
"products.enrichment.piece.attributes": "Atributos",
+1
View File
@@ -2766,6 +2766,7 @@ export const fr: MessageDict = {
"products.option.attributes": "Attributs / spécifications",
"products.option.titlesAi": "Titres (IA)",
"products.option.descriptionsAi": "Descriptions (IA)",
"products.option.seoMetaAi": "Titre et description méta SEO (IA)",
"products.enrichment.piece.name": "Nom",
"products.enrichment.piece.description": "Description",
"products.enrichment.piece.attributes": "Attributs",
+1
View File
@@ -2766,6 +2766,7 @@ export const it: MessageDict = {
"products.option.attributes": "Attributi / specifiche",
"products.option.titlesAi": "Titoli (IA)",
"products.option.descriptionsAi": "Descrizioni (IA)",
"products.option.seoMetaAi": "Titolo e descrizione meta SEO (IA)",
"products.enrichment.piece.name": "Nome",
"products.enrichment.piece.description": "Descrizione",
"products.enrichment.piece.attributes": "Attributi",
+1
View File
@@ -2766,6 +2766,7 @@ export const ja: MessageDict = {
"products.option.attributes": "属性 / 仕様",
"products.option.titlesAi": "タイトル(AI)",
"products.option.descriptionsAi": "説明(AI)",
"products.option.seoMetaAi": "SEOメタタイトル・説明文(AI)",
"products.enrichment.piece.name": "名前",
"products.enrichment.piece.description": "説明",
"products.enrichment.piece.attributes": "属性",
+1
View File
@@ -2766,6 +2766,7 @@ export const nl: MessageDict = {
"products.option.attributes": "Attributen / specificaties",
"products.option.titlesAi": "Titels (AI)",
"products.option.descriptionsAi": "Beschrijvingen (AI)",
"products.option.seoMetaAi": "SEO-metatitel en -beschrijving (AI)",
"products.enrichment.piece.name": "Naam",
"products.enrichment.piece.description": "Beschrijving",
"products.enrichment.piece.attributes": "Attributen",
+1
View File
@@ -2766,6 +2766,7 @@ export const pl: MessageDict = {
"products.option.attributes": "Atrybuty / specyfikacje",
"products.option.titlesAi": "Tytuły (AI)",
"products.option.descriptionsAi": "Opisy (AI)",
"products.option.seoMetaAi": "Tytuł i opis meta SEO (AI)",
"products.enrichment.piece.name": "Nazwa",
"products.enrichment.piece.description": "Opis",
"products.enrichment.piece.attributes": "Atrybuty",
+1
View File
@@ -2766,6 +2766,7 @@ export const pt: MessageDict = {
"products.option.attributes": "Atributos / especificações",
"products.option.titlesAi": "Títulos (IA)",
"products.option.descriptionsAi": "Descrições (IA)",
"products.option.seoMetaAi": "Título e descrição meta SEO (IA)",
"products.enrichment.piece.name": "Nome",
"products.enrichment.piece.description": "Descrição",
"products.enrichment.piece.attributes": "Atributos",
+1
View File
@@ -2,6 +2,7 @@ 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 = {
"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",
"admin.users.cloneCatalogTitle": "Copy company catalog",
+4 -11
View File
@@ -7,17 +7,13 @@ import { PUBLIC_API_URL } from "$env/static/public";
const API_BASE = (PUBLIC_API_URL ?? "").replace(/\/$/, "");
/** Public production API base from OpenAPI servers[0] (Descrybe-hosted; not customer self-host). */
export const PUBLIC_DOCS_API_SERVER = "https://descrybe.io/api/v1";
export const PUBLIC_DOCS_API_SERVER = "https://api.descrybe.io/api/v1";
/** Public OpenAPI document URL for links and fetches. */
export const OPENAPI_SPEC_URL = `${API_BASE}/api/v1/openapi.yaml`;
/**
* Absolute base for RapiDoc Try-it.
* Dev/local: PUBLIC_API_URL when set (npm run dev forces http://localhost:28471),
* else current origin so Vite proxies /api → :28471.
* Production same-origin deploy resolves to https://descrybe.io/api/v1.
* OpenAPI servers[0] stays PUBLIC_DOCS_API_SERVER for the public YAML narrative.
/** The public reference defaults to the published production API.
* A configured API origin is used only for explicitly configured deployments.
*/
export function docsTryItServerURL(
origin = typeof window !== "undefined" ? window.location.origin : ""
@@ -25,9 +21,6 @@ export function docsTryItServerURL(
if (API_BASE) {
return `${API_BASE}/api/v1`;
}
if (origin) {
return `${origin}/api/v1`;
}
return PUBLIC_DOCS_API_SERVER;
}
@@ -38,7 +31,7 @@ export type RapiDocTryItHost = {
};
/**
* Point RapiDoc Try-it at the local/dev API.
* Point RapiDoc Try-it at the published API endpoint.
* RapiDoc only selects `server-url` when it equals `default-api-server`;
* otherwise Try-it uses OpenAPI servers[0] (production) even if server-url is set.
*/