Members may now request more than is in stock (or items that are sold out); only their points have to cover the full request. When approving, the manager can approve fewer than requested. The quantity field is prefilled with what is in stock, the cost updates as you type, and only the approved part is charged and taken from stock. The order keeps the requested quantity, so the member sees e.g. "3 von 10 bewilligt". The order list also shows the current stock and flags when it isn't enough. The column upgrade check now covers every table that has upgrades, instead of only users and roles. Tables that are about to be created fresh are skipped. The dashboard gets a card with your Lumipunkte and your rank. In the sidebar, the points move from under your name into a gold box above the profile. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
240 lines
11 KiB
PHP
240 lines
11 KiB
PHP
<?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');
|
||
}
|
||
|
||
// Mehr als verfuegbar darf beantragt werden - wie viel es wirklich gibt, entscheidet die
|
||
// Bewilligung (auch teilweise).
|
||
$pdo->beginTransaction();
|
||
$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, requested_quantity, unit_price, total_price, note)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
|
||
)->execute([$userId, $itemId, $item['name'], $quantity, $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 (auf Wunsch nur einen Teil): Punkte abziehen, Bestand verringern / aus dem Lagerhaus entnehmen ----
|
||
case 'approve':
|
||
$pdo->beginTransaction();
|
||
$order = shop_lock_order($orderId, 'pending', $url);
|
||
$buyerId = (int) $order['user_id'];
|
||
$requested = (int) $order['quantity'];
|
||
$quantity = filter_var($_POST['approve_quantity'] ?? $requested, FILTER_VALIDATE_INT);
|
||
if ($quantity === false || $quantity < 1 || $quantity > $requested) {
|
||
shop_fail('Bitte zwischen 1 und ' . $requested . ' Stück bewilligen.', $url);
|
||
}
|
||
$total = (int) $order['unit_price'] * $quantity;
|
||
$order['quantity'] = $quantity; // fuer die Beschriftung der Buchung
|
||
|
||
$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 - bitte eine kleinere Anzahl bewilligen.', $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'] . '“ - bitte eine kleinere Anzahl bewilligen.', $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', quantity = ?, total_price = ?, decided_by = ?, decided_at = NOW(),
|
||
award_id = ?, warehouse_movement_id = ?, stock_taken = ? WHERE id = ?"
|
||
)->execute([$quantity, $total, $userId, $awardId, $movementId, $stockTaken, $orderId]);
|
||
$pdo->commit();
|
||
|
||
set_flash('success', 'Bewilligt: ' . shop_order_label($order) . ($quantity < $requested ? ' (von ' . $requested . ' beantragt)' : '')
|
||
. ' 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');
|
||
}
|