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.
*/
+3 -1
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
import { i18n } from "$lib/i18n";
import { onMount } from "svelte";
import { goto } from "$app/navigation";
@@ -1076,6 +1077,7 @@
{#if canAdmin}
<TabsContent value="bulk" class="mt-4">
<RemoteCatalogImport kind="attributes" onComplete={load}/>
<form class="space-y-4" onsubmit={bulkImport}>
<div class="grid gap-2">
<Label for="bulk-file">{i18n.t("attributes.bulk.fileLabel")}</Label>
@@ -1093,7 +1095,7 @@
<Input
id="bulk-file"
type="file"
accept=".csv,.tsv,text/csv,text/tab-separated-values"
accept=".csv,.tsv,.json,text/csv,text/tab-separated-values,application/json"
onchange={(e) => {
const input = e.currentTarget as HTMLInputElement;
addFile = input.files?.[0] ?? null;
@@ -1,4 +1,5 @@
<script lang="ts">
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
import { i18n } from "$lib/i18n";
import { onMount } from "svelte";
import { goto } from "$app/navigation";
@@ -185,6 +186,7 @@
<Alert message={error} />
<Alert tone="success" message={success} />
{#if canAdmin}<RemoteCatalogImport kind="categories" onComplete={load}/>{/if}
{#if !loading && promptCount > 0}
<p class="text-sm text-muted-foreground">
@@ -197,7 +197,7 @@
function publicPath(feed: ExportRow): string {
const token = String(feed.public_token ?? "");
const ext = String(feed.format ?? "xml").toLowerCase() === "csv" ? "csv" : "xml";
const ext = ["csv","json"].includes(String(feed.format ?? "xml").toLowerCase()) ? String(feed.format).toLowerCase() : "xml";
return `/api/public/export-feeds/${token}.${ext}`;
}
@@ -234,11 +234,12 @@
function inferPresetId(format: string, template: ExportRow["template"]): ExportPresetId {
const channel = String(template?.channel ?? "").toLowerCase();
const fmt = format === "csv" ? "csv" : "xml";
const fmt = format === "json" ? "json" : format === "csv" ? "csv" : "xml";
if (channel === "google_shopping") {
return fmt === "csv" ? "google_shopping_csv" : "google_shopping_xml";
}
if (channel === "meta") return "meta_csv";
if (fmt === "json") return "custom_json";
return fmt === "csv" ? "custom_csv" : "custom_xml";
}
@@ -271,7 +272,7 @@
const full = await api<ExportRow>(`/api/export-feeds/${feed.id}`);
editingId = String(full.id);
formName = String(full.name ?? i18n.t("exports.fallbackName"));
formFormat = String(full.format ?? "xml").toLowerCase() === "csv" ? "csv" : "xml";
formFormat = ["csv","json"].includes(String(full.format ?? "xml").toLowerCase()) ? String(full.format).toLowerCase() : "xml";
formRoot = String(full.template?.root ?? "products");
formItem = String(full.template?.item ?? "product");
formSourceFeedId = full.source_feed_id ? String(full.source_feed_id) : "";
+51 -10
View File
@@ -155,7 +155,11 @@
let formName = $state("");
let formUrl = $state("");
let formType = $state("xml");
let formHeaders = $state("");
let formAuthType = $state("bearer");
let formAuthToken = $state("");
let formAuthHeader = $state("X-API-Key");
let formType = $state("xml");
let formInterval = $state("60");
let formSource = $state<"url" | "file">("url");
let formFile = $state<File | null>(null);
@@ -458,8 +462,19 @@
}
}
function openAdd(source: "url" | "file" = "url") {
function requestHeaders(): Record<string,string> {
const headers:Record<string,string>={};
if (formHeaders.trim()) {
const parsed=JSON.parse(formHeaders);
if (!parsed || Array.isArray(parsed) || typeof parsed!=="object") throw new Error("HTTP headers must be a JSON object");
for (const [k,v] of Object.entries(parsed)) {if(typeof v!=="string")throw new Error("Header values must be strings");headers[k]=v}
}
if (formAuthToken.trim()) headers[formAuthType==="bearer"?"Authorization":formAuthHeader.trim()||"X-API-Key"] = formAuthType==="bearer"?`Bearer ${formAuthToken.trim()}`:formAuthToken.trim();
return headers;
}
function openAdd(source: "url" | "file" = "url") {
formName = "";
formHeaders="";formAuthToken="";formAuthType="bearer";formAuthHeader="X-API-Key";
formUrl = "";
formType = source === "file" ? "csv" : "xml";
formInterval = "60";
@@ -512,7 +527,7 @@
function onCsvSelected(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0] ?? null;
if (file && !file.name.toLowerCase().endsWith(".csv")) {
if (file && !/\.(csv|json|xml)$/i.test(file.name)) {
formFile = null;
input.value = "";
error = i18n.t("flash.feed.csvRequired");
@@ -530,6 +545,7 @@
formName = String(feed.name ?? "");
formUrl = String(feed.url ?? "");
formType = String(feed.feed_type ?? "xml");
formAuthToken=""; formHeaders="";
formInterval = String(feed.sync_interval_minutes ?? 60);
showEdit = true;
clearFormFeedback();
@@ -550,12 +566,13 @@
}
const body = new FormData();
body.append("name", formName.trim());
body.append("feed_type", "csv");
body.append("feed_type", formFile?.name.toLowerCase().endsWith(".json") ? "json" : formFile?.name.toLowerCase().endsWith(".xml") ? "xml" : "csv");
body.append("sync_interval_minutes", String(parseSyncIntervalMinutes(formInterval)));
body.append("file", formFile);
created = await api<FeedRow>("/api/feeds", { method: "POST", body });
} else {
const url = formUrl.trim();
const inferredType = formType === "xml" && /(?:\.json(?:$|[?#])|[?&]format=json(?:&|$))/i.test(url) ? "json" : formType;
if (!url) {
error = i18n.t("flash.feed.urlRequired");
fieldErrors = { url: error };
@@ -567,8 +584,9 @@
body: {
name: formName.trim(),
url,
feed_type: formType,
sync_interval_minutes: parseSyncIntervalMinutes(formInterval)
feed_type: inferredType,
sync_interval_minutes: parseSyncIntervalMinutes(formInterval),
request_headers: requestHeaders()
}
});
}
@@ -602,14 +620,16 @@
saving = true;
clearFormFeedback();
try {
const nextType = isFileFeed(editing) ? "csv" : formType;
const body: Record<string, string | number> = {
const nextType = isFileFeed(editing) ? String(editing.feed_type ?? "csv") : formType;
const body: Record<string, unknown> = {
name: formName.trim(),
feed_type: nextType,
sync_interval_minutes: parseSyncIntervalMinutes(formInterval)
};
if (!isFileFeed(editing)) {
body.url = formUrl.trim();
// An empty form preserves existing encrypted credentials.
if (formAuthToken.trim() || formHeaders.trim()) body.request_headers = requestHeaders();
}
await api(`/api/feeds/${editing.id}`, {
method: "PATCH",
@@ -1254,9 +1274,20 @@
<Select id="add-feed-type" bind:value={formType}>
<option value="xml">XML</option>
<option value="csv">CSV</option>
<option value="json">JSON</option>
</Select>
</div>
<FeedFormatHelp format={formType === "csv" ? "csv" : "xml"} />
{#if formType === "json"}<p class="text-xs text-muted-foreground">JSON arrays and nested products/results/items are supported. Map a record path if needed.</p>{:else}
<FeedFormatHelp format={formType === "csv" ? "csv" : "xml"} />{/if}
<div class="space-y-2 rounded-md border p-3">
<p class="text-sm font-medium">Optional HTTP authentication</p>
<Select bind:value={formAuthType}><option value="bearer">Bearer token</option><option value="header">API key / custom header</option></Select>
{#if formAuthType === "header"}<Input placeholder="Header name (X-API-Key)" bind:value={formAuthHeader} />{/if}
<Input type="password" autocomplete="off" placeholder="Token / API key (optional)" bind:value={formAuthToken}/>
<Label for="feed-headers">Other headers (JSON object, optional)</Label>
<textarea id="feed-headers" class="w-full rounded-md border bg-background p-2 font-mono text-xs" rows="2" bind:value={formHeaders} placeholder='{"X-Store-ID":"store-1"}'></textarea>
<p class="text-xs text-muted-foreground">Credentials are encrypted. Existing keys are not shown when editing.</p>
</div>
</TabsContent>
<TabsContent value="file" class="mt-4 space-y-4">
<div class="space-y-1.5">
@@ -1265,7 +1296,7 @@
id="add-feed-file"
bind:this={formFileInput}
type="file"
accept=".csv,text/csv"
accept=".csv,.xml,.json,text/csv,application/xml,application/json"
class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1.5 file:text-sm file:font-medium"
onchange={onCsvSelected}
required={formSource === "file"}
@@ -1343,12 +1374,22 @@
aria-describedby={fieldDescribedBy(fieldErrors, "url", FEEDS_FORM_ERROR_ID)}
/>
</div>
<div class="space-y-2 rounded-md border p-3">
<p class="text-sm font-medium">Update HTTP credentials (optional)</p>
<p class="text-xs text-muted-foreground">Leave blank to keep existing encrypted credentials. Enter a new token or headers to replace them.</p>
<Select bind:value={formAuthType}><option value="bearer">Bearer token</option><option value="header">API key / custom header</option></Select>
{#if formAuthType === "header"}<Input placeholder="Header name" bind:value={formAuthHeader} />{/if}
<Input type="password" autocomplete="off" placeholder="New token / API key" bind:value={formAuthToken} />
<Label for="edit-feed-headers">Other headers (JSON object)</Label>
<textarea id="edit-feed-headers" class="w-full rounded-md border bg-background p-2 font-mono text-xs" rows="2" bind:value={formHeaders} placeholder='{"X-Store-ID":"store-1"}'></textarea>
</div>
{/if}
<div class="space-y-1.5">
<Label for="edit-feed-type">{i18n.t("feeds.field.type")}</Label>
<Select id="edit-feed-type" bind:value={formType} disabled={editing != null && isFileFeed(editing)}>
<option value="xml">XML</option>
<option value="csv">CSV</option>
<option value="json">JSON</option>
</Select>
{#if editing && isFileFeed(editing)}
<p class="text-xs text-muted-foreground">{i18n.t("feeds.csvTypeLocked")}</p>
@@ -199,7 +199,7 @@
itemPath = normalized.itemPath;
rows =
normalized.rows.length > 0
? normalized.rows
? requiredFirst(normalized.rows,enabledFields)
: [{ source: "", target: "none" }];
if (itemPath || isCsv) activeTab = "fields";
dirty = false;
@@ -219,7 +219,7 @@
const keys = enabledFields.map((f) => f.value);
const again = normalizeMappingRows(mapRes.mappings, keys);
itemPath = again.itemPath || itemPath;
if (again.rows.length > 0) rows = again.rows;
if (again.rows.length > 0) rows = requiredFirst(again.rows,enabledFields);
})
.catch(() => {});
}
@@ -260,7 +260,11 @@
})();
});
function markDirty() {
function requiredFirst(items: FieldMappingRow[], fields: TargetField[]): FieldMappingRow[] {
const required = new Set(fields.filter(f => f.isRequired).map(f => f.value));
return [...items].sort((a,b)=>Number(required.has(b.target))-Number(required.has(a.target)));
}
function markDirty() {
dirty = true;
success = "";
showPostMapCta = false;
@@ -454,7 +458,7 @@
}
function addRow() {
rows = [...rows, { source: "", target: "none" }];
rows = [{ source: "", target: "none" }, ...rows.filter(r => r.source.trim() || r.target !== "none")];
markDirty();
}
+15 -17
View File
@@ -39,6 +39,7 @@
import UpgradeBanner from "$lib/components/UpgradeBanner.svelte";
import { Button, Card, CardHeader } from "$lib/components/ui";
import ProductTabs from "$lib/components/products/ProductTabs.svelte";
import RemoteCatalogImport from "$lib/components/feeds/RemoteCatalogImport.svelte";
import ProductSearchFilters from "$lib/components/products/ProductSearchFilters.svelte";
import ProductTable from "$lib/components/products/ProductTable.svelte";
import ProductEmptyState from "$lib/components/products/ProductEmptyState.svelte";
@@ -629,23 +630,12 @@
});
return;
}
const wantsAI = types.some((t) => t === "title" || t === "description");
const wantsAttrs = types.includes("attributes") || types.includes("category");
let processingType = "full";
if (types.length === 1 && types[0] === "title") {
processingType = "title";
} else if (types.length === 1 && types[0] === "description") {
processingType = "description";
} else if (types.length === 1 && types[0] === "category") {
// Vector categorize runs inside fill_fields (attributes pipeline), not normalize_only.
processingType = "attributes";
} else if (types.length === 1 && types[0] === "attributes") {
processingType = "attributes";
} else if (wantsAI && !wantsAttrs) {
processingType = "enhance";
} else if (!wantsAI && wantsAttrs) {
processingType = "attributes";
}
const selected = new Set(types);
// The worker accepts a single execution mode; SEO-only preserves existing
// product copy, while selecting multiple outputs runs the AI enhancement pass.
const processingType = selected.size === 1
? selected.has("seo_meta") ? "seo_meta" : selected.has("title") ? "title" : "description"
: "enhance";
const job = await api<{
id: string;
@@ -1309,6 +1299,14 @@
/>
{/if}
{#if canAdmin}
<details class="mb-4 rounded-md border border-border bg-card p-3">
<summary class="cursor-pointer text-sm font-medium">Import products from a JSON URL</summary>
<div class="mt-3">
<RemoteCatalogImport kind="products" onComplete={async () => { await loadProducts(); }} />
</div>
</details>
{/if}
<Card
class={`min-w-0 overflow-x-auto border-border shadow-sm transition-all duration-300 ${fetching ? "bg-background/20 backdrop-blur-sm" : ""}`}
>