- Pakete > Nach Modell: "Auswählen" markiert mehrere Stufen (oder alle) und löscht sie auf einmal
- Pakete > Alle Pakete: Haken je Zeile, "Alle" bezieht sich auf das Suchergebnis
- Von anderem Modell kopieren: hat das Ziel schon Pakete, wahlweise alle ersetzen
(Vorgabe) oder nur fehlende ergänzen
- API: POST /packages/delete {ids}, copy-packages mit replace_existing
- ui: Checkbox-Baustein, Icon check
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017yqbrkqFsLrgVr6QMrvEZz
422 lines
16 KiB
PHP
422 lines
16 KiB
PHP
<?php
|
|
|
|
namespace App\Controllers;
|
|
|
|
use App\Config\Database;
|
|
use App\Support\Http;
|
|
use App\Support\Translations;
|
|
use App\Support\Slug;
|
|
use App\Support\TextStyleCleanup;
|
|
|
|
class PackageController
|
|
{
|
|
// Markierungen, die auf der Paket-Kachel oben als Badge erscheinen koennen. "custom" zeigt
|
|
// den frei eingegebenen badge_text, alle anderen werden im Frontend uebersetzt.
|
|
public const BADGES = ['recommended', 'popular', 'tip', 'coming_soon', 'custom'];
|
|
|
|
private static function normalizeMarkup(array $body): array
|
|
{
|
|
$type = $body['markup_type'] ?? 'none';
|
|
if (!in_array($type, ['none', 'fixed', 'percent'], true)) {
|
|
$type = 'none';
|
|
}
|
|
$value = $type === 'none' ? 0 : (float) ($body['markup_value'] ?? 0);
|
|
|
|
return [$type, $value];
|
|
}
|
|
|
|
/**
|
|
* @return array{0: ?string, 1: ?string} [badge, badge_text]
|
|
*/
|
|
private static function normalizeBadge(array $body): array
|
|
{
|
|
// Aeltere Clients kennen nur die Empfohlen-Checkbox.
|
|
if (!array_key_exists('badge', $body)) {
|
|
return [!empty($body['is_featured']) ? 'recommended' : null, null];
|
|
}
|
|
|
|
$badge = (string) ($body['badge'] ?? '');
|
|
if (!in_array($badge, self::BADGES, true)) {
|
|
return [null, null];
|
|
}
|
|
if ($badge !== 'custom') {
|
|
return [$badge, null];
|
|
}
|
|
|
|
$text = mb_substr(trim((string) ($body['badge_text'] ?? '')), 0, 40);
|
|
return $text === '' ? [null, null] : ['custom', $text];
|
|
}
|
|
|
|
private static function normalizeVideoUrl(array $body): ?string
|
|
{
|
|
$url = trim((string) ($body['video_url'] ?? ''));
|
|
if ($url === '') {
|
|
return null;
|
|
}
|
|
// "youtu.be/..." ohne Schema ist die haeufigste Eingabe aus der Zwischenablage.
|
|
if (!preg_match('#^https?://#i', $url)) {
|
|
$url = 'https://' . $url;
|
|
}
|
|
if (strlen($url) > 500 || !filter_var($url, FILTER_VALIDATE_URL)) {
|
|
Http::error('Video-Link ist keine gültige Adresse (z. B. https://youtu.be/...)', 422);
|
|
}
|
|
|
|
return $url;
|
|
}
|
|
|
|
/** Pakete aus der Zeit vor der Markierungs-Auswahl hatten nur is_featured ("Empfohlen"). */
|
|
public static function effectiveBadge(array $package): ?string
|
|
{
|
|
$badge = $package['badge'] ?? null;
|
|
if ($badge !== null && $badge !== '') {
|
|
return $badge;
|
|
}
|
|
return !empty($package['is_featured']) ? 'recommended' : null;
|
|
}
|
|
|
|
public static function index(): void
|
|
{
|
|
$stmt = Database::connection()->query(
|
|
'SELECT p.id, p.name, p.slug, p.description, p.markup_type, p.markup_value, p.icon_name, p.tagline,
|
|
p.price_text, p.is_featured, p.is_hidden, p.badge, p.badge_text, p.video_url, p.sort_order,
|
|
p.car_model_id, m.name AS model_name, b.name AS brand_name
|
|
FROM packages p
|
|
JOIN car_models m ON m.id = p.car_model_id
|
|
JOIN brands b ON b.id = m.brand_id
|
|
ORDER BY b.name, m.name, p.sort_order, p.name'
|
|
);
|
|
$packages = $stmt->fetchAll();
|
|
foreach ($packages as &$package) {
|
|
$package['badge'] = self::effectiveBadge($package);
|
|
$package['is_featured'] = $package['badge'] === 'recommended';
|
|
$package['is_hidden'] = (bool) $package['is_hidden'];
|
|
}
|
|
unset($package);
|
|
Http::send(Translations::attach('packages', $packages));
|
|
}
|
|
|
|
public static function store(): void
|
|
{
|
|
$body = Http::jsonBody();
|
|
$name = trim($body['name'] ?? '');
|
|
$modelId = (int) ($body['car_model_id'] ?? 0);
|
|
|
|
if ($name === '' || $modelId <= 0) {
|
|
Http::error('Name und Modell erforderlich', 422);
|
|
}
|
|
|
|
[$markupType, $markupValue] = self::normalizeMarkup($body);
|
|
[$badge, $badgeText] = self::normalizeBadge($body);
|
|
$videoUrl = self::normalizeVideoUrl($body);
|
|
|
|
$db = Database::connection();
|
|
$stmt = $db->prepare(
|
|
'INSERT INTO packages (car_model_id, name, slug, description, markup_type, markup_value, icon_name, tagline, price_text,
|
|
is_featured, badge, badge_text, video_url, sort_order)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
$stmt->execute([
|
|
$modelId,
|
|
$name,
|
|
Slug::make($name),
|
|
$body['description'] ?? null,
|
|
$markupType,
|
|
$markupValue,
|
|
trim($body['icon_name'] ?? '') ?: null,
|
|
trim($body['tagline'] ?? '') ?: null,
|
|
trim($body['price_text'] ?? '') ?: null,
|
|
// is_featured bleibt fuer Alt-Code/Exporte synchron zur Markierung "Empfohlen".
|
|
$badge === 'recommended' ? 1 : 0,
|
|
$badge,
|
|
$badgeText,
|
|
$videoUrl,
|
|
(int) ($body['sort_order'] ?? 0),
|
|
]);
|
|
|
|
$id = (int) $db->lastInsertId();
|
|
Translations::saveFromBody('packages', $id, $body);
|
|
|
|
Http::send(['id' => $id], 201);
|
|
}
|
|
|
|
public static function update(array $params): void
|
|
{
|
|
$id = (int) $params['id'];
|
|
$body = Http::jsonBody();
|
|
$name = trim($body['name'] ?? '');
|
|
$modelId = (int) ($body['car_model_id'] ?? 0);
|
|
|
|
if ($name === '' || $modelId <= 0) {
|
|
Http::error('Name und Modell erforderlich', 422);
|
|
}
|
|
|
|
[$markupType, $markupValue] = self::normalizeMarkup($body);
|
|
[$badge, $badgeText] = self::normalizeBadge($body);
|
|
$videoUrl = self::normalizeVideoUrl($body);
|
|
|
|
// is_hidden bewusst nicht hier - das schaltet setVisibility() sofort per Klick um,
|
|
// unabhaengig vom "Alle speichern" des Batch-Editors.
|
|
$stmt = Database::connection()->prepare(
|
|
'UPDATE packages SET car_model_id = ?, name = ?, slug = ?, description = ?, markup_type = ?, markup_value = ?, icon_name = ?,
|
|
tagline = ?, price_text = ?, is_featured = ?, badge = ?, badge_text = ?, video_url = ?, sort_order = ?
|
|
WHERE id = ?'
|
|
);
|
|
$stmt->execute([
|
|
$modelId,
|
|
$name,
|
|
Slug::make($name),
|
|
$body['description'] ?? null,
|
|
$markupType,
|
|
$markupValue,
|
|
trim($body['icon_name'] ?? '') ?: null,
|
|
trim($body['tagline'] ?? '') ?: null,
|
|
trim($body['price_text'] ?? '') ?: null,
|
|
$badge === 'recommended' ? 1 : 0,
|
|
$badge,
|
|
$badgeText,
|
|
$videoUrl,
|
|
(int) ($body['sort_order'] ?? 0),
|
|
$id,
|
|
]);
|
|
Translations::saveFromBody('packages', $id, $body);
|
|
|
|
Http::send(['ok' => true]);
|
|
}
|
|
|
|
/** Blendet ein Paket auf der oeffentlichen Modellseite aus bzw. wieder ein (ein Klick im Admin). */
|
|
public static function setVisibility(array $params): void
|
|
{
|
|
$id = (int) $params['id'];
|
|
$body = Http::jsonBody();
|
|
if (!array_key_exists('is_hidden', $body)) {
|
|
Http::error('is_hidden erforderlich', 422);
|
|
}
|
|
$hidden = !empty($body['is_hidden']);
|
|
|
|
$stmt = Database::connection()->prepare('UPDATE packages SET is_hidden = ? WHERE id = ?');
|
|
$stmt->execute([$hidden ? 1 : 0, $id]);
|
|
if ($stmt->rowCount() === 0) {
|
|
$exists = Database::connection()->prepare('SELECT 1 FROM packages WHERE id = ?');
|
|
$exists->execute([$id]);
|
|
if (!$exists->fetch()) {
|
|
Http::error('Paket nicht gefunden', 404);
|
|
}
|
|
}
|
|
|
|
Http::send(['ok' => true, 'is_hidden' => $hidden]);
|
|
}
|
|
|
|
/**
|
|
* Alle Produkte und Upgrades der Pakete eines Modells in einer Antwort - der Paket-Editor
|
|
* zeigt beides direkt im jeweiligen Paket an (statt je Paket einer eigenen Seite) und
|
|
* rechnet daraus live den Endpreis. Admin-Endpunkt, daher inkl. Einzelpreisen.
|
|
*/
|
|
public static function itemsForModel(array $params): void
|
|
{
|
|
$modelId = (int) $params['id'];
|
|
$db = Database::connection();
|
|
|
|
$products = $db->prepare(
|
|
'SELECT pp.id, pp.package_id, pp.source_url, pp.name_override, pp.scraped_name, pp.scraped_price,
|
|
pp.scraped_currency, pp.scraped_image_url, pp.price_updated_at, pp.scrape_status,
|
|
pp.scrape_error, pp.sort_order
|
|
FROM package_products pp JOIN packages p ON p.id = pp.package_id
|
|
WHERE p.car_model_id = ? ORDER BY pp.sort_order, pp.id'
|
|
);
|
|
$products->execute([$modelId]);
|
|
|
|
$upgrades = $db->prepare(
|
|
'SELECT u.id, u.package_id, u.name, u.description, u.price, u.sort_order
|
|
FROM package_upgrades u JOIN packages p ON p.id = u.package_id
|
|
WHERE p.car_model_id = ? ORDER BY u.sort_order, u.id'
|
|
);
|
|
$upgrades->execute([$modelId]);
|
|
|
|
Http::send([
|
|
'products' => $products->fetchAll(),
|
|
'upgrades' => Translations::attach('package_upgrades', $upgrades->fetchAll()),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Kopiert alle Pakete eines Quellmodells (inkl. der verknuepften
|
|
* package_products-Zeilen samt gecachter Scrape-Daten - KEIN Re-Scraping)
|
|
* auf das Zielmodell. Paketstufen, deren Slug im Ziel schon existiert,
|
|
* werden uebersprungen (abgesichert durch UNIQUE uniq_model_slug).
|
|
* package_upgrades nur auf Wunsch (include_upgrades) - frueher nie, dann musste man
|
|
* sie pro Modell und Paket neu abtippen.
|
|
* replace_existing loescht vorher alle Pakete des Zielmodells, damit es danach genau wie das
|
|
* Quellmodell aussieht (sonst musste man jedes vorhandene Paket einzeln loeschen).
|
|
*/
|
|
public static function copyFromModel(array $params): void
|
|
{
|
|
$targetId = (int) $params['id'];
|
|
$body = Http::jsonBody();
|
|
$sourceId = (int) ($body['source_model_id'] ?? 0);
|
|
$includeUpgrades = !empty($body['include_upgrades']);
|
|
$replaceExisting = !empty($body['replace_existing']);
|
|
|
|
if ($targetId <= 0 || $sourceId <= 0) {
|
|
Http::error('Quell- und Zielmodell erforderlich', 422);
|
|
}
|
|
if ($sourceId === $targetId) {
|
|
Http::error('Quell- und Zielmodell müssen unterschiedlich sein', 422);
|
|
}
|
|
|
|
$db = Database::connection();
|
|
|
|
$stmt = $db->prepare('SELECT id FROM car_models WHERE id IN (?, ?)');
|
|
$stmt->execute([$sourceId, $targetId]);
|
|
if (count($stmt->fetchAll()) !== 2) {
|
|
Http::error('Modell nicht gefunden', 404);
|
|
}
|
|
|
|
$db->beginTransaction();
|
|
try {
|
|
$removed = 0;
|
|
if ($replaceExisting) {
|
|
$stmt = $db->prepare('SELECT id FROM packages WHERE car_model_id = ?');
|
|
$stmt->execute([$targetId]);
|
|
$removed = self::deletePackages($db, array_map('intval', array_column($stmt->fetchAll(), 'id')));
|
|
}
|
|
[$copied, $skipped] = self::copyPackages($db, $sourceId, $targetId, $includeUpgrades);
|
|
$db->commit();
|
|
} catch (\Throwable $e) {
|
|
$db->rollBack();
|
|
throw $e;
|
|
}
|
|
|
|
Http::send(['copied' => $copied, 'skipped' => $skipped, 'removed' => $removed]);
|
|
}
|
|
|
|
/**
|
|
* Kopiert alle Pakete (samt Produkten, Uebersetzungen und optional Upgrades) von einem Modell
|
|
* auf ein anderes; Pakete mit gleichem Slug am Ziel werden uebersprungen. Ohne eigene
|
|
* Transaktion - auch von der Fahrzeug-Vorlage genutzt.
|
|
*
|
|
* @return array{0: array<int, array{name: string, products: int, upgrades: int}>, 1: string[]}
|
|
*/
|
|
public static function copyPackages(\PDO $db, int $sourceId, int $targetId, bool $includeUpgrades): array
|
|
{
|
|
$stmt = $db->prepare('SELECT slug FROM packages WHERE car_model_id = ?');
|
|
$stmt->execute([$targetId]);
|
|
$existingSlugs = array_column($stmt->fetchAll(), 'slug');
|
|
|
|
$stmt = $db->prepare('SELECT * FROM packages WHERE car_model_id = ? ORDER BY sort_order, name');
|
|
$stmt->execute([$sourceId]);
|
|
$sourcePackages = $stmt->fetchAll();
|
|
|
|
$copied = [];
|
|
$skipped = [];
|
|
|
|
$insertPackage = $db->prepare(
|
|
'INSERT INTO packages (car_model_id, name, slug, description, markup_type, markup_value, icon_name, tagline, price_text,
|
|
is_featured, is_hidden, badge, badge_text, video_url, sort_order)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
|
);
|
|
$copyProducts = $db->prepare(
|
|
'INSERT INTO package_products (package_id, source_url, name_override, scraped_name, scraped_price, scraped_currency,
|
|
scraped_image_url, price_updated_at, scrape_status, scrape_error, sort_order)
|
|
SELECT ?, source_url, name_override, scraped_name, scraped_price, scraped_currency,
|
|
scraped_image_url, price_updated_at, scrape_status, scrape_error, sort_order
|
|
FROM package_products WHERE package_id = ?'
|
|
);
|
|
$copyUpgrades = $db->prepare(
|
|
'INSERT INTO package_upgrades (package_id, name, description, price, sort_order)
|
|
SELECT ?, name, description, price, sort_order FROM package_upgrades WHERE package_id = ?'
|
|
);
|
|
|
|
foreach ($sourcePackages as $pkg) {
|
|
if (in_array($pkg['slug'], $existingSlugs, true)) {
|
|
$skipped[] = $pkg['name'];
|
|
continue;
|
|
}
|
|
$insertPackage->execute([
|
|
$targetId,
|
|
$pkg['name'],
|
|
$pkg['slug'],
|
|
$pkg['description'],
|
|
$pkg['markup_type'],
|
|
$pkg['markup_value'],
|
|
$pkg['icon_name'],
|
|
$pkg['tagline'],
|
|
$pkg['price_text'],
|
|
(int) $pkg['is_featured'],
|
|
(int) $pkg['is_hidden'],
|
|
$pkg['badge'],
|
|
$pkg['badge_text'],
|
|
$pkg['video_url'],
|
|
(int) $pkg['sort_order'],
|
|
]);
|
|
$newId = (int) $db->lastInsertId();
|
|
Translations::copy('packages', (int) $pkg['id'], $newId);
|
|
$copyProducts->execute([$newId, $pkg['id']]);
|
|
$upgradeCount = 0;
|
|
if ($includeUpgrades) {
|
|
$copyUpgrades->execute([$newId, $pkg['id']]);
|
|
$upgradeCount = $copyUpgrades->rowCount();
|
|
}
|
|
$copied[] = ['name' => $pkg['name'], 'products' => $copyProducts->rowCount(), 'upgrades' => $upgradeCount];
|
|
}
|
|
|
|
return [$copied, $skipped];
|
|
}
|
|
|
|
public static function destroy(array $params): void
|
|
{
|
|
self::deletePackages(Database::connection(), [(int) $params['id']]);
|
|
Http::send(['ok' => true]);
|
|
}
|
|
|
|
/** Mehrere Pakete auf einmal loeschen (Auswahl im Admin), alles oder nichts. */
|
|
public static function destroyMany(): void
|
|
{
|
|
$body = Http::jsonBody();
|
|
$ids = array_values(array_unique(array_filter(array_map('intval', (array) ($body['ids'] ?? [])), fn($id) => $id > 0)));
|
|
if (!$ids) {
|
|
Http::error('Keine Pakete ausgewählt', 422);
|
|
}
|
|
|
|
$db = Database::connection();
|
|
$db->beginTransaction();
|
|
try {
|
|
$deleted = self::deletePackages($db, $ids);
|
|
$db->commit();
|
|
} catch (\Throwable $e) {
|
|
$db->rollBack();
|
|
throw $e;
|
|
}
|
|
|
|
Http::send(['deleted' => $deleted]);
|
|
}
|
|
|
|
/**
|
|
* Loescht Pakete samt Schriftstilen und Uebersetzungen; Produkte und Upgrades gehen per
|
|
* ON DELETE CASCADE mit. Ohne eigene Transaktion.
|
|
*
|
|
* @param int[] $ids
|
|
*/
|
|
private static function deletePackages(\PDO $db, array $ids): int
|
|
{
|
|
$stmt = $db->prepare('DELETE FROM packages WHERE id = ?');
|
|
$deleted = 0;
|
|
foreach ($ids as $id) {
|
|
$stmt->execute([$id]);
|
|
$deleted += $stmt->rowCount();
|
|
TextStyleCleanup::forgetEntity('packages', (string) $id);
|
|
Translations::forget('packages', $id);
|
|
}
|
|
return $deleted;
|
|
}
|
|
|
|
public static function products(array $params): void
|
|
{
|
|
$stmt = Database::connection()->prepare(
|
|
'SELECT id, package_id, source_url, name_override, scraped_name, scraped_price, scraped_currency,
|
|
scraped_image_url, price_updated_at, scrape_status, scrape_error, sort_order
|
|
FROM package_products WHERE package_id = ? ORDER BY sort_order, id'
|
|
);
|
|
$stmt->execute([(int) $params['id']]);
|
|
Http::send($stmt->fetchAll());
|
|
}
|
|
}
|