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>
This commit is contained in:
Maaxxs 2026-09-21 10:49:05 +02:00
parent 5f25e20900
commit ebc9e2367e
19 changed files with 1985 additions and 5 deletions

View file

@ -28,6 +28,9 @@ und wird später ausgebaut. Fokus dieser Version ist der Mitglieder-/Admin-Berei
direkt auf die Karte gezeichnet werden direkt auf die Karte gezeichnet werden
- Lumipunkte: Punkte für Raids, Events und andere Aktivitäten an einzelne oder viele - Lumipunkte: Punkte für Raids, Events und andere Aktivitäten an einzelne oder viele
Mitglieder vergeben, mit Rangliste und Verlauf Mitglieder vergeben, mit Rangliste und Verlauf
- Lumishop: Mitglieder beantragen Gegenstände gegen Lumipunkte, die Leitung bewilligt oder
lehnt ab, bewilligte Anträge ziehen die Punkte ab und werden im Spiel übergeben. Bestand
wahlweise eigen, unbegrenzt oder direkt aus dem Lagerhaus
- Lagerhaus: Bestand der Legion mit Einlagerungen (wer hat was wann überreicht) und Entnahmen - Lagerhaus: Bestand der Legion mit Einlagerungen (wer hat was wann überreicht) und Entnahmen
(wann, optional an wen), Gegenstandsliste aus dem Aion-2-Wiki mit rund 2.300 Einträgen (wann, optional an wen), Gegenstandsliste aus dem Aion-2-Wiki mit rund 2.300 Einträgen
- Anwesenheitsliste pro Raid (anwesend, abwesend, entschuldigt), automatische Lumipunkte - Anwesenheitsliste pro Raid (anwesend, abwesend, entschuldigt), automatische Lumipunkte
@ -497,6 +500,57 @@ Rangliste) und `contributions.manage`
„Administrator“. Anderen Gruppen muss man sie unter Berechtigungsgruppen zuweisen, den „Administrator“. Anderen Gruppen muss man sie unter Berechtigungsgruppen zuweisen, den
Mitgliedern z.B. nur `contributions.view`. Mitgliedern z.B. nur `contributions.view`.
### Lumishop
Im **Lumishop** (`shop.php`) tauschen Mitglieder Lumipunkte gegen Gegenstände.
- **Angebot** als Kacheln mit Bild, Kategorie, Beschreibung, Preis und verfügbarer Menge, dazu
Suche und Kategoriefilter. Oben steht, wie viele Punkte man ausgeben kann: der Punktestand
abzüglich der Punkte in eigenen offenen Anträgen.
- **Beantragen:** Anzahl und optional eine Bemerkung (z.B. der Charaktername). Die Website
prüft, ob Punkte und Bestand reichen, wobei offene Anträge schon abgezogen sind. Abgezogen
wird aber noch nichts, und offene Anträge lassen sich unter **Meine Anträge** zurückziehen.
- **Anträge** (`shop_orders.php`, mit `shop.manage`), aufgeteilt in Offen, Zur Übergabe und
Erledigt. Bei offenen Anträgen steht der Punktestand des Mitglieds dabei.
- **Bewilligen** zieht die Lumipunkte ab. Das ist eine Buchung „Lumishop: …“ im
Lumipunkte-Verlauf. Gleichzeitig verringert es den Bestand bzw. bucht im Lagerhaus eine
Entnahme an das Mitglied.
- **Ablehnen** geht mit einem optionalen Grund, den das Mitglied sieht.
- Nach der Übergabe im Spiel wird der Antrag als **übergeben** markiert.
- Ein bewilligter, noch nicht übergebener Antrag lässt sich **stornieren**. Dann gehen
Punkte, Bestand und Lagerhaus-Entnahme zurück.
Die Menüzahl am Lumishop zeigt die offenen Anträge.
- **Shop verwalten** (`shop_manage.php`, mit `shop.manage`): Kategorien mit Reihenfolge
anlegen, umbenennen und löschen. Gegenstände anlegen und bearbeiten: Name, Kategorie,
Beschreibung, Preis, Bestand und „im Shop anbieten“. Gegenstände lassen sich aus dem Angebot
nehmen oder löschen. Solange es offene oder nicht übergebene Anträge gibt, geht nur Ersteres.
**Bestand und Lagerhaus:** Jeder Gegenstand hat eine der Bestandsarten eigener Bestand im
Shop, unbegrenzt oder **aus dem Lagerhaus**. Bei der letzten ist der Shop-Bestand der
Lagerbestand des verknüpften Lagerhaus-Gegenstands. Bewilligte Anträge erscheinen dort als
Entnahme „Lumishop-Antrag #…“ an das Mitglied, und die Lagerhaus-Kachel zeigt „Lumishop“ mit
dem Preis. Zum Abgleich gibt es zwei Wege:
- **Aus dem Lagerhaus übernehmen:** Alles, was auf Lager und noch nicht im Shop ist (ohne
Kina), lässt sich auswählen, mit Preis und Kategorie, und kommt verknüpft in den Shop.
- **Ins Lagerhaus übertragen** (Kisten-Symbol bei Gegenständen mit eigenem Bestand): Der
Shop-Bestand wird im Lagerhaus eingelagert, von „Lumishop“. Danach führt der Gegenstand
seinen Bestand aus dem Lagerhaus. Gibt es ihn dort noch nicht, wird er angelegt.
Das Bild eines Shop-Gegenstands kommt vom verknüpften Lagerhaus-Gegenstand. Trägt man keinen
ein, verknüpft der Shop einen gleichnamigen Gegenstand aus der Lagerhaus-Liste, falls es einen
gibt, sonst erscheint ein Platzhalter.
Buchungen aus dem Lumishop lassen sich nicht auf der Lumipunkte-Seite löschen, nur über das
Stornieren im Shop. Sonst stimmten Antrag und Punkte nicht mehr überein. Da die Rangliste den
aktuellen Punktestand zeigt, rutscht man nach einem Einkauf entsprechend nach unten.
Rechte: `shop.view` (ansehen und beantragen) und `shop.manage` (alles verwalten, Anträge
bearbeiten). Die Website legt beide selbst an und gibt sie nur der Gruppe „Administrator“. So
bleibt der Shop für alle anderen verborgen, bis man ihn einrichtet und `shop.view` unter
Berechtigungsgruppen z.B. den Mitgliedern zuweist. Die Tabellen `shop_categories`, `shop_items` und `shop_orders`
entstehen automatisch.
### Lagerhaus ### Lagerhaus
Die Seite **Lagerhaus** (`warehouse.php`) führt Buch über die Gegenstände der Legion. Die Seite **Lagerhaus** (`warehouse.php`) führt Buch über die Gegenstände der Legion.

View file

@ -2653,3 +2653,198 @@ a.button-small:hover { text-decoration: none; }
.warehouse-kina strong { font-size: 1.35rem; color: var(--gold); font-variant-numeric: tabular-nums; } .warehouse-kina strong { font-size: 1.35rem; color: var(--gold); font-variant-numeric: tabular-nums; }
.warehouse-kina .warehouse-icon { background: none; } .warehouse-kina .warehouse-icon { background: none; }
.warehouse-kina-actions { display: flex; flex-direction: column; gap: 0.3rem; margin-left: 0.5rem; } .warehouse-kina-actions { display: flex; flex-direction: column; gap: 0.3rem; margin-left: 0.5rem; }
/* --- Lumishop --- */
.app-content.bg-shop {
background-image: linear-gradient(rgba(20, 20, 20, 0.7), rgba(20, 20, 20, 0.86)), url('/assets/images/Landscapes/web/landscape7-bg.jpg');
}
.shop-reserved { font-size: 0.75rem; margin-top: 0.1rem; }
.shop-hero-actions { display: flex; flex-direction: column; gap: 0.4rem; }
.shop-count {
display: inline-block;
min-width: 1.2rem;
margin-left: 0.2rem;
padding: 0 0.35rem;
border-radius: 999px;
background: #1a1a1a;
color: var(--gold);
font-size: 0.75rem;
font-weight: 700;
line-height: 1.2rem;
text-align: center;
}
.button-secondary .shop-count { background: var(--gold); color: #1a1a1a; }
.shop-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
gap: 0.85rem;
}
.shop-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.35rem;
padding: 1rem 0.75rem 0.85rem;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(35, 35, 35, 0.72);
text-align: center;
transition: border-color 0.15s, transform 0.15s;
}
.shop-card:hover { border-color: var(--gold); transform: translateY(-2px); }
.shop-card[hidden] { display: none; }
.shop-card.sold-out { opacity: 0.55; }
.shop-card.sold-out:hover { transform: none; border-color: var(--border); }
.shop-card-image { display: inline-block; }
.shop-card-name { margin-top: 0.3rem; font-weight: 600; font-size: 0.92rem; line-height: 1.25; overflow-wrap: anywhere; }
.shop-card-description { font-size: 0.8rem; color: var(--text-muted); line-height: 1.35; overflow-wrap: anywhere; }
.shop-card-price {
display: inline-flex;
align-items: center;
gap: 0.3rem;
margin-top: auto;
padding-top: 0.35rem;
font-size: 1.15rem;
font-weight: 700;
color: var(--gold);
}
.shop-card-stock { font-size: 0.75rem; color: var(--text-muted); }
.shop-card-stock.is-empty { color: var(--danger); }
.shop-card .shop-buy { width: 100%; margin-top: 0.25rem; }
.shop-buy-title { margin: 0; font-size: 1.05rem; }
.shop-buy-total {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.6rem 0;
font-size: 1.3rem;
font-weight: 700;
color: var(--gold);
}
.shop-buy-hint { margin: 0; font-size: 0.85rem; }
/* Antraege */
.shop-orders { display: flex; flex-direction: column; gap: 0.6rem; }
.shop-order {
display: flex;
align-items: center;
gap: 0.9rem;
padding: 0.75rem 0.9rem;
border: 1px solid var(--border);
border-left: 3px solid var(--border);
border-radius: 8px;
background: rgba(35, 35, 35, 0.72);
}
.shop-order-pending { border-left-color: var(--gold); }
.shop-order-approved { border-left-color: #5fa8ff; }
.shop-order-delivered { border-left-color: var(--success); }
.shop-order-rejected { border-left-color: var(--danger); }
.shop-order-rejected, .shop-order-cancelled { opacity: 0.75; }
.shop-order-icon { flex-shrink: 0; }
.shop-order-body { flex: 1; min-width: 0; }
.shop-order-title { display: flex; align-items: center; flex-wrap: wrap; gap: 0.4rem 0.6rem; }
.shop-order-meta { margin-top: 0.2rem; font-size: 0.8rem; }
.shop-order-buyer { color: var(--text); }
.shop-order-note { margin-top: 0.25rem; font-size: 0.88rem; overflow-wrap: anywhere; }
.shop-order-price {
display: inline-flex;
align-items: center;
gap: 0.3rem;
flex-shrink: 0;
font-size: 1.05rem;
font-weight: 700;
color: var(--text-muted);
white-space: nowrap;
}
.shop-order-price.is-paid { color: var(--gold); }
.shop-order-actions { display: flex; align-items: center; gap: 0.4rem; flex-shrink: 0; }
.shop-order-actions form { display: inline; }
.shop-order-actions .button-small { display: inline-flex; align-items: center; gap: 0.3rem; }
.shop-order-actions .button-small .icon { width: 15px; height: 15px; }
.shop-order-balance { margin: 0.4rem 0 -0.3rem 0.2rem; font-size: 0.8rem; color: var(--text-muted); }
.shop-order-balance.is-short { color: var(--danger); }
.shop-badge-approved { border-color: #5fa8ff; color: #8cc0ff; }
.shop-badge-warehouse { border-color: var(--gold); color: var(--gold); }
@media (max-width: 700px) {
.shop-order { flex-wrap: wrap; }
.shop-order-body { flex-basis: calc(100% - 60px); }
.shop-order-price { margin-left: 56px; }
.shop-order-actions { margin-left: auto; }
}
/* Verwaltung */
.shop-manage-table tr.is-inactive td:not(:last-child) { opacity: 0.55; }
.shop-categories { display: flex; flex-direction: column; gap: 0.5rem; max-width: 640px; }
.shop-category-row { display: flex; align-items: center; gap: 0.5rem; }
.shop-category-form { flex-direction: row; align-items: center; gap: 0.5rem; flex: 1; }
.shop-category-form input[type="text"] { flex: 1; min-width: 0; }
.shop-category-new { margin-top: 0.4rem; padding-top: 0.75rem; border-top: 1px dashed var(--border); }
input.shop-sort-input { width: 80px; text-align: center; }
.checkbox-label { display: flex; align-items: center; gap: 0.5rem; font-weight: 400; }
.checkbox-label input { width: auto; }
[data-mode-field][hidden] { display: none; }
.modal.modal-wide { max-width: 720px; }
.shop-import-price { display: flex; gap: 0.5rem; }
.shop-import-price input { flex: 1; min-width: 0; }
.shop-import-list {
display: flex;
flex-direction: column;
max-height: 45vh;
overflow-y: auto;
border: 1px solid var(--border);
border-radius: 8px;
}
.shop-import-row {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.45rem 0.7rem;
border-bottom: 1px solid var(--border);
}
.shop-import-row:last-child { border-bottom: none; }
.shop-import-row label {
display: flex;
align-items: center;
gap: 0.55rem;
flex: 1;
min-width: 0;
font-weight: 400;
cursor: pointer;
}
.shop-import-row label input { width: auto; }
.shop-import-row label span:not(.text-muted) { overflow-wrap: anywhere; }
.shop-import-row label .text-muted { margin-left: auto; font-size: 0.8rem; white-space: nowrap; }
input.shop-import-row-price { width: 100px; }
.shop-import-all { font-weight: 400; cursor: pointer; background: var(--bg-panel-alt); position: sticky; top: 0; z-index: 1; }
.shop-import-all input { width: auto; }
.contribution-badge-shop { border-color: var(--gold); color: var(--gold); }
.warehouse-card-shop {
display: inline-flex;
align-items: center;
gap: 0.2rem;
font-size: 0.72rem;
color: var(--gold);
}
#shop-item-description { font-family: inherit; }

178
assets/js/shop.js Normal file
View file

@ -0,0 +1,178 @@
(function () {
'use strict';
function formatPoints(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}
// ---- Dialoge ----
function closeModal(modal) { modal.hidden = true; }
document.querySelectorAll('.modal-overlay').forEach(function (modal) {
var close = modal.querySelector('.modal-close');
if (close) close.addEventListener('click', function () { closeModal(modal); });
modal.addEventListener('click', function (event) {
if (event.target === modal) closeModal(modal);
});
});
document.addEventListener('keydown', function (event) {
if (event.key !== 'Escape') return;
document.querySelectorAll('.modal-overlay:not([hidden])').forEach(closeModal);
});
// ---- Shop: Beantragen ----
var buyModal = document.getElementById('shop-buy-modal');
if (buyModal) {
var buyItem = document.getElementById('shop-buy-item');
var buyName = document.getElementById('shop-buy-name');
var buyQuantity = document.getElementById('shop-buy-quantity');
var buyTotal = document.getElementById('shop-buy-total');
var price = 0;
var updateTotal = function () {
var qty = parseInt(buyQuantity.value, 10) || 0;
buyTotal.textContent = formatPoints(Math.max(0, qty) * price);
};
var openBuy = function (button, keepValues) {
buyItem.value = button.dataset.itemId;
buyName.textContent = button.dataset.itemName;
price = parseInt(button.dataset.price, 10) || 0;
buyQuantity.max = button.dataset.max;
if (!keepValues) {
buyQuantity.value = 1;
document.getElementById('shop-buy-note').value = '';
}
updateTotal();
buyModal.hidden = false;
buyQuantity.focus();
buyQuantity.select();
};
document.querySelectorAll('.shop-buy').forEach(function (button) {
button.addEventListener('click', function () { openBuy(button, false); });
});
buyQuantity.addEventListener('input', updateTotal);
// Nach einem Fehler ist der Dialog schon offen - Preis und Hoechstmenge nachladen.
if (!buyModal.hidden) {
var current = document.querySelector('.shop-buy[data-item-id="' + buyItem.value + '"]');
if (current) openBuy(current, true); else buyModal.hidden = true;
}
}
// ---- Shop: Suche und Kategorie ----
var search = document.getElementById('shop-search');
var grid = document.getElementById('shop-items');
if (search && grid) {
var category = document.getElementById('shop-category');
var noMatch = document.getElementById('shop-no-match');
var filter = function () {
var term = search.value.trim().toLowerCase();
var cat = category ? category.value : '';
var visible = 0;
grid.querySelectorAll('.shop-card').forEach(function (card) {
var show = (term === '' || card.dataset.name.indexOf(term) !== -1)
&& (cat === '' || card.dataset.category === cat);
card.hidden = !show;
if (show) visible++;
});
if (noMatch) noMatch.hidden = visible > 0;
};
search.addEventListener('input', filter);
if (category) category.addEventListener('change', filter);
}
// ---- Antraege: Grund abfragen (Ablehnen / Stornieren) ----
document.querySelectorAll('form[data-prompt]').forEach(function (form) {
form.addEventListener('submit', function (event) {
var reason = window.prompt(form.dataset.prompt, '');
if (reason === null) {
event.preventDefault();
return;
}
form.querySelector('input[name="reason"]').value = reason;
});
});
// ---- Verwaltung: Gegenstand anlegen / bearbeiten ----
var itemModal = document.getElementById('shop-item-modal');
if (itemModal) {
var form = document.getElementById('shop-item-form');
var title = document.getElementById('shop-item-title');
var mode = form.elements.stock_mode;
var applyMode = function () {
itemModal.querySelectorAll('[data-mode-field]').forEach(function (field) {
field.hidden = field.dataset.modeField !== mode.value;
});
var hint = itemModal.querySelector('[data-mode-hint]');
if (hint) hint.textContent = mode.value === 'warehouse' ? '(Pflicht - daraus kommt der Bestand)' : '(optional, für das Bild)';
form.elements.warehouse_item.required = mode.value === 'warehouse';
};
mode.addEventListener('change', applyMode);
var fill = function (data) {
data = data || {};
form.elements.item_id.value = data.id || '';
form.elements.name.value = data.name || '';
form.elements.category_id.value = data.category_id || '';
form.elements.description.value = data.description || '';
form.elements.price.value = data.price !== undefined ? data.price : '';
mode.value = data.stock_mode || 'manual';
form.elements.stock.value = data.stock !== undefined ? data.stock : 0;
form.elements.warehouse_item.value = data.warehouse_item || '';
form.elements.active.checked = data.active === undefined ? true : !!data.active;
title.textContent = data.id ? 'Gegenstand bearbeiten' : 'Gegenstand anlegen';
applyMode();
};
document.querySelectorAll('[data-open-modal="shop-item-modal"]').forEach(function (button) {
button.addEventListener('click', function () {
fill(button.dataset.item ? JSON.parse(button.dataset.item) : null);
itemModal.hidden = false;
form.elements.name.focus();
});
});
if (itemModal.dataset.old) {
fill(JSON.parse(itemModal.dataset.old));
} else {
applyMode();
}
}
// ---- Verwaltung: aus dem Lagerhaus uebernehmen ----
var importModal = document.getElementById('shop-import-modal');
if (importModal) {
document.querySelectorAll('[data-open-modal="shop-import-modal"]').forEach(function (button) {
button.addEventListener('click', function () { importModal.hidden = false; });
});
var checks = importModal.querySelectorAll('.shop-import-check');
var all = document.getElementById('shop-import-all');
var priceFor = function (check) {
return importModal.querySelector('input[name="prices[' + check.value + ']"]');
};
// Wer einen Gegenstand auswaehlt, muss einen Preis angeben.
checks.forEach(function (check) {
check.addEventListener('change', function () {
priceFor(check).required = check.checked;
all.checked = Array.prototype.every.call(checks, function (c) { return c.checked; });
});
});
all.addEventListener('change', function () {
checks.forEach(function (check) {
check.checked = all.checked;
priceFor(check).required = all.checked;
});
});
document.getElementById('shop-import-apply').addEventListener('click', function () {
var value = document.getElementById('shop-import-price').value;
if (value === '') return;
checks.forEach(function (check) {
if (check.checked) priceFor(check).value = value;
});
});
}
})();

View file

@ -197,6 +197,7 @@ include __DIR__ . '/includes/header.php';
} }
} }
$shownPoints = $mine ?? $uniform; $shownPoints = $mine ?? $uniform;
$isSystem = isset(CONTRIBUTION_SYSTEM_CATEGORIES[(string) $award['category']]);
?> ?>
<article class="contribution-award"> <article class="contribution-award">
<div class="contribution-award-points<?= $shownPoints !== null && $shownPoints < 0 ? ' negative' : '' ?>"> <div class="contribution-award-points<?= $shownPoints !== null && $shownPoints < 0 ? ' negative' : '' ?>">
@ -217,7 +218,7 @@ include __DIR__ . '/includes/header.php';
<div class="contribution-award-meta text-muted"> <div class="contribution-award-meta text-muted">
<?= e(contribution_format_time($award['awarded_at'])) ?> <?= e(contribution_format_time($award['awarded_at'])) ?>
· <?= count($entries) ?> <?= count($entries) === 1 ? 'Mitglied' : 'Mitglieder' ?> · <?= count($entries) ?> <?= count($entries) === 1 ? 'Mitglied' : 'Mitglieder' ?>
<?php if (!empty($award['author'])): ?>· vergeben von <?= e((string) $award['author']) ?><?php endif; ?> <?php if (!empty($award['author'])): ?>· <?= $isSystem ? 'bewilligt' : 'vergeben' ?> von <?= e((string) $award['author']) ?><?php endif; ?>
</div> </div>
<details class="contribution-award-members"<?= count($entries) <= 6 ? ' open' : '' ?>> <details class="contribution-award-members"<?= count($entries) <= 6 ? ' open' : '' ?>>
<summary>Mitglieder anzeigen</summary> <summary>Mitglieder anzeigen</summary>
@ -228,7 +229,7 @@ include __DIR__ . '/includes/header.php';
<?php if ($uniform === null): ?> <?php if ($uniform === null): ?>
<span class="text-muted"><?= contribution_format((int) $entry['points'], true) ?></span> <span class="text-muted"><?= contribution_format((int) $entry['points'], true) ?></span>
<?php endif; ?> <?php endif; ?>
<?php if ($canManage): ?> <?php if ($canManage && !$isSystem): ?>
<form class="inline-form" method="post" action="/contributions_action.php" <form class="inline-form" method="post" action="/contributions_action.php"
onsubmit="return confirm(<?= e(json_encode('„' . $entry['name'] . '“ aus dieser Vergabe entfernen? Die Punkte werden abgezogen.', JSON_UNESCAPED_UNICODE)) ?>);"> onsubmit="return confirm(<?= e(json_encode('„' . $entry['name'] . '“ aus dieser Vergabe entfernen? Die Punkte werden abgezogen.', JSON_UNESCAPED_UNICODE)) ?>);">
<?= csrf_field() ?> <?= csrf_field() ?>
@ -242,7 +243,7 @@ include __DIR__ . '/includes/header.php';
</div> </div>
</details> </details>
</div> </div>
<?php if ($canManage): ?> <?php if ($canManage && !$isSystem): ?>
<form class="contribution-award-delete" method="post" action="/contributions_action.php" <form class="contribution-award-delete" method="post" action="/contributions_action.php"
onsubmit="return confirm(<?= e(json_encode('Vergabe „' . $award['title'] . '“ komplett löschen? Allen ' . count($entries) . ' Mitgliedern werden die Punkte wieder abgezogen.', JSON_UNESCAPED_UNICODE)) ?>);"> onsubmit="return confirm(<?= e(json_encode('Vergabe „' . $award['title'] . '“ komplett löschen? Allen ' . count($entries) . ' Mitgliedern werden die Punkte wieder abgezogen.', JSON_UNESCAPED_UNICODE)) ?>);">
<?= csrf_field() ?> <?= csrf_field() ?>

View file

@ -11,6 +11,18 @@ verify_csrf();
$action = (string) ($_POST['action'] ?? ''); $action = (string) ($_POST['action'] ?? '');
$pdo = db(); $pdo = db();
/** Bricht ab, wenn die Vergabe vom Lumishop stammt - die wird dort storniert, sonst stimmen Bestellung und Punkte nicht mehr ueberein. */
function contribution_guard_system(int $awardId): void
{
$stmt = db()->prepare('SELECT category FROM contribution_awards WHERE id = ?');
$stmt->execute([$awardId]);
$category = (string) $stmt->fetchColumn();
if (isset(CONTRIBUTION_SYSTEM_CATEGORIES[$category])) {
set_flash('error', 'Diese Buchung stammt aus dem Lumishop. Bitte dort die Bestellung stornieren.');
redirect('/contributions.php#verlauf');
}
}
/** Zurueck ins Formular, mit Fehlermeldung und den bisherigen Eingaben. */ /** Zurueck ins Formular, mit Fehlermeldung und den bisherigen Eingaben. */
function contribution_fail(string $message): void function contribution_fail(string $message): void
{ {
@ -85,6 +97,7 @@ switch ($action) {
// ---- Ganze Vergabe loeschen ---- // ---- Ganze Vergabe loeschen ----
case 'delete_award': case 'delete_award':
contribution_guard_system((int) ($_POST['award_id'] ?? 0));
$stmt = $pdo->prepare('DELETE FROM contribution_awards WHERE id = ?'); $stmt = $pdo->prepare('DELETE FROM contribution_awards WHERE id = ?');
$stmt->execute([(int) ($_POST['award_id'] ?? 0)]); $stmt->execute([(int) ($_POST['award_id'] ?? 0)]);
set_flash($stmt->rowCount() > 0 ? 'success' : 'error', $stmt->rowCount() > 0 ? 'Vergabe gelöscht.' : 'Diese Vergabe gibt es nicht mehr.'); set_flash($stmt->rowCount() > 0 ? 'success' : 'error', $stmt->rowCount() > 0 ? 'Vergabe gelöscht.' : 'Diese Vergabe gibt es nicht mehr.');
@ -100,6 +113,7 @@ switch ($action) {
set_flash('error', 'Diesen Eintrag gibt es nicht mehr.'); set_flash('error', 'Diesen Eintrag gibt es nicht mehr.');
redirect('/contributions.php#verlauf'); redirect('/contributions.php#verlauf');
} }
contribution_guard_system($awardId);
$pdo->beginTransaction(); $pdo->beginTransaction();
$pdo->prepare('DELETE FROM contribution_entries WHERE id = ?')->execute([$entryId]); $pdo->prepare('DELETE FROM contribution_entries WHERE id = ?')->execute([$entryId]);

View file

@ -16,6 +16,12 @@ const CONTRIBUTION_CATEGORIES = [
'other' => 'Sonstiges', 'other' => 'Sonstiges',
]; ];
// Anlaesse, die nur das System anlegt (nicht im Formular waehlbar). Vergaben dieser Art
// lassen sich nicht auf der Lumipunkte-Seite loeschen, sondern nur dort, wo sie entstanden sind.
const CONTRIBUTION_SYSTEM_CATEGORIES = [
'shop' => 'Lumishop',
];
// So viele Plaetze der Rangliste sieht jeder mit contributions.view - den Rest nur mit // So viele Plaetze der Rangliste sieht jeder mit contributions.view - den Rest nur mit
// contributions.view_all (oder contributions.manage). // contributions.view_all (oder contributions.manage).
const CONTRIBUTION_PUBLIC_RANKS = 25; const CONTRIBUTION_PUBLIC_RANKS = 25;
@ -25,7 +31,7 @@ const CONTRIBUTION_MAX_POINTS = 10000;
function contribution_category_label(string $key): string function contribution_category_label(string $key): string
{ {
return CONTRIBUTION_CATEGORIES[$key] ?? $key; return CONTRIBUTION_CATEGORIES[$key] ?? CONTRIBUTION_SYSTEM_CATEGORIES[$key] ?? $key;
} }
/** Das Muenz-Symbol der Lumipunkte. */ /** Das Muenz-Symbol der Lumipunkte. */

View file

@ -135,6 +135,7 @@ function icon(string $name): string
'chevron-down' => '<polyline points="6 9 12 15 18 9"/>', 'chevron-down' => '<polyline points="6 9 12 15 18 9"/>',
'check' => '<polyline points="20 6 9 17 4 12"/>', 'check' => '<polyline points="20 6 9 17 4 12"/>',
'heart' => '<path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 0 0-7.8 7.8l1 1.1L12 21l7.8-7.5 1-1.1a5.5 5.5 0 0 0 0-7.8z"/>', 'heart' => '<path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 0 0-7.8 7.8l1 1.1L12 21l7.8-7.5 1-1.1a5.5 5.5 0 0 0 0-7.8z"/>',
'bag' => '<path d="M5 8h14l-1.2 11.2a2 2 0 0 1-2 1.8H8.2a2 2 0 0 1-2-1.8z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/>',
'box' => '<path d="M21 8 12 3 3 8v8l9 5 9-5z"/><path d="M3 8l9 5 9-5"/><line x1="12" y1="13" x2="12" y2="21"/>', 'box' => '<path d="M21 8 12 3 3 8v8l9 5 9-5z"/><path d="M3 8l9 5 9-5"/><line x1="12" y1="13" x2="12" y2="21"/>',
]; ];

View file

@ -12,6 +12,16 @@ $canViewEvents = $currentUser && user_has_permission('events.view');
$canViewMap = $currentUser && user_has_permission('map.view'); $canViewMap = $currentUser && user_has_permission('map.view');
$canViewWarehouse = $currentUser && user_has_permission('warehouse.view'); $canViewWarehouse = $currentUser && user_has_permission('warehouse.view');
$canViewContributions = $currentUser && user_has_permission('contributions.view'); $canViewContributions = $currentUser && user_has_permission('contributions.view');
$canViewShop = $currentUser && user_has_permission('shop.view');
// Offene Lumishop-Antraege als Zahl am Menuepunkt (nur fuer die, die sie bearbeiten).
$shopPendingCount = 0;
if ($canViewShop && user_has_permission('shop.manage')) {
try {
$shopPendingCount = (int) db()->query("SELECT COUNT(*) FROM shop_orders WHERE status = 'pending'")->fetchColumn();
} catch (PDOException $e) {
$shopPendingCount = 0;
}
}
// Eigener Punktestand unten in der Seitenleiste. // Eigener Punktestand unten in der Seitenleiste.
$sidebarPoints = null; $sidebarPoints = null;
if ($canViewContributions && $shellUser) { if ($canViewContributions && $shellUser) {
@ -40,6 +50,7 @@ $isEventsActive = $currentScript === 'events.php';
$isMapActive = $currentScript === 'map.php'; $isMapActive = $currentScript === 'map.php';
$isWarehouseActive = $currentScript === 'warehouse.php'; $isWarehouseActive = $currentScript === 'warehouse.php';
$isContributionsActive = in_array($currentScript, ['contributions.php', 'contributions_award.php'], true); $isContributionsActive = in_array($currentScript, ['contributions.php', 'contributions_award.php'], true);
$isShopActive = in_array($currentScript, ['shop.php', 'shop_orders.php', 'shop_manage.php'], true);
$isMembersActive = $currentScript === 'members.php'; $isMembersActive = $currentScript === 'members.php';
$isReportsActive = $currentScript === 'reports.php'; $isReportsActive = $currentScript === 'reports.php';
$isUsersActive = in_array($currentScript, ['users.php', 'user_form.php', 'user_delete.php', 'user_approve.php'], true); $isUsersActive = in_array($currentScript, ['users.php', 'user_form.php', 'user_delete.php', 'user_approve.php'], true);
@ -56,6 +67,9 @@ $pageBackgrounds = [
'warehouse.php' => 'bg-warehouse', 'warehouse.php' => 'bg-warehouse',
'contributions.php' => 'bg-contributions', 'contributions.php' => 'bg-contributions',
'contributions_award.php' => 'bg-contributions', 'contributions_award.php' => 'bg-contributions',
'shop.php' => 'bg-shop',
'shop_orders.php' => 'bg-shop',
'shop_manage.php' => 'bg-shop',
'members.php' => 'bg-members', 'members.php' => 'bg-members',
'users.php' => 'bg-admin', 'users.php' => 'bg-admin',
'user_form.php' => 'bg-admin', 'user_form.php' => 'bg-admin',
@ -126,6 +140,14 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($
<?= icon('heart') ?><span class="label">Lumipunkte</span> <?= icon('heart') ?><span class="label">Lumipunkte</span>
</a> </a>
<?php endif; ?> <?php endif; ?>
<?php if ($canViewShop): ?>
<a href="/shop.php" class="sidebar-link<?= $isShopActive ? ' active' : '' ?>" title="Lumishop">
<?= icon('bag') ?><span class="label">Lumishop</span>
<?php if ($shopPendingCount > 0): ?>
<span class="sidebar-badge" title="Offene Anträge"><?= $shopPendingCount ?></span>
<?php endif; ?>
</a>
<?php endif; ?>
<?php if ($canViewMembers): ?> <?php if ($canViewMembers): ?>
<a href="/members.php" class="sidebar-link<?= $isMembersActive ? ' active' : '' ?>" title="Mitglieder"> <a href="/members.php" class="sidebar-link<?= $isMembersActive ? ' active' : '' ?>" title="Mitglieder">
<?= icon('users') ?><span class="label">Mitglieder</span> <?= icon('users') ?><span class="label">Mitglieder</span>

View file

@ -25,6 +25,8 @@ const CORE_PERMISSIONS = [
['key' => 'contributions.view', 'description' => 'Lumipunkte: Punktestände und Verlauf einsehen'], ['key' => 'contributions.view', 'description' => 'Lumipunkte: Punktestände und Verlauf einsehen'],
['key' => 'contributions.view_all', 'description' => 'Lumipunkte: vollständige Rangliste sehen (sonst nur die besten 25)'], ['key' => 'contributions.view_all', 'description' => 'Lumipunkte: vollständige Rangliste sehen (sonst nur die besten 25)'],
['key' => 'contributions.manage', 'description' => 'Lumipunkte vergeben, abziehen und Vergaben löschen'], ['key' => 'contributions.manage', 'description' => 'Lumipunkte vergeben, abziehen und Vergaben löschen'],
['key' => 'shop.view', 'description' => 'Lumishop: Angebot ansehen und Gegenstände gegen Lumipunkte beantragen'],
['key' => 'shop.manage', 'description' => 'Lumishop: Kategorien, Gegenstände, Bestand und Preise verwalten, Anträge bewilligen oder ablehnen'],
['key' => 'members.view', 'description' => 'Mitgliederliste einsehen'], ['key' => 'members.view', 'description' => 'Mitgliederliste einsehen'],
['key' => 'reports.view', 'description' => 'Eingegangene Reports einsehen'], ['key' => 'reports.view', 'description' => 'Eingegangene Reports einsehen'],
['key' => 'reports.manage', 'description' => 'Reports löschen/archivieren und die Punkte-Gewichtung verwalten'], ['key' => 'reports.manage', 'description' => 'Reports löschen/archivieren und die Punkte-Gewichtung verwalten'],

View file

@ -11,7 +11,7 @@ declare(strict_types=1);
*/ */
// Hochzaehlen, sobald unten eine Aenderung dazukommt - dann pruefen alle Sitzungen neu. // Hochzaehlen, sobald unten eine Aenderung dazukommt - dann pruefen alle Sitzungen neu.
const SCHEMA_VERSION = 8; const SCHEMA_VERSION = 9;
/** /**
* Tabellen, die nachtraeglich dazugekommen sind: Tabelle => CREATE-Befehl (wie in sql/schema.sql). * Tabellen, die nachtraeglich dazugekommen sind: Tabelle => CREATE-Befehl (wie in sql/schema.sql).
@ -86,6 +86,72 @@ CREATE TABLE IF NOT EXISTS contribution_entries (
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
INDEX idx_contribution_entries_user (user_id) INDEX idx_contribution_entries_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'shop_categories' => <<<'SQL'
CREATE TABLE IF NOT EXISTS shop_categories (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80) NOT NULL,
sort_order INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'shop_items' => <<<'SQL'
CREATE TABLE IF NOT EXISTS shop_items (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
category_id INT UNSIGNED NULL,
name VARCHAR(150) NOT NULL,
description VARCHAR(500) NULL,
-- Preis in Lumipunkten pro Stueck
price INT UNSIGNED NOT NULL,
-- manual = eigener Bestand (stock), warehouse = Bestand des Lagerhaus-Gegenstands, unlimited
stock_mode ENUM('manual', 'warehouse', 'unlimited') NOT NULL DEFAULT 'manual',
stock INT UNSIGNED NOT NULL DEFAULT 0,
-- Verknuepfter Lagerhaus-Gegenstand: liefert das Bild und bei stock_mode = warehouse den Bestand
warehouse_item_id INT UNSIGNED NULL,
active TINYINT(1) NOT NULL DEFAULT 1,
created_by INT UNSIGNED NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NULL,
FOREIGN KEY (category_id) REFERENCES shop_categories(id) ON DELETE SET NULL,
FOREIGN KEY (warehouse_item_id) REFERENCES warehouse_items(id) ON DELETE SET NULL,
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL,
'shop_orders' => <<<'SQL'
CREATE TABLE IF NOT EXISTS shop_orders (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED NOT NULL,
item_id INT UNSIGNED NULL,
-- Name und Preis zum Zeitpunkt der Bestellung (bleiben, auch wenn der Gegenstand spaeter
-- geaendert oder geloescht wird)
item_name VARCHAR(150) NOT NULL,
quantity INT UNSIGNED NOT NULL,
unit_price INT UNSIGNED NOT NULL,
total_price INT UNSIGNED NOT NULL,
-- Bemerkung des Mitglieds (z.B. Charaktername)
note VARCHAR(255) NULL,
-- pending, approved, delivered, rejected, cancelled (SHOP_STATUSES in includes/shop.php)
status ENUM('pending', 'approved', 'delivered', 'rejected', 'cancelled') NOT NULL DEFAULT 'pending',
decision_note VARCHAR(255) NULL,
decided_by INT UNSIGNED NULL,
decided_at DATETIME NULL,
delivered_by INT UNSIGNED NULL,
delivered_at DATETIME NULL,
-- Die Vergabe mit dem Punkteabzug und die Entnahme im Lagerhaus (fuer eine Stornierung)
award_id INT UNSIGNED NULL,
warehouse_movement_id INT UNSIGNED NULL,
-- 1 = bei der Bewilligung wurde der eigene Bestand im Shop verringert
stock_taken TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES shop_items(id) ON DELETE SET NULL,
FOREIGN KEY (decided_by) REFERENCES users(id) ON DELETE SET NULL,
FOREIGN KEY (delivered_by) REFERENCES users(id) ON DELETE SET NULL,
FOREIGN KEY (award_id) REFERENCES contribution_awards(id) ON DELETE SET NULL,
FOREIGN KEY (warehouse_movement_id) REFERENCES warehouse_movements(id) ON DELETE SET NULL,
INDEX idx_shop_orders_status (status),
INDEX idx_shop_orders_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL, SQL,
'raid_settings' => <<<'SQL' 'raid_settings' => <<<'SQL'
CREATE TABLE IF NOT EXISTS raid_settings ( CREATE TABLE IF NOT EXISTS raid_settings (

215
includes/shop.php Normal file
View file

@ -0,0 +1,215 @@
<?php
declare(strict_types=1);
/**
* Lumishop: Mitglieder tauschen Lumipunkte gegen Gegenstaende.
*
* Ablauf einer Bestellung:
* pending - Mitglied hat beantragt. Punkte und Bestand sind vorgemerkt, aber noch nicht abgezogen.
* approved - bewilligt: Punkte abgezogen (negative Vergabe der Kategorie "shop"), Bestand
* verringert bzw. aus dem Lagerhaus entnommen. Wartet auf die Uebergabe im Spiel.
* delivered - im Spiel uebergeben.
* rejected - abgelehnt (nichts wurde abgezogen).
* cancelled - vom Mitglied zurueckgezogen oder nach der Bewilligung storniert (Punkte und
* Bestand zurueck).
*
* Bestand eines Gegenstands (stock_mode):
* unlimited - unbegrenzt
* manual - eigene Zahl im Shop (shop_items.stock)
* warehouse - der Bestand des verknuepften Lagerhaus-Gegenstands; bei der Bewilligung wird
* automatisch eine Entnahme an das Mitglied gebucht.
*/
require_once __DIR__ . '/contributions.php';
require_once __DIR__ . '/warehouse.php';
const SHOP_STATUSES = [
'pending' => 'Beantragt',
'approved' => 'Bewilligt – Übergabe ausstehend',
'delivered' => 'Übergeben',
'rejected' => 'Abgelehnt',
'cancelled' => 'Storniert',
];
const SHOP_STOCK_MODES = [
'manual' => 'Eigener Bestand im Shop',
'warehouse' => 'Aus dem Lagerhaus (automatisch)',
'unlimited' => 'Unbegrenzt',
];
const SHOP_MAX_PRICE = 1000000;
const SHOP_MAX_STOCK = 1000000;
const SHOP_MAX_ORDER_QUANTITY = 1000;
function shop_status_label(string $status): string
{
return SHOP_STATUSES[$status] ?? $status;
}
/** @return array<int, array<string, mixed>> */
function shop_categories(): array
{
return db()->query('SELECT id, name, sort_order FROM shop_categories ORDER BY sort_order, name')->fetchAll();
}
/**
* Gegenstaende mit Kategorie, Bild, Lagerbestand und vorgemerkter Menge (offene Antraege).
*
* @return array<int, array<string, mixed>>
*/
function shop_items(bool $onlyActive): array
{
$rows = db()->query(
"SELECT s.*, c.name AS category_name, c.sort_order AS category_sort,
w.name AS warehouse_name, w.icon,
(SELECT COALESCE(SUM(CASE WHEN m.direction = 'in' THEN m.quantity ELSE -m.quantity END), 0)
FROM warehouse_movements m WHERE m.item_id = s.warehouse_item_id) AS warehouse_stock,
(SELECT COALESCE(SUM(o.quantity), 0) FROM shop_orders o
WHERE o.item_id = s.id AND o.status = 'pending') AS reserved
FROM shop_items s
LEFT JOIN shop_categories c ON c.id = s.category_id
LEFT JOIN warehouse_items w ON w.id = s.warehouse_item_id
" . ($onlyActive ? 'WHERE s.active = 1' : '') . "
ORDER BY c.sort_order IS NULL, c.sort_order, c.name, s.name"
)->fetchAll();
foreach ($rows as &$row) {
$row['available'] = shop_available($row);
}
unset($row);
return $rows;
}
function shop_item(int $id): ?array
{
$stmt = db()->prepare(
'SELECT s.*, w.name AS warehouse_name, w.icon FROM shop_items s
LEFT JOIN warehouse_items w ON w.id = s.warehouse_item_id WHERE s.id = ?'
);
$stmt->execute([$id]);
return $stmt->fetch() ?: null;
}
/** Bestand vor Abzug der offenen Antraege; null = unbegrenzt. */
function shop_stock(array $item): ?int
{
switch ($item['stock_mode']) {
case 'unlimited':
return null;
case 'warehouse':
if (empty($item['warehouse_item_id'])) {
return 0;
}
return array_key_exists('warehouse_stock', $item)
? (int) $item['warehouse_stock']
: warehouse_item_stock((int) $item['warehouse_item_id']);
default:
return (int) $item['stock'];
}
}
/** Was noch beantragt werden kann (Bestand minus offene Antraege); null = unbegrenzt. */
function shop_available(array $item): ?int
{
$stock = shop_stock($item);
if ($stock === null) {
return null;
}
if (!array_key_exists('reserved', $item)) {
$stmt = db()->prepare("SELECT COALESCE(SUM(quantity), 0) FROM shop_orders WHERE item_id = ? AND status = 'pending'");
$stmt->execute([(int) $item['id']]);
$item['reserved'] = (int) $stmt->fetchColumn();
}
return max(0, $stock - (int) $item['reserved']);
}
/** Punkte, die in offenen Antraegen eines Mitglieds vorgemerkt sind. */
function shop_reserved_points(int $userId): int
{
$stmt = db()->prepare("SELECT COALESCE(SUM(total_price), 0) FROM shop_orders WHERE user_id = ? AND status = 'pending'");
$stmt->execute([$userId]);
return (int) $stmt->fetchColumn();
}
function shop_pending_count(): int
{
return (int) db()->query("SELECT COUNT(*) FROM shop_orders WHERE status = 'pending'")->fetchColumn();
}
/**
* Bestellungen, neueste zuerst.
*
* @param string[] $statuses leer = alle
* @return array<int, array<string, mixed>>
*/
function shop_orders(array $statuses, ?int $userId, int $limit, int $offset): array
{
[$where, $params] = shop_orders_where($statuses, $userId);
$stmt = db()->prepare(
"SELECT o.*, w.icon, s.stock_mode, s.warehouse_item_id,
COALESCE(NULLIF(u.display_name, ''), u.username) AS buyer,
COALESCE(NULLIF(du.display_name, ''), du.username) AS decider,
COALESCE(NULLIF(vu.display_name, ''), vu.username) AS deliverer
FROM shop_orders o
JOIN users u ON u.id = o.user_id
LEFT JOIN shop_items s ON s.id = o.item_id
LEFT JOIN warehouse_items w ON w.id = s.warehouse_item_id
LEFT JOIN users du ON du.id = o.decided_by
LEFT JOIN users vu ON vu.id = o.delivered_by
$where
ORDER BY o.created_at " . (in_array('pending', $statuses, true) && count($statuses) === 1 ? 'ASC' : 'DESC') . ', o.id DESC
LIMIT ' . (int) $limit . ' OFFSET ' . (int) $offset
);
$stmt->execute($params);
return $stmt->fetchAll();
}
function shop_order_count(array $statuses, ?int $userId): int
{
[$where, $params] = shop_orders_where($statuses, $userId);
$stmt = db()->prepare("SELECT COUNT(*) FROM shop_orders o $where");
$stmt->execute($params);
return (int) $stmt->fetchColumn();
}
/** @return array{0: string, 1: array<int, mixed>} */
function shop_orders_where(array $statuses, ?int $userId): array
{
$conditions = [];
$params = [];
if (!empty($statuses)) {
$conditions[] = 'o.status IN (' . implode(',', array_fill(0, count($statuses), '?')) . ')';
array_push($params, ...$statuses);
}
if ($userId !== null) {
$conditions[] = 'o.user_id = ?';
$params[] = $userId;
}
return [$conditions ? 'WHERE ' . implode(' AND ', $conditions) : '', $params];
}
/** Bild eines Shop-Gegenstands (das des verknuepften Lagerhaus-Gegenstands oder Platzhalter). */
function shop_icon_html(array $item, int $size): string
{
return warehouse_icon_html($item['icon'] ?? null, (string) ($item['name'] ?? $item['item_name'] ?? ''), $size);
}
/** "3× Name" bzw. nur "Name" bei einem Stueck. */
function shop_order_label(array $order): string
{
return ((int) $order['quantity'] > 1 ? (int) $order['quantity'] . '× ' : '') . $order['item_name'];
}
function shop_format_availability(?int $available): string
{
if ($available === null) {
return 'Unbegrenzt verfügbar';
}
return $available > 0 ? number_format($available, 0, ',', '.') . ' verfügbar' : 'Ausverkauft';
}
/** Jetzt in deutscher Zeit - wie die Zeitpunkte, die im Lagerhaus und bei Vergaben eingetragen werden. */
function shop_now(): string
{
return (new DateTimeImmutable('now', new DateTimeZone('Europe/Berlin')))->format('Y-m-d H:i:s');
}

105
includes/shop_order_row.php Normal file
View file

@ -0,0 +1,105 @@
<?php
/**
* Eine Bestellung als Zeile - fuer "Meine Antraege" (shop.php) und die Antragsliste der
* Verwaltung (shop_orders.php, dort mit $orderView = 'manage' und den Bearbeitungsknoepfen).
*
* @var array $order
* @var string|null $orderView
* @var string|null $orderReturn Ruecksprung nach einer Aktion
*/
$isManageView = ($orderView ?? 'member') === 'manage';
$status = (string) $order['status'];
$badgeClass = [
'pending' => 'badge-pending',
'approved' => 'shop-badge-approved',
'delivered' => 'badge-active',
'rejected' => 'badge-disabled',
'cancelled' => '',
][$status] ?? '';
$return = $orderReturn ?? '/shop.php#antraege';
?>
<article class="shop-order shop-order-<?= e($status) ?>">
<span class="shop-order-icon"><?= warehouse_icon_html($order['icon'] ?? null, (string) $order['item_name'], 44) ?></span>
<div class="shop-order-body">
<div class="shop-order-title">
<strong><?= e(shop_order_label($order)) ?></strong>
<span class="badge <?= e($badgeClass) ?>"><?= e(shop_status_label($status)) ?></span>
<span class="text-muted">#<?= (int) $order['id'] ?></span>
</div>
<div class="shop-order-meta text-muted">
<?php if ($isManageView): ?>
<strong class="shop-order-buyer"><?= e((string) $order['buyer']) ?></strong> ·
<?php endif; ?>
beantragt am <?= e(contribution_format_time($order['created_at'])) ?>
<?php if ((int) $order['quantity'] > 1): ?>
· <?= (int) $order['quantity'] ?> × <?= contribution_format((int) $order['unit_price']) ?>
<?php endif; ?>
</div>
<?php if (!empty($order['note'])): ?>
<div class="shop-order-note"><span class="text-muted">Bemerkung:</span> <?= e((string) $order['note']) ?></div>
<?php endif; ?>
<?php if ($order['decided_at'] !== null): ?>
<div class="shop-order-meta text-muted">
<?= $status === 'rejected' ? 'Abgelehnt' : ($status === 'cancelled' ? 'Storniert' : 'Bewilligt') ?>
am <?= e(contribution_format_time($order['decided_at'])) ?>
<?php if (!empty($order['decider'])): ?>von <?= e((string) $order['decider']) ?><?php endif; ?>
<?php if ($order['delivered_at'] !== null): ?>
· übergeben am <?= e(contribution_format_time($order['delivered_at'])) ?>
<?php if (!empty($order['deliverer'])): ?>von <?= e((string) $order['deliverer']) ?><?php endif; ?>
<?php endif; ?>
</div>
<?php elseif ($status === 'cancelled'): ?>
<div class="shop-order-meta text-muted">Vom Mitglied zurückgezogen.</div>
<?php endif; ?>
<?php if (!empty($order['decision_note'])): ?>
<div class="shop-order-note"><span class="text-muted">Grund:</span> <?= e((string) $order['decision_note']) ?></div>
<?php endif; ?>
</div>
<div class="shop-order-price<?= in_array($status, ['approved', 'delivered'], true) ? ' is-paid' : '' ?>" title="<?= in_array($status, ['approved', 'delivered'], true) ? 'Abgezogen' : ($status === 'pending' ? 'Vorgemerkt' : 'Nicht abgezogen') ?>">
<?= contribution_coin(18) ?> <?= contribution_format((int) $order['total_price']) ?>
</div>
<div class="shop-order-actions">
<?php if ($isManageView): ?>
<?php if ($status === 'pending'): ?>
<form method="post" action="/shop_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="approve">
<input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
<input type="hidden" name="return" value="<?= e($return) ?>">
<button type="submit" class="button-success button-small" title="Lumipunkte abziehen und zur Übergabe freigeben"><?= icon('check') ?> Bewilligen</button>
</form>
<form method="post" action="/shop_action.php" data-prompt="Grund für die Ablehnung (optional, sieht das Mitglied):">
<?= csrf_field() ?>
<input type="hidden" name="action" value="reject">
<input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
<input type="hidden" name="reason" value="">
<input type="hidden" name="return" value="<?= e($return) ?>">
<button type="submit" class="button-secondary button-small"><?= icon('x') ?> Ablehnen</button>
</form>
<?php elseif ($status === 'approved'): ?>
<form method="post" action="/shop_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="deliver">
<input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
<input type="hidden" name="return" value="<?= e($return) ?>">
<button type="submit" class="button-small" title="Im Spiel übergeben"><?= icon('check') ?> Übergeben</button>
</form>
<form method="post" action="/shop_action.php" data-prompt="Bestellung stornieren? Die Lumipunkte gehen zurück an das Mitglied und der Bestand wird wieder aufgefüllt.&#10;&#10;Grund (optional):">
<?= csrf_field() ?>
<input type="hidden" name="action" value="revoke">
<input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
<input type="hidden" name="reason" value="">
<input type="hidden" name="return" value="<?= e($return) ?>">
<button type="submit" class="icon-button icon-button-danger" title="Stornieren" aria-label="Stornieren"><?= icon('restore') ?></button>
</form>
<?php endif; ?>
<?php elseif ($status === 'pending'): ?>
<form method="post" action="/shop_action.php" onsubmit="return confirm('Antrag zurückziehen?');">
<?= csrf_field() ?>
<input type="hidden" name="action" value="cancel">
<input type="hidden" name="order_id" value="<?= (int) $order['id'] ?>">
<button type="submit" class="button-secondary button-small">Zurückziehen</button>
</form>
<?php endif; ?>
</div>
</article>

165
shop.php Normal file
View file

@ -0,0 +1,165 @@
<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/shop.php';
require_permission('shop.view');
$canManage = user_has_permission('shop.manage');
$userId = (int) current_user()['id'];
$balance = contribution_user_balance($userId);
$reservedPoints = shop_reserved_points($userId);
$spendable = max(0, $balance - $reservedPoints);
$items = shop_items(true);
$categories = [];
foreach ($items as $item) {
if ($item['category_id'] !== null) {
$categories[(int) $item['category_id']] = (string) $item['category_name'];
}
}
$hasUncategorized = (bool) array_filter($items, static fn (array $i): bool => $i['category_id'] === null);
// Eigene Antraege
$perPage = 10;
$totalOrders = shop_order_count([], $userId);
$pageCount = max(1, (int) ceil($totalOrders / $perPage));
$page = min($pageCount, max(1, (int) ($_GET['page'] ?? 1)));
$myOrders = shop_orders([], $userId, $perPage, ($page - 1) * $perPage);
$pendingCount = $canManage ? shop_pending_count() : 0;
// Eingaben nach einem Fehler (siehe shop_action.php)
$old = $_SESSION['shop_form'] ?? [];
unset($_SESSION['shop_form']);
$pageTitle = 'Lumishop';
$containerWide = true;
include __DIR__ . '/includes/header.php';
?>
<div class="panel contribution-hero shop-hero">
<img class="contribution-hero-coin" src="/assets/images/lumipunkt.svg" alt="" width="72" height="72">
<div class="contribution-hero-text">
<h1>Lumishop</h1>
<p class="text-muted">Tausche deine Lumipunkte gegen Gegenstände aus dem Legionslager. Nach der Bewilligung bekommst du den Gegenstand im Spiel überreicht.</p>
</div>
<div class="contribution-hero-balance" title="Punktestand abzüglich offener Anträge">
<span class="text-muted">Verfügbar</span>
<strong><?= contribution_coin(26) ?> <?= contribution_format($spendable) ?></strong>
<?php if ($reservedPoints > 0): ?>
<span class="text-muted shop-reserved"><?= contribution_format($reservedPoints) ?> in offenen Anträgen vorgemerkt</span>
<?php endif; ?>
</div>
<?php if ($canManage): ?>
<div class="shop-hero-actions">
<a class="button" href="/shop_orders.php">Anträge<?php if ($pendingCount > 0): ?> <span class="shop-count"><?= $pendingCount ?></span><?php endif; ?></a>
<a class="button button-secondary" href="/shop_manage.php">Shop verwalten</a>
</div>
<?php endif; ?>
</div>
<div class="panel">
<div class="warehouse-filters">
<input type="search" id="shop-search" placeholder="Gegenstand suchen …" autocomplete="off">
<?php if (count($categories) + ($hasUncategorized ? 1 : 0) > 1): ?>
<select id="shop-category">
<option value="">Alle Kategorien</option>
<?php foreach ($categories as $id => $name): ?>
<option value="<?= (int) $id ?>"><?= e($name) ?></option>
<?php endforeach; ?>
<?php if ($hasUncategorized): ?>
<option value="0">Ohne Kategorie</option>
<?php endif; ?>
</select>
<?php endif; ?>
</div>
<?php if (empty($items)): ?>
<p class="text-muted">Im Lumishop gibt es gerade nichts.<?= $canManage ? ' Unter „Shop verwalten“ legst du Gegenstände an oder übernimmst sie aus dem Lagerhaus.' : '' ?></p>
<?php else: ?>
<div class="shop-grid" id="shop-items">
<?php foreach ($items as $item): ?>
<?php
$available = $item['available'];
$price = (int) $item['price'];
$soldOut = $available !== null && $available < 1;
$affordable = $price === 0 ? SHOP_MAX_ORDER_QUANTITY : intdiv($spendable, $price);
$max = min(SHOP_MAX_ORDER_QUANTITY, $affordable, $available ?? SHOP_MAX_ORDER_QUANTITY);
$reason = $soldOut ? 'Ausverkauft' : ($max < 1 ? 'Nicht genug Lumipunkte' : '');
?>
<div class="shop-card<?= $soldOut ? ' sold-out' : '' ?>" data-name="<?= e(mb_strtolower((string) $item['name'])) ?>" data-category="<?= (int) ($item['category_id'] ?? 0) ?>">
<span class="shop-card-image"><?= shop_icon_html($item, 72) ?></span>
<span class="shop-card-name"><?= e((string) $item['name']) ?></span>
<?php if ($item['category_name'] !== null): ?>
<span class="warehouse-card-category"><?= e((string) $item['category_name']) ?></span>
<?php endif; ?>
<?php if (!empty($item['description'])): ?>
<span class="shop-card-description"><?= nl2br(e((string) $item['description'])) ?></span>
<?php endif; ?>
<span class="shop-card-price"><?= contribution_coin(18) ?> <?= contribution_format($price) ?></span>
<span class="shop-card-stock<?= $soldOut ? ' is-empty' : '' ?>"><?= e(shop_format_availability($available)) ?></span>
<button type="button" class="button-small shop-buy" <?= $reason !== '' ? 'disabled title="' . e($reason) . '"' : '' ?>
data-item-id="<?= (int) $item['id'] ?>" data-item-name="<?= e((string) $item['name']) ?>"
data-price="<?= $price ?>" data-max="<?= max(0, $max) ?>">
<?= $reason !== '' ? e($reason) : 'Beantragen' ?>
</button>
</div>
<?php endforeach; ?>
</div>
<p class="text-muted warehouse-no-match" id="shop-no-match" hidden>Kein Gegenstand passt zur Suche.</p>
<?php endif; ?>
</div>
<div class="panel" id="antraege">
<h2>Meine Anträge</h2>
<?php if (empty($myOrders)): ?>
<p class="text-muted">Du hast noch nichts beantragt.</p>
<?php else: ?>
<div class="shop-orders">
<?php foreach ($myOrders as $order): ?>
<?php include __DIR__ . '/includes/shop_order_row.php'; ?>
<?php endforeach; ?>
</div>
<div class="warehouse-pages">
<span class="text-muted">
Anträge <?= ($page - 1) * $perPage + 1 ?>–<?= min($page * $perPage, $totalOrders) ?>
von <?= number_format($totalOrders, 0, ',', '.') ?>
</span>
<?php render_pagination('/shop.php?', $page, $pageCount, '#antraege'); ?>
</div>
<?php endif; ?>
</div>
<!-- Beantragen -->
<div class="modal-overlay" id="shop-buy-modal" <?= !empty($old) ? '' : 'hidden' ?>>
<div class="modal">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2>Beantragen</h2>
<form method="post" action="/shop_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="order">
<input type="hidden" name="item_id" id="shop-buy-item" value="<?= e((string) ($old['item_id'] ?? '')) ?>">
<p class="shop-buy-title"><strong id="shop-buy-name"><?= e((string) ($old['item_name'] ?? '')) ?></strong></p>
<div class="warehouse-row">
<div>
<label for="shop-buy-quantity">Anzahl</label>
<input type="number" id="shop-buy-quantity" name="quantity" min="1" required value="<?= e((string) ($old['quantity'] ?? '1')) ?>">
</div>
<div>
<label>Kosten</label>
<div class="shop-buy-total"><?= contribution_coin(20) ?> <span id="shop-buy-total">0</span></div>
</div>
</div>
<div>
<label for="shop-buy-note">Bemerkung <span class="text-muted">(optional, z.B. Name deines Charakters)</span></label>
<input type="text" id="shop-buy-note" name="note" maxlength="255" value="<?= e((string) ($old['note'] ?? '')) ?>">
</div>
<p class="text-muted shop-buy-hint">Die Lumipunkte werden erst abgezogen, wenn dein Antrag bewilligt ist. Bis dahin kannst du ihn zurückziehen.</p>
<div class="actions">
<button type="submit" class="button-success">Antrag stellen</button>
</div>
</form>
</div>
</div>
<script src="<?= e(asset_url('/assets/js/shop.js')) ?>"></script>
<?php include __DIR__ . '/includes/footer.php'; ?>

239
shop_action.php Normal file
View file

@ -0,0 +1,239 @@
<?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');
}

300
shop_manage.php Normal file
View file

@ -0,0 +1,300 @@
<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/shop.php';
require_permission('shop.manage');
warehouse_sync_catalog();
$categories = shop_categories();
$items = shop_items(false);
$pendingCount = shop_pending_count();
// Lagerhaus-Gegenstaende fuer die Vorschlagsliste (Bild/Verknuepfung) und zum Uebernehmen:
// alles, was auf Lager ist und noch nicht im Shop steht (ohne Kina).
$warehouseNames = db()->query('SELECT name FROM warehouse_items ORDER BY name')->fetchAll(PDO::FETCH_COLUMN);
$linkedIds = array_filter(array_map(static fn (array $i): int => (int) $i['warehouse_item_id'], $items));
$importable = array_values(array_filter(
warehouse_stock(),
static fn (array $row): bool => $row['category'] !== 'currency' && !in_array((int) $row['id'], $linkedIds, true)
));
// Eingaben nach einem Fehler (siehe shop_manage_action.php)
$old = $_SESSION['shop_item_form'] ?? null;
unset($_SESSION['shop_item_form']);
/** Daten eines Gegenstands fuer den Bearbeiten-Dialog. */
function shop_item_form_data(array $item): string
{
return (string) json_encode([
'id' => (int) $item['id'],
'name' => (string) $item['name'],
'category_id' => $item['category_id'] !== null ? (string) $item['category_id'] : '',
'description' => (string) ($item['description'] ?? ''),
'price' => (string) $item['price'],
'stock_mode' => (string) $item['stock_mode'],
'stock' => (string) $item['stock'],
'warehouse_item' => (string) ($item['warehouse_name'] ?? ''),
'active' => (bool) (int) $item['active'],
], JSON_UNESCAPED_UNICODE);
}
$pageTitle = 'Lumishop verwalten';
$containerWide = true;
include __DIR__ . '/includes/header.php';
?>
<div class="panel">
<div class="warehouse-head">
<div>
<h1>Lumishop verwalten</h1>
<p class="text-muted"><?= count($items) ?> Gegenstände, davon <?= count(array_filter($items, static fn (array $i): bool => (bool) (int) $i['active'])) ?> im Angebot.</p>
</div>
<div class="actions">
<a class="button button-secondary" href="/shop.php">Zum Shop</a>
<a class="button button-secondary" href="/shop_orders.php">Anträge<?= $pendingCount > 0 ? ' <span class="shop-count">' . $pendingCount . '</span>' : '' ?></a>
</div>
</div>
</div>
<div class="panel">
<div class="warehouse-head">
<h2>Gegenstände</h2>
<div class="actions">
<button type="button" class="button-success" data-open-modal="shop-item-modal" data-item="">+ Gegenstand anlegen</button>
<button type="button" class="button-secondary" data-open-modal="shop-import-modal" <?= empty($importable) ? 'disabled title="Alles, was im Lagerhaus liegt, steht schon im Shop"' : '' ?>>Aus dem Lagerhaus übernehmen</button>
</div>
</div>
<?php if (empty($items)): ?>
<p class="text-muted">Noch keine Gegenstände. Lege einen an oder übernimm Gegenstände aus dem Lagerhaus – deren Bestand gleicht der Shop dann automatisch ab.</p>
<?php else: ?>
<div class="table-scroll">
<table class="table-actions shop-manage-table">
<thead>
<tr>
<th>Gegenstand</th>
<th>Kategorie</th>
<th class="num">Preis</th>
<th>Bestand</th>
<th>Aktionen</th>
</tr>
</thead>
<tbody>
<?php foreach ($items as $item): ?>
<?php $stock = shop_stock($item); ?>
<tr class="<?= (int) $item['active'] ? '' : 'is-inactive' ?>">
<td>
<span class="warehouse-item-inline">
<?= shop_icon_html($item, 32) ?>
<span>
<?= e((string) $item['name']) ?>
<?php if (!(int) $item['active']): ?><span class="badge">nicht im Angebot</span><?php endif; ?>
</span>
</span>
</td>
<td><?= $item['category_name'] !== null ? e((string) $item['category_name']) : '<span class="text-muted">-</span>' ?></td>
<td class="num"><?= contribution_coin(16) ?> <?= contribution_format((int) $item['price']) ?></td>
<td>
<?php if ($item['stock_mode'] === 'unlimited'): ?>
Unbegrenzt
<?php else: ?>
<?= number_format((int) $stock, 0, ',', '.') ?>
<?php if ($item['stock_mode'] === 'warehouse'): ?>
<span class="badge shop-badge-warehouse" title="Bestand kommt aus dem Lagerhaus (<?= e((string) ($item['warehouse_name'] ?? '?')) ?>)">Lagerhaus</span>
<?php endif; ?>
<?php endif; ?>
<?php if ((int) $item['reserved'] > 0): ?>
<span class="text-muted">· <?= (int) $item['reserved'] ?> beantragt</span>
<?php endif; ?>
</td>
<td>
<div class="actions">
<button type="button" class="icon-button" title="Bearbeiten" aria-label="Bearbeiten"
data-open-modal="shop-item-modal" data-item="<?= e(shop_item_form_data($item)) ?>"><?= icon('edit') ?></button>
<form class="inline-form" method="post" action="/shop_manage_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="item_toggle">
<input type="hidden" name="item_id" value="<?= (int) $item['id'] ?>">
<button type="submit" class="icon-button" title="<?= (int) $item['active'] ? 'Aus dem Angebot nehmen' : 'Ins Angebot aufnehmen' ?>"
aria-label="<?= (int) $item['active'] ? 'Aus dem Angebot nehmen' : 'Ins Angebot aufnehmen' ?>"><?= icon((int) $item['active'] ? 'archive' : 'restore') ?></button>
</form>
<?php if ($item['stock_mode'] === 'manual'): ?>
<form class="inline-form" method="post" action="/shop_manage_action.php"
onsubmit="return confirm(<?= e(json_encode('„' . $item['name'] . '“ mit dem Lagerhaus verknüpfen?' . ((int) $item['stock'] > 0 ? ' Der Shop-Bestand von ' . (int) $item['stock'] . ' Stück wird dort eingelagert.' : '') . ' Danach kommt der Bestand automatisch aus dem Lagerhaus.', JSON_UNESCAPED_UNICODE)) ?>);">
<?= csrf_field() ?>
<input type="hidden" name="action" value="to_warehouse">
<input type="hidden" name="item_id" value="<?= (int) $item['id'] ?>">
<button type="submit" class="icon-button" title="Ins Lagerhaus übertragen und verknüpfen" aria-label="Ins Lagerhaus übertragen"><?= icon('box') ?></button>
</form>
<?php endif; ?>
<form class="inline-form" method="post" action="/shop_manage_action.php"
onsubmit="return confirm(<?= e(json_encode('„' . $item['name'] . '“ aus dem Shop löschen? Bisherige Anträge bleiben erhalten.', JSON_UNESCAPED_UNICODE)) ?>);">
<?= csrf_field() ?>
<input type="hidden" name="action" value="item_delete">
<input type="hidden" name="item_id" value="<?= (int) $item['id'] ?>">
<button type="submit" class="icon-button icon-button-danger" title="Löschen" aria-label="Löschen"><?= icon('trash') ?></button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
<div class="panel">
<h2>Kategorien</h2>
<p class="text-muted">Die Reihenfolge bestimmt, wie die Kategorien im Shop sortiert sind (kleinere Zahl zuerst).</p>
<div class="shop-categories">
<?php foreach ($categories as $category): ?>
<div class="shop-category-row">
<form method="post" action="/shop_manage_action.php" class="shop-category-form">
<?= csrf_field() ?>
<input type="hidden" name="action" value="category_save">
<input type="hidden" name="category_id" value="<?= (int) $category['id'] ?>">
<input type="text" name="name" maxlength="80" required value="<?= e((string) $category['name']) ?>" aria-label="Name">
<input type="number" name="sort_order" value="<?= (int) $category['sort_order'] ?>" class="shop-sort-input" aria-label="Reihenfolge" title="Reihenfolge">
<button type="submit" class="button-secondary button-small">Speichern</button>
</form>
<form method="post" action="/shop_manage_action.php" class="inline-form"
onsubmit="return confirm(<?= e(json_encode('Kategorie „' . $category['name'] . '“ löschen? Ihre Gegenstände bleiben ohne Kategorie im Shop.', JSON_UNESCAPED_UNICODE)) ?>);">
<?= csrf_field() ?>
<input type="hidden" name="action" value="category_delete">
<input type="hidden" name="category_id" value="<?= (int) $category['id'] ?>">
<button type="submit" class="icon-button icon-button-danger" title="Kategorie löschen" aria-label="Kategorie löschen"><?= icon('trash') ?></button>
</form>
</div>
<?php endforeach; ?>
<form method="post" action="/shop_manage_action.php" class="shop-category-form shop-category-new">
<?= csrf_field() ?>
<input type="hidden" name="action" value="category_save">
<input type="text" name="name" maxlength="80" required placeholder="Neue Kategorie, z.B. Ausrüstung" aria-label="Neue Kategorie">
<input type="number" name="sort_order" value="<?= count($categories) * 10 + 10 ?>" class="shop-sort-input" aria-label="Reihenfolge" title="Reihenfolge">
<button type="submit" class="button-small">+ Anlegen</button>
</form>
</div>
</div>
<!-- Gegenstand anlegen / bearbeiten -->
<div class="modal-overlay" id="shop-item-modal" <?= $old !== null ? '' : 'hidden' ?>
data-old="<?= $old !== null ? e((string) json_encode($old, JSON_UNESCAPED_UNICODE)) : '' ?>">
<div class="modal">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2 id="shop-item-title">Gegenstand anlegen</h2>
<form method="post" action="/shop_manage_action.php" id="shop-item-form">
<?= csrf_field() ?>
<input type="hidden" name="action" value="item_save">
<input type="hidden" name="item_id" value="">
<div>
<label for="shop-item-name">Name</label>
<input type="text" id="shop-item-name" name="name" maxlength="150" required list="shop-warehouse-list" autocomplete="off">
</div>
<div class="warehouse-row">
<div>
<label for="shop-item-category">Kategorie</label>
<select id="shop-item-category" name="category_id">
<option value="">– ohne Kategorie –</option>
<?php foreach ($categories as $category): ?>
<option value="<?= (int) $category['id'] ?>"><?= e((string) $category['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="shop-item-price">Preis in Lumipunkten</label>
<input type="number" id="shop-item-price" name="price" min="0" max="<?= SHOP_MAX_PRICE ?>" required>
</div>
</div>
<div>
<label for="shop-item-description">Beschreibung <span class="text-muted">(optional)</span></label>
<textarea id="shop-item-description" name="description" maxlength="500" rows="2"></textarea>
</div>
<div class="warehouse-row">
<div>
<label for="shop-item-mode">Bestand</label>
<select id="shop-item-mode" name="stock_mode">
<?php foreach (SHOP_STOCK_MODES as $value => $label): ?>
<option value="<?= e($value) ?>"><?= e($label) ?></option>
<?php endforeach; ?>
</select>
</div>
<div data-mode-field="manual">
<label for="shop-item-stock">Stückzahl im Shop</label>
<input type="number" id="shop-item-stock" name="stock" min="0" max="<?= SHOP_MAX_STOCK ?>" value="0">
</div>
</div>
<div>
<label for="shop-item-warehouse">Lagerhaus-Gegenstand <span class="text-muted" data-mode-hint>(optional, für das Bild)</span></label>
<input type="text" id="shop-item-warehouse" name="warehouse_item" maxlength="150" list="shop-warehouse-list" autocomplete="off"
placeholder="Leer lassen = gleicher Name wie oben, falls es ihn im Lagerhaus gibt">
<div class="field-hint" data-mode-field="warehouse">Der Bestand im Shop ist der Lagerbestand dieses Gegenstands. Beim Bewilligen wird die Entnahme automatisch im Lagerhaus gebucht.</div>
</div>
<label class="checkbox-label">
<input type="checkbox" name="active" value="1" checked> Im Shop anbieten
</label>
<div class="actions">
<button type="submit" class="button-success">Speichern</button>
</div>
</form>
</div>
</div>
<datalist id="shop-warehouse-list">
<?php foreach ($warehouseNames as $name): ?>
<option value="<?= e((string) $name) ?>">
<?php endforeach; ?>
</datalist>
<!-- Aus dem Lagerhaus uebernehmen -->
<?php if (!empty($importable)): ?>
<div class="modal-overlay" id="shop-import-modal" hidden>
<div class="modal modal-wide">
<button type="button" class="modal-close icon-button" title="Schließen"><?= icon('x') ?></button>
<h2>Aus dem Lagerhaus übernehmen</h2>
<p class="text-muted">Die ausgewählten Gegenstände kommen in den Shop. Ihr Bestand wird laufend aus dem Lagerhaus übernommen, bewilligte Anträge werden dort automatisch als Entnahme gebucht.</p>
<form method="post" action="/shop_manage_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="import_warehouse">
<div class="warehouse-row">
<div>
<label for="shop-import-category">Kategorie für alle</label>
<select id="shop-import-category" name="category_id">
<option value="">– ohne Kategorie –</option>
<?php foreach ($categories as $category): ?>
<option value="<?= (int) $category['id'] ?>"><?= e((string) $category['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div>
<label for="shop-import-price">Preis für alle ausgewählten</label>
<div class="shop-import-price">
<input type="number" id="shop-import-price" min="0" max="<?= SHOP_MAX_PRICE ?>" placeholder="z.B. 50">
<button type="button" class="button-secondary button-small" id="shop-import-apply">Übernehmen</button>
</div>
</div>
</div>
<div class="shop-import-list">
<label class="shop-import-row shop-import-all">
<input type="checkbox" id="shop-import-all"> <strong>Alle auswählen</strong>
</label>
<?php foreach ($importable as $row): ?>
<div class="shop-import-row">
<label>
<input type="checkbox" name="warehouse_ids[]" value="<?= (int) $row['id'] ?>" class="shop-import-check">
<?= warehouse_icon_html($row['icon'] ?? null, (string) $row['name'], 28) ?>
<span><?= e((string) $row['name']) ?></span>
<span class="text-muted"><?= number_format((int) $row['quantity'], 0, ',', '.') ?> auf Lager</span>
</label>
<input type="number" name="prices[<?= (int) $row['id'] ?>]" min="0" max="<?= SHOP_MAX_PRICE ?>" placeholder="Preis" class="shop-import-row-price" aria-label="Preis für <?= e((string) $row['name']) ?>">
</div>
<?php endforeach; ?>
</div>
<div class="actions">
<button type="submit" class="button-success">Ausgewählte übernehmen</button>
</div>
</form>
</div>
</div>
<?php endif; ?>
<script src="<?= e(asset_url('/assets/js/shop.js')) ?>"></script>
<?php include __DIR__ . '/includes/footer.php'; ?>

255
shop_manage_action.php Normal file
View file

@ -0,0 +1,255 @@
<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/shop.php';
require_permission('shop.manage');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect('/shop_manage.php');
}
verify_csrf();
$action = (string) ($_POST['action'] ?? '');
$userId = (int) current_user()['id'];
$pdo = db();
/** Zurueck in den Dialog, mit Fehlermeldung und den bisherigen Eingaben. */
function shop_item_fail(string $message): void
{
if (db()->inTransaction()) {
db()->rollBack();
}
$_SESSION['shop_item_form'] = [
'id' => (int) ($_POST['item_id'] ?? 0),
'name' => (string) ($_POST['name'] ?? ''),
'category_id' => (string) ($_POST['category_id'] ?? ''),
'description' => (string) ($_POST['description'] ?? ''),
'price' => (string) ($_POST['price'] ?? ''),
'stock_mode' => (string) ($_POST['stock_mode'] ?? 'manual'),
'stock' => (string) ($_POST['stock'] ?? '0'),
'warehouse_item' => (string) ($_POST['warehouse_item'] ?? ''),
'active' => !empty($_POST['active']),
];
set_flash('error', $message);
redirect('/shop_manage.php');
}
function shop_manage_done(string $type, string $message, string $anchor = ''): void
{
set_flash($type, $message);
redirect('/shop_manage.php' . $anchor);
}
/** Kategorie-ID aus dem Formular, null = ohne Kategorie; unbekannte IDs zaehlen als ohne. */
function shop_read_category(): ?int
{
$id = (int) ($_POST['category_id'] ?? 0);
if ($id <= 0) {
return null;
}
$stmt = db()->prepare('SELECT id FROM shop_categories WHERE id = ?');
$stmt->execute([$id]);
return $stmt->fetchColumn() !== false ? $id : null;
}
function shop_find_warehouse_item(string $name): ?array
{
if (trim($name) === '') {
return null;
}
$stmt = db()->prepare('SELECT id, name, category FROM warehouse_items WHERE name = ?');
$stmt->execute([trim($name)]);
return $stmt->fetch() ?: null;
}
$itemId = (int) ($_POST['item_id'] ?? 0);
switch ($action) {
// ---- Kategorie anlegen / umbenennen ----
case 'category_save':
$name = trim((string) ($_POST['name'] ?? ''));
if ($name === '' || mb_strlen($name) > 80) {
shop_manage_done('error', 'Bitte einen Kategorienamen mit höchstens 80 Zeichen angeben.');
}
$sort = (int) ($_POST['sort_order'] ?? 0);
$categoryId = (int) ($_POST['category_id'] ?? 0);
if ($categoryId > 0) {
$pdo->prepare('UPDATE shop_categories SET name = ?, sort_order = ? WHERE id = ?')->execute([$name, $sort, $categoryId]);
shop_manage_done('success', 'Kategorie „' . $name . '“ gespeichert.');
}
$pdo->prepare('INSERT INTO shop_categories (name, sort_order) VALUES (?, ?)')->execute([$name, $sort]);
shop_manage_done('success', 'Kategorie „' . $name . '“ angelegt.');
case 'category_delete':
$pdo->prepare('DELETE FROM shop_categories WHERE id = ?')->execute([(int) ($_POST['category_id'] ?? 0)]);
shop_manage_done('success', 'Kategorie gelöscht.');
// ---- Gegenstand anlegen / bearbeiten ----
case 'item_save':
$name = trim((string) ($_POST['name'] ?? ''));
if ($name === '' || mb_strlen($name) > 150) {
shop_item_fail('Bitte einen Namen mit höchstens 150 Zeichen angeben.');
}
$description = trim((string) ($_POST['description'] ?? ''));
if (mb_strlen($description) > 500) {
shop_item_fail('Die Beschreibung darf höchstens 500 Zeichen lang sein.');
}
$price = filter_var($_POST['price'] ?? '', FILTER_VALIDATE_INT);
if ($price === false || $price < 0 || $price > SHOP_MAX_PRICE) {
shop_item_fail('Bitte einen Preis zwischen 0 und ' . number_format(SHOP_MAX_PRICE, 0, ',', '.') . ' Lumipunkten angeben.');
}
$mode = (string) ($_POST['stock_mode'] ?? 'manual');
if (!isset(SHOP_STOCK_MODES[$mode])) {
$mode = 'manual';
}
$stock = 0;
if ($mode === 'manual') {
$stock = filter_var($_POST['stock'] ?? '', FILTER_VALIDATE_INT);
if ($stock === false || $stock < 0 || $stock > SHOP_MAX_STOCK) {
shop_item_fail('Bitte eine Stückzahl zwischen 0 und ' . number_format(SHOP_MAX_STOCK, 0, ',', '.') . ' angeben.');
}
}
// Lagerhaus-Verknuepfung: ausdruecklich angegeben oder - fuer das Bild - gleicher Name.
$warehouseName = trim((string) ($_POST['warehouse_item'] ?? ''));
$warehouse = shop_find_warehouse_item($warehouseName !== '' ? $warehouseName : $name);
if ($warehouseName !== '' && !$warehouse) {
shop_item_fail('„' . $warehouseName . '“ gibt es im Lagerhaus nicht. Bitte einen Namen aus der Vorschlagsliste wählen.');
}
if ($mode === 'warehouse' && !$warehouse) {
shop_item_fail('Für den Bestand aus dem Lagerhaus bitte angeben, welcher Lagerhaus-Gegenstand gemeint ist.');
}
if ($mode === 'warehouse') {
$dup = $pdo->prepare("SELECT name FROM shop_items WHERE warehouse_item_id = ? AND stock_mode = 'warehouse' AND id <> ?");
$dup->execute([(int) $warehouse['id'], $itemId]);
$dupName = $dup->fetchColumn();
if ($dupName !== false) {
shop_item_fail('„' . $warehouse['name'] . '“ aus dem Lagerhaus ist schon mit „' . $dupName . '“ im Shop verknüpft.');
}
}
$values = [
shop_read_category(), $name, $description !== '' ? $description : null, (int) $price, $mode, (int) $stock,
$warehouse ? (int) $warehouse['id'] : null, !empty($_POST['active']) ? 1 : 0,
];
if ($itemId > 0) {
$stmt = $pdo->prepare(
'UPDATE shop_items SET category_id = ?, name = ?, description = ?, price = ?, stock_mode = ?, stock = ?,
warehouse_item_id = ?, active = ?, updated_at = NOW() WHERE id = ?'
);
$stmt->execute([...$values, $itemId]);
shop_manage_done('success', '„' . $name . '“ gespeichert.');
}
$pdo->prepare(
'INSERT INTO shop_items (category_id, name, description, price, stock_mode, stock, warehouse_item_id, active, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
)->execute([...$values, $userId]);
shop_manage_done('success', '„' . $name . '“ angelegt.');
case 'item_toggle':
$pdo->prepare('UPDATE shop_items SET active = 1 - active, updated_at = NOW() WHERE id = ?')->execute([$itemId]);
$item = shop_item($itemId);
shop_manage_done('success', $item ? '„' . $item['name'] . '“ ' . ((int) $item['active'] ? 'ist wieder im Angebot.' : 'aus dem Angebot genommen.') : 'Gespeichert.');
case 'item_delete':
$item = shop_item($itemId);
if (!$item) {
shop_manage_done('error', 'Diesen Gegenstand gibt es nicht mehr.');
}
// Offene Antraege brauchen den Gegenstand noch (Bestand beim Bewilligen/Stornieren).
$open = $pdo->prepare("SELECT COUNT(*) FROM shop_orders WHERE item_id = ? AND status IN ('pending', 'approved')");
$open->execute([$itemId]);
if ((int) $open->fetchColumn() > 0) {
shop_manage_done('error', 'Für „' . $item['name'] . '“ gibt es noch offene oder nicht übergebene Anträge. Bitte erst diese abschließen - oder den Gegenstand nur aus dem Angebot nehmen.');
}
$pdo->prepare('DELETE FROM shop_items WHERE id = ?')->execute([$itemId]);
shop_manage_done('success', '„' . $item['name'] . '“ gelöscht.');
// ---- Lagerhaus -> Shop: Gegenstaende mit Lagerbestand uebernehmen ----
case 'import_warehouse':
$ids = array_values(array_unique(array_filter(array_map('intval', (array) ($_POST['warehouse_ids'] ?? [])))));
if (empty($ids)) {
shop_manage_done('error', 'Bitte mindestens einen Gegenstand auswählen.');
}
$prices = (array) ($_POST['prices'] ?? []);
$categoryId = shop_read_category();
$pdo->beginTransaction();
$find = $pdo->prepare("SELECT id, name FROM warehouse_items WHERE id = ? AND category <> 'currency'");
$linked = $pdo->prepare("SELECT 1 FROM shop_items WHERE warehouse_item_id = ? AND stock_mode = 'warehouse'");
$insert = $pdo->prepare(
"INSERT INTO shop_items (category_id, name, price, stock_mode, warehouse_item_id, active, created_by)
VALUES (?, ?, ?, 'warehouse', ?, 1, ?)"
);
$added = [];
foreach ($ids as $warehouseId) {
$price = filter_var($prices[$warehouseId] ?? '', FILTER_VALIDATE_INT);
$find->execute([$warehouseId]);
$warehouse = $find->fetch();
if (!$warehouse) {
continue;
}
if ($price === false || $price < 0 || $price > SHOP_MAX_PRICE) {
$pdo->rollBack();
shop_manage_done('error', 'Bitte für „' . $warehouse['name'] . '“ einen Preis zwischen 0 und ' . number_format(SHOP_MAX_PRICE, 0, ',', '.') . ' angeben.');
}
$linked->execute([$warehouseId]);
if ($linked->fetchColumn()) {
continue; // schon im Shop
}
$insert->execute([$categoryId, $warehouse['name'], (int) $price, $warehouseId, $userId]);
$added[] = $warehouse['name'];
}
$pdo->commit();
shop_manage_done('success', count($added) === 1
? '„' . $added[0] . '“ in den Shop übernommen.'
: count($added) . ' Gegenstände in den Shop übernommen.');
// ---- Shop -> Lagerhaus: eigenen Bestand einlagern und kuenftig aus dem Lagerhaus fuehren ----
case 'to_warehouse':
$pdo->beginTransaction();
$stmt = $pdo->prepare('SELECT * FROM shop_items WHERE id = ? FOR UPDATE');
$stmt->execute([$itemId]);
$item = $stmt->fetch();
if (!$item || $item['stock_mode'] !== 'manual') {
$pdo->rollBack();
shop_manage_done('error', 'Dieser Gegenstand führt keinen eigenen Bestand im Shop.');
}
// Verknuepften Lagerhaus-Gegenstand nehmen, sonst einen mit gleichem Namen, sonst neu anlegen.
$warehouseId = (int) ($item['warehouse_item_id'] ?? 0);
if ($warehouseId === 0) {
$warehouse = shop_find_warehouse_item((string) $item['name']);
if ($warehouse) {
$warehouseId = (int) $warehouse['id'];
} else {
$pdo->prepare("INSERT INTO warehouse_items (name, category, source, created_by) VALUES (?, 'other', 'custom', ?)")
->execute([$item['name'], $userId]);
$warehouseId = (int) $pdo->lastInsertId();
}
}
$dup = $pdo->prepare("SELECT name FROM shop_items WHERE warehouse_item_id = ? AND stock_mode = 'warehouse' AND id <> ?");
$dup->execute([$warehouseId, $itemId]);
$dupName = $dup->fetchColumn();
if ($dupName !== false) {
$pdo->rollBack();
shop_manage_done('error', 'Dieser Lagerhaus-Gegenstand ist schon mit „' . $dupName . '“ im Shop verknüpft.');
}
$stock = (int) $item['stock'];
if ($stock > 0) {
$pdo->prepare(
"INSERT INTO warehouse_movements (item_id, direction, quantity, occurred_at, counterpart_name, note, created_by)
VALUES (?, 'in', ?, ?, 'Lumishop', 'Bestand aus dem Lumishop übertragen', ?)"
)->execute([$warehouseId, $stock, shop_now(), $userId]);
}
$pdo->prepare("UPDATE shop_items SET stock_mode = 'warehouse', stock = 0, warehouse_item_id = ?, updated_at = NOW() WHERE id = ?")
->execute([$warehouseId, $itemId]);
$pdo->commit();
shop_manage_done('success', '„' . $item['name'] . '“ ist jetzt mit dem Lagerhaus verknüpft'
. ($stock > 0 ? ' - ' . $stock . ' Stück dort eingelagert.' : '.'));
default:
redirect('/shop_manage.php');
}

81
shop_orders.php Normal file
View file

@ -0,0 +1,81 @@
<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/shop.php';
require_permission('shop.manage');
$tabs = [
'open' => ['label' => 'Offen', 'statuses' => ['pending']],
'delivery' => ['label' => 'Zur Übergabe', 'statuses' => ['approved']],
'done' => ['label' => 'Erledigt', 'statuses' => ['delivered', 'rejected', 'cancelled']],
];
$tab = isset($tabs[$_GET['tab'] ?? '']) ? (string) $_GET['tab'] : 'open';
$counts = [];
foreach ($tabs as $key => $def) {
$counts[$key] = shop_order_count($def['statuses'], null);
}
$perPage = 25;
$total = $counts[$tab];
$pageCount = max(1, (int) ceil($total / $perPage));
$page = min($pageCount, max(1, (int) ($_GET['page'] ?? 1)));
$orders = shop_orders($tabs[$tab]['statuses'], null, $perPage, ($page - 1) * $perPage);
// Punktestand der Antragsteller - zeigt schon vor dem Bewilligen, ob es reicht.
$balances = [];
foreach ($orders as $order) {
$balances[(int) $order['user_id']] ??= contribution_user_balance((int) $order['user_id']);
}
$orderView = 'manage';
$orderReturn = '/shop_orders.php?tab=' . $tab . ($page > 1 ? '&page=' . $page : '');
$pageTitle = 'Lumishop-Anträge';
$containerWide = true;
include __DIR__ . '/includes/header.php';
?>
<div class="panel">
<div class="warehouse-head">
<div>
<h1>Lumishop-Anträge</h1>
<p class="text-muted">Bewilligen zieht die Lumipunkte ab und bucht bei Lagerhaus-Gegenständen die Entnahme. Danach den Gegenstand im Spiel überreichen und als übergeben markieren.</p>
</div>
<div class="actions">
<a class="button button-secondary" href="/shop.php">Zum Shop</a>
<a class="button button-secondary" href="/shop_manage.php">Shop verwalten</a>
</div>
</div>
<div class="filter-tabs">
<?php foreach ($tabs as $key => $def): ?>
<a class="filter-tab<?= $tab === $key ? ' active' : '' ?>" href="/shop_orders.php?tab=<?= e($key) ?>">
<?= e($def['label']) ?><?= $key !== 'done' ? ' (' . $counts[$key] . ')' : '' ?>
</a>
<?php endforeach; ?>
</div>
<?php if (empty($orders)): ?>
<p class="text-muted"><?= $tab === 'open' ? 'Keine offenen Anträge.' : ($tab === 'delivery' ? 'Nichts wartet auf die Übergabe.' : 'Noch keine erledigten Anträge.') ?></p>
<?php else: ?>
<div class="shop-orders">
<?php foreach ($orders as $order): ?>
<?php if ($order['status'] === 'pending'): ?>
<?php $buyerBalance = $balances[(int) $order['user_id']]; ?>
<div class="shop-order-balance<?= $buyerBalance < (int) $order['total_price'] ? ' is-short' : '' ?>">
Punktestand von <?= e((string) $order['buyer']) ?>: <?= contribution_coin(14) ?> <?= contribution_format($buyerBalance) ?>
<?= $buyerBalance < (int) $order['total_price'] ? ' – reicht nicht für diesen Antrag' : '' ?>
</div>
<?php endif; ?>
<?php include __DIR__ . '/includes/shop_order_row.php'; ?>
<?php endforeach; ?>
</div>
<div class="warehouse-pages">
<span class="text-muted">
Anträge <?= ($page - 1) * $perPage + 1 ?>–<?= min($page * $perPage, $total) ?> von <?= number_format($total, 0, ',', '.') ?>
</span>
<?php render_pagination('/shop_orders.php?tab=' . $tab . '&', $page, $pageCount, ''); ?>
</div>
<?php endif; ?>
</div>
<script src="<?= e(asset_url('/assets/js/shop.js')) ?>"></script>
<?php include __DIR__ . '/includes/footer.php'; ?>

View file

@ -183,6 +183,73 @@ CREATE TABLE IF NOT EXISTS warehouse_movements (
INDEX idx_warehouse_movements_time (occurred_at) INDEX idx_warehouse_movements_time (occurred_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------------------------
-- Lumishop
-- --------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS shop_categories (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(80) NOT NULL,
sort_order INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS shop_items (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
category_id INT UNSIGNED NULL,
name VARCHAR(150) NOT NULL,
description VARCHAR(500) NULL,
-- Preis in Lumipunkten pro Stueck
price INT UNSIGNED NOT NULL,
-- manual = eigener Bestand (stock), warehouse = Bestand des Lagerhaus-Gegenstands, unlimited
stock_mode ENUM('manual', 'warehouse', 'unlimited') NOT NULL DEFAULT 'manual',
stock INT UNSIGNED NOT NULL DEFAULT 0,
-- Verknuepfter Lagerhaus-Gegenstand: liefert das Bild und bei stock_mode = warehouse den Bestand
warehouse_item_id INT UNSIGNED NULL,
active TINYINT(1) NOT NULL DEFAULT 1,
created_by INT UNSIGNED NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NULL,
FOREIGN KEY (category_id) REFERENCES shop_categories(id) ON DELETE SET NULL,
FOREIGN KEY (warehouse_item_id) REFERENCES warehouse_items(id) ON DELETE SET NULL,
FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS shop_orders (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED NOT NULL,
item_id INT UNSIGNED NULL,
-- Name und Preis zum Zeitpunkt der Bestellung (bleiben, auch wenn der Gegenstand spaeter
-- geaendert oder geloescht wird)
item_name VARCHAR(150) NOT NULL,
quantity INT UNSIGNED NOT NULL,
unit_price INT UNSIGNED NOT NULL,
total_price INT UNSIGNED NOT NULL,
-- Bemerkung des Mitglieds (z.B. Charaktername)
note VARCHAR(255) NULL,
-- pending, approved, delivered, rejected, cancelled (SHOP_STATUSES in includes/shop.php)
status ENUM('pending', 'approved', 'delivered', 'rejected', 'cancelled') NOT NULL DEFAULT 'pending',
decision_note VARCHAR(255) NULL,
decided_by INT UNSIGNED NULL,
decided_at DATETIME NULL,
delivered_by INT UNSIGNED NULL,
delivered_at DATETIME NULL,
-- Die Vergabe mit dem Punkteabzug und die Entnahme im Lagerhaus (fuer eine Stornierung)
award_id INT UNSIGNED NULL,
warehouse_movement_id INT UNSIGNED NULL,
-- 1 = bei der Bewilligung wurde der eigene Bestand im Shop verringert
stock_taken TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES shop_items(id) ON DELETE SET NULL,
FOREIGN KEY (decided_by) REFERENCES users(id) ON DELETE SET NULL,
FOREIGN KEY (delivered_by) REFERENCES users(id) ON DELETE SET NULL,
FOREIGN KEY (award_id) REFERENCES contribution_awards(id) ON DELETE SET NULL,
FOREIGN KEY (warehouse_movement_id) REFERENCES warehouse_movements(id) ON DELETE SET NULL,
INDEX idx_shop_orders_status (status),
INDEX idx_shop_orders_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- -------------------------------------------------------------------------- -- --------------------------------------------------------------------------
-- Taktiken auf der Karte -- Taktiken auf der Karte
-- -------------------------------------------------------------------------- -- --------------------------------------------------------------------------

View file

@ -15,6 +15,15 @@ $kinaStmt->execute([WAREHOUSE_KINA]);
$kinaItem = $kinaStmt->fetch() ?: null; $kinaItem = $kinaStmt->fetch() ?: null;
$kinaBalance = $kinaItem ? warehouse_item_stock((int) $kinaItem['id']) : 0; $kinaBalance = $kinaItem ? warehouse_item_stock((int) $kinaItem['id']) : 0;
$itemStock = array_values(array_filter($stock, static fn (array $row): bool => $row['category'] !== 'currency')); $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)); $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). // Verlauf, optional nur fuer einen Gegenstand (Klick auf den Namen im Bestand).
@ -145,6 +154,11 @@ include __DIR__ . '/includes/header.php';
</span> </span>
<span class="warehouse-card-name"><?= e((string) $row['name']) ?></span> <span class="warehouse-card-name"><?= e((string) $row['name']) ?></span>
<span class="warehouse-card-category"><?= e(warehouse_category_label((string) $row['category'])) ?></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> </a>
<?php if ($canManage): ?> <?php if ($canManage): ?>
<div class="warehouse-card-actions"> <div class="warehouse-card-actions">