Tour-Chat für Teilnehmer implementieren
This commit is contained in:
parent
569d939907
commit
a4cc8fd857
18 changed files with 1390 additions and 11 deletions
10
DEPLOY.md
10
DEPLOY.md
|
|
@ -109,6 +109,16 @@ verschlüsseltes Backup-Ziel).
|
|||
Falls sich DB-Zugangsdaten seit dem Backup geändert haben, `files/.env`
|
||||
auf dem Server entsprechend anpassen.
|
||||
|
||||
## Datenbank-Migrationen
|
||||
|
||||
Nach Schemaänderungen – z. B. für den Tour-Chat – die idempotente Migration
|
||||
ausführen:
|
||||
|
||||
```bash
|
||||
cd ~/repos/motorradig2027
|
||||
python3 tools/migrate_motorradig.py
|
||||
```
|
||||
|
||||
## Reguläres Deployment (alle App-Dateien)
|
||||
|
||||
```bash
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ Keine externen Composer-Abhängigkeiten.
|
|||
- Startseite und „Aktivitäten" (Inhalt in der Datenbank editierbar)
|
||||
- Mitgliederliste, Benutzerprofile mit Bild
|
||||
- Tourenplan mit Anmeldung, Zimmer-Buchung und Galerie
|
||||
- Tour-Chat für Teilnehmer (Polling, ungelesen, Push optional)
|
||||
- Rollen `GUEST` / `MEMBER` / `TOUR GUIDE` / `ADMIN`
|
||||
- Login/Logout, Registrierung, Passwort-Reset per E-Mail
|
||||
- PDF-Upload (Tourenplan)
|
||||
|
|
|
|||
|
|
@ -141,6 +141,51 @@ if (!tableExists($pdo, 'push_subscriptions')) {
|
|||
$out("Tabelle 'push_subscriptions' existiert bereits (übersprungen)");
|
||||
}
|
||||
|
||||
// Tour-Chat: Nachrichten
|
||||
if (!tableExists($pdo, 'tour_messages')) {
|
||||
$pdo->exec('CREATE TABLE `tour_messages` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`tour_id` int(11) NOT NULL,
|
||||
`user_id` bigint(20) unsigned NULL DEFAULT NULL,
|
||||
`type` varchar(20) NOT NULL DEFAULT \'user\',
|
||||
`body` text NOT NULL,
|
||||
`created_at` timestamp NULL DEFAULT NULL,
|
||||
`deleted_at` timestamp NULL DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `tour_messages_tour_id_id_index` (`tour_id`,`id`),
|
||||
KEY `tour_messages_user_id_index` (`user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;');
|
||||
$out("Tabelle 'tour_messages' angelegt");
|
||||
} else {
|
||||
$out("Tabelle 'tour_messages' existiert bereits (übersprungen)");
|
||||
}
|
||||
|
||||
// Tour-Chat: Lesestatus
|
||||
if (!tableExists($pdo, 'tour_chat_reads')) {
|
||||
$pdo->exec('CREATE TABLE `tour_chat_reads` (
|
||||
`tour_id` int(11) NOT NULL,
|
||||
`user_id` bigint(20) unsigned NOT NULL,
|
||||
`last_read_message_id` bigint(20) unsigned NOT NULL DEFAULT 0,
|
||||
`updated_at` timestamp NULL DEFAULT NULL,
|
||||
PRIMARY KEY (`tour_id`,`user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;');
|
||||
$out("Tabelle 'tour_chat_reads' angelegt");
|
||||
} else {
|
||||
$out("Tabelle 'tour_chat_reads' existiert bereits (übersprungen)");
|
||||
}
|
||||
|
||||
// Tour-Chat: Push-Drosselung
|
||||
if (!tableExists($pdo, 'tour_chat_push')) {
|
||||
$pdo->exec('CREATE TABLE `tour_chat_push` (
|
||||
`tour_id` int(11) NOT NULL,
|
||||
`last_sent_at` timestamp NULL DEFAULT NULL,
|
||||
PRIMARY KEY (`tour_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;');
|
||||
$out("Tabelle 'tour_chat_push' angelegt");
|
||||
} else {
|
||||
$out("Tabelle 'tour_chat_push' existiert bereits (übersprungen)");
|
||||
}
|
||||
|
||||
// Unbenutzte Tabellen entfernen
|
||||
foreach (['migrations', 'failed_jobs', 'galleries', 'gallery_items'] as $table) {
|
||||
if (tableExists($pdo, $table)) {
|
||||
|
|
|
|||
|
|
@ -985,3 +985,145 @@ body .datepicker-footer {
|
|||
border: 1px solid #dee2e6;
|
||||
border-radius: .5rem;
|
||||
}
|
||||
|
||||
/* Tour-Chat */
|
||||
.tour-chat-card {
|
||||
overflow: hidden;
|
||||
border: 0;
|
||||
border-radius: .85rem;
|
||||
box-shadow: 0 18px 40px rgba(15, 23, 42, .12);
|
||||
}
|
||||
|
||||
.tour-chat-messages {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: .7rem;
|
||||
min-height: 320px;
|
||||
height: 60vh;
|
||||
max-height: 560px;
|
||||
padding: 1rem;
|
||||
overflow-y: auto;
|
||||
background: #f8fafc;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
}
|
||||
|
||||
.tour-chat-message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-self: flex-start;
|
||||
max-width: 84%;
|
||||
}
|
||||
|
||||
.tour-chat-message.is-own {
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
.tour-chat-meta {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: .5rem;
|
||||
margin: 0 .25rem .18rem;
|
||||
color: #64748b;
|
||||
font-size: .73rem;
|
||||
}
|
||||
|
||||
.tour-chat-message.is-own .tour-chat-meta {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.tour-chat-meta strong {
|
||||
color: #334155;
|
||||
}
|
||||
|
||||
.tour-chat-bubble {
|
||||
padding: .58rem .78rem;
|
||||
color: #1e293b;
|
||||
background: #fff;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: .8rem;
|
||||
font-size: .95rem;
|
||||
line-height: 1.4;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.tour-chat-message.is-own .tour-chat-bubble {
|
||||
color: #fff;
|
||||
background: #2e7d5b;
|
||||
border-color: #2e7d5b;
|
||||
}
|
||||
|
||||
.tour-chat-delete {
|
||||
margin: .15rem .25rem 0;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.tour-chat-message.is-own .tour-chat-delete {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.tour-chat-delete-button {
|
||||
padding: 0;
|
||||
color: #94a3b8;
|
||||
background: none;
|
||||
border: 0;
|
||||
font-size: .7rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.tour-chat-delete-button:hover {
|
||||
color: #c0392b;
|
||||
}
|
||||
|
||||
.tour-chat-system {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
align-items: baseline;
|
||||
gap: .35rem;
|
||||
align-self: center;
|
||||
max-width: 90%;
|
||||
padding: .3rem .75rem;
|
||||
color: #64748b;
|
||||
background: #eef2f7;
|
||||
border-radius: 999px;
|
||||
font-size: .78rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tour-chat-system small {
|
||||
color: #94a3b8;
|
||||
font-size: .68rem;
|
||||
}
|
||||
|
||||
.tour-chat-empty {
|
||||
margin: auto;
|
||||
color: #94a3b8;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.tour-chat-composer {
|
||||
background: #fff;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
}
|
||||
|
||||
.tour-chat-composer textarea {
|
||||
min-height: 3.2rem;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.tour-chat-page .badge-light {
|
||||
color: #1e293b;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
@media (max-width: 575.98px) {
|
||||
.tour-chat-messages {
|
||||
height: 62vh;
|
||||
padding: .75rem;
|
||||
}
|
||||
|
||||
.tour-chat-message {
|
||||
max-width: 92%;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
299
motorradig/public/js/tour-chat.js
Normal file
299
motorradig/public/js/tour-chat.js
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
/*
|
||||
* Tour-Chat: Polling, Senden und Löschen ohne WebSockets.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var root = document.getElementById('tourChatMessages');
|
||||
if (!root) {
|
||||
return;
|
||||
}
|
||||
|
||||
var form = document.getElementById('tourChatForm');
|
||||
var input = document.getElementById('tourChatBody');
|
||||
var errorBox = document.getElementById('tourChatError');
|
||||
var counter = document.getElementById('tourChatCount');
|
||||
var messagesUrl = root.dataset.messagesUrl || '';
|
||||
var sendUrl = root.dataset.sendUrl || messagesUrl;
|
||||
var csrf = root.dataset.csrf || '';
|
||||
var lastId = parseInt(root.dataset.lastId, 10) || 0;
|
||||
var polling = false;
|
||||
var pollTimer = null;
|
||||
var pollInterval = 5000;
|
||||
|
||||
function setError(message) {
|
||||
if (errorBox) {
|
||||
errorBox.textContent = message || '';
|
||||
}
|
||||
}
|
||||
|
||||
function isNearBottom() {
|
||||
return root.scrollHeight - root.scrollTop - root.clientHeight < 100;
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
root.scrollTop = root.scrollHeight;
|
||||
}
|
||||
|
||||
function makeMessage(message) {
|
||||
var wrapper = document.createElement('div');
|
||||
wrapper.dataset.messageId = String(message.id);
|
||||
|
||||
if (message.type === 'system') {
|
||||
wrapper.className = 'tour-chat-system';
|
||||
|
||||
var text = document.createElement('span');
|
||||
text.textContent = message.body || '';
|
||||
wrapper.appendChild(text);
|
||||
|
||||
var time = document.createElement('small');
|
||||
time.textContent = message.time || '';
|
||||
wrapper.appendChild(time);
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
wrapper.className = 'tour-chat-message' + (message.own ? ' is-own' : '');
|
||||
|
||||
var meta = document.createElement('div');
|
||||
meta.className = 'tour-chat-meta';
|
||||
|
||||
var name = document.createElement('strong');
|
||||
name.textContent = message.own ? 'Du' : (message.user_name || 'Unbekannt');
|
||||
|
||||
var stamp = document.createElement('span');
|
||||
stamp.textContent = message.time || '';
|
||||
|
||||
meta.appendChild(name);
|
||||
meta.appendChild(stamp);
|
||||
wrapper.appendChild(meta);
|
||||
|
||||
var bubble = document.createElement('div');
|
||||
bubble.className = 'tour-chat-bubble';
|
||||
bubble.textContent = message.body || '';
|
||||
wrapper.appendChild(bubble);
|
||||
|
||||
if (message.can_delete) {
|
||||
var deleteForm = document.createElement('form');
|
||||
deleteForm.className = 'tour-chat-delete';
|
||||
deleteForm.method = 'post';
|
||||
deleteForm.action = sendUrl + '/' + encodeURIComponent(message.id) + '/delete';
|
||||
|
||||
var token = document.createElement('input');
|
||||
token.type = 'hidden';
|
||||
token.name = '_token';
|
||||
token.value = csrf;
|
||||
deleteForm.appendChild(token);
|
||||
|
||||
var button = document.createElement('button');
|
||||
button.type = 'submit';
|
||||
button.className = 'tour-chat-delete-button';
|
||||
button.textContent = 'Löschen';
|
||||
deleteForm.appendChild(button);
|
||||
|
||||
wrapper.appendChild(deleteForm);
|
||||
}
|
||||
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
function appendMessage(message) {
|
||||
if (!message || !message.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (root.querySelector('[data-message-id="' + message.id + '"]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
var empty = root.querySelector('.tour-chat-empty');
|
||||
if (empty) {
|
||||
empty.remove();
|
||||
}
|
||||
|
||||
root.appendChild(makeMessage(message));
|
||||
lastId = Math.max(lastId, parseInt(message.id, 10) || 0);
|
||||
root.dataset.lastId = String(lastId);
|
||||
}
|
||||
|
||||
function load() {
|
||||
if (polling || !messagesUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
polling = true;
|
||||
var nearBottom = isNearBottom();
|
||||
|
||||
fetch(messagesUrl + '?after=' + encodeURIComponent(lastId) + '&mark_read=1', {
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Accept': 'application/json' }
|
||||
}).then(function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error('HTTP ' + response.status);
|
||||
}
|
||||
return response.json();
|
||||
}).then(function (data) {
|
||||
(data.messages || []).forEach(appendMessage);
|
||||
|
||||
if (data.last_id) {
|
||||
lastId = Math.max(lastId, parseInt(data.last_id, 10) || 0);
|
||||
root.dataset.lastId = String(lastId);
|
||||
}
|
||||
|
||||
if (nearBottom) {
|
||||
scrollToBottom();
|
||||
}
|
||||
}).catch(function () {
|
||||
// Polling-Fehler still ignorieren; der nächste Versuch folgt.
|
||||
}).finally(function () {
|
||||
polling = false;
|
||||
});
|
||||
}
|
||||
|
||||
function updateCounter() {
|
||||
if (counter && input) {
|
||||
counter.textContent = String(input.value.length);
|
||||
}
|
||||
}
|
||||
|
||||
function send() {
|
||||
if (!form || !input || !sendUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
var body = input.value.trim();
|
||||
if (body === '') {
|
||||
setError('Bitte eine Nachricht eingeben.');
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
setError('');
|
||||
var button = form.querySelector('button[type="submit"]');
|
||||
if (button) {
|
||||
button.disabled = true;
|
||||
}
|
||||
|
||||
var data = new URLSearchParams();
|
||||
data.set('_token', csrf);
|
||||
data.set('body', input.value);
|
||||
|
||||
fetch(sendUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
|
||||
'X-CSRF-Token': csrf
|
||||
},
|
||||
body: data.toString()
|
||||
}).then(function (response) {
|
||||
return response.json().catch(function () { return {}; }).then(function (payload) {
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.error || 'Senden fehlgeschlagen.');
|
||||
}
|
||||
return payload;
|
||||
});
|
||||
}).then(function (payload) {
|
||||
input.value = '';
|
||||
updateCounter();
|
||||
if (payload.message) {
|
||||
appendMessage(payload.message);
|
||||
}
|
||||
scrollToBottom();
|
||||
input.focus();
|
||||
}).catch(function (error) {
|
||||
setError(error.message || 'Senden fehlgeschlagen.');
|
||||
}).finally(function () {
|
||||
if (button) {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (form) {
|
||||
form.addEventListener('submit', function (event) {
|
||||
event.preventDefault();
|
||||
send();
|
||||
});
|
||||
}
|
||||
|
||||
if (input) {
|
||||
input.addEventListener('input', function () {
|
||||
setError('');
|
||||
updateCounter();
|
||||
});
|
||||
input.addEventListener('keydown', function (event) {
|
||||
if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
|
||||
event.preventDefault();
|
||||
send();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
root.addEventListener('click', function (event) {
|
||||
var button = event.target.closest ? event.target.closest('.tour-chat-delete-button') : null;
|
||||
if (!button) {
|
||||
return;
|
||||
}
|
||||
|
||||
var deleteForm = button.closest('form');
|
||||
if (!deleteForm) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
if (!window.confirm('Diese Nachricht wirklich löschen?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(deleteForm.action, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
|
||||
'X-CSRF-Token': csrf
|
||||
},
|
||||
body: new URLSearchParams({ '_token': csrf }).toString()
|
||||
}).then(function (response) {
|
||||
return response.json().catch(function () { return {}; }).then(function (payload) {
|
||||
if (!response.ok) {
|
||||
throw new Error(payload.error || 'Löschen fehlgeschlagen.');
|
||||
}
|
||||
return payload;
|
||||
});
|
||||
}).then(function () {
|
||||
var message = button.closest('[data-message-id]');
|
||||
if (message) {
|
||||
message.remove();
|
||||
}
|
||||
}).catch(function (error) {
|
||||
setError(error.message || 'Löschen fehlgeschlagen.');
|
||||
});
|
||||
});
|
||||
|
||||
function schedule() {
|
||||
if (pollTimer) {
|
||||
window.clearInterval(pollTimer);
|
||||
}
|
||||
|
||||
pollTimer = window.setInterval(function () {
|
||||
if (!document.hidden) {
|
||||
load();
|
||||
}
|
||||
}, pollInterval);
|
||||
}
|
||||
|
||||
document.addEventListener('visibilitychange', function () {
|
||||
if (!document.hidden) {
|
||||
load();
|
||||
schedule();
|
||||
}
|
||||
});
|
||||
|
||||
updateCounter();
|
||||
scrollToBottom();
|
||||
load();
|
||||
schedule();
|
||||
})();
|
||||
304
motorradig/src/Controllers/TourChatController.php
Normal file
304
motorradig/src/Controllers/TourChatController.php
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Auth;
|
||||
use App\Models\Booking;
|
||||
use App\Models\PushSubscription;
|
||||
use App\Models\Tour;
|
||||
use App\Models\TourMessage;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Tour-Chat: geschlossener Chat pro Tour.
|
||||
*
|
||||
* Zugriff haben nur Teilnehmer der Tour, der zugeordnete Tour Guide und
|
||||
* Admins. Die Seite pollt alle paar Sekunden; es werden keine WebSockets
|
||||
* benötigt.
|
||||
*/
|
||||
class TourChatController
|
||||
{
|
||||
public function index(string $tour_id): void
|
||||
{
|
||||
$tour = Tour::find((int) $tour_id);
|
||||
$user = Auth::user();
|
||||
|
||||
if ($tour === null || $user === null) {
|
||||
redirect('/tour');
|
||||
}
|
||||
|
||||
if (!TourMessage::isAvailable()) {
|
||||
flash_set('error', 'Der Tour-Chat ist derzeit nicht verfügbar.');
|
||||
redirect('/tour/' . $tour->id);
|
||||
}
|
||||
|
||||
if (!Booking::canAccessTour((int) $tour->id, $user)) {
|
||||
app_log('warning', 'Tour-Chat Zugriff verweigert', [
|
||||
'tour_id' => (int) $tour->id,
|
||||
'user_id' => (int) $user->id,
|
||||
]);
|
||||
redirect('/tour/' . $tour->id);
|
||||
}
|
||||
|
||||
$messages = TourMessage::latestForTour((int) $tour->id, 200);
|
||||
$lastId = TourMessage::latestId((int) $tour->id);
|
||||
$canModerate = Tour::canManage((int) $tour->id, $user);
|
||||
|
||||
// Beim Öffnen gilt der Chat als gelesen.
|
||||
TourMessage::markRead((int) $tour->id, (int) $user->id, $lastId);
|
||||
|
||||
view('tour.chat', [
|
||||
'tour' => $tour,
|
||||
'messages' => array_map(
|
||||
fn(array $row): array => $this->normalizeMessage($row, $user, $canModerate),
|
||||
$messages
|
||||
),
|
||||
'lastId' => $lastId,
|
||||
'canModerate' => $canModerate,
|
||||
'participantCount' => Booking::countForTour((int) $tour->id),
|
||||
]);
|
||||
}
|
||||
|
||||
public function messages(string $tour_id): void
|
||||
{
|
||||
$tour = Tour::find((int) $tour_id);
|
||||
$user = Auth::user();
|
||||
|
||||
if ($tour === null || $user === null) {
|
||||
$this->respondJson(['error' => 'Nicht angemeldet.'], 401);
|
||||
}
|
||||
|
||||
if (!TourMessage::isAvailable()) {
|
||||
$this->respondJson(['error' => 'Der Tour-Chat ist derzeit nicht verfügbar.'], 503);
|
||||
}
|
||||
|
||||
if (!Booking::canAccessTour((int) $tour->id, $user)) {
|
||||
$this->respondJson(['error' => 'Kein Zugriff auf diesen Tour-Chat.'], 403);
|
||||
}
|
||||
|
||||
$after = max(0, (int) input('after', 0));
|
||||
$rows = TourMessage::forTour((int) $tour->id, $after, 100);
|
||||
$lastId = TourMessage::latestId((int) $tour->id);
|
||||
$canModerate = Tour::canManage((int) $tour->id, $user);
|
||||
|
||||
if ((string) input('mark_read', '0') === '1') {
|
||||
TourMessage::markRead((int) $tour->id, (int) $user->id, $lastId);
|
||||
}
|
||||
|
||||
$this->respondJson([
|
||||
'ok' => true,
|
||||
'messages' => array_map(
|
||||
fn(array $row): array => $this->normalizeMessage($row, $user, $canModerate),
|
||||
$rows
|
||||
),
|
||||
'last_id' => $lastId,
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(string $tour_id): void
|
||||
{
|
||||
$tour = Tour::find((int) $tour_id);
|
||||
$user = Auth::user();
|
||||
|
||||
if ($tour === null || $user === null) {
|
||||
$this->fail('Nicht angemeldet.', 401, '/tour');
|
||||
}
|
||||
|
||||
if (!TourMessage::isAvailable()) {
|
||||
$this->fail('Der Tour-Chat ist derzeit nicht verfügbar.', 503, '/tour/' . $tour->id);
|
||||
}
|
||||
|
||||
if (!Booking::canAccessTour((int) $tour->id, $user)) {
|
||||
$this->fail('Kein Zugriff auf diesen Tour-Chat.', 403, '/tour/' . $tour->id);
|
||||
}
|
||||
|
||||
$body = trim((string) input('body', ''));
|
||||
$body = str_replace(["\r\n", "\r"], "\n", $body);
|
||||
|
||||
if ($body === '') {
|
||||
$this->fail('Bitte eine Nachricht eingeben.', 422, '/tour/' . $tour->id . '/chat');
|
||||
}
|
||||
|
||||
if (mb_strlen($body) > 2000) {
|
||||
$this->fail('Die Nachricht darf höchstens 2000 Zeichen enthalten.', 422, '/tour/' . $tour->id . '/chat');
|
||||
}
|
||||
|
||||
$messageId = TourMessage::create((int) $tour->id, (int) $user->id, $body);
|
||||
|
||||
if ($messageId <= 0) {
|
||||
$this->fail('Die Nachricht konnte nicht gespeichert werden.', 500, '/tour/' . $tour->id . '/chat');
|
||||
}
|
||||
|
||||
TourMessage::markRead((int) $tour->id, (int) $user->id, $messageId);
|
||||
$this->queueChatPush($tour, $user);
|
||||
|
||||
$row = TourMessage::findForTour((int) $tour->id, $messageId);
|
||||
$canModerate = Tour::canManage((int) $tour->id, $user);
|
||||
|
||||
if ($this->wantsJson()) {
|
||||
$this->respondJson([
|
||||
'ok' => true,
|
||||
'message' => $row === null
|
||||
? null
|
||||
: $this->normalizeMessage($row, $user, $canModerate),
|
||||
]);
|
||||
}
|
||||
|
||||
redirect('/tour/' . $tour->id . '/chat');
|
||||
}
|
||||
|
||||
public function destroy(string $tour_id, string $message_id): void
|
||||
{
|
||||
$tour = Tour::find((int) $tour_id);
|
||||
$user = Auth::user();
|
||||
|
||||
if ($tour === null || $user === null) {
|
||||
$this->fail('Nicht angemeldet.', 401, '/tour');
|
||||
}
|
||||
|
||||
if (!Booking::canAccessTour((int) $tour->id, $user)) {
|
||||
$this->fail('Kein Zugriff auf diesen Tour-Chat.', 403, '/tour/' . $tour->id);
|
||||
}
|
||||
|
||||
$message = TourMessage::findForTour((int) $tour->id, (int) $message_id);
|
||||
|
||||
if ($message === null || $message['deleted_at'] !== null || (string) $message['type'] !== 'user') {
|
||||
$this->fail('Nachricht nicht gefunden.', 404, '/tour/' . $tour->id . '/chat');
|
||||
}
|
||||
|
||||
$ownerId = $message['user_id'] !== null ? (int) $message['user_id'] : 0;
|
||||
$canModerate = Tour::canManage((int) $tour->id, $user);
|
||||
|
||||
if ($ownerId !== (int) $user->id && !$canModerate) {
|
||||
$this->fail('Keine Berechtigung zum Löschen dieser Nachricht.', 403, '/tour/' . $tour->id . '/chat');
|
||||
}
|
||||
|
||||
TourMessage::softDelete((int) $tour->id, (int) $message_id);
|
||||
|
||||
if ($this->wantsJson()) {
|
||||
$this->respondJson(['ok' => true]);
|
||||
}
|
||||
|
||||
redirect('/tour/' . $tour->id . '/chat');
|
||||
}
|
||||
|
||||
private function normalizeMessage(array $row, User $user, bool $canModerate): array
|
||||
{
|
||||
$userId = $row['user_id'] !== null ? (int) $row['user_id'] : null;
|
||||
$createdAt = (string) ($row['created_at'] ?? '');
|
||||
$isSystem = (string) ($row['type'] ?? 'user') === 'system';
|
||||
$userName = (string) ($row['user_name'] ?? '');
|
||||
if (!$isSystem && $userName === '') {
|
||||
$userName = 'Unbekannt';
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => (int) $row['id'],
|
||||
'type' => $isSystem ? 'system' : 'user',
|
||||
'user_id' => $userId,
|
||||
'user_name' => $userName,
|
||||
'body' => (string) $row['body'],
|
||||
'created_at' => $createdAt,
|
||||
'time' => $createdAt !== '' ? date('d.m. H:i', strtotime($createdAt)) : '',
|
||||
'own' => !$isSystem && $userId !== null && $userId === (int) $user->id,
|
||||
'can_delete' => !$isSystem
|
||||
&& ($canModerate || ($userId !== null && $userId === (int) $user->id)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Plant eine Push-Benachrichtigung für die Tour ein. Sie wird erst nach
|
||||
* dem Senden der HTTP-Antwort im Shutdown ausgeführt, damit der Chat
|
||||
* schnell bleibt. Pro Tour höchstens alle fünf Minuten.
|
||||
*/
|
||||
private function queueChatPush(Tour $tour, User $sender): void
|
||||
{
|
||||
$tourId = (int) $tour->id;
|
||||
|
||||
if (!TourMessage::canNotify($tourId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Slot sofort reservieren, damit parallele Nachrichten nicht doppelt pushen.
|
||||
TourMessage::markNotified($tourId);
|
||||
|
||||
$senderId = (int) $sender->id;
|
||||
|
||||
register_shutdown_function(function () use ($tourId, $senderId): void {
|
||||
try {
|
||||
$tour = Tour::find($tourId);
|
||||
|
||||
if ($tour === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$recipients = Booking::userIdsForTour($tourId);
|
||||
$recipients[] = (int) $tour->tour_guide_id;
|
||||
$recipients = array_values(array_unique(array_filter(
|
||||
$recipients,
|
||||
fn(int $id): bool => $id > 0 && $id !== $senderId
|
||||
)));
|
||||
|
||||
if ($recipients === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$result = PushSubscription::sendToUsers($recipients, [
|
||||
'title' => 'Neue Nachricht im Tour-Chat',
|
||||
'body' => (string) $tour->name,
|
||||
'url' => '/tour/' . $tourId . '/chat',
|
||||
'tag' => 'tour-chat-' . $tourId,
|
||||
]);
|
||||
|
||||
if ($result['failed'] > 0) {
|
||||
app_log('warning', 'Tour-Chat Push teilweise fehlgeschlagen', [
|
||||
'tour_id' => $tourId,
|
||||
'sent' => $result['sent'],
|
||||
'failed' => $result['failed'],
|
||||
]);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
app_log('error', 'Tour-Chat Push fehlgeschlagen', [
|
||||
'tour_id' => $tourId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function fail(string $message, int $status, string $redirectTo): void
|
||||
{
|
||||
if ($this->wantsJson()) {
|
||||
$this->respondJson(['error' => $message], $status);
|
||||
}
|
||||
|
||||
flash_set('error', $message);
|
||||
redirect($redirectTo);
|
||||
}
|
||||
|
||||
private function wantsJson(): bool
|
||||
{
|
||||
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
|
||||
$requestedWith = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '';
|
||||
|
||||
return str_contains($accept, 'application/json')
|
||||
|| strtolower($requestedWith) === 'xmlhttprequest';
|
||||
}
|
||||
|
||||
private function respondJson(array $data, int $status = 200): void
|
||||
{
|
||||
http_response_code($status);
|
||||
header('Content-Type: application/json; charset=UTF-8');
|
||||
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
|
||||
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
|
||||
|
||||
// Antwort früh senden; registrierte Push-Jobs laufen danach im Shutdown.
|
||||
if (function_exists('fastcgi_finish_request')) {
|
||||
fastcgi_finish_request();
|
||||
}
|
||||
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@ use App\Models\Booking;
|
|||
use App\Models\PushSubscription;
|
||||
use App\Models\Tour;
|
||||
use App\Models\TourRoom;
|
||||
use App\Models\TourMessage;
|
||||
use App\Models\User;
|
||||
|
||||
class TourController
|
||||
|
|
@ -219,6 +220,7 @@ class TourController
|
|||
}
|
||||
|
||||
$this->notifyEvent($tour, false);
|
||||
$this->postChatSystem((int) $tour->id, 'Die Tour wurde angelegt. Hier könnt ihr euch austauschen.');
|
||||
|
||||
redirect('/tour');
|
||||
}
|
||||
|
|
@ -258,9 +260,16 @@ class TourController
|
|||
redirect('/tour');
|
||||
}
|
||||
|
||||
$current = Auth::user();
|
||||
$guide = User::find((int) $tour->tour_guide_id);
|
||||
$canManage = $this->canManageTour($tour);
|
||||
$tourImages = $this->tourImages((int) $tour->id);
|
||||
$canChat = $current !== null
|
||||
&& TourMessage::isAvailable()
|
||||
&& Booking::canAccessTour((int) $tour->id, $current);
|
||||
$chatUnread = $canChat
|
||||
? TourMessage::unreadCount((int) $tour->id, (int) $current->id)
|
||||
: 0;
|
||||
|
||||
$users = [];
|
||||
foreach (Booking::forTour((int) $tour->id) as $booking) {
|
||||
|
|
@ -281,6 +290,8 @@ class TourController
|
|||
'guide' => $guide,
|
||||
'tourImages' => $tourImages,
|
||||
'canManage' => $canManage,
|
||||
'canChat' => $canChat,
|
||||
'chatUnread' => $chatUnread,
|
||||
]);
|
||||
|
||||
return;
|
||||
|
|
@ -298,6 +309,8 @@ class TourController
|
|||
'tourImages' => $tourImages,
|
||||
'rooms' => $rooms,
|
||||
'canManage' => $canManage,
|
||||
'canChat' => $canChat,
|
||||
'chatUnread' => $chatUnread,
|
||||
]);
|
||||
}
|
||||
|
||||
|
|
@ -404,6 +417,9 @@ class TourController
|
|||
|
||||
if ($tour->is_cancelled && !$wasCancelled) {
|
||||
$this->notifyEvent($tour, true);
|
||||
$this->postChatSystem($tourId, 'Die Tour wurde abgesagt.');
|
||||
} elseif (!$tour->is_cancelled && $wasCancelled) {
|
||||
$this->postChatSystem($tourId, 'Die Tour wurde wieder aktiviert.');
|
||||
}
|
||||
|
||||
redirect('/tour/' . $tourId . '/edit');
|
||||
|
|
@ -429,6 +445,7 @@ class TourController
|
|||
// Abhängige Daten zuerst entfernen.
|
||||
db()->execute('DELETE FROM `bookings` WHERE tour_id = ?', [$tourId]);
|
||||
db()->execute('DELETE FROM `tour_rooms` WHERE tour_id = ?', [$tourId]);
|
||||
TourMessage::deleteForTour($tourId);
|
||||
db()->execute('DELETE FROM `tours` WHERE id = ?', [$tourId]);
|
||||
|
||||
// Galerie und Tourbilder von der Festplatte entfernen.
|
||||
|
|
@ -681,6 +698,7 @@ class TourController
|
|||
}
|
||||
|
||||
Booking::joinRoom((int) $tour->id, (int) $user->id, $roomId);
|
||||
$this->postChatSystem((int) $tour->id, $user->name . ' hat die Tour gebucht.');
|
||||
redirect('/tour/' . $tour_id);
|
||||
}
|
||||
|
||||
|
|
@ -693,9 +711,35 @@ class TourController
|
|||
}
|
||||
|
||||
$userId = (int) input('user_id', 0);
|
||||
$roomId = (int) $room_id;
|
||||
|
||||
if ($userId > 0) {
|
||||
Booking::joinRoom((int) $tour->id, $userId, (int) $room_id);
|
||||
if ($roomId > 0 && TourRoom::findForTour($roomId, (int) $tour->id) === null) {
|
||||
redirect('/tour/' . $tour_id . '/edit');
|
||||
}
|
||||
|
||||
Booking::joinRoom((int) $tour->id, $userId, $roomId);
|
||||
|
||||
$participant = User::find($userId);
|
||||
|
||||
if ($participant !== null) {
|
||||
if ($roomId > 0) {
|
||||
$room = TourRoom::findForTour($roomId, (int) $tour->id);
|
||||
$roomName = $room !== null ? (string) $room['name'] : '';
|
||||
$roomLabel = $roomName !== ''
|
||||
? 'dem ' . $roomName . ' (ID ' . $roomId . ')'
|
||||
: 'einem Zimmer';
|
||||
$this->postChatSystem(
|
||||
(int) $tour->id,
|
||||
$participant->name . ' wurde ' . $roomLabel . ' zugeordnet.'
|
||||
);
|
||||
} else {
|
||||
$this->postChatSystem(
|
||||
(int) $tour->id,
|
||||
'Die Zimmerzuordnung von ' . $participant->name . ' wurde entfernt.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
redirect('/tour/' . $tour_id . '/edit');
|
||||
|
|
@ -717,7 +761,13 @@ class TourController
|
|||
redirect('/tour/' . $tour_id);
|
||||
}
|
||||
|
||||
$participant = User::find((int) $user_id);
|
||||
Booking::deleteForUser((int) $tour_id, (int) $user_id);
|
||||
|
||||
if ($participant !== null) {
|
||||
$this->postChatSystem((int) $tour_id, $participant->name . ' wurde aus der Tour entfernt.');
|
||||
}
|
||||
|
||||
redirect('/tour/' . $tour_id);
|
||||
}
|
||||
|
||||
|
|
@ -730,6 +780,10 @@ class TourController
|
|||
}
|
||||
|
||||
Tour::createRoom((int) $tour->id, (int) $capacity);
|
||||
$this->postChatSystem(
|
||||
(int) $tour->id,
|
||||
(int) $capacity === 1 ? 'Ein Einzelzimmer wurde erstellt.' : 'Ein Doppelzimmer wurde erstellt.'
|
||||
);
|
||||
redirect('/tour/' . $tour_id . '/edit');
|
||||
}
|
||||
|
||||
|
|
@ -741,18 +795,37 @@ class TourController
|
|||
redirect('/tour');
|
||||
}
|
||||
|
||||
$room = TourRoom::findForTour((int) $room_id, (int) $tour->id);
|
||||
|
||||
db()->execute('UPDATE `bookings` SET room_id = NULL WHERE room_id = ?', [(int) $room_id]);
|
||||
db()->execute('DELETE FROM `tour_rooms` WHERE tour_id = ? AND id = ?', [(int) $tour->id, (int) $room_id]);
|
||||
|
||||
$roomName = $room !== null ? (string) $room['name'] : '';
|
||||
$this->postChatSystem(
|
||||
(int) $tour->id,
|
||||
$roomName !== ''
|
||||
? 'Das ' . $roomName . ' (ID ' . (int) $room_id . ') wurde gelöscht.'
|
||||
: 'Ein Zimmer wurde gelöscht.'
|
||||
);
|
||||
|
||||
redirect('/tour/' . $tour_id . '/edit');
|
||||
}
|
||||
|
||||
private function canManageTour(?Tour $tour): bool
|
||||
{
|
||||
$user = Auth::user();
|
||||
return $tour !== null && Tour::canManage((int) $tour->id, Auth::user());
|
||||
}
|
||||
|
||||
return $user !== null
|
||||
&& $tour !== null
|
||||
&& ($user->isAdmin() || (int) $user->id === (int) $tour->tour_guide_id);
|
||||
/** Schreibt eine Systemnachricht in den Tour-Chat, ohne Buchungen zu blockieren. */
|
||||
private function postChatSystem(int $tourId, string $body): void
|
||||
{
|
||||
try {
|
||||
TourMessage::postSystem($tourId, $body);
|
||||
} catch (\Throwable $e) {
|
||||
app_log('error', 'Tour-Chat Systemnachricht fehlgeschlagen', [
|
||||
'tour_id' => $tourId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,10 +16,10 @@ class Booking extends Model
|
|||
}
|
||||
|
||||
/**
|
||||
* true, wenn der Benutzer die Bildergalerie einer Tour sehen darf:
|
||||
* true, wenn der Benutzer die geschützten Inhalte einer Tour sehen darf:
|
||||
* Admins immer, der eingetragene Tour Guide und Teilnehmer.
|
||||
*/
|
||||
public static function canAccessTourGallery(int $tourId, ?User $user): bool
|
||||
public static function canAccessTour(int $tourId, ?User $user): bool
|
||||
{
|
||||
if ($user === null || $tourId <= 0) {
|
||||
return false;
|
||||
|
|
@ -38,6 +38,23 @@ class Booking extends Model
|
|||
return static::forUser($tourId, (int) $user->id) !== null;
|
||||
}
|
||||
|
||||
/** true, wenn der Benutzer die Bildergalerie einer Tour sehen darf. */
|
||||
public static function canAccessTourGallery(int $tourId, ?User $user): bool
|
||||
{
|
||||
return static::canAccessTour($tourId, $user);
|
||||
}
|
||||
|
||||
/** Alle Teilnehmer-IDs einer Tour (für Chat-Benachrichtigungen). */
|
||||
public static function userIdsForTour(int $tourId): array
|
||||
{
|
||||
$rows = db()->fetchAll(
|
||||
'SELECT user_id FROM `bookings` WHERE tour_id = ?',
|
||||
[$tourId]
|
||||
);
|
||||
|
||||
return array_map(fn(array $row): int => (int) $row['user_id'], $rows);
|
||||
}
|
||||
|
||||
public static function forUser(int $tourId, int $userId): ?static
|
||||
{
|
||||
$row = db()->fetchOne('SELECT * FROM `bookings` WHERE tour_id = ? AND user_id = ?', [$tourId, $userId]);
|
||||
|
|
|
|||
|
|
@ -141,13 +141,52 @@ class PushSubscription
|
|||
*/
|
||||
public static function sendToAll(array $payload): array
|
||||
{
|
||||
$result = ['sent' => 0, 'removed' => 0, 'failed' => 0];
|
||||
|
||||
if (!WebPush::isConfigured()) {
|
||||
return $result;
|
||||
return ['sent' => 0, 'removed' => 0, 'failed' => 0];
|
||||
}
|
||||
|
||||
foreach (self::all() as $subscription) {
|
||||
return self::sendMany(self::all(), $payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Versendet eine Nachricht an die Abos bestimmter Benutzer.
|
||||
*
|
||||
* @param int[] $userIds
|
||||
* @return array{sent: int, removed: int, failed: int}
|
||||
*/
|
||||
public static function sendToUsers(array $userIds, array $payload): array
|
||||
{
|
||||
if (!WebPush::isConfigured() || !self::isAvailable()) {
|
||||
return ['sent' => 0, 'removed' => 0, 'failed' => 0];
|
||||
}
|
||||
|
||||
$ids = array_values(array_unique(array_filter(
|
||||
array_map('intval', $userIds),
|
||||
fn(int $id): bool => $id > 0
|
||||
)));
|
||||
|
||||
if ($ids === []) {
|
||||
return ['sent' => 0, 'removed' => 0, 'failed' => 0];
|
||||
}
|
||||
|
||||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||||
$subscriptions = db()->fetchAll(
|
||||
'SELECT * FROM `push_subscriptions` WHERE user_id IN (' . $placeholders . ')',
|
||||
$ids
|
||||
);
|
||||
|
||||
return self::sendMany($subscriptions, $payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $subscriptions
|
||||
* @return array{sent: int, removed: int, failed: int}
|
||||
*/
|
||||
private static function sendMany(array $subscriptions, array $payload): array
|
||||
{
|
||||
$result = ['sent' => 0, 'removed' => 0, 'failed' => 0];
|
||||
|
||||
foreach ($subscriptions as $subscription) {
|
||||
$send = WebPush::send($subscription, $payload);
|
||||
|
||||
if ($send['ok']) {
|
||||
|
|
|
|||
|
|
@ -54,4 +54,20 @@ class Tour extends Model
|
|||
[$name, $tourId, $capacity, now(), now()]
|
||||
);
|
||||
}
|
||||
|
||||
/** Admin oder der dieser Tour zugeordnete Tour Guide. */
|
||||
public static function canManage(int $tourId, ?User $user): bool
|
||||
{
|
||||
if ($user === null || $tourId <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($user->isAdmin()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$tour = static::find($tourId);
|
||||
|
||||
return $tour !== null && (int) $tour->tour_guide_id === (int) $user->id;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
245
motorradig/src/Models/TourMessage.php
Normal file
245
motorradig/src/Models/TourMessage.php
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
/**
|
||||
* Tour-Chat: Nachrichten, Lesestatus und Push-Drosselung.
|
||||
*
|
||||
* Die Tabellen werden über tools/migrate_motorradig.py bzw. bin/migrate.php
|
||||
* angelegt. Fehlen sie noch, liefern die Methoden leere Ergebnisse, statt die
|
||||
* Tour-Seite mit einem Fehler abzubrechen.
|
||||
*/
|
||||
class TourMessage
|
||||
{
|
||||
private static ?bool $available = null;
|
||||
|
||||
public static function isAvailable(): bool
|
||||
{
|
||||
if (self::$available !== null) {
|
||||
return self::$available;
|
||||
}
|
||||
|
||||
try {
|
||||
db()->fetchOne('SELECT 1 FROM `tour_messages` LIMIT 1');
|
||||
db()->fetchOne('SELECT 1 FROM `tour_chat_reads` LIMIT 1');
|
||||
self::$available = true;
|
||||
} catch (\PDOException $e) {
|
||||
self::$available = false;
|
||||
}
|
||||
|
||||
return self::$available;
|
||||
}
|
||||
|
||||
/** Letzte Nachrichten für die initiale Anzeige (chronologisch). */
|
||||
public static function latestForTour(int $tourId, int $limit = 200): array
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$limit = max(1, min(500, $limit));
|
||||
|
||||
$rows = db()->fetchAll(
|
||||
'SELECT m.*, u.name AS user_name
|
||||
FROM `tour_messages` m
|
||||
LEFT JOIN `users` u ON u.id = m.user_id
|
||||
WHERE m.tour_id = ? AND m.deleted_at IS NULL
|
||||
ORDER BY m.id DESC
|
||||
LIMIT ' . $limit,
|
||||
[$tourId]
|
||||
);
|
||||
|
||||
return array_reverse($rows);
|
||||
}
|
||||
|
||||
/** Neue Nachrichten nach einer bekannten ID (für das Polling). */
|
||||
public static function forTour(int $tourId, int $afterId = 0, int $limit = 100): array
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$limit = max(1, min(200, $limit));
|
||||
|
||||
return db()->fetchAll(
|
||||
'SELECT m.*, u.name AS user_name
|
||||
FROM `tour_messages` m
|
||||
LEFT JOIN `users` u ON u.id = m.user_id
|
||||
WHERE m.tour_id = ? AND m.id > ? AND m.deleted_at IS NULL
|
||||
ORDER BY m.id ASC
|
||||
LIMIT ' . $limit,
|
||||
[$tourId, max(0, $afterId)]
|
||||
);
|
||||
}
|
||||
|
||||
public static function latestId(int $tourId): int
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (int) db()->fetchValue(
|
||||
'SELECT COALESCE(MAX(id), 0) FROM `tour_messages` WHERE tour_id = ?',
|
||||
[$tourId]
|
||||
);
|
||||
}
|
||||
|
||||
public static function unreadCount(int $tourId, int $userId): int
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0 || $userId <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$lastRead = self::lastReadId($tourId, $userId);
|
||||
|
||||
return (int) db()->fetchValue(
|
||||
'SELECT COUNT(*)
|
||||
FROM `tour_messages`
|
||||
WHERE tour_id = ?
|
||||
AND id > ?
|
||||
AND deleted_at IS NULL
|
||||
AND (user_id IS NULL OR user_id <> ?)',
|
||||
[$tourId, $lastRead, $userId]
|
||||
);
|
||||
}
|
||||
|
||||
public static function lastReadId(int $tourId, int $userId): int
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0 || $userId <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$row = db()->fetchOne(
|
||||
'SELECT last_read_message_id FROM `tour_chat_reads` WHERE tour_id = ? AND user_id = ?',
|
||||
[$tourId, $userId]
|
||||
);
|
||||
|
||||
return $row === null ? 0 : (int) $row['last_read_message_id'];
|
||||
}
|
||||
|
||||
public static function markRead(int $tourId, int $userId, int $messageId): void
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0 || $userId <= 0 || $messageId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
db()->execute(
|
||||
'INSERT INTO `tour_chat_reads` (tour_id, user_id, last_read_message_id, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
last_read_message_id = GREATEST(last_read_message_id, ?),
|
||||
updated_at = ?',
|
||||
[$tourId, $userId, $messageId, now(), $messageId, now()]
|
||||
);
|
||||
}
|
||||
|
||||
public static function create(int $tourId, ?int $userId, string $body, string $type = 'user'): int
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return db()->insert(
|
||||
'INSERT INTO `tour_messages` (tour_id, user_id, type, body, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)',
|
||||
[$tourId, $userId, $type, $body, now()]
|
||||
);
|
||||
}
|
||||
|
||||
public static function postSystem(int $tourId, string $body): int
|
||||
{
|
||||
return self::create($tourId, null, $body, 'system');
|
||||
}
|
||||
|
||||
public static function findForTour(int $tourId, int $messageId): ?array
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0 || $messageId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return db()->fetchOne(
|
||||
'SELECT m.*, u.name AS user_name
|
||||
FROM `tour_messages` m
|
||||
LEFT JOIN `users` u ON u.id = m.user_id
|
||||
WHERE m.id = ? AND m.tour_id = ?
|
||||
LIMIT 1',
|
||||
[$messageId, $tourId]
|
||||
);
|
||||
}
|
||||
|
||||
public static function softDelete(int $tourId, int $messageId): bool
|
||||
{
|
||||
if (!self::isAvailable() || $tourId <= 0 || $messageId <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return db()->execute(
|
||||
'UPDATE `tour_messages`
|
||||
SET deleted_at = ?
|
||||
WHERE id = ? AND tour_id = ? AND deleted_at IS NULL',
|
||||
[now(), $messageId, $tourId]
|
||||
) > 0;
|
||||
}
|
||||
|
||||
/** Entfernt alle Chatdaten einer gelöschten Tour. */
|
||||
public static function deleteForTour(int $tourId): void
|
||||
{
|
||||
if ($tourId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (['tour_messages', 'tour_chat_reads', 'tour_chat_push'] as $table) {
|
||||
try {
|
||||
db()->execute('DELETE FROM `' . $table . '` WHERE tour_id = ?', [$tourId]);
|
||||
} catch (\PDOException $e) {
|
||||
// Tabelle fehlt noch (Migration nicht gelaufen) – ignorieren.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** true, wenn für diese Tour in den letzten 5 Minuten kein Push rausging. */
|
||||
public static function canNotify(int $tourId): bool
|
||||
{
|
||||
if ($tourId <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$row = db()->fetchOne(
|
||||
'SELECT last_sent_at FROM `tour_chat_push` WHERE tour_id = ?',
|
||||
[$tourId]
|
||||
);
|
||||
} catch (\PDOException $e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($row === null || empty($row['last_sent_at'])) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return strtotime((string) $row['last_sent_at']) < time() - 300;
|
||||
}
|
||||
|
||||
public static function markNotified(int $tourId): void
|
||||
{
|
||||
if ($tourId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
db()->execute(
|
||||
'INSERT INTO `tour_chat_push` (tour_id, last_sent_at)
|
||||
VALUES (?, ?)
|
||||
ON DUPLICATE KEY UPDATE last_sent_at = ?',
|
||||
[$tourId, now(), now()]
|
||||
);
|
||||
} catch (\PDOException $e) {
|
||||
app_log('warning', 'Tour-Chat Push-Drossel konnte nicht gespeichert werden', [
|
||||
'tour_id' => $tourId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -28,6 +28,18 @@ class TourRoom extends Model
|
|||
return $row !== null && (int) $row['booked'] < (int) $row['capacity'];
|
||||
}
|
||||
|
||||
public static function findForTour(int $roomId, int $tourId): ?array
|
||||
{
|
||||
if ($roomId <= 0 || $tourId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return db()->fetchOne(
|
||||
'SELECT * FROM `tour_rooms` WHERE id = ? AND tour_id = ?',
|
||||
[$roomId, $tourId]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liefert alle Räume einer Tour inkl. gebuchter Benutzer und freier
|
||||
* Plätze. Übernommen aus der ursprünglichen SQL-Abfrage (fetch_rooms).
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ use App\Controllers\AuthController;
|
|||
use App\Controllers\HomeController;
|
||||
use App\Controllers\UserController;
|
||||
use App\Controllers\TourController;
|
||||
use App\Controllers\TourChatController;
|
||||
use App\Controllers\GalleryController;
|
||||
use App\Controllers\AdminController;
|
||||
use App\Controllers\ImageController;
|
||||
|
|
@ -69,6 +70,12 @@ $router->post('/tour/{tour_id}/delete_room/{room_id}', [TourController::class, '
|
|||
$router->post('/tour/{tour_id}/images', [TourController::class, 'storeImages'], true);
|
||||
$router->post('/tour/{tour_id}/images/delete/{imageName}', [TourController::class, 'deleteImage'], true);
|
||||
|
||||
// Tour-Chat (Zugriff wird im Controller geprüft)
|
||||
$router->get('/tour/{tour_id}/chat', [TourChatController::class, 'index'], true);
|
||||
$router->get('/tour/{tour_id}/chat/messages', [TourChatController::class, 'messages'], true);
|
||||
$router->post('/tour/{tour_id}/chat/messages', [TourChatController::class, 'store'], true);
|
||||
$router->post('/tour/{tour_id}/chat/messages/{message_id}/delete', [TourChatController::class, 'destroy'], true);
|
||||
|
||||
// Bilder (Zugriff wird im Controller geprüft)
|
||||
$router->get('/img_storage/{category}/{imageName}', [ImageController::class, 'getImage']);
|
||||
|
||||
|
|
|
|||
|
|
@ -78,6 +78,13 @@
|
|||
<td class="text-center"><?= $yes ?></td>
|
||||
<td class="text-center"><?= $yes ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Tour-Chat der gebuchten Tour nutzen</td>
|
||||
<td class="text-center"><?= $no ?></td>
|
||||
<td class="text-center"><?= $yes ?></td>
|
||||
<td class="text-center"><?= $yes ?></td>
|
||||
<td class="text-center"><?= $yes ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong>Touren anlegen</strong></td>
|
||||
<td class="text-center"><?= $no ?></td>
|
||||
|
|
|
|||
88
motorradig/views/tour/chat.php
Normal file
88
motorradig/views/tour/chat.php
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
<?php
|
||||
$current = auth_check() ? user() : null;
|
||||
$flashError = flash_pull('error');
|
||||
$chatUrl = '/tour/' . (int) $tour->id . '/chat';
|
||||
$messagesUrl = $chatUrl . '/messages';
|
||||
?>
|
||||
|
||||
<div class="container tour-chat-page">
|
||||
<div class="row justify-content-center">
|
||||
<div class="col-lg-8">
|
||||
<div class="card tour-chat-card mt-4">
|
||||
<div class="card-header d-flex flex-wrap justify-content-between align-items-center">
|
||||
<div>
|
||||
<h5 class="mb-0">Tour-Chat</h5>
|
||||
<div class="small text-muted">
|
||||
<?= e($tour->name) ?> · <?= e($participantCount) ?> Teilnehmer
|
||||
</div>
|
||||
</div>
|
||||
<a href="/tour/<?= e($tour->id) ?>" class="btn btn-sm btn-outline-secondary mt-2 mt-sm-0">
|
||||
Zur Tour
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<?php if ($flashError !== null): ?>
|
||||
<div class="alert alert-danger mb-0 rounded-0" role="alert"><?= e($flashError) ?></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="tour-chat-messages" id="tourChatMessages"
|
||||
data-tour-id="<?= e($tour->id) ?>"
|
||||
data-last-id="<?= e($lastId) ?>"
|
||||
data-current-user-id="<?= e($current?->id ?? 0) ?>"
|
||||
data-messages-url="<?= e($messagesUrl) ?>"
|
||||
data-send-url="<?= e($messagesUrl) ?>"
|
||||
data-csrf="<?= e(csrf_token()) ?>">
|
||||
<?php if ($messages === []): ?>
|
||||
<p class="tour-chat-empty">Noch keine Nachrichten. Starte den Austausch!</p>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php foreach ($messages as $message): ?>
|
||||
<?php if ($message['type'] === 'system'): ?>
|
||||
<div class="tour-chat-system" data-message-id="<?= e($message['id']) ?>">
|
||||
<span><?= e($message['body']) ?></span>
|
||||
<small><?= e($message['time']) ?></small>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="tour-chat-message<?= $message['own'] ? ' is-own' : '' ?>"
|
||||
data-message-id="<?= e($message['id']) ?>">
|
||||
<div class="tour-chat-meta">
|
||||
<strong><?= $message['own'] ? 'Du' : e($message['user_name']) ?></strong>
|
||||
<span><?= e($message['time']) ?></span>
|
||||
</div>
|
||||
<div class="tour-chat-bubble"><?= e($message['body']) ?></div>
|
||||
<?php if ($message['can_delete']): ?>
|
||||
<form class="tour-chat-delete"
|
||||
action="<?= e($chatUrl . '/messages/' . $message['id'] . '/delete') ?>"
|
||||
method="post">
|
||||
<?= csrf_field() ?>
|
||||
<button type="submit" class="tour-chat-delete-button">Löschen</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
|
||||
<div class="card-body tour-chat-composer">
|
||||
<form id="tourChatForm" action="<?= e($messagesUrl) ?>" method="post">
|
||||
<?= csrf_field() ?>
|
||||
<label class="sr-only" for="tourChatBody">Nachricht</label>
|
||||
<textarea class="form-control" id="tourChatBody" name="body" rows="2" maxlength="2000"
|
||||
required placeholder="Nachricht an die Tour ..."></textarea>
|
||||
<div class="d-flex justify-content-between align-items-center mt-2">
|
||||
<small class="text-muted"><span id="tourChatCount">0</span>/2000</small>
|
||||
<button type="submit" class="btn btn-success btn-sm px-3">Senden</button>
|
||||
</div>
|
||||
<div class="text-danger small mt-2" id="tourChatError" role="alert"></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-muted small mt-3 mb-5">
|
||||
Nur Teilnehmer, Tour Guide und Admins sehen diesen Chat.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="<?= e(asset_versioned('js/tour-chat.js')) ?>"></script>
|
||||
|
|
@ -106,6 +106,14 @@
|
|||
<textarea class="col-12" name="beschreibung" rows="10" cols="50" readonly><?= e($tour->beschreibung) ?></textarea>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($canChat)): ?>
|
||||
<a href="/tour/<?= e($tour->id) ?>/chat" class="btn btn-primary col-3 mb-2 float-left mr-2">
|
||||
Chat
|
||||
<?php if (($chatUnread ?? 0) > 0): ?>
|
||||
<span class="badge badge-light"><?= e(($chatUnread ?? 0) > 99 ? '99+' : (string) $chatUnread) ?></span>
|
||||
<?php endif; ?>
|
||||
</a>
|
||||
<?php endif; ?>
|
||||
<?php if ($current && $canManage): ?>
|
||||
<a href="/tour/<?= e($tour->id) ?>/edit">
|
||||
<div type="submit" class="btn btn-danger col-3 mb-2 float-left mr-2">Bearbeiten</div>
|
||||
|
|
@ -156,6 +164,20 @@
|
|||
</div>
|
||||
|
||||
<div class="col-md-3 mt-2">
|
||||
<?php if (!empty($canChat)): ?>
|
||||
<div class="card mt-4">
|
||||
<div class="card-body text-center">
|
||||
<a href="/tour/<?= e($tour->id) ?>/chat" class="btn btn-primary btn-block">
|
||||
Tour-Chat
|
||||
<?php if (($chatUnread ?? 0) > 0): ?>
|
||||
<span class="badge badge-light ml-1"><?= e(($chatUnread ?? 0) > 99 ? '99+' : (string) $chatUnread) ?></span>
|
||||
<?php endif; ?>
|
||||
</a>
|
||||
<small class="text-muted d-block mt-2">Geschlossener Chat für Teilnehmer</small>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card mt-4">
|
||||
<div class="card-header"><h5>Teilnehmer</h5></div>
|
||||
|
||||
|
|
|
|||
|
|
@ -79,6 +79,14 @@
|
|||
<textarea class="col-12" name="bericht" rows="10" cols="50" readonly><?= e($tour->bericht) ?></textarea>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($canChat)): ?>
|
||||
<a href="/tour/<?= e($tour->id) ?>/chat" class="btn btn-primary col-3 mb-2 float-left mr-2">
|
||||
Chat
|
||||
<?php if (($chatUnread ?? 0) > 0): ?>
|
||||
<span class="badge badge-light"><?= e(($chatUnread ?? 0) > 99 ? '99+' : (string) $chatUnread) ?></span>
|
||||
<?php endif; ?>
|
||||
</a>
|
||||
<?php endif; ?>
|
||||
<?php if ($current && $canManage): ?>
|
||||
<a href="/tour/<?= e($tour->id) ?>/edit"><div type="submit" class="btn btn-danger col-3 mb-2 float-left mr-2">Bearbeiten</div></a>
|
||||
<?php endif; ?>
|
||||
|
|
@ -89,6 +97,20 @@
|
|||
</div>
|
||||
|
||||
<div class="col-md-3 mt-2">
|
||||
<?php if (!empty($canChat)): ?>
|
||||
<div class="card mt-4">
|
||||
<div class="card-body text-center">
|
||||
<a href="/tour/<?= e($tour->id) ?>/chat" class="btn btn-primary btn-block">
|
||||
Tour-Chat
|
||||
<?php if (($chatUnread ?? 0) > 0): ?>
|
||||
<span class="badge badge-light ml-1"><?= e(($chatUnread ?? 0) > 99 ? '99+' : (string) $chatUnread) ?></span>
|
||||
<?php endif; ?>
|
||||
</a>
|
||||
<small class="text-muted d-block mt-2">Geschlossener Chat für Teilnehmer</small>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="card mt-4">
|
||||
<div class="card-header"><h5>Teilnehmer</h5></div>
|
||||
|
||||
|
|
|
|||
|
|
@ -99,6 +99,36 @@ MIGRATIONS = [
|
|||
KEY `push_subscriptions_user_id_index` (`user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci''',
|
||||
|
||||
# Tour-Chat: Nachrichten
|
||||
'''CREATE TABLE IF NOT EXISTS `tour_messages` (
|
||||
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`tour_id` int(11) NOT NULL,
|
||||
`user_id` bigint(20) unsigned NULL DEFAULT NULL,
|
||||
`type` varchar(20) NOT NULL DEFAULT 'user',
|
||||
`body` text NOT NULL,
|
||||
`created_at` timestamp NULL DEFAULT NULL,
|
||||
`deleted_at` timestamp NULL DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `tour_messages_tour_id_id_index` (`tour_id`,`id`),
|
||||
KEY `tour_messages_user_id_index` (`user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci''',
|
||||
|
||||
# Tour-Chat: Lesestatus pro Benutzer und Tour
|
||||
'''CREATE TABLE IF NOT EXISTS `tour_chat_reads` (
|
||||
`tour_id` int(11) NOT NULL,
|
||||
`user_id` bigint(20) unsigned NOT NULL,
|
||||
`last_read_message_id` bigint(20) unsigned NOT NULL DEFAULT 0,
|
||||
`updated_at` timestamp NULL DEFAULT NULL,
|
||||
PRIMARY KEY (`tour_id`,`user_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci''',
|
||||
|
||||
# Tour-Chat: Drosselung der Push-Benachrichtigungen
|
||||
'''CREATE TABLE IF NOT EXISTS `tour_chat_push` (
|
||||
`tour_id` int(11) NOT NULL,
|
||||
`last_sent_at` timestamp NULL DEFAULT NULL,
|
||||
PRIMARY KEY (`tour_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci''',
|
||||
|
||||
# Annahme-Felder für bestehende Installationen ergänzen (idempotent)
|
||||
'''SET @has_accepted_at := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'membership_applications' AND COLUMN_NAME = 'accepted_at');
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue