Überarbeitete Version der 1. Version. Es bestehen noch grosse Feher in einzelnen Skripten.

This commit is contained in:
Fabio Herzig
2026-04-18 23:45:17 +02:00
parent a51fd9dbeb
commit 3731183654
85 changed files with 2965 additions and 3371 deletions

View File

@@ -2,26 +2,19 @@
header('Content-Type: application/json');
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
if (
empty($_SESSION['access_granted_kampfrichter']) ||
$_SESSION['access_granted_kampfrichter'] !== true ||
empty($_SESSION['passcodekampfrichter_id']) ||
intval($_SESSION['passcodekampfrichter_id']) < 1
) {
http_response_code(403);
exit;
}
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
require $baseDir . '/../scripts/csrf_functions.php';
require_once $baseDir . '/../scripts/session_functions.php';
ini_wkvs_session();
check_user_permission('kampfrichter');
verify_csrf();
if (!verify_csrf()) {
echo json_encode(['success' => false, 'message' => 'Forbidden']);
@@ -158,6 +151,14 @@ $notenConfig = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$displayIdNoteL = intval(db_get_var($mysqli, "SELECT `value` FROM $tableVar WHERE `name` = ?", ['displayIdNoteL'])) ?? 0;
$displayIdNoteR = intval(db_get_var($mysqli, "SELECT `value` FROM $tableVar WHERE `name` = ?", ['displayIdNoteR'])) ?? 0;
if ($displayIdNoteL !== 0 && $displayIdNoteR !== 0) {
$displayNoten = [$displayIdNoteR => 0, $displayIdNoteL => 0];
}
$noten = [];
$row = $dbresult[0];
@@ -176,15 +177,25 @@ foreach ($disciplines as $d) {
// Determine number of runs for this program
$anzRunsConfig = !empty($snC['anzahl_laeufe_json']) ? json_decode($snC['anzahl_laeufe_json'], true) : [];
$runs = $anzRunsConfig[$programm_id] ?? $anzRunsConfig['default'] ?? 1;
$runs = $anzRunsConfig[$d][$programm_id] ?? $anzRunsConfig['default'] ?? 1;
if (isset($displayNoten) && array_key_exists($snC['id'], $displayNoten)) {
$displayNoten[$snC['id']] = $runs;
}
for ($r = 1; $r <= $runs; $r++) {
$value = $indexedNotenDB[$d][$snC['id']][$r] ?? $snC['default_value'] ?? 0;
$noten[$d][$snC['id']][$r] = number_format($value, $snC['nullstellen'] ?? 2);
$noten[$d][$r][$snC['id']] = number_format($value, $snC['nullstellen'] ?? 2);
}
}
}
$countBtn = 1;
if (isset($displayNoten)) {
$countBtn = min($displayNoten);
}
$titel = $row['vorname'].' '.$row['name'].', '.$row['programm'];
@@ -305,7 +316,8 @@ if ($isAdmin) {
'id' => $editId,
'programm_id' => $programm_id,
'titel' => $titel,
'noten' => $noten
'noten' => $noten,
'countBtn' => $countBtn
]);
} else {
echo json_encode([
@@ -314,7 +326,8 @@ if ($isAdmin) {
'programm_id' => $programm_id,
'titel' => $titel,
'noten' => $noten,
'nturnerin' => $nturnerin
'nturnerin' => $nturnerin,
'countBtn' => $countBtn
]);
}

View File

@@ -8,16 +8,18 @@ ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);*/
// Start session if not already started
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
// Check access
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true ||
empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
http_response_code(403);
exit;
}
require_once $baseDir . '/../scripts/session_functions.php';
ini_wkvs_session();
check_user_permission('kampfrichter');
verify_csrf();
// Validate POST input
if (!isset($_POST['abteilung'])) {

View File

@@ -2,24 +2,17 @@
use TCPDF;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
// Show all errors except deprecation notices (these come from vendor libraries
// that aren't yet typed for newer PHP versions). Long-term fix: update
// dependencies to versions compatible with your PHP runtime.
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
// Start session if not already started
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
// Check access
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true ||
empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
http_response_code(403);
exit;
}
require_once $baseDir . '/../scripts/session_functions.php';
ini_wkvs_session();
check_user_permission('kampfrichter');
verify_csrf();
// Validate POST input
/*

View File

@@ -1,19 +1,17 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
// Show all errors except deprecation notices (these come from vendor libraries
// that aren't yet typed for newer PHP versions). Long-term fix: update
// dependencies to versions compatible with your PHP runtime.
error_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);
header('Content-Type: application/json');
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
require_once $baseDir . '/../scripts/session_functions.php';
ini_wkvs_session();
check_user_permission('kampfrichter');
verify_csrf();
$type = 'kr';
$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';
@@ -26,8 +24,8 @@ if ($data['success'] === false){
require $baseDir . '/../scripts/db/db-tables.php';
// ---------- Get and sanitize input ----------
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$discipline = isset($_GET['discipline']) ? preg_replace('/[^a-zA-Z0-9 _-]/', '', $_GET['discipline']) : '';
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$discipline = isset($_POST['discipline']) ? preg_replace('/[^a-zA-Z0-9 _-]/', '', $_POST['discipline']) : '';
if ($discipline !== 'boden') {
echo json_encode(['success' => false, 'message' => 'Invalid discipline']);

View File

@@ -2,9 +2,17 @@
header('Content-Type: application/json');
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
require_once $baseDir . '/../scripts/session_functions.php';
ini_wkvs_session();
check_user_permission('kampfrichter');
verify_csrf();
$discipline = 'boden';
$folder = realpath($baseDir . '/displays/json');

View File

@@ -2,21 +2,18 @@
header('Content-Type: application/json');
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
session_start();
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
http_response_code(403);
exit;
}
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
require_once $baseDir . '/../scripts/session_functions.php';
ini_wkvs_session();
check_user_permission('kampfrichter');
verify_csrf();
$type = 'kr';
$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';

View File

@@ -1,51 +0,0 @@
<?php
session_start();
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
$new_value = $_POST['freigabe'] ?? '';
$type = $_POST['type'] ?? 'nan';
$allowedTypes = ['kampfrichter', 'trainer'];
if (in_array($type, $allowedTypes)) {
$accessKey = "access_granted_" . $type;
$idKey = "passcode" . $type . "_id";
// 3. Check if they have access
$hasAccess = isset($_SESSION[$accessKey]) &&
$_SESSION[$accessKey] === true &&
!empty($_SESSION[$idKey]) &&
$_SESSION[$idKey] > 0;
if (!$hasAccess) {
echo json_encode(['success' => false, 'message' => 'no permissions']);
exit;
}
} else {
echo json_encode(['success' => false, 'message' => 'no permissions']);
exit;
}
if (!$new_value) {
echo json_encode('Invalid Input');
exit;
}
if ($type === 'kampfrichter'){
$_SESSION['selectedFreigabeKampfrichter'] = $new_value;
}
if ($type === 'trainer'){
$_SESSION['selectedFreigabeTrainer'] = $new_value;
}
// ---------- Return JSON ----------
echo json_encode(['success' => true, 'message' => 'SESSION updated']);
exit;

View File

@@ -1,21 +1,17 @@
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
session_start();
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
http_response_code(403);
exit;
}
header('Content-Type: application/json');
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
require_once $baseDir . '/../scripts/session_functions.php';
ini_wkvs_session();
check_user_permission('kampfrichter');
verify_csrf();
$type = 'kr';
$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';
@@ -120,6 +116,10 @@ try {
$geraete = db_select($mysqli, $tableGeraete, "id");
$programmName = db_get_var($mysqli, "SELECT `programm` FROM $tableTurnerinnen WHERE `id` = ?", [$person_id]);
$programmId = db_get_var($mysqli, "SELECT `id` FROM $tableProgramme WHERE `programm` = ?", [$programmName]);
// Alle Werte werden von der Datenbank geholt und werden, wenn nicht vorhanden, durch den Standartwert ersetzt.
$alleNoten = db_select($mysqli, $tableNotenBezeichnungen, "id, berechnung, default_value, nullstellen, pro_geraet, geraete_json, anzahl_laeufe_json");
@@ -132,9 +132,20 @@ $ascArrayGeraeteJSON = array_column($alleNoten, 'geraete_json', 'id');
$ascArrayAnzahlLaeufeJSON = array_column($alleNoten, 'anzahl_laeufe_json', 'id');
$ascArrayRechnungen = array_column($alleNoten, 'berechnung', 'id');
// $proGeraet = intval($calc['pro_geraet']) !== 1;
$mRunFunctions = [];
foreach ($abhaenigeRechnungen as $saRechnung) {
$sRechnung = $ascArrayRechnungen[$saRechnung[0]] ?? 0;
//var_dump($sRechnung);
$mRunCalc = $notenRechner->checkRunFunctions($sRechnung) ?? false;
if ($mRunCalc) {
$mRunFunctions[] = $saRechnung[0];
break;
}
}
$indexedNotenArray = [];
@@ -158,22 +169,72 @@ foreach ($noten as $sn) {
$alleNotenIds = array_column($alleNoten, 'id') ?? [];
foreach ($indexedNotenArray as $sG => $siNA) {
$existierendeNotenIds = array_keys($siNA) ?? [];
$nichtExistierendeNotenIds = array_diff($alleNotenIds, $existierendeNotenIds) ?? [];
foreach ($nichtExistierendeNotenIds as $neni) {
if (!isset($ascArrayDefaultValues[$neni])) { continue; }
if (intval($ascArrayProGeraet[$neni]) === 1 && intval($sG) === 0) { continue; }
if (intval($ascArrayProGeraet[$neni]) !== 1 && (!is_array($ascArrayGeraeteJSON[$neni]) || !in_array($sG, $ascArrayGeraeteJSON[$neni]))) { continue; }
// For non-existent notes, we fill all runs with default value
// We set Run 1 by default, and if more are configured, also those
$indexedNotenArray[$sG][$neni][1] = $ascArrayDefaultValues[$neni];
if (count($mRunFunctions) > 0) {
foreach ($indexedNotenArray as $sG => $siNA) {
// Check for more runs in config? (Actually, this might be overkill for defaults,
// but the calculator might need them)
foreach ($alleNotenIds as $neni) { // Use $neni as the ID
// 1. Skip if no default value is defined
if (!isset($ascArrayDefaultValues[$neni])) {
continue;
}
// 2. Logic Check: Is this note assigned to this device?
$isProGeraet = (int)($ascArrayProGeraet[$neni] ?? 0);
if ($isProGeraet === 1 && (int)$sG === 0) {
continue;
}
if ($isProGeraet !== 1) {
$allowedGeraete = $ascArrayGeraeteJSON[$neni] ?? [];
if (!is_array($allowedGeraete) || !in_array($sG, $allowedGeraete)) {
continue;
}
}
$runs = $ascArrayAnzahlLaeufeJSON[$neni][$sG][$programmId] ?? $ascArrayAnzahlLaeufeJSON[$neni]["default"] ?? 1;
for ($r = 1; $r <= $runs; $r++) {
if (isset($indexedNotenArray[$sG][$neni][$r])) {
continue;
}
$indexedNotenArray[$sG][$neni][$r] = $ascArrayDefaultValues[$neni];
}
}
}
} else {
foreach ($indexedNotenArray as $sG => $siNA) {
foreach ($alleNotenIds as $neni) { // Use $neni as the ID
// 1. Skip if value already exists for this specific run
if (isset($indexedNotenArray[$sG][$neni][$run_number])) {
continue;
}
// 2. Skip if no default value is defined
if (!isset($ascArrayDefaultValues[$neni])) {
continue;
}
// 3. Logic Check: Is this note assigned to this device?
$isProGeraet = (int)($ascArrayProGeraet[$neni] ?? 0);
if ($isProGeraet === 1 && (int)$sG === 0) {
continue;
}
if ($isProGeraet !== 1) {
$allowedGeraete = $ascArrayGeraeteJSON[$neni] ?? [];
if (!is_array($allowedGeraete) || !in_array($sG, $allowedGeraete)) {
continue;
}
}
// 4. Assign the default value
$indexedNotenArray[$sG][$neni][$run_number] = $ascArrayDefaultValues[$neni];
}
}
}
@@ -181,44 +242,51 @@ foreach ($indexedNotenArray as $sG => $siNA) {
$idsToSave = [];
foreach ($abhaenigeRechnungen as $sRechnung) {
if ($sRechnung[1] !== "A" && intval($sRechnung[1]) !== $gereat_id) { continue; }
$rechnung = $ascArrayRechnungen[$sRechnung[0]] ?? null;
$gereadIdArrays = ($sRechnung[1] === "A") ? $gereat_id : $sRechnung[1];
$targetNoteId = $sRechnung[0];
$isProGeraet = (intval($ascArrayProGeraet[$targetNoteId]) === 1);
$rechnungType = $sRechnung[1];
// 1. Initial Filter
if ($rechnungType !== "A" && intval($rechnungType) !== $gereat_id) continue;
$rechnung = $ascArrayRechnungen[$targetNoteId] ?? null;
if ($rechnung === null) {
echo json_encode(['success' => true, 'message' => "Fehler: Rechnung $targetNoteId nicht gefunden"]);
exit;
}
// 2. Determine Target Device ID
$isProGeraet = (intval($ascArrayProGeraet[$targetNoteId] ?? 0) === 1);
$allowedGeraete = $ascArrayGeraeteJSON[$targetNoteId] ?? [];
if ($isProGeraet) {
$gereadIdArrays = $gereat_id;
} elseif (in_array($gereat_id, $allowedGeraete)) {
$gereadIdArrays = $gereat_id;
if ($rechnungType === "A" || $isProGeraet || in_array($gereat_id, $allowedGeraete)) {
$targetGeraetKey = $gereat_id;
} else {
$gereadIdArrays = 0;
$targetGeraetKey = 0;
}
if ($rechnung === null) {
echo json_encode(['success' => true, 'message' => "Wert aktualisiert, Fehler: Rechnung" . $sRechnung[0] . "nicht gefunden"]);
// 3. Calculation Logic
$runsConfig = $ascArrayAnzahlLaeufeJSON[$targetNoteId] ?? [];
$runs = $runsConfig[$gereat_id][$programmId] ?? $runsConfig["default"] ?? 1;
$acrun = min($runs, $run_number);
if (in_array($targetNoteId, $mRunFunctions)) {
$calcResult = $notenRechner->berechneStringComplexRun($rechnung, $indexedNotenArray, $gereat_id, $programmId, $ascArrayAnzahlLaeufeJSON);
} else {
$calcResult = $notenRechner->berechneStringComplex($rechnung, $indexedNotenArray, $gereat_id, $acrun);
}
if (!($calcResult['success'] ?? false)) {
echo json_encode(['success' => true, 'message' => "Rechenfehler in $targetNoteId: " . ($calcResult['value'] ?? '')]);
exit;
}
$calcResult = $notenRechner->berechneStringComplex($rechnung, $indexedNotenArray, $gereat_id);
if ($calcResult['success'] !== true) {
echo json_encode(['success' => true, 'message' => "Wert aktualisiert, Rechenfehler: " . ($calcResult['value'] ?? '')]);
exit;
}
// Update the local array (Always Run 1 for calculations for now, UNLESS we want calculated runs?)
// Most calculations are "Total" points which have run_number = 1
$indexedNotenArray[$gereadIdArrays][$sRechnung[0]][1] = $calcResult['value'];
// Track that this ID needs to be written to the database (Target run is 1)
$updatedValues[$gereadIdArrays][$sRechnung[0]][1] = $calcResult['value'];
// 4. Update State
$val = $calcResult['value'];
$indexedNotenArray[$targetGeraetKey][$targetNoteId][$acrun] = $val;
$updatedValues[$targetGeraetKey][$targetNoteId][$acrun] = $val;
}
// Prepare the statement once
$sql = "INSERT INTO $tableNoten (`value`, `person_id`, `note_bezeichnung_id`, `geraet_id`, `jahr`, `run_number`)
VALUES (?, ?, ?, ?, ?, ?)

View File

@@ -1,93 +0,0 @@
<?php
session_start();
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1 || !isset($_SESSION['selectedFreigabeKampfrichter']) || $_SESSION['selectedFreigabeKampfrichter'] !== 'admin') {
http_response_code(403);
exit;
}
header('Content-Type: application/json');
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
$type = 'kr';
$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';
if ($data['success'] === false){
echo json_encode(['success' => false, 'message' => $data['message']]);
exit;
}
require $baseDir . '/../scripts/db/db-tables.php';
// ---------- Get and sanitize input ----------
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$fieldType = isset($_POST['field_type']) ? preg_replace('/[^a-zA-Z0-9 _-]/', '', $_POST['field_type']) : '';
$discipline = isset($_POST['discipline']) ? preg_replace('/[^a-zA-Z0-9 _-]/', '', $_POST['discipline']) : '';
$value = isset($_POST['value']) ? floatval($_POST['value']) : 0;
if ($id <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid ID']);
exit;
}
if (!isset($value) || floatval($value) < 0 || !isset($discipline) || $discipline === ''|| !isset($fieldType) || $fieldType === '') {
http_response_code(422);
exit;
}
if ($discipline === 'all') {
$column = $fieldType;
} else {
$column = $fieldType . ' ' . $discipline;
}
$excluded_columns = [
'id',
'name',
'vorname',
'bezahlt',
'bezahltoverride',
'geburtsdatum',
'programm',
'verein',
'bodenmusik'
];
$sql = "SHOW COLUMNS FROM `$tableTurnerinnen`";
$result = $mysqli->query($sql);
$all_columns = [];
while ($row = $result->fetch_assoc()) {
$all_columns[] = $row['Field'];
}
$allowed_columns = array_values(
array_diff($all_columns, $excluded_columns)
);
if (!in_array($column, $allowed_columns, true)) {
http_response_code(422);
exit;
}
$stmt = $mysqli->prepare("UPDATE `$tableTurnerinnen` SET `$column` = ? WHERE id = ?");
$stmt->bind_param("di", $value, $id);
if (!$stmt->execute()) {
http_response_code(500);
exit;
}
$stmt->close();
$mysqli->close();
http_response_code(200);
echo json_encode([
'success' => true,
'message' => 'Updated successfully'
]);
exit;

View File

@@ -1,20 +1,23 @@
<?php
header('Content-Type: application/json');
session_start();
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
http_response_code(403);
exit;
}
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
require_once $baseDir . '/../scripts/session_functions.php';
ini_wkvs_session();
check_user_permission('kampfrichter');
verify_csrf();
// ---------- Get and sanitize input ----------
$id = intval($_POST['personId']) ?? 0;
$run = intval($_POST['run']) ?? 0;
$geraetId = intval($_POST['geraetId']) ?? 0;
$dataType = intval($_POST['dataType']) ?? 0;
$jahr = isset($_POST['jahr']) ? preg_replace('/[^0-9]/', '', $_POST['jahr']) : '';
$anfrageType = $_POST['type'] ?? '';
@@ -123,20 +126,28 @@ switch ($anfrageType) {
$jsonData = json_encode($data);
break;
case "start":
if (array_key_exists("start", $oldjson)) {
$oldjson["start"] = true;
$jsonData = json_encode($oldjson);
} else {
echo json_encode(['success' => false, 'message' => 'Turnerin nicht auf Display '.json_encode($oldjson).'; '.$jsonString]);
if (!array_key_exists("id", $oldjson) || intval($oldjson["id"]) !== $id || !array_key_exists("start", $oldjson)) {
echo json_encode(['success' => false, 'message' => 'Person nicht auf Display!']);
exit;
}
$oldjson["start"] = (bool) $dataType;
$jsonData = json_encode($oldjson);
break;
case "result":
// 1. Get IDs and filter out empty values
$noteLinksId = db_get_var($mysqli, "SELECT `value` FROM $tableVar WHERE `name` = ?", ['displayIdNoteL']);
$noteRechtsId = db_get_var($mysqli, "SELECT `value` FROM $tableVar WHERE `name` = ?", ['displayIdNoteR']);
$stmt = $mysqli->prepare("UPDATE $tableNoten SET `is_public` = 1, `public_value` = `value` WHERE `person_id` = ? AND `jahr` = ? AND `geraet_id` = ? AND `run_number` = ?");
$stmt->bind_param("ssss", $id, $jahr, $geraetId, $run);
$stmt->execute();
$stmt->close();
// Create an array of IDs that actually exist
$validIds = array_filter([$noteLinksId, $noteRechtsId]);
@@ -148,12 +159,12 @@ switch ($anfrageType) {
$placeholders = implode(',', array_fill(0, count($validIds), '?'));
$sqlNoten = "SELECT `value`, `note_bezeichnung_id` FROM $tableNoten
WHERE person_id = ? AND `jahr` = ? AND `geraet_id` = ?
WHERE person_id = ? AND `jahr` = ? AND `geraet_id` = ? AND run_number = ?
AND `note_bezeichnung_id` IN ($placeholders)";
$stmt = $mysqli->prepare($sqlNoten);
// Combine standard params with our dynamic ID list
$params = array_merge([$id, $jahr, $geraetId], $validIds);
$params = array_merge([$id, $jahr, $geraetId, $run], $validIds);
$types = str_repeat('s', count($params));
$stmt->bind_param($types, ...$params);
$stmt->execute();

View File

@@ -1,115 +0,0 @@
<?php
header('Content-Type: application/json');
session_start();
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
http_response_code(403);
exit;
}
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
$type = 'kr';
$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';
if ($data['success'] === false){
echo json_encode(['success' => false, 'message' => $data['message']]);
exit;
}
require $baseDir . '/../scripts/db/db-tables.php';
// ---------- Get and sanitize input ----------
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$discipline = isset($_POST['discipline']) ? preg_replace('/[^a-zA-Z0-9 _-]/', '', $_POST['discipline']) : '';
$stmt = $mysqli->prepare("SELECT `name` FROM $tableGeraete ORDER BY start_index ASC");
if (!$stmt->execute()) {
http_response_code(500);
exit;
}
$result = $stmt->get_result();
$allowed_disciplines = array_map(
'strtolower',
array_column($result->fetch_all(MYSQLI_ASSOC), 'name')
);
$stmt->close();
if (!in_array($discipline, $allowed_disciplines)) {
echo json_encode(['success' => false, 'message' => 'Invalid discipline']);
exit;
}
if ($id <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid ID']);
exit;
}
// ---------- Step 2: Get values from DB ----------
$result = $mysqli->query("SELECT * FROM `$tableTurnerinnen` WHERE id = $id");
$row = $result->fetch_assoc();
if (!$row) {
echo json_encode(['success' => false, 'message' => 'Row fetch failed']);
exit;
}
$folder = realpath($baseDir . '/displays/json');
if ($folder === false) {
echo json_encode([
'success' => false,
'message' => 'Could not find displays folder.'
]);
exit;
}
$filename = 'display_' . $discipline . '.json';
$filepath = $folder . '/' . $filename;
if (!is_writable($folder)) {
echo json_encode(['success' => false, 'message' => 'Folder not writable: ' . $folder]);
exit;
}
$jsonString = file_get_contents($filepath);
// decode JSON, fallback to empty array if invalid
$oldjson = json_decode($jsonString, true) ?? [];
if (array_key_exists("note", $oldjson) && array_key_exists("dnote", $oldjson)) {
$oldjson["note"] = (float)$row['note '.$discipline];
$oldjson["dnote"] = (float)$row['d-note '.$discipline];
} else {
echo json_encode([
'success' => false,
'message' => 'ERROR: JSON keys "note" or "dnote" do not exist'
]);
exit;
}
$jsonData = json_encode($oldjson);
// Write file
if (file_put_contents($filepath, $jsonData) === false) {
echo json_encode([
'success' => false,
'message' => 'Failed to write JSON file: ' . $filepath
]);
exit;
}
// ---------- Return JSON ----------
echo json_encode([
'success' => true,
'message' => 'JSON updated successfully for '.$discipline,
]);
exit;

View File

@@ -1,97 +0,0 @@
<?php
header('Content-Type: application/json');
session_start();
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
http_response_code(403);
exit;
}
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
// ---------- Get and sanitize input ----------
$discipline = isset($_GET['discipline']) ? preg_replace('/[^a-zA-Z0-9 _-]/', '', $_GET['discipline']) : '';
$type = 'kr';
$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';
if ($data['success'] === false){
echo json_encode(['success' => false, 'message' => $data['message']]);
exit;
}
require $baseDir . '/../scripts/db/db-tables.php';
$stmt = $mysqli->prepare("SELECT `name` FROM $tableGeraete ORDER BY start_index ASC");
if (!$stmt->execute()) {
http_response_code(500);
exit;
}
$result = $stmt->get_result();
$allowed_disciplines = array_map(
'strtolower',
array_column($result->fetch_all(MYSQLI_ASSOC), 'name')
);
$stmt->close();
if (!in_array($discipline, $allowed_disciplines)) {
echo json_encode(['success' => false, 'message' => 'Invalid discipline']);
exit;
}
$folder = realpath($baseDir . '/displays/json');
if ($folder === false) {
echo json_encode([
'success' => false,
'message' => 'Could not find displays folder.'
]);
exit;
}
$filename = 'display_' . $discipline . '.json';
$filepath = $folder . '/' . $filename;
if (!is_writable($folder)) {
echo json_encode(['success' => false, 'message' => 'Folder not writable']);
exit;
}
$jsonString = file_get_contents($filepath);
// decode JSON, fallback to empty array if invalid
$oldjson = json_decode($jsonString, true) ?? [];
if (array_key_exists("start", $oldjson)) {
$oldjson["start"] = true;
$jsonData = json_encode($oldjson);
} else {
echo json_encode(['success' => false, 'message' => 'Turnerin nicht auf Display '.json_encode($oldjson).'; '.$jsonString]);
exit;
}
// Write file
if (file_put_contents($filepath, $jsonData) === false) {
echo json_encode([
'success' => false,
'message' => 'Failed to write JSON file'
]);
exit;
}
// ---------- Return JSON ----------
echo json_encode([
'success' => true,
'message' => 'JSON updated successfully for '.$discipline,
'disable_start_button' => true
]);
exit;

View File

@@ -1,122 +0,0 @@
<?php
header('Content-Type: application/json');
session_start();
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
$type = 'kr';
$data = include $baseDir . '/../scripts/db/db-verbindung-script.php';
if ($data['success'] === false){
echo json_encode(['success' => false, 'message' => $data['message']]);
exit;
}
require $baseDir . '/../scripts/db/db-tables.php';
// ---------- Get and sanitize input ----------
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$discipline = isset($_GET['discipline']) ? preg_replace('/[^a-zA-Z0-9 _-]/', '', $_GET['discipline']) : '';
$stmt = $mysqli->prepare("SELECT `name` FROM $tableGeraete ORDER BY start_index ASC");
if (!$stmt->execute()) {
http_response_code(500);
exit;
}
$result = $stmt->get_result();
$allowed_disciplines = array_map(
'strtolower',
array_column($result->fetch_all(MYSQLI_ASSOC), 'name')
);
$stmt->close();
if (!in_array($discipline, $allowed_disciplines)) {
echo json_encode(['success' => false, 'message' => 'Invalid discipline']);
exit;
}
if ($id <= 0) {
echo json_encode(['success' => false, 'message' => 'Invalid ID']);
exit;
}
// ---------- Step 2: Get values from DB ----------
$result = $mysqli->query("SELECT name, vorname, verein, programm FROM `$tableTurnerinnen` WHERE id = $id");
$row = $result->fetch_assoc();
if (!$row) {
echo json_encode(['success' => false, 'message' => 'Row fetch failed']);
exit;
}
$folder = realpath($baseDir . '/displays/json');
if ($folder === false) {
echo json_encode([
'success' => false,
'message' => 'Could not find displays folder. Tried: ' . __DIR__ . '/../displays'
]);
exit;
}
$filename = 'display_' . $discipline . '.json';
$filepath = $folder . '/' . $filename;
if (!is_writable($folder)) {
echo json_encode(['success' => false, 'message' => 'Folder not writable: ' . $folder]);
exit;
}
if (file_put_contents($filepath, $jsonData) === false) {
echo json_encode(['success' => false, 'message' => 'Failed to write file: ' . $filepath]);
exit;
}
$jsonString = file_get_contents($folder . $filename);
// decode JSON, fallback to empty array if invalid
$oldjson = json_decode($jsonString, true) ?? [];
// safely get value, default 0 if missing
$olduniqueid = $oldjson['uniqueid'] ?? 0;
$uniqueid = $olduniqueid + 1;
$data = ["note" => 'nan',
"dnote" => 'nan',
"id" => $id,
"name" => $row['name'],
"vorname" => $row['vorname'],
"programm" => $row['programm'],
"verein" => $row['verein'],
"start" => false,
"musik" => 'nan',
"uniqueid" => $uniqueid];
$jsonData = json_encode($data);
// Encode JSON with readable formatting
$jsonData = json_encode($data);
// Write file
if (file_put_contents($filepath, $jsonData) === false) {
echo json_encode([
'success' => false,
'message' => 'Failed to write JSON file: ' . $filepath
]);
exit;
}
// ---------- Return JSON ----------
echo json_encode([
'success' => true,
'message' => 'JSON updated successfully for '.$discipline,
'disable_turnerin_button' => true,
'enable_result_button' => true
]);
exit;

View File

@@ -1,160 +0,0 @@
<?php
session_start();
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
http_response_code(403);
exit;
}
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
header('Content-Type: application/json');
if (!isset($baseDir)) {
$baseDir = $_SERVER['DOCUMENT_ROOT'];
}
$type = 'kr';
$data = require $baseDir . '/../scripts/db/db-verbindung-script.php';
if ($data['success'] === false){
echo json_encode(['success' => false, 'message' => $data['message']]);
exit;
}
require $baseDir . '/../scripts/db/db-functions.php';
require $baseDir . '/../scripts/db/db-tables.php';
$noten = db_select($mysqli, $tableNotenBezeichnungen, "id, berechnung, type");
// 1. Re-index the array so the keys match the database IDs
$notenById = array_column($noten, null, 'id');
$berechnungen = [];
foreach ($notenById as $id => $sn) {
if ($sn['type'] === 'berechnung') {
$berechnungen[] = $sn;
}
}
if (empty($berechnungen)) {
echo json_encode(['success' => true, 'message' => "Keine Berechnungen ausgewählt"]);
exit;
}
require $baseDir . "/../scripts/string-calculator/string-calculator-functions.php";
$notenRechner = new NotenRechner();
// 1. Build the direct map
// Format: [ Changed_Note_ID => [ "CalcId|GeraetId" => [CalcId, GeraetId] ] ]
$dependencyMap = [];
foreach ($berechnungen as $calc) {
$neededIdsArray = $notenRechner->getBenoetigteIdsComplex($calc['berechnung']);
if (empty($neededIdsArray)) {
continue;
}
$calcId = (int)$calc['id'];
foreach ($neededIdsArray as $needed) {
$nId = (int)$needed['noteId'];
// Keep geraetId as integer if it's a number (e.g., 3), otherwise string ('S')
$gId = is_numeric($needed['geraetId']) ? (int)$needed['geraetId'] : $needed['geraetId'];
// Create a unique string key so we don't store exact duplicates
$nodeKey = $calcId . '|' . $gId;
if (!isset($dependencyMap[$nId])) {
$dependencyMap[$nId] = [];
}
// Store it as the "little array" you requested: [DependentCalcId, GeraetId]
$dependencyMap[$nId][$nodeKey] = [$calcId, $gId];
}
}
// 2. Our recursive helper function (Updated for complex nodes)
function getCompleteDependencyChain($id, $directMap, $visited = [])
{
// If this ID doesn't have anything depending on it, return empty
if (!isset($directMap[$id])) {
return [];
}
$allDependencies = [];
foreach ($directMap[$id] as $nodeKey => $complexNode) {
// CIRCULAR DEPENDENCY CHECK:
// We check against the string key (e.g., "10|S") to prevent infinite loops
if (isset($visited[$nodeKey])) {
continue;
}
// 1. Mark this specific node as visited
$visited[$nodeKey] = true;
// 2. Add the little array [CalcId, GeraetId] to our master list
$allDependencies[$nodeKey] = $complexNode;
// 3. Recursively find everything that depends on THIS calculation ID
// $complexNode[0] is the dependent Calc ID
$childDependencies = getCompleteDependencyChain($complexNode[0], $directMap, $visited);
// 4. Merge the child results into our master list safely
foreach ($childDependencies as $childKey => $childNode) {
$allDependencies[$childKey] = $childNode;
$visited[$childKey] = true; // Ensure the parent loop knows this was visited
}
}
return $allDependencies;
}
// 3. Create the final flattened map for ALL IDs
$flatDependencyMap = [];
foreach (array_keys($notenById) as $id) {
$chain = getCompleteDependencyChain($id, $dependencyMap);
// Only add it if dependencies exist
if (!empty($chain)) {
// array_values() removes the "10|S" string keys, turning it into a perfect
// 0-indexed array for clean JSON encoding: [[10, "S"], [12, 3]]
$flatDependencyMap[$id] = array_values($chain);
}
}
// 4. Database Updates
// Step 1: Reset all rows to NULL in a single query
$resetSql = "UPDATE $tableNotenBezeichnungen SET `berechnung_json` = NULL";
$mysqli->query($resetSql);
// Step 2: Prepare the statement
$updateSql = "UPDATE $tableNotenBezeichnungen SET `berechnung_json` = ? WHERE id = ?";
$stmt = $mysqli->prepare($updateSql);
foreach ($flatDependencyMap as $id => $completeDependencyArray) {
if (empty($completeDependencyArray)) {
continue;
}
$jsonString = json_encode($completeDependencyArray);
// Bind parameters: 's' for string (JSON), 'i' for integer (ID)
$stmt->bind_param("si", $jsonString, $id);
$stmt->execute();
}
$stmt->close();
echo json_encode(['success' => true, 'message' => "Abhaengigkeiten berechnet"]);
exit;

View File

@@ -5,7 +5,7 @@ ini_set('display_startup_errors', 1);
session_start();
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['passcodekampfrichter_id']) || $_SESSION['passcodekampfrichter_id'] < 1) {
if (empty($_SESSION['access_granted_kampfrichter']) || $_SESSION['access_granted_kampfrichter'] !== true || empty($_SESSION['user_id_kampfrichter']) || $_SESSION['user_id_kampfrichter'] < 1) {
http_response_code(403);
exit;
}

View File

@@ -20,6 +20,7 @@ function toggleFullscreen() {
}
let messagePosArray = [];
const csrf_token = window.CSDR_TOKEN;
function displayMsg(type, msg) {
const colors = ["#900000ff", "#00b200ff"];
@@ -75,9 +76,15 @@ async function fetchNewWSToken(freigabe) {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({ access: freigabe })
body: new URLSearchParams({ access: freigabe, csrf_token })
});
if (response.status === 403) {
console.warn("Please Re-Autenithicate. Reloading page...");
location.reload();
return null;
}
if (!response.ok) return null;
const data = await response.json();
@@ -152,7 +159,39 @@ function scheduleRetry() {
// Start the initial connection attempt safely
startWebSocket();
function updateRunButtons(targetCount, personId, $container) {
if (targetCount === 0) { return; }
const geraetId = $container.find('.submit-display-result').first().data('geraet-id') || "";
const currentCount = $container.find('.submit-display-result').length;
if (targetCount > currentCount) {
for (let i = currentCount + 1; i <= targetCount; i++) {
const buttonHtml = `
<input type="button" class="submit-display-result"
data-person-id="${personId}"
data-geraet-id="${geraetId}"
data-run="${i}"
value="Ergebnis anzeigen (Run ${i})">`;
$container.append(buttonHtml);
}
$container.find('.submit-display-result[data-run="1"]').val('Ergebnis anzeigen (Run 1)');
} else if (targetCount < currentCount) {
for (let i = currentCount; i > targetCount; i--) {
$container.find(`.submit-display-result[data-run="${i}"]`).remove();
}
if (targetCount === 1 && $container.find('.submit-display-result').length === 1) {
$container.find('.submit-display-result').val('Ergebnis anzeigen');
}
}
$container.find('.submit-display-result').each(function() {
$(this).attr('data-person-id', personId);
});
}
$.fn.updateCurrentEdit = function() {
return this.each(function() {
@@ -183,7 +222,7 @@ $.fn.updateCurrentEdit = function() {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
csrf_token: window.CSDR_TOKEN,
csrf_token,
editId: $input.attr('data-person-id'),
geraet: $input.attr('data-geraet-id') ?? null
})
@@ -196,10 +235,13 @@ $.fn.updateCurrentEdit = function() {
'color': '#209200ff',
'transition': 'all 0.3s ease-out'
});
setTimeout(() => $(".current-turnerin-name").css({
'color': ''
}), 2000);
$(".heading_fv_selturnerin").focus();
$(".div_edit_values_user").css("display", "flex");
$(".current-turnerin-name").text(response.titel);
@@ -212,86 +254,93 @@ $.fn.updateCurrentEdit = function() {
$(".submit-display-result").css("opacity", "1");
const $editAllDiv = $('.div_edit_values_all_gereate');
const noten = response.noten;
const programmId = response.programm_id;
const noten = response.noten;
const personId = response.id;
// First, reset all containers to a single input state and clear values
$editAllDiv.find('.note-container').each(function() {
const $container = $(this);
const $tbody = $container.find('tbody');
const $headerRow = $container.find('thead tr');
// 1. Loop directly through the 'noten' object
for (const [geraetId, disciplineData] of Object.entries(noten)) {
// Reset header
$headerRow.find('.run-num-header').remove();
// Find the specific DOM wrapper for this Geraet using the outer div
// Assuming your PHP renders the tables with the correct geraetId on the button
const $disciplineWrapper = $editAllDiv.find(`.submit-display-turnerin[data-geraet-id="${geraetId}"]`).closest('.all_vaules_div');
// Remove extra inputs beyond run 1
$tbody.find('.inputs-row').each(function() {
$(this).find('td:not(.input-cell-run-1)').remove();
if ($disciplineWrapper.length === 0) continue;
// --- UPDATE GENERAL BUTTONS FOR THIS GERAET ---
$disciplineWrapper.find(".submit-display-turnerin, .submit-display-start").attr({
'data-person-id': personId,
'data-geraet-id': geraetId
});
// Clear value of run 1
$container.find('input[data-run="1"]').val('').attr('data-person-id', response.id);
});
$disciplineWrapper.find(".submit-musik-start, .submit-musik-stopp").attr({
'data-id': personId,
'data-geraet': geraetId
});
// Now loop through the data and populate/expand
for (const [geraetId, noteGroup] of Object.entries(noten)) {
for (const [noteId, runGroup] of Object.entries(noteGroup)) {
const $container = $editAllDiv.find(`.note-container[data-note-id="${noteId}"]`);
if ($container.length === 0) continue;
// 2. Identify master containers for this specific discipline
const $masterContainer = $disciplineWrapper.find('.singleNotentable').first();
const $displayresultDiv = $disciplineWrapper.find('.div-submit-display-result');
// 3. CLEANUP: Remove previously generated runs and buttons
$disciplineWrapper.find('.singleNotentable').not(':first').remove();
$displayresultDiv.find('.submit-display-result').not(':first').remove();
const $tbody = $container.find('tbody');
const $headerRow = $container.find('thead tr');
const $inputsRow = $tbody.find('.inputs-row');
const runCount = Object.keys(runGroup).length;
const $originalResultBtn = $displayresultDiv.find('.submit-display-result').first();
const runKeys = Object.keys(disciplineData).sort((a, b) => a - b);
const totalRuns = runKeys.length;
$headerRow.find('.note-name-header .rm').remove();
console.log(totalRuns);
const originalText = $headerRow.find('.note-name-header').text().trim();
// 4. Process each Run in the data
runKeys.forEach(runNum => {
const runInt = parseInt(runNum);
let $currentRunContainer;
// If more than 1 run, add headers if not already present
if (runCount > 1 && $headerRow.find('.run-num-header').length === 0) {
$headerRow.find('.note-name-header').html(originalText + ' <span class="rm">(R1)</span>');
for (let r = 2; r <= runCount; r++) {
$headerRow.append(`<th class="run-num-header">${originalText} <span class="rm">(R${r})</span></th>`);
}
if (runInt === 1) {
$currentRunContainer = $masterContainer;
} else {
// CLONE the entire container for Run 2, 3, etc.
$currentRunContainer = $masterContainer.clone();
$currentRunContainer.addClass(`run-container-block run-${runNum}`);
$currentRunContainer.insertAfter($disciplineWrapper.find('.singleNotentable').last());
}
for (const [runNum, val] of Object.entries(runGroup)) {
let $input = $inputsRow.find(`input[data-run="${runNum}"][data-geraet-id="${geraetId}"]`);
// 5. Update all Tables and Inputs inside this Run Container
for (const [noteId, value] of Object.entries(disciplineData[runNum])) {
const $table = $currentRunContainer.find(`.note-container[data-note-id="${noteId}"]`);
// If input doesn't exist yet (for Run 2+), clone it
if ($input.length === 0) {
const $cell1 = $inputsRow.find('.input-cell-run-1');
const $newCell = $cell1.clone();
$newCell.removeClass('input-cell-run-1').addClass(`input-cell-run-${runNum}`);
$input = $newCell.find('input');
$input.attr('data-run', runNum).val(val ?? '');
$inputsRow.append($newCell);
// Re-bind change event to new input
//bindAjaxInput($input);
} else {
$input.val(val ?? '').attr('data-person-id', response.id);
// Update Header to show Run Number
if (runInt > 1) {
const $header = $table.find('.note-name-header');
if (!$header.find('.rm-tag').length) {
$header.append(` <span class="rm-tag" style="font-size: 0.8em;">(R${runNum})</span>`);
}
}
// Update Input attributes and value
const $input = $table.find('input');
$input.attr({
'data-run': runNum,
'data-person-id': personId,
'data-geraet-id': geraetId
}).val(value ?? '');
}
}
// 6. Remove tables cloned from Run 1 that don't exist in Run 2+
if (runInt > 1) {
$currentRunContainer.find('input[data-run="1"]').closest('.note-container').remove();
}
});
// Ensure the UI script tracking the buttons is updated last
updateRunButtons(totalRuns, personId, $displayresultDiv);
}
$(".submit-display-turnerin").attr('data-person-id', response.id);
$(".submit-display-start").attr('data-person-id', response.id);
const submitMusikStart = $(".submit-musik-start");
const submitMusikStopp = $(".submit-musik-stopp");
if (submitMusikStart.length > 0 && submitMusikStopp.length > 0){
submitMusikStart.attr('data-id', response.id);
submitMusikStopp.attr('data-id', response.id);
}
$(".submit-display-result").attr('data-person-id', response.id);
//$(".submit-display-result").attr('data-person-id', response.id);
} else {
displayMsg(0, response.message);
@@ -320,60 +369,63 @@ jQuery(document).ready(function($) {
$(this).updateCurrentEdit();
});
const $ajaxInputDiv = $('.div_edit_values_all_gereate');
$ajaxInputDiv.on('change', '.ajax-input', function(e) {
const start = performance.now();
const $input = $(this);
const url = `/intern/scripts/kampfrichter/ajax/ajax-update_value_kampfrichter.php`;
function bindAjaxInput($el) {
$el.on('change', function() {
const start = performance.now();
const $input = $(this);
const url = `/intern/scripts/kampfrichter/ajax/ajax-update_value_kampfrichter.php`;
personId = $input.data('person-id');
fieldTypeId = $input.data('field-type-id');
gereatId = $input.data('geraet-id');
runNum = $input.attr('data-run') || 1;
jahr = window.AKTUELLES_JAHR;
value = $input.val();
personId = $input.data('person-id');
fieldTypeId = $input.data('field-type-id');
gereatId = $input.data('geraet-id');
runNum = $input.attr('data-run') || 1;
jahr = window.AKTUELLES_JAHR;
value = $input.val();
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
personId: personId,
fieldTypeId: fieldTypeId,
gereatId: gereatId,
run: runNum,
jahr: jahr,
value: value
})
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
csrf_token,
personId: personId,
fieldTypeId: fieldTypeId,
gereatId: gereatId,
run: runNum,
jahr: jahr,
value: value
})
.then(res => res.json())
.then(response => {
const end = performance.now();
console.log(`Total AJAX time: ${(end - start).toFixed(3)} ms`);
if (response.success) {
})
.then(res => res.json())
.then(response => {
const end = performance.now();
console.log(`Total AJAX time: ${(end - start).toFixed(3)} ms`);
if (response.success) {
let objValues = [];
const rowId = $input.attr('data-id');
$input.css({"color": "#0e670d", "font-weight": "600"});
setTimeout(() => $input.css({'color': '', "font-weight": ""}), 2000);
const noten = response.noten;
for (const [keyN, noteGroup] of Object.entries(noten)) {
for (const [key, runGroup] of Object.entries(noteGroup)) {
if (key == fieldTypeId && keyN == gereatId) { continue; }
for (const [run, value] of Object.entries(runGroup)) {
$(`input.changebleValue[data-field-type-id="${key}"][data-geraet-id="${keyN}"][data-person-id="${personId}"][data-run="${run}"]`)
const selectorBase = `[data-field-type-id="${key}"][data-geraet-id="${keyN}"][data-person-id="${personId}"][data-run="${run}"]`;
// Handle Inputs (excluding current one)
$(`input.changebleValue${selectorBase}`)
.not(this)
.val(value ?? '');
$(`.changebleValue:not(input)[data-field-type-id="${key}"][data-geraet-id="${keyN}"][data-person-id="${personId}"][data-run="${run}"]`)
// Handle Display elements (Spans/Divs)
$(`.changebleValue:not(input)${selectorBase}`)
.text(value ?? '');
}
}
@@ -389,101 +441,20 @@ jQuery(document).ready(function($) {
noten: noten
}
}));
} else {
// Flash red on error
$input.css({'color': '#ff6a76ff'});
displayMsg(0, response.message || 'Unknown error');
console.error(response.message || 'Unknown error');
}
})
.catch(err => {
$input.css({'color': '#670d0d'});
console.error('AJAX fetch error:', err);
});
});
}
$('.ajax-input').each(function() {
bindAjaxInput($(this));
} else {
// Flash red on error
$input.css({'color': '#ff6a76ff'});
displayMsg(0, response.message || 'Unknown error');
console.error(response.message || 'Unknown error');
}
})
.catch(err => {
$input.css({'color': '#670d0d'});
console.error('AJAX fetch error:', err);
});
});
/*$('.ranglisteExport').on('click', function(e) {
const $input = $(this);
if ($input.data('field_type') !== 'upload_programm') {e.preventDefault();}
// Build the data to send
const data = new URLSearchParams();
data.append('prog', $input.data('id'));
data.append('type', $input.data('field_type'));
// Record start time
const start = performance.now();
const url = '/intern/scripts/kampfrichter/ajax/ajax-neu_rangliste.php';
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
prog: $input.data('id'),
type: $input.data('field_type')
})
})
.then(res => res.blob())
.then(blob => {
if ($input.data('field_type') !== 'upload_programm'){
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = "KTBB_Ergebnisse.pdf"; // optional
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
} else {
alert('PDF auf Webseite geladen!');
}
});
});
$('.protokollExport').on('click', function() {
console.log('ok');
const $input = $(this);
// Build the data to send
const data = new URLSearchParams();
data.append('abteilung', $input.data('abteilung'));
// Record start time
const start = performance.now();
const url = '/intern/scripts/kampfrichter/ajax/ajax-neu_protokoll.php';
fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
abteilung: $input.data('abteilung')
})
})
.then(res => res.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = "KTBB_Protokoll.pdf"; // optional
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
});
});*/
$('.inputnamekr').on('change', function() {
const $input = $(this);
@@ -494,6 +465,7 @@ jQuery(document).ready(function($) {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
csrf_token,
aufgabe: $input.data('id'),
abteilung: $input.data('abt'),
geraet: $input.data('user'),
@@ -534,50 +506,6 @@ jQuery(document).ready(function($) {
});
/**
* Handle namekr input updates
$('.ajax-input-namekr').on('change', function() {
let $input = $(this);
$.post(ajax_object.ajaxurl, {
action: 'save_namekr_input',
id: $input.data('id'),
abt: $input.data('abt'),
user: $input.data('user'),
value: $input.val()
}, function(response) {
if (response.success) {
console.log(response.data.message);
$input.css({
'background-color': '#a4bf4a',
'color': '#fff',
'transition': 'all 0.3s ease-out'
});
setTimeout(() => $input.css({
'background-color': '',
'color': ''
}), 2000);
} else {
console.error(response.data.message);
$input.css({
'background-color': '#f8d7da',
'color': '#fff',
'transition': 'all 0.3s ease-out'
});
setTimeout(() => $input.css({
'background-color': '',
'color': ''
}), 2000);
}
}, 'json');
}); */
/**
* Handle display JSON updates
*/
$('.submit-display-turnerin').on('click', function() {
const $input = $(this);
@@ -588,6 +516,7 @@ jQuery(document).ready(function($) {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
csrf_token,
personId: $input.attr('data-person-id'),
geraetId: $input.attr('data-geraet-id'),
jahr: window.AKTUELLES_JAHR,
@@ -623,12 +552,16 @@ jQuery(document).ready(function($) {
const $input = $(this);
const url = '/intern/scripts/kampfrichter/ajax/displays/ajax-display-functions.php';
const dataType = $input.attr('data-type');
fetch(url,{
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
csrf_token,
geraetId: $input.attr('data-geraet-id'),
personId: $input.attr('data-person-id'),
dataType: dataType,
type: "start"
})
})
@@ -643,11 +576,16 @@ jQuery(document).ready(function($) {
data: response.data
}
}));
displayMsg(1, 'Start freigegeben');
$input.css('opacity', 0.5);
if (dataType == 1) {
displayMsg(1, 'Start freigegeben');
} else if (dataType == 0) {
displayMsg(1, 'Startfreigabe entzogen');
}
} else {
alert('Error: ' + response.message);
displayMsg(0, response.message);
}
})
.catch(err => {
@@ -656,48 +594,23 @@ jQuery(document).ready(function($) {
console.error('AJAX fetch error:', err);
});
});
/*$('.submit-display-start').on('click', function() {
let discipline = $(this).data('discipline');
$.post(ajax_object.ajaxurl, {
action: 'write_discipline_json_start',
discipline: discipline
}, function(response) {
if (response.success) {
alert('Start freigegeben');
if (response.data.disable_start_button) {
$('.submit-display-start').css({
'border': '1px solid #aaa',
'background-color': '#aaa',
'color': '#555',
'pointer-events': 'none'
});
$('.submit-musik-start').css({
'background-color': '#077',
'border': '1px solid #077',
'color': '#fff',
'cursor': 'pointer',
'pointer-events': 'auto'
});
}
} else {
alert('Error: ' + response.data.message);
}
}, 'json');
});*/
$('.submit-musik-start').on('click', function() {
const $input = $(this);
// Build the URL with GET parameters safely
const url = `/intern/scripts/kampfrichter/ajax/ajax-update_kampfrichter_start_musik.php` +
`?id=${$input.attr('data-id')}` +
`&discipline=${encodeURIComponent($input.data('geraet'))}`;
const url = `/intern/scripts/kampfrichter/ajax/ajax-update_kampfrichter_start_musik.php`;
fetch(url)
fetch(url,{
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
csrf_token,
id: $input.attr('data-id'),
discipline: $input.data('geraet')
})
})
.then(res => res.json())
.then(response => {
const end = performance.now();
@@ -725,7 +638,13 @@ jQuery(document).ready(function($) {
// Build the URL with GET parameters safely
const url = `/intern/scripts/kampfrichter/ajax/ajax-update_kampfrichter_stopp_musik.php`;
fetch(url)
fetch(url,{
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
csrf_token
})
})
.then(res => res.json())
.then(response => {
if (response.success) {
@@ -745,7 +664,7 @@ jQuery(document).ready(function($) {
});
});
$('.submit-display-result').on('click', function() {
$('.div-submit-display-result').on('click', '.submit-display-result', function() {
$input = $(this);
// Build the URL with GET parameters safely
@@ -755,8 +674,10 @@ jQuery(document).ready(function($) {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
csrf_token,
personId: $input.attr('data-person-id'),
geraetId: $input.attr('data-geraet-id'),
run: $input.attr("data-run"),
jahr: window.AKTUELLES_JAHR,
type: "result"
})
@@ -843,34 +764,3 @@ ws.addEventListener("message", event => { // Use 'event' as it's more standard t
}
}
});
/*document.getElementById('freigabe-select').addEventListener('change', function() {
const freigabe = this.value;
const user_id = document.getElementById('user_id').value;
const nonce = document.getElementById('freigabe_nonce').value;
const type = document.getElementById('type_freigabe').value;
const params = new URLSearchParams();
params.append('action', 'save_freigabe');
params.append('freigabe', freigabe);
params.append('user_id', user_id);
params.append('type', type);
fetch('/intern/scripts/kampfrichter/ajax/ajax-update_selected_kampfrichter.php', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params
})
.then(res => res.json())
.then(data => {
if (data.success) {
window.location.reload();
} else {
alert('Error: ' + data.data);
}
})
.catch(err => {
console.error(err);
displayMsg(0, 'AJAX fetch error:' + err);
});
});*/