diff --git a/README.md b/README.md index 53bae5e..fec4a36 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,9 @@ und wird später ausgebaut. Fokus dieser Version ist der Mitglieder-/Admin-Berei direkt auf die Karte gezeichnet werden - Lumipunkte: Punkte für Raids, Events und andere Aktivitäten an einzelne oder viele 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 (wann, optional an wen), Gegenstandsliste aus dem Aion-2-Wiki mit rund 2.300 Einträgen - 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 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 Die Seite **Lagerhaus** (`warehouse.php`) führt Buch über die Gegenstände der Legion. diff --git a/assets/css/style.css b/assets/css/style.css index c8a7217..a9abed2 100644 --- a/assets/css/style.css +++ b/assets/css/style.css @@ -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 .warehouse-icon { background: none; } .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; } diff --git a/assets/js/shop.js b/assets/js/shop.js new file mode 100644 index 0000000..03dfafb --- /dev/null +++ b/assets/js/shop.js @@ -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; + }); + }); + } +})(); diff --git a/contributions.php b/contributions.php index fcc73f1..18ef540 100644 --- a/contributions.php +++ b/contributions.php @@ -197,6 +197,7 @@ include __DIR__ . '/includes/header.php'; } } $shownPoints = $mine ?? $uniform; + $isSystem = isset(CONTRIBUTION_SYSTEM_CATEGORIES[(string) $award['category']]); ?>
@@ -217,7 +218,7 @@ include __DIR__ . '/includes/header.php';
· - · vergeben von + · von
> Mitglieder anzeigen @@ -228,7 +229,7 @@ include __DIR__ . '/includes/header.php'; - +
@@ -242,7 +243,7 @@ include __DIR__ . '/includes/header.php';
- + diff --git a/contributions_action.php b/contributions_action.php index bb7273a..96655b3 100644 --- a/contributions_action.php +++ b/contributions_action.php @@ -11,6 +11,18 @@ verify_csrf(); $action = (string) ($_POST['action'] ?? ''); $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. */ function contribution_fail(string $message): void { @@ -85,6 +97,7 @@ switch ($action) { // ---- Ganze Vergabe loeschen ---- case 'delete_award': + contribution_guard_system((int) ($_POST['award_id'] ?? 0)); $stmt = $pdo->prepare('DELETE FROM contribution_awards WHERE id = ?'); $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.'); @@ -100,6 +113,7 @@ switch ($action) { set_flash('error', 'Diesen Eintrag gibt es nicht mehr.'); redirect('/contributions.php#verlauf'); } + contribution_guard_system($awardId); $pdo->beginTransaction(); $pdo->prepare('DELETE FROM contribution_entries WHERE id = ?')->execute([$entryId]); diff --git a/includes/contributions.php b/includes/contributions.php index 5092a1f..998f648 100644 --- a/includes/contributions.php +++ b/includes/contributions.php @@ -16,6 +16,12 @@ const CONTRIBUTION_CATEGORIES = [ '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 // contributions.view_all (oder contributions.manage). const CONTRIBUTION_PUBLIC_RANKS = 25; @@ -25,7 +31,7 @@ const CONTRIBUTION_MAX_POINTS = 10000; 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. */ diff --git a/includes/functions.php b/includes/functions.php index db1c80a..9aace7d 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -135,6 +135,7 @@ function icon(string $name): string 'chevron-down' => '', 'check' => '', 'heart' => '', + 'bag' => '', 'box' => '', ]; diff --git a/includes/header.php b/includes/header.php index 6875304..d0f2cf2 100644 --- a/includes/header.php +++ b/includes/header.php @@ -12,6 +12,16 @@ $canViewEvents = $currentUser && user_has_permission('events.view'); $canViewMap = $currentUser && user_has_permission('map.view'); $canViewWarehouse = $currentUser && user_has_permission('warehouse.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. $sidebarPoints = null; if ($canViewContributions && $shellUser) { @@ -40,6 +50,7 @@ $isEventsActive = $currentScript === 'events.php'; $isMapActive = $currentScript === 'map.php'; $isWarehouseActive = $currentScript === 'warehouse.php'; $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'; $isReportsActive = $currentScript === 'reports.php'; $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', 'contributions.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', 'users.php' => 'bg-admin', 'user_form.php' => 'bg-admin', @@ -126,6 +140,14 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($ Lumipunkte + + + Lumishop + 0): ?> + + + + Mitglieder diff --git a/includes/permissions.php b/includes/permissions.php index 90fd328..7f9de9d 100644 --- a/includes/permissions.php +++ b/includes/permissions.php @@ -25,6 +25,8 @@ const CORE_PERMISSIONS = [ ['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.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' => 'reports.view', 'description' => 'Eingegangene Reports einsehen'], ['key' => 'reports.manage', 'description' => 'Reports löschen/archivieren und die Punkte-Gewichtung verwalten'], diff --git a/includes/schema.php b/includes/schema.php index 8642d66..e2a5af0 100644 --- a/includes/schema.php +++ b/includes/schema.php @@ -11,7 +11,7 @@ declare(strict_types=1); */ // 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). @@ -86,6 +86,72 @@ CREATE TABLE IF NOT EXISTS contribution_entries ( FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, INDEX idx_contribution_entries_user (user_id) ) 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, 'raid_settings' => <<<'SQL' CREATE TABLE IF NOT EXISTS raid_settings ( diff --git a/includes/shop.php b/includes/shop.php new file mode 100644 index 0000000..bb220e1 --- /dev/null +++ b/includes/shop.php @@ -0,0 +1,215 @@ + '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> */ +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> + */ +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> + */ +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} */ +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'); +} diff --git a/includes/shop_order_row.php b/includes/shop_order_row.php new file mode 100644 index 0000000..fed1d3e --- /dev/null +++ b/includes/shop_order_row.php @@ -0,0 +1,105 @@ + 'badge-pending', + 'approved' => 'shop-badge-approved', + 'delivered' => 'badge-active', + 'rejected' => 'badge-disabled', + 'cancelled' => '', +][$status] ?? ''; +$return = $orderReturn ?? '/shop.php#antraege'; +?> +
+ +
+
+ + + # +
+
+ + · + + beantragt am + 1): ?> + · × + +
+ +
Bemerkung:
+ + +
+ + am + von + + · übergeben am + von + +
+ +
Vom Mitglied zurückgezogen.
+ + +
Grund:
+ +
+
+ +
+
+ + + + + + + + + +
+ + + + + + +
+ +
+ + + + + +
+
+ + + + + + +
+ + +
+ + + + +
+ +
+
diff --git a/shop.php b/shop.php new file mode 100644 index 0000000..24c847b --- /dev/null +++ b/shop.php @@ -0,0 +1,165 @@ + $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'; +?> +
+ +
+
+ + 1): ?> + + +
+ + +

Im Lumishop gibt es gerade nichts.

+ +
+ + +
+ + + + + + + + + + + +
+ +
+ + +
+ +
+

Meine Anträge

+ +

Du hast noch nichts beantragt.

+ +
+ + + +
+
+ + Anträge – + von + + +
+ +
+ + + + + + diff --git a/shop_action.php b/shop_action.php new file mode 100644 index 0000000..cab15a9 --- /dev/null +++ b/shop_action.php @@ -0,0 +1,239 @@ +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'); +} diff --git a/shop_manage.php b/shop_manage.php new file mode 100644 index 0000000..16da264 --- /dev/null +++ b/shop_manage.php @@ -0,0 +1,300 @@ +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'; +?> +
+
+
+

Lumishop verwalten

+

Gegenstände, davon (bool) (int) $i['active'])) ?> im Angebot.

+
+ +
+
+ +
+
+

Gegenstände

+
+ + +
+
+ + +

Noch keine Gegenstände. Lege einen an oder übernimm Gegenstände aus dem Lagerhaus – deren Bestand gleicht der Shop dann automatisch ab.

+ +
+ + + + + + + + + + + + + + + + + + + + + + +
GegenstandKategoriePreisBestandAktionen
+ + + + + nicht im Angebot + + + -' ?> + + Unbegrenzt + + + + Lagerhaus + + + 0): ?> + · beantragt + + +
+ +
+ + + + +
+ +
+ + + + +
+ +
+ + + + +
+
+
+
+ +
+ +
+

Kategorien

+

Die Reihenfolge bestimmt, wie die Kategorien im Shop sortiert sind (kleinere Zahl zuerst).

+
+ +
+
+ + + + + + +
+
+ + + + +
+
+ +
+ + + + + +
+
+
+ + + + + + + + + + + + + + diff --git a/shop_manage_action.php b/shop_manage_action.php new file mode 100644 index 0000000..1d2904c --- /dev/null +++ b/shop_manage_action.php @@ -0,0 +1,255 @@ +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'); +} diff --git a/shop_orders.php b/shop_orders.php new file mode 100644 index 0000000..75866fa --- /dev/null +++ b/shop_orders.php @@ -0,0 +1,81 @@ + ['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'; +?> +
+
+
+

Lumishop-Anträge

+

Bewilligen zieht die Lumipunkte ab und bucht bei Lagerhaus-Gegenständen die Entnahme. Danach den Gegenstand im Spiel überreichen und als übergeben markieren.

+
+ +
+ +
+ $def): ?> + + + + +
+ + +

+ +
+ + + +
+ Punktestand von : + +
+ + + +
+
+ + Anträge – von + + +
+ +
+ + + diff --git a/sql/schema.sql b/sql/schema.sql index 3f28b13..e5924d2 100644 --- a/sql/schema.sql +++ b/sql/schema.sql @@ -183,6 +183,73 @@ CREATE TABLE IF NOT EXISTS warehouse_movements ( INDEX idx_warehouse_movements_time (occurred_at) ) 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 -- -------------------------------------------------------------------------- diff --git a/warehouse.php b/warehouse.php index 62afc8a..f591eaa 100644 --- a/warehouse.php +++ b/warehouse.php @@ -15,6 +15,15 @@ $kinaStmt->execute([WAREHOUSE_KINA]); $kinaItem = $kinaStmt->fetch() ?: null; $kinaBalance = $kinaItem ? warehouse_item_stock((int) $kinaItem['id']) : 0; $itemStock = array_values(array_filter($stock, static fn (array $row): bool => $row['category'] !== 'currency')); +// Gegenstaende, die der Lumishop aus dem Lagerhaus verkauft - bekommen einen Hinweis mit Preis. +$shopPrices = []; +try { + $shopPrices = db()->query( + "SELECT warehouse_item_id, price FROM shop_items WHERE stock_mode = 'warehouse' AND active = 1 AND warehouse_item_id IS NOT NULL" + )->fetchAll(PDO::FETCH_KEY_PAIR); +} catch (PDOException $e) { + $shopPrices = []; +} $stockTotal = array_sum(array_map(static fn (array $row): int => (int) $row['quantity'], $itemStock)); // Verlauf, optional nur fuer einen Gegenstand (Klick auf den Namen im Bestand). @@ -145,6 +154,11 @@ include __DIR__ . '/includes/header.php'; + + + Lumishop · + +