LuminaWebsite/includes/warehouse.php
Maaxxs 11d8e8d819 Warehouse history: search, in/out filter and sorting (server-side, kept across pages)
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 21:16:07 +02:00

289 lines
11 KiB
PHP

<?php
declare(strict_types=1);
/**
* Lagerhaus der Legion: Gegenstandsliste, Einlagerungen und Entnahmen.
*
* Der Bestand wird nicht gespeichert, sondern aus den Bewegungen berechnet (Summe der
* Einlagerungen minus Summe der Entnahmen). So kann er nie von der Historie abweichen.
*/
const WAREHOUSE_CATALOG_FILE = __DIR__ . '/data/warehouse_items.json';
/**
* Kategorien: Schluessel => [Bezeichnung, Gruppe]. Die ersten stammen aus dem Aion-2-Wiki,
* "material" und "other" sind fuer selbst angelegte Gegenstaende (Rohstoffe usw. fuehrt das
* Wiki nicht).
*/
const WAREHOUSE_CATEGORIES = [
'currency' => ['Währung', 'Währung'],
'sword' => ['Schwert', 'Waffen'],
'greatsword' => ['Großschwert', 'Waffen'],
'dagger' => ['Dolch', 'Waffen'],
'bow' => ['Bogen', 'Waffen'],
'mace' => ['Streitkolben', 'Waffen'],
'staff' => ['Stab', 'Waffen'],
'orb' => ['Orb', 'Waffen'],
'spellbook' => ['Zauberbuch', 'Waffen'],
'guarder' => ['Schild', 'Waffen'],
'helmet' => ['Helm', 'Rüstung'],
'shoulder' => ['Schultern', 'Rüstung'],
'torso' => ['Brustrüstung', 'Rüstung'],
'pants' => ['Beinschutz', 'Rüstung'],
'gloves' => ['Handschuhe', 'Rüstung'],
'boots' => ['Stiefel', 'Rüstung'],
'cape' => ['Umhang', 'Rüstung'],
'necklace' => ['Halskette', 'Accessoires'],
'earring' => ['Ohrringe', 'Accessoires'],
'ring' => ['Ring', 'Accessoires'],
'bracelet' => ['Armband', 'Accessoires'],
'belt' => ['Gürtel', 'Accessoires'],
'amulet' => ['Amulett', 'Accessoires'],
'rune' => ['Rune', 'Accessoires'],
'potion' => ['Trank', 'Verbrauchsgüter'],
'food' => ['Essen', 'Verbrauchsgüter'],
'drink' => ['Getränk', 'Verbrauchsgüter'],
'scroll' => ['Schriftrolle', 'Verbrauchsgüter'],
'material' => ['Material', 'Sonstiges'],
'other' => ['Sonstiges', 'Sonstiges'],
];
// Kategorien, die man beim Anlegen eigener Gegenstaende waehlen kann.
const WAREHOUSE_CUSTOM_CATEGORIES = ['material', 'other', 'potion', 'food', 'drink', 'scroll'];
const WAREHOUSE_MAX_QUANTITY = 1000000;
// Kina (Waehrung) geht schnell in die Millionen - dafuer gilt eine eigene Obergrenze.
const WAREHOUSE_KINA = 'Kina';
const WAREHOUSE_MAX_CURRENCY = 1000000000000;
/** Hoechstmenge pro Eintrag fuer eine Kategorie. */
function warehouse_max_quantity(string $category): int
{
return $category === 'currency' ? WAREHOUSE_MAX_CURRENCY : WAREHOUSE_MAX_QUANTITY;
}
function warehouse_category_label(string $key): string
{
return WAREHOUSE_CATEGORIES[$key][0] ?? $key;
}
/**
* Uebernimmt die Gegenstandsliste aus includes/data/warehouse_items.json in die Datenbank.
* Laeuft nur, wenn sich die Datei geaendert hat (Pruefsumme in settings). Vorhandene Eintraege
* und alles, was schon eingelagert wurde, bleiben erhalten - neue Namen kommen dazu.
*/
function warehouse_sync_catalog(): void
{
if (!is_file(WAREHOUSE_CATALOG_FILE)) {
return;
}
$hash = md5_file(WAREHOUSE_CATALOG_FILE);
if (setting_get('warehouse_catalog_hash') === $hash) {
return;
}
$data = json_decode((string) file_get_contents(WAREHOUSE_CATALOG_FILE), true);
if (!is_array($data) || !is_array($data['items'] ?? null)) {
return;
}
$pdo = db();
$pdo->beginTransaction();
// Die Waehrung hiess kurz "Kinah" - vorhandene Buchungen wandern zu "Kina".
$old = $pdo->query("SELECT id FROM warehouse_items WHERE name = 'Kinah' AND category = 'currency'")->fetchColumn();
if ($old !== false) {
$new = $pdo->query("SELECT id FROM warehouse_items WHERE name = 'Kina' AND category = 'currency'")->fetchColumn();
if ($new === false) {
$pdo->prepare("UPDATE warehouse_items SET name = 'Kina' WHERE id = ?")->execute([(int) $old]);
} else {
$pdo->prepare('UPDATE warehouse_movements SET item_id = ? WHERE item_id = ?')->execute([(int) $new, (int) $old]);
$pdo->prepare('DELETE FROM warehouse_items WHERE id = ?')->execute([(int) $old]);
}
}
$icons = is_array($data['icons'] ?? null) ? $data['icons'] : [];
$insert = $pdo->prepare(
"INSERT INTO warehouse_items (name, category, icon, source) VALUES (?, ?, ?, 'wiki')
ON DUPLICATE KEY UPDATE category = IF(source = 'wiki', VALUES(category), category),
icon = IF(source = 'wiki', VALUES(icon), icon)"
);
foreach ($data['items'] as $category => $names) {
if (!isset(WAREHOUSE_CATEGORIES[$category]) || !is_array($names)) {
continue;
}
foreach ($names as $name) {
$name = (string) $name;
$icon = isset($icons[$name]) ? (string) $icons[$name] : null;
$insert->execute([mb_substr($name, 0, 150), $category, $icon]);
}
}
$pdo->commit();
setting_set('warehouse_catalog_hash', (string) $hash);
}
/**
* Aktueller Bestand: alle Gegenstaende mit Menge > 0.
*
* @return array<int, array<string, mixed>>
*/
function warehouse_stock(): array
{
return db()->query(
"SELECT i.id, i.name, i.category, i.icon,
SUM(CASE WHEN m.direction = 'in' THEN m.quantity ELSE -m.quantity END) AS quantity,
MAX(m.occurred_at) AS last_movement
FROM warehouse_items i
JOIN warehouse_movements m ON m.item_id = i.id
GROUP BY i.id
HAVING quantity > 0
ORDER BY i.category = 'currency' DESC, i.name"
)->fetchAll();
}
/** Bestand eines einzelnen Gegenstands. */
function warehouse_item_stock(int $itemId): int
{
$stmt = db()->prepare(
"SELECT COALESCE(SUM(CASE WHEN direction = 'in' THEN quantity ELSE -quantity END), 0)
FROM warehouse_movements WHERE item_id = ?"
);
$stmt->execute([$itemId]);
return (int) $stmt->fetchColumn();
}
/** Findet einen Gegenstand ueber seinen Namen (Gross-/Kleinschreibung egal). */
function warehouse_find_item(string $name): ?array
{
$stmt = db()->prepare('SELECT id, name, category FROM warehouse_items WHERE name = ?');
$stmt->execute([trim($name)]);
$row = $stmt->fetch();
return $row ?: null;
}
/** Sortierungen fuer den Verlauf: Schluessel => [Beschriftung, ORDER BY]. */
const WAREHOUSE_HISTORY_SORTS = [
'new' => ['Neueste', 'm.occurred_at DESC, m.id DESC'],
'old' => ['Älteste', 'm.occurred_at ASC, m.id ASC'],
'qty' => ['Menge', 'm.quantity DESC, m.occurred_at DESC, m.id DESC'],
'item' => ['Gegenstand', 'i.name ASC, m.occurred_at DESC, m.id DESC'],
];
/**
* WHERE-Teil fuer den Verlauf. Filter: item (ID), direction ('in'/'out') und q (Suche in
* Gegenstand, Von/An, Bemerkung und "Eingetragen von").
*
* @param array{item?: ?int, direction?: string, q?: string} $filter
* @return array{0: string, 1: array<int, mixed>}
*/
function warehouse_history_where(array $filter): array
{
$conditions = [];
$params = [];
if (($filter['item'] ?? null) !== null) {
$conditions[] = 'm.item_id = ?';
$params[] = (int) $filter['item'];
}
if (in_array($filter['direction'] ?? '', ['in', 'out'], true)) {
$conditions[] = 'm.direction = ?';
$params[] = $filter['direction'];
}
$q = trim((string) ($filter['q'] ?? ''));
if ($q !== '') {
$like = '%' . addcslashes($q, '%_\\') . '%';
$conditions[] = '(i.name LIKE ? OR m.counterpart_name LIKE ? OR m.note LIKE ?
OR cu.display_name LIKE ? OR cu.username LIKE ? OR au.display_name LIKE ? OR au.username LIKE ?)';
array_push($params, $like, $like, $like, $like, $like, $like, $like);
}
return [$conditions ? 'WHERE ' . implode(' AND ', $conditions) : '', $params];
}
/** Gemeinsame Joins fuer Verlauf und Zaehlung (die Suche braucht die Namen). */
const WAREHOUSE_HISTORY_FROM = 'FROM warehouse_movements m
JOIN warehouse_items i ON i.id = m.item_id
LEFT JOIN users cu ON cu.id = m.counterpart_user_id
LEFT JOIN users au ON au.id = m.created_by';
/**
* Anzahl der Bewegungen (fuer die Seitenzahlen im Verlauf).
*
* @param array{item?: ?int, direction?: string, q?: string} $filter
*/
function warehouse_movement_count(array $filter = []): int
{
[$where, $params] = warehouse_history_where($filter);
$stmt = db()->prepare('SELECT COUNT(*) ' . WAREHOUSE_HISTORY_FROM . ' ' . $where);
$stmt->execute($params);
return (int) $stmt->fetchColumn();
}
/**
* Bewegungen fuer den Verlauf, gefiltert und sortiert (siehe WAREHOUSE_HISTORY_SORTS).
*
* @param array{item?: ?int, direction?: string, q?: string} $filter
* @return array<int, array<string, mixed>>
*/
function warehouse_movements(array $filter, int $limit, int $offset, string $sort = 'new'): array
{
[$where, $params] = warehouse_history_where($filter);
$order = (WAREHOUSE_HISTORY_SORTS[$sort] ?? WAREHOUSE_HISTORY_SORTS['new'])[1];
$stmt = db()->prepare(
"SELECT m.id, m.item_id, m.direction, m.quantity, m.occurred_at, m.note, m.created_at,
m.counterpart_name, i.name AS item_name, i.category, i.icon,
COALESCE(NULLIF(cu.display_name, ''), cu.username) AS counterpart_user,
COALESCE(NULLIF(au.display_name, ''), au.username) AS author
" . WAREHOUSE_HISTORY_FROM . "
$where
ORDER BY $order
LIMIT " . (int) $limit . ' OFFSET ' . (int) $offset
);
$stmt->execute($params);
return $stmt->fetchAll();
}
/**
* Bild eines Gegenstands. Ohne Bild (selbst angelegte Gegenstaende, ein paar Wiki-Eintraege)
* ein Platzhalter mit Kisten-Symbol in derselben Groesse.
*/
function warehouse_icon_html(?string $icon, string $name, int $size): string
{
$style = 'width:' . $size . 'px;height:' . $size . 'px;';
if ($icon !== null && $icon !== '' && preg_match('/^[a-z0-9_]+\.webp$/', $icon)) {
return '<img class="warehouse-icon" src="/assets/images/warehouse/' . e($icon) . '" alt="" loading="lazy" '
. 'width="' . $size . '" height="' . $size . '" style="' . $style . '">';
}
return '<span class="warehouse-icon warehouse-icon-placeholder" style="' . $style . '" title="' . e($name) . '">'
. icon('box') . '</span>';
}
/** Jetzt in deutscher Zeit, passend fuer ein datetime-local-Feld. */
function warehouse_now_input(): string
{
return (new DateTimeImmutable('now', new DateTimeZone('Europe/Berlin')))->format('Y-m-d\TH:i');
}
/**
* Liest einen Zeitpunkt aus einem datetime-local-Feld. Null bei ungueltiger Eingabe oder
* wenn er mehr als einen Tag in der Zukunft liegt (Tippfehler im Jahr o.ae.).
*/
function warehouse_parse_time(string $value): ?string
{
$tz = new DateTimeZone('Europe/Berlin');
$time = DateTimeImmutable::createFromFormat('Y-m-d\TH:i', trim($value), $tz);
if ($time === false || $time > new DateTimeImmutable('+1 day', $tz)) {
return null;
}
return $time->format('Y-m-d H:i:s');
}
/** Anzeige eines gespeicherten Zeitpunkts: 21.09.2026 14:30 */
function warehouse_format_time(?string $value): string
{
if ($value === null || $value === '') {
return '-';
}
$time = strtotime($value);
return $time ? date('d.m.Y H:i', $time) : $value;
}