LuminaWebsite/warehouse_action.php
Maaxxs 338a00c21f Log all administrative website actions to the Discord log channel via the bot API
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:16:54 +02:00

214 lines
9.8 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.manage');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect('/warehouse.php');
}
verify_csrf();
$action = (string) ($_POST['action'] ?? '');
$userId = (int) current_user()['id'];
$pdo = db();
/** Bricht mit Fehlermeldung ab und oeffnet das Formular mit den bisherigen Eingaben wieder. */
function warehouse_fail(string $form, string $message, array $extra = []): void
{
$_SESSION['warehouse_form'] = array_merge([
'form' => $form,
'item' => (string) ($_POST['item'] ?? ''),
'item_id' => (string) ($_POST['item_id'] ?? ''),
'quantity' => (string) ($_POST['quantity'] ?? ''),
'occurred_at' => (string) ($_POST['occurred_at'] ?? ''),
'counterpart_user' => (string) ($_POST['counterpart_user'] ?? ''),
'counterpart_name' => (string) ($_POST['counterpart_name'] ?? ''),
'note' => (string) ($_POST['note'] ?? ''),
'create_category' => (string) ($_POST['create_category'] ?? ''),
], $extra);
set_flash('error', $message);
redirect('/warehouse.php');
}
/**
* Liest die gemeinsamen Felder beider Formulare.
*
* @return array{quantity: int, occurred_at: string, user_id: ?int, name: ?string, note: ?string}
*/
function warehouse_read_common(string $form, bool $counterpartRequired): array
{
// Obergrenze hier die fuer Kina; die fuer Gegenstaende prueft warehouse_check_quantity().
$quantity = filter_var($_POST['quantity'] ?? '', FILTER_VALIDATE_INT);
if ($quantity === false || $quantity < 1 || $quantity > WAREHOUSE_MAX_CURRENCY) {
warehouse_fail($form, 'Bitte eine gültige Anzahl angeben.');
}
$occurredAt = warehouse_parse_time((string) ($_POST['occurred_at'] ?? ''));
if ($occurredAt === null) {
warehouse_fail($form, 'Bitte einen gültigen Zeitpunkt angeben (nicht in der Zukunft).');
}
$counterpartUser = (int) ($_POST['counterpart_user'] ?? 0);
$counterpartName = trim((string) ($_POST['counterpart_name'] ?? ''));
if ($counterpartUser > 0) {
$stmt = db()->prepare('SELECT 1 FROM users WHERE id = ?');
$stmt->execute([$counterpartUser]);
if (!$stmt->fetchColumn()) {
warehouse_fail($form, 'Das ausgewählte Konto gibt es nicht mehr.');
}
$counterpartName = ''; // Konto hat Vorrang vor dem frei eingetragenen Namen
}
if (mb_strlen($counterpartName) > 100) {
warehouse_fail($form, 'Der Name darf höchstens 100 Zeichen lang sein.');
}
if ($counterpartRequired && $counterpartUser === 0 && $counterpartName === '') {
warehouse_fail($form, 'Bitte angeben, von wem der Gegenstand überreicht wurde - ein Konto auswählen oder einen Namen eintragen.');
}
$note = trim((string) ($_POST['note'] ?? ''));
if (mb_strlen($note) > 255) {
warehouse_fail($form, 'Die Bemerkung darf höchstens 255 Zeichen lang sein.');
}
return [
'quantity' => (int) $quantity,
'occurred_at' => $occurredAt,
'user_id' => $counterpartUser > 0 ? $counterpartUser : null,
'name' => $counterpartName !== '' ? $counterpartName : null,
'note' => $note !== '' ? $note : null,
];
}
/** Prueft die Menge gegen die Obergrenze der Kategorie (Gegenstaende 1 Mio., Kina 1 Billion). */
function warehouse_check_quantity(string $form, int $quantity, string $category, array $extra = []): void
{
$max = warehouse_max_quantity($category);
if ($quantity > $max) {
warehouse_fail($form, 'Bitte eine Anzahl zwischen 1 und ' . number_format($max, 0, ',', '.') . ' angeben.', $extra);
}
}
/** Discord-Log fuer eine Ein- bzw. Auslagerung. */
function warehouse_log(string $direction, array $item, array $data): void
{
$isCurrency = $item['category'] === 'currency';
admin_log($direction === 'in'
? ($isCurrency ? '📦 Lagerhaus: Kina eingezahlt' : '📦 Lagerhaus: eingelagert')
: ($isCurrency ? '📦 Lagerhaus: Kina ausgezahlt' : '📦 Lagerhaus: entnommen'), [
'Gegenstand' => number_format($data['quantity'], 0, ',', '.') . ($isCurrency ? ' ' : '× ') . $item['name'],
$direction === 'in' ? 'Von' : 'An' => $data['user_id'] !== null ? admin_log_user((int) $data['user_id']) : (string) $data['name'],
'Bemerkung' => (string) $data['note'],
], $direction === 'in' ? 'success' : 'warning');
}
function warehouse_insert_movement(int $itemId, string $direction, array $data, int $userId): void
{
db()->prepare(
'INSERT INTO warehouse_movements (item_id, direction, quantity, occurred_at, counterpart_user_id, counterpart_name, note, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
)->execute([$itemId, $direction, $data['quantity'], $data['occurred_at'], $data['user_id'], $data['name'], $data['note'], $userId]);
}
switch ($action) {
// ---- Einlagern ----
case 'deposit':
$itemName = trim((string) ($_POST['item'] ?? ''));
if ($itemName === '') {
warehouse_fail('in', 'Bitte einen Gegenstand angeben.');
}
$data = warehouse_read_common('in', true);
$item = warehouse_find_item($itemName);
if (!$item) {
// Unbekannt: erst nachfragen, dann anlegen - sonst entstuende aus jedem Tippfehler
// ein neuer Gegenstand.
if (empty($_POST['create_item'])) {
warehouse_fail('in', '„' . $itemName . '“ steht nicht in der Gegenstandsliste. Tippfehler? Sonst unten bestätigen, dass er neu angelegt werden soll.', ['unknown_item' => true]);
}
if (mb_strlen($itemName) > 150) {
warehouse_fail('in', 'Der Name des Gegenstands darf höchstens 150 Zeichen lang sein.', ['unknown_item' => true]);
}
$category = (string) ($_POST['create_category'] ?? 'other');
if (!in_array($category, WAREHOUSE_CUSTOM_CATEGORIES, true)) {
$category = 'other';
}
$pdo->prepare("INSERT INTO warehouse_items (name, category, source, created_by) VALUES (?, ?, 'custom', ?)")
->execute([$itemName, $category, $userId]);
$item = ['id' => (int) $pdo->lastInsertId(), 'name' => $itemName, 'category' => $category];
}
warehouse_check_quantity('in', $data['quantity'], (string) $item['category']);
warehouse_insert_movement((int) $item['id'], 'in', $data, $userId);
warehouse_log('in', $item, $data);
set_flash('success', number_format($data['quantity'], 0, ',', '.') . ($item['category'] === 'currency' ? ' ' . $item['name'] . ' eingezahlt.' : '× ' . $item['name'] . ' eingelagert.'));
redirect('/warehouse.php');
// ---- Entnehmen ----
case 'withdraw':
$itemId = (int) ($_POST['item_id'] ?? 0);
$data = warehouse_read_common('out', false);
$pdo->beginTransaction();
// Zeile des Gegenstands sperren: zwei gleichzeitige Entnahmen koennten sonst beide den
// alten Bestand sehen und zusammen mehr entnehmen, als da ist.
$stmt = $pdo->prepare('SELECT id, name, category FROM warehouse_items WHERE id = ? FOR UPDATE');
$stmt->execute([$itemId]);
$item = $stmt->fetch();
if (!$item) {
$pdo->rollBack();
warehouse_fail('out', 'Bitte einen Gegenstand aus dem Bestand wählen.');
}
if ($data['quantity'] > warehouse_max_quantity((string) $item['category'])) {
$pdo->rollBack();
warehouse_check_quantity('out', $data['quantity'], (string) $item['category']);
}
$available = warehouse_item_stock($itemId);
if ($data['quantity'] > $available) {
$pdo->rollBack();
warehouse_fail('out', 'Von „' . $item['name'] . '“ sind nur ' . number_format($available, 0, ',', '.') . ' auf Lager.');
}
warehouse_insert_movement($itemId, 'out', $data, $userId);
$pdo->commit();
warehouse_log('out', $item, $data);
set_flash('success', number_format($data['quantity'], 0, ',', '.') . ($item['category'] === 'currency' ? ' ' . $item['name'] . ' ausgezahlt.' : '× ' . $item['name'] . ' entnommen.'));
redirect('/warehouse.php');
// ---- Eintrag loeschen (Fehleingabe) ----
case 'delete':
$movementId = (int) ($_POST['movement_id'] ?? 0);
$pdo->beginTransaction();
$stmt = $pdo->prepare(
'SELECT m.id, m.item_id, m.direction, m.quantity, i.name
FROM warehouse_movements m JOIN warehouse_items i ON i.id = m.item_id
WHERE m.id = ? FOR UPDATE'
);
$stmt->execute([$movementId]);
$movement = $stmt->fetch();
if (!$movement) {
$pdo->rollBack();
set_flash('error', 'Diesen Eintrag gibt es nicht mehr.');
redirect('/warehouse.php');
}
// Eine Einlagerung laesst sich nur loeschen, wenn danach nicht mehr entnommen als
// eingelagert waere.
if ($movement['direction'] === 'in' && warehouse_item_stock((int) $movement['item_id']) < (int) $movement['quantity']) {
$pdo->rollBack();
set_flash('error', 'Diese Einlagerung wurde schon (teilweise) wieder entnommen - bitte zuerst die passende Entnahme löschen.');
redirect('/warehouse.php');
}
$pdo->prepare('DELETE FROM warehouse_movements WHERE id = ?')->execute([$movementId]);
$pdo->commit();
admin_log('🗑️ Lagerhaus-Eintrag gelöscht', [
'Eintrag' => ($movement['direction'] === 'in' ? 'Einlagerung' : 'Entnahme') . ': ' . $movement['quantity'] . '× ' . $movement['name'],
], 'danger');
set_flash('success', 'Eintrag gelöscht (' . $movement['quantity'] . '× ' . $movement['name'] . ').');
redirect('/warehouse.php');
default:
redirect('/warehouse.php');
}