source: src/main/resources/static/js/editUser.js@ 43c9090

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

Updated version

  • Property mode set to 100644
File size: 13.2 KB
Line 
1
2import { deleteAppointment, confirmCarriedOut, getUsersByTermExcept, removeRequestAndUpdateUser, removeAppointment, makeReservation ,displayDiv} from './shared.js';
3import { verificationCheck } from './authentication-shared.js';
4
5let loggedPerson,checkDifferent;
6const modal = document.getElementById('popupModal');
7const cancelBtn = document.getElementById('cancelBtn');
8const approveBtn = document.getElementById('approveBtn');
9const closeSpan = document.querySelector('.close');
10
11cancelBtn.addEventListener('click', () => {
12 modal.style.display = 'none';
13});
14closeSpan.addEventListener('click', () => {
15 modal.style.display = 'none';
16});
17
18function 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}
65function 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 return counter;
74}
75function createHeader(headersArray){
76 const tableHead=document.getElementById("active-tableHead");
77 tableHead.innerHTML='';
78 const headerRow = document.createElement('tr');
79
80 headersArray.forEach(headerText => {
81 const th = document.createElement('th');
82 th.textContent = headerText;
83 headerRow.appendChild(th);
84 });
85
86 tableHead.appendChild(headerRow);
87}
88
89async function getAll(url) {
90 const tableBody = document.getElementById("active-table");
91 const response = await fetch(url);
92 if (!response.ok) {
93 throw new Error('Network response was not ok');
94 }
95
96 const data = await response.json();
97 tableBody.innerHTML = '';
98 data.forEach(request => {
99 const row = document.createElement('tr');
100 const termCell = document.createElement('td');
101 termCell.textContent = request.term.replace('T', ' ').substring(0, 16);
102 row.appendChild(termCell);
103 const additionalInfoCell = document.createElement('td');
104 additionalInfoCell.textContent = request.additionalInfo;
105 row.appendChild(additionalInfoCell);
106
107 const button1 = document.createElement('button');
108 const button2 = document.createElement('button');
109 const buttonCell = document.createElement('td');
110 if(url.includes("requests")){
111 button1.textContent = "Прифати";
112 button1.addEventListener('click', () => displayDiv(request.term, loggedPerson.username));
113 buttonCell.appendChild(button1);
114 button2.textContent = "Одбиј";
115 button2.addEventListener('click',()=>removeRequestAndUpdateUser(request.term,loggedPerson.id,"rejected"));
116 buttonCell.appendChild(button2);
117 }
118 else{
119 button1.textContent = "Откажи";
120 button1.addEventListener('click',()=> removeAppointment(request.term,"cancelledAppointmentByAdmin"));
121 buttonCell.appendChild(button1);
122 button2.textContent = "Потврди одржан";
123 buttonCell.appendChild(button2);
124 button2.addEventListener('click',()=> {
125 modal.style.display='flex';
126 document.getElementById("userInput").disabled=false;
127 });
128 approveBtn.addEventListener('click', () => {
129 const userInput = document.getElementById('userInput').value;
130 confirmCarriedOut(request.term,userInput);
131 modal.style.display = 'none';
132 });
133
134 }
135
136 row.appendChild(buttonCell);
137 tableBody.appendChild(row);
138 });
139
140}
141function 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}
171async 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}
178function updateButtonText(isBlocked) {
179 const button = document.getElementById('block-account');
180 button.innerText = isBlocked ? "Активирај к.сметка" : "Блокирај к.сметка";
181}
182function 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: '' };
233 });
234}
235function updateCookieUsername(newUsername) {
236 document.cookie = `username=${newUsername}; path=/;`;
237}
238
239
240function 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}
252function 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 console.log("success")
270 });
271 }
272 }
273}
274function saveProfileChanges() {
275 const userName = document.querySelector('input[name="username"]').value;
276 const phoneNum=document.querySelector('input[name="phone"]').value.replace(/-/g,"")
277 console.log(phoneNum);
278 const updatedData = {
279 username: userName,
280 name: document.querySelector('input[name="firstName"]').value,
281 surname: document.querySelector('input[name="lastName"]').value,
282 phone: phoneNum,
283 age: document.querySelector('input[name="age"]').value
284 };
285 if(!verificationCheck(updatedData,checkDifferent)){
286 return;
287 }
288
289 fetch(`/api/users/updateUser`, {
290 method: 'POST',
291 headers: {
292 'Content-Type': 'application/json'
293 },
294 body: JSON.stringify(updatedData)
295 })
296 .then(response => console.log(response.json()))
297 .then(data => {
298 alert('Profile updated successfully!');
299 toggleEditing(false);
300 updateCookieUsername(userName);
301 })
302 .catch(error => {
303 console.error('Error updating user data:', error);
304 });
305}
306function getQueryParams() {
307 const params = new URLSearchParams(window.location.search);
308 return {
309 param1: params.get('param1'),
310 param2: params.get('param2')
311 };
312}
313function removeOptions(){
314 if(getRoleFromCookie()!=="ADMIN"){
315 let temp=this;
316 temp.removeChild(document.getElementById("requests"));
317 temp.removeChild(document.getElementById("appointments"))
318 }
319}
320
321function toggleEditing(isEnabled) {
322 const inputs = document.querySelectorAll('input');
323 inputs.forEach(input => {
324 input.disabled = !isEnabled;
325 });
326}
327
328window.onload = function(){
329 checkDifferent=true;
330 updateProfile();
331 toggleEditing(false);
332 document.getElementById('edit-profile').addEventListener('click', function() {
333 const role=getQueryParams();
334 if(role.param1 ==='ADMIN'){
335 toggleEditing(true);
336 checkDifferent=false;
337 }
338
339 });
340 document.getElementById('saveChanges').addEventListener('click', saveProfileChanges);
341 document.getElementById("statusDropdown").addEventListener('change',createRowsBasedOnType);
342 document.getElementById("statusDropdown").addEventListener('click',removeOptions);
343}
Note: See TracBrowser for help on using the repository browser.