LuminaWebsite/shop_action.php
Maaxxs ebc9e2367e Lumishop: trade Lumipunkte for items, with approval
Members request items from the shop. Their points and the stock are
earmarked but not taken until someone with shop.manage approves. Approving
books a negative "Lumishop" entry in the Lumipunkte history and takes the
stock. For warehouse-backed items it also books a withdrawal to the member
in the warehouse. Approved orders are then marked as handed over in the
game, or can be reversed, which restores points, stock and the warehouse
withdrawal.

The management page handles categories and items (price, description,
stock). Stock is either the shop's own count, unlimited, or live from a
linked warehouse item. Items in stock can be imported from the warehouse,
and an item's own stock can be moved into the warehouse to link it there.
Warehouse cards show when an item is sold in the shop.

Shop bookings can't be deleted from the Lumipunkte page, only reversed in
the shop, so orders and points stay in sync. The new permissions go to the
Administrator group only, so the shop stays hidden until it is assigned.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 10:49:05 +02:00

239 lines
11 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/shop.php';
require_permission('shop.view');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect('/shop.php');
}
verify_csrf();
$action = (string) ($_POST['action'] ?? '');
$userId = (int) current_user()['id'];
$pdo = db();
/** Ruecksprung der Verwaltung: nur Seiten des Shops, keine fremden Adressen. */
function shop_return_url(): string
{
$return = (string) ($_POST['return'] ?? '');
return preg_match('#^/shop(_orders)?\.php(\?[\w=&%-]*)?(\#[\w-]+)?$#', $return) ? $return : '/shop_orders.php';
}
function shop_fail(string $message, string $url): void
{
if (db()->inTransaction()) {
db()->rollBack();
}
set_flash('error', $message);
redirect($url);
}
/** Laedt eine Bestellung gesperrt (fuer Statuswechsel) oder bricht ab. */
function shop_lock_order(int $orderId, string $expectedStatus, string $url): array
{
$stmt = db()->prepare('SELECT * FROM shop_orders WHERE id = ? FOR UPDATE');
$stmt->execute([$orderId]);
$order = $stmt->fetch();
if (!$order) {
shop_fail('Diesen Antrag gibt es nicht mehr.', $url);
}
if ($order['status'] !== $expectedStatus) {
shop_fail('Der Antrag #' . $orderId . ' ist inzwischen „' . shop_status_label((string) $order['status']) . '“ - bitte die Seite neu laden.', $url);
}
return $order;
}
function shop_read_reason(): ?string
{
$reason = trim((string) ($_POST['reason'] ?? ''));
return $reason !== '' ? mb_substr($reason, 0, 255) : null;
}
$orderId = (int) ($_POST['order_id'] ?? 0);
switch ($action) {
// ---- Mitglied: beantragen ----
case 'order':
$itemId = (int) ($_POST['item_id'] ?? 0);
$quantity = filter_var($_POST['quantity'] ?? '', FILTER_VALIDATE_INT);
$note = trim((string) ($_POST['note'] ?? ''));
$item = $itemId > 0 ? shop_item($itemId) : null;
$_SESSION['shop_form'] = [
'item_id' => (string) $itemId,
'item_name' => (string) ($item['name'] ?? ''),
'quantity' => (string) ($_POST['quantity'] ?? ''),
'note' => $note,
];
if (!$item || !(int) $item['active']) {
unset($_SESSION['shop_form']);
shop_fail('Diesen Gegenstand gibt es im Lumishop nicht mehr.', '/shop.php');
}
if ($quantity === false || $quantity < 1 || $quantity > SHOP_MAX_ORDER_QUANTITY) {
shop_fail('Bitte eine Anzahl zwischen 1 und ' . SHOP_MAX_ORDER_QUANTITY . ' angeben.', '/shop.php');
}
if (mb_strlen($note) > 255) {
shop_fail('Die Bemerkung darf höchstens 255 Zeichen lang sein.', '/shop.php');
}
$pdo->beginTransaction();
// Gegenstand sperren, damit zwei gleichzeitige Antraege nicht beide das letzte Stueck bekommen.
$pdo->prepare('SELECT id FROM shop_items WHERE id = ? FOR UPDATE')->execute([$itemId]);
$available = shop_available($item);
if ($available !== null && $quantity > $available) {
shop_fail($available > 0
? 'Von „' . $item['name'] . '“ sind nur noch ' . $available . ' verfügbar.'
: '„' . $item['name'] . '“ ist leider ausverkauft.', '/shop.php');
}
$total = (int) $item['price'] * $quantity;
$spendable = contribution_user_balance($userId) - shop_reserved_points($userId);
if ($total > $spendable) {
shop_fail('Dafür reichen deine Lumipunkte nicht: ' . contribution_format($total) . ' benötigt, '
. contribution_format(max(0, $spendable)) . ' verfügbar (offene Anträge sind schon abgezogen).', '/shop.php');
}
$pdo->prepare(
'INSERT INTO shop_orders (user_id, item_id, item_name, quantity, unit_price, total_price, note) VALUES (?, ?, ?, ?, ?, ?, ?)'
)->execute([$userId, $itemId, $item['name'], $quantity, (int) $item['price'], $total, $note !== '' ? $note : null]);
$pdo->commit();
unset($_SESSION['shop_form']);
set_flash('success', 'Antrag gestellt: ' . shop_order_label(['quantity' => $quantity, 'item_name' => $item['name']])
. ' für ' . contribution_format($total) . ' Lumipunkte. Den Stand siehst du unter „Meine Anträge“.');
redirect('/shop.php#antraege');
// ---- Mitglied: eigenen offenen Antrag zurueckziehen ----
case 'cancel':
$pdo->beginTransaction();
$order = shop_lock_order($orderId, 'pending', '/shop.php#antraege');
if ((int) $order['user_id'] !== $userId) {
shop_fail('Das ist nicht dein Antrag.', '/shop.php#antraege');
}
$pdo->prepare("UPDATE shop_orders SET status = 'cancelled' WHERE id = ?")->execute([$orderId]);
$pdo->commit();
set_flash('success', 'Antrag zurückgezogen.');
redirect('/shop.php#antraege');
}
// Ab hier nur die Verwaltung.
if (!user_has_permission('shop.manage')) {
http_response_code(403);
include __DIR__ . '/includes/forbidden.php';
exit;
}
$url = shop_return_url();
switch ($action) {
// ---- Bewilligen: Punkte abziehen, Bestand verringern / aus dem Lagerhaus entnehmen ----
case 'approve':
$pdo->beginTransaction();
$order = shop_lock_order($orderId, 'pending', $url);
$buyerId = (int) $order['user_id'];
$quantity = (int) $order['quantity'];
$total = (int) $order['total_price'];
$buyerStmt = $pdo->prepare("SELECT COALESCE(NULLIF(display_name, ''), username) FROM users WHERE id = ?");
$buyerStmt->execute([$buyerId]);
$buyerName = (string) $buyerStmt->fetchColumn();
$balance = contribution_user_balance($buyerId);
if ($balance < $total) {
shop_fail($buyerName . ' hat nur noch ' . contribution_format($balance) . ' Lumipunkte - für diesen Antrag werden '
. contribution_format($total) . ' gebraucht.', $url);
}
$item = null;
if ($order['item_id'] !== null) {
$stmt = $pdo->prepare('SELECT * FROM shop_items WHERE id = ? FOR UPDATE');
$stmt->execute([(int) $order['item_id']]);
$item = $stmt->fetch() ?: null;
}
$stockTaken = 0;
$movementId = null;
if ($item && $item['stock_mode'] === 'manual') {
if ((int) $item['stock'] < $quantity) {
shop_fail('Von „' . $item['name'] . '“ sind nur noch ' . (int) $item['stock'] . ' im Shop-Bestand.', $url);
}
$pdo->prepare('UPDATE shop_items SET stock = stock - ? WHERE id = ?')->execute([$quantity, (int) $item['id']]);
$stockTaken = 1;
} elseif ($item && $item['stock_mode'] === 'warehouse') {
$warehouseId = (int) $item['warehouse_item_id'];
if ($warehouseId === 0) {
shop_fail('„' . $item['name'] . '“ ist mit keinem Lagerhaus-Gegenstand verknüpft - bitte in der Shop-Verwaltung nachtragen.', $url);
}
$pdo->prepare('SELECT id FROM warehouse_items WHERE id = ? FOR UPDATE')->execute([$warehouseId]);
$inStock = warehouse_item_stock($warehouseId);
if ($inStock < $quantity) {
shop_fail('Im Lagerhaus sind nur noch ' . $inStock . '× „' . $item['name'] . '“.', $url);
}
$pdo->prepare(
"INSERT INTO warehouse_movements (item_id, direction, quantity, occurred_at, counterpart_user_id, note, created_by)
VALUES (?, 'out', ?, ?, ?, ?, ?)"
)->execute([$warehouseId, $quantity, shop_now(), $buyerId, 'Lumishop-Antrag #' . $orderId, $userId]);
$movementId = (int) $pdo->lastInsertId();
}
$pdo->prepare(
"INSERT INTO contribution_awards (category, title, note, awarded_at, created_by) VALUES ('shop', ?, ?, ?, ?)"
)->execute([mb_substr('Lumishop: ' . shop_order_label($order), 0, 150), 'Antrag #' . $orderId, shop_now(), $userId]);
$awardId = (int) $pdo->lastInsertId();
if ($total > 0) {
$pdo->prepare('INSERT INTO contribution_entries (award_id, user_id, points) VALUES (?, ?, ?)')
->execute([$awardId, $buyerId, -$total]);
}
$pdo->prepare(
"UPDATE shop_orders SET status = 'approved', decided_by = ?, decided_at = NOW(), award_id = ?,
warehouse_movement_id = ?, stock_taken = ? WHERE id = ?"
)->execute([$userId, $awardId, $movementId, $stockTaken, $orderId]);
$pdo->commit();
set_flash('success', 'Bewilligt: ' . shop_order_label($order) . ' für ' . $buyerName . '. '
. contribution_format($total) . ' Lumipunkte abgezogen' . ($movementId ? ', Entnahme im Lagerhaus gebucht' : '') . '.');
redirect($url);
// ---- Ablehnen ----
case 'reject':
$pdo->beginTransaction();
shop_lock_order($orderId, 'pending', $url);
$pdo->prepare("UPDATE shop_orders SET status = 'rejected', decided_by = ?, decided_at = NOW(), decision_note = ? WHERE id = ?")
->execute([$userId, shop_read_reason(), $orderId]);
$pdo->commit();
set_flash('success', 'Antrag #' . $orderId . ' abgelehnt.');
redirect($url);
// ---- Im Spiel uebergeben ----
case 'deliver':
$pdo->beginTransaction();
$order = shop_lock_order($orderId, 'approved', $url);
$pdo->prepare("UPDATE shop_orders SET status = 'delivered', delivered_by = ?, delivered_at = NOW() WHERE id = ?")
->execute([$userId, $orderId]);
$pdo->commit();
set_flash('success', shop_order_label($order) . ' als übergeben markiert.');
redirect($url);
// ---- Bewilligten Antrag stornieren: alles zurueck ----
case 'revoke':
$pdo->beginTransaction();
$order = shop_lock_order($orderId, 'approved', $url);
if ($order['award_id'] !== null) {
$pdo->prepare('DELETE FROM contribution_awards WHERE id = ?')->execute([(int) $order['award_id']]);
}
if ($order['warehouse_movement_id'] !== null) {
$pdo->prepare('DELETE FROM warehouse_movements WHERE id = ?')->execute([(int) $order['warehouse_movement_id']]);
}
if ((int) $order['stock_taken'] === 1 && $order['item_id'] !== null) {
$pdo->prepare('UPDATE shop_items SET stock = stock + ? WHERE id = ?')->execute([(int) $order['quantity'], (int) $order['item_id']]);
}
$pdo->prepare(
"UPDATE shop_orders SET status = 'cancelled', decided_by = ?, decided_at = NOW(), decision_note = ?,
award_id = NULL, warehouse_movement_id = NULL, stock_taken = 0 WHERE id = ?"
)->execute([$userId, shop_read_reason(), $orderId]);
$pdo->commit();
set_flash('success', 'Antrag #' . $orderId . ' storniert - ' . contribution_format((int) $order['total_price']) . ' Lumipunkte zurückgebucht.');
redirect($url);
default:
redirect('/shop.php');
}