LuminaWebsite/warehouse.php

425 lines
24 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/warehouse.php';
require_permission('warehouse.view');
$canManage = user_has_permission('warehouse.manage');
warehouse_sync_catalog();
$stock = warehouse_stock();
// Kina steht als eigener Kasten oben, nicht zwischen den Gegenstaenden.
$kinaStmt = db()->prepare("SELECT id, icon FROM warehouse_items WHERE name = ? AND category = 'currency'");
$kinaStmt->execute([WAREHOUSE_KINA]);
$kinaItem = $kinaStmt->fetch() ?: null;
$kinaBalance = $kinaItem ? warehouse_item_stock((int) $kinaItem['id']) : 0;
$itemStock = array_values(array_filter($stock, static fn (array $row): bool => $row['category'] !== 'currency'));
// Gegenstaende, die der Lumishop aus dem Lagerhaus verkauft - bekommen einen Hinweis mit Preis.
$shopPrices = [];
try {
$shopPrices = db()->query(
"SELECT warehouse_item_id, price FROM shop_items WHERE stock_mode = 'warehouse' AND active = 1 AND warehouse_item_id IS NOT NULL"
)->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (PDOException $e) {
$shopPrices = [];
}
$stockTotal = array_sum(array_map(static fn (array $row): int => (int) $row['quantity'], $itemStock));
// Verlauf, optional nur fuer einen Gegenstand (Klick auf den Namen im Bestand).
$filterItemId = isset($_GET['item']) ? (int) $_GET['item'] : null;
$filterItem = null;
if ($filterItemId !== null) {
$stmt = db()->prepare('SELECT id, name FROM warehouse_items WHERE id = ?');
$stmt->execute([$filterItemId]);
$filterItem = $stmt->fetch() ?: null;
if (!$filterItem) {
$filterItemId = null;
}
}
// Suche, Art (eingelagert/entnommen) und Sortierung - alles in der Adresse, damit die Seiten mitwandern.
$historyQuery = mb_substr(trim((string) ($_GET['q'] ?? '')), 0, 100);
$historyDirection = in_array($_GET['dir'] ?? '', ['in', 'out'], true) ? (string) $_GET['dir'] : '';
$historySort = isset(WAREHOUSE_HISTORY_SORTS[$_GET['sort'] ?? '']) ? (string) $_GET['sort'] : 'new';
$historyFilter = ['item' => $filterItemId, 'direction' => $historyDirection, 'q' => $historyQuery];
$historyFiltered = $historyQuery !== '' || $historyDirection !== '';
/** Link auf den Verlauf mit den aktuellen Filtern, einzelne Werte ueberschrieben ('' = weglassen). */
$historyUrl = static function (array $overrides = []) use ($filterItemId, $historyQuery, $historyDirection, $historySort): string {
$params = array_merge([
'item' => $filterItemId !== null ? (string) $filterItemId : '',
'q' => $historyQuery,
'dir' => $historyDirection,
'sort' => $historySort !== 'new' ? $historySort : '',
], $overrides);
$params = array_filter($params, static fn ($value): bool => $value !== '' && $value !== null);
return '/warehouse.php?' . ($params ? http_build_query($params) . '&' : '');
};
$perPage = 25;
$totalMovements = warehouse_movement_count($historyFilter);
$pageCount = max(1, (int) ceil($totalMovements / $perPage));
$page = min($pageCount, max(1, (int) ($_GET['page'] ?? 1)));
$movements = warehouse_movements($historyFilter, $perPage, ($page - 1) * $perPage, $historySort);
// Fuer die Formulare: alle Gegenstaende (Vorschlagsliste) und die Konten der Website.
$allItems = $canManage ? db()->query('SELECT id, name, category, icon FROM warehouse_items ORDER BY name')->fetchAll() : [];
$stockById = array_map('intval', array_column($stock, 'quantity', 'id'));
// Vorschlaege fuer die Suche im Verlauf: nur Gegenstaende, die schon einmal bewegt wurden.
$historyItems = db()->query(
'SELECT i.id, i.name, i.category, i.icon FROM warehouse_items i
WHERE EXISTS (SELECT 1 FROM warehouse_movements m WHERE m.item_id = i.id) ORDER BY i.name'
)->fetchAll();
$members = $canManage ? db()->query(
"SELECT id, COALESCE(NULLIF(display_name, ''), username) AS name FROM users
WHERE status = 'active' ORDER BY name"
)->fetchAll() : [];
// Eingaben nach einem Fehler wieder ins Formular (siehe warehouse_action.php).
$old = $_SESSION['warehouse_form'] ?? [];
unset($_SESSION['warehouse_form']);
$openForm = (string) ($old['form'] ?? '');
$categoriesInStock = [];
$categoryCounts = [];
foreach ($itemStock as $row) {
$categoriesInStock[$row['category']] = warehouse_category_label((string) $row['category']);
$categoryCounts[$row['category']] = ($categoryCounts[$row['category']] ?? 0) + 1;
}
asort($categoriesInStock);
/** Von wem / an wen: Konto oder frei eingetragener Name. */
function warehouse_counterpart(array $movement): string
{
if (!empty($movement['counterpart_user'])) {
return (string) $movement['counterpart_user'];
}
return (string) ($movement['counterpart_name'] ?? '');
}
/** Auswahl "Konto oder Name" fuer beide Formulare. */
function warehouse_render_counterpart(string $prefix, array $members, array $old, bool $required): void
{
$selectedUser = (string) ($old['counterpart_user'] ?? '');
?>
<div class="warehouse-counterpart">
<div>
<label for="<?= e($prefix) ?>-user">Mitglied der Website</label>
<select id="<?= e($prefix) ?>-user" name="counterpart_user">
<option value="">– kein Konto / Name eintragen –</option>
<?php foreach ($members as $member): ?>
<option value="<?= (int) $member['id'] ?>" <?= $selectedUser === (string) $member['id'] ? 'selected' : '' ?>><?= e((string) $member['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="<?= e($prefix) ?>-name">oder Name</label>
<input type="text" id="<?= e($prefix) ?>-name" name="counterpart_name" maxlength="100"
value="<?= e((string) ($old['counterpart_name'] ?? '')) ?>" placeholder="z.B. Spielername ohne Website-Konto">
</div>
</div>
<div class="field-hint"><?= $required ? 'Ein Konto auswählen oder einen Namen eintragen.' : 'Optional - leer lassen, wenn es an niemand Bestimmten ging.' ?></div>
<?php
}
$pageTitle = 'Lagerhaus';
$containerWide = true;
include __DIR__ . '/includes/header.php';
?>
<div class="panel">
<div class="warehouse-head">
<div>
<h1>Lagerhaus</h1>
<p class="text-muted">
<?= count($itemStock) ?> verschiedene Gegenstände, <?= number_format($stockTotal, 0, ',', '.') ?> Stück insgesamt.
</p>
</div>
<?php if ($kinaItem): ?>
<div class="warehouse-kina">
<?= warehouse_icon_html($kinaItem['icon'] ?? null, WAREHOUSE_KINA, 44) ?>
<div>
<span class="text-muted">Kina im Lager</span>
<strong><?= number_format($kinaBalance, 0, ',', '.') ?></strong>
</div>
<?php if ($canManage): ?>
<div class="warehouse-kina-actions">
<button type="button" class="button-secondary button-small" data-open-modal="warehouse-in-modal" data-item-name="<?= e(WAREHOUSE_KINA) ?>">+ Einzahlen</button>
<button type="button" class="button-secondary button-small" data-open-modal="warehouse-out-modal" data-item-id="<?= (int) $kinaItem['id'] ?>" <?= $kinaBalance > 0 ? '' : 'disabled' ?>>− Auszahlen</button>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($canManage): ?>
<div class="actions">
<button type="button" class="button-success" data-open-modal="warehouse-in-modal">+ Einlagern</button>
<button type="button" class="button-secondary" data-open-modal="warehouse-out-modal" <?= empty($stock) ? 'disabled' : '' ?>>− Entnehmen</button>
</div>
<?php endif; ?>
</div>
<div class="list-toolbar warehouse-filters">
<label class="search-field">
<?= icon('search') ?>
<input type="search" id="warehouse-search" placeholder="Gegenstand suchen …" autocomplete="off" aria-label="Bestand durchsuchen">
</label>
<?php if (count($categoriesInStock) > 1): ?>
<div class="members-chips" id="warehouse-category" role="group" aria-label="Nach Kategorie filtern">
<button type="button" class="members-chip active" data-value="" aria-pressed="true">Alle <span class="chip-count"><?= count($itemStock) ?></span></button>
<?php foreach ($categoriesInStock as $key => $label): ?>
<button type="button" class="members-chip" data-value="<?= e((string) $key) ?>" aria-pressed="false"><?= e($label) ?> <span class="chip-count"><?= (int) $categoryCounts[$key] ?></span></button>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php if (empty($itemStock)): ?>
<p class="text-muted">Keine Gegenstände im Lager.<?= $canManage ? ' Mit „Einlagern“ trägst du den ersten Gegenstand ein.' : '' ?></p>
<?php else: ?>
<div class="warehouse-grid" id="warehouse-stock">
<?php foreach ($itemStock as $row): ?>
<div class="warehouse-card" data-name="<?= e(mb_strtolower((string) $row['name'])) ?>" data-category="<?= e((string) $row['category']) ?>">
<a class="warehouse-card-link" href="/warehouse.php?item=<?= (int) $row['id'] ?>#verlauf"
title="<?= e((string) $row['name']) ?> - zuletzt bewegt <?= e(warehouse_format_time($row['last_movement'])) ?>. Klicken für den Verlauf.">
<span class="warehouse-card-image">
<?= warehouse_icon_html($row['icon'] ?? null, (string) $row['name'], 72) ?>
<span class="warehouse-card-qty"><?= number_format((int) $row['quantity'], 0, ',', '.') ?></span>
</span>
<span class="warehouse-card-name"><?= e((string) $row['name']) ?></span>
<span class="warehouse-card-category"><?= e(warehouse_category_label((string) $row['category'])) ?></span>
<?php if (isset($shopPrices[(int) $row['id']])): ?>
<span class="warehouse-card-shop" title="Im Lumishop erhältlich">
Lumishop · <img src="/assets/images/lumipunkt.svg" alt="" width="12" height="12"> <?= e(number_format((int) $shopPrices[(int) $row['id']], 0, ',', '.')) ?>
</span>
<?php endif; ?>
</a>
<?php if ($canManage): ?>
<div class="warehouse-card-actions">
<button type="button" class="icon-button" title="Entnehmen" aria-label="Entnehmen"
data-open-modal="warehouse-out-modal" data-item-id="<?= (int) $row['id'] ?>">−</button>
<button type="button" class="icon-button" title="Mehr einlagern" aria-label="Mehr einlagern"
data-open-modal="warehouse-in-modal" data-item-name="<?= e((string) $row['name']) ?>">+</button>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<p class="text-muted warehouse-no-match" id="warehouse-no-match" hidden>Kein Gegenstand passt zur Suche.</p>
<?php endif; ?>
</div>
<div class="panel" id="verlauf">
<div class="warehouse-head">
<h2>Verlauf<?= $filterItem ? ': ' . e((string) $filterItem['name']) : '' ?></h2>
<?php if ($filterItem): ?>
<a href="<?= e($historyUrl(['item' => '']) . '#verlauf') ?>">Alle Gegenstände anzeigen</a>
<?php endif; ?>
</div>
<form class="list-toolbar" id="warehouse-history-filter" method="get" action="/warehouse.php#verlauf">
<?php if ($filterItemId !== null): ?><input type="hidden" name="item" value="<?= (int) $filterItemId ?>"><?php endif; ?>
<input type="hidden" name="dir" value="<?= e($historyDirection) ?>">
<input type="hidden" name="sort" value="<?= e($historySort) ?>">
<div class="item-picker" data-picker-items="warehouse-picker-history" data-picker-mode="submit" data-picker-empty="Kein Gegenstand - Enter sucht auch in Personen und Bemerkungen.">
<label class="search-field">
<span class="item-picker-icon"><?= icon('search') ?></span>
<input type="search" class="item-picker-input" id="history-search" name="q" value="<?= e($historyQuery) ?>" placeholder="Gegenstand, Person oder Bemerkung suchen …" aria-label="Verlauf durchsuchen">
</label>
</div>
<script type="application/json" id="warehouse-picker-history"><?= warehouse_picker_json($historyItems) ?></script>
<div class="list-toolbar-row">
<div class="members-chips" role="group" aria-label="Nach Art filtern">
<?php foreach (['' => 'Alle', 'in' => 'Eingelagert', 'out' => 'Entnommen'] as $value => $label): ?>
<button type="submit" name="dir" value="<?= e($value) ?>" class="members-chip<?= $historyDirection === $value ? ' active' : '' ?>" aria-pressed="<?= $historyDirection === $value ? 'true' : 'false' ?>"><?= e($label) ?></button>
<?php endforeach; ?>
</div>
<div class="list-toolbar-meta">
<span class="members-filter-label"><?= icon('sort') ?> Sortieren</span>
<div class="members-segment" role="group" aria-label="Sortieren">
<?php foreach (WAREHOUSE_HISTORY_SORTS as $value => [$label]): ?>
<button type="submit" name="sort" value="<?= e($value) ?>" class="<?= $historySort === $value ? 'active' : '' ?>"><?= e($label) ?></button>
<?php endforeach; ?>
</div>
<span class="list-search-count text-muted">
<?= number_format($totalMovements, 0, ',', '.') ?> <?= $totalMovements === 1 ? 'Eintrag' : 'Einträge' ?>
<?php if ($historyFiltered): ?>
· <a href="<?= e($historyUrl(['q' => '', 'dir' => '']) . '#verlauf') ?>">Filter zurücksetzen</a>
<?php endif; ?>
</span>
</div>
</div>
</form>
<?php if (empty($movements)): ?>
<p class="text-muted"><?= $historyFiltered ? 'Kein Eintrag passt zu Suche und Filter.' : 'Noch keine Einträge.' ?></p>
<?php else: ?>
<div class="table-scroll">
<table class="table-actions">
<thead>
<tr>
<th>Zeitpunkt</th>
<th>Art</th>
<th>Gegenstand</th>
<th class="num">Menge</th>
<th>Von / An</th>
<th>Bemerkung</th>
<th>Eingetragen von</th>
<th><?= $canManage ? 'Aktionen' : '' ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($movements as $movement): ?>
<?php $isIn = $movement['direction'] === 'in'; ?>
<tr>
<td><?= e(warehouse_format_time($movement['occurred_at'])) ?></td>
<td><span class="badge <?= $isIn ? 'badge-active' : 'badge-disabled' ?>"><?= $isIn ? 'Eingelagert' : 'Entnommen' ?></span></td>
<td>
<a class="warehouse-item-inline" href="/warehouse.php?item=<?= (int) $movement['item_id'] ?>#verlauf">
<?= warehouse_icon_html($movement['icon'] ?? null, (string) $movement['item_name'], 32) ?>
<span><?= e((string) $movement['item_name']) ?></span>
</a>
</td>
<td class="num"><?= $isIn ? '+' : '−' ?><?= number_format((int) $movement['quantity'], 0, ',', '.') ?></td>
<td>
<?php $who = warehouse_counterpart($movement); ?>
<?php if ($who !== ''): ?>
<span class="text-muted"><?= $isIn ? 'von' : 'an' ?></span> <?= e($who) ?>
<?php else: ?>
<span class="text-muted">-</span>
<?php endif; ?>
</td>
<td><?= e((string) ($movement['note'] ?? '')) ?></td>
<td><?= e((string) ($movement['author'] ?? '-')) ?></td>
<td>
<?php if ($canManage): ?>
<form class="inline-form" method="post" action="/warehouse_action.php"
onsubmit="return confirm('Diesen Eintrag löschen? Der Bestand wird entsprechend angepasst.');">
<?= csrf_field() ?>
<input type="hidden" name="action" value="delete">
<input type="hidden" name="movement_id" value="<?= (int) $movement['id'] ?>">
<button type="submit" class="icon-button icon-button-danger" title="Eintrag löschen" aria-label="Eintrag löschen"><?= icon('trash') ?></button>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div class="warehouse-pages">
<span class="text-muted">
Einträge <?= ($page - 1) * $perPage + 1 ?>–<?= min($page * $perPage, $totalMovements) ?>
von <?= number_format($totalMovements, 0, ',', '.') ?>
</span>
<?php render_pagination($historyUrl(), $page, $pageCount, '#verlauf'); ?>
</div>
<?php endif; ?>
</div>
<?php if ($canManage): ?>
<?php $oldIn = $openForm === 'in' ? $old : []; $oldOut = $openForm === 'out' ? $old : []; ?>
<!-- Einlagern -->
<div class="modal-overlay" id="warehouse-in-modal" <?= $openForm === 'in' ? '' : 'hidden' ?>>
<div class="modal">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2>Einlagern</h2>
<form method="post" action="/warehouse_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="deposit">
<div>
<label for="in-item">Gegenstand</label>
<div class="item-picker" data-picker-items="warehouse-picker-all" data-picker-empty="Nicht im Katalog - wird beim Einlagern als neuer Gegenstand angelegt.">
<label class="search-field">
<span class="item-picker-icon"><?= icon('search') ?></span>
<input type="text" class="item-picker-input" id="in-item" name="item" required
value="<?= e((string) ($oldIn['item'] ?? '')) ?>" placeholder="Gegenstand suchen …">
</label>
</div>
<script type="application/json" id="warehouse-picker-all"><?= warehouse_picker_json($allItems, $stockById) ?></script>
</div>
<?php if (!empty($oldIn['unknown_item'])): ?>
<div class="warehouse-new-item">
<label>
<input type="checkbox" name="create_item" value="1" checked>
„<?= e((string) $oldIn['item']) ?>“ als neuen Gegenstand anlegen
</label>
<select name="create_category">
<?php foreach (WAREHOUSE_CUSTOM_CATEGORIES as $key): ?>
<option value="<?= e($key) ?>" <?= ($oldIn['create_category'] ?? 'material') === $key ? 'selected' : '' ?>><?= e(warehouse_category_label($key)) ?></option>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?>
<div class="warehouse-row">
<div>
<label for="in-quantity">Anzahl</label>
<input type="number" id="in-quantity" name="quantity" min="1" max="<?= WAREHOUSE_MAX_CURRENCY ?>" required
value="<?= e((string) ($oldIn['quantity'] ?? '1')) ?>">
</div>
<div>
<label for="in-time">Überreicht am</label>
<input type="datetime-local" id="in-time" name="occurred_at" required
value="<?= e((string) ($oldIn['occurred_at'] ?? warehouse_now_input())) ?>">
</div>
</div>
<label>Überreicht von</label>
<?php warehouse_render_counterpart('in', $members, $oldIn, true); ?>
<div>
<label for="in-note">Bemerkung <span class="text-muted">(optional)</span></label>
<input type="text" id="in-note" name="note" maxlength="255" value="<?= e((string) ($oldIn['note'] ?? '')) ?>">
</div>
<div class="actions">
<button type="submit" class="button-success">Einlagern</button>
</div>
</form>
</div>
</div>
<!-- Entnehmen -->
<div class="modal-overlay" id="warehouse-out-modal" <?= $openForm === 'out' ? '' : 'hidden' ?>>
<div class="modal">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2>Entnehmen</h2>
<form method="post" action="/warehouse_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="withdraw">
<div>
<label for="out-item-search">Gegenstand</label>
<div class="item-picker" data-picker-items="warehouse-picker-stock" data-picker-mode="id" data-picker-empty="Nicht auf Lager.">
<input type="hidden" id="out-item" name="item_id" value="<?= e((string) ($oldOut['item_id'] ?? '')) ?>">
<label class="search-field">
<span class="item-picker-icon"><?= icon('search') ?></span>
<input type="text" class="item-picker-input" id="out-item-search" required placeholder="Aus dem Bestand wählen …" aria-label="Gegenstand">
</label>
</div>
<script type="application/json" id="warehouse-picker-stock"><?= warehouse_picker_json($stock) ?></script>
</div>
<div class="warehouse-row">
<div>
<label for="out-quantity">Anzahl</label>
<input type="number" id="out-quantity" name="quantity" min="1" required
value="<?= e((string) ($oldOut['quantity'] ?? '1')) ?>">
</div>
<div>
<label for="out-time">Entnommen am</label>
<input type="datetime-local" id="out-time" name="occurred_at" required
value="<?= e((string) ($oldOut['occurred_at'] ?? warehouse_now_input())) ?>">
</div>
</div>
<label>Überreicht an <span class="text-muted">(optional)</span></label>
<?php warehouse_render_counterpart('out', $members, $oldOut, false); ?>
<div>
<label for="out-note">Bemerkung <span class="text-muted">(optional)</span></label>
<input type="text" id="out-note" name="note" maxlength="255" value="<?= e((string) ($oldOut['note'] ?? '')) ?>">
</div>
<div class="actions">
<button type="submit">Entnehmen</button>
</div>
</form>
</div>
</div>
<?php endif; ?>
<script src="<?= e(asset_url('/assets/js/item-picker.js')) ?>"></script>
<script src="<?= e(asset_url('/assets/js/warehouse.js')) ?>"></script>
<?php include __DIR__ . '/includes/footer.php'; ?>