finished tournaments

This commit is contained in:
Torsten Schulz
2025-07-16 14:29:34 +02:00
parent d0544da1ba
commit 4122868ab0
6 changed files with 963 additions and 137 deletions

View File

@@ -57,9 +57,9 @@ export const getParticipants = async (req, res) => {
// 5. Turniermodus (Gruppen/K.O.) setzen
export const setModus = async (req, res) => {
const { authcode: token } = req.headers;
const { clubId, tournamentId, type, numberOfGroups } = req.body;
const { clubId, tournamentId, type, numberOfGroups, advancingPerGroup } = req.body;
try {
await tournamentService.setModus(token, clubId, tournamentId, type, numberOfGroups);
await tournamentService.setModus(token, clubId, tournamentId, type, numberOfGroups, advancingPerGroup);
res.sendStatus(204);
} catch (error) {
console.error(error);
@@ -164,9 +164,117 @@ export const startKnockout = async (req, res) => {
try {
await tournamentService.startKnockout(token, clubId, tournamentId);
res.status(200).json({ message: 'K.O.-Runde erfolgreich gestartet' });
res.status(200).json({ message: "K.o.-Runde erfolgreich gestartet" });
} catch (error) {
console.error('Error in startKnockout:', error);
const status = /Gruppenmodus|Zu wenige Qualifikanten/.test(error.message) ? 400 : 500;
res.status(status).json({ error: error.message });
}
};
export const manualAssignGroups = async (req, res) => {
const { authcode: token } = req.headers;
const {
clubId,
tournamentId,
assignments, // [{ participantId, groupNumber }]
numberOfGroups, // optional
maxGroupSize // optional
} = req.body;
try {
const groupsWithParts = await tournamentService.manualAssignGroups(
token,
clubId,
tournamentId,
assignments,
numberOfGroups, // neu
maxGroupSize // neu
);
res.status(200).json(groupsWithParts);
} catch (error) {
console.error('Error in manualAssignGroups:', error);
res.status(500).json({ error: error.message });
}
};
export const resetGroups = async (req, res) => {
const { authcode: token } = req.headers;
const { clubId, tournamentId } = req.body;
try {
await tournamentService.resetGroups(token, clubId, tournamentId);
res.sendStatus(204);
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
};
export const resetMatches = async (req, res) => {
const { authcode: token } = req.headers;
const { clubId, tournamentId } = req.body;
try {
await tournamentService.resetMatches(token, clubId, tournamentId);
res.sendStatus(204);
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
};
export const removeParticipant = async (req, res) => {
const { authcode: token } = req.headers;
const { clubId, tournamentId, participantId } = req.body;
try {
await tournamentService.removeParticipant(token, clubId, tournamentId, participantId);
const participants = await tournamentService.getParticipants(token, clubId, tournamentId);
res.status(200).json(participants);
} catch (err) {
console.error(err);
res.status(500).json({ error: err.message });
}
};
export const deleteMatchResult = async (req, res) => {
const { authcode: token } = req.headers;
const { clubId, tournamentId, matchId, set } = req.body;
try {
await tournamentService.deleteMatchResult(
token,
clubId,
tournamentId,
matchId,
set
);
res.status(200).json({ message: 'Einzelsatz gelöscht' });
} catch (error) {
console.error('Error in deleteMatchResult:', error);
res.status(500).json({ error: error.message });
}
};
export const reopenMatch = async (req, res) => {
const { authcode: token } = req.headers;
const { clubId, tournamentId, matchId } = req.body;
try {
await tournamentService.reopenMatch(token, clubId, tournamentId, matchId);
// Gib optional das aktualisierte Match zurück
res.status(200).json({ message: "Match reopened" });
} catch (error) {
console.error("Error in reopenMatch:", error);
res.status(500).json({ error: error.message });
}
};
export const deleteKnockoutMatches = async (req, res) => {
const { authcode: token } = req.headers;
const { clubId, tournamentId } = req.body;
try {
await tournamentService.resetKnockout(token, clubId, tournamentId);
res.status(200).json({ message: "K.o.-Runde gelöscht" });
} catch (error) {
console.error("Error in deleteKnockoutMatches:", error);
res.status(500).json({ error: error.message });
}
};

View File

@@ -14,14 +14,14 @@ const Tournament = sequelize.define('Tournament', {
type: DataTypes.STRING,
allowNull: false,
},
bestOfEndroundSize: {
advancingPerGroup: {
type: DataTypes.INTEGER,
allowNull: false,
},
numberOfGroups: {
type: DataTypes.INTEGER,
allowNull: true,
defaultValue: 0,
defaultValue: 0,
},
clubId: {
type: DataTypes.INTEGER,

View File

@@ -25,6 +25,10 @@ const TournamentMatch = sequelize.define('TournamentMatch', {
onDelete: 'SET NULL',
onUpdate: 'CASCADE'
},
groupRound: {
type: DataTypes.INTEGER,
allowNull: true,
},
round: {
type: DataTypes.STRING,
allowNull: false,

View File

@@ -13,6 +13,13 @@ import {
addMatchResult,
finishMatch,
startKnockout,
manualAssignGroups,
resetGroups,
resetMatches,
removeParticipant,
deleteMatchResult,
reopenMatch,
deleteKnockoutMatches,
} from '../controllers/tournamentController.js';
import { authenticate } from '../middleware/authMiddleware.js';
@@ -20,17 +27,23 @@ const router = express.Router();
router.post('/participant', authenticate, addParticipant);
router.post('/participants', authenticate, getParticipants);
router.delete('/participant', authenticate, removeParticipant);
router.post('/modus', authenticate, setModus);
router.post('/groups/reset', authenticate, resetGroups);
router.post('/matches/reset', authenticate, resetMatches);
router.put('/groups', authenticate, createGroups);
router.post('/groups', authenticate, fillGroups);
router.get('/groups', authenticate, getGroups);
router.post('/match/result', authenticate, addMatchResult);
router.delete('/match/result', authenticate, deleteMatchResult);
router.post("/match/reopen", reopenMatch);
router.post('/match/finish', authenticate, finishMatch);
router.get('/matches/:clubId/:tournamentId', authenticate, getTournamentMatches);
router.get('/:clubId/:tournamentId', authenticate, getTournament);
router.get('/:clubId', authenticate, getTournaments);
router.post('/knockout', authenticate, startKnockout);
router.delete("/matches/knockout", deleteKnockoutMatches);
router.post('/groups/manual', authenticate, manualAssignGroups);
router.post('/', authenticate, addTournament);
export default router;

View File

@@ -8,6 +8,25 @@ import TournamentResult from "../models/TournamentResult.js";
import { checkAccess } from '../utils/userUtils.js';
import { Op, literal } from 'sequelize';
function getRoundName(size) {
switch (size) {
case 2: return "Finale";
case 4: return "Halbfinale";
case 8: return "Viertelfinale";
case 16: return "Achtelfinale";
default: return `Runde der ${size}`;
}
}
function nextRoundName(currentName) {
switch (currentName) {
case "Achtelfinale": return "Viertelfinale";
case "Viertelfinale": return "Halbfinale";
case "Halbfinale": return "Finale";
default: return null;
}
}
class TournamentService {
// 1. Turniere listen
async getTournaments(userToken, clubId) {
@@ -76,13 +95,13 @@ class TournamentService {
}
// 5. Modus setzen (Gruppen / KORunde)
async setModus(userToken, clubId, tournamentId, type, numberOfGroups) {
async setModus(userToken, clubId, tournamentId, type, numberOfGroups, advancingPerGroup) {
await checkAccess(userToken, clubId);
const tournament = await Tournament.findByPk(tournamentId);
if (!tournament || tournament.clubId != clubId) {
throw new Error('Turnier nicht gefunden');
}
await tournament.update({ type, numberOfGroups });
await tournament.update({ type, numberOfGroups, advancingPerGroup });
}
// 6. Leere Gruppen anlegen
@@ -106,53 +125,95 @@ class TournamentService {
}
// 7. Gruppen zufällig füllen & Spiele anlegen
generateRoundRobinSchedule(players) {
const list = [...players];
const n = list.length;
const hasBye = n % 2 === 1;
if (hasBye) list.push(null); // füge Bye hinzu
const total = list.length; // jetzt gerade Zahl
const rounds = [];
for (let round = 0; round < total - 1; round++) {
const pairs = [];
for (let i = 0; i < total / 2; i++) {
const p1 = list[i];
const p2 = list[total - 1 - i];
if (p1 && p2) {
pairs.push([p1.id, p2.id]);
}
}
rounds.push(pairs);
// Rotation (Fixpunkt list[0]):
list.splice(1, 0, list.pop());
}
return rounds;
}
// services/tournamentService.js
async fillGroups(userToken, clubId, tournamentId) {
await checkAccess(userToken, clubId);
const tournament = await Tournament.findByPk(tournamentId);
if (!tournament || tournament.clubId != clubId) {
throw new Error('Turnier nicht gefunden');
}
const groups = await TournamentGroup.findAll({ where: { tournamentId } });
// 1) Hole vorhandene Gruppen
let groups = await TournamentGroup.findAll({ where: { tournamentId } });
// **Neu**: Falls noch keine Gruppen existieren, lege sie nach numberOfGroups an
if (!groups.length) {
throw new Error('Keine Gruppen vorhanden. Erst erstellen.');
const desired = tournament.numberOfGroups || 1; // Fallback auf 1, wenn undefiniert
for (let i = 0; i < desired; i++) {
await TournamentGroup.create({ tournamentId });
}
groups = await TournamentGroup.findAll({ where: { tournamentId } });
}
const members = await TournamentMember.findAll({ where: { tournamentId } });
if (!members.length) {
throw new Error('Keine Teilnehmer vorhanden.');
}
// alte Matches löschen
// 2) Alte Matches löschen
await TournamentMatch.destroy({ where: { tournamentId } });
// mische Teilnehmer
// 3) Shuffle + verteilen
const shuffled = members.slice();
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
// verteile in roundrobinGruppen
for (let idx = 0; idx < shuffled.length; idx++) {
const grpId = groups[idx % groups.length].id;
await shuffled[idx].update({ groupId: grpId });
}
// lege alle Paarungen in jeder Gruppe an
groups.forEach((g, idx) => {
shuffled
.filter((_, i) => i % groups.length === idx)
.forEach(m => m.update({ groupId: g.id }));
});
// 4) RoundRobin anlegen wie gehabt
for (const g of groups) {
const gm = await TournamentMember.findAll({ where: { groupId: g.id } });
for (let i = 0; i < gm.length; i++) {
for (let j = i + 1; j < gm.length; j++) {
const rounds = this.generateRoundRobinSchedule(gm);
for (let roundIndex = 0; roundIndex < rounds.length; roundIndex++) {
for (const [p1Id, p2Id] of rounds[roundIndex]) {
await TournamentMatch.create({
tournamentId,
groupId: g.id,
round: 'group',
player1Id: gm[i].id,
player2Id: gm[j].id
player1Id: p1Id,
player2Id: p2Id,
groupRound: roundIndex + 1
});
}
}
}
// 5) Teilnehmer mit Gruppen zurückgeben
return await TournamentMember.findAll({ where: { tournamentId } });
}
// 8. Nur Gruppen (ohne Teilnehmer)
async getGroups(userToken, clubId, tournamentId) {
await checkAccess(userToken, clubId);
const tournament = await Tournament.findByPk(tournamentId);
@@ -163,6 +224,8 @@ class TournamentService {
}
// 9. Gruppen mit ihren Teilnehmern
// services/tournamentService.js
async getGroupsWithParticipants(userToken, clubId, tournamentId) {
await checkAccess(userToken, clubId);
const tournament = await Tournament.findByPk(tournamentId);
@@ -178,8 +241,11 @@ class TournamentService {
}],
order: [['id', 'ASC']]
});
return groups.map(g => ({
// hier den Index mit aufnehmen:
return groups.map((g, idx) => ({
groupId: g.id,
groupNumber: idx + 1, // jetzt definiert
participants: g.tournamentGroupMembers.map(m => ({
id: m.id,
name: `${m.member.firstName} ${m.member.lastName}`
@@ -187,6 +253,7 @@ class TournamentService {
}));
}
// 10. Einzelnes Turnier
async getTournament(userToken, clubId, tournamentId) {
await checkAccess(userToken, clubId);
@@ -208,6 +275,8 @@ class TournamentService {
{ model: TournamentResult, as: 'tournamentResults' }
],
order: [
['group_id', 'ASC'],
['group_round', 'ASC'],
['id', 'ASC'],
[{ model: TournamentResult, as: 'tournamentResults' }, 'set', 'ASC']
]
@@ -230,71 +299,74 @@ class TournamentService {
}
}
// 13. Match abschließen (Endergebnis setzen)
async finishMatch(userToken, clubId, tournamentId, matchId) {
await checkAccess(userToken, clubId);
const matches = await TournamentMatch.findAll({
where: { id: matchId, tournamentId },
include: [{ model: TournamentResult, as: 'tournamentResults' }],
order: [[{ model: TournamentResult, as: 'tournamentResults' }, 'set', 'ASC']]
const match = await TournamentMatch.findByPk(matchId, {
include: [{ model: TournamentResult, as: "tournamentResults" }]
});
const match = matches[0];
if (!match) throw new Error('Match nicht gefunden');
if (!match) throw new Error("Match nicht gefunden");
let win = 0, lose = 0;
match.tournamentResults.forEach(r => {
for (const r of match.tournamentResults) {
if (r.pointsPlayer1 > r.pointsPlayer2) win++;
else lose++;
});
}
match.isFinished = true;
match.result = `${win}:${lose}`;
await match.save();
const allFinished = await TournamentMatch.count({
where: { tournamentId, round: match.round, isFinished: false }
}) === 0;
if (allFinished) {
const sameRound = await TournamentMatch.findAll({
where: { tournamentId, round: match.round }
});
const winners = sameRound.map(m => {
const [w1, w2] = m.result.split(":").map(n => +n);
return w1 > w2 ? m.player1Id : m.player2Id;
});
const nextName = nextRoundName(match.round);
if (nextName) {
for (let i = 0; i < winners.length / 2; i++) {
await TournamentMatch.create({
tournamentId,
round: nextName,
player1Id: winners[i],
player2Id: winners[winners.length - 1 - i]
});
}
}
}
}
/**
* Ermittelt aus jeder Gruppe den Gruppensieger und legt
* für die K.O.-Runde die ersten Matches an.
*/
// services/tournamentService.js
async startKnockout(token, clubId, tournamentId) {
await checkAccess(token, clubId);
const t = await Tournament.findByPk(tournamentId);
if (!t || t.clubId != clubId) throw new Error('Tournament not found');
const totalQualifiers = t.numberOfGroups * t.advancingPerGroup;
if (totalQualifiers < 2) throw new Error('Zu wenige Qualifikanten für K.O.-Runde');
// lösche frühere KO-Matches
await TournamentMatch.destroy({ where: { tournamentId, round: { [Op.ne]: 'group' } } });
// lade alle Gruppenteilnehmer
async _determineQualifiers(tournamentId, tournament) {
const groups = await TournamentGroup.findAll({
where: { tournamentId },
include: [{ model: TournamentMember, as: 'tournamentGroupMembers' }]
include: [{ model: TournamentMember, as: "tournamentGroupMembers" }]
});
// lade alle Gruppenspiele und Ergebnisse
const groupMatches = await TournamentMatch.findAll({
where: { tournamentId, round: 'group' },
include: [{ model: TournamentResult, as: 'tournamentResults' }]
where: { tournamentId, round: "group", isFinished: true }
});
const qualifiers = [];
for (const g of groups) {
// init stats
const stats = {};
g.tournamentGroupMembers.forEach(m => {
stats[m.id] = { member: m, points: 0, setsWon: 0, setsLost: 0 };
});
// auswerten
for (const m of groupMatches.filter(m => m.groupId === g.id && m.isFinished)) {
const [p1, p2] = m.result.split(':').map(n => parseInt(n, 10));
for (const tm of g.tournamentGroupMembers) {
stats[tm.id] = { member: tm, points: 0, setsWon: 0, setsLost: 0 };
}
for (const m of groupMatches.filter(m => m.groupId === g.id)) {
if (!stats[m.player1Id] || !stats[m.player2Id]) continue;
const [p1, p2] = m.result.split(":").map(n => parseInt(n, 10));
if (p1 > p2) stats[m.player1Id].points += 2;
else if (p2 > p1) stats[m.player2Id].points += 2;
else stats[m.player2Id].points += 2;
stats[m.player1Id].setsWon += p1;
stats[m.player1Id].setsLost += p2;
stats[m.player2Id].setsWon += p2;
stats[m.player2Id].setsLost += p1;
}
// sortieren
const ranked = Object.values(stats).sort((a, b) => {
const diffA = a.setsWon - a.setsLost;
const diffB = b.setsWon - b.setsLost;
@@ -303,34 +375,206 @@ class TournamentService {
if (b.setsWon !== a.setsWon) return b.setsWon - a.setsWon;
return a.member.id - b.member.id;
});
// take top N
qualifiers.push(...ranked.slice(0, t.advancingPerGroup).map(r => r.member));
qualifiers.push(...ranked.slice(0, tournament.advancingPerGroup).map(r => r.member));
}
return qualifiers;
}
async startKnockout(userToken, clubId, tournamentId) {
await checkAccess(userToken, clubId);
const t = await Tournament.findByPk(tournamentId);
if (!t || t.clubId != clubId) throw new Error("Tournament not found");
if (t.type === "groups") {
const unfinished = await TournamentMatch.count({
where: { tournamentId, round: "group", isFinished: false }
});
if (unfinished > 0) {
throw new Error(
"Turnier ist im Gruppenmodus, K.o.-Runde kann erst nach Abschluss aller Gruppenspiele gestartet werden."
);
}
}
// bracket aufbauen
let roundSize = qualifiers.length;
const getRoundName = size => {
switch (size) {
case 2: return 'Finale';
case 4: return 'Halbfinale';
case 8: return 'Viertelfinale';
case 16: return 'Achtelfinale';
default: return `Runde der ${size}`;
}
};
const qualifiers = await this._determineQualifiers(tournamentId, t);
if (qualifiers.length < 2) throw new Error("Zu wenige Qualifikanten für K.O.-Runde");
while (roundSize >= 2) {
const rn = getRoundName(roundSize);
for (let i = 0; i < roundSize / 2; i++) {
const p1 = qualifiers[i].id;
const p2 = qualifiers[roundSize - 1 - i].id;
await TournamentMatch.create({ tournamentId, round: rn, player1Id: p1, player2Id: p2 });
}
// Platzhalter für nächste Runde
qualifiers.splice(roundSize / 2);
roundSize = roundSize / 2;
await TournamentMatch.destroy({
where: { tournamentId, round: { [Op.ne]: "group" } }
});
const roundSize = qualifiers.length;
const rn = getRoundName(roundSize);
for (let i = 0; i < roundSize / 2; i++) {
await TournamentMatch.create({
tournamentId,
round: rn,
player1Id: qualifiers[i].id,
player2Id: qualifiers[roundSize - 1 - i].id
});
}
}
async manualAssignGroups(
userToken,
clubId,
tournamentId,
assignments,
numberOfGroups,
maxGroupSize
) {
await checkAccess(userToken, clubId);
// 1) Turnier und Teilnehmerzahl validieren
const tournament = await Tournament.findByPk(tournamentId);
if (!tournament || tournament.clubId != clubId) {
throw new Error('Turnier nicht gefunden');
}
const totalMembers = assignments.length;
if (totalMembers === 0) {
throw new Error('Keine Teilnehmer zum Verteilen');
}
// 2) Bestimme, wie viele Gruppen wir anlegen
let groupCount;
if (numberOfGroups != null) {
groupCount = Number(numberOfGroups);
if (isNaN(groupCount) || groupCount < 1) {
throw new Error('Ungültige Anzahl Gruppen');
}
} else if (maxGroupSize != null) {
const sz = Number(maxGroupSize);
if (isNaN(sz) || sz < 1) {
throw new Error('Ungültige maximale Gruppengröße');
}
groupCount = Math.ceil(totalMembers / sz);
} else {
// Fallback auf im Turnier gespeicherte Anzahl
groupCount = tournament.numberOfGroups;
if (!groupCount || groupCount < 1) {
throw new Error('Anzahl Gruppen nicht definiert');
}
}
// 3) Alte Gruppen löschen und neue anlegen
await TournamentGroup.destroy({ where: { tournamentId } });
const createdGroups = [];
for (let i = 0; i < groupCount; i++) {
const grp = await TournamentGroup.create({ tournamentId });
createdGroups.push(grp);
}
// 4) Mapping von UINummer (1…groupCount) auf reale DBID
const groupMap = {};
createdGroups.forEach((grp, idx) => {
groupMap[idx + 1] = grp.id;
});
// 5) Teilnehmer updaten
await Promise.all(
assignments.map(({ participantId, groupNumber }) => {
const dbGroupId = groupMap[groupNumber];
if (!dbGroupId) {
throw new Error(`Ungültige GruppenNummer: ${groupNumber}`);
}
return TournamentMember.update(
{ groupId: dbGroupId },
{ where: { id: participantId } }
);
})
);
// 6) Ergebnis zurückliefern wie getGroupsWithParticipants
const groups = await TournamentGroup.findAll({
where: { tournamentId },
include: [{
model: TournamentMember,
as: 'tournamentGroupMembers',
include: [{ model: Member, as: 'member', attributes: ['id', 'firstName', 'lastName'] }]
}],
order: [['id', 'ASC']]
});
return groups.map(g => ({
groupId: g.id,
participants: g.tournamentGroupMembers.map(m => ({
id: m.id,
name: `${m.member.firstName} ${m.member.lastName}`
}))
}));
}
// services/tournamentService.js
async resetGroups(userToken, clubId, tournamentId) {
await checkAccess(userToken, clubId);
// löscht alle Gruppen … (inkl. CASCADE oder manuell TournamentMatch.destroy)
await TournamentMatch.destroy({ where: { tournamentId } });
await TournamentGroup.destroy({ where: { tournamentId } });
}
async resetMatches(userToken, clubId, tournamentId) {
await checkAccess(userToken, clubId);
await TournamentMatch.destroy({ where: { tournamentId } });
}
async removeParticipant(userToken, clubId, tournamentId, participantId) {
await checkAccess(userToken, clubId);
await TournamentMember.destroy({
where: { id: participantId, tournamentId }
});
}
// services/tournamentService.js
async deleteMatchResult(userToken, clubId, tournamentId, matchId, setToDelete) {
await checkAccess(userToken, clubId);
// Match existiert?
const match = await TournamentMatch.findOne({ where: { id: matchId, tournamentId } });
if (!match) throw new Error('Match nicht gefunden');
// Satz löschen
await TournamentResult.destroy({ where: { matchId, set: setToDelete } });
// verbleibende Sätze neu durchnummerieren
const remaining = await TournamentResult.findAll({
where: { matchId },
order: [['set', 'ASC']]
});
for (let i = 0; i < remaining.length; i++) {
const r = remaining[i];
const newSet = i + 1;
if (r.set !== newSet) {
r.set = newSet;
await r.save();
}
}
}
async reopenMatch(userToken, clubId, tournamentId, matchId) {
await checkAccess(userToken, clubId);
const match = await TournamentMatch.findOne({
where: { id: matchId, tournamentId }
});
if (!match) {
throw new Error("Match nicht gefunden");
}
// Nur den AbschlussStatus zurücksetzen, nicht die Einzelsätze
match.isFinished = false;
match.result = null; // optional: entfernt die zusammengefasste ErgebnisSpalte
await match.save();
}
async resetKnockout(userToken, clubId, tournamentId) {
await checkAccess(userToken, clubId);
// lösche alle Matches außer Gruppenphase
await TournamentMatch.destroy({
where: {
tournamentId,
round: { [Op.ne]: "group" }
}
});
}
}
export default new TournamentService();

View File

@@ -1,8 +1,6 @@
<template>
<div class="tournaments-view">
<h2>Turnier</h2>
<!-- Datumsauswahl / Neues Turnier -->
<div class="tournament-config">
<h3>Datum</h3>
<select v-model="selectedDate">
@@ -20,20 +18,31 @@
<button @click="createTournament">Erstellen</button>
</div>
</div>
<!-- Konfiguration & Gruppenphase -->
<div v-if="selectedDate !== 'new'" class="tournament-setup">
<label>
<input type="checkbox" v-model="isGroupTournament" />
<input type="checkbox" v-model="isGroupTournament" @change="onModusChange" />
Spielen in Gruppen
</label>
<section class="participants">
<h4>Teilnehmer</h4>
<ul>
<li v-for="participant in participants" :key="participant.id">
{{ participant.member.firstName }}
{{ participant.member.lastName }}
<template v-if="isGroupTournament">
<label class="inline-label">
Gruppe:
<select v-model.number="participant.groupNumber">
<option :value="null"></option>
<option v-for="group in groups" :key="group.groupId" :value="group.groupNumber">
Gruppe {{ group.groupNumber }}
</option>
</select>
</label>
</template>
<button @click="removeParticipant(participant)" style="margin-left:0.5rem">
Entfernen
</button>
</li>
</ul>
<select v-model="selectedMember">
@@ -44,20 +53,28 @@
</select>
<button @click="addParticipant">Hinzufügen</button>
</section>
<section v-if="isGroupTournament && participants.length > 1" class="group-controls">
<section v-if="isGroupTournament" class="group-controls">
<label>
Anzahl Gruppen:
<input type="number" v-model.number="numberOfGroups" min="1" />
<input type="number" v-model.number="numberOfGroups" min="1" @change="onGroupCountChange" />
</label>
<label style="margin-left:1em">
Aufsteiger pro Gruppe:
<input type="number" v-model.number="advancingPerGroup" min="1" @change="onModusChange" />
</label>
<label style="margin-left:1em">
Maximale Gruppengröße:
<input type="number" v-model.number="maxGroupSize" min="1" />
</label>
<button @click="createGroups">Gruppen erstellen</button>
<button @click="randomizeGroups">Zufällig verteilen</button>
</section>
<section v-if="groups.length" class="groups-overview">
<h3>Gruppenübersicht</h3>
<div v-for="group in groups" :key="group.groupId" class="group-table">
<h4>Gruppe {{ group.groupId }}</h4>
<h4>Gruppe {{ group.groupNumber }}</h4>
<table>
<thead>
<tr>
@@ -81,17 +98,102 @@
</tbody>
</table>
</div>
<div class="reset-controls" style="margin-top:1rem">
<button @click="resetGroups">
Gruppen zurücksetzen
</button>
<button @click="resetMatches" style="margin-left:0.5rem">
Gruppenspiele löschen
</button>
</div>
</section>
</div>
<section v-if="groupMatches.length" class="group-matches">
<h4>Gruppenspiele</h4>
<table>
<thead>
<tr>
<th>Runde</th>
<th>Gruppe</th>
<th>Begegnung</th>
<th>Ergebnis</th>
<th>Sätze</th>
<th>Aktion</th>
</tr>
</thead>
<tbody>
<tr v-for="m in groupMatches" :key="m.id">
<td>{{ m.groupRound }}</td>
<td>{{ m.groupNumber }}</td>
<td>
<template v-if="m.isFinished">
<span v-if="winnerIsPlayer1(m)">
<strong>{{ getPlayerName(m.player1) }}</strong> {{ getPlayerName(m.player2) }}
</span>
<span v-else>
{{ getPlayerName(m.player1) }} <strong>{{ getPlayerName(m.player2) }}</strong>
</span>
</template>
<template v-else>
{{ getPlayerName(m.player1) }} {{ getPlayerName(m.player2) }}
</template>
</td>
<!-- K.o.-Runde starten -->
<div v-if="participants.length > 1 && !showKnockout" class="ko-start">
<td>
<!-- 1. Fall: Match ist noch offen EditMode -->
<template v-if="!m.isFinished">
<!-- existierende Sätze als klickbare Labels -->
<template v-for="r in m.tournamentResults" :key="r.set">
<span @click="startEditResult(m, r)" class="result-text">
{{ r.pointsPlayer1 }}:{{ r.pointsPlayer2 }}
</span>
<span v-if="!isLastResult(m, r)">, </span>
</template>
<!-- Eingabefeld für neue Sätze (immer sichtbar solange offen) -->
<div class="new-set-line">
<input v-model="m.resultInput" placeholder="Neuen Satz, z.B. 11:7"
@keyup.enter="saveMatchResult(m, m.resultInput)"
@blur="saveMatchResult(m, m.resultInput)" class="inline-input" />
</div>
</template>
<!-- 2. Fall: Match ist abgeschlossen Readonly -->
<template v-else>
{{ formatResult(m) }}
</template>
</td>
<td>
{{ getSetsString(m) }}
</td>
<td>
<!-- Abschließen-Button nur, wenn noch nicht fertig -->
<button v-if="!m.isFinished" @click="finishMatch(m)">Abschließen</button>
<!-- Korrigieren-Button nur, wenn fertig -->
<button v-else @click="reopenMatch(m)">Korrigieren</button>
</td>
</tr>
</tbody>
</table>
</section>
<div v-if="participants.length > 1
&& !groupMatches.length
&& !knockoutMatches.length" class="start-matches" style="margin-top:1.5rem">
<button @click="startMatches">
Spiele erstellen
</button>
</div>
<div v-if="canStartKnockout && !showKnockout" class="ko-start">
<button @click="startKnockout">
K.o.-Runde starten
</button>
</div>
<!-- K.o.-Runde anzeigen -->
<div v-if="showKnockout && canResetKnockout" class="ko-reset" style="margin-top:1rem">
<button @click="resetKnockout">
K.o.-Runde löschen
</button>
</div>
<section v-if="showKnockout" class="ko-round">
<h4>K.-o.-Runde</h4>
<table>
@@ -100,6 +202,7 @@
<th>Runde</th>
<th>Begegnung</th>
<th>Ergebnis</th>
<th>Sätze</th>
<th>Aktion</th>
</tr>
</thead>
@@ -107,16 +210,68 @@
<tr v-for="m in knockoutMatches" :key="m.id">
<td>{{ m.round }}</td>
<td>
{{ getPlayerName(m.player1) }}
{{ getPlayerName(m.player2) }}
<template v-if="m.isFinished">
<span v-if="winnerIsPlayer1(m)">
<strong>{{ getPlayerName(m.player1) }}</strong>  {{ getPlayerName(m.player2) }}
</span>
<span v-else>
{{ getPlayerName(m.player1) }}  <strong>{{ getPlayerName(m.player2) }}</strong>
</span>
</template>
<template v-else>
{{ getPlayerName(m.player1) }}  {{ getPlayerName(m.player2) }}
</template>
</td>
<td>{{ m.result || '-' }}</td>
<td v-if="!m.isFinished">
<input v-model="m.resultInput" placeholder="z.B. 11:4, 4:11, 4, -4"
@keyup.enter="saveMatchResult(m, m.resultInput)" />
<button @click="finishMatch(m)">
Fertig
</button>
<td>
<!-- 1. Fall: Match ist noch offen → EditMode -->
<template v-if="!m.isFinished">
<!-- existierende Sätze als klickbare Labels -->
<template v-for="r in m.tournamentResults" :key="r.set">
<span @click="startEditResult(m, r)" class="result-text">
{{ r.pointsPlayer1 }}:{{ r.pointsPlayer2 }}
</span>
<span v-if="!isLastResult(m, r)">, </span>
</template>
<!-- Eingabefeld für neue Sätze (immer sichtbar solange offen) -->
<div class="new-set-line">
<input v-model="m.resultInput" placeholder="Neuen Satz, z.B. 11:7"
@keyup.enter="saveMatchResult(m, m.resultInput)"
@blur="saveMatchResult(m, m.resultInput)" class="inline-input" />
</div>
</template>
<!-- 2. Fall: Match ist abgeschlossen → Readonly -->
<template v-else>
{{ formatResult(m) }}
</template>
</td>
<td>
{{ getSetsString(m) }}
</td>
<td>
<button v-if="!m.isFinished" @click="finishMatch(m)">Fertig</button>
<button v-else @click="reopenMatch(m)">Korrigieren</button>
</td>
</tr>
</tbody>
</table>
</section>
<section v-if="rankingList.length" class="ranking">
<h4>Rangliste</h4>
<table>
<thead>
<tr>
<th>Platz</th>
<th>Spieler</th>
</tr>
</thead>
<tbody>
<tr v-for="(entry, idx) in rankingList" :key="`${entry.member.id}-${idx}`">
<td>{{ entry.position }}.</td>
<td>
{{ entry.member.firstName }}
{{ entry.member.lastName }}
</td>
</tr>
</tbody>
@@ -136,24 +291,43 @@ export default {
selectedDate: 'new',
newDate: '',
dates: [],
participants: [],
selectedMember: null,
clubMembers: [],
advancingPerGroup: 1,
numberOfGroups: 1,
maxGroupSize: null,
isGroupTournament: false,
groups: [],
matches: [],
showKnockout: false,
editingResult: {
matchId: null, // aktuell bearbeitetes Match
set: null, // aktuell bearbeitete SatzNummer
value: '' // Eingabewert
}
};
},
computed: {
...mapGetters(['isAuthenticated', 'currentClub']),
knockoutMatches() {
return this.matches.filter(m => m.round !== 'group');
},
groupMatches() {
return this.matches
.filter(m => m.round === 'group')
.sort((a, b) => {
// zuerst nach Runde
if (a.groupRound !== b.groupRound) {
return a.groupRound - b.groupRound;
}
// dann nach Gruppe
return a.groupNumber - b.groupNumber;
});
},
groupRankings() {
const byGroup = {};
this.groups.forEach(g => {
@@ -193,7 +367,52 @@ export default {
}));
});
return rankings;
}
},
rankingList() {
const finalMatch = this.knockoutMatches.find(
m => m.round.toLowerCase() === 'finale'
);
if (!finalMatch || !finalMatch.isFinished) return [];
const list = [];
const [s1, s2] = finalMatch.result.split(':').map(n => +n);
const winner = s1 > s2 ? finalMatch.player1 : finalMatch.player2;
const loser = s1 > s2 ? finalMatch.player2 : finalMatch.player1;
list.push({ position: 1, member: winner.member });
list.push({ position: 2, member: loser.member });
const roundsMap = {};
this.knockoutMatches.forEach(m => {
if (m.round.toLowerCase() === 'finale') return;
(roundsMap[m.round] ||= []).push(m);
});
Object.values(roundsMap).forEach(matches => {
const M = matches.length;
const pos = M + 1;
matches.forEach(match => {
const [a, b] = match.result.split(':').map(n => +n);
const knockedOut = a > b ? match.player2 : match.player1;
list.push({ position: pos, member: knockedOut.member });
});
});
return list.sort((a, b) => a.position - b.position);
},
canStartKnockout() {
if (this.participants.length < 2) return false;
if (!this.isGroupTournament) {
// kein Gruppenmodus → immer starten
return true;
}
// Gruppenmodus → nur, wenn es Gruppenspiele gibt und alle beendet sind
return this.groupMatches.length > 0
&& this.groupMatches.every(m => m.isFinished);
},
canResetKnockout() {
// KOMatches existieren und keiner ist beendet
return this.knockoutMatches.length > 0
&& this.knockoutMatches.every(m => !m.isFinished);
},
},
watch: {
selectedDate: {
@@ -209,7 +428,6 @@ export default {
this.$router.push('/login');
return;
}
// Turniere und Mitglieder laden
const d = await apiClient.get(`/tournament/${this.currentClub}`);
this.dates = d.data;
const m = await apiClient.get(
@@ -218,23 +436,51 @@ export default {
this.clubMembers = m.data;
},
methods: {
normalizeResultInput(raw) {
const s = raw.trim();
if (s.includes(':')) {
const [xRaw, yRaw] = s.split(':');
const x = Number(xRaw), y = Number(yRaw);
if (
Number.isInteger(x) && Number.isInteger(y) &&
(x >= 11 || y >= 11) &&
Math.abs(x - y) >= 2
) {
return `${x}:${y}`;
}
console.warn('Ungültiges Satz-Ergebnis:', s);
return null;
}
const num = Number(s);
if (isNaN(num)) {
console.warn('Ungültiges Ergebnisformat:', raw);
return null;
}
const losing = Math.abs(num);
const winning = losing < 10 ? 11 : losing + 2;
if (num >= 0) {
return `${winning}:${losing}`;
} else {
return `${losing}:${winning}`;
}
},
async loadTournamentData() {
// 1) TurnierMetadaten holen (Typ + Anzahl Gruppen)
const tRes = await apiClient.get(
`/tournament/${this.currentClub}/${this.selectedDate}`
);
const tournament = tRes.data;
this.isGroupTournament = tournament.type === 'groups';
this.numberOfGroups = tournament.numberOfGroups;
// 2) Teilnehmer
this.advancingPerGroup = tournament.advancingPerGroup;
const pRes = await apiClient.post('/tournament/participants', {
clubId: this.currentClub,
tournamentId: this.selectedDate
});
this.participants = pRes.data;
// 3) Gruppen (mit Teilnehmern)
const gRes = await apiClient.get('/tournament/groups', {
params: {
clubId: this.currentClub,
@@ -242,14 +488,18 @@ export default {
}
});
this.groups = gRes.data;
// 4) Alle Matches
const mRes = await apiClient.get(
`/tournament/matches/${this.currentClub}/${this.selectedDate}`
);
this.matches = mRes.data;
// 5) Steuere K.o.-Anzeige
const grpMap = this.groups.reduce((m, g) => {
m[g.groupId] = g.groupNumber;
return m;
}, {});
this.matches = mRes.data.map(m => ({
...m,
groupNumber: grpMap[m.groupId] || 0,
resultInput: ''
}));
this.showKnockout = this.matches.some(m => m.round !== 'group');
},
@@ -269,19 +519,45 @@ export default {
},
async addParticipant() {
const oldMap = this.participants.reduce((map, p) => {
map[p.id] = p.groupNumber
return map
}, {})
const r = await apiClient.post('/tournament/participant', {
clubId: this.currentClub,
tournamentId: this.selectedDate,
participant: this.selectedMember
});
this.participants = r.data;
})
this.participants = r.data.map(p => ({
...p,
groupNumber:
oldMap[p.id] != null
? oldMap[p.id]
: (p.groupId || null)
}))
this.selectedMember = null
},
async createGroups() {
await apiClient.put('/tournament/groups', {
clubId: this.currentClub,
tournamentId: this.selectedDate
});
const assignments = this.participants.map(p => ({
participantId: p.id,
groupNumber: p.groupNumber
}));
const manual = assignments.some(a => a.groupNumber != null);
if (manual) {
await apiClient.post('/tournament/groups/manual', {
clubId: this.currentClub,
tournamentId: this.selectedDate,
assignments,
numberOfGroups: this.numberOfGroups,
maxGroupSize: this.maxGroupSize
});
} else {
await apiClient.put('/tournament/groups', {
clubId: this.currentClub,
tournamentId: this.selectedDate
});
}
await this.loadTournamentData();
},
@@ -300,12 +576,12 @@ export default {
},
async saveMatchResult(match, result) {
// wenn kein ':' dabei, ergänzen
if (result.indexOf(':') === -1) {
result = result.indexOf('-') > -1
? '11:' + result
: (result * -1) + ':11';
if (!result || result.trim().length === 0) {
return;
}
const normalized = this.normalizeResultInput(result);
if (!normalized) return;
result = normalized;
await apiClient.post('/tournament/match/result', {
clubId: this.currentClub,
tournamentId: this.selectedDate,
@@ -313,7 +589,24 @@ export default {
set: (match.tournamentResults?.length || 0) + 1,
result
});
await this.loadTournamentData();
const allRes = await apiClient.get(
`/tournament/matches/${this.currentClub}/${this.selectedDate}`
);
const updated = allRes.data.find(m2 => m2.id === match.id);
if (!updated) {
console.error('Konnte aktualisiertes Match nicht finden');
return;
}
match.tournamentResults = updated.tournamentResults || [];
const resultString = match.tournamentResults.length
? match.tournamentResults
.sort((a, b) => a.set - b.set)
.map(r => `${Math.abs(r.pointsPlayer1)}:${Math.abs(r.pointsPlayer2)}`)
.join(', ')
: null;
match.result = resultString;
match.resultInput = '';
},
async finishMatch(match) {
@@ -331,6 +624,170 @@ export default {
tournamentId: this.selectedDate
});
await this.loadTournamentData();
},
formatResult(match) {
if (!match.tournamentResults?.length) return '-';
return match.tournamentResults
.sort((a, b) => a.set - b.set)
.map(r => `${Math.abs(r.pointsPlayer1)}:${Math.abs(r.pointsPlayer2)}`)
.join(', ');
},
async startMatches() {
if (this.isGroupTournament) {
if (!this.groups.length) {
await this.createGroups();
}
await this.randomizeGroups();
} else {
await this.startKnockout();
}
await this.loadTournamentData();
},
async onModusChange() {
const type = this.isGroupTournament ? 'groups' : 'knockout';
await apiClient.post('/tournament/modus', {
clubId: this.currentClub,
tournamentId: this.selectedDate,
type,
numberOfGroups: this.numberOfGroups,
advancingPerGroup: this.advancingPerGroup
});
await this.loadTournamentData();
},
async resetGroups() {
await apiClient.post('/tournament/groups/reset', {
clubId: this.currentClub,
tournamentId: this.selectedDate
});
await this.loadTournamentData();
},
async resetMatches() {
await apiClient.post('/tournament/matches/reset', {
clubId: this.currentClub,
tournamentId: this.selectedDate
});
await this.loadTournamentData();
},
async removeParticipant(p) {
await apiClient.delete('/tournament/participant', {
data: {
clubId: this.currentClub,
tournamentId: this.selectedDate,
participantId: p.id
}
});
this.participants = this.participants.filter(x => x.id !== p.id);
},
async onGroupCountChange() {
await apiClient.post('/tournament/modus', {
clubId: this.currentClub,
tournamentId: this.selectedDate,
type: this.isGroupTournament ? 'groups' : 'knockout',
numberOfGroups: this.numberOfGroups
});
await this.loadTournamentData();
},
async reopenMatch(match) {
await apiClient.post('/tournament/match/reopen', {
clubId: this.currentClub,
tournamentId: this.selectedDate,
matchId: match.id
});
await this.loadTournamentData();
},
async deleteResult(match, set) {
if (match.isFinished) {
await this.reopenMatch(match);
match.isFinished = false;
}
await apiClient.delete('/tournament/match/result', {
data: {
clubId: this.currentClub,
tournamentId: this.selectedDate,
matchId: match.id,
set
}
});
await this.loadTournamentData();
},
startEditResult(match, result) {
if (match.isFinished) {
this.reopenMatch(match);
match.isFinished = false;
}
this.editingResult.matchId = match.id;
this.editingResult.set = result.set;
this.editingResult.value = `${result.pointsPlayer1}:${result.pointsPlayer2}`;
},
async saveEditedResult(match) {
const { set, value } = this.editingResult;
const normalized = this.normalizeResultInput(value);
if (!normalized) return;
let result = normalized;
await apiClient.post('/tournament/match/result', {
clubId: this.currentClub,
tournamentId: this.selectedDate,
matchId: match.id,
set,
result
});
this.editingResult.matchId = null;
this.editingResult.set = null;
this.editingResult.value = '';
await this.loadTournamentData();
},
isEditing(match, set) {
return (
this.editingResult.matchId === match.id &&
this.editingResult.set === set
);
},
isLastResult(match, result) {
const arr = match.tournamentResults || [];
return arr.length > 0 && arr[arr.length - 1].set === result.set;
},
getSetsString(match) {
const results = match.tournamentResults || [];
let win1 = 0, win2 = 0;
for (const r of results) {
if (r.pointsPlayer1 > r.pointsPlayer2) win1++;
else if (r.pointsPlayer2 > r.pointsPlayer1) win2++;
}
return `${win1}:${win2}`;
},
winnerIsPlayer1(match) {
const [w1, w2] = this.getSetsString(match).split(':').map(Number);
return w1 > w2;
},
async resetKnockout() {
try {
await apiClient.delete('/tournament/matches/knockout', {
data: {
clubId: this.currentClub,
tournamentId: this.selectedDate
}
});
await this.loadTournamentData();
} catch (err) {
console.error('Reset KO failed:', err);
alert(err.response?.data?.error || err.message);
}
}
}
};