diff --git a/Packaging/webconsole/console.js b/Packaging/webconsole/console.js
new file mode 100644
index 0000000..1049ae1
--- /dev/null
+++ b/Packaging/webconsole/console.js
@@ -0,0 +1,253 @@
+"use strict";
+
+const element = (id) => document.getElementById(id);
+const routes = ["overview", "storage", "security", "audit"];
+const nav = [...document.querySelectorAll("nav button")];
+const dateFormat = new Intl.DateTimeFormat("ru", { dateStyle: "short", timeStyle: "short" });
+const labels = { LOGIN: "Вход", LOGOUT: "Выход" };
+const pageSize = 20;
+let token = "";
+let revision = 0;
+let auditPage = 0;
+let auditFilters = {};
+let sessionTimer;
+let storagePath = "";
+
+if ("serviceWorker" in navigator) {
+ navigator.serviceWorker.getRegistration("/webconsole/").then((registration) => {
+ const worker = registration?.active || registration?.waiting || registration?.installing;
+ if (worker && new URL(worker.scriptURL).pathname === "/webconsole/service-worker.js") {
+ return registration.unregister();
+ }
+ }).catch(() => {});
+}
+
+async function api(path, data, authorized = true) {
+ const requestToken = token;
+ const headers = new Headers({ Accept: "application/json" });
+ if (authorized && requestToken) headers.set("Authorization", "Bearer " + requestToken);
+ const options = { headers, cache: "no-store" };
+ if (data !== undefined) {
+ headers.set("Content-Type", "application/json");
+ options.method = "POST";
+ options.body = JSON.stringify(data);
+ }
+ let response;
+ try {
+ response = await fetch(path, options);
+ } catch {
+ throw new Error("Не удалось соединиться с ezServer.");
+ }
+ if (!response.ok) {
+ if (response.status === 401 && authorized && requestToken === token) {
+ showLogin("Сеанс завершён. Войдите снова.");
+ }
+ if (response.status === 429) throw new Error("Слишком много попыток. Повторите через минуту.");
+ if (response.status === 401) throw new Error("Проверьте имя пользователя и пароль.");
+ throw new Error("Сервер не выполнил запрос. HTTP " + response.status);
+ }
+ return response.json();
+}
+
+async function encodeLogin(username, password) {
+ if (!globalThis.crypto?.subtle) throw new Error("Откройте консоль по локальному адресу из меню ezServer.");
+ const bytes = (encoded) => Uint8Array.from(atob(encoded), (char) => char.charCodeAt(0));
+ // Original AppLogInR2 wire format. The key and IV are protocol constants.
+ const key = await crypto.subtle.importKey("raw", bytes("fCVpkpDy3QII1bJ0uklkvQ=="), "AES-CBC", false, ["encrypt"]);
+ const iv = bytes("p+O8XWH7eWQw1xifYtxx5Q==");
+ const plaintext = new TextEncoder().encode(JSON.stringify({
+ ver: "1.0.0",
+ client: { name: "EzServer Web Console", ver: "3.0.0" },
+ auth: { enc: "raw", usr: username, sec: password, exp: Math.floor(Date.now() / 1000) + 600 }
+ }));
+ const padded = new Uint8Array(Math.ceil((plaintext.length + 1) / 16) * 16);
+ padded.set(plaintext);
+ padded[plaintext.length] = 0x80;
+ const encrypted = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-CBC", iv }, key, padded));
+ // Web Crypto adds a final PKCS#7 block. The original endpoint expects only the ISO-padded blocks.
+ return btoa(String.fromCharCode(...encrypted.subarray(0, -16)));
+}
+
+function message(id, value) {
+ const item = element(id);
+ item.textContent = value;
+ item.hidden = !value;
+}
+
+function showLogin(error = "") {
+ token = "";
+ revision++;
+ clearTimeout(sessionTimer);
+ element("workspace").hidden = true;
+ element("login").hidden = false;
+ element("login-form").elements.password.value = "";
+ message("login-error", error);
+ element("login-form").elements.username.focus();
+}
+
+element("login-form").addEventListener("submit", async (event) => {
+ event.preventDefault();
+ const form = event.currentTarget;
+ if (form.elements.username.value.length > 256 || form.elements.password.value.length > 1024) {
+ message("login-error", "Проверьте длину имени пользователя и пароля.");
+ return;
+ }
+ const button = form.querySelector("button");
+ button.disabled = true;
+ button.textContent = "Вход…";
+ message("login-error", "");
+ try {
+ const username = form.elements.username.value.trim();
+ const data = await encodeLogin(username, form.elements.password.value);
+ const result = await api("/api/v1/auth/apploginr2", { data }, false);
+ if (!result.token) throw new Error("Сервер не выдал сеанс.");
+ token = result.token;
+ element("account").textContent = username;
+ form.reset();
+ element("login").hidden = true;
+ element("workspace").hidden = false;
+ sessionTimer = setTimeout(() => showLogin("Сеанс завершён. Войдите снова."), 600000);
+ navigate(routes.includes(location.hash.slice(1)) ? location.hash.slice(1) : "overview");
+ } catch (error) {
+ message("login-error", error.message);
+ } finally {
+ button.disabled = false;
+ button.textContent = "Войти";
+ }
+});
+
+element("logout").addEventListener("click", async () => {
+ element("logout").disabled = true;
+ try {
+ await api("/api/v1/analytics/eventsr2", { eventType: "LOGOUT" });
+ showLogin();
+ } catch (error) {
+ if (token) message("page-error", error.message);
+ } finally {
+ element("logout").disabled = false;
+ }
+});
+
+function tableRows(target, rows) {
+ element(target).replaceChildren(...rows.map((values) => {
+ const row = document.createElement("tr");
+ for (const value of values) row.insertCell().textContent = value ?? "—";
+ return row;
+ }));
+}
+
+function definitions(target, entries) {
+ element(target).replaceChildren(...entries.map(([label, value]) => {
+ const row = document.createElement("div");
+ const term = document.createElement("dt");
+ const definition = document.createElement("dd");
+ term.textContent = label;
+ definition.textContent = value;
+ row.append(term, definition);
+ return row;
+ }));
+}
+
+const yesNo = (value) => value === "true" ? "Да" : value === "false" ? "Нет" : "—";
+const loaders = {
+ async overview(active) {
+ const [health, result] = await Promise.all([api("/health"), api("/api/v1/info/versions")]);
+ if (!active()) return;
+ element("status").textContent = health.status === "ok" ? "Сервер работает" : "Статус неизвестен";
+ element("status").dataset.online = health.status === "ok";
+ element("server-name").textContent = result.serverName;
+ element("api-version").textContent = result.currentVersionName;
+ element("server-address").textContent = location.host;
+ tableRows("versions", result.versions.slice().reverse().map((version) =>
+ [version.name, version.supportStatus === "supported" ? "Поддерживается" : version.supportStatus, version.url]));
+ },
+ async storage(active) {
+ const result = await api("/api/v1/settings/fileserversettings");
+ if (!active()) return;
+ storagePath = result.FileServerSettings.dataFilePath;
+ element("storage-path").textContent = storagePath;
+ element("copy-path").disabled = !storagePath;
+ },
+ async security(active) {
+ const [policy, protection, counts] = await Promise.all([
+ api("/api/v1/settings/settingvalues/section/PasswordPolicy"),
+ api("/api/v1/settings/settingvaluesp2/section/ProtectPatientSocialIDs/key/isEnabled"),
+ api("/api/v1/e2ds/patientsocialids")
+ ]);
+ if (!active()) return;
+ const values = Object.fromEntries(policy.data.map(({ key, value }) => [key, value]));
+ definitions("policy", [
+ ["Минимальная длина", values.minimumLength],
+ ["Прописные буквы", yesNo(values.isUpperAlphabetsEnabled)],
+ ["Строчные буквы", yesNo(values.isLowerAlphabetsEnabled)],
+ ["Цифры", yesNo(values.isNumericDigitsEnabled)],
+ ["Специальные символы", yesNo(values.isSpecialCharactersEnabled)],
+ ["Срок действия", yesNo(values.isExpirationEnabled)]
+ ]);
+ definitions("privacy", [
+ ["Защита включена", yesNo(protection.data[0]?.value)],
+ ["Защищено", counts.protectedSocialIDs],
+ ["Без защиты", counts.unprotectedSocialIDs]
+ ]);
+ },
+ async audit(active) {
+ const result = await api("/api/v1/analytics/eventsforsearch", { ...auditFilters, pageNum: auditPage, numRows: pageSize });
+ if (!active()) return;
+ tableRows("events", result.pagedEvents.map((item) => {
+ const date = new Date(item.created);
+ return [Number.isNaN(date.valueOf()) ? item.created : dateFormat.format(date),
+ labels[item.eventType] ?? item.eventType, item.userName, item.message];
+ }));
+ element("audit-empty").hidden = result.pagedEvents.length !== 0;
+ element("audit-count").textContent = "Найдено: " + result.numTotalEvents;
+ element("previous").disabled = auditPage === 0;
+ element("next").disabled = (auditPage + 1) * pageSize >= result.numTotalEvents;
+ }
+};
+
+async function load(view) {
+ const current = ++revision;
+ const active = () => current === revision && Boolean(token);
+ message("page-error", "");
+ try {
+ await loaders[view](active);
+ } catch (error) {
+ if (active()) message("page-error", error.message);
+ }
+}
+
+function navigate(view) {
+ if (!token || !routes.includes(view)) return;
+ history.replaceState(null, "", "#" + view);
+ for (const route of routes) element(route).hidden = route !== view;
+ for (const button of nav) {
+ if (button.dataset.view === view) button.setAttribute("aria-current", "page");
+ else button.removeAttribute("aria-current");
+ }
+ element(view + "-title").focus();
+ load(view);
+}
+
+nav.forEach((button) => button.addEventListener("click", () => navigate(button.dataset.view)));
+window.addEventListener("hashchange", () => navigate(location.hash.slice(1)));
+element("copy-path").addEventListener("click", async () => {
+ try {
+ await navigator.clipboard.writeText(storagePath);
+ element("copy-status").textContent = "Скопировано";
+ } catch {
+ element("copy-status").textContent = "Выделите и скопируйте путь вручную.";
+ }
+});
+element("audit-form").addEventListener("submit", (event) => {
+ event.preventDefault();
+ const values = Object.fromEntries(new FormData(event.currentTarget));
+ if (values.startDate && values.endDate && values.startDate > values.endDate) {
+ message("page-error", "Конец периода должен быть не раньше начала.");
+ return;
+ }
+ auditFilters = values;
+ auditPage = 0;
+ load("audit");
+});
+element("previous").addEventListener("click", () => { auditPage--; load("audit"); });
+element("next").addEventListener("click", () => { auditPage++; load("audit"); });
diff --git a/Packaging/webconsole/index.html b/Packaging/webconsole/index.html
new file mode 100644
index 0000000..1ee7b1f
--- /dev/null
+++ b/Packaging/webconsole/index.html
@@ -0,0 +1,93 @@
+
+
+
+
+
+
+ ezServer · Web Console
+
+
+
+
+
+
+ ez ezServer
+ Вход в Web Console
+
+
+
+
+
+
+
+
+
+
+
+
+
Обзор сервера
+
Проверяем соединение…
+
+
+
Сервер
—
+
Версия API
—
+
Адрес
—
+
+ Поддерживаемые версии
+
+
+
+ Хранилище
+ Папка снимков
—
+ Путь можно изменить в меню ezServer, когда сервер остановлен.
+
+
+
+
+ Безопасность
+
+
Политика паролей
Требования оригинального EzServer к новым паролям
+
+
+
Защита идентификаторов
+
+
+
+ Журнал событий
+
+
+
| Время | Событие | Пользователь | Сообщение |
+
+
События не найдены.
+
+
+
+
+
+
+
+
diff --git a/Packaging/webconsole/material.css b/Packaging/webconsole/material.css
new file mode 100644
index 0000000..aee9153
--- /dev/null
+++ b/Packaging/webconsole/material.css
@@ -0,0 +1,117 @@
+:root {
+ color-scheme: light dark;
+ --surface: #f9f9ff;
+ --container: #eef0fa;
+ --low: #f4f4fc;
+ --ink: #1a1b23;
+ --muted: #454654;
+ --outline: #777786;
+ --line: #ddddea;
+ --primary: #395ca8;
+ --on-primary: #fff;
+ --primary-container: #dbe2ff;
+ --on-primary-container: #142b62;
+ --secondary-container: #e2e7f9;
+ --error: #ba1a1a;
+ --ok: #14634a;
+ font-family: Roboto, "Segoe UI", system-ui, sans-serif;
+ color: var(--ink);
+ background: var(--surface);
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --surface: #12131a;
+ --container: #202128;
+ --low: #1a1b22;
+ --ink: #e3e3ed;
+ --muted: #c6c5d5;
+ --outline: #9292a2;
+ --line: #383943;
+ --primary: #b1c5ff;
+ --on-primary: #092e70;
+ --primary-container: #233967;
+ --on-primary-container: #dbe2ff;
+ --secondary-container: #353d55;
+ --error: #ffb4ab;
+ --ok: #92d5bb;
+ }
+}
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+body { margin: 0; }
+h1, h2, p { margin-top: 0; }
+h1 { font-size: clamp(2rem, 5vw, 3rem); line-height: 1.12; font-weight: 500; letter-spacing: -.035em; margin-bottom: 20px; }
+h2 { font-size: 1.13rem; font-weight: 600; margin-bottom: 12px; }
+button, input, select { font: inherit; }
+button { cursor: pointer; border: 0; background: transparent; color: inherit; min-height: 42px; padding: 0 16px; border-radius: 999px; font-weight: 600; }
+button:hover:enabled { background: color-mix(in srgb, currentColor 9%, transparent); }
+button:disabled { cursor: default; opacity: .46; }
+:focus-visible { outline: 3px solid var(--primary); outline-offset: 3px; }
+.filled { color: var(--on-primary); background: var(--primary); padding-inline: 22px; }
+.filled:hover:enabled { background: color-mix(in srgb, var(--primary) 89%, var(--on-primary)); }
+.outlined { color: var(--primary); border: 1px solid var(--outline); }
+label { color: var(--muted); display: grid; gap: 7px; font-size: .875rem; font-weight: 550; }
+input, select { background: transparent; border: 1px solid var(--outline); border-radius: 8px; color: var(--ink); min-height: 46px; padding: 10px 13px; min-width: 0; }
+select option { color: var(--ink); background: var(--surface); }
+[role="alert"] { color: var(--error); margin: 0; overflow-wrap: anywhere; }
+.login { min-height: 100dvh; display: grid; place-items: center; padding: 24px; background: radial-gradient(ellipse at 18% 14%, var(--primary-container), var(--surface) 65%); }
+.login-panel { width: min(100%, 460px); border-radius: 32px; padding: clamp(24px, 6vw, 46px); background: var(--surface); border: 1px solid var(--line); box-shadow: 0 16px 60px #18275518; }
+.login-panel h1 { font-size: 2rem; margin: 27px 0; }
+.login-panel form { display: grid; gap: 19px; }
+.login-panel .filled { margin-top: 6px; }
+.brand { display: flex; align-items: center; gap: 11px; font-size: 1.3rem; font-weight: 700; letter-spacing: -.035em; }
+.mark { display: grid; place-items: center; width: 38px; height: 38px; background: var(--primary); color: var(--on-primary); border-radius: 13px; font-size: 1rem; }
+.workspace { display: grid; grid-template-columns: 232px minmax(0, 1fr); min-height: 100dvh; }
+.sidebar { background: var(--container); padding: 28px 16px; }
+.sidebar .brand { margin: 0 10px 30px; }
+nav { display: grid; gap: 6px; }
+nav button { display: flex; gap: 12px; align-items: center; text-align: start; color: var(--muted); min-height: 49px; white-space: nowrap; }
+nav button span { width: 20px; text-align: center; font-size: 1.26rem; line-height: 1; }
+nav button[aria-current="page"] { background: var(--secondary-container); color: var(--ink); }
+.topbar { min-height: 76px; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 28px; border-bottom: 1px solid var(--line); color: var(--muted); }
+.account { display: flex; align-items: center; gap: 12px; font-size: .88rem; }
+.page { padding: clamp(20px, 4vw, 48px); max-width: 1260px; margin: auto; }
+.page [role="alert"] { padding: 12px 0; }
+.hero { padding: clamp(22px, 4vw, 36px); background: var(--primary-container); color: var(--on-primary-container); border-radius: 28px; }
+.hero h1 { margin-bottom: 12px; }
+.status { display: inline-flex; gap: 9px; align-items: center; margin: 0; font-size: .9rem; font-weight: 600; }
+.status::before { content: ""; width: 9px; height: 9px; background: currentColor; border-radius: 50%; }
+.status[data-online="true"]::before { background: var(--ok); }
+.cards, .detail-grid { display: grid; gap: 14px; grid-template-columns: repeat(3, minmax(0, 1fr)); margin-top: 16px; }
+.detail-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+.card { padding: 20px; background: var(--low); border: 1px solid var(--line); border-radius: 20px; }
+.card h2 { color: var(--muted); }
+.card p:last-child { margin-bottom: 0; }
+.value { font-size: clamp(1.2rem, 3vw, 1.65rem); letter-spacing: -.025em; overflow-wrap: anywhere; }
+.address { font-variant-numeric: tabular-nums; }
+.section-heading { margin-top: 34px; }
+.table-wrap { border: 1px solid var(--line); border-radius: 18px; overflow: auto; }
+table { border-collapse: collapse; width: 100%; text-align: start; font-size: .9rem; }
+th, td { text-align: start; padding: 13px 17px; border-bottom: 1px solid var(--line); white-space: nowrap; }
+thead { background: var(--container); color: var(--muted); }
+tbody tr:last-child td { border-bottom: 0; }
+td:last-child { white-space: normal; overflow-wrap: anywhere; }
+.muted, .empty { color: var(--muted); }
+.empty { margin: 0; padding: 21px 17px; }
+.path { font-family: ui-monospace, monospace; line-height: 1.65; overflow-wrap: anywhere; }
+.actions, .pagination { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-top: 16px; }
+dl { margin: 0; }
+dl div { display: flex; gap: 12px; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid var(--line); }
+dl div:last-child { border-bottom: 0; }
+dd { margin: 0; font-weight: 600; text-align: end; }
+.filters { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 16px; }
+.pagination { justify-content: flex-end; }
+.pagination span { margin-inline-end: auto; }
+@media (max-width: 800px) {
+ .workspace { grid-template-columns: minmax(0, 1fr); }
+ .sidebar { padding: 14px 16px 8px; }
+ .sidebar .brand { margin: 0 0 10px; }
+ nav { display: flex; overflow-x: auto; }
+ nav button { flex: 0 0 auto; min-height: 41px; }
+ .topbar { min-height: 56px; padding: 8px 16px; }
+}
+@media (max-width: 570px) {
+ .cards, .detail-grid { grid-template-columns: 1fr; }
+ .filters label { flex: 1 1 9rem; }
+ .topbar { font-size: .9rem; }
+}
diff --git a/Packaging/webconsole/service-worker.js b/Packaging/webconsole/service-worker.js
new file mode 100644
index 0000000..8f13577
--- /dev/null
+++ b/Packaging/webconsole/service-worker.js
@@ -0,0 +1,5 @@
+// Retire the previous console's offline cache on installations upgraded in place.
+self.addEventListener("install", (event) => event.waitUntil(self.skipWaiting()));
+self.addEventListener("activate", (event) => {
+ event.waitUntil(self.registration.unregister());
+});
diff --git a/README.md b/README.md
index b54e6f5..fc7a539 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
В строке меню доступны запуск и остановка, выбор порта, выбор папки снимков и кнопка для открытия `/webconsole`. Путь и порт меняются при остановленной службе. При выборе папки EzServer копирует снимки в новый подкаталог `Files` и сохраняет прежнюю копию. По умолчанию SQLite и снимки находятся в `~/Library/Application Support/EzServerMac`. Для командной строки отдельную папку снимков можно задать абсолютным путём в `EZSERVER_IMAGES_PARENT`.
-Оригинальная Web Console извлекается из `webapps/webconsole` установщика. Её HTML, JavaScript и CSS входят в сборку, если ресурсы подготовлены через `server/prepare.sh`. В приложении вход выполняется под `Master Admin` с паролем `0000` по умолчанию. Для запуска с другим паролем задайте `EZSERVER_CONSOLE_PASSWORD`. Консоль доступна через loopback и показывает версию API, параметры SQLite, фактический путь снимков и журнал входов и выходов текущего процесса. Порт и папка меняются из строки меню. Поля оригинала для внешнего PostgreSQL и управления защитой идентификаторов пациентов в локальном режиме доступны для просмотра.
+Web Console приложения использует Material Design 3 и входит в каждую сборку. Локальный вход выполняется под `Master Admin` с паролем `0000` по умолчанию. Для запуска с другим паролем задайте `EZSERVER_CONSOLE_PASSWORD`. В консоли доступны обзор API, путь снимков, сведения о защите и журнал входов и выходов текущего процесса. Порт и папка меняются из строки меню. Отдельный PHP-режим раздаёт оригинальные статические ресурсы из установщика.
## Импорт из EzDent
diff --git a/context.md b/context.md
index 7a1ec9f..889a4c2 100644
--- a/context.md
+++ b/context.md
@@ -22,7 +22,7 @@
Относительно извлечённого `www/ezwebserver/src`:
-- Оригинальные статические ресурсы Web Console находятся в `webapps/webconsole` установщика. Swift-режим обслуживает её оригинальный AES-вход (Master Admin / 0000 по умолчанию), настройки SQLite и файлов, версии и журнал сеанса. PHP-режим пока раздаёт статические ресурсы консоли.
+- Панель приложения на Material Design 3 находится в `Packaging/webconsole` и собирается с приложением. Она использует оригинальный AES-вход (Master Admin / 0000 по умолчанию), версии, путь снимков, сведения о защите и журнал сеанса. DB Server Setting в панели отсутствует. PHP-режим раздаёт оригинальные статические ресурсы из `webapps/webconsole` установщика.
- `public/api/index.php` — точка входа, `application/config/routes.php` — маршруты. Версия API в комплекте — 3.0.6.
- `application/controllers/v1/E2Ds.php` — оригинальные операции с карточками, включая `POST /api/v1/e2ds/patients` с полем `strChartNo` и `GET /api/v1/e2ds/patientsByChartNo?chartno=…`.
- `application/config/database.php` — конфигурация групп БД. В `vendor/codeigniter/framework/system/database/drivers/` есть драйверы SQLite3 и PDO SQLite. При переносе проверить модели пациентов и групп данных на PostgreSQL-специфичные запросы. Схема текущего Swift-хранилища и схема оригинала требуют отдельного сопоставления.
diff --git a/scripts/build-server.sh b/scripts/build-server.sh
index fcd3637..89597ab 100755
--- a/scripts/build-server.sh
+++ b/scripts/build-server.sh
@@ -22,10 +22,7 @@ xcrun lipo -create "$arm64_bin/EzServerMac" "$x86_64_bin/EzServerMac" -output "$
xcrun lipo "$binary" -verify_arch arm64 x86_64
cp Packaging/Info.plist "$app/Contents/Info.plist"
cp README.md "$app/Contents/Resources/README.md"
-runtime="${EZSERVER_RUNTIME:-$PWD/.build/ezserver-macos/runtime}"
-if [[ -f "$runtime/webconsole/index.html" ]]; then
- ditto "$runtime/webconsole" "$app/Contents/Resources/webconsole"
-fi
+ditto Packaging/webconsole "$app/Contents/Resources/webconsole"
codesign --force --sign - "$app"
codesign --verify --deep --strict "$app"
ditto -c -k --keepParent "$app" "$stage/EzServerMac-universal.zip"