System > KI-Modellbilder: API-Key, Modell-Endpunkt, Prompt mit Platzhaltern, Referenzbild und Zusatzparameter. Im Modell-Panel 'Bild erzeugen' (auch bei vorhandenem Bild), Ergebnis anklicken = wird direkt Modellbild. Verbindungstest um Higgsfield erweitert. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ex4YsMRQ4GF2dkGWuX6Yio
385 lines
18 KiB
JavaScript
385 lines
18 KiB
JavaScript
import { useEffect, useMemo, useState } from 'react';
|
||
import { useSearchParams } from 'react-router-dom';
|
||
import { api } from '../../api/client.js';
|
||
import ImageUploadField from '../../components/ImageUploadField.jsx';
|
||
import TextStyleWidget from '../../components/TextStyleWidget.jsx';
|
||
import SortableList, { saveReorder } from '../../components/admin/SortableList.jsx';
|
||
import VehicleCatalogDialog from '../../components/admin/VehicleCatalogDialog.jsx';
|
||
import AiImageGenerator from '../../components/admin/AiImageGenerator.jsx';
|
||
import { useAuth } from '../../context/AuthContext.jsx';
|
||
import { useToast, useUnsavedChanges } from '../../context/AdminUiContext.jsx';
|
||
import { Button, Card, EmptyState, Field, Icon, IconButton, Input, PageHeader, Select, SlideOver } from '../../components/ui/index.jsx';
|
||
|
||
// Aufbau wie bei den Paketen: links die Marken, rechts die Modelle der gewaehlten Marke.
|
||
// Sortiert wird immer innerhalb einer Marke (so erscheinen sie auch auf der Website); "Alle
|
||
// Marken" ist zum Suchen da. Bearbeiten im Seitenpanel.
|
||
|
||
const emptyForm = { name: '', brand_id: '', image_path: '', sort_order: 0 };
|
||
|
||
const normalize = (s) =>
|
||
String(s || '')
|
||
.toLowerCase()
|
||
.replace(/ä/g, 'ae')
|
||
.replace(/ö/g, 'oe')
|
||
.replace(/ü/g, 'ue')
|
||
.replace(/ß/g, 'ss');
|
||
|
||
export default function Models() {
|
||
const toast = useToast();
|
||
const { hasPermission } = useAuth();
|
||
const canPackages = hasPermission('packages.manage');
|
||
const [searchParams, setSearchParams] = useSearchParams();
|
||
const [models, setModels] = useState(null);
|
||
const [brands, setBrands] = useState([]);
|
||
const [packageCounts, setPackageCounts] = useState(null); // { [modelId]: { total, visible } }
|
||
const [form, setForm] = useState(emptyForm);
|
||
const [initialForm, setInitialForm] = useState(emptyForm);
|
||
// null = Panel zu, 'new' = neues Modell, sonst die id des bearbeiteten Modells.
|
||
const [editing, setEditing] = useState(null);
|
||
const [error, setError] = useState('');
|
||
const [saving, setSaving] = useState(false);
|
||
const [search, setSearch] = useState('');
|
||
const [catalogOpen, setCatalogOpen] = useState(false);
|
||
|
||
const dirty = JSON.stringify(form) !== JSON.stringify(initialForm);
|
||
useUnsavedChanges(editing !== null && dirty, 'models');
|
||
|
||
const load = () => {
|
||
api.get('/models').then(setModels).catch(() => setModels([]));
|
||
api.get('/brands').then(setBrands).catch(() => {});
|
||
// Nur fuer die Anzeige "3 Pakete" / "keine Pakete" je Modell.
|
||
if (canPackages) {
|
||
api
|
||
.get('/packages')
|
||
.then((rows) =>
|
||
setPackageCounts(
|
||
rows.reduce((acc, p) => {
|
||
const c = acc[p.car_model_id] || { total: 0, visible: 0 };
|
||
return { ...acc, [p.car_model_id]: { total: c.total + 1, visible: c.visible + (p.is_hidden ? 0 : 1) } };
|
||
}, {}),
|
||
),
|
||
)
|
||
.catch(() => {});
|
||
}
|
||
};
|
||
|
||
useEffect(load, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||
|
||
// Gewaehlte Marke steht in der Adresse (?marke=…), "alle" = alle Marken. Ohne Angabe die
|
||
// erste Marke - eine Liste mit allen (evtl. ueber 1.000) Modellen hilft im Alltag nicht.
|
||
const brandParam = searchParams.get('marke');
|
||
const brandSel = brandParam === 'alle' ? 'all' : Number(brandParam) || Number(brands[0]?.id) || null;
|
||
const activeBrand = brands.find((b) => Number(b.id) === brandSel) || null;
|
||
const canSort = brandSel !== 'all' && !search.trim();
|
||
|
||
const selectBrand = (id) => {
|
||
setSearch('');
|
||
setSearchParams(id === 'all' ? { marke: 'alle' } : { marke: String(id) });
|
||
};
|
||
|
||
const brandStats = useMemo(() => {
|
||
const stats = {};
|
||
(models || []).forEach((m) => {
|
||
const s = (stats[m.brand_id] ||= { count: 0, empty: 0 });
|
||
s.count += 1;
|
||
if (packageCounts && !packageCounts[m.id]?.visible) s.empty += 1;
|
||
});
|
||
return stats;
|
||
}, [models, packageCounts]);
|
||
|
||
const visible = useMemo(() => {
|
||
const list = brandSel === 'all' ? models || [] : (models || []).filter((m) => Number(m.brand_id) === brandSel);
|
||
const tokens = normalize(search).split(/\s+/).filter(Boolean);
|
||
if (!tokens.length) return list;
|
||
return list.filter((m) => tokens.every((t) => normalize(`${m.brand_name} ${m.name}`).includes(t)));
|
||
}, [models, brandSel, search]);
|
||
|
||
const openPanel = (model) => {
|
||
const next = model
|
||
? { name: model.name, brand_id: model.brand_id, image_path: model.image_path || '', sort_order: model.sort_order }
|
||
: { ...emptyForm, brand_id: activeBrand?.id ?? '' };
|
||
setEditing(model ? model.id : 'new');
|
||
setForm(next);
|
||
setInitialForm(next);
|
||
setError('');
|
||
};
|
||
|
||
const closePanel = () => {
|
||
if (dirty && !window.confirm('Ungespeicherte Änderungen verwerfen?')) return;
|
||
setEditing(null);
|
||
setForm(emptyForm);
|
||
setInitialForm(emptyForm);
|
||
};
|
||
|
||
const handleSubmit = async (e) => {
|
||
e.preventDefault();
|
||
setError('');
|
||
setSaving(true);
|
||
const payload = { ...form, brand_id: Number(form.brand_id) };
|
||
try {
|
||
if (editing !== 'new') {
|
||
await api.put(`/models/${editing}`, payload);
|
||
} else {
|
||
const sort = (models || [])
|
||
.filter((m) => Number(m.brand_id) === payload.brand_id)
|
||
.reduce((max, m) => Math.max(max, Number(m.sort_order) || 0), 0) + 10;
|
||
await api.post('/models', { ...payload, sort_order: sort });
|
||
}
|
||
toast.success(editing !== 'new' ? 'Modell gespeichert.' : 'Modell angelegt.');
|
||
setInitialForm(form);
|
||
setEditing(null);
|
||
load();
|
||
} catch (err) {
|
||
setError(err.message);
|
||
} finally {
|
||
setSaving(false);
|
||
}
|
||
};
|
||
|
||
// Das KI-Bild speichert der Server direkt am Modell - Formular und Liste nur nachziehen,
|
||
// sonst wuerde "Speichern" das alte Bild zuruecksetzen.
|
||
const handleAiImage = (path) => {
|
||
setForm((f) => ({ ...f, image_path: path }));
|
||
setInitialForm((f) => ({ ...f, image_path: path }));
|
||
setModels((list) => list.map((m) => (m.id === editing ? { ...m, image_path: path } : m)));
|
||
toast.success('KI-Bild als Modellbild übernommen.');
|
||
};
|
||
|
||
const handleDelete = async (model) => {
|
||
const count = packageCounts?.[model.id]?.total || 0;
|
||
const detail = count > 0 ? ` und ${count} Paket${count === 1 ? '' : 'e'} mit allen Produkten` : '';
|
||
if (!window.confirm(`„${model.brand_name} ${model.name}“${detail} wirklich löschen?`)) return;
|
||
try {
|
||
await api.delete(`/models/${model.id}`);
|
||
if (editing === model.id) setEditing(null);
|
||
toast.success('Modell gelöscht.');
|
||
load();
|
||
} catch (err) {
|
||
toast.error(`Löschen fehlgeschlagen: ${err.message}`);
|
||
}
|
||
};
|
||
|
||
// Die Modelle einer Marke in neuer Reihenfolge an ihre bisherigen Plaetze in der
|
||
// Gesamtliste zuruecksetzen.
|
||
const mergeIntoModels = (all, reordered) => {
|
||
const queue = [...reordered];
|
||
return all.map((m) => (Number(m.brand_id) === brandSel ? queue.shift() : m));
|
||
};
|
||
|
||
const handleReorder = async (reordered) => {
|
||
const previous = models;
|
||
setModels(mergeIntoModels(models, reordered));
|
||
try {
|
||
const saved = await saveReorder('models', reordered);
|
||
setModels((current) => mergeIntoModels(current, saved));
|
||
toast.success('Reihenfolge gespeichert.');
|
||
} catch (err) {
|
||
setModels(previous);
|
||
toast.error(`Reihenfolge konnte nicht gespeichert werden: ${err.message}`);
|
||
}
|
||
};
|
||
|
||
const packageInfo = (model) => {
|
||
if (!packageCounts) return null;
|
||
const c = packageCounts[model.id];
|
||
if (!c?.visible) {
|
||
return <span className="font-medium text-amber-700 dark:text-amber-400">{c?.total ? 'Alle Pakete ausgeblendet' : 'Noch keine Pakete'}</span>;
|
||
}
|
||
return `${c.visible} Paket${c.visible === 1 ? '' : 'e'}${c.total > c.visible ? ` · ${c.total - c.visible} ausgeblendet` : ''}`;
|
||
};
|
||
|
||
const brandButton = (id, label, stats) => {
|
||
const active = brandSel === (id === 'all' ? 'all' : Number(id));
|
||
return (
|
||
<button
|
||
key={id}
|
||
type="button"
|
||
onClick={() => selectBrand(id === 'all' ? 'all' : Number(id))}
|
||
className={`flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm transition ${
|
||
active
|
||
? 'bg-brand-50 font-semibold text-brand-800 dark:bg-brand-500/10 dark:text-brand-300'
|
||
: 'text-neutral-700 hover:bg-neutral-100 dark:text-neutral-300 dark:hover:bg-neutral-800'
|
||
}`}
|
||
>
|
||
<span className="flex-1 truncate">{label}</span>
|
||
{stats?.empty > 0 && <span className="h-2 w-2 rounded-full bg-amber-400" title={`${stats.empty} Modell(e) ohne sichtbares Paket`} />}
|
||
<span className="text-xs font-normal text-neutral-400">{stats?.count ?? 0}</span>
|
||
</button>
|
||
);
|
||
};
|
||
|
||
return (
|
||
<div>
|
||
<PageHeader
|
||
title="Modelle"
|
||
description="Marke wählen, Modell anklicken zum Bearbeiten. Reihenfolge am Griff links ziehen – so erscheinen die Modelle auf der Website."
|
||
actions={
|
||
<>
|
||
<Button variant="secondary" icon="template" onClick={() => setCatalogOpen(true)}>Aus Vorlage laden</Button>
|
||
<Button icon="plus" onClick={() => openPanel(null)} disabled={!brands.length}>Neues Modell</Button>
|
||
</>
|
||
}
|
||
/>
|
||
|
||
{models !== null && brands.length === 0 ? (
|
||
<Card padded={false}>
|
||
<EmptyState
|
||
icon="tag"
|
||
title="Noch keine Marken"
|
||
description="Modelle gehören immer zu einer Marke. Lege zuerst Marken an oder übernimm Marken und Modelle aus der Vorlage."
|
||
actions={
|
||
<>
|
||
<Button variant="secondary" icon="template" onClick={() => setCatalogOpen(true)}>Aus Vorlage laden</Button>
|
||
<Button to="/admin/brands">Zu den Fahrzeugmarken</Button>
|
||
</>
|
||
}
|
||
/>
|
||
</Card>
|
||
) : (
|
||
<div className="grid gap-6 lg:grid-cols-[16rem_minmax(0,1fr)]">
|
||
{/* Marken: am Desktop als Liste, am Handy als Auswahlfeld. */}
|
||
<div className="lg:hidden">
|
||
<Select value={brandSel === 'all' ? 'all' : String(brandSel ?? '')} onChange={(e) => selectBrand(e.target.value === 'all' ? 'all' : Number(e.target.value))}>
|
||
{brands.map((b) => <option key={b.id} value={String(b.id)}>{b.name} ({brandStats[b.id]?.count ?? 0})</option>)}
|
||
<option value="all">Alle Marken ({models?.length ?? 0})</option>
|
||
</Select>
|
||
</div>
|
||
<Card padded={false} className="hidden max-h-[calc(100vh-7rem)] flex-col overflow-hidden lg:sticky lg:top-24 lg:flex lg:self-start">
|
||
<div className="flex-1 space-y-0.5 overflow-y-auto p-2">
|
||
{brands.map((b) => brandButton(b.id, b.name, brandStats[b.id]))}
|
||
</div>
|
||
<div className="border-t border-neutral-200 p-2 dark:border-neutral-800">
|
||
{brandButton('all', 'Alle Marken', { count: models?.length ?? 0 })}
|
||
</div>
|
||
</Card>
|
||
|
||
<div className="min-w-0">
|
||
<Card padded={false} className="overflow-hidden">
|
||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-neutral-200 p-3 dark:border-neutral-800">
|
||
<div className="relative w-full max-w-xs">
|
||
<Icon name="search" className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neutral-400" />
|
||
<Input
|
||
value={search}
|
||
onChange={(e) => setSearch(e.target.value)}
|
||
placeholder={brandSel === 'all' ? 'Alle Modelle durchsuchen …' : `In ${activeBrand?.name || 'Marke'} suchen …`}
|
||
className="h-9 pl-9"
|
||
/>
|
||
</div>
|
||
<span className="text-sm text-neutral-400">
|
||
{visible.length} Modell{visible.length === 1 ? '' : 'e'}
|
||
{brandSel === 'all' && ' · zum Sortieren eine Marke wählen'}
|
||
</span>
|
||
</div>
|
||
|
||
{models === null ? (
|
||
<ul className="divide-y divide-neutral-100 dark:divide-neutral-800">
|
||
{[0, 1, 2, 3].map((i) => (
|
||
<li key={i} className="flex items-center gap-4 px-4 py-3">
|
||
<span className="h-12 w-16 animate-pulse rounded-lg bg-neutral-100 dark:bg-neutral-800" />
|
||
<span className="h-4 w-40 animate-pulse rounded bg-neutral-100 dark:bg-neutral-800" />
|
||
</li>
|
||
))}
|
||
</ul>
|
||
) : visible.length === 0 ? (
|
||
search.trim() ? (
|
||
<p className="px-4 py-10 text-center text-sm text-neutral-500 dark:text-neutral-400">Kein Modell passt zu „{search}“.</p>
|
||
) : (
|
||
<EmptyState
|
||
icon="car"
|
||
title={`Noch keine Modelle${activeBrand ? ` für ${activeBrand.name}` : ''}`}
|
||
description="Einzeln anlegen oder die Generationen dieser Marke aus der Vorlage übernehmen."
|
||
actions={
|
||
<>
|
||
<Button variant="secondary" icon="template" onClick={() => setCatalogOpen(true)}>Aus Vorlage laden</Button>
|
||
<Button icon="plus" onClick={() => openPanel(null)}>Neues Modell</Button>
|
||
</>
|
||
}
|
||
/>
|
||
)
|
||
) : (
|
||
<SortableList items={visible} onReorder={handleReorder} disabled={!canSort} className="divide-y divide-neutral-100 dark:divide-neutral-800">
|
||
{(model, handle) => (
|
||
<div
|
||
className={`flex items-center gap-3 bg-white px-3 py-2.5 transition hover:bg-neutral-50 dark:bg-neutral-900 dark:hover:bg-neutral-800/50 sm:gap-4 sm:px-4 ${
|
||
editing === model.id ? 'bg-brand-50/60 dark:bg-brand-900/20' : ''
|
||
}`}
|
||
>
|
||
{canSort && <span className="w-6 shrink-0">{handle}</span>}
|
||
<button type="button" onClick={() => openPanel(model)} className="flex min-w-0 flex-1 items-center gap-4 text-left">
|
||
{model.image_path ? (
|
||
<img src={model.image_path} alt="" className="h-12 w-16 shrink-0 rounded-lg border border-neutral-200 object-cover dark:border-neutral-700" />
|
||
) : (
|
||
<span className="flex h-12 w-16 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-300 dark:bg-neutral-800 dark:text-neutral-600">
|
||
<Icon name="car" className="h-6 w-6" />
|
||
</span>
|
||
)}
|
||
<span className="min-w-0">
|
||
<span className="block truncate font-semibold text-neutral-900 dark:text-white">
|
||
{brandSel === 'all' && <span className="font-normal text-neutral-500 dark:text-neutral-400">{model.brand_name} </span>}
|
||
{model.name}
|
||
</span>
|
||
<span className="block text-xs text-neutral-500 dark:text-neutral-400">{packageInfo(model)}</span>
|
||
</span>
|
||
</button>
|
||
<div className="flex shrink-0 items-center gap-0.5">
|
||
{canPackages && (
|
||
<Button variant="secondary" size="sm" icon="box" to={`/admin/packages?model=${model.id}`} className="hidden md:inline-flex">
|
||
Pakete
|
||
</Button>
|
||
)}
|
||
{canPackages && <IconButton icon="box" label="Pakete bearbeiten" to={`/admin/packages?model=${model.id}`} className="md:hidden" />}
|
||
<IconButton icon="eye" label="Auf der Website ansehen" href={`/fahrzeuge/${model.brand_slug}/${model.slug}`} target="_blank" rel="noopener noreferrer" className="hidden sm:inline-flex" />
|
||
<IconButton icon="pencil" label="Bearbeiten" onClick={() => openPanel(model)} />
|
||
<IconButton icon="trash" label="Löschen" tone="danger" onClick={() => handleDelete(model)} />
|
||
</div>
|
||
</div>
|
||
)}
|
||
</SortableList>
|
||
)}
|
||
</Card>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
<SlideOver
|
||
as="form"
|
||
onSubmit={handleSubmit}
|
||
open={editing !== null}
|
||
onClose={closePanel}
|
||
size="lg"
|
||
title={editing === 'new' ? 'Neues Modell' : 'Modell bearbeiten'}
|
||
description={editing === 'new' ? 'Danach kannst du direkt Pakete dafür anlegen oder kopieren.' : undefined}
|
||
footer={
|
||
<>
|
||
{editing !== 'new' && editing !== null && canPackages && (
|
||
<Button variant="ghost" icon="box" to={`/admin/packages?model=${editing}`} className="mr-auto">Pakete bearbeiten</Button>
|
||
)}
|
||
<Button variant="secondary" onClick={closePanel}>Abbrechen</Button>
|
||
<Button type="submit" disabled={saving || (editing !== 'new' && !dirty)}>
|
||
{saving ? 'Speichere…' : editing === 'new' ? 'Anlegen' : 'Speichern'}
|
||
</Button>
|
||
</>
|
||
}
|
||
>
|
||
<Field label="Marke" required>
|
||
<Select required value={form.brand_id} onChange={(e) => setForm({ ...form, brand_id: e.target.value })}>
|
||
<option value="">Bitte wählen …</option>
|
||
{brands.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
|
||
</Select>
|
||
</Field>
|
||
<Field label="Modellname" required error={error} hint="Mit Generation, z. B. „Golf 7“ oder „A4 B9“.">
|
||
<Input required autoFocus value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||
</Field>
|
||
{editing !== 'new' && editing !== null && (
|
||
<TextStyleWidget fieldKey={`car_models.${editing}.name`} previewText={form.name || 'Beispieltext'} />
|
||
)}
|
||
<ImageUploadField value={form.image_path} onChange={(path) => setForm({ ...form, image_path: path })} label="Bild (optional)" />
|
||
{editing !== 'new' && editing !== null && (
|
||
<AiImageGenerator modelId={editing} hasImage={!!initialForm.image_path} onApplied={handleAiImage} />
|
||
)}
|
||
</SlideOver>
|
||
|
||
<VehicleCatalogDialog open={catalogOpen} onClose={() => setCatalogOpen(false)} onImported={load} />
|
||
</div>
|
||
);
|
||
}
|