source: src/main/resources/static/js/adminNewsCoupons.js@ 743de55

Last change on this file since 743de55 was 743de55, checked in by macagaso <gasoskamarija@…>, 6 weeks ago

Initial commit

  • Property mode set to 100644
File size: 10.7 KB
Line 
1const newsList = document.getElementById('news-list');
2const newsForm = document.getElementById('news-form');
3const couponsList = document.getElementById('coupons-list');
4const couponsForm = document.getElementById('coupons-form');
5
6let selectedImage;
7let questionable;
8
9let pageType;
10document.addEventListener('DOMContentLoaded',function (){
11 pageType = document.body.getAttribute('data-page');
12 if(pageType==='events'){
13
14 const openPopupButton = document.getElementById('open-popup');
15 const imagePopup = document.getElementById('image-popup');
16 const overlay = document.getElementById('overlay');
17 const imageInput = document.getElementById('image-url');
18 const imagePreview = document.getElementById('image-preview');
19 const saveButton = document.getElementById('save-button');
20 const cancelButton = document.getElementById('cancel-button');
21
22
23 openPopupButton.addEventListener('click', (e) => {
24 e.preventDefault();
25 imagePopup.style.display = 'block';
26 overlay.style.display = 'block';
27 });
28
29 imageInput.addEventListener('change', (event) => {
30 event.preventDefault();
31 selectedImage=null;
32 questionable=null;
33 const file = event.target.files[0];
34 questionable=file;
35 if (file) {
36 const reader = new FileReader();
37 reader.onload = (e) => {
38 imagePreview.style.display='inline';
39 imagePreview.innerHTML = `<img src="${e.target.result}" style="width: 100%; height: auto;">`;
40 selectedImage =e.target.result ; // Store the selected file
41
42 console.log(selectedImage);
43 saveButton.style.display = 'inline';
44 };
45 reader.readAsDataURL(questionable);
46 }
47 });
48
49 saveButton.addEventListener('click', () => {
50 if(selectedImage) {
51 let temp= document.getElementById('main-image');
52 temp.innerHTML=`<img src="${selectedImage}" style="width: 20%; height: 20%;">`;
53 closePopup();
54 }
55 else{
56 console.log('No image file selected');
57 }
58
59
60 });
61
62 cancelButton.addEventListener('click', ()=>{
63 closePopup();
64
65 });
66
67 function closePopup() {
68 imagePopup.style.display = 'none';
69 overlay.style.display = 'none';
70 imageInput.value = '';
71 imagePreview.innerHTML = '';
72 }
73 }
74});
75
76function elementCreation(ItemData){
77 const newItem = document.createElement('div');
78 newItem.classList.add('news-item');
79 newItem.setAttribute('data-id', ItemData.id);
80 if(pageType==='events'){
81 newItem.innerHTML = `
82 <h3>${ItemData.title}</h3>
83 <p>${ItemData.text}</p>
84 ${ItemData.imgSrc ? `<img src="${ItemData.imgSrc}" style="width: 50%; height: auto;" data-attribute="${ItemData.imgSrc}">` : ''}`
85 }
86 else{
87 newItem.innerHTML = `
88 <h3>${ItemData.title}</h3>
89 <p>${ItemData.code}</p>
90 <div>${ItemData.description}</div>`
91 }
92 newItem.innerHTML+=`<button onclick="edit(this)">Edit</button>
93 <button onclick="deleteBoth(this)">Delete</button>`
94 return newItem;
95}
96function eventsRetrieval(){
97 const url = pageType === 'events' ? `/api/news/getAllEvents` : `/api/coupons/getAllCoupons`;
98 fetch(url,{
99 method: 'GET',
100 headers: {
101 'Content-Type': 'application/json'
102 }
103 })
104 .then(response => {
105 if (!response.ok) {
106 throw new Error('Failed to fetch news.');
107 }
108 return response.json();
109 })
110 .then(data => {
111 data.forEach(ItemData => {
112 let newItem=elementCreation(ItemData);
113 pageType === 'events' ? newsList.appendChild(newItem) : couponsList.appendChild(newItem);
114 });
115 })
116 .catch(error => {
117 console.error('Error:', error);
118 alert('Failed to load news.');
119 });
120}
121
122window.onload=function(){
123 eventsRetrieval();
124}
125function clearData(){
126 if(pageType==='events'){
127 document.getElementById('text').value = '';
128 }
129 else if(pageType==='coupons'){
130 let temp1=document.getElementById('code');
131 temp1.value = '';
132 temp1.removeAttribute('data-initial');
133 let temp2=document.getElementById('description');
134 temp2.value = '';
135 temp2.removeAttribute('data-initial');
136 }
137 let temp3=document.getElementById('title');
138 temp3.value = '';
139 temp3.removeAttribute('data-initial');
140}
141function showForm() {
142 if(pageType==='events')
143 document.getElementById("main-image").innerHTML='';
144 pageType === 'events' ? newsForm.style.display = 'flex' : couponsForm.style.display='flex';
145}
146
147function hideForm() {
148 pageType === 'events' ? newsForm.style.display = 'none' : couponsForm.style.display='none';
149 clearData();
150 selectedImage = null;
151 questionable=null;
152}
153
154function submitForm() {
155 let param1,param2,param3;
156 param1 = document.getElementById('title').value;
157
158 if(pageType==='events'){
159 param2 = document.getElementById('text').value;
160 param3 = selectedImage;
161 }
162 else if(pageType==='coupons'){
163 param2 = document.getElementById('code').value;
164 param3 = document.getElementById('description').value;
165 }
166 if (param1 && param2) {
167 let newsData;
168 if (pageType === 'events') {
169 newsData = {
170 title: param1,
171 text: param2,
172 imgSrc: param3
173 };
174 } else {
175 newsData = {
176 title: param1,
177 code: param2,
178 description: param3
179 };
180 }
181 let initialTitle = document.getElementById('title').getAttribute('data-initial');
182 console.log(initialTitle);
183
184 if(initialTitle!==null){
185 let initialParam2,initialParam3;
186 if(pageType==='events'){
187 initialParam2=document.getElementById("text").getAttribute('data-initial');
188 initialParam3 = document.getElementsByTagName('img')[0].getAttribute('data-attribute');
189 }
190 else if(pageType==='coupons'){
191 initialParam2 = document.getElementById('code').getAttribute('data-initial');
192 initialParam3=document.getElementById('description').getAttribute('data-initial');
193 }
194 clearData();
195 if (initialTitle !== param1 || initialParam2 !== param2 || initialParam3 !== param3) {
196 console.log('Changes detected! Submitting the form.');
197 } else {
198 hideForm();
199 return;
200 }
201
202 const url = pageType === 'events' ? `/api/news/editEvent?identifier=${initialTitle}` : `/api/coupons/editCoupon?identifier=${initialTitle}`;
203 fetch(url, {
204 method: 'POST',
205 headers: {
206 'Content-Type': 'application/json'
207 },
208 body: JSON.stringify(newsData)
209 }).then(response => {
210 if (!response.ok) {
211 throw new Error('Network response was not ok');
212 }
213 console.log("Successfully edited");
214 hideForm();
215 if (pageType === 'events') {
216 newsList.innerHTML = '';
217 } else {
218 couponsList.innerHTML = '';
219 }
220 eventsRetrieval();
221 }).catch(error => {
222 console.error('Error occurred');
223 });
224
225 return;
226 }
227 const url = pageType === 'events' ? `/api/news/createEvent` : `/api/coupons/createCoupon`;
228 fetch(url, {
229 method: 'PUT',
230 headers: {
231 'Content-Type': 'application/json'
232 },
233 body: JSON.stringify(newsData)
234 })
235 .then(response => {
236 if (!response.ok) {
237 throw new Error('Failed to update news.');
238 }
239 return response.json();
240 })
241 .then(data => {
242 console.log('Data updated:', data);
243 let newItem = elementCreation(data);
244 if (pageType === 'events') {
245 newsList.appendChild(newItem);
246 } else {
247 couponsList.appendChild(newItem);
248 }
249 document.getElementById('form').reset();
250 hideForm();
251 })
252 .catch(error => {
253 console.error('Error during submission:', error);
254 alert('Failed to save the news/coupon. Please try again.');
255
256 });
257 clearData();
258 }
259 else
260 {
261 alert('Missing fields');
262 }
263}
264
265function deleteBoth(button) {
266
267 let temp=button.parentElement;
268 let value=temp.getAttribute('data-id');
269 const url = pageType === 'events' ? `/api/news/deleteEvent?userId=${value}` : `/api/coupons/deleteCoupon?userId=${value}`;
270 fetch(url, {
271 method: 'DELETE',
272 headers: {
273 'Content-Type': 'application/json'
274 }
275 })
276 .then(r => {
277 if(r.ok){
278 console.log('Element deleted successfully');
279 }
280 else{
281 console.error('Failed to delete element');
282 }
283 })
284 .catch(error => {
285 console.log("error deleting");
286 });
287
288 const newItem = button.parentElement;
289 pageType === 'events' ? newsList.removeChild(newItem) : couponsList.removeChild(newItem);
290
291}
292
293function edit(button) {
294 showForm();
295 const newsItem = button.parentElement;
296 const param1 = newsItem.querySelector('h3').textContent;
297 const param2 = newsItem.querySelector('p').textContent;
298
299 if(pageType==='events'){
300 document.getElementById('text').value = param2;
301 let importantValue=newsItem.querySelector('img').getAttribute("data-attribute");
302 document.getElementById('main-image').innerHTML=`<img src="${importantValue}" style="width: 20%; height: 20%;">`;
303 }
304 else if(pageType==='coupons'){
305 const description=newsItem.querySelector('div').textContent;
306 document.getElementById('code').value = param2;
307 document.getElementById('code').setAttribute('data-initial',param2);
308 document.getElementById('description').value = description;
309 document.getElementById('description').setAttribute('data-initial',description);
310 }
311 document.getElementById('title').value = param1;
312 document.getElementById('title').setAttribute('data-initial', param1);
313
314}
315
Note: See TracBrowser for help on using the repository browser.