Merge branch 'master' into fronkdev

This commit is contained in:
Frank Schubert
2025-08-07 13:30:09 +02:00
81 changed files with 3442 additions and 1320 deletions
+3 -3
View File
@@ -477,8 +477,8 @@ foreach ($devicesall as $deviceall) {
<h4>OLT/ONT Informationen </h4> <h4>OLT/ONT Informationen </h4>
<h5><span id="olt-uptime"></span></h5> <h5><span id="olt-uptime"></span></h5>
</div> </div>
<div class="col-lg-6"> <div id="service-ports-h4" class="col-lg-6" style="display:none">
<h4>Serviceports von <span style="width: 20px;" <h4>Serviceports von <span style="width: 20px"
class="mr-4 ont-serviceport-refresh-span "><i class="mr-4 ont-serviceport-refresh-span "><i
title="Refresh" title="Refresh"
class="fa-solid fa-rotate-right ont-serviceport-refresh"></i></span> class="fa-solid fa-rotate-right ont-serviceport-refresh"></i></span>
@@ -825,7 +825,7 @@ foreach ($devicesall as $deviceall) {
if (data.success == false) { if (data.success == false) {
$('#olt-body').text('Keine OLT/ONT Daten verfügbar'); $('#olt-body').text('Keine OLT/ONT Daten verfügbar');
} else { } else {
$('#service-ports-h4').show();
$('#olt-body').append(`<div > $('#olt-body').append(`<div >
<table class="sp-table-border float-left" > <table class="sp-table-border float-left" >
<thead><tr><td>OLT</td></tr></thead> <thead><tr><td>OLT</td></tr></thead>
+1 -5
View File
@@ -97,10 +97,7 @@
background-color: #d7d7d7; background-color: #d7d7d7;
opacity: 1; opacity: 1;
} }
</style> </style>
<!-- start page title -->
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
<div class="page-title-box"> <div class="page-title-box">
@@ -126,7 +123,6 @@
</div> </div>
</div> </div>
</div> </div>
<!-- end page title -->
<?php <?php
$plugs[1] = "LC"; $plugs[1] = "LC";
$plugs[2] = "SC"; $plugs[2] = "SC";
@@ -181,7 +177,7 @@ if (!empty(trim($pops->vlan_ipv6)))
</tr> </tr>
<tr> <tr>
<th class="text-nowrap">Dokustand | Status</th> <th class="text-nowrap">Dokustand | Status</th>
<td><?= ($pops->doku_date) ? date("d.m.Y") : '-' ?><span class="ml-2 mr-2">|</span><?= ($pops->state) ? $stateArray[$pops->state] : '-' ?> </td> <td><?= ($pops->doku_date) ? date("d.m.Y",$pops->doku_date) : '-' ?><span class="ml-2 mr-2">|</span><?= ($pops->state) ? $stateArray[$pops->state] : '-' ?> </td>
</tr> </tr>
<tr> <tr>
<th class="text-nowrap">Fotospeicherort</th> <th class="text-nowrap">Fotospeicherort</th>
+26 -5
View File
@@ -519,7 +519,7 @@ $pagination_entity_name = "Vorbestellungen";
} }
} }
$requiredFlagIds = [3, 4, 5]; $requiredFlagIds = [1, 3, 4, 5];
$allFlagsChecked = true; $allFlagsChecked = true;
foreach ($requiredFlagIds as $flagId) { foreach ($requiredFlagIds as $flagId) {
@@ -545,7 +545,19 @@ $pagination_entity_name = "Vorbestellungen";
<?=__($preorder->type, "preorder")?><br /> <?=__($preorder->type, "preorder")?><br />
<?=$preorder->ucode?> <?=$preorder->ucode?>
</td> </td>
<td class="status"><?=$preorder->status->code?> - <?=$preorder->status->name?></td> <td class="status"><?=$preorder->status->code?> - <?=$preorder->status->name?>
<?php foreach(PreorderStatusflagModel::search(['ids' => [3,4]]) as $flag): ?>
<br><input type="checkbox" class="preorder-statusflag-main"
id="preorder-<?=$preorder->id?>-statusflag-<?=$flag->id?>"
data-preorder_id="<?=$preorder->id?>"
data-flag_id="<?=$flag->id?>"
<?=(array_key_exists($flag->id, $preorder->statusflags) && $preorder->statusflags[$flag->id]->value && $preorder->statusflags[$flag->id]->value->value) ? "checked='checked'" : ""?>
/>
<label class="m-0" style="font-weight: unset!important;" for="preorder-<?=$preorder->id?>-statusflag-<?=$flag->id?>" id="preorder-<?=$preorder->id?>-statusflag-<?=$flag->id?>-text" class="text-nowrap">
<?=$preorder->statusflags[$flag->id]->name?>
</label>
<?php endforeach; ?>
</td>
<?php if($preorder->building_id): ?> <?php if($preorder->building_id): ?>
<td><?=$preorder->building->street?><br /><?=$preorder->building->zip?> <?=$preorder->building->city?></td> <td><?=$preorder->building->street?><br /><?=$preorder->building->zip?> <?=$preorder->building->city?></td>
<?php elseif($preorder->adb_hausnummer_id): ?> <?php elseif($preorder->adb_hausnummer_id): ?>
@@ -576,8 +588,8 @@ $pagination_entity_name = "Vorbestellungen";
<td><?=($preorder->partner_id) ? $preorder->partner->getCompanyOrName() : ""?></td> <td><?=($preorder->partner_id) ? $preorder->partner->getCompanyOrName() : ""?></td>
<td> <td>
<label><input type="checkbox" name="attributes_bep_specified" id="attributes_bep_specified-<?=$preorder->id?>" data-preorder-id="<?=$preorder->id?>" value="1" <?=(is_array($preorder->attribute) && array_key_exists("bep_specified", $preorder->attribute) && $preorder->attribute["bep_specified"]) ? "checked='checked'" : ""?> /> Borderpoint festgelegt</label><br /> <label class="m-0" style="font-weight: unset!important;"><input type="checkbox" name="attributes_bep_specified" id="attributes_bep_specified-<?=$preorder->id?>" data-preorder-id="<?=$preorder->id?>" value="1" <?=(is_array($preorder->attribute) && array_key_exists("bep_specified", $preorder->attribute) && $preorder->attribute["bep_specified"]) ? "checked='checked'" : ""?> /> Borderpoint festgelegt</label><br />
<label><input type="checkbox" name="attributes_inhouse_cabling_supplied" id="attributes_inhouse_cabling_supplied-<?=$preorder->id?>" data-preorder-id="<?=$preorder->id?>" value="1" <?=(is_array($preorder->attribute) && array_key_exists("inhouse_cabling_supplied", $preorder->attribute) && $preorder->attribute["inhouse_cabling_supplied"]) ? "checked='checked'" : ""?> /> Starterpaket erhalten</label> <label class="m-0" style="font-weight: unset!important;"><input type="checkbox" name="attributes_inhouse_cabling_supplied" id="attributes_inhouse_cabling_supplied-<?=$preorder->id?>" data-preorder-id="<?=$preorder->id?>" value="1" <?=(is_array($preorder->attribute) && array_key_exists("inhouse_cabling_supplied", $preorder->attribute) && $preorder->attribute["inhouse_cabling_supplied"]) ? "checked='checked'" : ""?> /> Starterpaket erhalten</label>
</td> </td>
<td style="white-space: nowrap" class="text-monospace"> <td style="white-space: nowrap" class="text-monospace">
<?=date('d.m.Y H:i', $preorder->create)?><br /> <?=date('d.m.Y H:i', $preorder->create)?><br />
@@ -1026,7 +1038,7 @@ $pagination_entity_name = "Vorbestellungen";
} }
} }
$("input.preorder-statusflag").change((e) => { $("input.preorder-statusflag, input.preorder-statusflag-main").change((e) => {
var elem = e.target; var elem = e.target;
var preorder_id = $(elem).data("preorder_id"); var preorder_id = $(elem).data("preorder_id");
var flag_id = $(elem).data("flag_id"); var flag_id = $(elem).data("flag_id");
@@ -1060,6 +1072,15 @@ $pagination_entity_name = "Vorbestellungen";
}, 2000, textelem); }, 2000, textelem);
} }
// find all inputs with this data-preorder_id="21969" and data-flag_id="3" and set the text to the new value
// always with their own fields and then select / unselect the checkbox
$("input.preorder-statusflag[data-preorder_id='" + this.preorder_id + "'][data-flag_id='" + this.flag_id + "']").each(function() {
if(value) {
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
}, },
error: function () { error: function () {
@@ -134,6 +134,14 @@ $daysSelect .= "</select>";
value="<?= ($timerecordingemployees->birthday) ? date('Y-m-d', $timerecordingemployees->birthday) : "" ?>"/> value="<?= ($timerecordingemployees->birthday) ? date('Y-m-d', $timerecordingemployees->birthday) : "" ?>"/>
</div> </div>
</div> </div>
<div class="form-group row">
<label class="col-lg-2 col-form-label" for="insurance_number">SV-Nummer (4 stellig)</label>
<div class="col-lg-1">
<input type="number" id="insurance_number" name="insurance_number"
class="form-control" max="9999"
value="<?= ($timerecordingemployees->insurance_number) ?: "" ?>"/>
</div>
</div>
<?php if ($me->superexpertEnabled()): ?> <?php if ($me->superexpertEnabled()): ?>
<div class="form-group row"> <div class="form-group row">
<label class="col-lg-2 col-form-label" for="bpahours">Black Pig Stunden</label> <label class="col-lg-2 col-form-label" for="bpahours">Black Pig Stunden</label>
@@ -56,6 +56,7 @@ $type[3] = "Lehrling";
<th class="text-center edit-width-medium">Aktiv</th> <th class="text-center edit-width-medium">Aktiv</th>
<th class="text-center">Mitarbeiter</th> <th class="text-center">Mitarbeiter</th>
<th class="text-center">Geburtstag</th> <th class="text-center">Geburtstag</th>
<th class="text-center">SV-Nummer</th>
<th class="text-center">Vertragsart</th> <th class="text-center">Vertragsart</th>
<th title="Zeiterfassung Start" class="text-center">ZE Start</th> <th title="Zeiterfassung Start" class="text-center">ZE Start</th>
<th title="Zeiterfassung Ende" class="text-center">ZE Ende</th> <th title="Zeiterfassung Ende" class="text-center">ZE Ende</th>
@@ -80,6 +81,7 @@ $type[3] = "Lehrling";
<th></th> <th></th>
<th></th> <th></th>
<th></th> <th></th>
<th></th>
<?php if ($me->superexpertEnabled()): ?> <?php if ($me->superexpertEnabled()): ?>
<th></th> <th></th>
<?php endif; ?> <?php endif; ?>
@@ -127,6 +129,9 @@ $type[3] = "Lehrling";
<td><?= $timerecordinguser->name ?></td> <td><?= $timerecordinguser->name ?></td>
<td class="text-center" <td class="text-center"
data-order="<?= $timerecordingemployees[$timerecordinguser->id]['birthday'] ?>"><?= ($timerecordingemployees[$timerecordinguser->id]['birthday']) ? date("d.m.Y", $timerecordingemployees[$timerecordinguser->id]['birthday']) : "-" ?></td> data-order="<?= $timerecordingemployees[$timerecordinguser->id]['birthday'] ?>"><?= ($timerecordingemployees[$timerecordinguser->id]['birthday']) ? date("d.m.Y", $timerecordingemployees[$timerecordinguser->id]['birthday']) : "-" ?></td>
<td class="text-center"
data-order="<?= $timerecordingemployees[$timerecordinguser->id]['insurance_number'] ?>"><?= ($timerecordingemployees[$timerecordinguser->id]['insurance_number']) ?: "-" ?></td>
<td><?= $type[$timerecordingemployees[$timerecordinguser->id]['type']] ?></td> <td><?= $type[$timerecordingemployees[$timerecordinguser->id]['type']] ?></td>
<td class="text-center" <td class="text-center"
data-order="<?= $timerecordingemployees[$timerecordinguser->id]['startdate'] ?>"><?= ($timerecordingemployees[$timerecordinguser->id]['startdate']) ? date("d.m.Y", $timerecordingemployees[$timerecordinguser->id]['startdate']) : "-" ?></td> data-order="<?= $timerecordingemployees[$timerecordinguser->id]['startdate'] ?>"><?= ($timerecordingemployees[$timerecordinguser->id]['startdate']) ? date("d.m.Y", $timerecordingemployees[$timerecordinguser->id]['startdate']) : "-" ?></td>
@@ -164,11 +169,11 @@ $type[3] = "Lehrling";
src="<?= self::getResourcePath() ?>datatables/DataTables-2x/datatables.min.js?<?= $git_merge_ts ?>"></script> src="<?= self::getResourcePath() ?>datatables/DataTables-2x/datatables.min.js?<?= $git_merge_ts ?>"></script>
<script type="text/javascript"> <script type="text/javascript">
var hidesearch = [6, 7, 8, 9, 10, 13]; var hidesearch = [7, 8, 9, 10, 11, 14];
var columnfilter = [0, 11, 12];
<?php if ($me->superexpertEnabled()): ?>
var columnfilter = [0, 12, 13]; var columnfilter = [0, 12, 13];
hidesearch = [6, 7, 8, 9, 10, 11, 14]; <?php if ($me->superexpertEnabled()): ?>
var columnfilter = [0, 13, 14];
hidesearch = [7, 8, 9, 10, 11, 15];
<?php endif; ?> <?php endif; ?>
var columnoptions = '<option value=""></option><option value="Ja">Ja</option><option value="Nein">Nein</option>'; var columnoptions = '<option value=""></option><option value="Ja">Ja</option><option value="Nein">Nein</option>';
+5 -4
View File
@@ -290,8 +290,6 @@ $years[time() - 31536000] = date('Y', time() - 31536000);
</div> </div>
</div> </div>
</form> </form>
</div> </div>
<div class="card"> <div class="card">
@@ -303,7 +301,10 @@ $years[time() - 31536000] = date('Y', time() - 31536000);
<div class="col-6 col-lg-2 col-xl-2 text-center"> <div class="col-6 col-lg-2 col-xl-2 text-center">
<i class="fa-duotone fa-calendar-week display-calendar active-calendar" title="Kalenderwoche" <i class="fa-duotone fa-calendar-week display-calendar active-calendar" title="Kalenderwoche"
data-datatype="1"></i> <i class="fa-duotone fa-calendar-days display-calendar" data-datatype="1"></i> <i class="fa-duotone fa-calendar-days display-calendar"
title="Kalendermonat" data-datatype="2"></i> <i title="Abwesenheiten" title="Kalendermonat" data-datatype="2"></i> <i title="KalenderJahr"
class="fa-duotone fa-calendar display-calendar"
data-datatype="5"></i>
<i title="Abwesenheiten"
class="fa-duotone fa-calendar-clock display-calendar" class="fa-duotone fa-calendar-clock display-calendar"
data-datatype="3"></i> data-datatype="3"></i>
</div> </div>
@@ -322,7 +323,7 @@ $years[time() - 31536000] = date('Y', time() - 31536000);
<div class="input-group"> <div class="input-group">
<select id="datamonth" class="form-control select2"> <select id="datamonth" class="form-control select2">
<?php foreach ($month as $key => $Month): ?> <?php foreach ($month as $key => $Month): ?>
<option <?= (date("Y-m",$timenow) == date("Y-m",$key)) ? 'selected="selected"' : '' ?> <option <?= (date("Y-m", $timenow) == date("Y-m", $key)) ? 'selected="selected"' : '' ?>
value="<?= $key ?>"><?= $Month ?></option> value="<?= $key ?>"><?= $Month ?></option>
<?php endforeach; ?> <?php endforeach; ?>
</select> </select>
@@ -0,0 +1,62 @@
<?php include(realpath(dirname(__FILE__) . "/../../$mfLayoutPackage") . "/header.php");
?>
<link href="<?= self::getResourcePath() ?>css/pages/Calendar/View.css?<?= $git_merge_ts ?>" rel="stylesheet"
type="text/css"/>
<style>
.fa-triangle-exclamation {
font-size: 22px;
vertical-align: top;
color: red;
margin-right: 5px;
}
</style>
<!-- start page title -->
<div class="row">
<div class="col-12">
<div class="page-title-box">
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item"><a href="<?= self::getUrl("Dashboard") ?>"><?= MFAPPNAME_SLUG ?></a>
</li>
<li class="breadcrumb-item active">Reports</li>
</ol>
</div>
<h4 class="page-title">Reports</h4>
</div>
</div>
</div>
<div class="card">
<div class="card-body">
<div class="feature col-lg-6 card h-100">
<div class="card-body">
<form class="form-horizontal" method="post"
action="<?= self::getUrl("TimerecordingReportExport", "exportdeadline") ?>">
<h3 class="fs-2 text-body-emphasis">Auswertungen Stichtag <i
class="fa-duotone fa-solid fa-file-xls fa-xls-calendar"></i></h3>
<p>Hier wird eine XLS Auswertung pro Mitarbeiter generiert mit Urlaub, Mehrstunden und
Gutstunden
zum Stichtag X<br>
<b><i class="fa-solid fa-triangle-exclamation"></i> Zur Zeit ist der Stichtag auf den
letzten Tag des ausgewählten Monats gesetzt.</b><br>
</p>
<div class="row">
<div class="input-group col-12 col-lg-5">
<input type="date" name="date" value="<?= date('Y-m-d', strtotime('last day of previous month')); ?>" class="form-control" aria-label="Stichtag">
<button class="btn btn-outline-secondary" type="submit">Auswerten</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php include(realpath(dirname(__FILE__) . "/../../$mfLayoutPackage") . "/footer.php"); ?>
@@ -0,0 +1,41 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?= MFAPPNAME_FULL ?> | Link versendet</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="assets/images/favicon.ico">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>fontawesome/css/all.min.css">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/adminlte.css">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/fonts.css?<?= date('U') ?>">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/main.css?<?= date('U') ?>">
<style>
.alert-success {
color: #155724;
background-color: #d4edda;
border-color: #c3e6cb;
}
</style>
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="<?= self::getUrl("/") ?>"><img
src="<?= self::getResourcePath() ?>assets/images/<?= MFAPPNAME_SLUG ?>-logo.png"/></a>
</div>
<div class="card">
<div class="card-body login-card-body">
<p class="login-box-msg">Anfrage erhalten</p>
<div class="alert alert-success text-center" role="alert">
Wenn ein Konto mit diesem Benutzernamen oder dieser E-Mail existiert, wurde ein Link zum Zurücksetzen des Passworts gesendet.
</div>
<p class="mt-3 mb-1 text-center">
<a href="<?= self::getUrl("/") ?>">Zurück zum Login</a>
</p>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?= MFAPPNAME_FULL ?> | Passwort vergessen</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="assets/images/favicon.ico">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>fontawesome/css/all.min.css">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/adminlte.css">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/fonts.css?<?= date('U') ?>">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/main.css?<?= date('U') ?>">
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="<?= self::getUrl("/") ?>"><img
src="<?= self::getResourcePath() ?>assets/images/<?= MFAPPNAME_SLUG ?>-logo.png"/></a>
</div>
<div class="card">
<div class="card-body login-card-body">
<p class="login-box-msg">Passwort vergessen</p>
<p class="text-muted text-center mb-3">Gib deinen Benutzernamen oder Email ein, um einen Link zum Zurücksetzen des Passworts zu erhalten.</p>
<form action="<?= self::getUrl("UserPasswordReset", "sendResetLink") ?>" method="post">
<div class="input-group mb-3">
<input type="text" name="Username" class="form-control" placeholder="Benutzer" required>
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-envelope"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<button type="submit" class="btn btn-primary btn-block">Link anfordern</button>
</div>
</div>
</form>
<p class="mt-3 mb-1">
<a href="<?= self::getUrl("/") ?>">Zurück zum Login</a>
</p>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,57 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?= MFAPPNAME_FULL ?> | Passwort zurücksetzen</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="assets/images/favicon.ico">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>fontawesome/css/all.min.css">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/adminlte.css">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/fonts.css?<?= date('U') ?>">
<link rel="stylesheet" href="<?= self::getResourcePath() ?>css/main.css?<?= date('U') ?>">
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="<?= self::getUrl("/") ?>"><img
src="<?= self::getResourcePath() ?>assets/images/<?= MFAPPNAME_SLUG ?>-logo.png"/></a>
</div>
<div class="card">
<div class="card-body login-card-body">
<p class="login-box-msg">Neues Passwort festlegen</p>
<?php if ($error): ?>
<div class="alert alert-danger"><?= $error ?></div>
<?php endif; ?>
<form action="<?= self::getUrl("UserPasswordReset", "updatePassword") ?>" method="post">
<input type="hidden" name="token" value="<?= $token ?>" />
<div class="input-group mb-3">
<input type="password" name="Password" class="form-control" placeholder="Neues Passwort" required>
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="input-group mb-3">
<input type="password" name="Password_confirm" class="form-control" placeholder="Passwort bestätigen" required>
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-lock"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<button type="submit" class="btn btn-primary btn-block">Passwort speichern</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
-6
View File
@@ -19,12 +19,6 @@ if (is_dir($vueViewPath)) {
$additionalCSS = [ $additionalCSS = [
...$additionalCSS, ...$additionalCSS,
'plugins/daterangepicker/daterangepicker.css',
'plugins/vue/tt-components/css/tt-table.css',
'plugins/vue/tt-components/css/tt-tooltip.css',
'plugins/vue/tt-components/css/tt-loader.css',
'plugins/vue/tt-components/css/tt-file-gallery.css',
'plugins/vue/tt-components/css/tt-position-manager.css',
]; ];
/** /**
@@ -0,0 +1,122 @@
<!DOCTYPE html>
<html lang="de" class="h-full">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Lager-System Login</title>
<meta name="theme-color" content="#0055FF"/>
<link rel="manifest" href="/assets/pwa/shipping-note-tablet-manifest.json">
<script src="https://cdn.jsdelivr.net/npm/vue@3.4.27/dist/vue.global.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script>
window.WAREHOUSE_CONFIG = { userOptions: <?= json_encode($userOptions) ?> };
tailwind.config = {
theme: { extend: { colors: { 'brand-blue': '#0055FF' } } }
};
</script>
<style>
body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
.user-list-container::-webkit-scrollbar { width: 5px; }
.user-list-container::-webkit-scrollbar-track { background: #f1f5f9; }
.user-list-container::-webkit-scrollbar-thumb { background: #a8b2c1; border-radius: 10px; }
.list-move, .list-enter-active, .list-leave-active { transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1); }
.list-enter-from, .list-leave-to { opacity: 0; transform: scale(0.95); }
.list-leave-active { position: absolute !important; }
.container-enter-active { transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1); }
.container-enter-from { opacity: 0; transform: translateY(20px); }
</style>
</head>
<body class="bg-slate-100 flex items-center justify-center min-h-full font-sans p-4">
<div id="app" class="w-full max-w-lg mx-auto"></div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => navigator.serviceWorker.register('/assets/pwa/shipping-note-tablet-sw.js'));
}
const {createApp, ref, computed, onMounted} = Vue;
createApp({
setup() {
const excludedNames = ['cli', 'spitzer', 'test'];
const initialUsers = window.WAREHOUSE_CONFIG.userOptions.filter(user => {
const nameLower = user.text.toLowerCase();
return !excludedNames.some(ex => nameLower.includes(ex));
});
const selectedLetter = ref('All');
const selectedUserId = ref(null);
const isMounted = ref(false);
onMounted(() => isMounted.value = true);
const availableLetters = computed(() => {
const letters = new Set(initialUsers.map(u => u.text[0].toUpperCase()));
return ['All', ...Array.from(letters).sort()];
});
const filteredUsers = computed(() => {
if (selectedLetter.value === 'All') return initialUsers;
return initialUsers.filter(u => u.text.startsWith(selectedLetter.value));
});
function selectUser(userId) {
selectedUserId.value = userId;
}
return { isMounted, availableLetters, selectedLetter, filteredUsers, selectedUserId, selectUser };
},
template: `
<Transition name="container" appear>
<div v-if="isMounted" class="bg-white p-6 sm:p-8 rounded-2xl shadow-2xl shadow-slate-300/60 w-full text-center">
<header class="mb-6">
<img src="/assets/images/xinon-full.png" alt="Logo" class="h-12 w-auto mx-auto mb-4">
<h1 class="text-3xl sm:text-4xl font-bold text-slate-800 tracking-tight">Lager-System</h1>
</header>
<main>
<form action="/WarehouseShippingNote" method="POST">
<input type="hidden" name="wantedUserId" :value="selectedUserId"/>
<div class="mb-5 p-1.5 bg-slate-100 rounded-xl flex flex-wrap justify-center gap-1.5">
<button v-for="letter in availableLetters" :key="letter" type="button"
@click="selectedLetter = letter; selectedUserId = null;"
class="w-12 h-12 rounded-lg text-base font-bold transition-all duration-300"
:class="selectedLetter === letter ? 'bg-brand-blue text-white shadow' : 'bg-transparent text-slate-500 hover:bg-slate-200'">
{{ letter === 'All' ? 'Alle' : letter }}
</button>
</div>
<div class="user-list-container max-h-[35vh] min-h-[150px] overflow-y-auto relative p-1.5">
<TransitionGroup name="list" tag="div" class="relative overflow-x-hidden">
<button v-for="(user, index) in filteredUsers" :key="user.value" type="button"
@click="selectUser(user.value)"
class="w-full text-left p-4 rounded-xl transition-all duration-200 ease-in-out mb-2 last:mb-0"
:style="{ 'transition-delay': (index * 15) + 'ms' }"
:class="selectedUserId === user.value ? 'bg-brand-blue text-white shadow-lg' : 'bg-slate-50 hover:bg-slate-200 text-slate-700'">
<span class="text-lg font-medium">{{ user.text }}</span>
</button>
</TransitionGroup>
<div v-if="!filteredUsers.length" class="text-center text-slate-400 pt-10">
<p>Keine Mitarbeiter für diese Auswahl.</p>
</div>
</div>
<div class="mt-6">
<button type="submit" :disabled="!selectedUserId"
class="w-full text-white font-bold py-3.5 px-4 rounded-xl text-xl transition-all duration-300 bg-brand-blue hover:bg-blue-600 focus:outline-none focus:ring-4 focus:ring-blue-500/50 disabled:bg-slate-300 disabled:text-slate-500 disabled:cursor-not-allowed">
Anmelden
</button>
</div>
</form>
</main>
</div>
</Transition>
`
}).mount('#app');
</script>
</body>
</html>
+5 -3
View File
@@ -15,13 +15,15 @@
</footer> </footer>
<!-- end Footer --> <!-- end Footer -->
<!--<script type="text/javascript" src="<?=self::getResourcePath()?>assets/js/vendor.min.js"></script>--> <?php if(defined("ENABLE_VODIA_IDENTITY_SWITCHER") && ENABLE_VODIA_IDENTITY_SWITCHER && $me->is("employee") && !isset($_SESSION[MFAPPNAME . '_warehouse_login_override'])): ?>
<?php if(defined("ENABLE_VODIA_IDENTITY_SWITCHER") && ENABLE_VODIA_IDENTITY_SWITCHER && $me->is("employee")): ?>
<script type="text/javascript" src="<?=self::getResourcePath()?>assets/js/xinon-vodia-identity.js?<?=$git_merge_ts?>"></script> <script type="text/javascript" src="<?=self::getResourcePath()?>assets/js/xinon-vodia-identity.js?<?=$git_merge_ts?>"></script>
<?php endif; ?> <?php endif; ?>
<script type="text/javascript"> <script type="text/javascript">
if (typeof jQuery === 'undefined') {
throw new Error('jQuery not found. Please include jQuery before this script.');
}
if ($(".selectpicker").length) { if ($(".selectpicker").length) {
$(".selectpicker").selectpicker({ $(".selectpicker").selectpicker({
iconBase: "fas", iconBase: "fas",
+1
View File
@@ -44,6 +44,7 @@
<li><a href="<?=self::getUrl("TimerecordingPermit")?>"><i class="far fa-fw fa-calendar-check text-info"></i> Freigaben</a></li> <li><a href="<?=self::getUrl("TimerecordingPermit")?>"><i class="far fa-fw fa-calendar-check text-info"></i> Freigaben</a></li>
<li><a href="<?=self::getUrl("TimerecordingReport")?>"><i class="far fa-fw fa-chart-pie text-info"></i> Auswertung/Korrektur</a></li> <li><a href="<?=self::getUrl("TimerecordingReport")?>"><i class="far fa-fw fa-chart-pie text-info"></i> Auswertung/Korrektur</a></li>
<li><a href="<?=self::getUrl("TimerecordingBilling")?>"><i class="far fa-fw fa-money-bill-1-wave text-info"></i> Verrechnung</a></li> <li><a href="<?=self::getUrl("TimerecordingBilling")?>"><i class="far fa-fw fa-money-bill-1-wave text-info"></i> Verrechnung</a></li>
<li><a href="<?=self::getUrl("TimerecordingReportExport")?>"><i class="far fa-fw fa-chart-simple text-info"></i> Reports</a></li>
<li><a href="<?=self::getUrl("TimerecordingCategory")?>"><i class="far fa-fw fa-list text-info"></i> Buchungsarten</a></li> <li><a href="<?=self::getUrl("TimerecordingCategory")?>"><i class="far fa-fw fa-list text-info"></i> Buchungsarten</a></li>
<li><a href="<?=self::getUrl("TimerecordingHoliday")?>"><i class="far fa-fw fa-umbrella-beach text-info"></i> Feiertage</a></li> <li><a href="<?=self::getUrl("TimerecordingHoliday")?>"><i class="far fa-fw fa-umbrella-beach text-info"></i> Feiertage</a></li>
<li><a href="<?=self::getUrl("TimerecordingEmployee")?>"><i class="far fa-fw fa-user text-info"></i> Personaladministration</a></li> <li><a href="<?=self::getUrl("TimerecordingEmployee")?>"><i class="far fa-fw fa-user text-info"></i> Personaladministration</a></li>
+12 -1
View File
@@ -19,7 +19,7 @@ if ($requesttype == "2fa" || $requesttype == "false2fa") {
</div> </div>
<div class="row justify-content-center"> <div class="row justify-content-center">
<div class="mb-0 col-5"> <div class="mb-0 col-5">
<input type="number" required min="0" max="99999" class="form-control" <input autofocus type="number" required min="0" max="99999" class="form-control"
name="TwofactorCode" id="TwofactorCode"/> name="TwofactorCode" id="TwofactorCode"/>
</div> </div>
@@ -87,6 +87,7 @@ if ($requesttype == "2fa" || $requesttype == "false2fa") {
.cursor-pointer { .cursor-pointer {
cursor: pointer; cursor: pointer;
} }
.noselect { .noselect {
-webkit-touch-callout: none; /* iOS Safari */ -webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */ -webkit-user-select: none; /* Safari */
@@ -134,6 +135,9 @@ if ($requesttype == "2fa" || $requesttype == "false2fa") {
<?= $error ?> <?= $error ?>
<div class="row"> <div class="row">
<div class="col-6 col-lg-8"> <div class="col-6 col-lg-8">
<p class="mb-1 mt-1">
<a href="<?= self::getUrl("UserPasswordReset", "forgotPassword") ?>">Passwort vergessen?</a>
</p>
</div> </div>
<!-- /.col --> <!-- /.col -->
<div class="col-6 col-lg-4"> <div class="col-6 col-lg-4">
@@ -166,6 +170,13 @@ if ($requesttype == "2fa" || $requesttype == "false2fa") {
$('#TwofactorCode').remove(); $('#TwofactorCode').remove();
$('form').submit(); $('form').submit();
}); });
$(document).ready(function () {
if ($('#TwofactorCode').length > 0) {
$('#TwofactorCode').focus();
} else {
$('#mfUsername').focus();
}
})
</script> </script>
</body> </body>
-39
View File
@@ -15,45 +15,6 @@
<!-- End mobile menu toggle--> <!-- End mobile menu toggle-->
</li> </li>
<?php if(defined("ENABLE_VODIA_IDENTITY_SWITCHER") && ENABLE_VODIA_IDENTITY_SWITCHER && $me->is("employee")): ?>
<li id="vodia-identity-container" class="dropdown notification-list hidden" >
<a href="#" id="vodia-identity-switcher" class="nav-link nav-user dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<i class="phone-icon fas fa-phone text-success"></i>
<span class="pro-user-name ml-1">
Ausgehende Identität: <strong id="vodia-identity-current-text"></strong>
<strong id="vodia-identity-current-number"></strong>
<i class="far fa-chevron-down"></i>
</span>
</a>
<div id="vodia-identity-switcher-dropdown-menu" class="dropdown-menu dropdown-menu-right">
<div class="dropdown-item noti-title">
<h6 class="m-0">
Ausgehende Telefonidentität umschalten:
</h6>
</div>
<ul class="list-group" id="vodia-identities-list" style="min-width: 512px;">
</ul>
</div>
</li>
<template id="vodia-identity-list-item-template">
<li class="list-group-item pointer">
<table class="table table-borderless mb-0">
<tr>
<td class="color-block"><i class="fas fa-phone"></i></td>
<td class="text-block" style="vertical-align: middle">
<span class="name"></span>
<span class="number"></span>
</td>
</tr>
</table>
</li>
</template>
<?php endif; ?>
<li id="bookstackLink" class="dropdown notification-list" style="display: none"> <li id="bookstackLink" class="dropdown notification-list" style="display: none">
<a class="nav-link dropdown-toggle" href="" target="_blank"> <a class="nav-link dropdown-toggle" href="" target="_blank">
<i class="fas fa-book"></i> <i class="fas fa-book"></i>
+46 -55
View File
@@ -1,85 +1,76 @@
<?php /** @var TYPE_NAME $git_merge_ts */ ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8">
<title><?=MFAPPNAME_FULL?></title> <title><?= MFAPPNAME_FULL ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- App favicon -->
<link rel="shortcut icon" href="<?=self::getResourcePath()?>assets/images/favicon.ico">
<link href="<?=self::getResourcePath()?>fontawesome/css/all.min.css?<?=$git_merge_ts?>" rel="stylesheet" type="text/css" /> <link rel="preconnect" href="https://fonts.googleapis.com">
<link href="<?=self::getResourcePath()?>fontawesome/css/sharp-solid.css?<?=$git_merge_ts?>" rel="stylesheet" type="text/css" /> <link rel="shortcut icon" href="<?= self::getResourcePath() ?>assets/images/favicon.ico">
<link href="<?=self::getResourcePath()?>fontawesome/css/sharp-regular.css?<?=$git_merge_ts?>" rel="stylesheet" type="text/css" />
<link href="<?=self::getResourcePath()?>fontawesome/css/sharp-light.css?<?=$git_merge_ts?>" rel="stylesheet" type="text/css" />
<link href="<?=self::getResourcePath()?>fontawesome/css/sharp-thin.css?<?=$git_merge_ts?>" rel="stylesheet" type="text/css" />
<link href="<?=self::getResourcePath()?>assets/css/bootstrap.min.css?<?=$git_merge_ts?>" rel="stylesheet" type="text/css" />
<link href="<?=self::getResourcePath()?>assets/css/app.min.css?<?=$git_merge_ts?>" rel="stylesheet" type="text/css" />
<link href="<?=self::getResourcePath()?>plugins/notification/notify.min.css" rel="stylesheet" type="text/css" />
<link href="<?=self::getResourcePath()?>assets/css/thetool.css?<?=$git_merge_ts?>" rel="stylesheet" type="text/css" />
<link href="<?= self::getResourcePath() ?>cssbundler.php?<?= $git_merge_ts ?>" rel="stylesheet">
<link href="<?= self::getResourcePath() ?>fontawesome/css/fontawesome.min.css?<?= $git_merge_ts ?>"
rel="stylesheet">
<link href="<?= self::getResourcePath() ?>fontawesome/css/solid.min.css?<?= $git_merge_ts ?>" rel="stylesheet">
<link href="<?= self::getResourcePath() ?>fontawesome/css/regular.min.css?<?= $git_merge_ts ?>" rel="stylesheet">
<link href="<?= self::getResourcePath() ?>fontawesome/css/duotone.min.css?<?= $git_merge_ts ?>" rel="stylesheet">
<link href="<?= self::getResourcePath() ?>fontawesome/css/sharp-light.min.css?<?= $git_merge_ts ?>"
rel="stylesheet">
<?php if (!empty($additionalCSS)):
foreach ($additionalCSS as $css): ?>
<link rel="stylesheet" href="<?= self::getResourcePath() ?><?= $css ?>?<?= $git_merge_ts ?>">
<?php endforeach;
endif;
<?php if(isset($additionalCSS) && is_array($additionalCSS) && count($additionalCSS)): ?> if (!empty($additionalHead)):
<?php foreach($additionalCSS as $css): ?> foreach ($additionalHead as $head):
<link rel="stylesheet" href="<?=self::getResourcePath()?><?=$css?>?<?=$git_merge_ts?>" /> echo $head;
<?php endforeach; ?> endforeach;
<?php endif; ?> endif; ?>
<script type="text/javascript"> <script>
window.mfNotify = <?=isset($mfNotify) ? json_encode($mfNotify) : "null"; ?>; const baseurl = '<?=self::getResourcePath()?>';
window.mfNotify = <?=json_encode($mfNotify ?? null)?>;
window.TT_CONFIG = {}; window.TT_CONFIG = {};
<?php <?php
if(isset($JSGlobals) && is_array($JSGlobals) && count($JSGlobals)): if(isset($JSGlobals) && is_array($JSGlobals) && count($JSGlobals)):
foreach($JSGlobals as $key => $value): ?> foreach($JSGlobals as $key => $value): ?>
window.TT_CONFIG.<?=$key?> = <?=is_array($value) ? json_encode($value) : "'$value'"; ?>; window.TT_CONFIG.<?=$key?> = <?=is_array($value) ? json_encode($value) : "'$value'"; ?>;
<?php endforeach; endif;?> <?php endforeach; endif;?>
</script> </script>
<script type="text/javascript" src="<?=self::getResourcePath()?>js/jquery.min.js"></script> <script type="text/javascript" src="<?=self::getResourcePath()?>js/jquery.min.js"></script>
<script type="text/javascript" src="<?=self::getResourcePath()?>js/popper.min.js" defer></script> <script src="<?= self::getResourcePath() ?>plugins/notification/notify.js" defer></script>
<script type="text/javascript" src="<?=self::getResourcePath()?>js/bootstrap.min.js" defer></script> <script src="<?= self::getResourcePath() ?>plugins/bookstack/bookstackIntegration.js" defer></script>
<script type="text/javascript" src="<?=self::getResourcePath()?>plugins/notification/notify.js" defer></script>
<script type="text/javascript" src="<?=self::getResourcePath()?>plugins/bookstack/bookstackIntegration.js" defer></script>
<?php if(isset($additionalJS) && is_array($additionalJS) && count($additionalJS)): ?> <?php if (!empty($additionalJS)):
<?php foreach($additionalJS as $js): ?> foreach ($additionalJS as $js): ?>
<script src="<?=self::getResourcePath()?><?=$js?>?<?=$git_merge_ts?>"></script> <script src="<?= self::getResourcePath() ?><?= $js ?>?<?= $git_merge_ts ?>"></script>
<?php endforeach; ?> <?php endforeach;
<?php endif; ?> endif; ?>
<?php if(isset($additionalHead) && is_array($additionalHead) && count($additionalHead)):
foreach($additionalHead as $head): ?>
<?=$head?>
<?php endforeach; endif;?>
<style> <style>
<?php if(MFAPPNAME == "devthetool"): ?>
body {
border-left: 8px dashed #f672a7;
}
<?php endif; ?>
body { body {
min-height: 100vh; min-height: 100vh;
} }
<?php if (MFAPPNAME === "devthetool"): ?>
body {
border-left: 8px dashed #f672a7;
}
<?php endif; ?>
</style> </style>
</head> </head>
<body> <body>
<script type="text/javascript">
baseurl = '<?=self::getResourcePath()?>';
</script>
<!-- Navigation Bar-->
<header id="topnav"> <header id="topnav">
<?php include(realpath(dirname(__FILE__)."/")."/topbar.php"); ?> <?php
<?php include(realpath(dirname(__FILE__)."/")."/menu.php"); ?> include(__DIR__ . "/topbar.php");
include(__DIR__ . "/menu.php");
?>
</header> </header>
<!-- End Navigation Bar-->
<div class="wrapper pl-0 pl-lg-1 pr-0 pr-lg-1">
<div class="wrapper pl-0 pl-lg-1 pr-0 pr-lg-1 ">
<div class="container-fluid"> <div class="container-fluid">
+38 -13
View File
@@ -28,6 +28,10 @@ class ADBRimoFcpController extends TTCrud {
$this->columns[0]['modal']['items'] = $netzgebiete; $this->columns[0]['modal']['items'] = $netzgebiete;
} }
public function afterInit() {
$this->model = ADBRimoFcp::class;
}
public function ImportFCPsAction() { public function ImportFCPsAction() {
$input = json_decode(file_get_contents('php://input'), true); $input = json_decode(file_get_contents('php://input'), true);
$fcpList = $input['data'] ?? []; $fcpList = $input['data'] ?? [];
@@ -37,20 +41,30 @@ class ADBRimoFcpController extends TTCrud {
$now = date('U'); $now = date('U');
foreach ($fcpList as $fcpIn) { foreach ($fcpList as $fcpIn) {
$rimoId = $fcpIn['ExternalID'] ?? null; $rimoId = $fcpIn['ExternalID'] ?? $fcpIn['External ID'] ?? $fcpIn['Externe ID'] ?? null;
if ($rimoId === null) $rimoId = $fcpIn['External ID'] ?? null;
if ($rimoId === null) continue; if ($rimoId === null) continue;
if (!is_numeric($networkAreaId)) {
$netzgebiet = ADBNetzgebietModel::getFirst(['extref' =>
explode(':', $fcpIn['FCP Cluster'] ?? '')[0] ?? 'DEFINETLY_NOT_A_VALID_EXTREF'
]);
if ($netzgebiet) {
$networkAreaId = $netzgebiet->id;
} else {
continue;
}
}
$data = [ $data = [
'netzgebiet_id' => $networkAreaId, 'netzgebiet_id' => $networkAreaId,
'name' => $fcpIn['Name'] ?? null, 'name' => $fcpIn['Name'] ?? $fcpIn['Name/ID'] ?? null,
'rimo_id' => $rimoId, 'rimo_id' => $rimoId,
'label' => $fcpIn['User label'] ?? null, 'label' => $fcpIn['User label'] ?? $fcpIn['Bezeichnung'] ?? null,
'building_type' => $fcpIn['Building type'] ?? null, 'building_type' => $fcpIn['Building type'] ?? $fcpIn['Typ'] ?? null,
'rimo_ex_state' => $fcpIn['Execution state'] ?? null, 'rimo_ex_state' => $fcpIn['Execution state'] ?? $fcpIn['Ausführungsstatus'] ?? null,
'rimo_op_state' => $fcpIn['Operational state'] ?? null, 'rimo_op_state' => $fcpIn['Operational state'] ?? $fcpIn['Betriebszustand'] ?? null,
'gps_lat' => floatval(str_replace(',', '.', $fcpIn['Latitude'] ?? '0')), 'gps_lat' => isset($fcpIn['Latitude']) ? floatval(str_replace(',', '.', $fcpIn['Latitude'] ?? '0')) : null,
'gps_long' => floatval(str_replace(',', '.', $fcpIn['Longitude'] ?? '0')), 'gps_long' => isset($fcpIn['Latitude']) ? floatval(str_replace(',', '.', $fcpIn['Longitude'] ?? '0')) : null,
'edit' => $now 'edit' => $now
]; ];
@@ -79,9 +93,20 @@ class ADBRimoFcpController extends TTCrud {
$counts = ['upd' => 0, 'fcpNF' => 0, 'noFCP' => 0, 'noExtId' => 0]; $counts = ['upd' => 0, 'fcpNF' => 0, 'noFCP' => 0, 'noExtId' => 0];
foreach ($input['data'] as $loc) { foreach ($input['data'] as $loc) {
$fcpName = trim($loc['FCP cluster name'] ?? ''); if (empty($fcpsByName)) {
$extId = $loc['ExternalID'] ?? null; $fcpCluster = explode(':', $loc['FCP Cluster'] ?? '');
if ($extId === null) $extId = $loc['External ID'] ?? null; $network = ADBNetzgebietModel::getFirst(['extref' => $fcpCluster[0] ?? '']);
if ($network) {
$fcpsByName = array_column(ADBRimoFcp::getAll(['netzgebiet_id' => $network->id]), null, 'name');
} else {
$counts['fcpNF']++;
continue;
}
}
$fcpName = trim($loc['FCP cluster name'] ?? $loc['FCP Clustername'] ?? '');
$extId = $loc['ExternalID'] ?? $loc['Externe ID'] ?? null;
if ($extId === null) $extId = $loc['External ID'] ?? $loc['Externe ID'] ?? null;
if ($fcpName === '') { $counts['noFCP']++; continue; } if ($fcpName === '') { $counts['noFCP']++; continue; }
@@ -92,7 +117,7 @@ class ADBRimoFcpController extends TTCrud {
if ($hn = ADBHausnummerModel::getFirst(['rimo_id' => $extId])) { if ($hn = ADBHausnummerModel::getFirst(['rimo_id' => $extId])) {
$hn->fcp_id = $fcp->id; $hn->fcp_id = $fcp->id;
$hn->rimo_fcp_name = $fcp->name; $hn->rimo_fcp_name = $fcp->name;
$hn->save(); $hn->save(["no_aftersave" => true]);
$counts['upd']++; $counts['upd']++;
} }
} }
+29 -6
View File
@@ -4,13 +4,36 @@ class AddressController extends mfBaseController {
private $filter; private $filter;
protected function init() { protected function init() {
$this->needlogin = true; $user = null;
$me = new User(); $overrideKey = MFAPPNAME . '_warehouse_login_override';
$me->loadMe(); $timestampKey = MFAPPNAME . '_warehouse_login_override_timestamp';
$this->me = $me;
$this->layout()->set("me", $me);
if (!$me->is(["Admin", "salespartner"])) { $overrideId = $_SESSION[$overrideKey] ?? null;
$timestamp = $_SESSION[$timestampKey] ?? null;
if (is_numeric($overrideId) && $timestamp && (time() - $timestamp) < 600) {
$potentialUser = new User($overrideId);
if ($potentialUser->id && $potentialUser->address_id == 1) {
$user = $potentialUser;
} else {
unset($_SESSION[$overrideKey], $_SESSION[$timestampKey]);
$this->redirect('WarehouseShippingNote');
return;
}
} elseif ($overrideId) {
unset($_SESSION[$overrideKey], $_SESSION[$timestampKey]);
}
if (!$user) {
$this->needlogin = true;
$user = new User();
$user->loadMe();
}
$this->me = $user;
$this->layout()->set("me", $this->me);
if (!$this->me->is(["Admin", "salespartner"])) {
$this->redirect("Dashboard"); $this->redirect("Dashboard");
} }
} }
@@ -120,6 +120,13 @@ class PreorderStatusflagModel {
} }
} }
if (array_key_exists("ids", $filter)) {
$ids = $filter['ids'];
if (is_array($ids) && count($ids)) {
$where .= " AND PreorderStatusflag.id IN (" . implode(',', $ids) . ")";
}
}
if (array_key_exists("create_by", $filter)) { if (array_key_exists("create_by", $filter)) {
$create_by = $filter['create_by']; $create_by = $filter['create_by'];
if (is_numeric($create_by)) { if (is_numeric($create_by)) {
+192 -10
View File
@@ -5,6 +5,7 @@ class RMLWorkorderModel extends TTCrudBaseModel {
public int $id; public int $id;
public int $preorderId; public int $preorderId;
public ?int $companyId; public ?int $companyId;
public ?int $clusterId;
public string $status; public string $status;
public ?int $assignmentDate; public ?int $assignmentDate;
public ?int $deadlineDate; public ?int $deadlineDate;
@@ -12,18 +13,11 @@ class RMLWorkorderModel extends TTCrudBaseModel {
public int $create; public int $create;
public int $createBy; public int $createBy;
/** // This method remains unchanged as requested.
* Finds work orders that are nearing their deadline or are overdue.
* This can be used for the traffic light system.
*
* @param string $urgency 'red', 'yellow', or 'green'
* @return array
*/
public static function getWorkordersByUrgency(string $urgency, ?int $companyId = null): array { public static function getWorkordersByUrgency(string $urgency, ?int $companyId = null): array {
$db = self::getDB(); $db = self::getDB();
$table = self::getFullyQualifiedTable(); $table = self::getFullyQualifiedTable();
$now = time(); $whereClause = "WHERE status IN ('assigned', 'scheduled', 'correction_requested')";
$whereClause = "WHERE status IN ('assigned', 'scheduled')";
if ($companyId) { if ($companyId) {
$whereClause .= " AND companyId = " . intval($companyId); $whereClause .= " AND companyId = " . intval($companyId);
@@ -32,7 +26,7 @@ class RMLWorkorderModel extends TTCrudBaseModel {
switch ($urgency) { switch ($urgency) {
case 'red': // Less than 1 week left or overdue case 'red': // Less than 1 week left or overdue
$redDate = strtotime('+1 week'); $redDate = strtotime('+1 week');
$whereClause .= " AND deadlineDate < $redDate"; $whereClause .= " AND deadlineDate IS NOT NULL AND deadlineDate < $redDate";
break; break;
case 'yellow': // Between 1 and 3 weeks left case 'yellow': // Between 1 and 3 weeks left
$yellowDateStart = strtotime('+1 week'); $yellowDateStart = strtotime('+1 week');
@@ -56,4 +50,192 @@ class RMLWorkorderModel extends TTCrudBaseModel {
return $orders; return $orders;
} }
// --- REFACTORED METHODS ---
private static function buildWhereClause(array $filters, array $allowedCampaignIds): string {
if (empty($allowedCampaignIds)) {
return " WHERE 1=0";
}
$sql = Helper::generateFilterCondition(array_map('intval', $allowedCampaignIds), 'p.preordercampaign_id');
if (!empty($filters['id'])) {
$sql .= Helper::generateFilterCondition($filters['id'], 'w.id', true);
}
if (!empty($filters['status'])) {
$sql .= Helper::generateFilterCondition($filters['status'], 'w.status', true);
}
if (!empty($filters['preordercampaign_id'])) {
$sql .= Helper::generateFilterCondition($filters['preordercampaign_id'], 'p.preordercampaign_id');
}
if (!empty($filters['companyName'])) {
$sql .= Helper::generateFilterCondition($filters['companyName'], 'c.name');
}
if (!empty($filters['deadlineDate'])) {
$sql .= Helper::generateFilterCondition($filters['deadlineDate'], 'w.deadlineDate');
}
if (!empty($filters['preorderInfo'])) {
$searchColumns = "p.firstname|p.lastname|p.company|p.oaid|p.street|p.housenumber|p.zip|p.city|str.name|ort.name";
$sql .= Helper::generateFilterCondition($filters['preorderInfo'], $searchColumns);
}
return "WHERE " . ltrim(trim($sql), 'AND');
}
public static function getAdminWorkorders(array $filters, ?int $limit, int $offset, array $order, array $allowedCampaignIds): array {
$db = self::getDB();
$fronkDbName = FRONKDB_DBNAME;
$addressDbName = defined('ADDRESSDB_DBNAME') ? ADDRESSDB_DBNAME : 'addressdb';
$sql = "
SELECT
w.id, w.status, w.deadlineDate, w.companyId, p.preordercampaign_id,
CONCAT_WS(' ', p.firstname, p.lastname) as customerName,
p.company as customerCompany, p.oaid, c.name as companyName,
str.name as street, hn.hausnummer, hn.stiege, we.bezeichner as apartment, plz.plz, ort.name as city
FROM `$fronkDbName`.`RMLWorkorder` w
JOIN `$fronkDbName`.`Preorder` p ON w.preorderId = p.id
LEFT JOIN `$fronkDbName`.`Preordercampaign` pc ON p.preordercampaign_id = pc.id
LEFT JOIN `$fronkDbName`.`RMLWorkorderCompany` c ON w.companyId = c.id
LEFT JOIN `$addressDbName`.`Hausnummer` hn ON p.adb_hausnummer_id = hn.id
LEFT JOIN `$addressDbName`.`Strasse` str ON hn.strasse_id = str.id
LEFT JOIN `$addressDbName`.`Plz` plz ON hn.plz_id = plz.id
LEFT JOIN `$addressDbName`.`Ortschaft` ort ON hn.ortschaft_id = ort.id
LEFT JOIN `$addressDbName`.`Wohneinheit` we ON p.adb_wohneinheit_id = we.id
";
$sql .= self::buildWhereClause($filters, $allowedCampaignIds);
$sql .= " ORDER BY CASE WHEN w.deadlineDate IS NULL THEN 1 ELSE 0 END, w.deadlineDate ASC";
if (!empty($order['key'])) {
$sortableColumns = ['id', 'status', 'deadlineDate', 'companyName', 'clusterName'];
if (in_array($order['key'], $sortableColumns)) {
$sortOrder = (strtoupper($order['order']) === 'DESC') ? 'DESC' : 'ASC';
$sql .= ", " . $db->real_escape_string($order['key']) . " " . $sortOrder;
}
}
if ($limit !== null) {
$sql .= " LIMIT " . intval($limit) . " OFFSET " . intval($offset);
}
$result = $db->query($sql);
return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}
public static function countAdminWorkorders(array $filters, array $allowedCampaignIds): int {
$db = self::getDB();
$fronkDbName = FRONKDB_DBNAME;
$addressDbName = defined('ADDRESSDB_DBNAME') ? ADDRESSDB_DBNAME : 'addressdb';
$sql = "
SELECT COUNT(w.id) as count
FROM `$fronkDbName`.`RMLWorkorder` w
JOIN `$fronkDbName`.`Preorder` p ON w.preorderId = p.id
LEFT JOIN `$fronkDbName`.`RMLWorkorderCompany` c ON w.companyId = c.id
LEFT JOIN `$addressDbName`.`Hausnummer` hn ON p.adb_hausnummer_id = hn.id
LEFT JOIN `$addressDbName`.`Strasse` str ON hn.strasse_id = str.id
LEFT JOIN `$addressDbName`.`Plz` plz ON hn.plz_id = plz.id
LEFT JOIN `$addressDbName`.`Ortschaft` ort ON hn.ortschaft_id = ort.id
";
$sql .= self::buildWhereClause($filters, $allowedCampaignIds);
$result = $db->query($sql);
if ($result === false) return 0;
$row = $result->fetch_assoc();
return $row['count'] ?? 0;
}
private static function buildCompanyWhereClause(array $filters, int $companyId): string
{
$sql = "w.companyId = " . $companyId;
if (!empty($filters['id'])) {
$sql .= Helper::generateFilterCondition($filters['id'], 'w.id', true);
}
if (!empty($filters['status'])) {
$sql .= Helper::generateFilterCondition($filters['status'], 'w.status');
}
if (!empty($filters['deadlineDate'])) {
$sql .= Helper::generateFilterCondition($filters['deadlineDate'], 'w.deadlineDate');
}
if (!empty($filters['appointmentDate'])) {
$sql .= Helper::generateFilterCondition($filters['appointmentDate'], 'w.appointmentDate');
}
if (!empty($filters['preorderInfo'])) {
$searchColumns = "p.firstname|p.lastname|p.company|p.oaid|p.street|p.housenumber|p.zip|p.city|str.name|ort.name|p.phone|p.email";
$sql .= Helper::generateFilterCondition($filters['preorderInfo'], $searchColumns);
}
return "WHERE " . $sql;
}
public static function getCompanyWorkorders(array $filters, ?int $limit, int $offset, array $order, int $companyId): array
{
$db = self::getDB();
$fronkDbName = FRONKDB_DBNAME;
$addressDbName = defined('ADDRESSDB_DBNAME') ? ADDRESSDB_DBNAME : 'addressdb';
$sql = "
SELECT
w.id, w.status, w.deadlineDate, w.appointmentDate,
CONCAT_WS(' ', p.firstname, p.lastname) as customerName,
p.company as customerCompany, p.oaid, p.phone, p.email,
str.name as street, hn.hausnummer, hn.stiege, we.bezeichner as apartment, plz.plz, ort.name as city
FROM `$fronkDbName`.`RMLWorkorder` w
JOIN `$fronkDbName`.`Preorder` p ON w.preorderId = p.id
LEFT JOIN `$addressDbName`.`Hausnummer` hn ON p.adb_hausnummer_id = hn.id
LEFT JOIN `$addressDbName`.`Strasse` str ON hn.strasse_id = str.id
LEFT JOIN `$addressDbName`.`Plz` plz ON hn.plz_id = plz.id
LEFT JOIN `$addressDbName`.`Ortschaft` ort ON hn.ortschaft_id = ort.id
LEFT JOIN `$addressDbName`.`Wohneinheit` we ON p.adb_wohneinheit_id = we.id
";
$sql .= self::buildCompanyWhereClause($filters, $companyId);
$orderBy = " ORDER BY CASE WHEN w.deadlineDate IS NULL THEN 1 ELSE 0 END, w.deadlineDate ASC";
if (!empty($order['key'])) {
$sortableColumns = ['id', 'status', 'deadlineDate', 'appointmentDate'];
if (in_array($order['key'], $sortableColumns)) {
$sortOrder = (strtoupper($order['order']) === 'DESC') ? 'DESC' : 'ASC';
$orderBy = " ORDER BY " . $db->real_escape_string($order['key']) . " " . $sortOrder;
}
}
$sql .= $orderBy;
if ($limit !== null) {
$sql .= " LIMIT " . intval($limit) . " OFFSET " . intval($offset);
}
$result = $db->query($sql);
return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}
public static function countCompanyWorkorders(array $filters, int $companyId): int
{
$db = self::getDB();
$fronkDbName = FRONKDB_DBNAME;
$addressDbName = defined('ADDRESSDB_DBNAME') ? ADDRESSDB_DBNAME : 'addressdb';
$sql = "
SELECT COUNT(w.id) as count
FROM `$fronkDbName`.`RMLWorkorder` w
JOIN `$fronkDbName`.`Preorder` p ON w.preorderId = p.id
LEFT JOIN `$addressDbName`.`Hausnummer` hn ON p.adb_hausnummer_id = hn.id
LEFT JOIN `$addressDbName`.`Strasse` str ON hn.strasse_id = str.id
LEFT JOIN `$addressDbName`.`Plz` plz ON hn.plz_id = plz.id
LEFT JOIN `$addressDbName`.`Ortschaft` ort ON hn.ortschaft_id = ort.id
";
$sql .= self::buildCompanyWhereClause($filters, $companyId);
$result = $db->query($sql);
if ($result === false) {
return 0;
}
$row = $result->fetch_assoc();
return $row['count'] ?? 0;
}
} }
@@ -10,21 +10,27 @@ class RMLWorkorderAdminController extends TTCrud
protected array $columns = [ protected array $columns = [
['key' => 'id', 'text' => 'Auftrag-Nr.', 'table' => ['sortable' => true]], ['key' => 'id', 'text' => 'Auftrag-Nr.', 'table' => ['sortable' => true]],
['key' => 'preorderInfo', 'text' => 'Kunde / Projekt', 'modal' => false, 'table' => ['sortable' => false, 'filter' => 'search']], ['key' => 'preorderInfo', 'text' => 'Kunde / Projekt', 'modal' => false, 'table' => ['sortable' => false, 'filter' => 'search']],
['key' => 'preordercampaign_id', 'text' => 'Cluster', 'modal' => false, 'table' => ['filter' => 'select']],
['key' => 'companyName', 'text' => 'Zuständige Firma', 'modal' => false, 'table' => ['filter' => 'search']], ['key' => 'companyName', 'text' => 'Zuständige Firma', 'modal' => false, 'table' => ['filter' => 'search']],
['key' => 'status', 'text' => 'Status', 'modal' => false, 'table' => ['filter' => 'iconSelect', 'filterOptions' => [ ['key' => 'status', 'text' => 'Status', 'modal' => false, 'table' => ['filter' => 'iconSelect', 'filterOptions' => [
['value' => 'new', 'text' => 'Neu', 'icon' => 'fas fa-star text-primary'], ['value' => 'new', 'text' => 'Neu', 'icon' => 'fas fa-star text-primary'],
['value' => 'assigned', 'text' => 'Zugewiesen', 'icon' => 'fas fa-user-check text-info'], ['value' => 'assigned', 'text' => 'Zugewiesen', 'icon' => 'fas fa-user-check text-info'],
['value' => 'scheduled', 'text' => 'Terminiert', 'icon' => 'fas fa-calendar-check text-warning'], ['value' => 'scheduled', 'text' => 'Terminiert', 'icon' => 'fas fa-calendar-check text-warning'],
['value' => 'correction_requested', 'text' => 'Korrektur angefordert', 'icon' => 'fas fa-exclamation-triangle text-danger'],
['value' => 'documented', 'text' => 'Dokumentiert', 'icon' => 'fas fa-file-alt text-success'], ['value' => 'documented', 'text' => 'Dokumentiert', 'icon' => 'fas fa-file-alt text-success'],
['value' => 'completed', 'text' => 'Abgeschlossen', 'icon' => 'fas fa-check-double text-secondary'], ['value' => 'completed', 'text' => 'Abgeschlossen', 'icon' => 'fas fa-check-double text-secondary'],
]]], ]]],
['key' => 'deadlineDate', 'text' => 'Deadline', 'modal' => false, 'table' => ['filter' => 'date']], ['key' => 'deadlineDate', 'text' => 'Deadline', 'modal' => false, 'table' => ['filter' => 'date']],
['key' => 'appointmentDate', 'text' => 'Termin', 'modal' => false, 'table' => ['filter' => 'date']],
['key' => 'actions', 'text' => 'Aktionen', 'modal' => false, 'table' => ['filter' => false, 'sortable' => false]],
]; ];
protected function indexAction() protected function indexAction()
{ {
$campaigns = Helper::getPreorderCampaignFromUser($this->user, true);
$this->columns[array_search('preordercampaign_id', array_column($this->columns, 'key'))]['table']['filterOptions'] = array_map(
fn($c) => ['value' => $c->id, 'text' => $c->name],
$campaigns
);
$this->createWorkordersFromPreorders(); $this->createWorkordersFromPreorders();
Helper::renderVue($this, 'RMLWorkorderAdmin', $this->headerTitle, [ Helper::renderVue($this, 'RMLWorkorderAdmin', $this->headerTitle, [
"CRUD_CONFIG" => $this->getCrudConfig(), "CRUD_CONFIG" => $this->getCrudConfig(),
@@ -32,62 +38,50 @@ class RMLWorkorderAdminController extends TTCrud
]); ]);
} }
protected function getAction() protected function getAction() {
{
$json = json_decode(file_get_contents('php://input'), true); $json = json_decode(file_get_contents('php://input'), true);
$pagination = $json['pagination'] ?? ['page' => 1, 'per_page' => 10]; $pagination = $json['pagination'] ?? ['page' => 1, 'per_page' => 10];
$filters = $json['filters'] ?? []; $filters = $json['filters'] ?? [];
$order = $json['order'] ?? ['key' => 'id', 'order' => 'DESC']; $order = $json['order'] ?? [];
// Custom filter logic for preorderInfo $allowedCampaignIds = Helper::getPreorderCampaignFromUser($this->user);
if (!empty($filters['preorderInfo'])) {
$searchTerm = $filters['preorderInfo'];
unset($filters['preorderInfo']);
// This is a simplified search. A more robust implementation might involve a full-text search or a more complex query. if (empty($allowedCampaignIds)) {
$preorders = PreorderModel::getAll(['firstname|lastname|company|oaid' => $searchTerm]); self::returnJson([
$preorderIds = array_map(fn($p) => $p->id, $preorders); 'rows' => [],
'pagination' => array_merge($pagination, ['total_rows' => 0, 'total_pages' => 0, 'filtered_available' => 0])
if (!empty($preorderIds)) { ]);
$filters['preorderId'] = $preorderIds; return;
} else {
// No preorders found, so no workorders will be found
$filters['id'] = -1;
}
} }
$workorders = RMLWorkorderModel::getAll($filters, $pagination['per_page'], ($pagination['page'] - 1) * $pagination['per_page'], $order); $limit = $pagination['per_page'];
$totalCount = RMLWorkorderModel::count($filters); $offset = ($pagination['page'] - 1) * $limit;
$rows = []; $workorders = RMLWorkorderModel::getAdminWorkorders($filters, $limit, $offset, $order, $allowedCampaignIds);
foreach($workorders as $workorder) { $totalCount = RMLWorkorderModel::countAdminWorkorders($filters, $allowedCampaignIds);
$rows = array_map(function($workorder) {
$row = (array)$workorder; $row = (array)$workorder;
$preorder = new Preorder($workorder->preorderId); $anschlussadresse = "{$row['street']} {$row['hausnummer']}";
$anschlussadresse = 'N/A'; if ($row['stiege']) $anschlussadresse .= "/{$row['stiege']}";
if ($preorder->adb_hausnummer_id) { if ($row['apartment']) $anschlussadresse .= " / WE: {$row['apartment']}";
$hn = $preorder->adb_hausnummer; $anschlussadresse .= ", {$row['plz']} {$row['city']}";
$anschlussadresse = "{$hn->strasse->name} {$hn->hausnummer}";
if ($hn->stiege) $anschlussadresse .= "/{$hn->stiege}";
if ($preorder->adb_wohneinheit_id) $anschlussadresse .= " / WE: {$preorder->adb_wohneinheit->bezeichner}";
$anschlussadresse .= ", {$hn->plz->plz} {$hn->ortschaft->name}";
}
$kunde = ($preorder->company) ?: "{$preorder->firstname} {$preorder->lastname}"; $kunde = $row['customerCompany'] ?: $row['customerName'];
$row['preorderInfo'] = "<strong>Kunde:</strong> {$kunde}<br>" . $row['preorderInfo'] = "<strong>Kunde:</strong> {$kunde}<br>" .
"<strong>Anschluss:</strong> {$anschlussadresse}<br>" . "<strong>Anschluss:</strong> {$anschlussadresse}<br>" .
"<strong>OAID:</strong> <span class='text-pink'>{$preorder->oaid}</span>"; "<strong>OAID:</strong> <span class='text-pink'>{$row['oaid']}</span>";
if($workorder->companyId) { $row['companyName'] ??= 'Nicht zugewiesen';
$company = RMLWorkorderCompanyModel::get($workorder->companyId); $row['deadlineDateFormatted'] = $row['deadlineDate'] ? date('d.m.Y', $row['deadlineDate']) : 'Keine Deadline';
$row['companyName'] = $company->name ?? 'N/A'; $row['daysUntilDeadline'] = $row['deadlineDate'] ? ceil(($row['deadlineDate'] - time()) / (60 * 60 * 24)) : null;
} else {
$row['companyName'] = 'Nicht zugewiesen';
}
$rows[] = $row; unset($row['customerName'], $row['customerCompany'], $row['street'], $row['hausnummer'], $row['stiege'], $row['oaid'], $row['apartment'], $row['plz'], $row['city']);
}
return $row;
}, $workorders);
self::returnJson([ self::returnJson([
'rows' => $rows, 'rows' => $rows,
@@ -95,7 +89,7 @@ class RMLWorkorderAdminController extends TTCrud
'page' => $pagination['page'], 'page' => $pagination['page'],
'per_page' => $pagination['per_page'], 'per_page' => $pagination['per_page'],
'total_rows' => $totalCount, 'total_rows' => $totalCount,
'total_pages' => ceil($totalCount / $pagination['per_page']), 'total_pages' => ceil($totalCount / $limit),
'filtered_available' => $totalCount 'filtered_available' => $totalCount
] ]
]); ]);
@@ -109,6 +103,7 @@ class RMLWorkorderAdminController extends TTCrud
if (!RMLWorkorderModel::getFirst(['preorderId' => $preorder->id])) { if (!RMLWorkorderModel::getFirst(['preorderId' => $preorder->id])) {
RMLWorkorderModel::create([ RMLWorkorderModel::create([
'preorderId' => $preorder->id, 'preorderId' => $preorder->id,
'clusterId' => $preorder->preordercampaign_id,
'status' => 'new', 'status' => 'new',
'create' => time(), 'create' => time(),
'createBy' => $this->user->id 'createBy' => $this->user->id
@@ -127,7 +122,7 @@ class RMLWorkorderAdminController extends TTCrud
$workorder->companyId = $post['companyId']; $workorder->companyId = $post['companyId'];
$workorder->status = 'assigned'; $workorder->status = 'assigned';
$workorder->assignmentDate = time(); $workorder->assignmentDate = time();
$workorder->deadlineDate = strtotime('+6 weeks'); $workorder->deadlineDate = $post['deadlineDate'] ?? strtotime('+6 weeks');
RMLWorkorderModel::update((array)$workorder); RMLWorkorderModel::update((array)$workorder);
@@ -138,15 +133,62 @@ class RMLWorkorderAdminController extends TTCrud
if(empty($this->request->workorderId)) self::sendError("Workorder ID missing."); if(empty($this->request->workorderId)) self::sendError("Workorder ID missing.");
$docs = RMLWorkorderDocumentationModel::getAll(['workorderId' => $this->request->workorderId], null, 0, ['key' => 'create', 'order' => 'DESC']); $docs = RMLWorkorderDocumentationModel::getAll(['workorderId' => $this->request->workorderId], null, 0, ['key' => 'create', 'order' => 'DESC']);
$users = UserModel::search(['employee' => true]); $journals = RMLWorkorderJournalModel::getAll(['workorderId' => $this->request->workorderId], null, 0, ['key' => 'create', 'order' => 'DESC']);
$userMap = array_reduce($users, fn($carry, $user) => $carry + [$user->id => $user->name], []); $users = UserModel::search();
foreach($docs as $doc) { foreach($docs as $doc) {
$file = new File($doc->fileId); $file = new File($doc->fileId);
$doc->fileName = $file->orig_filename ?? $file->filename; $doc->fileName = $file->orig_filename ?? $file->filename;
$doc->userName = $userMap[$doc->createBy] ?? 'Unbekannt'; $doc->userName = UserModel::getOne($doc->createBy)->name ?? 'Unbekannt';
$doc->mimetype = $file->mimetype ?? 'application/octet-stream';
} }
self::returnJson($docs); foreach($journals as $journal) {
$journal->createByName = UserModel::getOne($journal->createBy)->name ?? 'Unbekannt';
}
self::returnJson(['docs' => $docs, 'journals' => $journals]);
}
protected function massAssignWorkordersAction() {
$post = json_decode(file_get_contents('php://input'), true);
if (empty($post['workorderIds']) || empty($post['companyId'])) self::sendError("Required fields are missing.");
$deadline = strtotime($post['deadlineDate'] ?? '+6 weeks');
$count = 0;
foreach ($post['workorderIds'] as $workorderId) {
$workorder = RMLWorkorderModel::get($workorderId);
if ($workorder && $workorder->status === 'new') {
$workorder->companyId = $post['companyId'];
$workorder->status = 'assigned';
$workorder->assignmentDate = time();
$workorder->deadlineDate = $deadline;
RMLWorkorderModel::update((array)$workorder);
$count++;
}
}
self::returnJson(['success' => true, 'message' => "$count Aufträge erfolgreich zugewiesen."]);
}
protected function requestCorrectionAction() {
$post = json_decode(file_get_contents('php://input'), true);
if (empty($post['workorderId']) || empty($post['text'])) self::sendError("Required fields are missing.");
$workorder = RMLWorkorderModel::get($post['workorderId']);
if (!$workorder) self::sendError("Workorder not found.");
$oldStatus = $workorder->status;
$workorder->status = 'correction_requested';
RMLWorkorderModel::update((array)$workorder);
RMLWorkorderJournalModel::create([
'workorderId' => $workorder->id,
'text' => $post['text'],
'fileIds' => !empty($post['fileIds']) ? json_encode($post['fileIds']) : null,
'statusChange' => "$oldStatus -> correction_requested",
'create' => time(),
'createBy' => $this->user->id,
]);
self::returnJson(['success' => true, 'message' => 'Korrektur wurde angefordert.']);
} }
protected function getCompaniesAction() { protected function getCompaniesAction() {
@@ -154,4 +196,34 @@ class RMLWorkorderAdminController extends TTCrud
$items = array_map(fn($c) => ['value' => $c->id, 'text' => $c->name], $companies); $items = array_map(fn($c) => ['value' => $c->id, 'text' => $c->name], $companies);
self::returnJson($items); self::returnJson($items);
} }
protected function addJournalAction() {
$post = json_decode(file_get_contents('php://input'), true);
if (empty($post['workorderId']) || empty(trim($post['text']))) {
self::sendError("Workorder ID and text are required.");
}
RMLWorkorderJournalModel::create([
'workorderId' => $post['workorderId'],
'text' => $post['text'],
'createBy' => $this->user->id,
'create' => time(),
]);
$journals = array_map(
function ($j) {
$j->createByName = UserModel::getOne($j->createBy)->name ?? 'Unbekannt';
return (array)$j;
},
RMLWorkorderJournalModel::getAll(['workorderId' => $post['workorderId']], null, 0, ['key' => 'create', 'order' => 'DESC'])
);
self::returnJson([
'success' => true,
'message' => 'Journal-Eintrag hinzugefügt.',
'journals' => $journals
]);
}
} }
@@ -13,12 +13,12 @@ class RMLWorkorderCompanyController extends TTCrud
['value' => 'new', 'text' => 'Neu', 'icon' => 'fas fa-star text-primary'], ['value' => 'new', 'text' => 'Neu', 'icon' => 'fas fa-star text-primary'],
['value' => 'assigned', 'text' => 'Zugewiesen', 'icon' => 'fas fa-user-check text-info'], ['value' => 'assigned', 'text' => 'Zugewiesen', 'icon' => 'fas fa-user-check text-info'],
['value' => 'scheduled', 'text' => 'Terminiert', 'icon' => 'fas fa-calendar-check text-warning'], ['value' => 'scheduled', 'text' => 'Terminiert', 'icon' => 'fas fa-calendar-check text-warning'],
['value' => 'correction_requested', 'text' => 'Korrektur angefordert', 'icon' => 'fas fa-exclamation-triangle text-danger'],
['value' => 'documented', 'text' => 'Dokumentiert', 'icon' => 'fas fa-file-alt text-success'], ['value' => 'documented', 'text' => 'Dokumentiert', 'icon' => 'fas fa-file-alt text-success'],
['value' => 'completed', 'text' => 'Abgeschlossen', 'icon' => 'fas fa-check-double text-secondary'], ['value' => 'completed', 'text' => 'Abgeschlossen', 'icon' => 'fas fa-check-double text-secondary'],
]]], ]]],
['key' => 'deadlineDate', 'text' => 'Deadline', 'modal' => false, 'table' => ['filter' => 'date']], ['key' => 'deadlineDate', 'text' => 'Deadline', 'modal' => false, 'table' => ['filter' => 'date']],
['key' => 'appointmentDate', 'text' => 'Termin', 'modal' => false, 'table' => ['filter' => 'date']], ['key' => 'appointmentDate', 'text' => 'Termin', 'modal' => false, 'table' => ['filter' => 'date']],
['key' => 'actions', 'text' => 'Aktionen', 'modal' => false, 'table' => ['filter' => false, 'sortable' => false]],
]; ];
protected array $additionalJSVariables = ['COMPANY_ID' => '0']; protected array $additionalJSVariables = ['COMPANY_ID' => '0'];
@@ -46,40 +46,38 @@ class RMLWorkorderCompanyController extends TTCrud
$json = json_decode(file_get_contents('php://input'), true); $json = json_decode(file_get_contents('php://input'), true);
$pagination = $json['pagination'] ?? ['page' => 1, 'per_page' => 10]; $pagination = $json['pagination'] ?? ['page' => 1, 'per_page' => 10];
$filters = $json['filters'] ?? []; $filters = $json['filters'] ?? [];
$order = $json['order'] ?? ['key' => 'id', 'order' => 'DESC']; $order = $json['order'] ?? ['key' => 'deadlineDate', 'order' => 'ASC'];
$company = RMLWorkorderCompanyModel::getFirst(['addressId' => $this->user->address_id]); $company = RMLWorkorderCompanyModel::getFirst(['addressId' => $this->user->address_id]);
if(!$company) self::sendError("Company not found for user.", 403); if (!$company) {
$filters['companyId'] = $company->id; self::sendError("Company not found for user.", 403);
if (!empty($filters['preorderInfo'])) {
$searchTerm = $filters['preorderInfo'];
//todo: fix this preordermodel search shit
$preorders = PreorderModel::getAll(['firstname|lastname|company|oaid' => $searchTerm]);
$preorderIds = array_map(fn($p) => $p->id, $preorders);
if (!empty($preorderIds)) {
$filters['preorderId'] = $preorderIds;
} else {
$filters['id'] = -1;
} }
}
unset($filters['preorderInfo']);
// only show workorders that are assigned to the company and have the status assigned or scheduled
$filters['status'] = ['assigned', 'scheduled'];
$filters['companyId'] = $company->id;
// Get paginated workorders and total count from the new model methods
$workorders = RMLWorkorderModel::getCompanyWorkorders($filters, $pagination['per_page'], ($pagination['page'] - 1) * $pagination['per_page'], $order, $company->id);
$totalCount = RMLWorkorderModel::countCompanyWorkorders($filters, $company->id);
$workorders = RMLWorkorderModel::getAll($filters, $pagination['per_page'], ($pagination['page'] - 1) * $pagination['per_page'], $order); // Format rows for the frontend
$totalCount = RMLWorkorderModel::count($filters); $rows = array_map(function($workorder) {
$rows = [];
foreach($workorders as $workorder) {
$row = (array)$workorder; $row = (array)$workorder;
$row['preorderInfo'] = $this->getPreorderInfoText($workorder->preorderId);
$rows[] = $row; $anschlussadresse = "{$row['street']} {$row['hausnummer']}";
} if ($row['stiege']) $anschlussadresse .= "/{$row['stiege']}";
if ($row['apartment']) $anschlussadresse .= " / WE: {$row['apartment']}";
$anschlussadresse .= ", {$row['plz']} {$row['city']}";
$kunde = $row['customerCompany'] ?: $row['customerName'];
$row['preorderInfo'] = "<strong>Kunde:</strong> {$kunde}<br>" .
"<strong>Anschluss:</strong> {$anschlussadresse}<br>" .
"<strong>Kontakt:</strong> {$row['phone']} / {$row['email']}<br>" .
"<strong>OAID:</strong> <span class='text-pink'>{$row['oaid']}</span>";
// Clean up unnecessary fields before sending
unset($row['customerName'], $row['customerCompany'], $row['street'], $row['hausnummer'], $row['stiege'], $row['oaid'], $row['apartment'], $row['plz'], $row['city'], $row['phone'], $row['email']);
return $row;
}, $workorders);
self::returnJson([ self::returnJson([
'rows' => $rows, 'rows' => $rows,
@@ -92,7 +90,6 @@ class RMLWorkorderCompanyController extends TTCrud
] ]
]); ]);
} }
public function getWorkorderByIdAction() { public function getWorkorderByIdAction() {
$id = $this->request->id; $id = $this->request->id;
if(!$id) self::sendError("ID missing"); if(!$id) self::sendError("ID missing");
@@ -173,22 +170,30 @@ class RMLWorkorderCompanyController extends TTCrud
]); ]);
$uploadCount++; $uploadCount++;
} catch (Exception $e) { } catch (Exception $e) {
var_dump($e->getMessage());exit;
// Log error but continue with other files
error_log("File upload failed for $name: " . $e->getMessage()); error_log("File upload failed for $name: " . $e->getMessage());
} }
} }
} }
self::returnJson(['success' => true, 'message' => "$uploadCount Datei(en) erfolgreich hochgeladen."]); $workorder = RMLWorkorderModel::get($workorderId);
if ($workorder->status === 'correction_requested') {
$workorder->status = 'assigned';
RMLWorkorderModel::update((array)$workorder);
$workorder = RMLWorkorderModel::get($workorderId);
} }
protected function getDocumentationAction() { $formattedDocs = $this->getFormattedDocs($workorderId);
if(empty($this->request->workorderId)) self::sendError("Workorder ID missing.");
// Order by creation date to ensure consistent numbering (_1, _2, etc.) self::returnJson([
$docs = RMLWorkorderDocumentationModel::getAll(['workorderId' => $this->request->workorderId], null, 0, ['key' => 'create', 'order' => 'ASC']); 'success' => true,
'message' => "$uploadCount Datei(en) erfolgreich hochgeladen.",
'docs' => $formattedDocs,
'workorder' => (array)$workorder
]);
}
private function getFormattedDocs($workorderId) {
$docs = RMLWorkorderDocumentationModel::getAll(['workorderId' => $workorderId], null, 0, ['key' => 'create', 'order' => 'ASC']);
$responseDocs = []; $responseDocs = [];
$typeCounts = []; $typeCounts = [];
@@ -202,8 +207,6 @@ class RMLWorkorderCompanyController extends TTCrud
foreach($docs as $doc) { foreach($docs as $doc) {
$file = new File($doc->fileId); $file = new File($doc->fileId);
// Increment counter for the specific document type
$documentTypeKey = $doc->documentType; $documentTypeKey = $doc->documentType;
if (!isset($typeCounts[$documentTypeKey])) { if (!isset($typeCounts[$documentTypeKey])) {
$typeCounts[$documentTypeKey] = 1; $typeCounts[$documentTypeKey] = 1;
@@ -211,23 +214,37 @@ class RMLWorkorderCompanyController extends TTCrud
$typeCounts[$documentTypeKey]++; $typeCounts[$documentTypeKey]++;
} }
// Construct the new filename using the original key
$originalFilename = $file->orig_filename ?? $file->filename; $originalFilename = $file->orig_filename ?? $file->filename;
$extension = pathinfo($originalFilename, PATHINFO_EXTENSION); $extension = pathinfo($originalFilename, PATHINFO_EXTENSION);
$translatedType = $translationMap[$documentTypeKey] ?? $documentTypeKey; $translatedType = $translationMap[$documentTypeKey] ?? $documentTypeKey;
$newFilename = "{$translatedType} {$typeCounts[$documentTypeKey]}." . strtolower($extension); $newFilename = "{$translatedType}_{$typeCounts[$documentTypeKey]}." . strtolower($extension);
// Get the translated text, with a fallback to the original key
// Build the response object with 'id' mapped from 'fileId' and the translated type
$responseDocs[] = [ $responseDocs[] = [
'id' => $doc->fileId, 'id' => $doc->id,
'fileId' => $doc->fileId,
'fileName' => $newFilename, 'fileName' => $newFilename,
'documentType' => $documentTypeKey, 'documentType' => $documentTypeKey,
'mimetype' => $file->mimetype, 'mimetype' => $file->mimetype,
]; ];
} }
self::returnJson($responseDocs); return $responseDocs;
}
protected function getDocumentationAction() {
if(empty($this->request->workorderId)) self::sendError("Workorder ID missing.");
$docs = $this->getFormattedDocs($this->request->workorderId);
$journals = array_map(
function ($j) {
$j->createByName = UserModel::getOne($j->createBy)->getAbbrName();
return (array)$j;
},
RMLWorkorderJournalModel::getAll(['workorderId' => $this->request->workorderId], null, 0, ['key' => 'create', 'order' => 'DESC'])
);
self::returnJson(['docs' => $docs, 'journals' => $journals]);
} }
protected function completeWorkorderAction() { protected function completeWorkorderAction() {
$post = json_decode(file_get_contents('php://input'), true); $post = json_decode(file_get_contents('php://input'), true);
@@ -241,4 +258,74 @@ class RMLWorkorderCompanyController extends TTCrud
self::returnJson(['success' => true, 'message' => 'Auftrag abgeschlossen.']); self::returnJson(['success' => true, 'message' => 'Auftrag abgeschlossen.']);
} }
protected function deleteDocumentationAction() {
$post = json_decode(file_get_contents('php://input'), true);
if (empty($post['id'])) self::sendError("Document ID missing.");
$doc = RMLWorkorderDocumentationModel::get($post['id']);
if (!$doc) self::sendError("Document not found.");
$workorderId = $doc->workorderId;
RMLWorkorderDocumentationModel::delete($post['id']);
$formattedDocs = $this->getFormattedDocs($workorderId);
self::returnJson([
'success' => true,
'message' => 'Dokument gelöscht.',
'docs' => $formattedDocs
]);
}
protected function updateDocumentationAction() {
$post = json_decode(file_get_contents('php://input'), true);
if (empty($post['id'])) self::sendError("Document ID missing.");
$doc = RMLWorkorderDocumentationModel::get($post['id']);
if (!$doc) self::sendError("Dokument nicht gefunden.");
if (isset($post['documentType'])) {
$doc->documentType = $post['documentType'];
}
RMLWorkorderDocumentationModel::update((array)$doc);
$formattedDocs = $this->getFormattedDocs($doc->workorderId);
self::returnJson([
'success' => true,
'message' => 'Dokument aktualisiert.',
'docs' => $formattedDocs
]);
}
protected function addJournalAction() {
$post = json_decode(file_get_contents('php://input'), true);
if (empty($post['workorderId']) || empty(trim($post['text']))) {
self::sendError("Workorder ID and text are required.");
}
RMLWorkorderJournalModel::create([
'workorderId' => $post['workorderId'],
'text' => $post['text'],
'createBy' => $this->user->id,
'create' => time(),
]);
$journals = array_map(
function ($j) {
$j->createByName = UserModel::getOne($j->createBy)->getAbbrName();
return (array)$j;
},
RMLWorkorderJournalModel::getAll(['workorderId' => $post['workorderId']], null, 0, ['key' => 'create', 'order' => 'DESC'])
);
self::returnJson([
'success' => true,
'message' => 'Journal-Eintrag hinzugefügt.',
'journals' => $journals
]);
}
} }
@@ -0,0 +1,11 @@
<?php
class RMLWorkorderJournalModel extends TTCrudBaseModel {
public int $id;
public int $workorderId;
public ?string $text;
public ?string $fileIds;
public ?string $statusChange;
public int $create;
public int $createBy;
}
@@ -204,9 +204,11 @@ class TimerecordingEmployeeController extends mfBaseController
if (!$data['overtime']) { if (!$data['overtime']) {
$data['overtime'] = 0; $data['overtime'] = 0;
} }
if (!$data['bmd_active']) { if (!$data['bmd_active']) {
$data['bmd_active'] = 0; $data['bmd_active'] = 0;
} }
if (!$data['enddate']) { if (!$data['enddate']) {
$data['enddate'] = null; $data['enddate'] = null;
} }
@@ -216,6 +218,13 @@ class TimerecordingEmployeeController extends mfBaseController
} else { } else {
$data['birthday'] = null; $data['birthday'] = null;
} }
if ($r->insurance_number) {
$data['insurance_number'] = $r->insurance_number;
} else {
$data['insurance_number'] = null;
}
if (!$data['user_id']) { if (!$data['user_id']) {
$this->layout()->setFlash("Mitarbeiter darf nicht leer sein", "error"); $this->layout()->setFlash("Mitarbeiter darf nicht leer sein", "error");
$this->redirect("TimerecordingEmployee"); $this->redirect("TimerecordingEmployee");
@@ -22,6 +22,7 @@ class TimerecordingEmployeeModel
private $jobbike; private $jobbike;
private $only_admin; private $only_admin;
private $birthday; private $birthday;
private $insurance_number;
public static $employeetypesbmd = array('1' => '1000', '2' => '1200', '3' => '1400'); public static $employeetypesbmd = array('1' => '1000', '2' => '1200', '3' => '1400');
@@ -98,9 +98,8 @@ class TimerecordingReportController extends mfBaseController
$workinghourshistory = TimerecordingEmployeeWorkingHourHistoryModel::getAll(); $workinghourshistory = TimerecordingEmployeeWorkingHourHistoryModel::getAll();
if ($workinghourshistory) { if ($workinghourshistory) {
$workingHoursHistory[2147483500] = $workingHours;
foreach ($workinghourshistory as $workinghourhistory) { foreach ($workinghourshistory as $workinghourhistory) {
$workingHoursHistory[$workinghourshistory->user_id][2147483500] = $workingHours; $workingHoursHistory[$workinghourhistory->user_id][2147483500] = $workingHours[$workinghourhistory->user_id];
$whenddate = $workinghourhistory->enddate; $whenddate = $workinghourhistory->enddate;
$workinghourhistoryhours = json_decode($workinghourhistory->workinghours, true); $workinghourhistoryhours = json_decode($workinghourhistory->workinghours, true);
foreach ($workinghourhistoryhours as $workinghourhistoryhour) { foreach ($workinghourhistoryhours as $workinghourhistoryhour) {
@@ -112,12 +111,8 @@ class TimerecordingReportController extends mfBaseController
$workingHoursHistory[$workinghourhistory->user_id][$whenddate][$workinghourhistoryhour['day']] = $workingHoursHistory[$whenddate][$workinghourhistoryhour['day']] + $whend - $whstart; $workingHoursHistory[$workinghourhistory->user_id][$whenddate][$workinghourhistoryhour['day']] = $workingHoursHistory[$whenddate][$workinghourhistoryhour['day']] + $whend - $whstart;
} }
} }
// echo $workinghourhistory->user_id."<br>";
} }
} }
// var_dump($workingHoursHistory);
// die();
foreach ($this->holidays as $holiday) { foreach ($this->holidays as $holiday) {
$holiDay[date('Y-m-d', $holiday->timestamp)] = $holiday->timestamp; $holiDay[date('Y-m-d', $holiday->timestamp)] = $holiday->timestamp;
@@ -182,6 +177,30 @@ class TimerecordingReportController extends mfBaseController
} }
} else if ($datatype == 5) {
$firstdate = strtotime(date("Y-01-01", $datayear));
$lastdate = strtotime(date("Y-12-31 23:59:59", $datayear));
$daycount = date("t", $datamonth);
$lastdate = strtotime(date("Y-m-d", $lastdate) . ' 23:59:59');
if ($calendar == "1") {
$lastdate = strtotime(" +3 years", $lastdate);
}
$searchArray = ['start' => $firstdate, 'end' => $lastdate];
$timestamp = $firstdate;
for ($i = 1; $i <= $daycount; $i++) {
$dDate = date('Y-m-d', $timestamp);
$dDay = date('w', $timestamp);
if (!$holiDay[$dDate]) {
//$mustSeconds = $mustSeconds + $workingHours[$dDay];
}
$timestamp = $timestamp + 86400;
}
} }
@@ -0,0 +1,240 @@
<?php
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Style\Font;
class TimerecordingReportExportController extends mfBaseController
{
protected function init()
{
$this->needlogin = true;
$me = new User();
$me->loadMe();
$this->me = $me;
$this->layout()->set("me", $me);
if (!$me->is(["employee"])) {
$this->redirect("Dashboard");
}
}
protected function indexAction()
{
$this->layout()->setTemplate("TimerecordingReportExport/Index");
}
protected function exportdeadlineAction()
{
$r = $this->request;
$month=$r->date;
if (!$month) {
$month = date('Y-m-d');
}
$timerecordingBillings = TimerecordingBillingModel::getAll();
foreach ($timerecordingBillings as $value) {
$timerecordingBilling[$value->month] = $value;
}
$timerecordingBillingsEmployees = TimerecordingBillingEmployeeModel::getAllOrderbyNameDate();
$timerecordingemployees = TimerecordingEmployeeModel::getAll();
$enddate = strtotime($month);
$enddate = strtotime("last day of this month", $enddate);
$enddate = strtotime("23:59:59", $enddate);
$holidays = [];
// $generateTimerecording=new TimerecordingController();
// $newtimerecordings=$generateTimerecording->getTimerecordingsApi(6, '1672527600', '1672527600', '1672527600', '1672527600', '1735685940', 25);
// var_dump($newtimerecordings);
// die();
foreach ($timerecordingemployees as $timerecordingemployee) {
$holidays[$timerecordingemployee->user_id] = $this->getholidays($timerecordingemployee->user_id, $enddate);
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Monatsübersicht');
$headers = [
'Stichtag', 'Pers. Nr.', 'Mitarbeiter', 'Urlaub', 'Mehrstunden', 'Gutstunden'
];
if ($this->me->superexpertEnabled()) {
$headers[] = 'Black P. St.';
}
$sheet->fromArray($headers, NULL, 'A1');
$sheet->getStyle('A1:' . $sheet->getHighestColumn() . '1')->getFont()->setBold(true);
$row = 2;
$oldEmployee_id = "";
$bpadiff = 0;
$overtimediff = 0;
$plushoursdiff = 0;
foreach ($timerecordingBillingsEmployees as $timerecordingbillingsemployee) {
// Daten vorbereiten (Logik aus der View übernehmen)
$user = new User($timerecordingbillingsemployee->timerecordingEmployee->user->id);
$employee_number = (string)$user->getFlag('employee_number');
if ($oldEmployee_id != $timerecordingbillingsemployee->timerecordingEmployee_id) {
$bpadiff = 0;
$overtimediff = 0;
$plushoursdiff = 0;
}
$bpadiff = $bpadiff + $timerecordingbillingsemployee->transfer_bpahours;
$overtimediff = $overtimediff + $timerecordingbillingsemployee->transfer_overtime;
$plushoursdiff = $plushoursdiff + $timerecordingbillingsemployee->transfer_plushours;
if ($timerecordingbillingsemployee->timerecordingBilling->month != date("m.Y",$enddate)) {
$oldEmployee_id = $timerecordingbillingsemployee->timerecordingEmployee_id;
continue;
}
$sheet->setCellValue('A' . $row, date("d.m.Y",$enddate). " ");
$sheet->setCellValue('B' . $row, $employee_number);
$sheet->setCellValue('C' . $row, $timerecordingbillingsemployee->timerecordingEmployee->user->name);
$sheet->setCellValue('D' . $row, $holidays[$timerecordingbillingsemployee->timerecordingEmployee->user_id]);
$sheet->setCellValue('E' . $row, round(($timerecordingbillingsemployee->plushours_all + $timerecordingbillingsemployee->transfer_plushours) / 3600, 2));
$sheet->setCellValue('F' . $row, round(($timerecordingbillingsemployee->timerecordingEmployee->overtime_now + $overtimediff) / 3600, 2));
$oldEmployee_id = $timerecordingbillingsemployee->timerecordingEmployee_id;
$row++;
}
$number_format_code = '#,##0.00';
$sheet->getStyle('A2:A' . $row)->getNumberFormat()->setFormatCode('@');
$sheet->getStyle('C2:C' . $row)->getNumberFormat()->setFormatCode($number_format_code);
$sheet->getStyle('E2:E' . $row)->getNumberFormat()->setFormatCode($number_format_code);
$sheet->getStyle('F2:F' . $row)->getNumberFormat()->setFormatCode($number_format_code);
$sheet->getStyle('G2:G' . $row)->getNumberFormat()->setFormatCode($number_format_code);
$sheet->getStyle('H2:H' . $row)->getNumberFormat()->setFormatCode($number_format_code);
$sheet->getStyle('I2:I' . $row)->getNumberFormat()->setFormatCode($number_format_code);
$sheet->getStyle('J2:J' . $row)->getNumberFormat()->setFormatCode($number_format_code);
if ($this->me->superexpertEnabled()) {
$sheet->getStyle('K2:K' . $row)->getNumberFormat()->setFormatCode($number_format_code);
}
$sheet->getStyle('D2:D' . $row)->getAlignment()->setWrapText(true);
foreach (range('A', $sheet->getHighestColumn()) as $columnID) {
$sheet->getColumnDimension($columnID)->setAutoSize(true);
}
$writer = new Xlsx($spreadsheet);
$filename = 'Monatsuebersicht_' . date('Y-m-d',$enddate) . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
// Datei an den Browser senden
$writer->save('php://output');
exit();
}
protected function getholidays($userid, $enddate)
{
$employee = TimerecordingEmployeeModel::search(['user_id' => $userid]);
if ($employee) {
$employee = $employee[0];
$holidays = $employee->holidays;
$holidays_now = $employee->holidays_now;
$holidays_timestamp = $employee->holidays_timestamp;
$workinghours = TimerecordingEmployeeWorkingHourModel::search(['user_id' => $userid]);
$realHolidays = TimerecordingHolidayModel::getAll();
foreach ($realHolidays as $realHoliday) {
$realholiDay[date('Y-m-d', $realHoliday->timestamp)] = $realHoliday->timestamp;
}
if (!$holidays_timestamp) {
//$holidays_timestamp = $employee->startdate;
$holidays_timestamp = strtotime('2024-01-01 00:00:00');
$holidays_now = $holidays;
}
$timerecordings = TimerecordingModel::search(['user_id' => $userid, 'start' => $holidays_timestamp, 'timerecordingCategory_id' => 3]);
$timerecordingscorrections = TimerecordingModel::search(['user_id' => $userid, 'start' => $holidays_timestamp, 'endsdate' => $enddate, 'days' => 1]);
foreach ($timerecordings as $timerecording) {
if ($timerecording->end > $enddate) {
$timerecording->end = $enddate;
}
$daycounter = ($timerecording->end - $timerecording->start) / 86400;
$daycounter = intval(round($daycounter, 0, PHP_ROUND_HALF_DOWN));
$daycounter = $daycounter * 86400;
if (is_int($daycounter)) {
for ($i = 86400; $i <= $daycounter; $i = $i + 86400) {
$holidayDays[date("Y-m-d", $timerecording->start + $i - 86400)] = 1;
}
}
}
foreach ($workinghours as $workinghour) {
$whstart = strtotime(date('Y-m-d', time()) . " " . $workinghour->start . ":00");
$whend = strtotime(date('Y-m-d', time()) . " " . $workinghour->end . ":00");
if (!$workingHours[$workinghour->day]) {
$workingHours[$workinghour->day] = $whend - $whstart;
} else {
$workingHours[$workinghour->day] = $workingHours[$workinghour->day] + $whend - $whstart;
}
}
$workinghourshistory = TimerecordingEmployeeWorkingHourHistoryModel::search(['user_id' => $userid]);
if ($workinghourshistory) {
$workingHoursHistory[2147483500] = $workingHours;
foreach ($workinghourshistory as $workinghourhistory) {
$whenddate = $workinghourhistory->enddate;
$workinghourhistoryhours = json_decode($workinghourhistory->workinghours, true);
foreach ($workinghourhistoryhours as $workinghourhistoryhour) {
$whstart = strtotime(date('Y-m-d', time()) . " " . $workinghourhistoryhour['start'] . ":00");
$whend = strtotime(date('Y-m-d', time()) . " " . $workinghourhistoryhour['end'] . ":00");
if (!$workingHoursHistory[$whenddate][$workinghourhistoryhour['day']]) {
$workingHoursHistory[$whenddate][$workinghourhistoryhour['day']] = $whend - $whstart;
} else {
$workingHoursHistory[$whenddate][$workinghourhistoryhour['day']] = $workingHoursHistory[$whenddate][$workinghourhistoryhour['day']] + $whend - $whstart;
}
}
}
}
//check if holiday is already in the list
foreach ($holidayDays as $key => $holidayDay) {
if ($workingHoursHistory) {
foreach ($workingHoursHistory as $whkey => $whdata) {
$whtimestamp = strtotime(date('Y-m-d 23:59:59', $whkey));
$timestamp = strtotime($key);
if ($whtimestamp >= $timestamp) {
$workingHours = $whdata;
}
}
}
if (($realholiDay[$key])) {
} else if ($workingHours[date('w', strtotime($key))]) {
$holidays_now--;
}
}
foreach ($timerecordingscorrections as $timerecordingscorrection) {
$holidays_now = $holidays_now + $timerecordingscorrection->days;
}
}
return $holidays_now;
}
}
+2
View File
@@ -125,6 +125,8 @@ class UserModel
$where .= " AND WorkerPermission.employee = 'true'"; $where .= " AND WorkerPermission.employee = 'true'";
} }
} }
if (isset($filter['active']))
$where .= " AND Worker.active = " . (int)$filter['active'];
//var_dump($filter, $where);exit; //var_dump($filter, $where);exit;
return $where; return $where;
@@ -0,0 +1,108 @@
<?php
class UserPasswordResetController extends mfBaseController
{
protected function indexAction()
{
self::redirect("UserPasswordReset", "forgotPassword");
}
protected function forgotPasswordAction()
{
$this->layout()->setTemplate("UserPasswordReset/forgot-password");
}
protected function sendResetLinkAction($request)
{
$username = $this->db()->escape($request['Username']);
$res = $this->db()->select(MFUSERTABLE, "*", "username='$username' OR email='$username'");
if ($this->db()->num_rows($res)) {
$user = $this->db()->fetch_object($res);
$token = bin2hex(random_bytes(32));
$expires = time() + 3600;
$this->db()->update(MFUSERTABLE, array(
'password_reset_token' => $token,
'password_reset_expires' => $expires
), "id=" . (int)$user->id);
$resetLink = "https://".MFAPPNAME.".xinon.at/UserPasswordReset/resetPassword?token=" . $token;
$email = new Emailnotification();
$email->setTo($user->email);
$email->setFrom('noreply@xinon.at','XINON No-Reply');
$email->setSubject("Passwort zurücksetzen für " . MFAPPNAME_FULL);
$textBody = "Hallo " . $user->username . ",\n\n" .
"Klicke auf den folgenden Link, um dein Passwort zurückzusetzen. Der Link ist eine Stunde gültig.\n\n" .
$resetLink . "\n\n" .
"Wenn du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail.\n";
$htmlBody = "<h2>Passwort zurücksetzen</h2>" .
"<p>Hallo " . $user->username . ",</p>" .
"<p>Klicke auf den folgenden Link, um dein Passwort zurückzusetzen. Der Link ist eine Stunde gültig.</p>" .
'<p><a href="' . $resetLink . '">Passwort jetzt zurücksetzen</a></p>' .
"<p>Wenn du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail bitte.</p>";
$email->setBody($textBody);
$email->setHtmlBody($htmlBody);
$email->send();
}
$this->layout()->setTemplate("UserPasswordReset/forgot-password-sent");
}
protected function resetPasswordAction($request)
{
if (empty($request['token'])) {
self::redirect("mfLogin", "index");
return;
}
$token = $this->db()->escape($request['token']);
$res = $this->db()->select(MFUSERTABLE, "*", "password_reset_token='$token' AND password_reset_expires > " . time());
if (!$this->db()->num_rows($res)) {
$this->layout()->setTemplate("mfLogin/Index");
return;
}
$this->layout()->set("token", $token);
$this->layout()->setTemplate("UserPasswordReset/reset-password");
}
protected function updatePasswordAction($request)
{
$token = $this->db()->escape($request['token']);
$password = $request['Password'];
$password_confirm = $request['Password_confirm'];
if (empty($token) || empty($password) || $password !== $password_confirm) {
$error="Passwörter stimmen nicht überein oder die Anfrage ist ungültig.";
$this->layout()->set("error",$error,);
$this->layout()->set("token", $token);
$this->layout()->setTemplate("UserPasswordReset/reset-password");
return;
}
$res = $this->db()->select(MFUSERTABLE, "*", "password_reset_token='$token' AND password_reset_expires > " . time());
if (!$this->db()->num_rows($res)) {
$this->layout()->setTemplate("mfLogin/Index");
return;
}
$user = $this->db()->fetch_object($res);
$new_hash = mfLoginController::generatePasswordHash($password);
$this->db()->update(MFUSERTABLE, array(
'password' => $new_hash,
'password_reset_token' => NULL,
'password_reset_expires' => NULL
), "id=" . (int)$user->id);
$this->layout()->setFlash("Dein Passwort wurde erfolgreich geändert. Du kannst dich jetzt einloggen.", "success");
self::redirect("/");
}
}
@@ -4,12 +4,13 @@ class WarehouseArticleController extends TTCrud {
protected string $headerTitle = 'Artikel'; protected string $headerTitle = 'Artikel';
protected $createText = 'Artikel erstellen'; protected $createText = 'Artikel erstellen';
protected string $singleText = 'Artikel'; protected string $singleText = 'Artikel';
protected bool $reopenOnCreate = true;
// @formatter:off // @formatter:off
protected array $columns = [ protected array $columns = [
['key' => 'title', 'text' => 'Titel', 'required' => true, 'table' => ['priority' => 9]], ['key' => 'title', 'text' => 'Titel', 'required' => true, 'table' => ['priority' => 9]],
['key' => 'articleNumber', 'text' => 'Nr.', 'required' => true], ['key' => 'articleNumber', 'text' => 'Nr.', 'required' => true],
['key' => 'description', 'text' => 'Beschreibung', 'required' => true, 'table' => ['sortable' => false]], ['key' => 'description', 'text' => 'Beschreibung', 'required' => true,'modal' => ['type' => 'textarea'], 'table' => ['sortable' => false]],
['key' => 'category_id', 'text' => 'Kategorie', 'required' => true, 'modal' => ['type' => 'select', 'items' => []], 'table' => ['filter' => 'select']], ['key' => 'category_id', 'text' => 'Kategorie', 'required' => true, 'modal' => ['type' => 'select', 'items' => []], 'table' => ['filter' => 'select']],
['key' => 'unit', 'text' => 'Einheit', 'required' => true,'table' => false], ['key' => 'unit', 'text' => 'Einheit', 'required' => true,'table' => false],
['key' => 'revenueAccount', 'text' => 'Erlöskonto', 'required' => true,'modal' => ['type' => 'select', 'items' => [['value' => 0, 'text' => 'Dienstleistungen'], ['value' => 1, 'text' => 'Handelswaren']]], 'table' => false], ['key' => 'revenueAccount', 'text' => 'Erlöskonto', 'required' => true,'modal' => ['type' => 'select', 'items' => [['value' => 0, 'text' => 'Dienstleistungen'], ['value' => 1, 'text' => 'Handelswaren']]], 'table' => false],
@@ -46,7 +47,15 @@ class WarehouseArticleController extends TTCrud {
$this->additionalJSVariables['WAREHOUSE_ADMIN'] = false; $this->additionalJSVariables['WAREHOUSE_ADMIN'] = false;
} }
protected function beforeCreate() {
if (!in_array($this->user->id, [2, 5, 6, 145]))
self::sendError("Sie haben keine Berechtigung, Artikel zu erstellen.");
return true;
}
protected function beforeUpdate($postData): bool { protected function beforeUpdate($postData): bool {
if (!in_array($this->user->id, [2, 5, 6, 145]))
self::sendError("Sie haben keine Berechtigung, Artikel zu bearbeiten.");
(new WarehouseHistoryController)->create($postData, $this->mod); (new WarehouseHistoryController)->create($postData, $this->mod);
return true; return true;
} }
@@ -17,6 +17,6 @@ class WarehouseArticleModel extends TTCrudBaseModel {
public string $unit; public string $unit;
public ?int $isSerialDocumentation; public ?int $isSerialDocumentation;
public int $revenueAccount; public int $revenueAccount;
public int $create;
public int $createBy;
} }
@@ -7,4 +7,6 @@ class WarehouseArticleDistributorModel extends TTCrudBaseModel {
public float $purchasePrice; public float $purchasePrice;
public string $externalArticleNumber; public string $externalArticleNumber;
public ?string $note; public ?string $note;
public int $create;
public int $createBy;
} }
@@ -13,4 +13,6 @@ class WarehouseArticlePacketModel extends TTCrudBaseModel {
public ?int $isEShopHide; // New field to hide from Energie Steiermark shop public ?int $isEShopHide; // New field to hide from Energie Steiermark shop
public ?int $isSbidiShop; // New field for Sbidi shop visibility public ?int $isSbidiShop; // New field for Sbidi shop visibility
public ?int $isSbidiShopHide; // New field to hide from Sbidi shop public ?int $isSbidiShopHide; // New field to hide from Sbidi shop
public int $create;
public int $createBy;
} }
@@ -6,4 +6,6 @@ class WarehouseArticlePriceModel extends TTCrudBaseModel {
public int $articlePriceTypeId; public int $articlePriceTypeId;
public ?float $priceMultiplier; public ?float $priceMultiplier;
public ?float $priceOverride; public ?float $priceOverride;
public int $create;
public int $createBy;
} }
@@ -1,23 +1,11 @@
<?php <?php
class WarehouseCategory extends TTCrudBaseModel { class WarehouseCategory extends TTCrudBaseModel {
public int $id; public int $id;
public string $name; public string $name;
public string $description; public string $description;
public ?int $articleNumberPrefix;
public int $create; public int $create;
public int $create_by; public int $create_by;
public ?int $edit; public ?int $edit;
public ?int $edit_by; public ?int $edit_by;
} }
// SQL:
// CREATE TABLE `WarehouseCategory` (
// `id` INT NOT NULL AUTO_INCREMENT,
// `name` VARCHAR(255) NOT NULL,
// `description` TEXT NOT NULL,
// `create` INT NOT NULL,
// `create_by` INT NOT NULL,
// `edit` INT DEFAULT NULL,
// `edit_by` INT DEFAULT NULL,
// PRIMARY KEY (`id`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@@ -9,10 +9,9 @@ class WarehouseCategoryController extends TTCrud {
protected array $columns = [ protected array $columns = [
['key' => 'name', 'text' => 'Name', 'required' => true,], ['key' => 'name', 'text' => 'Name', 'required' => true,],
['key' => 'description', 'text' => 'Beschreibung', 'required' => true], ['key' => 'description', 'text' => 'Beschreibung', 'required' => true],
['key' => 'articleNumberPrefix', 'text' => 'Artikelnummerprefix', 'required' => true],
['key' => 'create', 'text' => 'Erstellt am', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center']], ['key' => 'create', 'text' => 'Erstellt am', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center']],
['key' => 'create_by', 'text' => 'Erstellt von', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center']], ['key' => 'create_by', 'text' => 'Erstellt von', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center']],
['key' => 'edit', 'text' => 'Bearbeitet am', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center']],
['key' => 'edit_by', 'text' => 'Bearbeitet von', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center']],
['key' => 'actions', 'text' => 'Aktionen', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center', 'priority' => 10]], ['key' => 'actions', 'text' => 'Aktionen', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center', 'priority' => 10]],
]; ];
// @formatter:on // @formatter:on
@@ -10,4 +10,6 @@ class WarehouseDistributorModel extends TTCrudBaseModel {
public string $email; public string $email;
public string $phone; public string $phone;
public string $contactPerson; public string $contactPerson;
public int $create;
public int $createBy;
} }
@@ -13,4 +13,6 @@ class WarehouseEShopOrderItemModel extends TTCrudBaseModel {
public ?int $articleId; public ?int $articleId;
public int $quantity; public int $quantity;
public ?int $articlePacketId; public ?int $articlePacketId;
public int $create;
public int $createBy;
} }
@@ -6,4 +6,6 @@ class WarehouseLocationThresholdOverrideModel extends TTCrudBaseModel {
public int $articleId; public int $articleId;
public int $warningAmount; public int $warningAmount;
public int $criticalAmount; public int $criticalAmount;
public int $create;
public int $createBy;
} }
@@ -24,4 +24,6 @@ class WarehouseOfferTemplateModel extends TTCrudBaseModel
public string $deliveryTerms; public string $deliveryTerms;
public string $closingText; public string $closingText;
public string $notes; public string $notes;
public int $create;
public int $createBy;
} }
@@ -28,11 +28,7 @@ class WarehouseShippingNoteController extends TTCrud {
['key' => 'actions', 'text' => 'Aktionen', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center']],]; ['key' => 'actions', 'text' => 'Aktionen', 'required' => false, 'modal' => false, 'table' => ['filter' => false, 'sortable' => false, 'class' => 'text-center']],];
protected array $defaultOrder = ['key' => 'create', 'order' => 'DESC']; protected array $defaultOrder = ['key' => 'create', 'order' => 'DESC'];
protected array $additionalJSVariables = ['WAREHOUSE_ADMIN' => true, 'HIDE_MENU' => false];
protected array $additionalJSVariables = ['WAREHOUSE_ADMIN' => true];
protected array $additionalJS = ['js/pages/WarehouseArticle/WarehouseArticleModal.js'];
protected array $additionalHead = ['<link rel="manifest" href="/assets/pwa/shipping-note-manifest.json">'];
protected array $infoMessages = ['create' => 'Lieferschein wurde erstellt.', protected array $infoMessages = ['create' => 'Lieferschein wurde erstellt.',
'update' => 'Lieferschein wurde aktualisiert', 'update' => 'Lieferschein wurde aktualisiert',
'delete' => 'Lieferschein wurde gelöscht', 'delete' => 'Lieferschein wurde gelöscht',
@@ -41,6 +37,7 @@ class WarehouseShippingNoteController extends TTCrud {
protected function prepareCrudConfig() { protected function prepareCrudConfig() {
if (!$this->user->can('WarehouseAdmin')) $this->additionalJSVariables['WAREHOUSE_ADMIN'] = false; if (!$this->user->can('WarehouseAdmin')) $this->additionalJSVariables['WAREHOUSE_ADMIN'] = false;
if (isset($_SESSION[MFAPPNAME . '_warehouse_login_override']) && is_numeric($_SESSION[MFAPPNAME . '_warehouse_login_override'])) $this->additionalJSVariables['HIDE_MENU'] = true;
} }
protected function beforeCreate($postData): bool { protected function beforeCreate($postData): bool {
+2 -1
View File
@@ -9,6 +9,7 @@
"phpseclib/phpseclib": "^3.0", "phpseclib/phpseclib": "^3.0",
"stomp-php/stomp-php": "^5", "stomp-php/stomp-php": "^5",
"phpmailer/phpmailer": "^6.9", "phpmailer/phpmailer": "^6.9",
"pear2/net_routeros": "dev-develop@dev" "pear2/net_routeros": "dev-develop@dev",
"matthiasmullie/minify": "^1.3"
} }
} }
@@ -0,0 +1,71 @@
<?php /** @noinspection ALL */
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class WarehouseAddAllCreateCols extends AbstractMigration
{
public function up(): void
{
if ($this->getEnvironment() == "thetool") {
$this->execute("ALTER TABLE `WarehouseArticle` ADD COLUMN `create` int(11) DEFAULT 1754312555, ADD COLUMN `createBy` int(11) DEFAULT 1;");
$this->execute("ALTER TABLE `WarehouseArticleDistributor` ADD COLUMN `create` int(11) DEFAULT 1754312555, ADD COLUMN `createBy` int(11) DEFAULT 1;");
$this->execute("ALTER TABLE `WarehouseArticlePacket` ADD COLUMN `create` int(11) DEFAULT 1754312555, ADD COLUMN `createBy` int(11) DEFAULT 1;");
$this->execute("ALTER TABLE `WarehouseArticlePrice` ADD COLUMN `create` int(11) DEFAULT 1754312555, ADD COLUMN `createBy` int(11) DEFAULT 1;");
$this->execute("ALTER TABLE `WarehouseDistributor` ADD COLUMN `create` int(11) DEFAULT 1754312555, ADD COLUMN `createBy` int(11) DEFAULT 1;");
$this->execute("ALTER TABLE `WarehouseEShopOrderItem` ADD COLUMN `create` int(11) DEFAULT 1754312555, ADD COLUMN `createBy` int(11) DEFAULT 1;");
$this->execute("ALTER TABLE `WarehouseLocationThresholdOverride` ADD COLUMN `create` int(11) DEFAULT 1754312555, ADD COLUMN `createBy` int(11) DEFAULT 1;");
$this->execute("ALTER TABLE `WarehouseOfferTemplate` ADD COLUMN `create` int(11) DEFAULT 1754312555, ADD COLUMN `createBy` int(11) DEFAULT 1;");
$this->execute("ALTER TABLE `WarehouseCategory` ADD `articleNumberPrefix` int NULL AFTER `description`;");
}
}
public function down(): void
{
if ($this->getEnvironment() == "thetool") {
$table = $this->table('WarehouseArticle');
$table->removeColumn('create')
->removeColumn('createBy')
->save();
$table = $this->table('WarehouseArticleDistributor');
$table->removeColumn('create')
->removeColumn('createBy')
->save();
$table = $this->table('WarehouseArticlePacket');
$table->removeColumn('create')
->removeColumn('createBy')
->save();
$table = $this->table('WarehouseArticlePrice');
$table->removeColumn('create')
->removeColumn('createBy')
->save();
$table = $this->table('WarehouseDistributor');
$table->removeColumn('create')
->removeColumn('createBy')
->save();
$table = $this->table('WarehouseEShopOrderItem');
$table->removeColumn('create')
->removeColumn('createBy')
->save();
$table = $this->table('WarehouseLocationThresholdOverride');
$table->removeColumn('create')
->removeColumn('createBy')
->save();
$table = $this->table('WarehouseOfferTemplate');
$table->removeColumn('create')
->removeColumn('createBy')
->save();
$table = $this->table('WarehouseCategory');
$table->removeColumn('articleNumberPrefix')
->save();
}
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class TimerecordingEmployeeAddInsuranceNumber extends AbstractMigration
{
public function up(): void
{
if ($this->getEnvironment() == "thetool") {
$table = $this->table("TimerecordingEmployee", ["signed" => true]);
$table->addColumn("insurance_number", "string", ["null" => true, "after" => "birthday"]);
$table->update();
}
if ($this->getEnvironment() == "addressdb") {
}
}
public function down(): void
{
if ($this->getEnvironment() == "thetool") {
$this->table("TimerecordingEmployee")->removeColumn("only_admin")->save();
}
if ($this->getEnvironment() == "addressdb") {
}
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class WorkerAddPasswordReset extends AbstractMigration
{
public function up(): void
{
if($this->getEnvironment() == "thetool") {
$table = $this->table("Worker");
$table->addColumn("password_reset_token", "string", ["null" => true, "after" => "twofactorrequired"]);
$table->addColumn("password_reset_expires", "integer", ["null" => true, "default" => null, "after" => "password_reset_token"]);
$table->update();
}
if($this->getEnvironment() == "addressdb") {
}
}
public function down(): void
{
if($this->getEnvironment() == "thetool") {
$this->table("Worker")->removeColumn("password_reset_token")->save();
$this->table("Worker")->removeColumn("password_reset_expires")->save();
}
if($this->getEnvironment() == "addressdb") {
}
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AlterWorkorderAndCreateJournal extends AbstractMigration
{
public function up(): void
{
if ($this->getEnvironment() == "thetool") {
$workorder = $this->table('RMLWorkorder');
$workorder->addColumn('clusterId', 'integer', ['null' => true, 'after' => 'companyId'])
->addIndex(['clusterId'], ['name' => 'clusterId_idx'])
->save();
if (!$this->hasTable('RMLWorkorderJournal')) {
$journal = $this->table('RMLWorkorderJournal', ['id' => false, 'primary_key' => ['id']]);
$journal->addColumn('id', 'integer', ['identity' => true, 'signed' => true])
->addColumn('workorderId', 'integer', ['null' => false])
->addColumn('text', 'text', ['null' => true])
->addColumn('fileIds', 'json', ['null' => true])
->addColumn('statusChange', 'string', ['limit' => 255, 'null' => true])
->addColumn('create', 'integer', ['null' => false])
->addColumn('createBy', 'integer', ['null' => false])
->addIndex(['workorderId'], ['name' => 'workorderId_idx'])
->create();
}
}
}
public function down(): void
{
if ($this->getEnvironment() == "thetool") {
if ($this->hasTable('RMLWorkorderJournal')) {
$this->table('RMLWorkorderJournal')->drop()->save();
}
$workorder = $this->table('RMLWorkorder');
if ($workorder->hasColumn('clusterId')) {
$workorder->removeColumn('clusterId')->save();
}
}
}
}
+55 -17
View File
@@ -11,49 +11,75 @@ class Helper {
public static function generateFilterCondition($filterValue, $columnName, bool $exactMatch = false): string { public static function generateFilterCondition($filterValue, $columnName, bool $exactMatch = false): string {
$sql = ""; $sql = "";
$quotedColumn = (strpos($columnName, '.') === false && strpos($columnName, '|') === false)
? "`$columnName`"
: $columnName;
if (is_array($filterValue)) { if (is_array($filterValue)) {
if (isset($filterValue['from']) && isset($filterValue['to'])) { if (isset($filterValue['from']) && isset($filterValue['to'])) {
$sql = " AND `$columnName` >= " . $filterValue['from'] . " AND `$columnName` <= " . $filterValue['to']; $sql = " AND $quotedColumn >= " . $filterValue['from'] . " AND $quotedColumn <= " . $filterValue['to'];
} elseif (isset($filterValue['from'])) { } elseif (isset($filterValue['from'])) {
$sql = " AND `$columnName` >= " . $filterValue['from']; $sql = " AND $quotedColumn >= " . $filterValue['from'];
} elseif (isset($filterValue['to'])) { } elseif (isset($filterValue['to'])) {
$sql = " AND `$columnName` <= " . $filterValue['to']; $sql = " AND $quotedColumn <= " . $filterValue['to'];
} else if (isset($filterValue['exact'])) { } else if (isset($filterValue['exact'])) {
$sql = " AND `$columnName` = " . "'{$filterValue['exact']}'"; $sql = " AND $quotedColumn = " . "'{$filterValue['exact']}'";
} else if (!empty($filterValue)) { } else if (!empty($filterValue)) {
$sql = " AND `$columnName` IN ('" . implode("','", $filterValue) . "')"; $sql = " AND $quotedColumn IN ('" . implode("','", $filterValue) . "')";
} }
} else if ($filterValue === "0" || $filterValue === "1") { } else if ($filterValue === "0" || $filterValue === "1") {
$sql .= " AND `$columnName` = " . $filterValue; $sql .= " AND $quotedColumn = " . $filterValue;
} else if ($filterValue === null) { } else if ($filterValue === null) {
$sql .= " AND `$columnName` IS NULL"; $sql .= " AND $quotedColumn IS NULL";
} else if ($filterValue === '!NULL') { } else if ($filterValue === '!NULL') {
$sql .= " AND `$columnName` IS NOT NULL"; $sql .= " AND $quotedColumn IS NOT NULL";
} else if (!empty($filterValue)) { } else if (!empty($filterValue)) {
if ($exactMatch) { if ($exactMatch) {
$sql .= " AND `$columnName` = '" . $filterValue . "'"; $sql .= " AND $quotedColumn = '" . $filterValue . "'";
} else if (strpos($columnName, "|") !== false) { } else if (strpos($columnName, "|") !== false) {
foreach (explode(" ", $filterValue) as $item) $columns = explode("|", $columnName);
$sql .= " AND CONCAT(" . join(",", explode("|", $columnName)) . ") LIKE '%" . $item . "%'";
// Loop through each search term (e.g., "john", "doe")
foreach (explode(" ", $filterValue) as $item) {
// Skip if the item is empty
if (empty(trim($item))) {
continue;
}
$escapedItem = addslashes($item); // Basic escaping
// Build the list of OR conditions for the current item
$orConditions = [];
foreach ($columns as $column) {
// e.g., "first_name LIKE '%john%'"
$orConditions[] = "$column LIKE '%" . $escapedItem . "%'";
}
// Combine the OR conditions into a single block and add to the query
// e.g., "AND (first_name LIKE '%john%' OR last_name LIKE '%john%')"
if (!empty($orConditions)) {
$sql .= " AND (" . implode(" OR ", $orConditions) . ")";
}
}
} else if ($filterValue[0] === "%") { } else if ($filterValue[0] === "%") {
$sql .= " AND `$columnName` LIKE '" . $filterValue . "'"; $sql .= " AND $quotedColumn LIKE '" . addslashes($filterValue) . "'";
} else if ($filterValue[strlen($filterValue) - 1] === "%") { } else if ($filterValue[strlen($filterValue) - 1] === "%") {
$sql .= " AND `$columnName` LIKE '" . $filterValue . "'"; $sql .= " AND $quotedColumn LIKE '" . addslashes($filterValue) . "'";
} else if ($filterValue[0] === "!") { } else if ($filterValue[0] === "!") {
$sql .= " AND `$columnName` NOT LIKE '%" . substr($filterValue, 1) . "%'"; $sql .= " AND $quotedColumn NOT LIKE '%" . addslashes(substr($filterValue, 1)) . "%'";
} else { } else {
$filterItems = explode(" ", $filterValue); $filterItems = explode(" ", $filterValue);
foreach ($filterItems as $item) { foreach ($filterItems as $item) {
$sql .= " AND `$columnName` LIKE '%" . $item . "%'"; $escapedItem = addslashes($item); // Basic escaping
$sql .= " AND $quotedColumn LIKE '%" . $escapedItem . "%'";
} }
} }
} else if ($filterValue === 0) { } else if ($filterValue === 0) {
$sql .= " AND `$columnName` = 0"; $sql .= " AND $quotedColumn = 0";
} }
return $sql; return $sql;
} }
/** /**
* Validates an array of data based on a set of predefined rules. * Validates an array of data based on a set of predefined rules.
* *
@@ -175,4 +201,16 @@ class Helper {
return number_format($number, $decimals, $decPoint, $thousandsSep); return number_format($number, $decimals, $decPoint, $thousandsSep);
} }
public static function getPreorderCampaignFromUser($user, bool $returnObject = false): array {
if ($user->isAdmin()) $campaigns = PreordercampaignModel::getAll();
else {
$networkIDs = array_unique(array_merge(
array_column($user->myNetworks(["netowner", "salespartner"]), 'id'),
json_decode($user->getFlag("preorder_networks")->value() ?: '[]')
));
$campaigns = PreordercampaignModel::search(['network_id' => $networkIDs]);
}
return $returnObject ? $campaigns : array_column($campaigns, 'id');
}
} }
+48 -9
View File
@@ -27,17 +27,23 @@ class TTCrud extends mfBaseController {
} }
protected function init() { protected function init() {
$this->needlogin = true; $className = get_class($this);
$me = new User();
$me->loadMe();
$this->user = $me;
$this->layout()->set('me', $me);
if (isset($this->permissionCheck) && !$me->can($this->permissionCheck)) { if (defined('TT_WAREHOUSE_LOGIN_OVERRIDE') && is_array(TT_WAREHOUSE_LOGIN_OVERRIDE)
$this->redirect("Dashboard"); && in_array($className, TT_WAREHOUSE_LOGIN_OVERRIDE) && !mfLoginController::isLoggedIn())
} else if (!$me->can($this->permissionCheck) && !$me->is(["Admin"])) { $this->user = $this->loginOverride();
$this->redirect("Dashboard"); else {
$this->needlogin = true;
$this->user = new User();
$this->user->loadMe();
} }
$this->layout()->set('me', $this->user);
if (method_exists($this, 'permissionsCheckOverride'))
$this->permissionsCheckOverride();
else if (!$this->user->is(["Admin"]))
$this->redirect("Dashboard");
$c = get_class($this); $c = get_class($this);
foreach ([str_replace('Controller', 'Model', $c), str_replace('Controller', '', $c)] as $m) foreach ([str_replace('Controller', 'Model', $c), str_replace('Controller', '', $c)] as $m)
@@ -52,6 +58,37 @@ class TTCrud extends mfBaseController {
if (method_exists($this, 'afterInit')) $this->afterInit(); if (method_exists($this, 'afterInit')) $this->afterInit();
} }
protected function loginOverride() {
$allowedIPs = ['193.105.204.200', '91.227.230.253', '91.227.230.251', '193.105.204.195', '172.18.0.1', '46.151.204.50'];
if (!in_array($_SERVER['REMOTE_ADDR'], $allowedIPs)) $this->redirect('Dashboard');
if (isset($_POST['wantedUserId']) && is_numeric($_POST['wantedUserId'])) {
$user = new User($_POST['wantedUserId']);
if ($user->id && $user->address_id == 1) {
$_SESSION[MFAPPNAME . '_warehouse_login_override'] = $user->id;
$_SESSION[MFAPPNAME . '_warehouse_login_override_timestamp'] = time();
$this->redirect('WarehouseShippingNote');
}
$this->redirect('Dashboard');
}
$sessionUserId = $_SESSION[MFAPPNAME . '_warehouse_login_override'] ?? null;
$sessionTimestamp = $_SESSION[MFAPPNAME . '_warehouse_login_override_timestamp'] ?? 0;
if (is_numeric($sessionUserId) && (time() - $sessionTimestamp <= 300)) {
$user = new User($sessionUserId);
if ($user->id && $user->address_id == 1) return $user;
$this->redirect('WarehouseShippingNote');
}
$users = UserModel::search(['employee' => true, 'active' => true]);
$userOptions = array_map(fn($user) => ['value' => (int)$user->id, 'text' => $user->name], $users);
$this->layout()->set('userOptions', $userOptions);
$this->layout()->setTemplate("VueViews/WarehouseLoginOverride");
echo $this->layout()->render();
exit;
}
/** /**
* Returns the checkArray for the CRUD component. * Returns the checkArray for the CRUD component.
* @return array * @return array
@@ -82,6 +119,7 @@ class TTCrud extends mfBaseController {
"CREATE_URL" => $this::getUrl("{$this->mod}/create"), "CREATE_URL" => $this::getUrl("{$this->mod}/create"),
"TABLE_URL" => $this::getUrl("{$this->mod}/get"), "TABLE_URL" => $this::getUrl("{$this->mod}/get"),
"UPDATE_URL" => $this::getUrl("{$this->mod}/update"), "UPDATE_URL" => $this::getUrl("{$this->mod}/update"),
"GET_BY_ID_URL" => $this::getUrl("{$this->mod}/getById"),
"DELETE_URL" => $this::getUrl("{$this->mod}/delete"), "DELETE_URL" => $this::getUrl("{$this->mod}/delete"),
"USER_ID" => $this->user->id "USER_ID" => $this->user->id
]; ];
@@ -137,6 +175,7 @@ class TTCrud extends mfBaseController {
return ['key' => $this->mod, return ['key' => $this->mod,
'tableHeader' => $this->headerTitle, 'tableHeader' => $this->headerTitle,
'reopenOnCreate' => $this->reopenOnCreate ?? false,
'createText' => $this->createText, 'createText' => $this->createText,
'columns' => $columns, 'columns' => $columns,
'additionalActions' => $this->additionalActions]; 'additionalActions' => $this->additionalActions];
+1 -1
View File
@@ -128,7 +128,7 @@ class mfLoginController extends mfBaseController
UserToken::checkToken(); UserToken::checkToken();
if ($_SESSION[MFAPPNAME . '_username'] && $_SESSION[MFAPPNAME . '_ip']) { if (isset($_SESSION[MFAPPNAME . '_username']) && $_SESSION[MFAPPNAME . '_username'] && $_SESSION[MFAPPNAME . '_ip']) {
$username = $_SESSION[MFAPPNAME . '_username']; $username = $_SESSION[MFAPPNAME . '_username'];
$ip = $_SERVER['REMOTE_ADDR']; $ip = $_SERVER['REMOTE_ADDR'];
$sid = session_id(); $sid = session_id();
+27 -24
View File
@@ -128,37 +128,40 @@ h1, h2, h3, h4, h5, h6 {
.card.border-top-purple { .card.border-top-purple {
border-top: 2px solid #6b5eae; border-top: 2px solid #6b5eae;
} }
/*
.card-header.underline-danger {
border-bottom: 2px solid #f1556c;
}*/
#vodia-identities-list > .list-group-item:hover {
background-color: #dee2e6; /* * Vodia Identity Container * */
#vodia-identity-container .dropdown-menu {
transition: opacity 0.15s linear, visibility 0.15s linear;
display: block; opacity: 0; visibility: hidden;
}
#vodia-identity-container.show .dropdown-menu { opacity: 1; visibility: visible; }
#vodia-identity-container .pointer { cursor: pointer; }
.opacity-75 { opacity: 0.75 !important; }
.vodia-list-item-icon {
font-size: 1.3em;
vertical-align: middle;
} }
#vodia-identities-list li.list-group-item .color-block { #vodia-identity-container * {
width: 50px; line-height: normal;
height: 16px; vertical-align: middle;
color: #fff;
vertical-align: top;
text-align: center;
border: 1px solid #fff;
} }
#vodia-identities-list .list-group-item td.color-block-blue { #vodia-identity-container > a {
background-color: #4b88e4; line-height: 70px;
max-height: 70px;
height: 70px;
} }
#vodia-identities-list .list-group-item td.color-block-green { .vodia-identity-color-blue { color: #4b88e4; }
background-color: #25b343; .vodia-identity-color-green { color: #25b343; }
} .vodia-identity-color-pink { color: #f672a7; }
#vodia-identities-list .list-group-item td.color-block-pink { .vodia-identity-color-black { color: #000; }
background-color: #f672a7; .vodia-identity-color-grey { color: #6c757d; }
} /* * Vodia Identity Container * */
#vodia-identities-list .list-group-item td.color-block-black {
background-color: #000;
}
#topnav { #topnav {
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

+232 -126
View File
@@ -1,162 +1,268 @@
/* Vodia Outbound Identity */ document.body.insertAdjacentHTML('beforeend', `
<template id="vodia-identity-template">
<li id="vodia-identity-container" class="dropdown notification-list ml-2 my-auto" style="display: none;">
<a href="#" class="nav-link nav-user dropdown-toggle d-flex align-items-center" aria-haspopup="true" aria-expanded="false" data-ref="toggleButton">
<i class="phone-icon fas fa-phone" data-ref="phoneIcon"></i>
<div class="pro-user-name ml-2">
<div style="line-height: 1.2;">
<span>Ausgehende Identität: </span>
<span class="font-weight-bold" data-ref="currentName"></span>
<i class="far fa-chevron-down ml-2"></i>
</div>
<div class="small opacity-75" data-ref="currentNumber"></div>
</div>
</a>
<div class="dropdown-menu dropdown-menu-right shadow-lg" style="min-width: 320px;" data-ref="dropdownMenu">
<div class="dropdown-item noti-title"><h6 class="m-0" data-ref="dropdownTitle"></h6></div>
<ul class="list-group list-group-flush" data-ref="identityList"></ul>
</div>
</li>
</template>
<template id="vodia-list-item-template">
<li class="list-group-item list-group-item-action d-flex align-items-center">
<i class="vodia-list-item-icon fas fa-circle mr-3" data-ref="colorBlock"></i>
<div>
<span class="name font-weight-bold d-block" data-ref="name"></span>
<span class="number small text-muted" data-ref="numberDisplay"></span>
</div>
</li>
</template>
`);
var vodia_identity_switcher_timer; class VodiaIdentitySwitcher {
var vodia_identity = null; API_BASE_URL = window.baseurl || '/';
POLLING_INTERVAL_MS = 30000;
CACHE_DURATION_MS = 30000;
CACHE_KEY = 'vodiaIdentityCache'; // Key for localStorage
getVodiaIdentity(); TEXT = {
checking: "Prüfe...",
setting: "Ändere...",
dropdownTitle: "Ausgehende Identität wählen:",
ownExtension: "Eigene Nummer",
customIdentity: "Andere Nummer"
};
async function getVodiaIdentity() { pollingTimer = null;
clearTimeout(vodia_identity_switcher_timer); elements = {};
templates = {};
if(!$("#vodia-identity-switcher .phone-icon").hasClass("fa-spin")) { constructor(parentElement) {
$("#vodia-identity-switcher .phone-icon").addClass("fa-spin text-warning"); if (!parentElement) return;
this.templates.main = document.getElementById('vodia-identity-template');
this.templates.listItem = document.getElementById('vodia-list-item-template');
if (!this.templates.main || !this.templates.listItem) {
return console.error("Vodia Switcher Error: Required HTML <template> tags not found.");
} }
var response = await fetch(baseurl + 'User/Api/do=getVodiaIdentity'); this._createSwitcherUI(parentElement);
if (!response.ok) { this._addEventListeners();
$("#vodia-identity-switcher a.phone-icon i").removeClass("fa-spin"); this.getVodiaIdentity();
return false;
}
var resp_json = await response.json();
if(resp_json.status != "OK") {
console.error("Error getting Vodia Identity: " + resp_json.message);
$("#vodia-identity-switcher a.phone-icon i").removeClass("fa-spin");
return false;
}
vodia_identity = resp_json.result;
if(!("enabled" in vodia_identity) || !vodia_identity.enabled) {
$("#vodia-identity-switcher a.phone-icon i").removeClass("fa-spin");
return true;
} }
var default_ident = vodia_identity.default; _getCache() {
var default_ident_number = vodia_identity.default_number.replaceAll(' ', ""); const cachedString = localStorage.getItem(this.CACHE_KEY);
if (!cachedString) return null;
var current_ident = vodia_identity.current; try {
var current_ident_number = current_ident.replaceAll(' ', ""); return JSON.parse(cachedString);
} catch (e) {
var identities = vodia_identity.identities; console.error("Vodia Cache Error: Could not parse cached data.", e);
// Clean up corrupted data
$("#vodia-identity-container").show(); localStorage.removeItem(this.CACHE_KEY);
return null;
if(default_ident_number == current_ident_number) {
$("#vodia-identity-current-text").text("Xinon Eigene Durchwahl");
$("#vodia-identity-current-number").text("(" + default_ident + ")");
$("#vodia-identity-switcher").attr("title", "Xinon Eigene Durchwahl (" + default_ident + ")");
} else {
ident_found = false;
for(const [ident_name, ident] of Object.entries(identities)) {
if(ident.number == current_ident_number) {
ident_found = true;
$("#vodia-identity-current-text").text(ident_name);
$("#vodia-identity-current-number").text("(" + ident.display + ")");
$("#vodia-identity-switcher").attr("title", ident_name + " (" + ident.display + ")");
}
}
if(!ident_found) {
$("#vodia-identity-current-number").text(vodia_identity.current);
$("#vodia-identity-switcher").attr("title", vodia_identity.current);
} }
} }
_setCache(vodiaState) {
const itemToCache = { data: vodiaState, timestamp: Date.now() };
try {
localStorage.setItem(this.CACHE_KEY, JSON.stringify(itemToCache));
} catch (e) {
console.error("Vodia Cache Error: Could not write to localStorage.", e);
}
}
$("#vodia-identities-list").empty(); _createSwitcherUI(parentElement) {
const fragment = this.templates.main.content.cloneNode(true);
const container = fragment.querySelector('#vodia-identity-container');
let item = addVodiaIdentityListItem( this.elements = {
default_ident_number, container,
default_ident_number, toggleButton: container.querySelector('[data-ref="toggleButton"]'),
"Xinon Eigene Durchwahl", phoneIcon: container.querySelector('[data-ref="phoneIcon"]'),
"blue" currentName: container.querySelector('[data-ref="currentName"]'),
); currentNumber: container.querySelector('[data-ref="currentNumber"]'),
dropdownMenu: container.querySelector('[data-ref="dropdownMenu"]'),
identityList: container.querySelector('[data-ref="identityList"]'),
};
console.log(default_ident_number, current_ident_number); this.elements.dropdownMenu.querySelector('[data-ref="dropdownTitle"]').textContent = this.TEXT.dropdownTitle;
if(default_ident_number == current_ident_number) { parentElement.prepend(fragment);
$(item).addClass("bg-info text-white"); }
$(item).find(".text-block").addClass("text-white");
$(item).removeClass("pointer"); _addEventListeners() {
} else { this.elements.toggleButton.addEventListener('click', e => {
$(item).click(function () { e.preventDefault();
setVodiaOutboundIdentity(default_ident_number) const isShown = this.elements.container.classList.toggle('show');
this.elements.toggleButton.setAttribute('aria-expanded', isShown);
});
document.addEventListener('click', e => {
if (!this.elements.container.contains(e.target)) {
this.elements.container.classList.remove('show');
this.elements.toggleButton.setAttribute('aria-expanded', 'false');
}
}); });
} }
_setLoadingState(isLoading, message = '') {
const { phoneIcon, currentName, currentNumber } = this.elements;
phoneIcon.className = 'phone-icon fas fa-phone'; // Reset
for(const [ident_name, ident] of Object.entries(identities)) { if (isLoading) {
phoneIcon.classList.add('fa-spin', 'text-warning');
let item = addVodiaIdentityListItem( currentName.textContent = message;
ident.number, currentNumber.textContent = '';
ident.display,
ident_name,
ident.color
);
if(ident.number == current_ident_number) {
$(item).addClass("bg-info text-white");
$(item).find(".text-block").addClass("text-white");
$(item).removeClass("pointer");
} else { } else {
$(item).click(function () { phoneIcon.classList.add('text-success');
setVodiaOutboundIdentity(ident.number)
});
} }
} }
$("#vodia-identity-switcher .phone-icon").removeClass("text-warning fa-spin"); async getVodiaIdentity() {
$("#vodia-identity-switcher .phone-icon").addClass("fa-bounce"); clearTimeout(this.pollingTimer);
setTimeout(() => { $("#vodia-identity-switcher .phone-icon").removeClass("fa-bounce"); }, 800);
vodia_identity_switcher_timer = setTimeout(() => {getVodiaIdentity()}, 30000); // try {
const cachedItem = this._getCache();
let vodiaState;
} if (cachedItem && (Date.now() - cachedItem.timestamp < this.CACHE_DURATION_MS)) {
vodiaState = cachedItem.data;
} else {
this._setLoadingState(true, this.TEXT.checking);
const response = await fetch(`${this.API_BASE_URL}User/Api/do=getVodiaIdentity`);
if (!response.ok) throw new Error('Network response was not ok');
function addVodiaIdentityListItem(number, number_display, name, color) { const data = await response.json();
//let tpl = $("#vodia-identity-list-item-template")[0].innerHTML; if (data.status !== "OK") throw new Error(data.message || 'API returned an error');
//item = $($.parseXML(tpl)).contents();
vodiaState = data.result;
this._setCache(vodiaState);
}
const tpl = document.querySelector("#vodia-identity-list-item-template").content.cloneNode(true); if (vodiaState?.enabled) {
const item = tpl.querySelector('li'); this.elements.container.style.display = 'list-item';
this._updateUI(vodiaState);
this._setLoadingState(false);
} else {
this.elements.container.style.display = 'none';
}
} catch (error) {
console.error("Vodia Fetch Error:", error.message);
this.elements.phoneIcon.className = 'phone-icon fas fa-phone text-danger';
this.elements.currentName.textContent = 'Fehler';
} finally {
this.pollingTimer = setTimeout(() => this.getVodiaIdentity(), this.POLLING_INTERVAL_MS);
}
}
//console.log(item); async setVodiaOutboundIdentity(number) {
this._setLoadingState(true, this.TEXT.setting);
this.elements.container.classList.remove('show');
this.elements.toggleButton.setAttribute('aria-expanded', 'false');
$(item).data("number", number); try {
const response = await fetch(`${this.API_BASE_URL}User/Api/do=setVodiaIdentity`, {
$(item).find("td.color-block").addClass("color-block-" + color);
$(item).find("span.name").text(name);
$(item).find("span.number").text("(" + number_display + ")");
$("#vodia-identities-list").append(item);
return item;
}
async function setVodiaOutboundIdentity(number) {
$("#vodia-identity-switcher .phone-icon").addClass("fa-spin text-warning");
$("#vodia-identities-list").empty();
$("#vodia-identities-list").append("<img src='" + baseurl + "img/ajax-loader.gif' />");
$("#vodia-identity-current-text").text("Identität wird gesetzt...");
$("#vodia-identity-current-number").text("");
$("#vodia-identity-switcher").attr("title", "Identität wird gesetzt...");
var response = await fetch(baseurl + 'User/Api/do=setVodiaIdentity',{
method: 'POST', method: 'POST',
body: new URLSearchParams({ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
'number': number body: new URLSearchParams({ 'number': number })
})
}); });
if (!response.ok) {
return false; if (!response.ok) throw new Error("Network response was not ok.");
const data = await response.json();
if (data.status !== "OK") throw new Error(data.message || 'API returned an error.');
localStorage.removeItem(this.CACHE_KEY)
} catch (error) {
console.error("Vodia Set Error:", error.message);
if (window.notify) window.notify.error("Fehler beim Ändern der ID!");
} finally {
await this.getVodiaIdentity();
} }
var resp_json = await response.json();
if(resp_json.status != "OK") {
console.error("Error setting Vodia Identity: " + resp_json.message);
notify.error("Fehler beim Setzen der Identität!");
} }
getVodiaIdentity(); _updateUI(vodiaState) {
const { 'default': defaultDisplay, default_number, current, identities } = vodiaState;
const currentId = current.replaceAll(' ', "");
return true; let activeName = this.TEXT.customIdentity;
let activeNumberDisplay = `(${current})`;
if (currentId === default_number.replaceAll(' ', "")) {
activeName = this.TEXT.ownExtension;
activeNumberDisplay = `(${defaultDisplay})`;
} else if (identities) {
const found = Object.entries(identities).find(([, ident]) => ident.number === currentId);
if (found) {
[activeName, activeNumberDisplay] = [found[0], `(${found[1].display})`];
}
}
this.elements.currentName.textContent = activeName;
this.elements.currentNumber.textContent = activeNumberDisplay;
this.elements.toggleButton.title = `Aktive ID: ${activeName} ${activeNumberDisplay}`;
this._renderIdentityList(vodiaState);
}
_renderIdentityList(vodiaState) {
this.elements.identityList.innerHTML = '';
const { 'default': defaultDisplay, default_number, current, identities } = vodiaState;
const currentId = current.replaceAll(' ', "");
// Add "Own Extension"
this.elements.identityList.appendChild(this._createListItem({
name: this.TEXT.ownExtension,
number: default_number.replaceAll(' ', ""),
display: defaultDisplay,
color: 'blue',
isActive: currentId === default_number.replaceAll(' ', "")
}));
// Add other identities
if (!identities) return;
for (const name in identities) {
const ident = identities[name];
this.elements.identityList.appendChild(this._createListItem({
name,
number: ident.number,
display: ident.display,
color: ident.color,
isActive: currentId === ident.number
}));
}
}
_createListItem({ name, number, display, color, isActive }) {
const fragment = this.templates.listItem.content.cloneNode(true);
const item = fragment.querySelector('li');
item.querySelector('[data-ref="colorBlock"]').classList.add(`vodia-identity-color-${color || 'grey'}`);
item.querySelector('[data-ref="name"]').textContent = name;
item.querySelector('[data-ref="numberDisplay"]').textContent = display;
if (isActive) {
item.classList.add('active');
item.querySelector('[data-ref="numberDisplay"]').classList.remove('text-muted');
} else {
item.classList.add('pointer');
item.addEventListener('click', () => this.setVodiaOutboundIdentity(number));
}
return item;
}
} }
document.addEventListener('DOMContentLoaded', () => {
const topbar = document.querySelector("#topbar");
if (topbar) new VodiaIdentitySwitcher(topbar);
});
@@ -0,0 +1,22 @@
{
"name": "Lieferscheine",
"short_name": "Lieferscheine",
"description": "XINON Lieferscheine App",
"start_url": "https://thetool.xinon.at/WarehouseShippingNote",
"display": "standalone",
"background_color": "#f1f5f9",
"theme_color": "#0055FF",
"orientation": "landscape-primary",
"icons": [
{
"src": "/assets/images/xinon-sm-192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/assets/images/xinon-sm-512.png",
"type": "image/png",
"sizes": "512x512"
}
]
}
@@ -0,0 +1,26 @@
const CACHE_NAME = 'lager-system-cache-v3';
const urlsToCache = [
'https://cdn.jsdelivr.net/npm/vue@3.4.27/dist/vue.global.min.js',
'https://cdn.tailwindcss.com',
'/assets/images/xinon-full.png',
'/assets/icons/icon-192x192.png',
'/assets/icons/icon-512x512.png'
];
self.addEventListener('install', event => {
event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(urlsToCache)));
});
self.addEventListener('fetch', event => {
event.respondWith(caches.match(event.request).then(response => response || fetch(event.request)));
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => Promise.all(
cacheNames
.filter(cacheName => cacheName !== CACHE_NAME)
.map(cacheName => caches.delete(cacheName))
))
);
});
-1
View File
@@ -29,7 +29,6 @@ $jsFiles = [
"plugins/axios/axios.min.js", "plugins/axios/axios.min.js",
"plugins/axios/axios.inject.js", "plugins/axios/axios.inject.js",
"plugins/moment/moment.min.js", "plugins/moment/moment.min.js",
"plugins/daterangepicker/daterangepicker.js",
"plugins/vue/" . (isset($_GET['VUE_DEBUG']) || $_SERVER['HTTP_HOST'] === "localhost" ? "vue.js" : "vue.min.js"), "plugins/vue/" . (isset($_GET['VUE_DEBUG']) || $_SERVER['HTTP_HOST'] === "localhost" ? "vue.js" : "vue.min.js"),
"plugins/vue/tt-components/tt-button.js", "plugins/vue/tt-components/tt-button.js",
"plugins/vue/tt-components/tt-card.js", "plugins/vue/tt-components/tt-card.js",
+54
View File
@@ -0,0 +1,54 @@
<?php
require '../vendor/autoload.php';
// Set the content type to CSS
header('Content-Type: text/css');
header('Cache-Control: max-age=31536000, public'); // Cache for 1 year
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT'); // Expires in 1 year
/**
* Combines and minifies an array of CSS files.
*
* @param array $files An array of CSS file paths.
* @return string The combined and minified CSS content.
*/
function combineAndMinifyCSS($files) {
// Create a new Minify\CSS instance
$minifier = new \MatthiasMullie\Minify\CSS();
foreach ($files as $file) {
if (file_exists($file)) {
// Add the file's content to the minifier
$minifier->add($file);
} else {
// Handle missing files gracefully
header("HTTP/1.1 404 Not Found");
echo "/* File not found: $file */";
exit;
}
}
// Return the minified content
return $minifier->minify();
}
// Define the array of CSS files to be combined and minified
$cssFiles = [
'plugins/daterangepicker/daterangepicker.css',
'assets/css/bootstrap.min.css',
'assets/css/app.min.css',
'plugins/notification/notify.min.css',
'assets/css/thetool.css',
'plugins/vue/tt-components/css/tt-table.css',
'plugins/vue/tt-components/css/tt-tooltip.css',
'plugins/vue/tt-components/css/tt-loader.css',
'plugins/vue/tt-components/css/tt-select.css',
'plugins/vue/tt-components/css/tt-file-gallery.css',
'plugins/vue/tt-components/css/tt-position-manager.css',
];
// Output the combined and minified CSS
echo combineAndMinifyCSS($cssFiles);
?>
+4 -4
View File
@@ -81,10 +81,10 @@ Vue.component('csv-import-modal', {
this.errorMessage = 'Bitte wählen Sie zuerst eine Datei aus.'; this.errorMessage = 'Bitte wählen Sie zuerst eine Datei aus.';
return; return;
} }
if (this.showNetworkAreas && !this.selectedNetworkArea) { // if (this.showNetworkAreas && !this.selectedNetworkArea) {
this.errorMessage = 'Bitte wählen Sie einen Netzbereich aus.'; // this.errorMessage = 'Bitte wählen Sie einen Netzbereich aus.';
return; // return;
} // }
this.errorMessage = null; this.errorMessage = null;
this.loading = true; this.loading = true;
@@ -94,7 +94,7 @@ Vue.component('Cpeprovisioning', {
<tt-input label="WLAN SSID" v-model="row.cpe_data.wifi_ssid" @input="markDirty(row, 3)" sm/> <tt-input label="WLAN SSID" v-model="row.cpe_data.wifi_ssid" @input="markDirty(row, 3)" sm/>
<tt-input label="WPA Key" v-model="row.cpe_data.wifi_pass" @input="markDirty(row, 4)" sm/> <tt-input label="WPA Key" v-model="row.cpe_data.wifi_pass" @input="markDirty(row, 4)" sm/>
<tt-input label="Router MAC" v-model="row.cpe_data.mac" @input="markDirty(row, 5)" sm/> <tt-input label="Router MAC" v-model="row.cpe_data.mac" @input="markDirty(row, 5)" sm/>
<tt-input v-if="row.termination_id" label="ONT SN" v-model="row.ont_sn" @input="markDirty(row, 6)" sm/> <tt-input v-if="row.termination_id && row.ont_deployed !== 0" label="ONT SN" v-model="row.ont_sn" @input="markDirty(row, 6)" sm/>
<h5 class="section-title">Versand</h5> <h5 class="section-title">Versand</h5>
<tt-checkbox label="Versandauftrag" v-model="row.cpe_data.shipping" @input="markDirty(row, 7);checkShipping(row)" sm/> <tt-checkbox label="Versandauftrag" v-model="row.cpe_data.shipping" @input="markDirty(row, 7);checkShipping(row)" sm/>
@@ -0,0 +1,27 @@
/*
* CSS for Workorder Table Row Highlighting (Balanced Colors)
*/
/* 🔴 Urgent: Deadline passed or less than 1 week away */
.table-hover .tt-rml-workorder-urgent:hover,
.tt-rml-workorder-urgent {
background-color: #f8d7da !important; /* Balanced Red */
}
/* 🟡 Medium: Deadline less than 3 weeks away */
.table-hover .tt-rml-workorder-medium:hover,
.tt-rml-workorder-medium {
background-color: #fff3cd !important; /* Balanced Yellow */
}
/* 🟢 On Track: Deadline more than 3 weeks away */
.table-hover .tt-rml-workorder-ontrack:hover,
.tt-rml-workorder-ontrack {
background-color: #d4edda !important; /* Balanced Green */
}
/* ⚫ Irrelevant: No deadline or status makes it not applicable */
.table-hover .tt-rml-workorder-irrelevant:hover,
.tt-rml-workorder-irrelevant {
background-color: #e9ecef !important; /* Balanced Grey */
}
@@ -2,22 +2,23 @@
Vue.component('r-m-l-workorder-admin', { Vue.component('r-m-l-workorder-admin', {
template: ` template: `
<tt-card> <tt-card>
<assign-company-modal <div class="mb-2 d-flex align-items-center" v-if="workordersToAssign.length > 0">
v-if="assignModalWorkorderId" <span class="mr-3 font-weight-bold">{{ workordersToAssign.length }} Workorder(s) zuweisen:</span>
:workorder-id="assignModalWorkorderId" <div style="width: 300px;">
@close="assignModalWorkorderId = null; $refs.table.$refs.table.refreshTable()" <tt-select
/> class="mb-0"
:options="companies"
<documentation-viewer-modal v-model="massAssignCompanyId"
v-if="docsModalWorkorderId" @input="massAssignCompanies"
:workorder-id="docsModalWorkorderId" placeholder="Firma auswählen..."
@close="docsModalWorkorderId = null" sm
no-form-group
/> />
</div>
</div>
<tt-table-crud <tt-table-crud
ref="table" ref="table"
@assign="assignModalWorkorderId = $event.id"
@view_docs="docsModalWorkorderId = $event.id"
:crud-config="crudConfig" :crud-config="crudConfig"
> >
<template v-slot:preorderinfo="{ row }"> <template v-slot:preorderinfo="{ row }">
@@ -25,46 +26,126 @@ Vue.component('r-m-l-workorder-admin', {
</template> </template>
<template v-slot:status="{ row }"> <template v-slot:status="{ row }">
<traffic-light :deadline="row.deadlineDate" :status="row.status" /> <traffic-light :deadline="row.deadlineDate" :status="row.status"/>
<i :class="getStatusColumn(row.status).icon" :title="getStatusColumn(row.status).text"></i> <i :class="getStatusColumn(row.status).icon" :title="getStatusColumn(row.status).text"></i>
<span class="ml-2">{{ getStatusColumn(row.status).text }}</span> <span class="ml-2">{{ getStatusColumn(row.status).text }}</span>
</template> </template>
<template v-slot:companyname="{ row }">
<div class="d-flex justify-content-between align-items-center">
<div class="flex-grow-1">
<div v-if="editingWorkorderId === row.id">
<tt-select
:options="companies"
:value="row.companyId"
@input="assignCompany(row, $event)"
@blur="editingWorkorderId = null"
@keydown.esc.native="editingWorkorderId = null"
placeholder="Firma zuweisen..."
sm
no-form-group
/>
</div>
<div v-else-if="row.status === 'new'">
<tt-select
:options="companies"
:value="row.companyId"
@input="assignCompany(row, $event)"
placeholder="Firma zuweisen..."
sm
no-form-group
/>
</div>
<div v-else class="d-flex align-items-center">
<span>{{ row.companyName || 'N/A' }}</span>
<tt-button
icon="fas fa-edit"
@click="editingWorkorderId = row.id"
additional-class="btn-link btn-sm p-0 ml-2"
title="Zuweisung ändern"
/>
</div>
</div>
<div class="ml-3">
<tt-button v-if="!workordersToAssign.includes(row.id)"
icon="fas fa-plus-circle text-success"
@click="addToAssignList(row)"
additional-class="btn-link btn-sm p-0"
title="Zur Zuweisungsliste hinzufügen"
/>
<tt-button v-if="workordersToAssign.includes(row.id)"
icon="fas fa-minus-circle text-danger"
@click="removeFromAssignList(row)"
additional-class="btn-link btn-sm p-0"
title="Von Zuweisungsliste entfernen"
/>
</div>
</div>
</template>
<template v-slot:deadlinedate="{ row }"> <template v-slot:deadlinedate="{ row }">
{{ formatDate(row.deadlineDate) }} {{ formatDate(row.deadlineDate) }}
<span v-if="row.daysUntilDeadline !== null && row.daysUntilDeadline >= 0" class="ml-2 text-muted small">
bis zum Termin: {{ row.daysUntilDeadline }} Tag{{ row.daysUntilDeadline !== 1 ? 'e' : '' }}
</span>
</template> </template>
<template v-slot:appointmentdate="{ row }"> <template v-slot:appointmentdate="{ row }">
{{ formatDate(row.appointmentDate) }} {{ formatDate(row.appointmentDate) }}
</template> </template>
<template v-slot:expandedRow="{ row }">
<rml-documentation-viewer-admin
:workorder-id="row.id"
@workorder-updated="$refs.table.$refs.table.refreshTable()"
/>
</template>
</tt-table-crud> </tt-table-crud>
</tt-card> </tt-card>
`, `,
data() { data() {
return { return {
assignModalWorkorderId: null, workordersToAssign: [],
docsModalWorkorderId: null, editingWorkorderId: null,
companies: [],
massAssignCompanyId: null,
massAssignLoading: false,
crudConfig: { crudConfig: {
...window.TT_CONFIG.CRUD_CONFIG, ...window.TT_CONFIG.CRUD_CONFIG,
additionalActions: [ selectable: false,
{ expandable: true,
"key": "assign", customRowClass: (row) => {
"title": "Firma zuweisen", const deadlineDate = moment.unix(row.deadlineDate);
"class": "fas fa-user-plus text-primary",
"condition": (row) => row.status === 'new', if (['completed', 'new'].includes(row.status) || !deadlineDate.isValid()) {
return 'tt-rml-workorder-irrelevant';
}
const daysLeft = deadlineDate.diff(moment(), 'days');
if (daysLeft <= 7) return 'tt-rml-workorder-urgent';
if (daysLeft <= 21) return 'tt-rml-workorder-medium';
return 'tt-rml-workorder-ontrack';
}, },
{ additionalActions: []
"key": "view_docs",
"title": "Dokumentation ansehen",
"class": "fas fa-folder-open text-info",
"condition": (row) => ['documented', 'completed'].includes(row.status),
},
]
} }
} }
}, },
async mounted() {
const response = await axios.get(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/getCompanies`);
this.companies = response.data;
},
methods: { methods: {
addToAssignList(row) {
if (!this.workordersToAssign.includes(row.id)) {
this.workordersToAssign.push(row.id);
}
},
removeFromAssignList(row) {
this.workordersToAssign = this.workordersToAssign.filter(id => id !== row.id);
},
getStatusColumn(status) { getStatusColumn(status) {
const column = this.crudConfig.columns.find(c => c.key === 'status'); const column = this.crudConfig.columns.find(c => c.key === 'status');
return column.table.filterOptions.find(opt => opt.value === status) || {}; return column.table.filterOptions.find(opt => opt.value === status) || {};
@@ -72,6 +153,60 @@ Vue.component('r-m-l-workorder-admin', {
formatDate(timestamp) { formatDate(timestamp) {
if (!timestamp) return ''; if (!timestamp) return '';
return window.moment.unix(timestamp).format('DD.MM.YYYY'); return window.moment.unix(timestamp).format('DD.MM.YYYY');
},
async assignCompany(workorder, companyId) {
if (!companyId) {
this.editingWorkorderId = null;
return;
}
const payload = {
workorderId: workorder.id,
companyId: companyId
};
try {
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/assignWorkorder`, payload);
if (response.data.success) {
window.notify('success', response.data.message);
this.$refs.table.$refs.table.refreshTable();
} else {
window.notify('error', response.data.message || 'Ein Fehler ist aufgetreten.');
}
} catch (e) {
window.notify('error', 'Ein Netzwerkfehler ist aufgetreten.');
} finally {
this.editingWorkorderId = null;
}
},
async massAssignCompanies(companyId) {
if (!companyId) return;
if (!confirm(`${this.workordersToAssign.length} Workorder(s) der ausgewählten Firma zuweisen?`)) {
this.massAssignCompanyId = null; // Reset select on cancel
return;
}
this.massAssignLoading = true;
const payload = {
companyId: companyId,
workorderIds: this.workordersToAssign
};
try {
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/massAssignWorkorders`, payload);
if (response.data.success) {
window.notify('success', response.data.message);
this.workordersToAssign = [];
this.$refs.table.$refs.table.refreshTable();
} else {
window.notify('error', response.data.message || 'Ein Fehler ist aufgetreten.');
}
} catch (e) {
window.notify('error', 'Ein Netzwerkfehler ist aufgetreten.');
} finally {
this.massAssignLoading = false;
this.massAssignCompanyId = null;
}
} }
} }
}); });
@@ -80,104 +215,158 @@ Vue.component('traffic-light', {
props: ['deadline', 'status'], props: ['deadline', 'status'],
computed: { computed: {
lightInfo() { lightInfo() {
if (['completed', 'new'].includes(this.status)) return { color: '#cccccc', title: 'Status irrelevant für Dringlichkeit' }; if (['completed', 'new'].includes(this.status)) return {color: '#cccccc', title: 'Status irrelevant für Dringlichkeit'};
const now = moment(); const now = moment();
const deadlineDate = moment.unix(this.deadline); const deadlineDate = moment.unix(this.deadline);
if (!deadlineDate.isValid()) return { color: '#cccccc', title: 'Keine Deadline gesetzt' }; if (!deadlineDate.isValid()) return {color: '#cccccc', title: 'Keine Deadline gesetzt'};
if (deadlineDate.isBefore(now)) return { color: '#dc3545', title: 'Deadline überschritten' }; if (deadlineDate.isBefore(now)) return {color: '#dc3545', title: 'Deadline überschritten'};
const daysLeft = deadlineDate.diff(now, 'days'); const daysLeft = deadlineDate.diff(now, 'days');
if (daysLeft <= 7) return { color: '#dc3545', title: 'Dringend: Weniger als 1 Woche' }; if (daysLeft <= 7) return {color: '#dc3545', title: 'Dringend: Weniger als 1 Woche'};
if (daysLeft <= 21) return { color: '#ffc107', title: 'Mittel: Weniger als 3 Wochen' }; if (daysLeft <= 21) return {color: '#ffc107', title: 'Mittel: Weniger als 3 Wochen'};
return { color: '#28a745', title: 'Im Plan: Mehr als 3 Wochen' }; return {color: '#28a745', title: 'Im Plan: Mehr als 3 Wochen'};
} }
}, },
template: `<span :style="{ color: lightInfo.color, fontSize: '1.2em' }" class="mr-2" :title="lightInfo.title">&#9679;</span>` template: `<span :style="{ color: lightInfo.color, fontSize: '1.2em' }" class="mr-2" :title="lightInfo.title">&#9679;</span>`
}); });
Vue.component('assign-company-modal', { Vue.component('rml-documentation-viewer-admin', {
props: ['workorderId'], props: ['workorderId'],
template: ` template: `
<tt-modal :show="true" title="Firma zuweisen" @submit="submit" @update:show="$emit('close')"> <div class="p-3 bg-light">
<tt-select label="Firma" :options="companies" v-model="selectedCompanyId" sm row required /> <div v-if="loading" class="text-center p-5"><i class="fas fa-spinner fa-spin fa-2x"></i></div>
</tt-modal> <div v-else class="row">
<div class="col-lg-6">
<tt-file-gallery :files="docs" @selection-changed="selectedDocs = $event" selectable />
</div>
<div class="col-lg-6">
<div class="card mb-3">
<div class="card-header"><h5><i class="fas fa-exclamation-triangle text-danger mr-2"></i>Korrektur anfordern</h5></div>
<div class="card-body">
<p class="small text-muted">Wählen Sie die zu korrigierenden Dokumente aus der Galerie aus und geben Sie einen Grund an.</p>
<tt-textarea v-model="correctionText" label="Grund für die Korrektur" sm row />
<tt-button text="Korrektur anfordern" @click="requestCorrection" :loading="correctionLoading" additional-class="btn-danger float-right"/>
</div>
</div>
<!-- add a new card with a green button Dokumentation akzeptieren-->
<div class="card mb-3">
<div class="card-header"><h5><i class="fas fa-check-circle text-success mr-2"></i>Dokumentation akzeptieren</h5></div>
<div class="card-body">
<p class="small text-muted">Wenn die Dokumentation korrekt ist, können Sie sie hier akzeptieren.</p>
<tt-button text="Dokumentation akzeptieren"
@click="$emit('accept-documentation', workorderId)"
additional-class="btn-success float-right"
icon="fas fa-check"
/>
</div>
</div>
<div class="card mt-3">
<div class="card-header"><h5><i class="fas fa-history mr-2"></i>Journal</h5></div>
<div class="card-body p-0" style="max-height: 200px; overflow-y: auto;">
<ul v-if="journals.length" class="list-group list-group-flush">
<li v-for="log in journals" :key="log.id" class="list-group-item small">
<strong>{{ formatDate(log.create) }} ({{ log.createByName }}):</strong>
<div class="text-muted" style="white-space: pre-wrap;">{{ log.text }}</div>
</li>
</ul>
<div v-else class="card-body text-muted text-center">Keine Journaleinträge.</div>
</div>
<div class="card-footer">
<tt-textarea v-model="newJournalMessage" placeholder="Ihre Nachricht oder Anmerkung..." rows="2" />
<tt-button
text="Eintrag speichern"
@click="addJournalEntry"
:loading="addingJournalEntry"
additional-class="btn-info btn-sm w-100 mt-2"
icon="fas fa-paper-plane"
/>
</div>
</div>
</div>
</div>
</div>
`, `,
data() { return { companies: [], selectedCompanyId: null } }, data() {
async mounted() { return {
const response = await axios.get(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/getCompanies`); loading: true,
this.companies = response.data; correctionLoading: false,
docs: [],
journals: [],
selectedDocs: [],
correctionText: '',
newJournalMessage: '',
addingJournalEntry: false,
}
}, },
methods: { methods: {
async submit() { async fetchData() {
if (!this.selectedCompanyId) return window.notify('error', 'Bitte eine Firma auswählen.'); this.loading = true;
try { try {
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/assignWorkorder`, { const response = await axios.get(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/getDocumentation`, { params: { workorderId: this.workorderId }});
this.docs = response.data.docs;
this.journals = response.data.journals;
} catch(e) {
window.notify('error', 'Dokumentation konnte nicht geladen werden.');
} finally {
this.loading = false;
}
},
async requestCorrection() {
if (!this.correctionText) return window.notify('error', 'Bitte geben Sie einen Grund für die Korrektur an.');
if (this.selectedDocs.length === 0) return window.notify('error', 'Bitte wählen Sie mindestens ein Dokument für die Korrektur aus.');
this.correctionLoading = true;
try {
const payload = {
workorderId: this.workorderId, workorderId: this.workorderId,
companyId: this.selectedCompanyId text: this.correctionText,
}); fileIds: this.selectedDocs
if(response.data.success) { };
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/requestCorrection`, payload);
if (response.data.success) {
window.notify('success', response.data.message); window.notify('success', response.data.message);
this.$emit('close'); this.correctionText = '';
this.selectedDocs = [];
await this.fetchData();
this.$emit('workorder-updated');
} else { } else {
window.notify('error', response.data.message || 'Ein Fehler ist aufgetreten.'); window.notify('error', response.data.message);
} }
} catch (e) { } catch (e) {
window.notify('error', 'Ein Netzwerkfehler ist aufgetreten.'); window.notify('error', 'Ein Netzwerkfehler ist aufgetreten.');
} }
} this.correctionLoading = false;
}
});
Vue.component('documentation-viewer-modal', {
props: ['workorderId'],
template: `
<tt-modal :show="true" :title="'Dokumentation für Auftrag #' + workorderId" :save="false" :delete="false" @update:show="$emit('close')">
<div class="card">
<div class="card-header">
<h5>Hochgeladene Dokumente</h5>
</div>
<div v-if="loading" class="card-body text-center"><i class="fas fa-spinner fa-spin fa-2x"></i></div>
<div v-else-if="!docs.length" class="card-body text-center text-muted">Keine Dokumente vorhanden.</div>
<ul v-else class="list-group list-group-flush">
<li v-for="doc in docs" :key="doc.id" class="list-group-item">
<a :href="'/File/download?id=' + doc.fileId" target="_blank">
<i class="fas fa-file-download mr-2"></i> {{ doc.fileName }}
</a>
<div class="text-muted small mt-1">
<strong>Typ:</strong> {{ getDocTypeText(doc.documentType) }} <br/>
<strong>Beschreibung:</strong> {{ doc.description || '-' }} <br/>
<strong>Hochgeladen von:</strong> {{ doc.userName }} am {{ formatDate(doc.create) }}
</div>
</li>
</ul>
</div>
</tt-modal>
`,
data() {
return { loading: false, docs: [] }
}, },
methods: { async addJournalEntry() {
async fetchDocs() { if (!this.newJournalMessage.trim()) {
this.loading = true; return window.notify('error', 'Bitte geben Sie eine Nachricht ein.');
const response = await axios.get(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/getDocumentation`, { params: { workorderId: this.workorderId }}); }
this.docs = response.data; this.addingJournalEntry = true;
this.loading = false; try {
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderAdmin/addJournal`, {
workorderId: this.workorderId,
text: this.newJournalMessage
});
if (response.data.success) {
window.notify('success', response.data.message || 'Journal-Eintrag hinzugefügt.');
this.newJournalMessage = '';
this.journals = response.data.journals;
} else {
window.notify('error', response.data.message || 'Eintrag konnte nicht gespeichert werden.');
}
} catch (e) {
window.notify('error', 'Ein Netzwerkfehler ist aufgetreten.');
} finally {
this.addingJournalEntry = false;
}
}, },
formatDate(timestamp) { formatDate(timestamp) {
return window.moment.unix(timestamp).format('DD.MM.YYYY HH:mm'); return window.moment.unix(timestamp).format('DD.MM.YYYY HH:mm');
}, },
getDocTypeText(type) {
const types = [
{ value: 'photo_before', text: 'Foto: Zustand vorher' },
{ value: 'photo_during', text: 'Foto: Während der Arbeit' },
{ value: 'photo_after', text: 'Foto: Zustand nachher' },
{ value: 'measurement_protocol', text: 'Messprotokoll (z.B. OTDR)' },
{ value: 'customer_signature', text: 'Unterschriebenes Arbeitsprotokoll' },
];
return types.find(t => t.value === type)?.text || type;
}
}, },
mounted() { mounted() {
this.fetchDocs(); this.fetchData();
} }
}); });
@@ -0,0 +1,30 @@
/*
* CSS for Workorder Table Row Highlighting
*/
/* Urgent: Deadline passed or less than 1 week away */
.table-hover .tt-rml-workorder-urgent:hover,
.tt-rml-workorder-urgent {
background-color: #fbe9e7 !important; /* Soft Red */
}
/* Medium: Deadline less than 3 weeks away */
.table-hover .tt-rml-workorder-medium:hover,
.tt-rml-workorder-medium {
background-color: #fff8e1 !important; /* Soft Yellow */
}
/* On Track: Deadline more than 3 weeks away */
.table-hover .tt-rml-workorder-ontrack:hover,
.tt-rml-workorder-ontrack {
background-color: #e8f5e9 !important; /* Soft Green */
}
/* Irrelevant: No deadline or status makes it not applicable */
.table-hover .tt-rml-workorder-irrelevant:hover,
.tt-rml-workorder-irrelevant {
background-color: #fafafa !important; /* Very light grey */
}
.tt-file-gallery-item.border.border-danger {
border: 4px solid #f1556c!important;
}
@@ -1,17 +1,9 @@
// RMLWorkorderCompany.js // RMLWorkorderCompany.js
Vue.component('r-m-l-workorder-company', { Vue.component('r-m-l-workorder-company', {
template: ` template: `
<tt-card> <tt-card>
<schedule-appointment-modal
v-if="scheduleModalWorkorderId"
:workorder-id="scheduleModalWorkorderId"
@close="scheduleModalWorkorderId = null; $refs.table.$refs.table.refreshTable()"
/>
<tt-table-crud <tt-table-crud
ref="table" ref="table"
@schedule="scheduleModalWorkorderId = $event.id"
:crud-config="crudConfig" :crud-config="crudConfig"
> >
<template v-slot:preorderinfo="{ row }"> <template v-slot:preorderinfo="{ row }">
@@ -29,7 +21,16 @@ Vue.component('r-m-l-workorder-company', {
</template> </template>
<template v-slot:appointmentdate="{ row }"> <template v-slot:appointmentdate="{ row }">
{{ formatDate(row.appointmentDate) }} <div v-if="!row.appointmentDate && ['assigned', 'correction_requested'].includes(row.status)">
<tt-date-picker
placeholder="Termin festlegen..."
:date-range="false"
@input="setAppointment(row, $event)"
sm
no-form-group
/>
</div>
<span v-else>{{ formatDate(row.appointmentDate) }}</span>
</template> </template>
<template v-slot:expandedRow="{ row }"> <template v-slot:expandedRow="{ row }">
@@ -44,18 +45,24 @@ Vue.component('r-m-l-workorder-company', {
`, `,
data() { data() {
return { return {
scheduleModalWorkorderId: null,
crudConfig: { crudConfig: {
...window.TT_CONFIG.CRUD_CONFIG, ...window.TT_CONFIG.CRUD_CONFIG,
expandable: true, expandable: true,
additionalActions: [ customRowClass: (row) => {
{ const deadlineDate = moment.unix(row.deadlineDate);
"key": "schedule",
"title": "Termin festlegen", if (['completed', 'new'].includes(row.status) || !deadlineDate.isValid()) {
"class": "fas fa-calendar-plus text-primary", return 'tt-rml-workorder-irrelevant';
"condition": (row) => row.status === 'assigned',
} }
]
const daysLeft = deadlineDate.diff(moment(), 'days');
if (daysLeft <= 7) return 'tt-rml-workorder-urgent';
if (daysLeft <= 21) return 'tt-rml-workorder-medium';
return 'tt-rml-workorder-ontrack';
},
additionalActions: []
} }
} }
}, },
@@ -67,6 +74,23 @@ Vue.component('r-m-l-workorder-company', {
formatDate(timestamp) { formatDate(timestamp) {
if (!timestamp) return ''; if (!timestamp) return '';
return window.moment.unix(timestamp).format('DD.MM.YYYY'); return window.moment.unix(timestamp).format('DD.MM.YYYY');
},
async setAppointment(workorder, date) {
if (!date) return;
try {
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderCompany/scheduleAppointment`, {
workorderId: workorder.id,
appointmentDate: date
});
if (response.data.success) {
window.notify('success', response.data.message);
this.$refs.table.$refs.table.refreshTable();
} else {
window.notify('error', response.data.message || 'Ein Fehler ist aufgetreten.');
}
} catch (e) {
window.notify('error', 'Ein Netzwerkfehler ist aufgetreten.');
}
} }
} }
}); });
@@ -90,35 +114,6 @@ Vue.component('traffic-light', {
template: `<span :style="{ color: lightInfo.color, fontSize: '1.2em' }" class="mr-2" :title="lightInfo.title">&#9679;</span>` template: `<span :style="{ color: lightInfo.color, fontSize: '1.2em' }" class="mr-2" :title="lightInfo.title">&#9679;</span>`
}); });
Vue.component('schedule-appointment-modal', {
props: ['workorderId'],
template: `
<tt-modal :show="true" title="Termin festlegen" @submit="submit" @update:show="$emit('close')">
<tt-date-picker label="Termindatum" :date-range="false" v-model="appointmentDate" sm row required />
</tt-modal>
`,
data() { return { appointmentDate: null } },
methods: {
async submit() {
if (!this.appointmentDate) return window.notify('error', 'Bitte ein Datum auswählen.');
try {
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderCompany/scheduleAppointment`, {
workorderId: this.workorderId,
appointmentDate: this.appointmentDate
});
if(response.data.success) {
window.notify('success', response.data.message);
this.$emit('close');
} else {
window.notify('error', response.data.message || 'Ein Fehler ist aufgetreten.');
}
} catch (e) {
window.notify('error', 'Ein Netzwerkfehler ist aufgetreten.');
}
}
}
});
Vue.component('documentation-manager', { Vue.component('documentation-manager', {
props: ['workorderId'], props: ['workorderId'],
template: ` template: `
@@ -126,6 +121,7 @@ Vue.component('documentation-manager', {
<div v-if="loadingWorkorder" class="text-center p-5"><i class="fas fa-spinner fa-spin fa-2x"></i></div> <div v-if="loadingWorkorder" class="text-center p-5"><i class="fas fa-spinner fa-spin fa-2x"></i></div>
<div v-else class="row"> <div v-else class="row">
<div class="col-lg-4 mb-3 mb-lg-0"> <div class="col-lg-4 mb-3 mb-lg-0">
<div>
<div class="card h-100"> <div class="card h-100">
<div class="card-body"> <div class="card-body">
<h5 class="card-title">Benötigte Dokumente</h5> <h5 class="card-title">Benötigte Dokumente</h5>
@@ -152,6 +148,29 @@ Vue.component('documentation-manager', {
</div> </div>
</div> </div>
</div> </div>
<div class="card mt-3">
<div class="card-header"><h5><i class="fas fa-history mr-2"></i>Journal</h5></div>
<div class="card-body p-0" style="max-height: 200px; overflow-y: auto;">
<ul class="list-group list-group-flush">
<li v-if="journals.length === 0" class="list-group-item text-center text-muted">Keine Einträge vorhanden.</li>
<li v-for="log in journals" :key="log.id" class="list-group-item small" :class="{'list-group-item-danger': log.statusChange && log.statusChange.includes('correction_requested')}">
<strong>{{ formatDate(log.create) }} ({{ log.createByName }}):</strong>
<div class="text-muted" style="white-space: pre-wrap;">{{ log.text }}</div>
</li>
</ul>
</div>
<div class="card-footer" v-if="workorder.status !== 'completed'">
<tt-textarea v-model="newJournalMessage" placeholder="Ihre Nachricht oder Anmerkung..." rows="2" />
<tt-button
text="Eintrag speichern"
@click="addJournalEntry"
:loading="addingJournalEntry"
additional-class="btn-info btn-sm w-100 mt-2"
icon="fas fa-paper-plane"
/>
</div>
</div>
</div>
</div> </div>
<div class="col-lg-8"> <div class="col-lg-8">
@@ -162,15 +181,30 @@ Vue.component('documentation-manager', {
<tt-input label="Beschreibung" v-model="uploadData.description" sm row placeholder="Optional"/> <tt-input label="Beschreibung" v-model="uploadData.description" sm row placeholder="Optional"/>
<div class="form-group row"> <div class="form-group row">
<label class="col-form-label col-sm-4 col-form-label-sm">Dateien</label> <label class="col-form-label col-sm-4 col-form-label-sm">Dateien</label>
<div class="col-sm-8"> <div class="col-sm-8 p-0">
<input type="file" class="form-control-file form-control-sm" @change="handleFileUpload" ref="fileInput" multiple /> <input type="file" class="form-control-file form-control-sm p-0" @change="handleFileUpload" ref="fileInput" multiple accept="image/*,.pdf,.doc,.docx" />
</div> </div>
</div> </div>
<tt-button text="Hochladen" @click="uploadFiles" :loading="uploading" additional-class="btn-primary float-right" icon="fas fa-upload" /> <tt-button text="Hochladen" @click="uploadFiles" :loading="uploading" additional-class="btn-primary float-right" icon="fas fa-upload" />
</div> </div>
</div> </div>
<tt-file-gallery :files="uploadedFiles" /> <tt-file-gallery
:files="filesWithStatus"
:edit-mode="workorder.status !== 'completed'"
:delete-mode="workorder.status !== 'completed'"
@delete-file="deleteDocumentation"
@update-file="updateDocumentation"
>
<template v-slot:file-edit="{ file }">
<tt-select
label="Dokumententyp"
:options="requiredDocTypes"
v-model="file.documentType"
sm
/>
</template>
</tt-file-gallery>
</div> </div>
</div> </div>
</div> </div>
@@ -182,6 +216,9 @@ Vue.component('documentation-manager', {
uploading: false, uploading: false,
completing: false, completing: false,
uploadedFiles: [], uploadedFiles: [],
journals: [],
newJournalMessage: '',
addingJournalEntry: false,
uploadData: { uploadData: {
files: [], files: [],
documentType: 'photo_before', documentType: 'photo_before',
@@ -199,9 +236,40 @@ Vue.component('documentation-manager', {
computed: { computed: {
canComplete() { canComplete() {
return this.requiredDocTypes.every(docType => this.isUploaded(docType.value)); return this.requiredDocTypes.every(docType => this.isUploaded(docType.value));
},
filesWithStatus() {
if (!this.journals || this.journals.length === 0) {
return this.uploadedFiles;
}
const correctionJournal = [...this.journals]
.sort((a, b) => b.create - a.create)
.find(j => j.statusChange && j.statusChange.includes('correction_requested'));
if (!correctionJournal || !correctionJournal.fileIds) {
return this.uploadedFiles;
}
try {
const incorrectFileIds = JSON.parse(correctionJournal.fileIds);
if (!Array.isArray(incorrectFileIds)) return this.uploadedFiles;
return this.uploadedFiles.map(file => {
if (incorrectFileIds.includes(file.id)) {
return { ...file, class: 'border border-danger' };
}
return file;
});
} catch (e) {
return this.uploadedFiles;
}
} }
}, },
methods: { methods: {
formatDate(timestamp) {
if (!timestamp) return '';
return window.moment.unix(timestamp).format('DD.MM.YYYY HH:mm');
},
async loadWorkorder() { async loadWorkorder() {
this.loadingWorkorder = true; this.loadingWorkorder = true;
try { try {
@@ -218,7 +286,8 @@ Vue.component('documentation-manager', {
async fetchDocs() { async fetchDocs() {
try { try {
const response = await axios.get(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderCompany/getDocumentation`, { params: { workorderId: this.workorderId }}); const response = await axios.get(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderCompany/getDocumentation`, { params: { workorderId: this.workorderId }});
this.uploadedFiles = response.data; this.uploadedFiles = response.data.docs;
this.journals = response.data.journals;
} catch(e) { } catch(e) {
window.notify('error', 'Dokumente konnten nicht geladen werden.'); window.notify('error', 'Dokumente konnten nicht geladen werden.');
} }
@@ -245,8 +314,9 @@ Vue.component('documentation-manager', {
this.$refs.fileInput.value = ''; this.$refs.fileInput.value = '';
this.uploadData.files = []; this.uploadData.files = [];
this.uploadData.description = ''; this.uploadData.description = '';
await this.fetchDocs();
await this.loadWorkorder(); // Reload to get updated status this.uploadedFiles = response.data.docs;
this.workorder = response.data.workorder;
} else { } else {
window.notify('error', response.data.error || 'Upload fehlgeschlagen.'); window.notify('error', response.data.error || 'Upload fehlgeschlagen.');
} }
@@ -271,9 +341,55 @@ Vue.component('documentation-manager', {
} }
this.completing = false; this.completing = false;
}, },
getDocTypeText(type) { async deleteDocumentation(file) {
const found = this.requiredDocTypes.find(t => t.value === type); try {
return found ? found.text : type; const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderCompany/deleteDocumentation`, { id: file.id });
if (response.data.success) {
window.notify('success', response.data.message);
this.uploadedFiles = response.data.docs;
} else {
window.notify('error', response.data.message || 'Löschen fehlgeschlagen.');
}
} catch (e) {
window.notify('error', 'Netzwerkfehler beim Löschen.');
}
},
async updateDocumentation(file) {
try {
const payload = { id: file.id, documentType: file.documentType };
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderCompany/updateDocumentation`, payload);
if (response.data.success) {
window.notify('success', response.data.message);
this.uploadedFiles = response.data.docs;
} else {
window.notify('error', response.data.message || 'Update fehlgeschlagen.');
}
} catch (e) {
window.notify('error', 'Netzwerkfehler beim Aktualisieren.');
}
},
async addJournalEntry() {
if (!this.newJournalMessage.trim()) {
return window.notify('error', 'Bitte geben Sie eine Nachricht ein.');
}
this.addingJournalEntry = true;
try {
const response = await axios.post(`${window.TT_CONFIG.BASE_PATH}/RMLWorkorderCompany/addJournal`, {
workorderId: this.workorderId,
text: this.newJournalMessage
});
if (response.data.success) {
window.notify('success', response.data.message || 'Journal-Eintrag hinzugefügt.');
this.newJournalMessage = '';
this.journals = response.data.journals;
} else {
window.notify('error', response.data.message || 'Eintrag konnte nicht gespeichert werden.');
}
} catch (e) {
window.notify('error', 'Ein Netzwerkfehler ist aufgetreten.');
} finally {
this.addingJournalEntry = false;
}
} }
}, },
async mounted() { async mounted() {
+4 -4
View File
@@ -391,8 +391,8 @@ Vue.component('radius', {
</thead> </thead>
<tbody> <tbody>
<tr v-for="user in freeNatUsers" :key="user.id"> <tr v-for="user in freeNatUsers" :key="user.id">
<td><a target="_blank" :href="'http://radius.xinon.at/edit_user.php?user=' + user.username">{{ user.username }}</a></td> <td><a target="_blank" :href="'http://radius.xinon.at/edit_user.php?user=' + user.Username">{{ user.Username }}</a></td>
<td>{{ user.info }}</td> <td>{{ user.Info }}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -408,8 +408,8 @@ Vue.component('radius', {
</thead> </thead>
<tbody> <tbody>
<tr v-for="user in freeStfUsers" :key="user.id"> <tr v-for="user in freeStfUsers" :key="user.id">
<td><a target="_blank" :href="'http://radius.xinon.at/edit_user.php?user=' + user.username">{{ user.username }}</a></td> <td><a target="_blank" :href="'http://radius.xinon.at/edit_user.php?user=' + user.Username">{{ user.Username }}</a></td>
<td>{{ user.info }}</td> <td>{{ user.Info }}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -502,14 +502,15 @@ Vue.component('warehouse-shipping-note', {
} }
}) })
window.addEventListener('DOMContentLoaded', () => { let hiddenTime = null;
if ('serviceWorker' in navigator) { const RELOAD_AFTER_SECONDS = 300;
navigator.serviceWorker.register('/WarehouseShippingNote/sw', {scope: '/'}) document.addEventListener('visibilitychange', () => {
.then(registration => { if (document.visibilityState === 'hidden') {
console.log('Patching PWA Service Worker registered with scope:', registration.scope); hiddenTime = new Date();
}) } else if (document.visibilityState === 'visible' && hiddenTime) {
.catch(error => { const secondsElapsed = (new Date() - hiddenTime) / 1000;
console.error('Patching PWA Service Worker registration failed:', error); if (secondsElapsed > RELOAD_AFTER_SECONDS) {
}); window.location.reload();
} }
}) }
});
+1 -1
View File
@@ -567,7 +567,7 @@ $(document).ready(function () {
$('#dynamictime-div').show(); $('#dynamictime-div').show();
$('#dataweek-col').hide(); $('#dataweek-col').hide();
$('#datayear-col').hide(); $('#datayear-col').hide();
} else if ($(this).data('datatype') == "3") { } else if ($(this).data('datatype') == "3" || $(this).data('datatype') == "5") {
$('#datayear-col').show(); $('#datayear-col').show();
$('#dynamictime-div').hide(); $('#dynamictime-div').hide();
$('#datamonth-col').hide(); $('#datamonth-col').hide();
@@ -1,3 +1,4 @@
/* tt-file-gallery.css */
.tt-file-gallery-grid { .tt-file-gallery-grid {
display: grid; display: grid;
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
@@ -13,11 +14,18 @@
cursor: pointer; cursor: pointer;
} }
.tt-file-gallery-thumbnail { .tt-file-gallery-thumbnail-wrapper {
position: relative;
width: 100%; width: 100%;
height: 100px; height: 100px;
object-fit: cover;
border-radius: 0.25rem; border-radius: 0.25rem;
overflow: hidden; /* Hide the scaled part of the image */
}
.tt-file-gallery-thumbnail {
width: 100%;
height: 100%;
object-fit: cover;
border: 1px solid #dee2e6; border: 1px solid #dee2e6;
transition: transform 0.2s; transition: transform 0.2s;
} }
@@ -30,8 +38,8 @@
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
right: 0; width: 100%;
bottom: 40px; /* Adjust to not cover filename */ height: 100%;
background: rgba(0, 0, 0, 0.4); background: rgba(0, 0, 0, 0.4);
color: white; color: white;
display: flex; display: flex;
@@ -43,13 +51,13 @@
border-radius: 0.25rem; border-radius: 0.25rem;
} }
.tt-file-gallery-item:hover .tt-file-gallery-overlay { .tt-file-gallery-item:hover .tt-file-gallery-thumbnail-wrapper .tt-file-gallery-overlay {
opacity: 1; opacity: 1;
} }
.tt-file-gallery-icon-container { .tt-file-gallery-icon-container {
width: 100%; width: 100%;
height: 100px; height: 100%;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
@@ -58,18 +66,40 @@
background-color: #f8f9fa; background-color: #f8f9fa;
text-decoration: none; text-decoration: none;
color: inherit; color: inherit;
transition: transform 0.2s;
} }
.tt-file-gallery-item:hover .tt-file-gallery-icon-container {
transform: scale(1.05);
}
.tt-file-gallery-filename { .tt-file-gallery-filename {
font-size: 0.8rem; font-size: 0.8rem;
margin-top: 0.5rem; margin-top: 0.5rem;
width: 100%; width: 100%;
padding: 0 4px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 0 0.25rem;
line-height: 1.2;
}
.tt-file-gallery-filename > span {
flex: 1 1 auto;
min-width: 0;
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
padding: 0 4px;
} }
.tt-file-gallery-filename > i {
flex-shrink: 0;
}
/* --- Fullscreen Viewer Styles --- */ /* --- Fullscreen Viewer Styles --- */
.tt-fullscreen-overlay { .tt-fullscreen-overlay {
@@ -0,0 +1,198 @@
/* --- tt-select.css --- */
.tt-select-modern {
position: relative;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
.tt-select-modern .form-group {
margin-bottom: 0;
}
.tt-select-modern .tt-select-trigger {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
padding: 0.5rem 0.75rem;
font-size: 1rem;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: 0.25rem;
transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
cursor: pointer;
text-align: left;
}
.tt-select-modern .tt-select-trigger.sm {
padding: 0.25rem 0.5rem;
font-size: 0.875rem;
border-radius: 0.2rem;
}
.tt-select-modern .tt-select-trigger:hover {
border-color: #80bdff;
}
.tt-select-modern .tt-select-trigger.open {
border-color: #80bdff;
box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}
.tt-select-modern .trigger-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex-grow: 1;
}
.tt-select-modern .trigger-text.placeholder {
color: #6c757d;
}
.tt-select-modern .trigger-arrow {
margin-left: 8px;
transition: transform 0.2s ease;
}
.tt-select-modern .tt-select-trigger.open .trigger-arrow {
transform: rotate(180deg);
}
.tt-select-modern .tt-select-dropdown {
position: absolute;
top: calc(100% + 4px);
left: 0;
min-width: 100%;
width: max-content;
z-index: 1050;
background-color: #fff;
border-radius: 0.3rem;
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
opacity: 0;
transform: translateY(-10px);
visibility: hidden;
transition: opacity 0.15s ease, transform 0.15s ease;
}
.tt-select-modern .tt-select-dropdown.show {
opacity: 1;
transform: translateY(0);
visibility: visible;
}
.tt-select-modern .dropdown-header {
display: none; /* Hidden on desktop */
}
.tt-select-modern .search-input-wrapper {
padding: 0.5rem;
border-bottom: 1px solid #e9ecef;
}
.tt-select-modern .search-input {
width: 100%;
padding: 0.375rem 0.75rem;
border: 1px solid #ced4da;
border-radius: 0.25rem;
}
.tt-select-modern .options-list {
list-style: none;
padding: 0.5rem 0;
margin: 0;
max-height: 250px;
overflow-y: auto;
}
.tt-select-modern .option-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.5rem 1rem;
cursor: pointer;
transition: background-color 0.15s ease;
user-select: none;
white-space: nowrap;
}
.tt-select-modern .option-label {
display: flex;
align-items: center;
}
.tt-select-modern .option-item input {
display: none;
}
.tt-select-modern .option-item:hover {
background-color: #f8f9fa;
}
.tt-select-modern .option-item.selected {
background-color: #e2f0ff;
font-weight: 600;
color: #0056b3;
}
.tt-select-modern .option-checkmark {
color: #0056b3;
}
.tt-select-modern .no-results {
padding: 0.5rem 1rem;
color: #6c757d;
text-align: center;
}
/* Mobile Compliance */
@media (max-width: 768px) {
.tt-select-modern .tt-select-trigger,
.tt-select-modern .option-item {
font-size: 1.1rem; /* Bigger font for readability */
}
.tt-select-modern .tt-select-dropdown.show {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
border-radius: 0;
display: flex;
flex-direction: column;
background-color: #f8f9fa;
transform: none;
}
.tt-select-modern .dropdown-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem;
background-color: #fff;
border-bottom: 1px solid #dee2e6;
font-size: 1.2rem;
font-weight: 600;
}
.tt-select-modern .close-btn {
font-size: 1.5rem;
cursor: pointer;
line-height: 1;
border: none;
background: none;
}
.tt-select-modern .options-list {
max-height: none;
flex-grow: 1;
}
}
File diff suppressed because one or more lines are too long
@@ -1,72 +1,57 @@
//TODO: if autocomplete is focus and the input has not a single character still show "Bitte mindestens 3 Zeichen eingeben"
//TODO: fix the fetchSuggestions function to not show a loading spinner when the input gets cleared
//TODO: fix so we can use arrow keys to navigate the suggestions
// TODO: Implement giving the option without the need of an API || need to use computed property to filter the items
// TODO: Fix the weirdness with timeout and selecting the suggestion
Vue.component('tt-autocomplete', { Vue.component('tt-autocomplete', {
template: ` template: `
<div class="form-group" :class="{'row': row}" <div class="form-group" :class="{'row': row}">
:data-api-url="apiUrl"
>
<slot name="prepend"></slot> <slot name="prepend"></slot>
<label :class="{'col-form-label': row, 'col-sm-4': row, 'col-form-label-sm': sm && row}" <label v-if="label" :for="label" :class="{'col-form-label': row, 'col-sm-4': row, 'col-form-label-sm': sm && row}">{{ label }}</label>
v-if="label" :for="label">{{ label }}</label>
<div class="autocomplete position-relative" :class="{'col-sm-8 p-0': row}"> <div class="autocomplete position-relative" :class="{'col-sm-8 p-0': row}">
<input <input
type="text"
:id="label" :id="label"
class="form-control tt-autocomplete"
:class="{'form-control-sm': sm}"
v-model="displayValue" v-model="displayValue"
:placeholder="placeholder" :placeholder="placeholder"
:class="{'form-control-sm': sm}"
:style="{'padding-right': $slots.append ? '30px' : '0'}"
type="text"
class="form-control tt-autocomplete"
autocomplete="off"
@input="onInput" @input="onInput"
@focus="onFocus" @focus="onFocus"
@blur="onBlur" @blur="onBlur"
autocomplete="off" @keydown.esc="showSuggestions = false"
:style="{'padding-right': $slots.append ? '30px' : '0'}" @keydown.down.prevent="navigate(1)"
@keydown.up.prevent="navigate(-1)"
@keydown.enter.prevent="selectOnEnter"
/> />
<slot name="append"></slot> <slot name="append"></slot>
<button v-show="displayValue.length > 0" @click="displayValue = ''; $emit('input', '');" tabindex="-1" type="button" <button v-show="displayValue.length > 0" @click="clear" tabindex="-1" type="button" class="btn btn-link position-absolute" style="right: -5px; top: 50%; transform: translateY(-50%);">
class="btn btn-link position-absolute"
style="right: -5px; top: 50%; transform: translateY(-50%);">
<i class="fas fa-times"></i> <i class="fas fa-times"></i>
</button> </button>
<ul v-show="showSuggestions && displayValue.length > 0 || isLoading" <ul v-if="showSuggestions" class="dropdown-menu show dropdown-shadow">
class="dropdown-menu show dropdown-shadow"> <li v-if="isLoading" class="dropdown-item">
<div class="spinner-border spinner-border-sm text-primary" role="status"><span class="sr-only">Loading...</span></div>
<li class="dropdown-item" v-show="isLoading">
<div class="spinner-border spinner-border-sm text-primary" role="status">
<span class="sr-only">Loading...</span>
</div>
Einträge werden geladen... Einträge werden geladen...
</li> </li>
<template v-if="!isLoading">
<template v-show="showSuggestions && displayingItems.length && isLoading !== true"> <li v-if="displayValue.length < 3" class="dropdown-item disabled">
Bitte mindestens 3 Zeichen eingeben
</li>
<li v-if="displayValue.length >= 3 && !displayingItems.length" class="dropdown-item disabled">
Keine Suchergebnisse vorhanden.
</li>
<li <li
v-for="(item) in displayingItems.slice(0, 10)" v-for="(item, index) in displayingItems.slice(0, 10)"
:key="item.value" :key="item.value"
:class="{'active': value === item.value}" :class="{'active': cursor === index}"
class="dropdown-item" class="dropdown-item"
@click.prevent="selectSuggestion(item)"
@mousedown.prevent="selectSuggestion(item)"
style="cursor: pointer;" style="cursor: pointer;"
@mousedown.prevent="selectSuggestion(item)"
> >
{{ item.text }} {{ item.text }}
</li> </li>
<!-- display more search results available define it more precisely in German --> <li v-if="displayingItems.length > 10" class="dropdown-item disabled">
<li v-show="displayingItems.length > 10" class="dropdown-item disabled">
Mehr Suchergebnisse vorhanden. Bitte genauer eingeben Mehr Suchergebnisse vorhanden. Bitte genauer eingeben
</li> </li>
</template> </template>
<li v-show="displayingItems.length === 0 && isLoading === false && displayValue.length >= 3"
class="dropdown-item disabled">
Keine Suchergebnisse vorhanden.
</li>
<li v-show="displayValue.length < 3" class="dropdown-item disabled">
Bitte mindestens 3 Zeichen eingeben
</li>
</ul> </ul>
</div> </div>
</div> </div>
@@ -80,132 +65,117 @@ Vue.component('tt-autocomplete', {
sm: {type: Boolean, default: true}, sm: {type: Boolean, default: true},
row: {type: Boolean, default: false}, row: {type: Boolean, default: false},
returnText: {type: Boolean, default: false}, returnText: {type: Boolean, default: false},
emitDisplayValue: {type: Boolean, default: false},
caseInsensitive: {type: Boolean, default: false}, caseInsensitive: {type: Boolean, default: false},
}, data() { },
data() {
return { return {
window,
displayingItems: [],
oldDisplayValue: '',
displayValue: '', displayValue: '',
displayingItems: [],
isLoading: false, isLoading: false,
showSuggestions: false, showSuggestions: false,
cursor: -1,
fetchSuggestionsDebounceTimer: null, fetchSuggestionsDebounceTimer: null,
disableIDFetch: false disableValueWatcher: false,
cursor: -1,
}; };
}, },
async mounted() { watch: {
this.updateDisplayValue().then(); value: {
handler(newValue) {
if (this.disableValueWatcher) return;
this.updateDisplayValue(newValue);
},
immediate: true
},
apiUrl: {
handler: 'fetchSuggestions',
immediate: true
},
}, },
methods: { methods: {
setOldDisplayValue(newValue, oldValue) { async updateDisplayValue(id) {
if (this.emitDisplayValue && newValue && typeof this.value !== 'number') { if (!id) {
this.$emit('displayValue', newValue);
}
this.oldDisplayValue = oldValue;
},
async updateDisplayValue(newValue, oldValue) {
if (this.disableIDFetch) {
this.disableIDFetch = false;
return;
}
if (newValue) {
this.$emit('input', newValue);
this.value = newValue;
}
if (oldValue && !newValue) {
this.$emit('input', '');
this.displayValue = ''; this.displayValue = '';
}
if (this.value && this.apiUrl) {
if (this.returnText && isNaN(this.value)) {
this.displayValue = this.value;
return; return;
} }
const response = await axios.get(`${this.apiUrl}${this.apiUrl.includes('?') ? '&' : '?'}autocomplete=1&searchedID=${this.value}`);
this.displayValue = response.data[0].text; if (this.returnText && isNaN(id)) {
} else if (this.value) { this.displayValue = id;
const selectedItem = this.caseInsensitive ? return;
this.items.find(item => item.value.toLowerCase() === this.value.toLowerCase()) : this.items.find(item => item.value === this.value) }
;
this.displayValue = selectedItem ? selectedItem.text : this.displayValue; if (this.apiUrl) {
const response = await axios.get(`${this.apiUrl}${this.apiUrl.includes('?') ? '&' : '?'}autocomplete=1&searchedID=${id}`);
if (response.data[0]) this.displayValue = response.data[0].text;
} else { } else {
if (this.returnText === false && !(typeof this.value === 'undefined' || this.value === '')) this.$emit('input', ''); const selectedItem = this.items.find(item =>
this.displayValue = this.displayValue.replace(this.oldDisplayValue, ''); this.caseInsensitive ? String(item.value).toLowerCase() === String(id).toLowerCase() : item.value === id
);
if (selectedItem) this.displayValue = selectedItem.text;
} }
}, },
onInput(event) { onInput() {
this.displayValue = event.target.value;
if (this.returnText) this.$emit('input', this.displayValue); if (this.returnText) this.$emit('input', this.displayValue);
this.fetchSuggestions(); this.fetchSuggestions();
}, onFocus() { },
onFocus() {
this.showSuggestions = true; this.showSuggestions = true;
}, onBlur() { this.fetchSuggestions();
setTimeout(() => { },
this.showSuggestions = false; onBlur() {
}, 200); setTimeout(() => this.showSuggestions = false, 200);
}, fetchSuggestions() { },
this.$set(this, 'displayingItems', []); fetchSuggestions() {
if (this.displayValue.length < 3) return;
if (!this.apiUrl) {
const isNegated = this.displayValue.startsWith('!');
const substrings = (isNegated ? this.displayValue.slice(1) : this.displayValue).split(' ').map(s => s.toLowerCase());
this.displayingItems = this.items.filter(item => {
let substringMatch = true;
for (var k = 0, klen = substrings.length; k < klen; ++k) {
if (!item.text.toLowerCase().includes(substrings[k])) {
substringMatch = false;
break;
}
}
return (isNegated && !substringMatch) || (!isNegated && substringMatch);
})
return
}
this.isLoading = true;
clearTimeout(this.fetchSuggestionsDebounceTimer); clearTimeout(this.fetchSuggestionsDebounceTimer);
this.fetchSuggestionsDebounceTimer = setTimeout(() => {
setTimeout(async () => {
if (this.displayValue.length < 3) { if (this.displayValue.length < 3) {
this.displayingItems = []; this.displayingItems = [];
this.isLoading = false; this.isLoading = false;
return; return;
} }
const response = await axios.get(`${this.apiUrl}${this.apiUrl.includes('?') ? '&' : '?'}autocomplete=1&q=${encodeURIComponent(this.displayValue)}`); this.fetchSuggestionsDebounceTimer = setTimeout(() => {
if (response.data?.status === 'error') { this.isLoading = true;
this.displayingItems = []; this.cursor = -1;
} else {
this.displayingItems = response.data
if (response.data.length === 1 && response.data[0].text === this.displayValue) this.selectSuggestion(response.data[0]);
}
this.isLoading = false;
this.fetchSuggestionsDebounceTimer = null; if (!this.apiUrl) {
}, 100); const searchTerms = this.displayValue.toLowerCase().split(' ').filter(s => s);
}, 300); // Adjust the 300ms debounce time as needed this.displayingItems = this.items.filter(item => {
}, selectSuggestion(item) { const itemText = item.text.toLowerCase();
this.disableIDFetch = true; return searchTerms.every(term => itemText.includes(term));
this.$emit('input', item.value); });
this.isLoading = false;
return;
}
axios.get(`${this.apiUrl}${this.apiUrl.includes('?') ? '&' : '?'}autocomplete=1&q=${encodeURIComponent(this.displayValue)}`)
.then(response => {
this.displayingItems = response.data?.status === 'error' ? [] : response.data;
if (this.displayingItems.length === 1 && this.displayingItems[0].text === this.displayValue) {
this.selectSuggestion(this.displayingItems[0]);
}
})
.finally(() => this.isLoading = false);
}, 300);
},
selectSuggestion(item) {
this.disableValueWatcher = true;
this.displayValue = item.text; this.displayValue = item.text;
this.$emit('input', item.value);
this.showSuggestions = false; this.showSuggestions = false;
}, clear() { this.$nextTick(() => this.disableValueWatcher = false);
},
selectOnEnter() {
if (this.cursor >= 0 && this.displayingItems[this.cursor])
this.selectSuggestion(this.displayingItems[this.cursor]);
},
navigate(direction) {
const itemCount = this.displayingItems.slice(0, 10).length;
if (!itemCount) return;
this.cursor = (this.cursor + direction + itemCount) % itemCount;
},
clear() {
this.displayValue = ''; this.displayValue = '';
this.$emit('input', ''); this.$emit('input', '');
this.displayingItems = [];
} }
},
watch: {
displayValue: {handler: 'setOldDisplayValue', immediate: true},
value: {handler: 'updateDisplayValue', immediate: true},
apiUrl: {handler: 'fetchSuggestions', immediate: true},
} }
}); });
+20 -33
View File
@@ -1,25 +1,18 @@
// noinspection JSCheckFunctionSignatures
Vue.component('tt-button', { Vue.component('tt-button', {
//language=Vue //language=Vue
template: ` template: `
<a v-if="href" :href="href" class="btn" :class="buttonClasses" @click="handleClick"> <component :is="href ? 'a' : 'button'"
<template v-if="loading"> :href="href"
<span class="spinner"></span> :disabled="!href && loading"
</template> :class="buttonClasses"
class="btn"
@click="handleClick">
<span v-if="loading" class="spinner"></span>
<template v-else> <template v-else>
<i v-if="icon" :class="icon"></i> <i v-if="icon" :class="icon"></i>
{{text}} {{ text }}
</template> </template>
</a> </component>
<button v-else @click="handleClick" class="btn" :class="buttonClasses" :disabled="loading">
<template v-if="loading">
<span class="spinner"></span>
</template>
<template v-else>
<i v-if="icon" :class="icon"></i>
{{text}}
</template>
</button>
`, `,
props: { props: {
sm: {type: Boolean, default: false}, sm: {type: Boolean, default: false},
@@ -32,26 +25,20 @@ Vue.component('tt-button', {
}, },
computed: { computed: {
buttonClasses() { buttonClasses() {
const classes = { const classes = [];
'btn-sm': this.sm, if (this.sm) classes.push('btn-sm');
'btn-loading': this.loading if (this.loading) classes.push('btn-loading');
} if (this.additionalClass) classes.push(...this.additionalClass.split(' '));
return classes;
if (this.additionalClass) {
this.additionalClass.split(' ').forEach(className => {
classes[className] = true
})
}
return classes
} }
}, },
methods: { methods: {
handleClick(event) { handleClick(event) {
if (this.loading) return event.preventDefault(); if (this.loading || (this.confirmText && !confirm(this.confirmText))) {
if (typeof this.confirmText === 'string' && !confirm(this.confirmText)) return event.preventDefault(); event.preventDefault();
return;
this.$emit('click', event) }
this.$emit('click', event);
} }
} }
}) });
@@ -14,139 +14,109 @@ Vue.component('tt-date-picker', {
template: ` template: `
<div class="form-group" :class="{'row': row}"> <div class="form-group" :class="{'row': row}">
<slot name="prepend"></slot> <slot name="prepend"></slot>
<label <label v-if="label" :for="label" :class="{'col-form-label': row, 'col-sm-4': row, 'col-form-label-sm': sm && row}">{{ label }}</label>
:class="{'col-form-label': row, 'col-sm-4': row, 'col-form-label-sm': sm && row}" <input type="text" ref="input" style="cursor: pointer;"
v-if="label" :id="label" :name="label" :placeholder="placeholder" :required="required" :disabled="disabled"
:for="label">{{ label }}</label> class="form-control" :class="{'form-control-sm': sm, 'col-sm-8': row}" v-bind="additionalProps">
<input type="text"
:id="label"
:name="label"
class="form-control"
:class="{'form-control-sm': sm, 'col-sm-8': row}"
:placeholder="placeholder"
:required="required"
:disabled="disabled"
v-bind="additionalProps"
ref="input"
style="cursor: pointer;"
>
<small v-if="hint" class="form-text text-muted">{{ hint }}</small> <small v-if="hint" class="form-text text-muted">{{ hint }}</small>
</div> </div>
`, `,
data() { data() {
return { return {
inputValue: '',
isInitialized: false, isInitialized: false,
moment: window.moment, moment: window.moment,
locale: { locale: {
// ... (keep your existing locale object) format: 'DD.MM.YYYY HH:mm',
separator: ' - ',
applyLabel: 'Übernehmen',
cancelLabel: 'Abbrechen',
fromLabel: 'Von',
toLabel: 'Bis',
customRangeLabel: 'Benutzerdef.',
weekLabel: 'W',
daysOfWeek: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
firstDay: 1
}, },
} }
}, },
mounted() { async mounted() {
this.isInitialized = true; const loadScript = (src, check) => new Promise((resolve, reject) => {
const datePickerOptions = { if (check()) return resolve();
autoUpdateInput: true, const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
document.head.appendChild(script);
});
await loadScript('/js/jquery.min.js', () => typeof jQuery !== 'undefined');
await loadScript('/plugins/daterangepicker/daterangepicker.js', () => typeof $?.fn?.daterangepicker !== 'undefined');
const pickerOptions = {
autoUpdateInput: false,
singleDatePicker: !this.dateRange, singleDatePicker: !this.dateRange,
timePicker: true, timePicker: true,
timePicker24Hour: true, timePicker24Hour: true,
locale: this.locale, locale: this.locale,
startDate: this.dateRange ? (this.value?.from ? this.moment.unix(this.value.from) : this.moment()) : (this.value ? this.moment.unix(this.value) : this.moment()),
endDate: this.dateRange ? (this.value?.to ? this.moment.unix(this.value.to) : this.moment()) : (this.value ? this.moment.unix(this.value) : this.moment()),
}; };
if (this.dateRange) { const $input = $(this.$refs.input);
datePickerOptions.startDate = this.value?.from ? this.moment.unix(this.value.from) : undefined; $input.daterangepicker(pickerOptions);
datePickerOptions.endDate = this.value?.to ? this.moment.unix(this.value.to) : undefined; this.updateInputValue(this.value);
} else {
datePickerOptions.startDate = this.value ? this.moment.unix(this.value) : undefined;
}
$(this.$refs.input).daterangepicker(datePickerOptions); $input.on('apply.daterangepicker', (ev, picker) => {
const val = this.dateRange
const _this = this; ? { from: picker.startDate.unix(), to: picker.endDate.unix() }
$(this.$refs.input).on('apply.daterangepicker', function (ev, picker) { : picker.startDate.unix();
if (_this.dateRange) { this.$emit('input', val);
_this.$emit('input', { this.updateInputValue(val);
from: picker.startDate.unix(),
to: picker.endDate.unix()
});
$(_this.$refs.input).val(picker.startDate.format(_this.locale.format) + _this.locale.separator + picker.endDate.format(_this.locale.format));
} else {
_this.$emit('input', picker.startDate.unix());
$(_this.$refs.input).val(picker.startDate.format(_this.locale.format));
}
}); });
function checkIfAppliedElseClear() { $input.on('cancel.daterangepicker', () => {
if (_this.dateRange) { this.$emit('input', undefined);
if (_this.value && _this.value.from && _this.value.to) return; this.updateInputValue(undefined);
} else { });
if (_this.value) return;
}
$(_this.$refs.input).val('');
}
function clearIfCancelled() { this.isInitialized = true;
_this.$emit('input', _this.dateRange ? {from: null, to: null} : null);
$(_this.$refs.input).val('');
}
$(this.$refs.input).on('cancel.daterangepicker', clearIfCancelled);
$(this.$refs.input).on('hide.daterangepicker', checkIfAppliedElseClear.bind(this));
// Clear input field if value is not set
if (_this.dateRange) {
if (!this.value || this.value.from === null || this.value.to === null) {
$(_this.$refs.input).val('');
}
} else {
if (!this.value) {
$(_this.$refs.input).val('');
}
}
// Add click event listener to the document
document.addEventListener('click', this.handleOutsideClick);
}, },
methods: { methods: {
handleOutsideClick(event) { updateInputValue(val) {
const datepicker = document.querySelector('.daterangepicker'); const $input = $(this.$refs.input);
const input = this.$refs.input; if (this.dateRange) {
if (val?.from && val?.to) {
if (datepicker && !datepicker.contains(event.target) && event.target !== input) { const from = this.moment.unix(val.from).format(this.locale.format);
if (input.parentElement.tagName.toLowerCase() === 'div' && input.parentElement.classList.contains('form-group')) { const to = this.moment.unix(val.to).format(this.locale.format);
return; $input.val(from + this.locale.separator + to);
} } else $input.val('');
$(this.$refs.input).data('daterangepicker').hide(); } else {
if (val) $input.val(this.moment.unix(val).format(this.locale.format));
else $input.val('');
} }
}, },
setStartDate(date) { setStartDate: (date) => $(this.$refs.input).data('daterangepicker').setStartDate(date)
$(this.$refs.input).data('daterangepicker').setStartDate(date);
}
}, },
watch: { watch: {
value: function (newVal) { value(newVal) {
if (!this.isInitialized) return; if (!this.isInitialized) return;
this.updateInputValue(newVal);
const datePicker = $(this.$refs.input).data('daterangepicker'); const datePicker = $(this.$refs.input).data('daterangepicker');
if (this.dateRange) { if (this.dateRange) {
if (!newVal || newVal.from === null || newVal.to === null) { datePicker.setStartDate(newVal?.from ? this.moment.unix(newVal.from) : this.moment());
$(this.$refs.input).val(''); datePicker.setEndDate(newVal?.to ? this.moment.unix(newVal.to) : this.moment());
} else { } else {
datePicker.setStartDate(this.moment.unix(newVal.from)); const date = newVal ? this.moment.unix(newVal) : this.moment();
datePicker.setEndDate(this.moment.unix(newVal.to)); datePicker.setStartDate(date);
} datePicker.setEndDate(date);
} else {
if (!newVal) {
$(this.$refs.input).val('');
} else {
datePicker.setStartDate(this.moment.unix(newVal));
datePicker.setEndDate(this.moment.unix(newVal));
}
} }
} }
}, },
beforeDestroy() { beforeDestroy() {
$(this.$refs.input).off('apply.daterangepicker'); const picker = $(this.$refs.input).data('daterangepicker');
document.removeEventListener('click', this.handleOutsideClick); if (picker) picker.remove();
}, },
}) });
@@ -1,13 +1,17 @@
// tt-file-gallery.js
Vue.component('tt-file-gallery', { Vue.component('tt-file-gallery', {
props: { props: {
files: { type: Array, default: () => [] } files: { type: Array, default: () => [] },
editMode: { type: Boolean, default: false },
deleteMode: { type: Boolean, default: false },
selectable: { type: Boolean, default: false },
}, },
data() { data() {
return { return {
fullscreenItem: null, // Holds the file being viewed fullscreenItem: null,
currentImageIndex: 0, currentImageIndex: 0,
editingFile: null,
// Zoom & Pan state selectedFiles: [],
zoom: 1, zoom: 1,
pan: { x: 0, y: 0 }, pan: { x: 0, y: 0 },
isPanning: false, isPanning: false,
@@ -23,7 +27,6 @@ Vue.component('tt-file-gallery', {
return this.fullscreenItem && this.isImage(this.fullscreenItem); return this.fullscreenItem && this.isImage(this.fullscreenItem);
}, },
imageTransformStyle() { imageTransformStyle() {
// Apply CSS transform for zoom and pan
const { x, y } = this.pan; const { x, y } = this.pan;
return { return {
transform: `translate(${x}px, ${y}px) scale(${this.zoom})`, transform: `translate(${x}px, ${y}px) scale(${this.zoom})`,
@@ -33,34 +36,33 @@ Vue.component('tt-file-gallery', {
}, },
fullscreenDownloadUrl() { fullscreenDownloadUrl() {
if (!this.fullscreenItem) return '#'; if (!this.fullscreenItem) return '#';
return `/File/download?id=${this.fullscreenItem.id}`; return `/File/download?id=${this.fullscreenItem.fileId}`;
} }
}, },
methods: { methods: {
// File type checks isImage: file => file.mimetype && file.mimetype.startsWith('image/'),
isImage(file) { isPdf: file => file.mimetype === 'application/pdf',
return file.mimetype && file.mimetype.startsWith('image/');
},
isPdf(file) {
return file.mimetype === 'application/pdf';
},
// Get icon for non-image/pdf files
getFileIcon(file) { getFileIcon(file) {
const extension = file.fileName?.split('.').pop().toLowerCase(); const extension = file.fileName?.split('.').pop().toLowerCase();
switch (extension) { switch (extension) {
case 'doc': case 'doc': case 'docx': return 'fas fa-file-word text-primary';
case 'docx': return 'fas fa-file-word text-primary'; case 'xls': case 'xlsx': return 'fas fa-file-excel text-success';
case 'xls': case 'zip': case 'rar': return 'fas fa-file-archive text-warning';
case 'xlsx': return 'fas fa-file-excel text-success';
case 'zip':
case 'rar': return 'fas fa-file-archive text-warning';
default: return 'fas fa-file text-secondary'; default: return 'fas fa-file text-secondary';
} }
}, },
toggleSelection(fileId) {
// Viewer controls if (!this.selectable) return;
const index = this.selectedFiles.indexOf(fileId);
if (index > -1) {
this.selectedFiles.splice(index, 1);
} else {
this.selectedFiles.push(fileId);
}
this.$emit('selection-changed', this.selectedFiles);
},
openViewer(file) { openViewer(file) {
if(this.editingFile) return;
this.fullscreenItem = file; this.fullscreenItem = file;
if (this.isImage(file)) { if (this.isImage(file)) {
this.currentImageIndex = this.imageFiles.findIndex(img => img.id === file.id); this.currentImageIndex = this.imageFiles.findIndex(img => img.id === file.id);
@@ -68,9 +70,7 @@ Vue.component('tt-file-gallery', {
this.resetZoomAndPan(); this.resetZoomAndPan();
this.$nextTick(() => { this.$refs.viewer?.focus(); }); this.$nextTick(() => { this.$refs.viewer?.focus(); });
}, },
closeViewer() { closeViewer() { this.fullscreenItem = null; },
this.fullscreenItem = null;
},
navigateImage(direction) { navigateImage(direction) {
const newIndex = this.currentImageIndex + direction; const newIndex = this.currentImageIndex + direction;
if (newIndex >= 0 && newIndex < this.imageFiles.length) { if (newIndex >= 0 && newIndex < this.imageFiles.length) {
@@ -79,9 +79,8 @@ Vue.component('tt-file-gallery', {
this.resetZoomAndPan(); this.resetZoomAndPan();
} }
}, },
// Event handlers for keyboard and clicks
handleKeyDown(event) { handleKeyDown(event) {
event.stopPropagation();
if (!this.fullscreenItem) return; if (!this.fullscreenItem) return;
switch (event.key) { switch (event.key) {
case 'Escape': this.closeViewer(); break; case 'Escape': this.closeViewer(); break;
@@ -89,24 +88,16 @@ Vue.component('tt-file-gallery', {
case 'ArrowRight': this.isViewingImage && this.navigateImage(1); break; case 'ArrowRight': this.isViewingImage && this.navigateImage(1); break;
} }
}, },
// --- Zoom and Pan Methods ---
resetZoomAndPan() { resetZoomAndPan() {
this.zoom = 1; this.zoom = 1; this.pan = { x: 0, y: 0 }; this.isPanning = false;
this.pan = { x: 0, y: 0 };
this.isPanning = false;
}, },
// Mouse Wheel Zoom
handleWheel(e) { handleWheel(e) {
if (!this.isViewingImage) return; if (!this.isViewingImage) return;
e.preventDefault(); e.preventDefault();
const scaleFactor = 0.2; const scaleFactor = 0.2;
const newZoom = this.zoom - (e.deltaY > 0 ? scaleFactor : -scaleFactor); const newZoom = this.zoom - (e.deltaY > 0 ? scaleFactor : -scaleFactor);
this.zoom = Math.max(1, Math.min(newZoom, 5)); // Clamp zoom between 1x and 5x this.zoom = Math.max(1, Math.min(newZoom, 5));
}, },
// Mouse Drag to Pan
onPanStart(e) { onPanStart(e) {
if (this.zoom <= 1) return; if (this.zoom <= 1) return;
e.preventDefault(); e.preventDefault();
@@ -119,78 +110,80 @@ Vue.component('tt-file-gallery', {
this.pan.x = e.clientX - this.panStart.x; this.pan.x = e.clientX - this.panStart.x;
this.pan.y = e.clientY - this.panStart.y; this.pan.y = e.clientY - this.panStart.y;
}, },
onPanEnd() { onPanEnd() { this.isPanning = false; },
this.isPanning = false; onTouchStart(e) { /* ... touch logic ... */ },
}, onTouchMove(e) { /* ... touch logic ... */ },
onTouchEnd(e) { /* ... touch logic ... */ },
// Touch Events for Mobile (Pinch-to-Zoom & Pan) startEdit(file, event) {
onTouchStart(e) { event?.stopPropagation();
if (this.zoom <= 1 && e.touches.length === 1) return; this.editingFile = { ...file }; // create a copy for editing
e.preventDefault(); },
if (e.touches.length === 1) { // Pan cancelEdit(event) {
this.isPanning = true; console.log('Edit cancelled');
this.panStart.x = e.touches[0].clientX - this.pan.x; event?.stopPropagation();
this.panStart.y = e.touches[0].clientY - this.pan.y; this.editingFile = null;
} else if (e.touches.length === 2) { // Zoom },
this.lastPinchDist = Math.hypot( saveEdit(event) {
e.touches[0].clientX - e.touches[1].clientX, event?.stopPropagation();
e.touches[0].clientY - e.touches[1].clientY this.$emit('update-file', this.editingFile);
); this.editingFile = null;
},
deleteFile(file, event) {
event?.stopPropagation();
if (confirm(`Sind Sie sicher, dass Sie die Datei "${file.fileName}" löschen möchten?`)) {
this.$emit('delete-file', file);
} }
}, },
onTouchMove(e) {
if (!this.isPanning && e.touches.length !== 2) return;
e.preventDefault();
if (e.touches.length === 1 && this.isPanning) { // Pan
this.pan.x = e.touches[0].clientX - this.panStart.x;
this.pan.y = e.touches[0].clientY - this.panStart.y;
} else if (e.touches.length === 2) { // Zoom
const pinchDist = Math.hypot(
e.touches[0].clientX - e.touches[1].clientX,
e.touches[0].clientY - e.touches[1].clientY
);
const scaleFactor = 0.01;
const newZoom = this.zoom + (pinchDist - this.lastPinchDist) * scaleFactor;
this.zoom = Math.max(1, Math.min(newZoom, 5)); // Clamp zoom
this.lastPinchDist = pinchDist;
}
},
onTouchEnd(e) {
this.isPanning = false;
if (e.touches.length < 2) {
this.lastPinchDist = 0;
}
}
}, },
watch: { watch: {
fullscreenItem(newItem) { fullscreenItem(newItem) {
// Prevent body scroll when viewer is open
document.body.style.overflow = newItem ? 'hidden' : ''; document.body.style.overflow = newItem ? 'hidden' : '';
} }
}, },
template: ` template: `
<div class="card"> <div class="card">
<div class="card-header"><h5>Hochgeladene Dokumente</h5></div> <div class="card-header"><i class="fas fa-images mr-2"></i><h5>Hochgeladene Dokumente</h5></div>
<div v-if="!files.length" class="card-body text-center text-muted">Keine Dokumente vorhanden.</div> <div v-if="!files.length" class="card-body text-center text-muted">Keine Dokumente vorhanden.</div>
<div v-else class="card-body"> <div v-else class="card-body">
<div class="tt-file-gallery-grid"> <div class="tt-file-gallery-grid">
<div v-for="file in files" :key="file.id" class="tt-file-gallery-item" @click="openViewer(file)"> <div v-for="file in files" :key="file.id"
class="tt-file-gallery-item"
:class="[{ 'selected': selectable && selectedFiles.includes(file.id) }, file.class]"
@click="openViewer(file)">
<div v-if="selectable" class="selection-indicator" @click.stop="toggleSelection(file.id)">
<i :class="selectedFiles.includes(file.id) ? 'fas fa-check-circle text-primary' : 'far fa-circle text-muted'"></i>
</div>
<div class="tt-file-gallery-thumbnail-wrapper">
<template v-if="isImage(file)"> <template v-if="isImage(file)">
<img :src="'/File/show?id=' + file.id + '&size=small'" class="tt-file-gallery-thumbnail" :alt="file.fileName"> <img :src="'/File/show?id=' + file.fileId + '&size=small'" class="tt-file-gallery-thumbnail" :alt="file.fileName">
<div class="tt-file-gallery-overlay"><i class="fas fa-search-plus"></i></div>
</template> </template>
<template v-else-if="isPdf(file)"> <template v-else-if="isPdf(file)">
<div class="tt-file-gallery-icon-container"><i class="fas fa-file-pdf fa-3x text-danger"></i></div> <div class="tt-file-gallery-icon-container"><i class="fas fa-file-pdf fa-3x text-danger"></i></div>
</template> </template>
<template v-else> <template v-else>
<a :href="'/File/download?id=' + file.id" target="_blank" @click.stop class="tt-file-gallery-icon-container"> <a :href="'/File/download?id=' + file.fileId" target="_blank" @click.stop class="tt-file-gallery-icon-container">
<i :class="getFileIcon(file)" class="fa-3x"></i> <i :class="getFileIcon(file)" class="fa-3x"></i>
</a> </a>
</template> </template>
<div class="tt-file-gallery-filename" :title="file.fileName">{{ file.fileName }}</div> <div class="tt-file-gallery-overlay" @click.stop="openViewer(file)"><i class="fas fa-search-plus"></i></div>
</div>
<div class="tt-file-gallery-filename" :title="file.fileName">
<span>{{ file.fileName }}</span>
<i v-if="editMode && !editingFile" class="fas fa-edit text-primary ml-1 action-icon" @click="startEdit(file, $event)"></i>
<i v-if="deleteMode && !editingFile" class="fas fa-trash text-danger ml-1 action-icon" @click="deleteFile(file, $event)"></i>
</div> </div>
</div> </div>
</div> </div>
</div>
<tt-modal v-if="editingFile" :show="true" title="Dokument bearbeiten" @close="cancelEdit" @submit="saveEdit" :delete="false">
<slot name="file-edit" :file="editingFile"></slot>
</tt-modal>
<div v-if="fullscreenItem" class="tt-fullscreen-overlay" @click.self="closeViewer" @keydown="handleKeyDown" tabindex="-1" ref="viewer"> <div v-if="fullscreenItem" class="tt-fullscreen-overlay" @click.self="closeViewer" @keydown="handleKeyDown" tabindex="-1" ref="viewer">
<div class="tt-fullscreen-toolbar"> <div class="tt-fullscreen-toolbar">
@@ -199,33 +192,19 @@ Vue.component('tt-file-gallery', {
</a> </a>
<button class="tt-fullscreen-btn" @click="closeViewer" title="Close"><i class="fas fa-times"></i></button> <button class="tt-fullscreen-btn" @click="closeViewer" title="Close"><i class="fas fa-times"></i></button>
</div> </div>
<div class="tt-fullscreen-content" @click.self="closeViewer"> <div class="tt-fullscreen-content" @click.self="closeViewer">
<template v-if="isViewingImage"> <template v-if="isViewingImage">
<div class="tt-fullscreen-image-wrapper" <div class="tt-fullscreen-image-wrapper" @wheel="handleWheel" @mousedown="onPanStart" @mousemove="onPanMove" @mouseup="onPanEnd" @mouseleave="onPanEnd">
@wheel="handleWheel" <img :src="'/File/show?id=' + fullscreenItem.fileId" class="tt-fullscreen-image" :style="imageTransformStyle" @click.stop />
@mousedown="onPanStart"
@mousemove="onPanMove"
@mouseup="onPanEnd"
@mouseleave="onPanEnd"
@touchstart="onTouchStart"
@touchmove="onTouchMove"
@touchend="onTouchEnd">
<img :src="'/File/show?id=' + fullscreenItem.id" class="tt-fullscreen-image" :style="imageTransformStyle" @click.stop />
</div> </div>
</template> </template>
<template v-else-if="isPdf(fullscreenItem)"> <template v-else-if="isPdf(fullscreenItem)">
<iframe :src="'/File/show?id=' + fullscreenItem.id" class="tt-fullscreen-pdf" @click.stop></iframe> <iframe :src="'/File/show?id=' + fullscreenItem.fileId" class="tt-fullscreen-pdf" @click.stop></iframe>
</template> </template>
</div> </div>
<template v-if="isViewingImage"> <template v-if="isViewingImage">
<button class="tt-fullscreen-nav-btn left" @click.stop="navigateImage(-1)" v-if="currentImageIndex > 0"> <button class="tt-fullscreen-nav-btn left" @click.stop="navigateImage(-1)" v-if="currentImageIndex > 0"><i class="fas fa-chevron-left"></i></button>
<i class="fas fa-chevron-left"></i> <button class="tt-fullscreen-nav-btn right" @click.stop="navigateImage(1)" v-if="currentImageIndex < imageFiles.length - 1"><i class="fas fa-chevron-right"></i></button>
</button>
<button class="tt-fullscreen-nav-btn right" @click.stop="navigateImage(1)" v-if="currentImageIndex < imageFiles.length - 1">
<i class="fas fa-chevron-right"></i>
</button>
</template> </template>
</div> </div>
</div> </div>
@@ -12,7 +12,6 @@ Vue.component('tt-modal', {
if (!newVal) { if (!newVal) {
this.$emit('close') this.$emit('close')
} }
// if show now is true then focus the first input element
if (newVal) { if (newVal) {
this.$nextTick(() => { this.$nextTick(() => {
const input = this.$refs.modal.querySelector('input') const input = this.$refs.modal.querySelector('input')
+96 -148
View File
@@ -1,50 +1,42 @@
Vue.component('tt-select', { Vue.component('tt-select', {
props: { props: {
options: { type: Array, required: true }, options: {type: Array, required: true},
label: { type: String, default: null }, label: {type: String, default: null},
required: { type: Boolean, default: false }, required: {type: Boolean, default: false},
value: { type: [String, Number, Array], default: null }, value: {type: [String, Number, Array], default: null},
disabled: { type: Boolean, default: false }, disabled: {type: Boolean, default: false},
suffix: { type: String, default: null }, suffix: {type: String, default: null},
sm: { type: Boolean, default: false }, sm: {type: Boolean, default: false},
row: { type: Boolean, default: false }, row: {type: Boolean, default: false},
multiple: { type: Boolean, default: false }, multiple: {type: Boolean, default: false},
searchable: { type: Boolean, default: true } searchable: {type: Boolean, default: true}
}, },
data() { data() {
return { return {
open: false, open: false,
searchQuery: '', searchQuery: '',
// internal model: array if multiple, else primitive selected: this.multiple ? (Array.isArray(this.value) ? [...this.value] : []) : this.value
selected: this.multiple
? (Array.isArray(this.value) ? [...this.value] : [])
: this.value
}; };
}, },
watch: { watch: {
// keep internal model in sync with external v-model
value(newVal) { value(newVal) {
this.selected = this.multiple this.selected = this.multiple ? (Array.isArray(newVal) ? [...newVal] : []) : newVal;
? (Array.isArray(newVal) ? [...newVal] : [])
: newVal;
}, },
// Enhancement: Handle focus and scroll on open
open(isOpen) { open(isOpen) {
if (isOpen) { if (!isOpen) {
this.$nextTick(() => { this.searchQuery = ''; // Reset search on close
if (this.$refs.dropdownMenu) { return;
// 2. Scroll to the top when opened
this.$refs.dropdownMenu.scrollTop = 0;
} }
this.$nextTick(() => {
if (this.searchable && this.$refs.searchInput) { if (this.searchable && this.$refs.searchInput) {
// 1. Focus the input when opened
this.$refs.searchInput.focus(); this.$refs.searchInput.focus();
} }
}); if (this.$refs.optionsList) {
this.$refs.optionsList.scrollTop = 0;
} }
});
} }
}, },
@@ -57,55 +49,42 @@ Vue.component('tt-select', {
}, },
computed: { computed: {
// normalize all options to { value, text, disabled }
normalizedOptions() { normalizedOptions() {
return this.options.map(opt => { return this.options.map(opt =>
if (opt !== null && typeof opt === 'object') { (opt !== null && typeof opt === 'object')
return { ? {value: opt.value, text: opt.text, disabled: !!opt.disabled}
value: opt.value, : {value: opt, text: String(opt), disabled: false}
text: opt.text,
disabled: !!opt.disabled
};
}
return {
value: opt,
text: String(opt),
disabled: false
};
});
},
// filter by searchQuery
filteredOptions() {
if (!this.searchable || !this.searchQuery) {
return this.normalizedOptions;
}
const q = this.searchQuery.toLowerCase();
return this.normalizedOptions.filter(o =>
o.text.toLowerCase().includes(q)
); );
}, },
// what to show on the button filteredOptions() {
if (!this.searchable || !this.searchQuery) return this.normalizedOptions;
const q = this.searchQuery.toLowerCase();
return this.normalizedOptions.filter(o => o.text.toLowerCase().includes(q));
},
displayText() { displayText() {
if (this.multiple) { const addSuffix = text => text ? `${text}${this.suffix ? ` ${this.suffix}` : ''}` : '';
const arr = Array.isArray(this.selected) ? this.selected : [];
const count = arr.length; if (!this.multiple) {
if (count === 0) return ''; const opt = this.normalizedOptions.find(o => o.value === this.selected);
return opt ? addSuffix(opt.text) : 'Auswählen...';
}
const count = Array.isArray(this.selected) ? this.selected.length : 0;
if (count === 0) return 'Auswählen...';
if (count === 1) { if (count === 1) {
const o = this.normalizedOptions.find(x => x.value === arr[0]); const opt = this.normalizedOptions.find(o => o.value === this.selected[0]);
return o return opt ? addSuffix(opt.text) : '';
? o.text + (this.suffix ? ' ' + this.suffix : '')
: '';
} }
// more than one selected
return `${count} ausgewählt`; return `${count} ausgewählt`;
},
hasSelection() {
if (this.multiple) {
return Array.isArray(this.selected) && this.selected.length > 0;
} }
// single select return this.selected !== null && this.selected !== undefined && this.selected !== '';
const sel = this.normalizedOptions.find(o => o.value === this.selected);
return sel
? sel.text + (this.suffix ? ' ' + this.suffix : '')
: '';
} }
}, },
@@ -116,7 +95,7 @@ Vue.component('tt-select', {
}, },
onClickOutside(e) { onClickOutside(e) {
if (!this.$el.contains(e.target)) { if (this.$el && !this.$el.contains(e.target)) {
this.open = false; this.open = false;
} }
}, },
@@ -129,111 +108,80 @@ Vue.component('tt-select', {
selectOption(opt) { selectOption(opt) {
if (opt.disabled) return; if (opt.disabled) return;
if (this.multiple) {
const arr = Array.isArray(this.selected) ? [...this.selected] : [];
const idx = arr.indexOf(opt.value);
if (idx > -1) arr.splice(idx, 1);
else arr.push(opt.value);
this.selected = arr; if (this.multiple) {
this.$emit('input', arr); const newSelection = Array.isArray(this.selected) ? [...this.selected] : [];
const index = newSelection.indexOf(opt.value);
if (index > -1) {
newSelection.splice(index, 1);
} else {
newSelection.push(opt.value);
}
this.selected = newSelection;
} else { } else {
this.selected = opt.value; this.selected = opt.value;
this.$emit('input', opt.value); this.open = false; // Close on selection for single mode
this.open = false;
} }
this.$emit('input', this.selected);
}, },
// Enhancement: Handle Enter key press on search input
handleEnter() { handleEnter() {
// 4. If search is active and only one result is left, select it
if (this.searchQuery && this.filteredOptions.length === 1) { if (this.searchQuery && this.filteredOptions.length === 1) {
this.selectOption(this.filteredOptions[0]); this.selectOption(this.filteredOptions[0]);
// Ensure dropdown closes for both single and multi-select mode if (!this.multiple) this.open = false;
this.open = false;
} }
} }
}, },
template: ` template: `
<div class="form-group" :class="{ row: row }"> <div class="form-group" :class="[{ 'row': row }, 'tt-select-modern']">
<label v-if="label" <label v-if="label" :for="'tt-select-' + _uid"
:for="label" :class="['col-form-label', { 'col-sm-4': row, 'col-form-label-sm': sm && row }]">
:class="{
'col-form-label': row,
'col-sm-4': row,
'col-form-label-sm': sm && row
}">
{{ label }} {{ label }}
</label> </label>
<div :class="row ? 'col-sm-8' : ''"> <div :class="{ 'col-sm-8 p-0': row }">
<div class="dropdown" :class="{ show: open }"> <div class="tt-select-container">
<button type="button" <button type="button" class="tt-select-trigger"
class="btn btn-outline-secondary form-control" :id="'tt-select-' + _uid"
:class="{ 'form-control-sm': sm, 'btn-sm': sm }" :class="{ 'sm': sm, 'open': open }"
:disabled="disabled" :disabled="disabled"
@click.stop="toggleDropdown" @click.stop="toggleDropdown">
style="display:flex; align-items:center;"> <span class="trigger-text" :class="{'placeholder': !hasSelection}">{{ displayText }}</span>
<span style=" <i class="fas fa-chevron-down trigger-arrow"></i>
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
text-align: left;
">
{{ displayText || 'Auswählen...' }}
</span>
<i class="fas fa-chevron-down ml-2"></i>
</button> </button>
<div class="dropdown-menu p-2" <div class="tt-select-dropdown" :class="{ show: open }" @click.stop>
ref="dropdownMenu" <div class="dropdown-header">
:class="{ show: open }" <span>{{ label || 'Auswählen' }}</span>
style=" <button type="button" class="close-btn" @click="toggleDropdown">&times;</button>
min-width: 100%;
max-width: 400px;
max-height: 300px;
overflow-y: auto;
">
<input v-if="searchable"
ref="searchInput"
type="text"
class="form-control mb-2"
v-model="searchQuery"
:disabled="disabled"
placeholder="Suchen..."
@keydown.enter.prevent="handleEnter">
<div v-if="!filteredOptions.length && searchQuery" class="dropdown-item disabled text-muted">
Keine Ergebnisse gefunden.
</div> </div>
<div v-for="opt in filteredOptions" <div v-if="searchable" class="search-input-wrapper">
:key="opt.value" <input ref="searchInput" type="text" class="search-input"
class="dropdown-item px-2 py-1" v-model="searchQuery" :disabled="disabled" placeholder="Suchen..."
:class="{ disabled: opt.disabled }" @keydown.enter.prevent="handleEnter">
@click.stop> </div>
<label class="d-flex align-items-center m-0 w-100" style="cursor: pointer;">
<input v-if="multiple" <ul class="options-list" ref="optionsList">
type="checkbox" <li v-if="!filteredOptions.length" class="no-results">
class="form-check-input mr-2" Keine Ergebnisse gefunden.
:checked="isSelected(opt)" </li>
:disabled="opt.disabled" <li v-for="opt in filteredOptions" :key="opt.value"
@change.prevent="selectOption(opt)"> class="option-item"
<input v-else :class="{ 'selected': isSelected(opt), 'disabled': opt.disabled }"
type="radio" @click="selectOption(opt)">
class="form-check-input mr-2" <div class="option-label">
:name="label" <input :type="multiple ? 'checkbox' : 'radio'"
:name="'option-' + _uid"
:value="opt.value" :value="opt.value"
:checked="isSelected(opt)" :checked="isSelected(opt)"
:disabled="opt.disabled" :disabled="opt.disabled">
@change.prevent="selectOption(opt)"> <span>{{ opt.text }}<span v-if="suffix"> {{ suffix }}</span></span>
<span>
{{ opt.text }}<span v-if="suffix"> {{ suffix }}</span>
</span>
</label>
</div> </div>
<i v-if="isSelected(opt)" class="fas fa-check option-checkmark"></i>
</li>
</ul>
</div> </div>
</div> </div>
</div> </div>
@@ -107,9 +107,17 @@ Vue.component('tt-table-crud', {
const response = await axios.post(this.crudModalData.id ? window['TT_CONFIG']['UPDATE_URL'] : window['TT_CONFIG']['CREATE_URL'], const response = await axios.post(this.crudModalData.id ? window['TT_CONFIG']['UPDATE_URL'] : window['TT_CONFIG']['CREATE_URL'],
this.crudModalData); this.crudModalData);
if (response.data.success) { if (response.data.success) {
this.$refs.table.refreshTable();
this.resetCrudModalData();
this.window.notify('success', response.data.message || 'Erfolgreich gespeichert'); this.window.notify('success', response.data.message || 'Erfolgreich gespeichert');
if (this.crudConfig.reopenOnCreate && !this.crudModalData.id) {
this.resetCrudModalData();
const getByIdUrl = window['TT_CONFIG']['GET_BY_ID_URL'] || `${window['TT_CONFIG']['BASE_PATH']}/${this.crudConfig.key}/getById`;
const getByIdResponse = await axios.get(getByIdUrl, {params: {id: response.data.id}});
this.crudModalData = getByIdResponse.data;
this.crudModal = true;
} else {
this.resetCrudModalData();
this.$refs.table.refreshTable();
}
} else { } else {
this.window.notify('error', this.window.notify('error',
response.data.errors ? Object.values(response.data.errors).join('<br>') : response.data.message || 'Ein Fehler ist aufgetreten'); response.data.errors ? Object.values(response.data.errors).join('<br>') : response.data.message || 'Ein Fehler ist aufgetreten');
@@ -179,6 +187,7 @@ Vue.component('tt-table-crud', {
tableConfig() { tableConfig() {
return { return {
key: this.crudConfig.key, key: this.crudConfig.key,
customRowClass: this.crudConfig.customRowClass,
tableHeader: this.crudConfig.tableHeader, tableHeader: this.crudConfig.tableHeader,
headers: this.crudConfig.columns.filter(column => column.table !== false).map(column => { headers: this.crudConfig.columns.filter(column => column.table !== false).map(column => {
return {text: column.text, key: column.key, ...column.table, filterOptions: column?.table?.filterOptions ?? column?.modal?.items ?? [], priority: column.priority} return {text: column.text, key: column.key, ...column.table, filterOptions: column?.table?.filterOptions ?? column?.modal?.items ?? [], priority: column.priority}
+6 -6
View File
@@ -201,9 +201,9 @@ Vue.component('tt-table', {
.isValid() ? moment.unix(row[key]).format('DD.MM.YYYY HH:mm') : moment(row[key]) .isValid() ? moment.unix(row[key]).format('DD.MM.YYYY HH:mm') : moment(row[key])
.format('DD.MM.YYYY HH:mm')) : '' .format('DD.MM.YYYY HH:mm')) : ''
}}</span> }}</span>
<!-- <i v-else-if="column.filter === 'iconSelect'"--> <i v-else-if="column.filter === 'iconSelect'"
<!-- :title="columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.text"--> :title="columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.text"
<!-- :class="columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.icon"></i>--> :class="columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.icon"></i>
<span v-else-if="column.filter === 'autocomplete'"> <span v-else-if="column.filter === 'autocomplete'">
{{ autoCompleteData[key] && autoCompleteData[key][row[key]] ? autoCompleteData[key][row[key]]['title'] : row[key] }} {{ autoCompleteData[key] && autoCompleteData[key][row[key]] ? autoCompleteData[key][row[key]]['title'] : row[key] }}
@@ -236,9 +236,9 @@ Vue.component('tt-table', {
}}</span> }}</span>
<span v-else-if="column.filter === 'select'">{{ columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.text }}</span> <span v-else-if="column.filter === 'select'">{{ columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.text }}</span>
<span v-else-if="key === 'create'">{{ window.moment(row[key] * 1000).format('DD.MM.YYYY HH:mm:ss') }}</span> <span v-else-if="key === 'create'">{{ window.moment(row[key] * 1000).format('DD.MM.YYYY HH:mm:ss') }}</span>
<!-- <i v-else-if="column.filter === 'iconSelect'"--> <i v-else-if="column.filter === 'iconSelect'"
<!-- :title="columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.text"--> :title="columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.text"
<!-- :class="columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.icon"></i>--> :class="columns[key].filterOptions.find(option => option.value.toString() === row[key].toString())?.icon"></i>
<span v-else-if="column.filter === 'autocomplete'"> <span v-else-if="column.filter === 'autocomplete'">
{{ autoCompleteData[key] && autoCompleteData[key][row[key]] ? autoCompleteData[key][row[key]]['title'] : row[key] }}</span> {{ autoCompleteData[key] && autoCompleteData[key][row[key]] ? autoCompleteData[key][row[key]]['title'] : row[key] }}</span>
@@ -0,0 +1,88 @@
<?php
require("../../config/config.php");
define('FRONKDB_SQLDEBUG', false);
error_reporting(E_ALL & ~(E_NOTICE | E_STRICT | E_DEPRECATED));
require_once(LIBDIR . "/mvcfronk/mfRouter/mfRouter.php");
require_once(LIBDIR . "/mvcfronk/mfBase/mfBaseModel.php");
require_once(LIBDIR . "/mvcfronk/mfBase/mfBaseController.php");
$me = new User(154);
define("INTERNAL_USER_ID", $me->id);
define("INTERNAL_USER_USERNAME", $me->username);
$calendar = CalendarModel::search(array("checkSubscriptions" => 1));
$adminUser = array(89, 173, 167, 8, 6, 9, 5, 123);
$addcalendararray = array(38, 39);
foreach ($calendar as $cal) {
$data = [];
$update = 0;
$allCalendarUser = $allCalendar;
unset($newrights);
if (in_array($cal->user_id, $adminUser)) {
$admin = 1;
} else {
$admin = 0;
}
$insert = 1;
$rights = json_decode($cal->rights, true);
$groups = json_decode($cal->groups, true);
foreach ($addcalendararray as $addcal) {
foreach ($rights as $key => $right) {
if ($key == $addcal) {
$insert = 0;
break;
}
}
if ($insert == 1) {
if ($admin == 1) {
$rights[$addcal] = "all";
} else {
$rights[$addcal] = "read";
}
foreach ($groups as $key => $group) {
if ($group['name'] == "Persönlich") {
$count = count($groups[$key]['calendars']);
$groups[$key]['calendars'][$count]['calendar_id'] = $addcal;
$groups[$key]['calendars'][$count]['checked'] = 0;
$groups[$key]['calendars'][$count]['origin'] = 1;
break;
}
}
}
}
// echo $insert;
// var_dump($groups);
if (!$groups) {
echo $cal->user_id;
}
if ($insert == 1) {
if ($groups) {
$data['groups'] = json_encode($groups, JSON_UNESCAPED_UNICODE);
}
$data['rights'] = json_encode($rights, JSON_UNESCAPED_UNICODE);
// var_dump(json_encode($groups, JSON_UNESCAPED_UNICODE));
// var_dump(json_encode($rights, JSON_UNESCAPED_UNICODE));
$cal->update($data);
echo "save" . $cal->id . "\n";
$cal->save();
}
}