fixed
This commit is contained in:
1
backend/web/admin/assets/css/app.css
Normal file
1
backend/web/admin/assets/css/app.css
Normal file
File diff suppressed because one or more lines are too long
188
backend/web/admin/assets/js/api.js
Normal file
188
backend/web/admin/assets/js/api.js
Normal file
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* API client for the bankline admin API.
|
||||
*
|
||||
* - Sends the raw JWT access token in the Authorization header
|
||||
* (the backend middleware expects the bare token, no "Bearer " prefix).
|
||||
* - Unwraps the response envelope { status, message, code, data }.
|
||||
* - On 401 tries a one-shot refresh via POST /v1/admin/token, then retries.
|
||||
* - Throws ApiError with a friendly, human-readable message.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const ACCESS_KEY = "bankline_admin_access";
|
||||
const REFRESH_KEY = "bankline_admin_refresh";
|
||||
const LOGIN_PAGE = "/admin/login";
|
||||
|
||||
class ApiError extends Error {
|
||||
constructor(message, status, code) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status || 0;
|
||||
this.code = code || "";
|
||||
}
|
||||
}
|
||||
|
||||
function friendlyMessage(status, fallback) {
|
||||
switch (status) {
|
||||
case 400:
|
||||
return fallback || "The request is invalid. Please check the form and try again.";
|
||||
case 401:
|
||||
return "Your session has expired. Please sign in again.";
|
||||
case 403:
|
||||
return "You don't have permission to perform this action.";
|
||||
case 404:
|
||||
return "The requested item was not found.";
|
||||
case 422:
|
||||
return fallback || "The submitted data is invalid.";
|
||||
case 500:
|
||||
return "Something went wrong on the server. Please try again.";
|
||||
default:
|
||||
return fallback || "An unexpected error occurred. Please try again.";
|
||||
}
|
||||
}
|
||||
|
||||
const tokens = {
|
||||
get access() {
|
||||
return localStorage.getItem(ACCESS_KEY) || "";
|
||||
},
|
||||
get refresh() {
|
||||
return localStorage.getItem(REFRESH_KEY) || "";
|
||||
},
|
||||
set(pair) {
|
||||
localStorage.setItem(ACCESS_KEY, pair.accessToken || "");
|
||||
localStorage.setItem(REFRESH_KEY, pair.refreshToken || "");
|
||||
},
|
||||
clear() {
|
||||
localStorage.removeItem(ACCESS_KEY);
|
||||
localStorage.removeItem(REFRESH_KEY);
|
||||
},
|
||||
};
|
||||
|
||||
function redirectToLogin() {
|
||||
tokens.clear();
|
||||
if (!window.location.pathname.startsWith(LOGIN_PAGE)) {
|
||||
window.location.href = LOGIN_PAGE;
|
||||
}
|
||||
}
|
||||
|
||||
async function parseEnvelope(response) {
|
||||
let payload = null;
|
||||
try {
|
||||
payload = await response.json();
|
||||
} catch (_) {
|
||||
/* non-JSON body */
|
||||
}
|
||||
|
||||
if (response.ok && payload && payload.status === true) {
|
||||
return payload.data;
|
||||
}
|
||||
if (response.ok && payload && payload.status === undefined) {
|
||||
// A few endpoints (e.g. JWT middleware errors) don't use the envelope.
|
||||
return payload;
|
||||
}
|
||||
|
||||
const serverMessage =
|
||||
(payload && (payload.message || payload.error)) || "";
|
||||
throw new ApiError(
|
||||
friendlyMessage(response.status, serverMessage),
|
||||
response.status,
|
||||
payload && payload.code
|
||||
);
|
||||
}
|
||||
|
||||
async function refreshTokens() {
|
||||
const refreshToken = tokens.refresh;
|
||||
if (!refreshToken) return false;
|
||||
try {
|
||||
const response = await fetch("/v1/admin/token", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refreshToken }),
|
||||
});
|
||||
if (!response.ok) return false;
|
||||
const payload = await response.json();
|
||||
const pair = payload && payload.data;
|
||||
if (pair && pair.accessToken) {
|
||||
tokens.set(pair);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform an authenticated JSON request.
|
||||
* @param {string} method HTTP method
|
||||
* @param {string} path request path, e.g. /v1/admin/news
|
||||
* @param {{ body?: object, query?: object, formData?: FormData, retried?: boolean }} [options]
|
||||
*/
|
||||
async function request(method, path, options) {
|
||||
options = options || {};
|
||||
|
||||
let url = path;
|
||||
if (options.query) {
|
||||
const params = new URLSearchParams();
|
||||
Object.entries(options.query).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== null && value !== "") {
|
||||
params.set(key, value);
|
||||
}
|
||||
});
|
||||
const qs = params.toString();
|
||||
if (qs) url += "?" + qs;
|
||||
}
|
||||
|
||||
const headers = {};
|
||||
if (tokens.access) headers["Authorization"] = tokens.access;
|
||||
|
||||
let body;
|
||||
if (options.formData) {
|
||||
body = options.formData;
|
||||
} else if (options.body !== undefined) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
body = JSON.stringify(options.body);
|
||||
}
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(url, { method, headers, body });
|
||||
} catch (_) {
|
||||
throw new ApiError(
|
||||
"Network error. Please check your connection and try again.",
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
if ((response.status === 401 || response.status === 403) && !options.retried) {
|
||||
const refreshed = await refreshTokens();
|
||||
if (refreshed) {
|
||||
return request(method, path, Object.assign({}, options, { retried: true }));
|
||||
}
|
||||
redirectToLogin();
|
||||
throw new ApiError(friendlyMessage(401), response.status);
|
||||
}
|
||||
|
||||
return parseEnvelope(response);
|
||||
}
|
||||
|
||||
/** Upload a file; resolves to its public path (e.g. /images/123.png). */
|
||||
function upload(file) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return request("POST", "/v1/admin/file", { formData });
|
||||
}
|
||||
|
||||
window.Api = {
|
||||
ApiError,
|
||||
tokens,
|
||||
redirectToLogin,
|
||||
get: (path, query) => request("GET", path, { query }),
|
||||
post: (path, body) => request("POST", path, { body }),
|
||||
put: (path, body) => request("PUT", path, { body }),
|
||||
del: (path) => request("DELETE", path, {}),
|
||||
request,
|
||||
upload,
|
||||
};
|
||||
})();
|
||||
66
backend/web/admin/assets/js/auth.js
Normal file
66
backend/web/admin/assets/js/auth.js
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Authentication helpers: login, logout, page guard and header profile.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
/** Redirect to the login page when no access token is stored. */
|
||||
function requireAuth() {
|
||||
if (!Api.tokens.access) {
|
||||
Api.redirectToLogin();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Sign in and store the token pair. */
|
||||
async function login(loginValue, password) {
|
||||
const pair = await Api.post("/v1/admin/login", {
|
||||
login: loginValue,
|
||||
password: password,
|
||||
});
|
||||
if (!pair || !pair.accessToken) {
|
||||
throw new Api.ApiError("Login failed. Please try again.", 500);
|
||||
}
|
||||
Api.tokens.set(pair);
|
||||
}
|
||||
|
||||
function logout() {
|
||||
Api.tokens.clear();
|
||||
window.location.href = "/admin/login";
|
||||
}
|
||||
|
||||
/** Load the admin profile and render it into the header. */
|
||||
async function loadProfile() {
|
||||
const nameEl = document.getElementById("profile-name");
|
||||
const avatarEl = document.getElementById("profile-avatar");
|
||||
const initialEl = document.getElementById("profile-initial");
|
||||
if (!nameEl) return;
|
||||
try {
|
||||
const profile = await Api.get("/v1/admin/get-profile");
|
||||
const fullName = (profile && profile.fullName) || "Admin";
|
||||
nameEl.textContent = fullName;
|
||||
if (avatarEl && profile && profile.avatar) {
|
||||
avatarEl.src = profile.avatar;
|
||||
avatarEl.alt = fullName;
|
||||
avatarEl.classList.remove("hidden");
|
||||
if (initialEl) initialEl.classList.add("hidden");
|
||||
} else if (initialEl) {
|
||||
initialEl.textContent = fullName.charAt(0).toUpperCase();
|
||||
}
|
||||
} catch (_) {
|
||||
/* profile is decorative; auth errors already redirect */
|
||||
}
|
||||
}
|
||||
|
||||
function bindLogoutButtons() {
|
||||
document.querySelectorAll("[data-logout]").forEach((button) => {
|
||||
button.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
logout();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
window.Auth = { requireAuth, login, logout, loadProfile, bindLogoutButtons };
|
||||
})();
|
||||
63
backend/web/admin/assets/js/dashboard.js
Normal file
63
backend/web/admin/assets/js/dashboard.js
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Dashboard: content count cards and the latest news list.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const CARDS = [
|
||||
{ id: "stat-news", endpoint: "/v1/admin/news", listKey: "news" },
|
||||
{ id: "stat-categories", endpoint: "/v1/admin/categories", listKey: "categories" },
|
||||
{ id: "stat-banners", endpoint: "/v1/admin/banner", listKey: "banners" },
|
||||
{ id: "stat-static", endpoint: "/v1/admin/static", listKey: "statics" },
|
||||
{ id: "stat-currency", endpoint: "/v1/admin/currency", listKey: "currencies" },
|
||||
];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (document.body.dataset.page !== "dashboard") return;
|
||||
if (!Auth.requireAuth()) return;
|
||||
|
||||
Auth.loadProfile();
|
||||
Auth.bindLogoutButtons();
|
||||
|
||||
CARDS.forEach(async (card) => {
|
||||
const valueEl = document.querySelector("#" + card.id + " [data-stat-value]");
|
||||
if (!valueEl) return;
|
||||
try {
|
||||
const data = await Api.get(card.endpoint, { limit: 1, page: 1 });
|
||||
valueEl.textContent = (data && data.count) || 0;
|
||||
} catch (_) {
|
||||
valueEl.textContent = "—";
|
||||
}
|
||||
});
|
||||
|
||||
loadLatestNews();
|
||||
});
|
||||
|
||||
async function loadLatestNews() {
|
||||
const container = document.getElementById("latest-news");
|
||||
if (!container) return;
|
||||
try {
|
||||
const data = await Api.get("/v1/admin/news", { limit: 5, page: 1 });
|
||||
const items = (data && data.news) || [];
|
||||
if (!items.length) {
|
||||
container.innerHTML =
|
||||
'<li class="py-4 text-base-content/60">No news yet.</li>';
|
||||
return;
|
||||
}
|
||||
container.innerHTML = items
|
||||
.map(
|
||||
(item) => `
|
||||
<li class="flex items-center gap-3 py-3">
|
||||
${item.imagePath ? `<img src="${UI.escapeHtml(item.imagePath)}" alt="" class="h-10 w-14 rounded object-cover" loading="lazy">` : ""}
|
||||
<div class="min-w-0 flex-1">
|
||||
<a href="/admin/news/${item.Id}/edit" class="block truncate font-medium hover:text-primary">${UI.escapeHtml(langText(item.title))}</a>
|
||||
<span class="text-sm text-base-content/60">${UI.escapeHtml(UI.formatDate(item.dateRelease))}</span>
|
||||
</div>
|
||||
</li>`
|
||||
)
|
||||
.join("");
|
||||
} catch (error) {
|
||||
container.innerHTML = `<li class="py-4 text-error">${UI.escapeHtml(error.message)}</li>`;
|
||||
}
|
||||
}
|
||||
})();
|
||||
417
backend/web/admin/assets/js/form.js
Normal file
417
backend/web/admin/assets/js/form.js
Normal file
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* Generic create/edit form engine.
|
||||
*
|
||||
* Builds the form from the resource schema in resources.js, handles
|
||||
* multilingual (TM/RU/EN) tabbed inputs, Quill rich text, image uploads
|
||||
* with preview, client-side required validation with inline errors and submit.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const LANGS = [
|
||||
{ code: "tm", label: "TM" },
|
||||
{ code: "ru", label: "RU" },
|
||||
{ code: "en", label: "EN" },
|
||||
];
|
||||
|
||||
const QUILL_TOOLBAR = [
|
||||
[{ header: [1, 2, 3, false] }],
|
||||
["bold", "italic", "underline", "strike"],
|
||||
[{ list: "ordered" }, { list: "bullet" }],
|
||||
["link"],
|
||||
["clean"],
|
||||
];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const body = document.body;
|
||||
if (body.dataset.page !== "form") return;
|
||||
if (!Auth.requireAuth()) return;
|
||||
|
||||
const slug = body.dataset.resource;
|
||||
const mode = body.dataset.mode; // create | edit
|
||||
const recordId = body.dataset.id || "";
|
||||
const schema = Resources[slug];
|
||||
if (!schema) return;
|
||||
|
||||
const form = document.getElementById("resource-form");
|
||||
const fieldsContainer = document.getElementById("form-fields");
|
||||
const submitButton = document.getElementById("form-submit");
|
||||
let record = null;
|
||||
const richEditors = {};
|
||||
|
||||
// ----- field builders ----------------------------------------------------
|
||||
|
||||
function fieldWrapper(field, inner) {
|
||||
return `
|
||||
<div class="form-control w-full" data-field="${field.name}">
|
||||
<label class="label" for="field-${field.name}">
|
||||
<span class="label-text font-medium">${UI.escapeHtml(field.label)}${field.required ? ' <span class="text-error" aria-hidden="true">*</span>' : ""}</span>
|
||||
</label>
|
||||
${inner}
|
||||
${field.help ? `<p class="label-text-alt mt-1 text-base-content/60">${UI.escapeHtml(field.help)}</p>` : ""}
|
||||
<p class="mt-1 hidden text-sm text-error" data-error role="alert"></p>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function langTabsHtml(field, isTextarea) {
|
||||
const tabs = LANGS.map(
|
||||
(lang, index) =>
|
||||
`<button type="button" role="tab" aria-selected="${index === 0}" ` +
|
||||
`class="tab ${index === 0 ? "tab-active" : ""}" data-lang-tab="${lang.code}">${lang.label}</button>`
|
||||
).join("");
|
||||
const inputs = LANGS.map((lang, index) => {
|
||||
const shared = `id="field-${field.name}-${lang.code}" data-lang-input="${lang.code}" ` +
|
||||
`class="${isTextarea ? "textarea textarea-bordered w-full" : "input input-bordered w-full"} ${index === 0 ? "" : "hidden"}" ` +
|
||||
`placeholder="${UI.escapeHtml(field.label)} (${lang.label})" aria-label="${UI.escapeHtml(field.label)} in ${lang.label}"`;
|
||||
return isTextarea
|
||||
? `<textarea ${shared} rows="${field.rows || 5}"></textarea>`
|
||||
: `<input type="text" ${shared}>`;
|
||||
}).join("");
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<div role="tablist" class="tabs tabs-boxed mb-2 w-fit">${tabs}</div>${inputs}`
|
||||
);
|
||||
}
|
||||
|
||||
function langRichHtml(field) {
|
||||
const tabs = LANGS.map(
|
||||
(lang, index) =>
|
||||
`<button type="button" role="tab" aria-selected="${index === 0}" ` +
|
||||
`class="tab ${index === 0 ? "tab-active" : ""}" data-lang-tab="${lang.code}">${lang.label}</button>`
|
||||
).join("");
|
||||
const panels = LANGS.map(
|
||||
(lang, index) =>
|
||||
`<div data-lang-panel="${lang.code}" class="${index === 0 ? "" : "hidden"} rounded-lg border border-base-300 bg-base-100">` +
|
||||
`<div id="field-${field.name}-${lang.code}" class="min-h-[12rem]" aria-label="${UI.escapeHtml(field.label)} in ${lang.label}"></div>` +
|
||||
`</div>`
|
||||
).join("");
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<div role="tablist" class="tabs tabs-boxed mb-2 w-fit">${tabs}</div>${panels}`
|
||||
);
|
||||
}
|
||||
|
||||
function inputHtml(field) {
|
||||
const type = field.type === "date" ? "date" : "text";
|
||||
const pattern = field.numeric ? 'inputmode="decimal" pattern="[0-9]*[.,]?[0-9]*"' : "";
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<input type="${type}" id="field-${field.name}" class="input input-bordered w-full" ` +
|
||||
`placeholder="${UI.escapeHtml(field.placeholder || "")}" value="${UI.escapeHtml(field.defaultValue || "")}" ${pattern}>`
|
||||
);
|
||||
}
|
||||
|
||||
function textareaHtml(field) {
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<textarea id="field-${field.name}" class="textarea textarea-bordered w-full" rows="${field.rows || 5}"></textarea>`
|
||||
);
|
||||
}
|
||||
|
||||
function selectHtml(field) {
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<select id="field-${field.name}" class="select select-bordered w-full">
|
||||
<option value="" disabled selected>Loading…</option>
|
||||
</select>`
|
||||
);
|
||||
}
|
||||
|
||||
function imageHtml(field) {
|
||||
return fieldWrapper(
|
||||
field,
|
||||
`<div class="flex flex-col gap-3">
|
||||
<img data-image-preview alt="Preview" class="hidden h-32 w-fit max-w-xs rounded-lg border border-base-300 object-contain">
|
||||
<input type="hidden" data-image-path>
|
||||
<div class="flex items-center gap-3">
|
||||
<input type="file" id="field-${field.name}" accept="image/*" class="file-input file-input-bordered w-full max-w-xs">
|
||||
<span data-upload-spinner class="loading loading-spinner loading-sm hidden" aria-label="Uploading"></span>
|
||||
</div>
|
||||
</div>`
|
||||
);
|
||||
}
|
||||
|
||||
function quillHtml(quill) {
|
||||
if (!quill) return "";
|
||||
const text = quill.getText().replace(/\n/g, "").trim();
|
||||
if (!text) return "";
|
||||
return quill.root.innerHTML;
|
||||
}
|
||||
|
||||
function initRichEditors() {
|
||||
if (typeof Quill === "undefined") return;
|
||||
schema.fields
|
||||
.filter((field) => field.type === "lang-richtext")
|
||||
.forEach((field) => {
|
||||
richEditors[field.name] = {};
|
||||
LANGS.forEach((lang) => {
|
||||
const el = document.getElementById("field-" + field.name + "-" + lang.code);
|
||||
if (!el) return;
|
||||
richEditors[field.name][lang.code] = new Quill(el, {
|
||||
theme: "snow",
|
||||
modules: { toolbar: QUILL_TOOLBAR },
|
||||
placeholder: field.label + " (" + lang.label + ")",
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function buildFields() {
|
||||
fieldsContainer.innerHTML = schema.fields
|
||||
.map((field) => {
|
||||
switch (field.type) {
|
||||
case "lang":
|
||||
return langTabsHtml(field, false);
|
||||
case "lang-textarea":
|
||||
return langTabsHtml(field, true);
|
||||
case "lang-richtext":
|
||||
return langRichHtml(field);
|
||||
case "textarea":
|
||||
return textareaHtml(field);
|
||||
case "select":
|
||||
return selectHtml(field);
|
||||
case "image":
|
||||
return imageHtml(field);
|
||||
default:
|
||||
return inputHtml(field);
|
||||
}
|
||||
})
|
||||
.join("");
|
||||
|
||||
// Language tab switching.
|
||||
fieldsContainer.querySelectorAll("[data-field]").forEach((wrapper) => {
|
||||
const tabs = wrapper.querySelectorAll("[data-lang-tab]");
|
||||
if (!tabs.length) return;
|
||||
tabs.forEach((tab) => {
|
||||
tab.addEventListener("click", () => {
|
||||
tabs.forEach((t) => {
|
||||
t.classList.toggle("tab-active", t === tab);
|
||||
t.setAttribute("aria-selected", String(t === tab));
|
||||
});
|
||||
const code = tab.dataset.langTab;
|
||||
wrapper.querySelectorAll("[data-lang-input]").forEach((input) => {
|
||||
input.classList.toggle("hidden", input.dataset.langInput !== code);
|
||||
});
|
||||
wrapper.querySelectorAll("[data-lang-panel]").forEach((panel) => {
|
||||
panel.classList.toggle("hidden", panel.dataset.langPanel !== code);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
initRichEditors();
|
||||
|
||||
// Image upload handling.
|
||||
schema.fields
|
||||
.filter((field) => field.type === "image")
|
||||
.forEach((field) => {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${field.name}"]`);
|
||||
const fileInput = wrapper.querySelector('input[type="file"]');
|
||||
const pathInput = wrapper.querySelector("[data-image-path]");
|
||||
const preview = wrapper.querySelector("[data-image-preview]");
|
||||
const spinner = wrapper.querySelector("[data-upload-spinner]");
|
||||
|
||||
fileInput.addEventListener("change", async () => {
|
||||
const file = fileInput.files && fileInput.files[0];
|
||||
if (!file) return;
|
||||
spinner.classList.remove("hidden");
|
||||
fileInput.disabled = true;
|
||||
try {
|
||||
const path = await Api.upload(file);
|
||||
pathInput.value = path;
|
||||
preview.src = path;
|
||||
preview.classList.remove("hidden");
|
||||
clearError(field.name);
|
||||
UI.toast("Image uploaded", "success");
|
||||
} catch (error) {
|
||||
UI.toast(error.message, "error");
|
||||
} finally {
|
||||
spinner.classList.add("hidden");
|
||||
fileInput.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function loadSelectOptions() {
|
||||
const selectFields = schema.fields.filter((field) => field.type === "select");
|
||||
await Promise.all(
|
||||
selectFields.map(async (field) => {
|
||||
const select = document.getElementById("field-" + field.name);
|
||||
try {
|
||||
const data = await Api.get(field.options.endpoint, { limit: 0, page: 0 });
|
||||
const items = (data && data[field.options.listKey]) || [];
|
||||
select.innerHTML =
|
||||
'<option value="" disabled selected>Select…</option>' +
|
||||
items
|
||||
.map(
|
||||
(item) =>
|
||||
`<option value="${item[field.options.valueField]}">${UI.escapeHtml(langText(item[field.options.labelField]))}</option>`
|
||||
)
|
||||
.join("");
|
||||
} catch (error) {
|
||||
select.innerHTML = '<option value="" disabled selected>Failed to load</option>';
|
||||
UI.toast(error.message, "error");
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ----- values ------------------------------------------------------------
|
||||
|
||||
function setError(name, message) {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${name}"]`);
|
||||
if (!wrapper) return;
|
||||
const errorEl = wrapper.querySelector("[data-error]");
|
||||
errorEl.textContent = message;
|
||||
errorEl.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function clearError(name) {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${name}"]`);
|
||||
if (!wrapper) return;
|
||||
const errorEl = wrapper.querySelector("[data-error]");
|
||||
errorEl.textContent = "";
|
||||
errorEl.classList.add("hidden");
|
||||
}
|
||||
|
||||
function isLangField(type) {
|
||||
return type === "lang" || type === "lang-textarea" || type === "lang-richtext";
|
||||
}
|
||||
|
||||
function collectValues() {
|
||||
const values = {};
|
||||
schema.fields.forEach((field) => {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${field.name}"]`);
|
||||
if (field.type === "lang-richtext") {
|
||||
const value = {};
|
||||
LANGS.forEach((lang) => {
|
||||
value[lang.code] = quillHtml(richEditors[field.name] && richEditors[field.name][lang.code]);
|
||||
});
|
||||
values[field.name] = value;
|
||||
} else if (field.type === "lang" || field.type === "lang-textarea") {
|
||||
const value = {};
|
||||
wrapper.querySelectorAll("[data-lang-input]").forEach((input) => {
|
||||
value[input.dataset.langInput] = input.value.trim();
|
||||
});
|
||||
values[field.name] = value;
|
||||
} else if (field.type === "image") {
|
||||
values[field.name] = wrapper.querySelector("[data-image-path]").value;
|
||||
} else if (field.type === "date") {
|
||||
const raw = document.getElementById("field-" + field.name).value;
|
||||
values[field.name] = raw ? raw + "T00:00:00Z" : "";
|
||||
} else {
|
||||
values[field.name] = document.getElementById("field-" + field.name).value.trim();
|
||||
}
|
||||
});
|
||||
return values;
|
||||
}
|
||||
|
||||
function validate(values) {
|
||||
let valid = true;
|
||||
schema.fields.forEach((field) => {
|
||||
clearError(field.name);
|
||||
if (!field.required) return;
|
||||
const value = values[field.name];
|
||||
if (isLangField(field.type)) {
|
||||
if (!value.tm && !value.ru && !value.en) {
|
||||
setError(field.name, "Fill in at least one language.");
|
||||
valid = false;
|
||||
}
|
||||
} else if (!value) {
|
||||
setError(
|
||||
field.name,
|
||||
field.type === "image" ? "Please upload an image." : "This field is required."
|
||||
);
|
||||
valid = false;
|
||||
}
|
||||
});
|
||||
return valid;
|
||||
}
|
||||
|
||||
function populate(values) {
|
||||
schema.fields.forEach((field) => {
|
||||
const wrapper = fieldsContainer.querySelector(`[data-field="${field.name}"]`);
|
||||
const value = values[field.name];
|
||||
if (value === undefined || value === null) return;
|
||||
if (field.type === "lang-richtext") {
|
||||
LANGS.forEach((lang) => {
|
||||
const quill = richEditors[field.name] && richEditors[field.name][lang.code];
|
||||
if (!quill) return;
|
||||
const html = (value && value[lang.code]) || "";
|
||||
quill.setContents([]);
|
||||
if (html) {
|
||||
quill.clipboard.dangerouslyPasteHTML(html);
|
||||
}
|
||||
});
|
||||
} else if (field.type === "lang" || field.type === "lang-textarea") {
|
||||
wrapper.querySelectorAll("[data-lang-input]").forEach((input) => {
|
||||
input.value = (value && value[input.dataset.langInput]) || "";
|
||||
});
|
||||
} else if (field.type === "image") {
|
||||
const pathInput = wrapper.querySelector("[data-image-path]");
|
||||
const preview = wrapper.querySelector("[data-image-preview]");
|
||||
pathInput.value = value || "";
|
||||
if (value) {
|
||||
preview.src = value;
|
||||
preview.classList.remove("hidden");
|
||||
}
|
||||
} else if (field.type === "date") {
|
||||
const input = document.getElementById("field-" + field.name);
|
||||
input.value = value ? String(value).slice(0, 10) : "";
|
||||
} else {
|
||||
document.getElementById("field-" + field.name).value = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ----- load & submit -------------------------------------------------------
|
||||
|
||||
async function loadRecord() {
|
||||
if (mode !== "edit") return;
|
||||
const url = schema.getOneUrl
|
||||
? schema.getOneUrl(recordId)
|
||||
: `${schema.endpoint}/${recordId}`;
|
||||
try {
|
||||
record = await Api.get(url);
|
||||
const values = schema.recordToValues ? schema.recordToValues(record) : record;
|
||||
populate(values);
|
||||
} catch (error) {
|
||||
UI.toast(error.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const values = collectValues();
|
||||
if (!validate(values)) {
|
||||
UI.toast("Please fix the highlighted fields.", "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = schema.buildPayload(values, mode, record);
|
||||
UI.setLoading(submitButton, true);
|
||||
try {
|
||||
if (mode === "edit") {
|
||||
await Api.put(`${schema.endpoint}/${recordId}`, payload);
|
||||
} else {
|
||||
await Api.post(schema.endpoint, payload);
|
||||
}
|
||||
UI.toast(mode === "edit" ? "Saved successfully" : "Created successfully", "success");
|
||||
setTimeout(() => {
|
||||
window.location.href = "/admin/" + slug;
|
||||
}, 600);
|
||||
} catch (error) {
|
||||
UI.setLoading(submitButton, false);
|
||||
UI.toast(error.message, "error");
|
||||
}
|
||||
});
|
||||
|
||||
// ----- init ----------------------------------------------------------------
|
||||
|
||||
buildFields();
|
||||
Auth.loadProfile();
|
||||
Auth.bindLogoutButtons();
|
||||
loadSelectOptions().then(loadRecord);
|
||||
});
|
||||
})();
|
||||
48
backend/web/admin/assets/js/login.js
Normal file
48
backend/web/admin/assets/js/login.js
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Login page: submit credentials, store the token pair and redirect.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (document.body.dataset.page !== "login") return;
|
||||
|
||||
// Already signed in? Go straight to the dashboard.
|
||||
if (Api.tokens.access) {
|
||||
window.location.href = "/admin";
|
||||
return;
|
||||
}
|
||||
|
||||
const form = document.getElementById("login-form");
|
||||
const loginInput = document.getElementById("login-input");
|
||||
const passwordInput = document.getElementById("password-input");
|
||||
const errorEl = document.getElementById("login-error");
|
||||
const submitButton = document.getElementById("login-submit");
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
errorEl.classList.add("hidden");
|
||||
|
||||
const loginValue = loginInput.value.trim();
|
||||
const password = passwordInput.value;
|
||||
if (!loginValue || !password) {
|
||||
errorEl.textContent = "Please enter your login and password.";
|
||||
errorEl.classList.remove("hidden");
|
||||
return;
|
||||
}
|
||||
|
||||
UI.setLoading(submitButton, true);
|
||||
try {
|
||||
await Auth.login(loginValue, password);
|
||||
window.location.href = "/admin";
|
||||
} catch (error) {
|
||||
errorEl.textContent =
|
||||
error.status === 400
|
||||
? "Invalid login or password."
|
||||
: error.message;
|
||||
errorEl.classList.remove("hidden");
|
||||
UI.setLoading(submitButton, false);
|
||||
}
|
||||
});
|
||||
});
|
||||
})();
|
||||
231
backend/web/admin/assets/js/resources.js
Normal file
231
backend/web/admin/assets/js/resources.js
Normal file
@@ -0,0 +1,231 @@
|
||||
/**
|
||||
* Declarative schemas for every admin CRUD resource.
|
||||
*
|
||||
* Column types: id | lang | text | image | date | bool | number
|
||||
* Field types: lang | lang-textarea | lang-richtext | text | textarea | image | date | select
|
||||
*
|
||||
* Endpoints follow the backend envelope { status, message, code, data }
|
||||
* where list payloads are { <listKey>: [...], count: N }.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
window.Resources = {
|
||||
categories: {
|
||||
title: "Categories",
|
||||
endpoint: "/v1/admin/categories",
|
||||
listKey: "categories",
|
||||
searchable: true,
|
||||
statusToggle: true,
|
||||
columns: [
|
||||
{ key: "Id", label: "ID", type: "id", sortKey: "id" },
|
||||
{ key: "name", label: "Name", type: "lang" },
|
||||
{ key: "status", label: "Status", type: "bool", sortKey: "status" },
|
||||
{ key: "createdAt", label: "Created", type: "date", sortKey: "createdAt" },
|
||||
],
|
||||
fields: [
|
||||
{ name: "name", label: "Name", type: "lang", required: true },
|
||||
],
|
||||
buildPayload: (values, mode, record) => {
|
||||
if (mode === "edit") {
|
||||
return { name: values.name, status: record ? !!record.status : true };
|
||||
}
|
||||
return { name: values.name };
|
||||
},
|
||||
},
|
||||
|
||||
"sub-categories": {
|
||||
title: "Sub-categories",
|
||||
endpoint: "/v1/admin/sub-categories",
|
||||
listKey: "subCategory",
|
||||
searchable: true,
|
||||
statusToggle: true,
|
||||
// The list endpoint is scoped by category: GET /v1/admin/sub-categories/:categoryId
|
||||
parentFilter: {
|
||||
label: "Category",
|
||||
endpoint: "/v1/admin/categories",
|
||||
listKey: "categories",
|
||||
labelField: "name",
|
||||
},
|
||||
listUrl: (state) => "/v1/admin/sub-categories/" + state.parentId,
|
||||
getOneUrl: (id) => "/v1/admin/sub-categories/" + id + "/edit",
|
||||
columns: [
|
||||
{ key: "Id", label: "ID", type: "id", sortKey: "id" },
|
||||
{ key: "name", label: "Name", type: "lang" },
|
||||
{ key: "status", label: "Status", type: "bool", sortKey: "status" },
|
||||
{ key: "createdAt", label: "Created", type: "date", sortKey: "createdAt" },
|
||||
],
|
||||
fields: [
|
||||
{
|
||||
name: "categoryId",
|
||||
label: "Category",
|
||||
type: "select",
|
||||
required: true,
|
||||
options: {
|
||||
endpoint: "/v1/admin/categories",
|
||||
listKey: "categories",
|
||||
valueField: "Id",
|
||||
labelField: "name",
|
||||
},
|
||||
},
|
||||
{ name: "name", label: "Name", type: "lang", required: true },
|
||||
{ name: "content", label: "Content", type: "lang-richtext", required: true },
|
||||
],
|
||||
buildPayload: (values) => ({
|
||||
categoryId: Number(values.categoryId),
|
||||
name: values.name,
|
||||
content: values.content,
|
||||
}),
|
||||
},
|
||||
|
||||
banners: {
|
||||
title: "Banners",
|
||||
endpoint: "/v1/admin/banner",
|
||||
listKey: "banners",
|
||||
searchable: true,
|
||||
columns: [
|
||||
{ key: "Id", label: "ID", type: "id", sortKey: "id" },
|
||||
{ key: "imagePath", label: "Image", type: "image" },
|
||||
{ key: "title", label: "Title", type: "lang" },
|
||||
{ key: "createdAt", label: "Created", type: "date", sortKey: "createdAt" },
|
||||
],
|
||||
fields: [
|
||||
{ name: "title", label: "Title", type: "lang", required: true },
|
||||
{
|
||||
name: "content",
|
||||
label: "Content",
|
||||
type: "lang-richtext",
|
||||
flat: true, // stored as contentTm / contentRu / contentEn
|
||||
},
|
||||
{ name: "imagePath", label: "Image", type: "image", required: true },
|
||||
],
|
||||
buildPayload: (values) => ({
|
||||
title: values.title,
|
||||
contentTm: (values.content && values.content.tm) || "",
|
||||
contentRu: (values.content && values.content.ru) || "",
|
||||
contentEn: (values.content && values.content.en) || "",
|
||||
imagePath: values.imagePath,
|
||||
}),
|
||||
recordToValues: (record) => ({
|
||||
title: record.title,
|
||||
content: {
|
||||
tm: record.contentTm || "",
|
||||
ru: record.contentRu || "",
|
||||
en: record.contentEn || "",
|
||||
},
|
||||
imagePath: record.imagePath,
|
||||
}),
|
||||
},
|
||||
|
||||
news: {
|
||||
title: "News",
|
||||
endpoint: "/v1/admin/news",
|
||||
listKey: "news",
|
||||
searchable: true,
|
||||
columns: [
|
||||
{ key: "Id", label: "ID", type: "id", sortKey: "id" },
|
||||
{ key: "imagePath", label: "Image", type: "image" },
|
||||
{ key: "title", label: "Title", type: "lang" },
|
||||
{ key: "dateRelease", label: "Release date", type: "date", sortKey: "dateRelease" },
|
||||
],
|
||||
fields: [
|
||||
{ name: "title", label: "Title", type: "lang", required: true },
|
||||
{ name: "content", label: "Content", type: "lang-richtext", required: true },
|
||||
{ name: "imagePath", label: "Image", type: "image", required: true },
|
||||
{ name: "dateRelease", label: "Release date", type: "date", required: true },
|
||||
],
|
||||
buildPayload: (values) => ({
|
||||
title: values.title,
|
||||
content: values.content,
|
||||
imagePath: values.imagePath,
|
||||
dateRelease: values.dateRelease,
|
||||
}),
|
||||
},
|
||||
|
||||
static: {
|
||||
title: "Static pages",
|
||||
endpoint: "/v1/admin/static",
|
||||
listKey: "statics",
|
||||
searchable: true,
|
||||
columns: [
|
||||
{ key: "Id", label: "ID", type: "id", sortKey: "id" },
|
||||
{ key: "logo", label: "Logo", type: "image" },
|
||||
{ key: "title", label: "Title", type: "lang" },
|
||||
{ key: "createdAt", label: "Created", type: "date", sortKey: "createdAt" },
|
||||
],
|
||||
fields: [
|
||||
{ name: "logo", label: "Logo", type: "image", required: true },
|
||||
{ name: "title", label: "Title", type: "lang", required: true },
|
||||
{
|
||||
name: "content",
|
||||
label: "Content",
|
||||
type: "lang-richtext",
|
||||
flat: true, // stored as contentTm / contentRu / contentEn
|
||||
},
|
||||
],
|
||||
buildPayload: (values) => ({
|
||||
logo: values.logo,
|
||||
title: values.title,
|
||||
contentTm: (values.content && values.content.tm) || "",
|
||||
contentRu: (values.content && values.content.ru) || "",
|
||||
contentEn: (values.content && values.content.en) || "",
|
||||
}),
|
||||
/** Map a fetched record into form values. */
|
||||
recordToValues: (record) => ({
|
||||
logo: record.logo,
|
||||
title: record.title,
|
||||
content: {
|
||||
tm: record.contentTm || "",
|
||||
ru: record.contentRu || "",
|
||||
en: record.contentEn || "",
|
||||
},
|
||||
}),
|
||||
},
|
||||
|
||||
currency: {
|
||||
title: "Currency",
|
||||
endpoint: "/v1/admin/currency",
|
||||
listKey: "currencies",
|
||||
searchable: true,
|
||||
columns: [
|
||||
{ key: "Id", label: "ID", type: "id", sortKey: "id" },
|
||||
{ key: "path", label: "Image", type: "image" },
|
||||
{ key: "title", label: "Title", type: "lang" },
|
||||
{ key: "createdAt", label: "Created", type: "date", sortKey: "createdAt" },
|
||||
],
|
||||
fields: [
|
||||
{ name: "path", label: "Image", type: "image", required: true },
|
||||
{ name: "title", label: "Title", type: "lang", required: true },
|
||||
{
|
||||
name: "content",
|
||||
label: "Content",
|
||||
type: "lang-richtext",
|
||||
flat: true, // stored as contentTm / contentRu / contentEn
|
||||
},
|
||||
],
|
||||
buildPayload: (values) => ({
|
||||
path: values.path,
|
||||
title: values.title,
|
||||
contentTm: (values.content && values.content.tm) || "",
|
||||
contentRu: (values.content && values.content.ru) || "",
|
||||
contentEn: (values.content && values.content.en) || "",
|
||||
}),
|
||||
recordToValues: (record) => ({
|
||||
path: record.path,
|
||||
title: record.title,
|
||||
content: {
|
||||
tm: record.contentTm || "",
|
||||
ru: record.contentRu || "",
|
||||
en: record.contentEn || "",
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
/** Preferred display order for a multilingual value. */
|
||||
window.langText = function (value) {
|
||||
if (!value) return "";
|
||||
if (typeof value === "string") return value;
|
||||
return value.tm || value.ru || value.en || "";
|
||||
};
|
||||
})();
|
||||
90
backend/web/admin/assets/js/settings.js
Normal file
90
backend/web/admin/assets/js/settings.js
Normal file
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Settings page: single-record form backed by
|
||||
* GET /v1/admin/setting and POST /v1/admin/setting/:id.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (document.body.dataset.page !== "settings") return;
|
||||
if (!Auth.requireAuth()) return;
|
||||
|
||||
Auth.loadProfile();
|
||||
Auth.bindLogoutButtons();
|
||||
|
||||
const form = document.getElementById("settings-form");
|
||||
const logoPath = document.getElementById("setting-logo-path");
|
||||
const logoFile = document.getElementById("setting-logo-file");
|
||||
const logoPreview = document.getElementById("setting-logo-preview");
|
||||
const phoneInput = document.getElementById("setting-phone");
|
||||
const faxInput = document.getElementById("setting-fax");
|
||||
const helpInput = document.getElementById("setting-help");
|
||||
const spinner = document.getElementById("setting-upload-spinner");
|
||||
const submitButton = document.getElementById("settings-submit");
|
||||
const errorEl = document.getElementById("settings-error");
|
||||
let settingId = 1;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const setting = await Api.get("/v1/admin/setting");
|
||||
if (setting) {
|
||||
settingId = setting.Id || 1;
|
||||
logoPath.value = setting.logoR || "";
|
||||
phoneInput.value = setting.phoneNumber || "";
|
||||
faxInput.value = setting.faxNumber || "";
|
||||
helpInput.value = setting.helpNumber || "";
|
||||
if (setting.logoR) {
|
||||
logoPreview.src = setting.logoR;
|
||||
logoPreview.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
errorEl.textContent = error.message;
|
||||
errorEl.classList.remove("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
logoFile.addEventListener("change", async () => {
|
||||
const file = logoFile.files && logoFile.files[0];
|
||||
if (!file) return;
|
||||
spinner.classList.remove("hidden");
|
||||
logoFile.disabled = true;
|
||||
try {
|
||||
const path = await Api.upload(file);
|
||||
logoPath.value = path;
|
||||
logoPreview.src = path;
|
||||
logoPreview.classList.remove("hidden");
|
||||
UI.toast("Logo uploaded", "success");
|
||||
} catch (error) {
|
||||
UI.toast(error.message, "error");
|
||||
} finally {
|
||||
spinner.classList.add("hidden");
|
||||
logoFile.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
errorEl.classList.add("hidden");
|
||||
UI.setLoading(submitButton, true);
|
||||
try {
|
||||
const saved = await Api.post("/v1/admin/setting/" + (settingId || 1), {
|
||||
logoR: logoPath.value,
|
||||
phoneNumber: phoneInput.value.trim(),
|
||||
faxNumber: faxInput.value.trim(),
|
||||
helpNumber: helpInput.value.trim(),
|
||||
});
|
||||
if (saved && saved.Id) {
|
||||
settingId = saved.Id;
|
||||
}
|
||||
UI.toast("Settings saved", "success");
|
||||
} catch (error) {
|
||||
UI.toast(error.message, "error");
|
||||
} finally {
|
||||
UI.setLoading(submitButton, false);
|
||||
}
|
||||
});
|
||||
|
||||
load();
|
||||
});
|
||||
})();
|
||||
302
backend/web/admin/assets/js/table.js
Normal file
302
backend/web/admin/assets/js/table.js
Normal file
@@ -0,0 +1,302 @@
|
||||
/**
|
||||
* Generic list page engine.
|
||||
*
|
||||
* Reads the resource slug from <body data-resource="...">, looks up its
|
||||
* schema in Resources and renders a DaisyUI table with server-side
|
||||
* pagination, sorting and search, plus loading / empty / error states.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const body = document.body;
|
||||
if (body.dataset.page !== "list") return;
|
||||
if (!Auth.requireAuth()) return;
|
||||
|
||||
const slug = body.dataset.resource;
|
||||
const schema = Resources[slug];
|
||||
if (!schema) return;
|
||||
|
||||
const els = {
|
||||
head: document.getElementById("list-head"),
|
||||
body: document.getElementById("list-body"),
|
||||
state: document.getElementById("list-state"),
|
||||
search: document.getElementById("list-search"),
|
||||
pagination: document.getElementById("list-pagination"),
|
||||
parentWrap: document.getElementById("list-parent-filter"),
|
||||
parentSelect: document.getElementById("list-parent-select"),
|
||||
count: document.getElementById("list-count"),
|
||||
};
|
||||
|
||||
const state = {
|
||||
page: 1,
|
||||
limit: PAGE_SIZE,
|
||||
search: "",
|
||||
sort: "",
|
||||
order: "desc",
|
||||
parentId: null,
|
||||
};
|
||||
|
||||
const columnCount = schema.columns.length + 1; // + actions
|
||||
|
||||
// ----- rendering helpers -------------------------------------------------
|
||||
|
||||
function renderHead() {
|
||||
const cells = schema.columns
|
||||
.map((column) => {
|
||||
if (!column.sortKey) {
|
||||
return `<th scope="col">${UI.escapeHtml(column.label)}</th>`;
|
||||
}
|
||||
const isActive = state.sort === column.sortKey;
|
||||
const arrow = !isActive ? "" : state.order === "asc" ? " ▲" : " ▼";
|
||||
return (
|
||||
`<th scope="col"><button type="button" class="inline-flex items-center gap-1 font-semibold hover:text-primary" ` +
|
||||
`data-sort="${column.sortKey}" aria-label="Sort by ${UI.escapeHtml(column.label)}">` +
|
||||
`${UI.escapeHtml(column.label)}${arrow}</button></th>`
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
els.head.innerHTML = `<tr>${cells}<th scope="col" class="text-right">Actions</th></tr>`;
|
||||
|
||||
els.head.querySelectorAll("[data-sort]").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
const key = button.dataset.sort;
|
||||
if (state.sort === key) {
|
||||
state.order = state.order === "asc" ? "desc" : "asc";
|
||||
} else {
|
||||
state.sort = key;
|
||||
state.order = "asc";
|
||||
}
|
||||
state.page = 1;
|
||||
load();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function cellHtml(column, row) {
|
||||
const value = row[column.key];
|
||||
switch (column.type) {
|
||||
case "id":
|
||||
return `<td class="font-mono text-xs">${UI.escapeHtml(value)}</td>`;
|
||||
case "lang":
|
||||
return `<td class="max-w-xs truncate" title="${UI.escapeHtml(langText(value))}">${UI.escapeHtml(langText(value))}</td>`;
|
||||
case "image":
|
||||
return value
|
||||
? `<td><img src="${UI.escapeHtml(value)}" alt="" class="h-10 w-16 rounded object-cover" loading="lazy"></td>`
|
||||
: `<td><span class="text-base-content/40">—</span></td>`;
|
||||
case "date":
|
||||
return `<td class="whitespace-nowrap">${UI.escapeHtml(UI.formatDate(value))}</td>`;
|
||||
case "bool":
|
||||
if (schema.statusToggle) {
|
||||
return (
|
||||
`<td><input type="checkbox" class="toggle toggle-primary toggle-sm" data-status-toggle ` +
|
||||
`${value ? "checked" : ""} aria-label="Toggle status"></td>`
|
||||
);
|
||||
}
|
||||
return `<td>${value ? '<span class="badge badge-success badge-sm">Active</span>' : '<span class="badge badge-ghost badge-sm">Inactive</span>'}</td>`;
|
||||
default:
|
||||
return `<td class="max-w-xs truncate" title="${UI.escapeHtml(value)}">${UI.escapeHtml(value)}</td>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderRows(rows) {
|
||||
els.body.innerHTML = "";
|
||||
rows.forEach((row) => {
|
||||
const tr = document.createElement("tr");
|
||||
tr.className = "hover";
|
||||
tr.innerHTML =
|
||||
schema.columns.map((column) => cellHtml(column, row)).join("") +
|
||||
`<td class="text-right whitespace-nowrap">
|
||||
<a class="btn btn-ghost btn-xs" href="/admin/${slug}/${row.Id}/edit" aria-label="Edit item ${row.Id}">Edit</a>
|
||||
<button type="button" class="btn btn-ghost btn-xs text-error" data-delete aria-label="Delete item ${row.Id}">Delete</button>
|
||||
</td>`;
|
||||
|
||||
const toggle = tr.querySelector("[data-status-toggle]");
|
||||
if (toggle) {
|
||||
toggle.addEventListener("change", async () => {
|
||||
toggle.disabled = true;
|
||||
try {
|
||||
await Api.put(
|
||||
`${schema.endpoint}/${row.Id}/status?status=${toggle.checked}`
|
||||
);
|
||||
UI.toast("Status updated", "success");
|
||||
} catch (error) {
|
||||
toggle.checked = !toggle.checked;
|
||||
UI.toast(error.message, "error");
|
||||
} finally {
|
||||
toggle.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
tr.querySelector("[data-delete]").addEventListener("click", async () => {
|
||||
const confirmed = await UI.confirm({
|
||||
title: "Delete item",
|
||||
message: `Delete this ${schema.title.toLowerCase().replace(/s$/, "")}? This action cannot be undone.`,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
try {
|
||||
await Api.del(`${schema.endpoint}/${row.Id}`);
|
||||
UI.toast("Deleted successfully", "success");
|
||||
load();
|
||||
} catch (error) {
|
||||
UI.toast(error.message, "error");
|
||||
}
|
||||
});
|
||||
|
||||
els.body.appendChild(tr);
|
||||
});
|
||||
}
|
||||
|
||||
function renderState(html) {
|
||||
els.body.innerHTML = "";
|
||||
els.state.innerHTML = html;
|
||||
els.state.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function renderLoading() {
|
||||
els.state.classList.add("hidden");
|
||||
els.body.innerHTML = Array.from({ length: 5 })
|
||||
.map(
|
||||
() =>
|
||||
`<tr>${Array.from({ length: columnCount })
|
||||
.map(() => '<td><div class="skeleton h-4 w-full"></div></td>')
|
||||
.join("")}</tr>`
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
function renderPagination(count) {
|
||||
const totalPages = Math.max(1, Math.ceil(count / state.limit));
|
||||
if (state.page > totalPages) {
|
||||
state.page = totalPages;
|
||||
}
|
||||
els.pagination.innerHTML = `
|
||||
<div class="join">
|
||||
<button type="button" class="join-item btn btn-sm" data-page-prev ${state.page <= 1 ? "disabled" : ""} aria-label="Previous page">«</button>
|
||||
<button type="button" class="join-item btn btn-sm no-animation" tabindex="-1">Page ${state.page} of ${totalPages}</button>
|
||||
<button type="button" class="join-item btn btn-sm" data-page-next ${state.page >= totalPages ? "disabled" : ""} aria-label="Next page">»</button>
|
||||
</div>`;
|
||||
const prev = els.pagination.querySelector("[data-page-prev]");
|
||||
const next = els.pagination.querySelector("[data-page-next]");
|
||||
prev.addEventListener("click", () => {
|
||||
state.page -= 1;
|
||||
load();
|
||||
});
|
||||
next.addEventListener("click", () => {
|
||||
state.page += 1;
|
||||
load();
|
||||
});
|
||||
}
|
||||
|
||||
// ----- data loading ------------------------------------------------------
|
||||
|
||||
function listUrl() {
|
||||
return schema.listUrl ? schema.listUrl(state) : schema.endpoint;
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (schema.parentFilter && !state.parentId) {
|
||||
renderState(
|
||||
`<div class="py-10 text-center text-base-content/60">Create a category first, then add sub-categories to it.</div>`
|
||||
);
|
||||
els.pagination.innerHTML = "";
|
||||
return;
|
||||
}
|
||||
|
||||
renderLoading();
|
||||
try {
|
||||
const data = await Api.get(listUrl(), {
|
||||
limit: state.limit,
|
||||
page: state.page,
|
||||
search: state.search,
|
||||
sort: state.sort,
|
||||
order: state.order,
|
||||
});
|
||||
const rows = (data && data[schema.listKey]) || [];
|
||||
const count = (data && data.count) || 0;
|
||||
|
||||
if (els.count) {
|
||||
els.count.textContent = count + " total";
|
||||
}
|
||||
|
||||
if (!rows.length) {
|
||||
renderState(
|
||||
`<div class="py-10 text-center text-base-content/60">
|
||||
<p class="mb-3">Nothing here yet${state.search ? " for “" + UI.escapeHtml(state.search) + "”" : ""}.</p>
|
||||
<a href="/admin/${slug}/new" class="btn btn-primary btn-sm">Create the first one</a>
|
||||
</div>`
|
||||
);
|
||||
} else {
|
||||
els.state.classList.add("hidden");
|
||||
renderRows(rows);
|
||||
}
|
||||
renderHead();
|
||||
renderPagination(count);
|
||||
} catch (error) {
|
||||
renderState(
|
||||
`<div class="py-10 text-center">
|
||||
<p class="mb-3 text-error">${UI.escapeHtml(error.message)}</p>
|
||||
<button type="button" class="btn btn-outline btn-sm" data-retry>Retry</button>
|
||||
</div>`
|
||||
);
|
||||
els.pagination.innerHTML = "";
|
||||
els.state
|
||||
.querySelector("[data-retry]")
|
||||
.addEventListener("click", () => load());
|
||||
}
|
||||
}
|
||||
|
||||
async function initParentFilter() {
|
||||
if (!schema.parentFilter) return;
|
||||
els.parentWrap.classList.remove("hidden");
|
||||
try {
|
||||
const data = await Api.get(schema.parentFilter.endpoint, {
|
||||
limit: 0,
|
||||
page: 0,
|
||||
});
|
||||
const items = (data && data[schema.parentFilter.listKey]) || [];
|
||||
els.parentSelect.innerHTML = items
|
||||
.map(
|
||||
(item) =>
|
||||
`<option value="${item.Id}">${UI.escapeHtml(langText(item[schema.parentFilter.labelField]))}</option>`
|
||||
)
|
||||
.join("");
|
||||
if (items.length) {
|
||||
state.parentId = items[0].Id;
|
||||
els.parentSelect.value = String(state.parentId);
|
||||
}
|
||||
els.parentSelect.addEventListener("change", () => {
|
||||
state.parentId = Number(els.parentSelect.value);
|
||||
state.page = 1;
|
||||
load();
|
||||
});
|
||||
} catch (error) {
|
||||
UI.toast(error.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ----- search ------------------------------------------------------------
|
||||
|
||||
if (els.search) {
|
||||
let debounce;
|
||||
els.search.addEventListener("input", () => {
|
||||
clearTimeout(debounce);
|
||||
debounce = setTimeout(() => {
|
||||
state.search = els.search.value.trim();
|
||||
state.page = 1;
|
||||
load();
|
||||
}, 350);
|
||||
});
|
||||
}
|
||||
|
||||
// ----- init ----------------------------------------------------------------
|
||||
|
||||
renderHead();
|
||||
Auth.loadProfile();
|
||||
Auth.bindLogoutButtons();
|
||||
initParentFilter().then(load);
|
||||
});
|
||||
})();
|
||||
96
backend/web/admin/assets/js/ui.js
Normal file
96
backend/web/admin/assets/js/ui.js
Normal file
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Small UI helpers built on DaisyUI: toasts, confirm dialog,
|
||||
* button loading states, HTML escaping and date formatting.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value == null ? "" : value)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function formatDate(value) {
|
||||
if (!value) return "";
|
||||
const date = new Date(value);
|
||||
if (isNaN(date.getTime())) return String(value);
|
||||
return date.toLocaleDateString(undefined, {
|
||||
year: "numeric",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
/** Show a toast notification. type: success | error | info | warning */
|
||||
function toast(message, type) {
|
||||
type = type || "info";
|
||||
let container = document.getElementById("toast-container");
|
||||
if (!container) {
|
||||
container = document.createElement("div");
|
||||
container.id = "toast-container";
|
||||
container.className = "toast toast-end toast-bottom z-50";
|
||||
container.setAttribute("aria-live", "polite");
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
const alert = document.createElement("div");
|
||||
alert.className = "alert alert-" + type + " shadow-lg";
|
||||
alert.setAttribute("role", type === "error" ? "alert" : "status");
|
||||
const text = document.createElement("span");
|
||||
text.textContent = message;
|
||||
alert.appendChild(text);
|
||||
container.appendChild(alert);
|
||||
setTimeout(() => alert.remove(), 4500);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a confirmation dialog. Resolves true when confirmed.
|
||||
* Uses the shared <dialog id="confirm-dialog"> from the layout.
|
||||
*/
|
||||
function confirmDialog(options) {
|
||||
options = options || {};
|
||||
const dialog = document.getElementById("confirm-dialog");
|
||||
if (!dialog) return Promise.resolve(window.confirm(options.message || "Are you sure?"));
|
||||
|
||||
dialog.querySelector("[data-confirm-title]").textContent =
|
||||
options.title || "Please confirm";
|
||||
dialog.querySelector("[data-confirm-message]").textContent =
|
||||
options.message || "Are you sure you want to continue?";
|
||||
const okButton = dialog.querySelector("[data-confirm-ok]");
|
||||
okButton.textContent = options.confirmText || "Delete";
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const onClose = () => {
|
||||
dialog.removeEventListener("close", onClose);
|
||||
resolve(dialog.returnValue === "ok");
|
||||
};
|
||||
dialog.addEventListener("close", onClose);
|
||||
dialog.showModal();
|
||||
okButton.focus();
|
||||
});
|
||||
}
|
||||
|
||||
/** Toggle a DaisyUI loading state on a button. */
|
||||
function setLoading(button, isLoading) {
|
||||
if (!button) return;
|
||||
if (isLoading) {
|
||||
button.disabled = true;
|
||||
button.setAttribute("aria-busy", "true");
|
||||
if (!button.querySelector(".loading")) {
|
||||
const spinner = document.createElement("span");
|
||||
spinner.className = "loading loading-spinner loading-xs";
|
||||
button.prepend(spinner);
|
||||
}
|
||||
} else {
|
||||
button.disabled = false;
|
||||
button.removeAttribute("aria-busy");
|
||||
const spinner = button.querySelector(".loading");
|
||||
if (spinner) spinner.remove();
|
||||
}
|
||||
}
|
||||
|
||||
window.UI = { escapeHtml, formatDate, toast, confirm: confirmDialog, setLoading };
|
||||
})();
|
||||
Reference in New Issue
Block a user