LuminaWebsite/includes/warehouse.php
Maaxxs 3e025b811e Lagerhaus: stock and history of the legion's items
A new page records items handed in (item, quantity, when, and from whom -
a website account or a free-text name) and taken out (when, now or entered
by hand, and optionally to whom). Stock is always computed from the
movements, withdrawals can't exceed it, and a deposit can only be deleted
once nothing of it has been taken out. Stock is shown as cards with the item
picture and quantity, name and category below, plus search and a category
filter; the history lists every movement with who entered it.

The item list holds 2,301 weapons, armor pieces, accessories and consumables
read from the Aion 2 wiki's MediaWiki API, with each item's icon downscaled
to 128px under assets/images/warehouse/. It is loaded into the database on
first visit and again whenever the JSON changes. Unknown names can be added
as custom items after a confirmation, since the wiki lists no materials.

warehouse.view and warehouse.manage are new permissions. Missing core
permissions are now created automatically and granted to the Administrator
group, and the two tables are created like the other schema additions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 08:46:40 +02:00

210 lines
7.6 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 = [
'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;
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();
$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.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;
}
/**
* Letzte Bewegungen, optional nur fuer einen Gegenstand.
*
* @return array<int, array<string, mixed>>
*/
function warehouse_movements(?int $itemId, int $limit, int $offset): array
{
$where = $itemId !== null ? 'WHERE m.item_id = ?' : '';
$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
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
$where
ORDER BY m.occurred_at DESC, m.id DESC
LIMIT " . (int) $limit . ' OFFSET ' . (int) $offset
);
$stmt->execute($itemId !== null ? [$itemId] : []);
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;
}