This commit is contained in:
Dvorinka
2025-06-20 11:59:42 +02:00
parent b0cf7b77d5
commit c3d30d7918
2 changed files with 134 additions and 151 deletions
+41 -49
View File
@@ -154,13 +154,18 @@
</div> </div>
</div> </div>
</div> </div>
<!-- Reservation Details (Hidden by default) --> <!-- Auto-filled from reservation -->
<div id="reservationDetails" class="hidden space-y-4"> <div id="reservationInfo" class="mt-4 p-4 bg-gray-50 rounded-lg hidden">
<div class="bg-blue-50 p-4 rounded-lg"> <h3 class="text-sm font-medium text-gray-600 mb-2">Informace z rezervace</h3>
<h3 class="text-blue-700 font-semibold mb-2">Informace o rezervaci:</h3> <div class="space-y-2">
<div id="reservationInfo" class="space-y-2"> <div>
<!-- Reservation info will be populated here --> <label class="block text-sm font-medium text-gray-500">Datum a čas odjezdu</label>
<div id="reservationStart" class="text-sm text-gray-700"></div>
</div>
<div>
<label class="block text-sm font-medium text-gray-500">Datum a čas příjezdu</label>
<div id="reservationEnd" class="text-sm text-gray-700"></div>
</div> </div>
</div> </div>
</div> </div>
@@ -369,47 +374,34 @@
const timeEnd = document.getElementById('time_end'); const timeEnd = document.getElementById('time_end');
const dateStart = document.getElementById('date_start'); const dateStart = document.getElementById('date_start');
const dateEnd = document.getElementById('date_end'); const dateEnd = document.getElementById('date_end');
const reservationDetails = document.getElementById('reservationDetails');
const reservationInfo = document.getElementById('reservationInfo'); const reservationInfo = document.getElementById('reservationInfo');
const currentReservationId = new URLSearchParams(window.location.search).get('reservationId'); const reservationStart = document.getElementById('reservationStart');
const reservationEnd = document.getElementById('reservationEnd');
let debounceTimer; // Check for pre-filled data from reservation
window.addEventListener('load', () => {
// Set default dates to today const preFilledData = localStorage.getItem('preFilledEvidence');
const today = new Date(); if (preFilledData) {
const yyyy = today.getFullYear(); const data = JSON.parse(preFilledData);
const mm = String(today.getMonth() + 1).padStart(2, '0');
const dd = String(today.getDate()).padStart(2, '0'); // Fill form fields
const todayStr = `${yyyy}-${mm}-${dd}`; document.getElementById('name').value = data.driverName;
document.getElementById('vehicle').value = data.vehicle;
document.getElementById('date_start').value = todayStr; dateStart.value = data.date_start;
document.getElementById('date_end').value = todayStr; timeStart.value = data.time_start;
dateEnd.value = data.date_end;
// Event handlers timeEnd.value = data.time_end;
destinationInput.addEventListener('input', function() {
clearTimeout(debounceTimer); // Show reservation info
debounceTimer = setTimeout(() => { reservationInfo.classList.remove('hidden');
const query = destinationInput.value.trim(); reservationStart.textContent = `${data.date_start} ${data.time_start}`;
if (query.length >= 3) { reservationEnd.textContent = `${data.date_end} ${data.time_end}`;
fetchSuggestions(query);
} else { // Clear pre-filled data from localStorage
suggestionsList.style.display = 'none'; localStorage.removeItem('preFilledEvidence');
} }
}, 300);
}); });
destinationInput.addEventListener('focus', function() {
if (destinationInput.value.trim().length >= 3) {
suggestionsList.style.display = 'block';
}
});
document.addEventListener('click', function(e) {
if (!destinationInput.contains(e.target) && !suggestionsList.contains(e.target)) {
suggestionsList.style.display = 'none';
}
});
// Suggestions API // Suggestions API
async function fetchSuggestions(query) { async function fetchSuggestions(query) {
try { try {
@@ -421,13 +413,13 @@
} }
const data = await response.json(); const data = await response.json();
displaySuggestions(data.items); return data.items;
} catch (error) { } catch (error) {
console.error('Error fetching suggestions:', error); console.error('Error fetching suggestions:', error);
showMessage('Chyba při načítání našeptávače.', 'error'); showMessage('Chyba při načítání našeptávače.', 'error');
} }
} }
function displaySuggestions(items) { function displaySuggestions(items) {
suggestionsList.innerHTML = ''; suggestionsList.innerHTML = '';
@@ -449,7 +441,7 @@
suggestionsList.style.display = 'none'; suggestionsList.style.display = 'none';
} }
} }
function selectSuggestion(item) { function selectSuggestion(item) {
destinationInput.value = item.name; destinationInput.value = item.name;
@@ -461,7 +453,7 @@
suggestionsList.style.display = 'none'; suggestionsList.style.display = 'none';
} }
// Calculate distance // Calculate distance
function calculateDistance() { function calculateDistance() {
const start = parseInt(kmStart.value) || 0; const start = parseInt(kmStart.value) || 0;
@@ -478,7 +470,7 @@
totalDistance.classList.remove('text-red-600'); totalDistance.classList.remove('text-red-600');
} }
} }
// Calculate time difference // Calculate time difference
function calculateTime() { function calculateTime() {
if (!timeStart.value || !timeEnd.value || !dateStart.value || !dateEnd.value) { if (!timeStart.value || !timeEnd.value || !dateStart.value || !dateEnd.value) {
+93 -102
View File
@@ -1092,10 +1092,6 @@
class="bg-brand-blue hover:bg-brand-light-blue text-white font-bold py-2 px-6 rounded-lg shadow transition-all duration-200"> class="bg-brand-blue hover:bg-brand-light-blue text-white font-bold py-2 px-6 rounded-lg shadow transition-all duration-200">
Vytvořit rezervaci Vytvořit rezervaci
</button> </button>
<button type="button" id="createEvidence"
class="bg-brand-light-blue hover:bg-brand-blue text-white font-bold py-2 px-6 rounded-lg shadow transition-all duration-200 ml-4">
Vytvořit záznam jízdy
</button>
</div> </div>
</form> </form>
@@ -1349,33 +1345,46 @@
reservationForm.addEventListener('submit', async function(e) { reservationForm.addEventListener('submit', async function(e) {
e.preventDefault(); e.preventDefault();
// Get form values
const driverName = document.getElementById('driverName').value; const driverName = document.getElementById('driverName').value;
const vehicle = document.getElementById('vehicle').value;
const startDate = document.getElementById('startDate').value;
const startTime = document.getElementById('startTime').value;
const endDate = document.getElementById('endDate').value;
const endTime = document.getElementById('endTime').value;
const purpose = document.getElementById('purpose').value;
// Validate form
if (!validateDriverName(driverName)) { if (!validateDriverName(driverName)) {
showMessage('Prosím zadejte platné jméno a příjmení', 'error'); showMessage('Prosím zadejte platné jméno a příjmení', 'error');
return; return;
} }
try { const startDateInput = document.getElementById('startDate');
// Prepare reservation data const startTimeInput = document.getElementById('startTime');
const reservationData = { const endDateInput = document.getElementById('endDate');
driverName: driverName, const endTimeInput = document.getElementById('endTime');
vehicle: vehicle,
startDate: startDate, const startDateTime = parseDateTimeInputs(startDateInput, startTimeInput);
startTime: startTime, const endDateTime = parseDateTimeInputs(endDateInput, endTimeInput);
endDate: endDate,
endTime: endTime, // Validate dates
purpose: purpose if (endDateTime <= startDateTime) {
}; showMessage('Konec rezervace musí být po začátku', 'error');
return;
}
// Check availability one last time
const isAvailable = await checkAvailabilityAndTraffic();
if (!isAvailable) {
showMessage('Vozidlo již není k dispozici v tomto čase', 'error');
return;
}
// Prepare reservation data
const reservationData = {
driverName: document.getElementById('driverName').value,
vehicle: document.getElementById('vehicle').value,
startDate: formatDateForAPI(startDateTime),
startTime: formatTimeForAPI(startDateTime),
endDate: formatDateForAPI(endDateTime),
endTime: formatTimeForAPI(endDateTime),
purpose: document.getElementById('purpose')?.value || ''
};
try {
const response = await fetch('/api/reservations', { const response = await fetch('/api/reservations', {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -1448,6 +1457,9 @@
const calendarEl = document.getElementById('calendar'); const calendarEl = document.getElementById('calendar');
let selectedVehicle = 'all'; let selectedVehicle = 'all';
let calendar; // Make calendar global let calendar; // Make calendar global
// Update reservations list when page loads
updateReservationsList();
// Fix calendar initialization // Fix calendar initialization
@@ -1916,90 +1928,69 @@
const startTime = document.getElementById('startTime').value; const startTime = document.getElementById('startTime').value;
const endDate = document.getElementById('endDate').value; const endDate = document.getElementById('endDate').value;
const endTime = document.getElementById('endTime').value; const endTime = document.getElementById('endTime').value;
const purpose = document.getElementById('purpose').value; const purpose = document.getElementById('purpose')?.value || '';
// Validate required fields // Validate form
if (!driverName || !vehicle || !startDate || !startTime || !endDate || !endTime) { if (!validateDriverName(driverName)) {
showMessage('Prosím vyplňte všechna povinná pole.', 'error'); showMessage('Prosím zadejte platné jméno a příjmení', 'error');
return; return;
} }
// Check if end time is after start time try {
const startDateTime = new Date(`${startDate}T${startTime}`); // Prepare reservation data
const endDateTime = new Date(`${endDate}T${endTime}`); const reservationData = {
if (endDateTime <= startDateTime) { driverName: driverName,
showMessage('Datum a čas příjezdu musí být pozdější než datum a čas odjezdu.', 'error'); vehicle: vehicle,
return; startDate: startDate,
startTime: startTime,
endDate: endDate,
endTime: endTime,
purpose: purpose
};
const response = await fetch('/api/reservations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(reservationData)
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
// Store reservation ID in localStorage
const userReservations = JSON.parse(localStorage.getItem('userReservations') || '[]');
userReservations.push(result.id);
localStorage.setItem('userReservations', JSON.stringify(userReservations));
// Add the new event to the calendar
calendar.addEvent({
id: result.id,
title: `${result.vehicle} - ${result.driverName}`,
start: `${result.startDate}T${result.startTime}`,
end: `${result.endDate}T${result.endTime}`,
extendedProps: {
driverName: result.driverName,
vehicle: result.vehicle,
purpose: result.purpose
}
});
// Reset form and close modal
reservationForm.reset();
document.getElementById('reservationModal').style.display = 'none';
showMessage('Rezervace byla úspěšně vytvořena', 'success');
} catch (error) {
console.error('Error:', error);
showMessage('Nepodařilo se vytvořit rezervaci', 'error');
} }
// Save to localStorage
const reservationData = {
id: Date.now().toString(),
driverName,
vehicle,
startDate,
startTime,
endDate,
endTime,
purpose,
created: new Date().toISOString()
};
// Get existing reservations or initialize empty array
let reservations = JSON.parse(localStorage.getItem('reservations') || '[]');
// Add new reservation
reservations.push(reservationData);
localStorage.setItem('reservations', JSON.stringify(reservations));
// Show success message
showMessage('Rezervace byla úspěšně vytvořena!', 'success');
// Close modal
document.getElementById('reservationModal').style.display = 'none';
// Refresh calendar
calendar.refetchEvents();
updateReservationsList();
}); });
// Handle evidence creation button
document.getElementById('createEvidence').addEventListener('click', async function() {
const driverName = document.getElementById('driverName').value;
const vehicle = document.getElementById('vehicle').value;
const startDate = document.getElementById('startDate').value;
const startTime = document.getElementById('startTime').value;
const endDate = document.getElementById('endDate').value;
const endTime = document.getElementById('endTime').value;
// Store reservation ID in localStorage
const reservations = JSON.parse(localStorage.getItem('reservations') || '[]');
const latestReservation = reservations[reservations.length - 1];
if (!latestReservation) {
showMessage('Nejdřív vytvořte rezervaci.', 'error');
return;
}
// Check if current user owns this reservation
const userReservations = JSON.parse(localStorage.getItem('userReservations') || '[]');
if (!userReservations.includes(latestReservation.id)) {
showMessage('Tuto rezervaci nemůžete použít pro vytvoření záznamu jízdy.', 'error');
return;
}
// Store reservation ID in localStorage
localStorage.setItem('currentReservationId', latestReservation.id);
// Redirect to evidence page with prefilled data
window.location.href = `evidence-aut.html?reservationId=${latestReservation.id}`;
});
// Initialize userReservations in localStorage if not exists
if (!localStorage.getItem('userReservations')) {
localStorage.setItem('userReservations', JSON.stringify([]));
}
// Make calendar events clickable // Make calendar events clickable
calendar.on('eventClick', function(info) { calendar.on('eventClick', function(info) {
showEventModal(info.event); showEventModal(info.event);