source: src/main/resources/static/js/calendar.js

Last change on this file was 43c9090, checked in by macagaso <gasoskamarija@…>, 5 weeks ago

Updated version

  • Property mode set to 100644
File size: 7.5 KB
RevLine 
[43c9090]1let lastClickedItem=null;
[743de55]2let calendar = document.querySelector('.calendar')
3
4const month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
5function showModal() {
6 const modal = document.getElementById('confirmation-modal');
7 modal.classList.add('modal');
8 modal.style.display = 'block';
9}
10document.getElementById("cancel-booking").addEventListener("click", function() {
11 window.location.reload();
12});
13
14document.getElementById('book-button').addEventListener('click', () => {
15 if (!window.selectedTime) {
16 alert('Please select an appointment time.');
17 return;
18 }
19 else{
20 document.getElementById("last-check").innerHTML=window.selectedTime;
21 showModal();
[43c9090]22 document.getElementById("coupon-type").selectedIndex=0;
23 document.getElementById("medical-condition").innerHTML='';
24
[743de55]25 }
26
27});
28
29document.getElementById("confirm-booking").addEventListener("click",function(){
30
31 const termData={
32 term: window.selectedTime,
33 couponCode: document.getElementById("coupon-type").value,
34 medicalCondition:document.getElementById("medical-condition").value
35 };
36 fetch('/api/requests/book', {
37 method: 'POST',
38 headers: {
39 'Content-Type': 'application/json'
40 },
41 body: JSON.stringify(termData)
42 })
43 .then(response => {
44 if (response.ok) {
45 alert('Appointment booked successfully!');
46 document.getElementById('confirmation-modal').style.display = 'none';
47 window.selectedTime = null;
48 document.getElementById('book-button').disabled = true;
49 } else {
50 alert('Failed to book the appointment.');
51 }
52 })
53 .catch(error => {
54 console.error('Error:', error);
55 alert('An error occurred while booking the appointment.');
56 });
57});
58
59isLeapYear = (year) => {
60 return (year % 4 === 0 && year % 100 !== 0 && year % 400 !== 0) || (year % 100 === 0 && year % 400 ===0)
61}
62
63getFebDays = (year) => {
64 return isLeapYear(year) ? 29 : 28
65}
66function fetchFreeOrPendingAppointments(date) {
67 fetch(`/api/appointments/free?date=${date}`)
68 .then(response => response.json())
69 .then(data => {
70 console.log(data);
71 displayFreeAppointments(data);
72 })
73 .catch(error => console.error('Error fetching free appointments:', error));
74}
75function displayFreeAppointments(appointments) {
76 const container = document.getElementById('hourly-terms');
[43c9090]77 container.innerHTML = '';
[743de55]78
79 appointments.forEach(appointment => {
80 const appointmentDiv = document.createElement('div');
81 appointmentDiv.classList.add('appointment-item');
82 appointmentDiv.style.border = '1px solid black';
83 appointmentDiv.style.padding = '20px';
84 appointmentDiv.style.display = 'inline-block';
85 appointmentDiv.style.marginRight = '10px';
86
87 const appointmentDate = new Date(appointment.term);
88 const timeOptions = { hour: '2-digit', minute: '2-digit', hour12: false };
89 const dateOptions = { year: 'numeric', month: '2-digit', day: '2-digit' };
90 const formattedTime = appointmentDate.toLocaleTimeString([], timeOptions);
91 const formattedDate=appointmentDate.toLocaleDateString('en-CA', dateOptions);
92
93 appointmentDiv.textContent = formattedTime;
[43c9090]94 appointmentDiv.dataset.time = formattedDate+" "+formattedTime;
[743de55]95
96 appointmentDiv.addEventListener('click', () => {
[43c9090]97 if(lastClickedItem){
98 lastClickedItem.style.backgroundColor="white";
99 }
100 lastClickedItem=appointmentDiv;
101 lastClickedItem.style.backgroundColor="grey";
[743de55]102 window.selectedTime = appointmentDiv.dataset.time;
103 document.getElementById('book-button').disabled = false;
104 });
105
106 container.appendChild(appointmentDiv);
107 });
108}
109
110generateCalendar = (month, year) => {
111
112 let calendar_days = calendar.querySelector('.calendar-days')
113 let calendar_header_year = calendar.querySelector('#year')
114
115 let days_of_month = [31, getFebDays(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
116
117 calendar_days.innerHTML = ''
118
119 let currDate = new Date()
[43c9090]120
121 if (typeof month !== 'number') month = currDate.getMonth();
[743de55]122 if (!year) year = currDate.getFullYear()
123
124 let curr_month = `${month_names[month]}`
125 month_picker.innerHTML = curr_month
126 calendar_header_year.innerHTML = year
127
128
129 let first_day = new Date(year, month, 1)
130
131 for (let i = 0; i <= days_of_month[month] + first_day.getDay() - 1; i++) {
132 let day = document.createElement('div')
133 if (i >= first_day.getDay()) {
134 day.classList.add('calendar-day-hover')
135 day.innerHTML = i - first_day.getDay() + 1;
136 day.innerHTML += `<span></span>
137 <span></span>
138 <span></span>
139 <span></span>`;
140 let selectedDate = `${year}-${(month + 1).toString().padStart(2, '0')}-${(i - first_day.getDay() + 1).toString().padStart(2, '0')}`;
[43c9090]141 day.addEventListener('click', () => {
142 let temp=document.getElementsByClassName('curr-date');
143 Array.from(temp).forEach(element => {
144 element.classList.remove('curr-date');
145 });
146 day.classList.add('curr-date');
147 document.getElementById("coupon-type").selectedIndex=0;
148 document.getElementById("medical-condition").value='';
149 fetchFreeOrPendingAppointments(selectedDate);
150 })
[743de55]151
152 if (i - first_day.getDay() + 1 === currDate.getDate() && year === currDate.getFullYear() && month === currDate.getMonth()) {
153 day.classList.add('curr-date')
154 }
155 }
156 calendar_days.appendChild(day)
157 }
158}
159
160let month_list = calendar.querySelector('.month-list')
161
162month_names.forEach((e, index) => {
163 let month = document.createElement('div')
164 month.innerHTML = `<div data-month="${index}">${e}</div>`
165 month.querySelector('div').onclick = () => {
166 month_list.classList.remove('show')
167 curr_month.value = index
168 generateCalendar(index, curr_year.value)
169 }
170 month_list.appendChild(month)
171})
172
173let month_picker = calendar.querySelector('#month-picker')
174
175month_picker.onclick = () => {
176 month_list.classList.add('show')
177}
178
179let currDate = new Date()
180
181let curr_month = {value: currDate.getMonth()}
182let curr_year = {value: currDate.getFullYear()}
183
184generateCalendar(curr_month.value, curr_year.value)
185
186document.querySelector('#prev-year').onclick = () => {
187 --curr_year.value
188 generateCalendar(curr_month.value, curr_year.value)
189}
190
191document.querySelector('#next-year').onclick = () => {
192 ++curr_year.value
193 generateCalendar(curr_month.value, curr_year.value)
194}
195
196
[43c9090]197window.onload = async function () {
198temp=document.getElementById("coupon-type");
199 try{
200 const response = await fetch(`/api/coupons/getCouponNames`);
201 if (response.ok) {
202 const couponNames = await response.json();
203 console.log("Coupons:", couponNames);
204
205 couponNames.forEach(coupon => {
206 const option = document.createElement("option");
207 option.value = coupon;
208 option.textContent = coupon;
209 temp.appendChild(option);
210 });
211 } else {
212 console.log(response.statusText);
213 }
214 }
215 catch(error){
216 console.error("Error fetching coupons:", error);
217 }
[743de55]218
[43c9090]219};
Note: See TracBrowser for help on using the repository browser.