hot fix conflict routing web and api advertisements

This commit is contained in:
arifal
2025-03-04 15:46:35 +07:00
parent b4ec7a9d25
commit d6d0acf8fb
5 changed files with 196 additions and 178 deletions

View File

@@ -62,7 +62,7 @@ class AdvertisementController extends Controller
// Pastikan model ditemukan // Pastikan model ditemukan
if (!$modelInstance) { if (!$modelInstance) {
info("AdvertisementController@edit: Model tidak ditemukan."); info("AdvertisementController@edit: Model tidak ditemukan.");
return redirect()->route('advertisements.index')->with('error', 'Advertisement not found'); return redirect()->route('web.advertisements.index')->with('error', 'Advertisement not found');
} }
// Mengambil dan memetakan village_name dan district_name // Mengambil dan memetakan village_name dan district_name

View File

@@ -167,7 +167,7 @@ class UsersRoleMenuSeeder extends Seeder
], ],
[ [
"name" => "Reklame", "name" => "Reklame",
"url" => "advertisements.index", "url" => "web.advertisements.index",
"icon" => null, "icon" => null,
"parent_id" => $data->id, "parent_id" => $data->id,
"sort_order" => 2, "sort_order" => 2,

View File

@@ -3,7 +3,7 @@ import GlobalConfig from "../../global-config";
document.addEventListener("DOMContentLoaded", function () { document.addEventListener("DOMContentLoaded", function () {
const saveButton = document.querySelector(".modal-footer .btn-primary"); const saveButton = document.querySelector(".modal-footer .btn-primary");
const modalButton = document.querySelector(".btn-modal"); const modalButton = document.querySelector(".btn-modal");
const form = document.querySelector("form#create-update-form"); const form = document.querySelector("form#create-update-form");
var authLogo = document.querySelector(".auth-logo"); var authLogo = document.querySelector(".auth-logo");
if (!saveButton || !form) return; if (!saveButton || !form) return;
@@ -16,10 +16,10 @@ document.addEventListener("DOMContentLoaded", function () {
Loading... Loading...
`; `;
const isEdit = saveButton.classList.contains("btn-edit"); const isEdit = saveButton.classList.contains("btn-edit");
const formData = new FormData(form) const formData = new FormData(form);
const toast = document.getElementById('toastEditUpdate'); const toast = document.getElementById("toastEditUpdate");
const toastBody = toast.querySelector('.toast-body'); const toastBody = toast.querySelector(".toast-body");
const toastHeader = toast.querySelector('.toast-header small'); const toastHeader = toast.querySelector(".toast-header small");
const data = {}; const data = {};
@@ -27,9 +27,9 @@ document.addEventListener("DOMContentLoaded", function () {
formData.forEach((value, key) => { formData.forEach((value, key) => {
data[key] = value; data[key] = value;
}); });
const url = form.getAttribute("action"); const url = form.getAttribute("action");
const method = isEdit ? "PUT" : "POST"; const method = isEdit ? "PUT" : "POST";
fetch(url, { fetch(url, {
@@ -40,99 +40,103 @@ document.addEventListener("DOMContentLoaded", function () {
.querySelector('meta[name="api-token"]') .querySelector('meta[name="api-token"]')
.getAttribute("content")}`, .getAttribute("content")}`,
"Content-Type": "application/json", "Content-Type": "application/json",
} },
}) })
.then(response => response.json()) .then((response) => response.json())
.then(data => { .then((data) => {
if (!data.errors) { if (!data.errors) {
// Remove existing icon (if any) before adding the new one // Remove existing icon (if any) before adding the new one
if (authLogo) { if (authLogo) {
// Hapus ikon yang sudah ada jika ada // Hapus ikon yang sudah ada jika ada
const existingIcon = authLogo.querySelector('.bx'); const existingIcon = authLogo.querySelector(".bx");
if (existingIcon) { if (existingIcon) {
authLogo.removeChild(existingIcon); authLogo.removeChild(existingIcon);
} }
// Buat ikon baru
const icon = document.createElement('i');
icon.classList.add('bx', 'bxs-check-square');
icon.style.fontSize = '25px';
icon.style.color = 'green'; // Pastikan 'green' dalam bentuk string
// Tambahkan ikon ke dalam auth-logo
authLogo.appendChild(icon);
}
// Set success message for the toast
toastBody.textContent = isEdit ? "Data updated successfully!" : "Data created successfully!";
toast.classList.add('show'); // Show the toast
setTimeout(() => {
toast.classList.remove('show'); // Hide the toast after 3 seconds
}, 2000);
setTimeout(() => {
window.location.href = '/data/advertisements';
}, 1000);
} else {
if (authLogo) {
// Hapus ikon yang sudah ada jika ada
const existingIcon = authLogo.querySelector('.bx');
if (existingIcon) {
authLogo.removeChild(existingIcon);
}
// Buat ikon baru
const icon = document.createElement('i');
icon.classList.add('bx', 'bxs-error-alt');
icon.style.fontSize = '25px';
icon.style.color = 'red'; // Pastikan 'green' dalam bentuk string
// Tambahkan ikon ke dalam auth-logo
authLogo.appendChild(icon);
}
// Buat ikon baru
const icon = document.createElement("i");
icon.classList.add("bx", "bxs-check-square");
icon.style.fontSize = "25px";
icon.style.color = "green"; // Pastikan 'green' dalam bentuk string
// Tambahkan ikon ke dalam auth-logo
authLogo.appendChild(icon);
}
// Set success message for the toast
toastBody.textContent = isEdit
? "Data updated successfully!"
: "Data created successfully!";
toast.classList.add("show"); // Show the toast
setTimeout(() => {
toast.classList.remove("show"); // Hide the toast after 3 seconds
}, 2000);
setTimeout(() => {
window.location.href = "/data/advertisements/index";
}, 1000);
} else {
if (authLogo) {
// Hapus ikon yang sudah ada jika ada
const existingIcon = authLogo.querySelector(".bx");
if (existingIcon) {
authLogo.removeChild(existingIcon);
}
// Buat ikon baru
const icon = document.createElement("i");
icon.classList.add("bx", "bxs-error-alt");
icon.style.fontSize = "25px";
icon.style.color = "red"; // Pastikan 'green' dalam bentuk string
// Tambahkan ikon ke dalam auth-logo
authLogo.appendChild(icon);
}
// Enable button and reset its text on error
modalButton.disabled = false;
modalButton.innerHTML = isEdit ? "Update" : "Create";
// Set error message for the toast
toastBody.textContent =
"Failed: " + (data.message || "Something went wrong");
toast.classList.add("show"); // Show the toast
setTimeout(() => {
toast.classList.remove("show"); // Hide the toast after 3 seconds
}, 3000);
}
})
.catch((errors) => {
if (authLogo) {
// Hapus ikon yang sudah ada jika ada
const existingIcon = authLogo.querySelector(".bx");
if (existingIcon) {
authLogo.removeChild(existingIcon);
}
// Buat ikon baru
const icon = document.createElement("i");
icon.classList.add("bx", "bxs-error-alt");
icon.style.fontSize = "25px";
icon.style.color = "red"; // Pastikan 'green' dalam bentuk string
// Tambahkan ikon ke dalam auth-logo
authLogo.appendChild(icon);
}
// Enable button and reset its text on error // Enable button and reset its text on error
modalButton.disabled = false; modalButton.disabled = false;
modalButton.innerHTML = isEdit ? "Update" : "Create"; modalButton.innerHTML = isEdit ? "Update" : "Create";
// Set error message for the toast // Set error message for the toast
toastBody.textContent = "Failed: " + (data.message || "Something went wrong"); toastBody.textContent =
toast.classList.add('show'); // Show the toast "An error occurred while processing your request.";
toast.classList.add("show"); // Show the toast
setTimeout(() => { setTimeout(() => {
toast.classList.remove('show'); // Hide the toast after 3 seconds toast.classList.remove("show"); // Hide the toast after 3 seconds
}, 3000); }, 3000);
} });
})
.catch(errors => {
if (authLogo) {
// Hapus ikon yang sudah ada jika ada
const existingIcon = authLogo.querySelector('.bx');
if (existingIcon) {
authLogo.removeChild(existingIcon);
}
// Buat ikon baru
const icon = document.createElement('i');
icon.classList.add('bx', 'bxs-error-alt');
icon.style.fontSize = '25px';
icon.style.color = 'red'; // Pastikan 'green' dalam bentuk string
// Tambahkan ikon ke dalam auth-logo
authLogo.appendChild(icon);
}
// Enable button and reset its text on error
modalButton.disabled = false;
modalButton.innerHTML = isEdit ? "Update" : "Create";
// Set error message for the toast
toastBody.textContent = "An error occurred while processing your request.";
toast.classList.add('show'); // Show the toast
setTimeout(() => {
toast.classList.remove('show'); // Hide the toast after 3 seconds
}, 3000);
});
}); });
// Fungsi fetchOptions untuk autocomplete server-side // Fungsi fetchOptions untuk autocomplete server-side
@@ -140,39 +144,43 @@ document.addEventListener("DOMContentLoaded", function () {
let inputValue = document.getElementById(field).value; let inputValue = document.getElementById(field).value;
if (inputValue.length < 2) return; if (inputValue.length < 2) return;
let districtValue = document.getElementById("district_name").value; // Ambil kecamatan terpilih let districtValue = document.getElementById("district_name").value; // Ambil kecamatan terpilih
let url = `${GlobalConfig.apiHost}/api/combobox/search-options?query=${encodeURIComponent(inputValue)}&field=${field}`; let url = `${
GlobalConfig.apiHost
}/api/combobox/search-options?query=${encodeURIComponent(
inputValue
)}&field=${field}`;
// Jika field desa, tambahkan kecamatan sebagai filter // Jika field desa, tambahkan kecamatan sebagai filter
if (field === "village_name") { if (field === "village_name") {
url += `&district=${encodeURIComponent(districtValue)}`; url += `&district=${encodeURIComponent(districtValue)}`;
} }
fetch(url, { fetch(url, {
method: 'GET', method: "GET",
headers: { headers: {
Authorization: `Bearer ${document Authorization: `Bearer ${document
.querySelector('meta[name="api-token"]') .querySelector('meta[name="api-token"]')
.getAttribute("content")}`, .getAttribute("content")}`,
"Content-Type": "application/json", "Content-Type": "application/json",
} },
}) })
.then(response => response.json()) .then((response) => response.json())
.then(data => { .then((data) => {
let dataList = document.getElementById(field + "Options"); let dataList = document.getElementById(field + "Options");
dataList.innerHTML = ""; dataList.innerHTML = "";
data.forEach(item => { data.forEach((item) => {
let option = document.createElement("option"); let option = document.createElement("option");
option.value = item.name; option.value = item.name;
option.dataset.code = item.code; option.dataset.code = item.code;
dataList.appendChild(option); dataList.appendChild(option);
}); });
}) })
.catch(error => console.error("Error fetching options:", error)); .catch((error) => console.error("Error fetching options:", error));
}; };
document.querySelector('.btn-back').addEventListener('click', function() { document.querySelector(".btn-back").addEventListener("click", function () {
window.history.back(); window.history.back();
}); });
}); });

View File

@@ -18,58 +18,61 @@ console.log(dropzonePreviewNode);
url: `${GlobalConfig.apiHost}/api/advertisements/import`, url: `${GlobalConfig.apiHost}/api/advertisements/import`,
// url: "https://httpbin.org/post", // url: "https://httpbin.org/post",
method: "post", method: "post",
acceptedFiles: ".xls,.xlsx", // Use acceptedFiles for better validation acceptedFiles: ".xls,.xlsx", // Use acceptedFiles for better validation
previewTemplate: previewTemplate, previewTemplate: previewTemplate,
previewsContainer: "#dropzone-preview", previewsContainer: "#dropzone-preview",
autoProcessQueue: false, // Disable auto post autoProcessQueue: false, // Disable auto post
headers: { headers: {
Authorization: `Bearer ${document Authorization: `Bearer ${document
.querySelector('meta[name="api-token"]') .querySelector('meta[name="api-token"]')
.getAttribute("content")}` .getAttribute("content")}`,
}, },
init: function() { init: function () {
// Listen for the success event // Listen for the success event
this.on("success", function(file, response) { this.on("success", function (file, response) {
console.log("File successfully uploaded:", file); console.log("File successfully uploaded:", file);
console.log("API Response:", response); console.log("API Response:", response);
// Show success toast // Show success toast
showToast('bxs-check-square', 'green', response.message); showToast("bxs-check-square", "green", response.message);
document.getElementById("submit-upload").innerHTML = "Upload Files"; document.getElementById("submit-upload").innerHTML =
"Upload Files";
// Tunggu sebentar lalu reload halaman // Tunggu sebentar lalu reload halaman
setTimeout(() => { setTimeout(() => {
window.location.href = "/data/advertisements"; window.location.href = "/data/advertisements/index";
}, 2000); }, 2000);
}); });
// Listen for the error event // Listen for the error event
this.on("error", function(file, errorMessage) { this.on("error", function (file, errorMessage) {
console.error("Error uploading file:", file); console.error("Error uploading file:", file);
console.error("Error message:", errorMessage); console.error("Error message:", errorMessage);
// Handle the error response // Handle the error response
// Show error toast // Show error toast
showToast('bxs-error-alt', 'red', errorMessage.message); showToast("bxs-error-alt", "red", errorMessage.message);
document.getElementById("submit-upload").innerHTML = "Upload Files"; document.getElementById("submit-upload").innerHTML =
"Upload Files";
}); });
} },
}))); })));
// Add event listener to control the submission manually // Add event listener to control the submission manually
document.querySelector("#submit-upload").addEventListener("click", function() { document.querySelector("#submit-upload").addEventListener("click", function () {
console.log("Ini adalah value dropzone", dropzone.files[0]); console.log("Ini adalah value dropzone", dropzone.files[0]);
const formData = new FormData() const formData = new FormData();
console.log("Dropzonefiles",dropzone.files); console.log("Dropzonefiles", dropzone.files);
this.innerHTML = '<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>Loading...'; this.innerHTML =
'<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>Loading...';
// Pastikan ada file dalam queue sebelum memprosesnya // Pastikan ada file dalam queue sebelum memprosesnya
if (dropzone.files.length > 0) { if (dropzone.files.length > 0) {
formData.append('file', dropzone.files[0]) formData.append("file", dropzone.files[0]);
console.log("ini adalah form data on submit", ...formData); console.log("ini adalah form data on submit", ...formData);
dropzone.processQueue(); // Ini akan manual memicu upload dropzone.processQueue(); // Ini akan manual memicu upload
} else { } else {
// Show error toast when no file is selected // Show error toast when no file is selected
showToast('bxs-error-alt', 'red', "Please add a file first."); showToast("bxs-error-alt", "red", "Please add a file first.");
document.getElementById("submit-upload").innerHTML = "Upload Files"; document.getElementById("submit-upload").innerHTML = "Upload Files";
} }
}); });
@@ -82,62 +85,68 @@ dropzone.on("addedfile", function (file) {
console.log("Ukuran File:", (file.size / 1024).toFixed(2) + " KB"); console.log("Ukuran File:", (file.size / 1024).toFixed(2) + " KB");
}); });
dropzone.on("complete", function(file) { dropzone.on("complete", function (file) {
dropzone.removeFile(file); dropzone.removeFile(file);
}); });
// Add event listener to donwload file template // Add event listener to donwload file template
document.getElementById('downloadtempadvertisement').addEventListener('click', function() { document
var url = `${GlobalConfig.apiHost}/api/download-template-advertisement`; .getElementById("downloadtempadvertisement")
fetch(url, { .addEventListener("click", function () {
method: 'GET', var url = `${GlobalConfig.apiHost}/api/download-template-advertisement`;
headers: { fetch(url, {
Authorization: `Bearer ${document method: "GET",
.querySelector('meta[name="api-token"]') headers: {
.getAttribute("content")}` Authorization: `Bearer ${document
}, .querySelector('meta[name="api-token"]')
}) .getAttribute("content")}`,
.then(response => { },
if (response.ok) { })
return response.blob(); .then((response) => {
} else { if (response.ok) {
return response.json(); return response.blob();
} } else {
}) return response.json();
.then((blob) => { }
const url = window.URL.createObjectURL(blob); })
const a = document.createElement('a'); .then((blob) => {
a.style.display = 'none'; const url = window.URL.createObjectURL(blob);
a.href = url; const a = document.createElement("a");
a.download = 'template_reklame.xlsx'; a.style.display = "none";
document.body.appendChild(a); a.href = url;
a.click(); a.download = "template_reklame.xlsx";
window.URL.revokeObjectURL(url); document.body.appendChild(a);
}) a.click();
.catch((error) => { window.URL.revokeObjectURL(url);
console.error("Gagal mendownload file:", error); })
showToast('bxs-error-alt', 'red', "Template file is not already exist."); .catch((error) => {
}) console.error("Gagal mendownload file:", error);
}) showToast(
"bxs-error-alt",
"red",
"Template file is not already exist."
);
});
});
// Function to show toast // Function to show toast
function showToast(iconClass, iconColor, message) { function showToast(iconClass, iconColor, message) {
const toastElement = document.getElementById('toastUploadAdvertisement'); const toastElement = document.getElementById("toastUploadAdvertisement");
const toastBody = toastElement.querySelector('.toast-body'); const toastBody = toastElement.querySelector(".toast-body");
const toastHeader = toastElement.querySelector('.toast-header'); const toastHeader = toastElement.querySelector(".toast-header");
// Remove existing icon (if any) before adding the new one // Remove existing icon (if any) before adding the new one
const existingIcon = toastHeader.querySelector('.bx'); const existingIcon = toastHeader.querySelector(".bx");
if (existingIcon) { if (existingIcon) {
toastHeader.querySelector('.auth-logo').removeChild(existingIcon); // Remove the existing icon toastHeader.querySelector(".auth-logo").removeChild(existingIcon); // Remove the existing icon
} }
// Add the new icon to the toast header // Add the new icon to the toast header
const icon = document.createElement('i'); const icon = document.createElement("i");
icon.classList.add('bx', iconClass); icon.classList.add("bx", iconClass);
icon.style.fontSize = '25px'; icon.style.fontSize = "25px";
icon.style.color = iconColor; icon.style.color = iconColor;
toastHeader.querySelector('.auth-logo').appendChild(icon); toastHeader.querySelector(".auth-logo").appendChild(icon);
// Set the toast message // Set the toast message
toastBody.textContent = message; toastBody.textContent = message;
@@ -146,4 +155,3 @@ function showToast(iconClass, iconColor, message) {
const toast = new bootstrap.Toast(toastElement); // Inisialisasi Bootstrap Toast const toast = new bootstrap.Toast(toastElement); // Inisialisasi Bootstrap Toast
toast.show(); toast.show();
} }

View File

@@ -77,7 +77,9 @@ Route::group(['middleware' => 'auth'], function(){
// data // data
Route::group(['prefix' => '/data'], function(){ Route::group(['prefix' => '/data'], function(){
// Resource route, kecuali create karena dibuat terpisah // Resource route, kecuali create karena dibuat terpisah
Route::resource('/advertisements', AdvertisementController::class)->except(['create', 'show']); Route::resource('/advertisements', AdvertisementController::class)->except(['create', 'show', 'index']);
Route::get('/advertisements/index', [AdvertisementController::class, 'index'])->name('web.advertisements.index');
// Rute khusus untuk create dan bulk-create // Rute khusus untuk create dan bulk-create
Route::get('/advertisements/create', [AdvertisementController::class, 'create'])->name('advertisements.create'); Route::get('/advertisements/create', [AdvertisementController::class, 'create'])->name('advertisements.create');