import { Grid } from "gridjs/dist/gridjs.umd.js"; import gridjs from "gridjs/dist/gridjs.umd.js"; import "gridjs/dist/gridjs.umd.js"; import GlobalConfig from "../global-config"; class Roles { init() { this.initTableRoles(); } initTableRoles() { new Grid({ columns: [ "ID", "Name", "Description", { name: "Action", formatter: (cell) => gridjs.html(`
Update Role Menu
`), }, ], pagination: { limit: 15, server: { url: (prev, page) => `${prev}${prev.includes("?") ? "&" : "?"}page=${ page + 1 }`, }, }, sort: true, search: { server: { url: (prev, keyword) => `${prev}?search=${keyword}`, }, }, server: { url: `${GlobalConfig.apiHost}/api/api-roles`, credentials: "include", headers: { Authorization: `Bearer ${document .querySelector('meta[name="api-token"]') .getAttribute("content")}`, "Content-Type": "application/json", }, then: (data) => data.data.map((item) => [ item.id, item.name, item.description, item.id, ]), total: (data) => data.total, }, }).render(document.getElementById("table-roles")); document.addEventListener("click", this.handleDelete); } handleDelete(event) { if (event.target.classList.contains("btn-delete-role")) { event.preventDefault(); const id = event.target.getAttribute("data-id"); let modalElement = document.getElementById("modalConfirmation"); if (!modalElement) { console.error("Modal element not found!"); return; } let modal = new bootstrap.Modal(modalElement); // Set the role ID on the confirm button inside the modal let btnSaveConfirmation = document.getElementById( "btnSaveConfirmation" ); btnSaveConfirmation.setAttribute("data-role-id", id); let toastElement = document.getElementById("toastNotificationApi"); let toast = new bootstrap.Toast(toastElement); // Show the modal modal.show(); // Prevent multiple event listeners btnSaveConfirmation.onclick = function () { let roleId = this.getAttribute("data-role-id"); console.log("Deleted ID:", roleId); fetch(`/roles/${roleId}`, { method: "DELETE", credentials: "include", headers: { "X-CSRF-TOKEN": document .querySelector('meta[name="csrf-token"]') .getAttribute("content"), "Content-Type": "application/json", }, }) .then((response) => { if (response.ok) { modal.hide(); toast.show(); setTimeout(() => window.location.reload(), 1500); } else { return response.json().then((error) => { console.error("Delete failed:", error); toast.show(); }); } }) .catch((error) => { console.error("Error deleting item:", error); toast.show(); }); }; } } } document.addEventListener("DOMContentLoaded", function (e) { new Roles().init(); });