This commit is contained in:
2026-08-04 12:50:20 +05:00
parent 4194cef934
commit 363127fe9e
3350 changed files with 1284220 additions and 1 deletions

1
backend/web/admin/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
node_modules/

File diff suppressed because one or more lines are too long

View 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,
};
})();

View 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 };
})();

View 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>`;
}
}
})();

View 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);
});
})();

View 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);
}
});
});
})();

View 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 || "";
};
})();

View 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();
});
})();

View 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);
});
})();

View 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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
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 };
})();

View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

1075
backend/web/admin/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
{
"name": "bankline-admin",
"private": true,
"scripts": {
"build": "tailwindcss -i css/input.css -o assets/css/app.css --minify",
"watch": "tailwindcss -i css/input.css -o assets/css/app.css --watch"
},
"devDependencies": {
"daisyui": "^4.12.24",
"tailwindcss": "^3.4.19"
}
}

View File

@@ -0,0 +1,21 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./templates/**/*.html", "./assets/js/**/*.js"],
theme: {
extend: {},
},
plugins: [require("daisyui")],
daisyui: {
themes: [
{
tbbank: {
...require("daisyui/src/theming/themes")["light"],
primary: "#67b03d",
"primary-content": "#ffffff",
},
},
],
logs: false,
},
};

View File

@@ -0,0 +1,22 @@
{{define "pages/404"}}
<!DOCTYPE html>
<html lang="en" data-theme="tbbank">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>{{.Title}} · Bankline Admin</title>
<link rel="stylesheet" href="/admin/assets/css/app.css">
</head>
<body class="min-h-screen bg-base-200" data-page="404">
<main class="flex min-h-screen flex-col items-center justify-center gap-4 p-4 text-center">
<p class="text-6xl font-bold text-primary">404</p>
<h1 class="text-xl font-semibold">Page not found</h1>
<p class="max-w-sm text-base-content/60">The page you are looking for doesn't exist or has been moved.</p>
<a href="/admin" class="btn btn-primary">Back to dashboard</a>
</main>
</body>
</html>
{{end}}

View File

@@ -0,0 +1,57 @@
{{define "pages/dashboard"}}
{{template "partials/layout-top" .}}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-5">
<div id="stat-news" class="stats bg-base-100 shadow-sm">
<div class="stat">
<div class="stat-title">News</div>
<div class="stat-value text-primary" data-stat-value><span class="loading loading-dots loading-sm"></span></div>
<div class="stat-desc"><a href="/admin/news" class="link-hover link">Manage news</a></div>
</div>
</div>
<div id="stat-categories" class="stats bg-base-100 shadow-sm">
<div class="stat">
<div class="stat-title">Categories</div>
<div class="stat-value text-primary" data-stat-value><span class="loading loading-dots loading-sm"></span></div>
<div class="stat-desc"><a href="/admin/categories" class="link-hover link">Manage categories</a></div>
</div>
</div>
<div id="stat-banners" class="stats bg-base-100 shadow-sm">
<div class="stat">
<div class="stat-title">Banners</div>
<div class="stat-value text-primary" data-stat-value><span class="loading loading-dots loading-sm"></span></div>
<div class="stat-desc"><a href="/admin/banners" class="link-hover link">Manage banners</a></div>
</div>
</div>
<div id="stat-static" class="stats bg-base-100 shadow-sm">
<div class="stat">
<div class="stat-title">Static pages</div>
<div class="stat-value text-primary" data-stat-value><span class="loading loading-dots loading-sm"></span></div>
<div class="stat-desc"><a href="/admin/static" class="link-hover link">Manage pages</a></div>
</div>
</div>
<div id="stat-currency" class="stats bg-base-100 shadow-sm">
<div class="stat">
<div class="stat-title">Currency</div>
<div class="stat-value text-primary" data-stat-value><span class="loading loading-dots loading-sm"></span></div>
<div class="stat-desc"><a href="/admin/currency" class="link-hover link">Manage currency</a></div>
</div>
</div>
</div>
<div class="card mt-6 bg-base-100 shadow-sm">
<div class="card-body">
<div class="flex items-center justify-between">
<h2 class="card-title text-base">Latest news</h2>
<a href="/admin/news/new" class="btn btn-primary btn-sm">Add news</a>
</div>
<ul id="latest-news" class="divide-y divide-base-200">
<li class="py-3"><div class="skeleton h-4 w-2/3"></div></li>
<li class="py-3"><div class="skeleton h-4 w-1/2"></div></li>
<li class="py-3"><div class="skeleton h-4 w-3/5"></div></li>
</ul>
</div>
</div>
{{template "partials/layout-bottom" .}}
{{end}}

View File

@@ -0,0 +1,28 @@
{{define "pages/form"}}
{{template "partials/layout-top" .}}
<div class="breadcrumbs mb-4 text-sm">
<ul>
<li><a href="/admin">Dashboard</a></li>
<li><a href="/admin/{{.Resource}}">{{.Resource}}</a></li>
<li>{{if eq .Mode "edit"}}Edit{{else}}New{{end}}</li>
</ul>
</div>
<div class="card max-w-3xl bg-base-100 shadow-sm">
<div class="card-body">
<form id="resource-form" novalidate>
<div id="form-fields" class="flex flex-col gap-4"></div>
<div class="mt-6 flex items-center gap-3">
<button type="submit" id="form-submit" class="btn btn-primary">
{{if eq .Mode "edit"}}Save changes{{else}}Create{{end}}
</button>
<a href="/admin/{{.Resource}}" class="btn btn-ghost">Cancel</a>
</div>
</form>
</div>
</div>
{{template "partials/layout-bottom" .}}
{{end}}

View File

@@ -0,0 +1,43 @@
{{define "pages/list"}}
{{template "partials/layout-top" .}}
<div class="card bg-base-100 shadow-sm">
<div class="card-body">
<div class="mb-2 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div class="flex flex-wrap items-center gap-3">
<label class="input input-bordered flex w-full max-w-xs items-center gap-2 sm:w-64">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-4 w-4 opacity-60" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z"/>
</svg>
<input type="search" id="list-search" class="grow" placeholder="Search…" aria-label="Search {{.Title}}">
</label>
<div id="list-parent-filter" class="hidden">
<select id="list-parent-select" class="select select-bordered w-full max-w-xs" aria-label="Filter by category"></select>
</div>
<span id="list-count" class="badge badge-ghost" aria-live="polite"></span>
</div>
<a href="/admin/{{.Resource}}/new" class="btn btn-primary btn-sm">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="h-4 w-4" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/>
</svg>
New
</a>
</div>
<div class="overflow-x-auto">
<table class="table" aria-label="{{.Title}}">
<thead id="list-head"></thead>
<tbody id="list-body"></tbody>
</table>
<div id="list-state" class="hidden" aria-live="polite"></div>
</div>
<div id="list-pagination" class="mt-4 flex justify-center"></div>
</div>
</div>
{{template "partials/layout-bottom" .}}
{{end}}

View File

@@ -0,0 +1,50 @@
{{define "pages/login"}}
<!DOCTYPE html>
<html lang="en" data-theme="tbbank">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>{{.Title}} · Bankline Admin</title>
<link rel="stylesheet" href="/admin/assets/css/app.css">
</head>
<body class="min-h-screen bg-base-200" data-page="login">
<main class="flex min-h-screen items-center justify-center p-4">
<div class="card w-full max-w-sm bg-base-100 shadow-xl">
<div class="card-body">
<div class="mb-2 flex items-center justify-center gap-2 text-primary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-8 w-8" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 21v-8.25M15.75 21v-8.25M8.25 21v-8.25M3 9l9-6 9 6m-1.5 12V10.332A48.36 48.36 0 0 0 12 9.75c-2.551 0-5.056.2-7.5.582V21M3 21h18M12 6.75h.008v.008H12V6.75Z"/>
</svg>
<span class="text-2xl font-bold">Bankline</span>
</div>
<p class="mb-4 text-center text-sm text-base-content/60">Sign in to the admin dashboard</p>
<form id="login-form" novalidate>
<div class="form-control w-full">
<label class="label" for="login-input"><span class="label-text">Login</span></label>
<input type="text" id="login-input" name="login" class="input input-bordered w-full"
autocomplete="username" required autofocus>
</div>
<div class="form-control mt-3 w-full">
<label class="label" for="password-input"><span class="label-text">Password</span></label>
<input type="password" id="password-input" name="password" class="input input-bordered w-full"
autocomplete="current-password" required>
</div>
<p id="login-error" class="mt-3 hidden text-sm text-error" role="alert"></p>
<button type="submit" id="login-submit" class="btn btn-primary mt-6 w-full">Sign in</button>
</form>
</div>
</div>
</main>
<script src="/admin/assets/js/api.js"></script>
<script src="/admin/assets/js/ui.js"></script>
<script src="/admin/assets/js/auth.js"></script>
<script src="/admin/assets/js/login.js"></script>
</body>
</html>
{{end}}

View File

@@ -0,0 +1,46 @@
{{define "pages/settings"}}
{{template "partials/layout-top" .}}
<div class="card max-w-2xl bg-base-100 shadow-sm">
<div class="card-body">
<h2 class="card-title mb-2 text-base">Site settings</h2>
<form id="settings-form" novalidate>
<div class="form-control w-full">
<span class="label"><span class="label-text font-medium">Logo</span></span>
<div class="flex flex-col gap-3">
<img id="setting-logo-preview" alt="Logo preview" class="hidden h-24 w-fit max-w-xs rounded-lg border border-base-300 object-contain">
<input type="hidden" id="setting-logo-path">
<div class="flex items-center gap-3">
<input type="file" id="setting-logo-file" accept="image/*" class="file-input file-input-bordered w-full max-w-xs" aria-label="Upload logo">
<span id="setting-upload-spinner" class="loading loading-spinner loading-sm hidden" aria-label="Uploading"></span>
</div>
</div>
</div>
<div class="form-control mt-4 w-full">
<label class="label" for="setting-phone"><span class="label-text font-medium">Phone number</span></label>
<input type="text" id="setting-phone" class="input input-bordered w-full" placeholder="(99312) 44-42-96">
</div>
<div class="form-control mt-4 w-full">
<label class="label" for="setting-fax"><span class="label-text font-medium">Fax number</span></label>
<input type="text" id="setting-fax" class="input input-bordered w-full" placeholder="(99312) 44-41-06">
</div>
<div class="form-control mt-4 w-full">
<label class="label" for="setting-help"><span class="label-text font-medium">Help number</span></label>
<input type="text" id="setting-help" class="input input-bordered w-full" placeholder="44-42-33">
</div>
<p id="settings-error" class="mt-3 hidden text-sm text-error" role="alert"></p>
<div class="mt-6">
<button type="submit" id="settings-submit" class="btn btn-primary">Save settings</button>
</div>
</form>
</div>
</div>
{{template "partials/layout-bottom" .}}
{{end}}

View File

@@ -0,0 +1,15 @@
{{define "partials/confirm-dialog"}}
<dialog id="confirm-dialog" class="modal" aria-labelledby="confirm-dialog-title">
<form method="dialog" class="modal-box">
<h2 id="confirm-dialog-title" class="text-lg font-bold" data-confirm-title>Please confirm</h2>
<p class="py-4" data-confirm-message>Are you sure you want to continue?</p>
<div class="modal-action">
<button type="submit" value="cancel" class="btn btn-ghost">Cancel</button>
<button type="submit" value="ok" class="btn btn-error" data-confirm-ok>Delete</button>
</div>
</form>
<form method="dialog" class="modal-backdrop">
<button value="cancel" aria-label="Close dialog">close</button>
</form>
</dialog>
{{end}}

View File

@@ -0,0 +1,36 @@
{{define "partials/header"}}
<header class="navbar sticky top-0 z-30 border-b border-base-300 bg-base-100 px-4 lg:px-8">
<div class="flex-none lg:hidden">
<label for="sidebar-drawer" class="btn btn-ghost btn-square" aria-label="Open sidebar">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-6 w-6" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"/>
</svg>
</label>
</div>
<div class="flex-1">
<h1 class="text-lg font-semibold lg:text-xl">{{.Title}}</h1>
</div>
<div class="flex-none">
<div class="dropdown dropdown-end">
<button type="button" tabindex="0" class="btn btn-ghost gap-2 normal-case" aria-haspopup="menu" aria-label="Account menu">
<div class="avatar placeholder">
<div class="w-8 rounded-full bg-primary text-primary-content">
<img id="profile-avatar" class="hidden rounded-full" src="" alt="">
<span id="profile-initial">A</span>
</div>
</div>
<span id="profile-name" class="hidden sm:inline">Admin</span>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-4 w-4" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5"/>
</svg>
</button>
<ul tabindex="0" role="menu" class="menu dropdown-content z-40 mt-2 w-48 rounded-box bg-base-100 p-2 shadow-lg">
<li role="none"><a role="menuitem" href="/admin/settings">Settings</a></li>
<li role="none"><button role="menuitem" type="button" data-logout class="text-error">Log out</button></li>
</ul>
</div>
</div>
</header>
{{end}}

View File

@@ -0,0 +1,50 @@
{{define "partials/layout-top"}}
<!DOCTYPE html>
<html lang="en" data-theme="tbbank">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>{{.Title}} · Bankline Admin</title>
<link rel="stylesheet" href="/admin/assets/css/app.css">
{{if eq .Page "form"}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.snow.css">
{{end}}
</head>
<body class="min-h-screen bg-base-200"
data-page="{{.Page}}"
{{if .Resource}}data-resource="{{.Resource}}"{{end}}
{{if .Mode}}data-mode="{{.Mode}}"{{end}}
{{if .Id}}data-id="{{.Id}}"{{end}}>
<div class="drawer lg:drawer-open">
<input id="sidebar-drawer" type="checkbox" class="drawer-toggle" aria-label="Toggle sidebar">
<div class="drawer-content flex min-h-screen flex-col">
{{template "partials/header" .}}
<main id="main-content" class="flex-1 p-4 lg:p-8">
{{end}}
{{define "partials/layout-bottom"}}
</main>
</div>
{{template "partials/sidebar" .}}
</div>
{{template "partials/confirm-dialog" .}}
<script src="/admin/assets/js/api.js"></script>
<script src="/admin/assets/js/ui.js"></script>
<script src="/admin/assets/js/auth.js"></script>
<script src="/admin/assets/js/resources.js"></script>
<script src="/admin/assets/js/table.js"></script>
{{if eq .Page "form"}}
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.3/dist/quill.js"></script>
{{end}}
<script src="/admin/assets/js/form.js"></script>
<script src="/admin/assets/js/dashboard.js"></script>
<script src="/admin/assets/js/settings.js"></script>
</body>
</html>
{{end}}

View File

@@ -0,0 +1,73 @@
{{define "partials/sidebar"}}
<div class="drawer-side z-40">
<label for="sidebar-drawer" aria-label="Close sidebar" class="drawer-overlay"></label>
<aside class="flex min-h-full w-64 flex-col bg-base-100">
<a href="/admin" class="flex items-center gap-2 px-6 py-5 text-lg font-bold text-primary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-7 w-7" aria-hidden="true">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 21v-8.25M15.75 21v-8.25M8.25 21v-8.25M3 9l9-6 9 6m-1.5 12V10.332A48.36 48.36 0 0 0 12 9.75c-2.551 0-5.056.2-7.5.582V21M3 21h18M12 6.75h.008v.008H12V6.75Z"/>
</svg>
<span>Bankline</span>
</a>
<nav aria-label="Main navigation" class="flex-1 overflow-y-auto px-3">
<ul class="menu gap-1 p-0">
<li>
<a href="/admin" class="{{if eq .Active "dashboard"}}active{{end}}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z"/></svg>
Dashboard
</a>
</li>
<li>
<a href="/admin/categories" class="{{if eq .Active "categories"}}active{{end}}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 12.75V12A2.25 2.25 0 0 1 4.5 9.75h15A2.25 2.25 0 0 1 21.75 12v.75m-8.69-6.44-2.12-2.12a1.5 1.5 0 0 0-1.061-.44H4.5A2.25 2.25 0 0 0 2.25 6v12a2.25 2.25 0 0 0 2.25 2.25h15A2.25 2.25 0 0 0 21.75 18V9a2.25 2.25 0 0 0-2.25-2.25h-5.379a1.5 1.5 0 0 1-1.06-.44Z"/></svg>
Categories
</a>
</li>
<li>
<a href="/admin/sub-categories" class="{{if eq .Active "sub-categories"}}active{{end}}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M8.25 6.75h12M8.25 12h12m-12 5.25h12M3.75 6.75h.007v.008H3.75V6.75Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0ZM3.75 12h.007v.008H3.75V12Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm-.375 5.25h.007v.008H3.75v-.008Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"/></svg>
Sub-categories
</a>
</li>
<li>
<a href="/admin/banners" class="{{if eq .Active "banners"}}active{{end}}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"/></svg>
Banners
</a>
</li>
<li>
<a href="/admin/news" class="{{if eq .Active "news"}}active{{end}}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M12 7.5h1.5m-1.5 3h1.5m-7.5 3h7.5m-7.5 3h7.5m3-9h3.375c.621 0 1.125.504 1.125 1.125V18a2.25 2.25 0 0 1-2.25 2.25M16.5 7.5V18a2.25 2.25 0 0 0 2.25 2.25M16.5 7.5V4.875c0-.621-.504-1.125-1.125-1.125H4.125C3.504 3.75 3 4.254 3 4.875V18a2.25 2.25 0 0 0 2.25 2.25h13.5M6 7.5h3v3H6v-3Z"/></svg>
News
</a>
</li>
<li>
<a href="/admin/static" class="{{if eq .Active "static"}}active{{end}}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"/></svg>
Static pages
</a>
</li>
<li>
<a href="/admin/currency" class="{{if eq .Active "currency"}}active{{end}}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v12m-3-2.818.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"/></svg>
Currency
</a>
</li>
</ul>
<div class="divider my-2"></div>
<ul class="menu gap-1 p-0">
<li>
<a href="/admin/settings" class="{{if eq .Active "settings"}}active{{end}}">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" class="h-5 w-5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"/></svg>
Settings
</a>
</li>
</ul>
</nav>
<div class="px-6 py-4 text-xs text-base-content/50">TBBANK admin</div>
</aside>
</div>
{{end}}