source: src/controllers/appointmentController.js@ 7517a3a

main
Last change on this file since 7517a3a was 7517a3a, checked in by Luka Krstikj <luka.krstik@…>, 16 hours ago

init

  • Property mode set to 100644
File size: 2.6 KB
Line 
1const { appointmentQueries, clientQueries } = require('../models/queries');
2
3exports.bookAppointmentForm = async (req, res) => {
4 try {
5 const { unit_id } = req.params;
6
7 const unitData = await clientQueries.getUnitById(unit_id);
8
9 if (!unitData) {
10 return res.status(404).send('Unit not found');
11 }
12
13 const timeslots = await appointmentQueries.getAvailableTimeslots();
14
15 const agentsMap = {};
16 timeslots.forEach(slot => {
17 if (!agentsMap[slot.agent_id]) {
18 agentsMap[slot.agent_id] = {
19 id: slot.agent_id,
20 name: slot.agent_name,
21 email: slot.email,
22 timeslots: [],
23 };
24 }
25 agentsMap[slot.agent_id].timeslots.push({
26 id: slot.timeslot_id,
27 date: slot.date,
28 time_start: slot.time_start,
29 time_end: slot.time_end,
30 });
31 });
32
33 const agents = Object.values(agentsMap);
34
35 res.render('client/book-appointment', {
36 unit: unitData,
37 agents
38 });
39 } catch (error) {
40 console.error('Error loading booking form:', error);
41 res.status(500).send('Database error');
42 }
43};
44
45exports.bookAppointmentSubmit = async (req, res) => {
46 try {
47 const { unit_id } = req.params;
48 const { client_name, client_email, client_phone, timeslot_id } = req.body;
49
50 const isAvailable = await appointmentQueries.verifyTimeslot(timeslot_id);
51 if (!isAvailable) {
52 return res.status(400).send('This timeslot is no longer available');
53 }
54
55 const unitData = await clientQueries.getUnitById(unit_id);
56 if (!unitData) {
57 return res.status(404).send('Unit not found');
58 }
59
60 const clientId = await appointmentQueries.createClient(
61 client_name,
62 client_email,
63 client_phone
64 );
65
66 const appointmentId = await appointmentQueries.createAppointment(
67 clientId,
68 unit_id,
69 timeslot_id
70 );
71
72 await appointmentQueries.bookTimeslot(timeslot_id);
73
74 res.redirect(`/appointments/${appointmentId}/confirmation`);
75 } catch (error) {
76 console.error('Booking failed —', error.message);
77 res.status(400).send('Could not complete your booking');
78 }
79};
80
81exports.appointmentConfirmation = async (req, res) => {
82 try {
83 const { id } = req.params;
84 const appointment = await appointmentQueries.getAppointmentDetails(id);
85
86 if (!appointment) {
87 return res.status(404).send('Appointment not found');
88 }
89
90 res.render('client/appointment-confirmation', { appointment });
91 } catch (error) {
92 console.error('Error fetching appointment:', error);
93 res.status(500).send('Database error');
94 }
95};
Note: See TracBrowser for help on using the repository browser.