0% found this document useful (0 votes)
14 views4 pages

Server Js

The document outlines the implementation of an API endpoint for fetching available appointments based on a state ID. It includes error handling for fetching booked appointments and a function for submitting inspection requests with form data. The server is set to run on a specified port, and the code includes logging for debugging purposes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views4 pages

Server Js

The document outlines the implementation of an API endpoint for fetching available appointments based on a state ID. It includes error handling for fetching booked appointments and a function for submitting inspection requests with form data. The server is set to run on a specified port, and the code includes logging for debugging purposes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

cd "C:\Users\asus2\OneDrive\Desktop\vehicle_inspection-backend"

‫ تعديل نقطة نهاية‬API ‫ تأكد من أن نقطة نهاية‬:‫لجلب المواعيد حسب الوالية‬


/api/available_appointments ‫ في الواجهة الخلفية يمكنها استقبال معلمة‬state_id
‫واالستعالم عن قاعدة البيانات بناًء عليها‬.

// ‫نقطة نهاية لجلب المواعيد المتاحة والمحجوزة‬


console.log('Attempting to define /api/available_appointments route...');

app.get('/api/available_appointments', async (req, res) => {


console.log('Received request at /api/available_appointments');
try {
const availableAndBooked = await
appointmentUtils.getAvailableAppointments(pool);
console.log('Data from getAvailableAppointments:', availableAndBooked); //
‫أضف هذا السطر‬
res.json(availableAndBooked);
} catch (error) {
console.error('Error fetching available appointments:', error);
res.status(500).json({ error: 'Failed to fetch available appointments.' });
}
});

console.log('/api/available_appointments route defined.');

// ... (‫ بقية تعريفات المسارات أو أي كود آخر في‬server.js) ...

app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});

async function getAvailableAppointments(pool, startDate = new Date(), numberOfDays


= 30, intervalMinutes = 15) {
const allPossibleAppointments = generateWeeklyAvailableAppointments(startDate,
numberOfDays, intervalMinutes);
const bookedAppointments = [];

try {
const [rows] = await pool.execute('SELECT DATE_FORMAT(appointment_date,
"%Y-%m-%d %H:%i") AS appointment_date FROM inspection_requests WHERE
appointment_date >= CURDATE()');
rows.forEach(row => {
bookedAppointments.push(row.appointment_date);
});
} catch (error) {
console.error('Error fetching booked appointments:', error);
return { available: [], booked: [] };
}

const bookedSet = new Set(bookedAppointments);

const availableAppointments = [];


allPossibleAppointments.forEach(day => {
const availableSlotsForDay = day.slots.filter(slot => {
const fullDateTime = `${day.date} ${slot}`;
return !bookedSet.has(fullDateTime);
}).map(slot => ({ time: slot }));

if (availableSlotsForDay.length > 0) {
availableAppointments.push({ date: day.date, slots:
availableSlotsForDay });
}
});

const bookedAppointmentsFormatted = bookedAppointments.map(booked => {


const [date, time] = booked.split(' ');
return { date, time, status: 'booked' };
});

return { available: availableAppointments, booked:


bookedAppointmentsFormatted };
}

module.exports = {
generateWeeklyAvailableAppointments,
getAvailableAppointments
};

async function handleSubmit(event) {


console.log('‫ تم استدعاء‬handleSubmit - ‫;)'البداية‬
console.log('‫نوع الحدث‬:', event.type);
event.preventDefault(); // ‫منع إعادة تحميل الصفحة‬
console.log('‫;)'تم منع السلوك االفتراضي للحدث‬

const submitButton = event.target.querySelector('button[type="submit"]');


if (submitButton) {
console.log('‫;)'تم العثور على زر الإرسال‬
submitButton.disabled = true;
submitButton.textContent = '‫جاٍر الإرسال‬...';
console.log('‫;)'تم تعطيل الزر وتغيير النص‬
} else {
console.log('‫;)'!لم يتم العثور على زر الإرسال‬
}

console.log('‫بيانات النموذج قبل الإرسال‬:', {


vehicle_owner_name: document.getElementById('vehicleOwnerNameInput').value,
location: document.getElementById('locationInput').value,
state:
document.getElementById('stateSelect').options[document.getElementById('stateSelect
').selectedIndex].textContent,
state_id: document.getElementById('stateSelect').value,
form_date: document.getElementById('formDateInput').value,
vehicle_category: document.getElementById('vehicleCategoryInput').value,
vehicle_type: document.getElementById('vehicleTypeInput').value,
vehicle_model_version:
document.getElementById('vehicleModelVersionInput').value,
vehicle_chassis: document.getElementById('vehicleChassisInput').value,
vehicle_energy_type:
document.getElementById('vehicleEnergyTypeInput').value,
vehicle_power: document.getElementById('vehiclePowerInput').value,
vehicle_first_use_year:
document.getElementById('vehicleFirstUseYearInput').value,
vehicle_registration_number:
document.getElementById('vehicleRegistrationNumberInput').value,
vehicle_previous_registration_number:
document.getElementById('vehiclePreviousRegistrationNumberInput').value,
vehicle_authorized_load:
document.getElementById('vehicleAuthorizedLoadInput').value,
vehicle_running_load:
document.getElementById('vehicleRunningLoadInput').value,
vehicle_limited_load:
document.getElementById('vehicleLimitedLoadInput').value,
vehicle_vin: document.getElementById('vehicleVinInput').value,
vehicle_mining_model:
document.getElementById('vehicleMiningModelInput').value,
vehicle_section_id: document.getElementById('vehicleSectionIdInput').value,
report_type_id: document.getElementById('reportTypeSelect').value,
appointment_date: document.getElementById('selectedAppointment').value,
});

console.log('‫جاٍر إرسال الطلب‬...');

try {
const response = await
fetch('http://localhost:3001/api/inspection_requests', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
console.log('‫ االستجابة‬،‫تم إرسال الطلب‬:', response);

if (response.ok) {
const responseData = await response.json();
console.log('‫تم إرسال الطلب بنجاح‬:', responseData);
window.location.href = `Confirm_inspection_request_form.html?
requestId=${responseData.requestId}&registrationCode=$
{responseData.registrationCode}&appointmentDate=$
{responseData.appointmentDate}&stateName=${formData.state}`;
console.log('‫;)'تمت إعادة التوجيه‬
} else {
const errorData = await response.json();
console.error('‫فشل إرسال الطلب‬:', errorData);
// ‫عرض رسالة خطأ للمستخدم‬
}
} catch (error) {
console.error('‫حدث خطأ أثناء إرسال الطلب‬:', error);
// ‫عرض رسالة خطأ للمستخدم‬
} finally {
if (submitButton && !submitButton.hasAttribute('data-original-text')) {
submitButton.setAttribute('data-original-text',
submitButton.textContent);
}
if (submitButton) {
submitButton.disabled = false;
submitButton.textContent = submitButton.getAttribute('data-original-
text') || '‫;'إرسال طلب الفحص‬
console.log('‫;)'تم تمكين الزر واستعادة النص‬
}
console.log('‫ انتهاء‬handleSubmit - ‫;)'النهاية‬
}
}

You might also like