Skip to content

Commit

Permalink
Added "edit" function in admin panel
Browse files Browse the repository at this point in the history
  • Loading branch information
Electronprod committed Nov 8, 2024
1 parent dca6b73 commit d41e5ed
Show file tree
Hide file tree
Showing 8 changed files with 153 additions and 18 deletions.
Binary file modified database.db
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,20 @@ public ResponseEntity<String> createUser(@RequestParam String login, @RequestPar
}
return ResponseEntity.internalServerError().body(answer.toJSONString());
}

@SuppressWarnings("unchecked")
@GetMapping("/admin/getevent")
public ResponseEntity<String> getEvents(@RequestParam int id) {
Optional<Event> event1 = database.findById(id);
if (event1.isEmpty())
return ResponseEntity.badRequest().body("[]");
Event event = event1.get();
JSONObject JSEvent = new JSONObject();
JSEvent.put("id", event.getId());
JSEvent.put("date", event.getDate());
JSEvent.put("title", event.getTitle());
JSEvent.put("content", event.getContent());
JSEvent.put("author", event.getAuthor());
return ResponseEntity.ok(JSEvent.toJSONString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import ru.electronprod.EventCalendar.security.AuthHelper;
import ru.electronprod.EventCalendar.models.Event;
import ru.electronprod.EventCalendar.repositories.EventRepository;

@Controller
public class CalendarController {
@Autowired
private EventRepository database;
@Autowired
private AuthHelper auth;

@GetMapping("/")
public String calendar() {
Expand All @@ -35,6 +37,9 @@ public String license() {
@SuppressWarnings("unchecked")
@PostMapping("/api/addevent")
public ResponseEntity<String> createEvent(@RequestBody Event event) {
if (event.getId() != 0 && !auth.getCurrentUser().getRole().equals("ROLE_ADMIN")) {
return ResponseEntity.status(403).body("[]");
}
event.setVerified(false);
event.setDate(event.getDate().replaceAll("-", "."));
boolean result = database.save(event) != null;
Expand Down
87 changes: 83 additions & 4 deletions src/main/resources/static/assets/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,32 @@ if (window.location.href.toLowerCase().includes("show_verified")) {
} else {
showNotification("Напоминание", "Здесь находятся события, ожидающие утверждения.", "warning");
}
if (window.location.href.toLowerCase().includes("?edited")) {
showNotification("Изменено!", "Изменения в событие внесены успешно", "success");
}

async function verify(id) {
console.log("Verifying ID: " + id);
if (sendData("/admin/verify?id=" + id)) {
if (await sendData("/admin/verify?id=" + id)) {
deleteByName(id);
showNotification("Утверждено", "Событие сохранено.", "success");
}
}
async function edit(id) {
console.log("Editing ID: " + id);
document.getElementById('id').value = id;
const event = await fetchData("/admin/getevent?id=" + id);
let dateParts = String(event.date).split('.');
let formattedDate = `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`;
document.getElementById("date").value = formattedDate;
document.getElementById('title').value = event.title;
document.getElementById('description').value = event.content;
document.getElementById('signature').value = event.author;
openModal();
}
async function deny(id) {
console.log("Removing ID: " + id);
if (sendData("/admin/deny?id=" + id)) {
if (await sendData("/admin/deny?id=" + id)) {
deleteByName(id);
showNotification("Удалено", "Событие удалено.", "info");
}
Expand Down Expand Up @@ -64,7 +79,32 @@ const sendData = async (url) => {
return false;
}
};

const sendJSONData = async (url, data) => {
var csrfToken = document.querySelector('input[name="_csrf"]').value;
// Опции для fetch запроса
const options = {
method: 'POST',
headers: {
'X-CSRF-TOKEN': csrfToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
try {
const response = await fetch(url, options);
if (!response.ok) {
showNotification("Ошибка HTTP " + response.status, "Некорректный ответ от сервера.", "error");
return false;
}
const responseData = await response.json();
console.log('Response:', responseData);
return true;
} catch (error) {
console.error('Error:', error);
showNotification("Ошибка!", error.toString(), "error");
return false;
}
};
function showNotification(title, text, icon) {
Swal.fire({
title: title,
Expand All @@ -73,7 +113,7 @@ function showNotification(title, text, icon) {
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timer: 5000,
timerProgressBar: true,
showClass: {
popup: 'swal2-show'
Expand All @@ -95,4 +135,43 @@ function changeView() {
} else {
window.location.href = "/admin?show_verified"
}
}
function openModal() {
document.getElementById('overlay').style.display = 'flex';
}
function closeModal() {
document.getElementById('overlay').style.display = 'none';
}
async function submitForm() {
const id = document.getElementById('id').value;
const date = document.getElementById('date').value;
const title = document.getElementById('title').value;
const description = document.getElementById('description').value;
const signature = document.getElementById('signature').value;
if (!date || !title || !signature || !id) {
alert('Пожалуйста, заполните обязательные поля: Дата, Заголовок, Подпись.');
return;
}
const data = {
id: id,
date: date,
title: title,
content: description,
author: signature
};
console.log(data);
if (await sendJSONData("/api/addevent", data)) {
if (window.location.href.toLowerCase().includes("show_verified")) {
deleteByName(data.id);
showNotification("Готово. Необходимо действие!", "Не забудьте заново утвердить событие.", "success");
} else {
window.location.href = "/admin?edited";
}
}
document.getElementById('id').value = "";
document.getElementById("date").valueAsDate = new Date();
document.getElementById('title').value = "";
document.getElementById('description').value = "";
document.getElementById('signature').value = "";
closeModal();
}
11 changes: 11 additions & 0 deletions src/main/resources/static/assets/calendar.css
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@
width: 100px;
}

.edit-btn {
background-color: blue;
color: #fff;
text-align: center;
width: 100px;
}

.deny-btn {
background-color: red;
color: #fff;
Expand All @@ -67,6 +74,10 @@
background-color: limegreen;
}

.edit-btn:hover {
background-color: darkblue;
}

.deny-btn:hover {
background-color: orangered;
}
Expand Down
22 changes: 10 additions & 12 deletions src/main/resources/static/assets/calendar.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@ async function main() {
verstate = false;
}
const eventsData = await fetchData("/api/getevents?verified=" + !verstate);
// Сортировка событий по месяцу
eventsData.sort((a, b) => {
const monthA = moment(a.date, "YYYY.MM.DD").month();
const monthB = moment(b.date, "YYYY.MM.DD").month();
return monthA - monthB;
const dateA = moment(a.date, "YYYY.MM.DD");
const dateB = moment(b.date, "YYYY.MM.DD");
const monthDifference = dateA.month() - dateB.month();
if (monthDifference !== 0) {
return monthDifference;
}
return dateA.date() - dateB.date();
});

function renderEvents(events) {
const container = document.getElementById("events-container");
let upcomingEventFound = false;
events.forEach(event => {
const date = moment(event.date, "YYYY.MM.DD");
const eventElement = document.createElement("div");
Expand All @@ -35,13 +38,10 @@ async function main() {
</div>
<div class="button-container" name="${event.id}">
<button class="verify-btn" onclick="verify(${event.id})">Утвердить</button>
<button class="edit-btn" onclick="edit(${event.id})">Редактировать</button>
<button class="deny-btn" onclick="deny(${event.id})">Удалить</button>
</div>
`;
if (date.isSameOrAfter(moment()) && !upcomingEventFound) {
eventElement.classList.add("upcoming-event");
upcomingEventFound = eventElement;
}
container.appendChild(eventElement);
});
if (window.location.href.toLowerCase().includes("show_verified")) {
Expand All @@ -50,12 +50,10 @@ async function main() {
button.remove();
});
}
if (upcomingEventFound) {
upcomingEventFound.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
renderEvents(eventsData);
}

window.onload = main;

async function fetchData(url) {
Expand Down
26 changes: 26 additions & 0 deletions src/main/resources/templates/admin/overview.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,32 @@ <h2>События</h2>
<div class="floating-button-4" onclick="window.location.href='/admin/usermgr';">
<i class="fas fa-users"></i>
</div>
<div class="overlay" id="overlay">
<div class="modal">
<h2>Редактирование</h2>
<input type="hidden" id="id" required>
<div class="form-group">
<label for="date">Когда это произошло?</label>
<input type="date" id="date" required>
</div>
<div class="form-group">
<label for="title">Как называется событие?</label>
<input spellcheck="true" type="text" id="title" placeholder="Введите название" required>
</div>
<div class="form-group">
<label for="description">Опишите событие подробнее:</label>
<textarea wrap="hard" required spellcheck="true" id="description" rows="2" maxlength="100"
placeholder="Не больше 100 букв."></textarea>
</div>
<div class="form-group">
<label for="signature">Кто вы?</label>
<input spellcheck="true" type="text" id="signature" placeholder="Иванов Иван" required>
</div>
<div class="modal-buttons">
<button class="submit-button" onclick="submitForm()">Отправить</button>
<button class="close-button" onclick="closeModal()">Закрыть</button>
</div>
</div>
</body>
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/templates/admin/usermgr.html
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ <h2>Введите данные</h2>
<script src="/assets/sweetalert2.js"></script>
<script>
async function deleteUser(id) {
if (sendData("/admin/delete_user?id=" + id)) {
if (await sendData("/admin/delete_user?id=" + id)) {
var divsToDelete = document.querySelectorAll('tr[name="' + id + '"]');
divsToDelete.forEach(function (div) {
div.remove();
Expand Down

0 comments on commit d41e5ed

Please sign in to comment.