1 |
|
---|
2 | import { deleteAppointment, confirmCarriedOut, getUsersByTermExcept, removeRequestAndUpdateUser, removeAppointment, makeReservation ,displayDiv} from './shared.js';
|
---|
3 | import { verificationCheck } from './authentication-shared.js';
|
---|
4 |
|
---|
5 | let loggedPerson;
|
---|
6 | const modal = document.getElementById('popupModal');
|
---|
7 | const cancelBtn = document.getElementById('cancelBtn');
|
---|
8 | const approveBtn = document.getElementById('approveBtn');
|
---|
9 | const closeSpan = document.querySelector('.close');
|
---|
10 |
|
---|
11 | cancelBtn.addEventListener('click', () => {
|
---|
12 | modal.style.display = 'none';
|
---|
13 | });
|
---|
14 | closeSpan.addEventListener('click', () => {
|
---|
15 | modal.style.display = 'none';
|
---|
16 | });
|
---|
17 |
|
---|
18 | function createAppointmentInfoField(selectedValue){
|
---|
19 | const tableBody = document.getElementById("active-table");
|
---|
20 | tableBody.innerHTML='';
|
---|
21 | let dates;
|
---|
22 | if(selectedValue==='not-completed'){
|
---|
23 | dates=loggedPerson.dates;
|
---|
24 | }
|
---|
25 | else if(selectedValue==='completed'){
|
---|
26 | dates=loggedPerson.carriedOut;
|
---|
27 | }
|
---|
28 | dates.forEach(date => {
|
---|
29 | let row = document.createElement("tr");
|
---|
30 | let tdTerm = document.createElement("td");
|
---|
31 | tdTerm.innerText = date.dateTime.replace('T', ' ').substring(0, 16);
|
---|
32 | let tdTemp1 = document.createElement("td");
|
---|
33 | let tdTemp2 = document.createElement("td");
|
---|
34 | if(selectedValue==='not-completed'){
|
---|
35 | tdTemp1.innerText = date.note;
|
---|
36 | switch(date.status){
|
---|
37 | case "rejected":
|
---|
38 | tdTemp2.innerText = "Одбиен предлог(админ)";
|
---|
39 | break;
|
---|
40 | case "cancelledRequest":
|
---|
41 | tdTemp2.innerText = "Одбиен предлог(корисник)";
|
---|
42 | break;
|
---|
43 | case "cancelledAppointmentByUser":
|
---|
44 | tdTemp2.innerText = "Откажан термин(корисник)";
|
---|
45 | break;
|
---|
46 | case "cancelledAppointmentByAdmin":
|
---|
47 | tdTemp2.innerText = "Откажан термин(админ)";
|
---|
48 | break;
|
---|
49 | default:
|
---|
50 | console.log("Problem with status");
|
---|
51 | break;
|
---|
52 | }
|
---|
53 |
|
---|
54 | }
|
---|
55 | else{
|
---|
56 | tdTemp1.innerText = date.userNote;
|
---|
57 | tdTemp2.innerText = date.adminNote;
|
---|
58 | }
|
---|
59 | row.appendChild(tdTerm);
|
---|
60 | row.appendChild(tdTemp1);
|
---|
61 | row.appendChild(tdTemp2);
|
---|
62 | tableBody.appendChild(row);
|
---|
63 | });
|
---|
64 | }
|
---|
65 | function countStatus(user, status) {
|
---|
66 | let counter=0;
|
---|
67 | if(status!=="carried_out"){
|
---|
68 | counter= user.dates.filter(appointment => appointment.status === status).length;
|
---|
69 | }
|
---|
70 | else{
|
---|
71 | counter= user.carriedOut.length;
|
---|
72 | }
|
---|
73 | console.log(counter);
|
---|
74 | return counter;
|
---|
75 | }
|
---|
76 | function createHeader(headersArray){
|
---|
77 | const tableHead=document.getElementById("active-tableHead");
|
---|
78 | tableHead.innerHTML='';
|
---|
79 | const headerRow = document.createElement('tr');
|
---|
80 |
|
---|
81 | headersArray.forEach(headerText => {
|
---|
82 | const th = document.createElement('th');
|
---|
83 | th.textContent = headerText;
|
---|
84 | headerRow.appendChild(th);
|
---|
85 | });
|
---|
86 |
|
---|
87 | tableHead.appendChild(headerRow);
|
---|
88 | }
|
---|
89 |
|
---|
90 | async function getAll(url) {
|
---|
91 | const tableBody = document.getElementById("active-table");
|
---|
92 | const response = await fetch(url);
|
---|
93 | if (!response.ok) {
|
---|
94 | throw new Error('Network response was not ok');
|
---|
95 | }
|
---|
96 |
|
---|
97 | const data = await response.json();
|
---|
98 | tableBody.innerHTML = '';
|
---|
99 | data.forEach(request => {
|
---|
100 | const row = document.createElement('tr');
|
---|
101 | const termCell = document.createElement('td');
|
---|
102 | termCell.textContent = request.term.replace('T', ' ').substring(0, 16);
|
---|
103 | row.appendChild(termCell);
|
---|
104 | const additionalInfoCell = document.createElement('td');
|
---|
105 | additionalInfoCell.textContent = request.additionalInfo;
|
---|
106 | row.appendChild(additionalInfoCell);
|
---|
107 |
|
---|
108 | const button1 = document.createElement('button');
|
---|
109 | const button2 = document.createElement('button');
|
---|
110 | const buttonCell = document.createElement('td');
|
---|
111 | if(url.includes("requests")){
|
---|
112 | button1.textContent = "Прифати";
|
---|
113 | button1.addEventListener('click', () => displayDiv(request.term, loggedPerson.username));
|
---|
114 | buttonCell.appendChild(button1);
|
---|
115 | button2.textContent = "Одбиј";
|
---|
116 | button2.addEventListener('click',()=>removeRequestAndUpdateUser(request.term,loggedPerson.id,"rejected"));
|
---|
117 | buttonCell.appendChild(button2);
|
---|
118 | }
|
---|
119 | else{
|
---|
120 | button1.textContent = "Откажи";
|
---|
121 | button1.addEventListener('click',()=> removeAppointment(request.term,"cancelledAppointmentByAdmin"));
|
---|
122 | buttonCell.appendChild(button1);
|
---|
123 | button2.textContent = "Потврди одржан";
|
---|
124 | button2.addEventListener('click',()=>
|
---|
125 | function(){
|
---|
126 | modal.style.display='flex';
|
---|
127 | approveBtn.addEventListener('click', () => {
|
---|
128 | const userInput = document.getElementById('userInput').value;
|
---|
129 | confirmCarriedOut(request.term,userInput);
|
---|
130 | modal.style.display = 'none'; // Close the modal after approval
|
---|
131 | });
|
---|
132 | });
|
---|
133 | buttonCell.appendChild(button2);
|
---|
134 | }
|
---|
135 |
|
---|
136 | row.appendChild(buttonCell);
|
---|
137 | tableBody.appendChild(row);
|
---|
138 | });
|
---|
139 |
|
---|
140 | }
|
---|
141 | function createRowsBasedOnType(){
|
---|
142 | let url;
|
---|
143 | let tHeadArray=["Термин","Медицинска состојба", "Статус"];
|
---|
144 | const dropdown = document.getElementById('statusDropdown');
|
---|
145 | const selectedValue = dropdown.value;
|
---|
146 | if(selectedValue==="requests"){
|
---|
147 | url=`/api/requests/listAll?username=${loggedPerson.username}`;
|
---|
148 | tHeadArray=["Термин", "Опции"];
|
---|
149 | createHeader(tHeadArray);
|
---|
150 | getAll(url);
|
---|
151 | }
|
---|
152 | else if(selectedValue==="appointments"){
|
---|
153 | let testTemp="RESERVED";
|
---|
154 | url=`/api/appointments/listAll?username=${loggedPerson.username}&status=${testTemp}`;
|
---|
155 | tHeadArray=["Термин", "Опции"];
|
---|
156 | createHeader(tHeadArray);
|
---|
157 | getAll(url);
|
---|
158 | }
|
---|
159 | else if(selectedValue==="not-completed"){
|
---|
160 | createHeader(tHeadArray);
|
---|
161 | createAppointmentInfoField(selectedValue);
|
---|
162 | }
|
---|
163 | else if(selectedValue==="completed"){
|
---|
164 | tHeadArray=["Термин","Забелешка-клиент", "Забелешка-терапевт"];
|
---|
165 | createHeader(tHeadArray);
|
---|
166 | createAppointmentInfoField(selectedValue);
|
---|
167 | }
|
---|
168 |
|
---|
169 | dropdown.selectedIndex = 0;
|
---|
170 | }
|
---|
171 | async function createAdminInfoField(user) {
|
---|
172 | document.getElementById("carried-out").innerText = countStatus(user, "carried_out").toString();
|
---|
173 | document.getElementById("rejected").innerText = countStatus(user, "rejected").toString();
|
---|
174 | document.getElementById("cancelledReqByUser").innerText = countStatus(user, "cancelledRequest").toString();
|
---|
175 | document.getElementById("cancelledAppByUser").innerText = countStatus(user, "cancelledAppointmentByUser").toString();
|
---|
176 | document.getElementById("cancelledAppByAdmin").innerText = countStatus(user, "cancelledAppointmentByAdmin").toString();
|
---|
177 | }
|
---|
178 | function updateButtonText(isBlocked) {
|
---|
179 | const button = document.getElementById('block-account');
|
---|
180 | button.innerText = isBlocked ? "Активирај к.сметка" : "Блокирај к.сметка";
|
---|
181 | }
|
---|
182 | function fetchUserData(username,role) {
|
---|
183 | return fetch(`/api/users/editUser?username=${username}`)
|
---|
184 | .then(response => {
|
---|
185 | console.log('Response:', response);
|
---|
186 | return response.json()})
|
---|
187 | .then(data => {
|
---|
188 | loggedPerson=data;
|
---|
189 | document.querySelector('input[name="username"]').value = data.username || '';
|
---|
190 | document.querySelector('input[name="firstName"]').value = data.name || '';
|
---|
191 | document.querySelector('input[name="lastName"]').value = data.surname || '';
|
---|
192 | document.querySelector('input[name="phone"]').value = data.phone || '';
|
---|
193 | document.querySelector('input[name="age"]').value = data.dateBirth || '';
|
---|
194 | if(role==='ADMIN'){
|
---|
195 | createAdminInfoField(data);
|
---|
196 | let blockedButton=document.getElementById("block-account");
|
---|
197 | blockedButton.style.display='block';
|
---|
198 | fetch(`/api/users/blockedStatus?username=${username}`)
|
---|
199 | .then(response => response.json())
|
---|
200 | .then(data => {
|
---|
201 | updateButtonText(data.isBlocked);
|
---|
202 | })
|
---|
203 | .catch(error => {
|
---|
204 | console.error('Error fetching user status:', error);
|
---|
205 | });
|
---|
206 | blockedButton.addEventListener('click',()=>{
|
---|
207 | fetch(`/api/users/toggleBlock?username=${username}`, {
|
---|
208 | method: 'PUT',
|
---|
209 | headers: {
|
---|
210 | 'Content-Type': 'application/json'
|
---|
211 | }
|
---|
212 | })
|
---|
213 | .then(response => response.json())
|
---|
214 | .then(data=>{
|
---|
215 | if (data.message === "User status updated") {
|
---|
216 | const currentText = document.getElementById('block-account').innerText;
|
---|
217 | updateButtonText(currentText === "Блокирај к.сметка");
|
---|
218 | } else {
|
---|
219 | console.error('Error updating user status:', data.message);
|
---|
220 | }
|
---|
221 | })
|
---|
222 | .catch(error => {
|
---|
223 | console.error('Error:', error);
|
---|
224 | });
|
---|
225 | });
|
---|
226 | }
|
---|
227 |
|
---|
228 | return { name: data.name, surname: data.surname };
|
---|
229 | })
|
---|
230 | .catch(error => {
|
---|
231 | console.error('Error fetching user data:', error);
|
---|
232 | return { name: '', surname: '' }; // return empty values on error
|
---|
233 | });
|
---|
234 | }
|
---|
235 | function updateCookieUsername(newUsername) {
|
---|
236 | document.cookie = `username=${newUsername}; path=/;`;
|
---|
237 | }
|
---|
238 |
|
---|
239 |
|
---|
240 | function getCookie(name) {
|
---|
241 | const nameEQ = name + "=";
|
---|
242 | console.log(document.cookie);
|
---|
243 | const cookiesArray = document.cookie.split(';');
|
---|
244 | for (let i = 0; i < cookiesArray.length; i++) {
|
---|
245 | let cookie = cookiesArray[i].trim();
|
---|
246 | if (cookie.indexOf(nameEQ) === 0)
|
---|
247 | console.log(cookie.split("=")[1])
|
---|
248 | return cookie.split("=")[1];
|
---|
249 | }
|
---|
250 | return null;
|
---|
251 | }
|
---|
252 | function updateProfile() {
|
---|
253 | const params=getQueryParams();
|
---|
254 | const username = params.param2;
|
---|
255 | const role=params.param1;
|
---|
256 | if(username && role==='ADMIN'){
|
---|
257 | fetchUserData(username,"ADMIN").then(r => {
|
---|
258 | console.log("success from admin")
|
---|
259 | document.getElementById("adminInfo-block").style.display='block';
|
---|
260 | })
|
---|
261 | }
|
---|
262 | else{
|
---|
263 |
|
---|
264 | document.getElementById("edit-profile").style.display='none';
|
---|
265 | document.getElementById("saveChanges").style.display='none';
|
---|
266 | const cookieUsername = getCookie('username');
|
---|
267 | if (cookieUsername) {
|
---|
268 | fetchUserData(cookieUsername,"USER").then(userData => {
|
---|
269 | const fullName = `${userData.name} ${userData.surname}`;
|
---|
270 | document.getElementById('cookie-name').innerHTML = fullName;
|
---|
271 | });
|
---|
272 | } else {
|
---|
273 | document.getElementById('cookie-name').textContent = 'Default Name';
|
---|
274 | }
|
---|
275 | }
|
---|
276 | }
|
---|
277 | function saveProfileChanges() {
|
---|
278 | const userName = document.querySelector('input[name="username"]').value;
|
---|
279 | console.log(userName);
|
---|
280 | const updatedData = {
|
---|
281 | username: userName,
|
---|
282 | name: document.querySelector('input[name="firstName"]').value,
|
---|
283 | surname: document.querySelector('input[name="lastName"]').value,
|
---|
284 | phone: document.querySelector('input[name="phone"]').value,
|
---|
285 | age: document.querySelector('input[name="age"]').value
|
---|
286 | };
|
---|
287 | if(!verificationCheck(updatedData)){
|
---|
288 | return;
|
---|
289 | }
|
---|
290 |
|
---|
291 | fetch(`/api/users/updateUser`, {
|
---|
292 | method: 'POST',
|
---|
293 | headers: {
|
---|
294 | 'Content-Type': 'application/json'
|
---|
295 | },
|
---|
296 | body: JSON.stringify(updatedData)
|
---|
297 | })
|
---|
298 | .then(response => console.log(response.json()))
|
---|
299 | .then(data => {
|
---|
300 | alert('Profile updated successfully!');
|
---|
301 | toggleEditing(false); // Disable fields after saving changes
|
---|
302 | updateCookieUsername(userName);
|
---|
303 | })
|
---|
304 | .catch(error => {
|
---|
305 | console.error('Error updating user data:', error);
|
---|
306 | });
|
---|
307 | }
|
---|
308 | function getQueryParams() {
|
---|
309 | const params = new URLSearchParams(window.location.search);
|
---|
310 | return {
|
---|
311 | param1: params.get('param1'),
|
---|
312 | param2: params.get('param2')
|
---|
313 | };
|
---|
314 | }
|
---|
315 |
|
---|
316 | function toggleEditing(isEnabled) {
|
---|
317 | const inputs = document.querySelectorAll('input');
|
---|
318 | inputs.forEach(input => {
|
---|
319 | input.disabled = !isEnabled;
|
---|
320 | });
|
---|
321 | }
|
---|
322 |
|
---|
323 | window.onload = function(){
|
---|
324 | updateProfile();
|
---|
325 | toggleEditing(false);
|
---|
326 | document.getElementById('edit-profile').addEventListener('click', function() {
|
---|
327 | const role=getQueryParams();
|
---|
328 | if(role.param1 ==='ADMIN')
|
---|
329 | toggleEditing(true);
|
---|
330 | });
|
---|
331 | document.getElementById('saveChanges').addEventListener('click', saveProfileChanges);
|
---|
332 | document.getElementById("statusDropdown").addEventListener('change',createRowsBasedOnType);
|
---|
333 |
|
---|
334 | } |
---|