Files
TableExpirationWatcher/src/api/views/settings-page.ts
T

392 lines
21 KiB
TypeScript

export function renderSettingsHtml(): string {
return `<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>Ajustes • Monitor de Tabelas Vencidas</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Onest:wght@400;500;600;700;800&display=swap');
:root {
--rms-pink: #ec008c;
--rms-blue: #303952;
--rms-cyan: #00bcd4;
--bg-primary: #f7f8fa;
--card-bg: #ffffff;
--card-border: rgba(0, 0, 0, 0.06);
--separator: rgba(60, 60, 67, 0.12);
--text-primary: #1a1c1e;
--text-secondary: #64748b;
--accent: var(--rms-pink);
--accent-hover: #c90078;
--control-bg: rgba(118, 118, 128, 0.12);
--switch-off: #e5e5ea;
--switch-on: #34c759;
--danger: #ff3b30;
--font-family: "Onest", -apple-system, BlinkMacSystemFont, "Helvetica Neue", sans-serif;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #121827;
--card-bg: #1b2433;
--card-border: rgba(255, 255, 255, 0.08);
--separator: rgba(84, 84, 88, 0.25);
--text-primary: #f8fafc;
--text-secondary: #a9b8ca;
--accent: var(--rms-pink);
--accent-hover: #ff4ab0;
--control-bg: rgba(118, 118, 128, 0.24);
--switch-off: #39393d;
--switch-on: #30d158;
--danger: #ff453a;
}
}
* { box-sizing: border-box; margin: 0; padding: 0; font-family: var(--font-family); -webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: transparent; }
body {
background-color: var(--bg-primary);
color: var(--text-primary);
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
padding: env(safe-area-inset-top) env(safe-area-inset-right) 40px env(safe-area-inset-left);
transition: background-color 0.3s ease;
}
header {
width: 100%;
max-width: 680px;
padding: 24px 16px 12px;
display: flex;
justify-content: space-between;
align-items: center;
}
.title-group h1 { font-size: 24px; font-weight: 800; letter-spacing: -0.5px; }
.title-group p { font-size: 13px; color: var(--text-secondary); margin-top: 2px; }
.header-actions { display: flex; gap: 8px; }
.btn {
appearance: none; border: none; outline: none; cursor: pointer;
font-size: 14px; font-weight: 600; border-radius: 999px; padding: 8px 16px;
display: inline-flex; align-items: center; gap: 6px;
transition: transform 150ms cubic-bezier(0.23, 1, 0.32, 1), background-color 150ms ease;
}
.btn:active { transform: scale(0.96); }
.btn:focus-visible, .segment-btn:focus-visible, input:focus-visible {
outline: 3px solid rgba(0, 188, 212, 0.35); outline-offset: 2px;
}
.btn-primary { background-color: var(--accent); color: #ffffff; }
@media (hover: hover) and (pointer: fine) { .btn-primary:hover { background-color: var(--accent-hover); } }
.btn-secondary { background-color: var(--control-bg); color: var(--text-primary); }
.segmented-control {
width: 100%; max-width: 680px; background: var(--control-bg); padding: 3px; border-radius: 12px;
display: flex; margin: 8px 0 20px; position: sticky; top: 12px; z-index: 20;
backdrop-filter: blur(25px); -webkit-backdrop-filter: blur(25px);
}
.segment-btn { flex: 1; padding: 8px 12px; font-size: 13px; font-weight: 500; text-align: center;
cursor: pointer; border-radius: 9px; transition: color 160ms ease, background-color 160ms ease;
color: var(--text-secondary); user-select: none; }
.segment-btn.active { background: var(--card-bg); color: var(--text-primary); font-weight: 600; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); }
main { width: 100%; max-width: 680px; padding: 0 16px; }
.section-title { font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-secondary); margin: 20px 16px 8px; font-weight: 500; }
.card-group { background: var(--card-bg); border-radius: 16px; border: 1px solid var(--card-border); overflow: hidden; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.03); }
.health-panel {
width: 100%; max-width: 680px; margin: 4px 0 8px; padding: 16px;
border: 1px solid rgba(0, 188, 212, 0.18); border-radius: 16px;
background: linear-gradient(135deg, rgba(48, 57, 82, 0.98), rgba(48, 57, 82, 0.92));
color: #fff; box-shadow: 0 4px 16px rgba(48, 57, 82, 0.25);
}
.health-panel-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.health-panel h2 { margin-top: 3px; font-size: 18px; font-weight: 700; letter-spacing: -0.3px; }
.health-panel .eyebrow { color: var(--rms-cyan); font-size: 11px; font-weight: 700; letter-spacing: .08em; }
.health-panel .btn-secondary { background: rgba(255,255,255,.12); color: #fff; }
.health-summary { margin: 14px 0 10px; color: rgba(255,255,255,.78); font-size: 13px; }
.health-components { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
.health-item { min-width: 0; padding: 10px; border-radius: 12px; background: rgba(255,255,255,.08); display: grid; grid-template-columns: auto 1fr; gap: 8px; align-items: center; }
.health-item strong, .health-item small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.health-item strong { font-size: 12px; }
.health-item small { margin-top: 2px; color: rgba(255,255,255,.58); font-size: 10px; }
.health-dot { width: 8px; height: 8px; border-radius: 50%; grid-row: span 2; }
.health-dot.is-ok { background: var(--rms-cyan); box-shadow: 0 0 8px rgba(0,188,212,.6); }
.health-dot.is-bad { background: #ffb4ab; }
.health-status { grid-column: 2; font-size: 10px; font-weight: 700; }
.health-status.is-ok { color: var(--rms-cyan); }
.health-status.is-bad { color: #ffb4ab; }
@media (max-width: 560px) { .health-components { grid-template-columns: repeat(2, 1fr); } }
.setting-row { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; border-bottom: 0.5px solid var(--separator); gap: 16px; }
.setting-row:last-child { border-bottom: none; }
.setting-info { flex: 1; min-width: 0; }
.setting-label { font-size: 15px; font-weight: 500; color: var(--text-primary); letter-spacing: -0.2px; }
.setting-desc { font-size: 12px; color: var(--text-secondary); margin-top: 2px; line-height: 1.35; }
.setting-control { display: flex; align-items: center; gap: 8px; }
.switch { position: relative; display: inline-block; width: 51px; height: 31px; flex-shrink: 0; }
.switch input { opacity: 0; width: 0; height: 0; }
.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: var(--switch-off); transition: background-color 0.25s cubic-bezier(0.2, 0, 0, 1); border-radius: 31px; }
.slider:before { position: absolute; content: ""; height: 27px; width: 27px; left: 2px; bottom: 2px; background-color: white; transition: transform 0.25s cubic-bezier(0.2, 0, 0, 1); border-radius: 50%; box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15), 0 1px 1px rgba(0, 0, 0, 0.16); }
input:checked + .slider { background-color: var(--switch-on); }
input:checked + .slider:before { transform: translateX(20px); }
.input-field { appearance: none; border: 1px solid var(--separator); background: var(--control-bg); color: var(--text-primary); padding: 8px 12px; border-radius: 10px; font-size: 14px; outline: none; width: 100%; max-width: 260px; transition: border-color 160ms ease, background-color 160ms ease, box-shadow 160ms ease; text-align: right; }
.input-field:focus { border-color: var(--accent); background: var(--card-bg); box-shadow: 0 0 0 3px rgba(236, 0, 140, 0.15); }
.input-field.secret { font-family: monospace; letter-spacing: 1px; }
#toast { position: fixed; bottom: 30px; background: rgba(0, 0, 0, 0.85); color: #ffffff; padding: 10px 20px; border-radius: 999px; font-size: 14px; font-weight: 500; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25); transform: translateY(80px) scale(0.9); opacity: 0; pointer-events: none; transition: transform 220ms cubic-bezier(0.23, 1, 0.32, 1), opacity 220ms ease; z-index: 1000; backdrop-filter: blur(15px); -webkit-backdrop-filter: blur(15px); display: flex; align-items: center; gap: 8px; }
@media (prefers-color-scheme: dark) { #toast { background: rgba(255, 255, 255, 0.9); color: #000000; } }
#toast.show { transform: translateY(0) scale(1); opacity: 1; }
#auth-modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.4); backdrop-filter: blur(25px); -webkit-backdrop-filter: blur(25px); display: flex; align-items: center; justify-content: center; padding: 16px; z-index: 2000; opacity: 0; pointer-events: none; transition: opacity 0.25s ease; }
#auth-modal.visible { opacity: 1; pointer-events: auto; }
.auth-card { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 20px; padding: 28px; width: 100%; max-width: 360px; text-align: center; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15); transform: scale(0.95); transition: transform 0.25s cubic-bezier(0.2, 0, 0, 1); }
#auth-modal.visible .auth-card { transform: scale(1); }
.auth-icon { width: 56px; height: 56px; background: var(--control-bg); border-radius: 16px; display: inline-flex; align-items: center; justify-content: center; font-size: 26px; margin-bottom: 16px; }
.auth-card h2 { font-size: 20px; font-weight: 700; letter-spacing: -0.3px; margin-bottom: 6px; }
.auth-card p { font-size: 13px; color: var(--text-secondary); margin-bottom: 20px; }
.auth-input { width: 100%; padding: 12px 14px; border-radius: 12px; border: 1px solid var(--separator); background: var(--control-bg); color: var(--text-primary); font-size: 15px; outline: none; margin-bottom: 14px; text-align: center; font-family: monospace; letter-spacing: 1px; transition: border-color 160ms ease, background-color 160ms ease; }
.auth-input:focus { border-color: var(--accent); background: var(--card-bg); }
.auth-input.shake { animation: shake 0.4s cubic-bezier(0.36, 0.07, 0.19, 0.97) both; border-color: var(--danger); }
@keyframes shake { 10%, 90% { transform: translate3d(-2px, 0, 0); } 20%, 80% { transform: translate3d(4px, 0, 0); } 30%, 50%, 70% { transform: translate3d(-6px, 0, 0); } 40%, 60% { transform: translate3d(6px, 0, 0); } }
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: .01ms !important; transition-duration: .01ms !important; } }
</style>
</head>
<body>
<!-- Modal de Autenticação Secret Key -->
<div id="auth-modal">
<div class="auth-card">
<div class="auth-icon">🔐</div>
<h2>Painel de Ajustes</h2>
<p>Digite a Secret Key da API para autenticar e gerenciar as configurações.</p>
<input type="password" id="secret-key-input" class="auth-input" placeholder="API Secret Key" autofocus autocomplete="current-password" />
<button id="auth-submit-btn" class="btn btn-primary" style="width: 100%; justify-content: center; padding: 12px;">Entrar</button>
</div>
</div>
<!-- Header -->
<header>
<div class="title-group">
<h1>Ajustes</h1>
<p>Monitor de Tabelas RMS • Hot-Reload Ativo</p>
</div>
<div class="header-actions">
<button id="save-all-btn" class="btn btn-primary">Salvar</button>
<button id="logout-btn" class="btn btn-secondary">Sair</button>
</div>
</header>
<section id="container-health" class="health-panel" aria-label="Saúde da aplicação">
<div class="health-panel-header">
<div><span class="eyebrow">OPERAÇÃO</span><h2>Saúde do Monitor</h2></div>
<button id="health-refresh" class="btn btn-secondary" type="button">Atualizar</button>
</div>
<div id="health-summary" class="health-summary" role="status" aria-live="polite">Verificando...</div>
<div id="health-components" class="health-components"></div>
</section>
<div class="segmented-control" id="category-tabs">
<div class="segment-btn active" data-cat="all">Todas</div>
<div class="segment-btn" data-cat="sync">Sync & CMS</div>
<div class="segment-btn" data-cat="notifications">Notificações</div>
<div class="segment-btn" data-cat="general">Sistema</div>
</div>
<main id="settings-container">
<div style="text-align:center; padding: 40px; color: var(--text-secondary);">Carregando configurações...</div>
</main>
<div id="toast"><span>✓</span> Ajustes atualizados com sucesso</div>
<script>
let currentSettings = [];
let dirtyValues = {};
let activeCategory = 'all';
const healthLabels = { cms: 'CMS API', db: 'SQLite', scheduler: 'Scheduler', notifier: 'Notificador' };
// 1. Verificação de Sessão
async function checkAuth() {
try {
const res = await fetch('/api/v1/configs/me');
const data = await res.json();
if (data.authenticated) { hideAuthModal(); loadSettings(); }
else { showAuthModal(); }
} catch (err) { showAuthModal(); }
}
function showAuthModal() {
document.getElementById('auth-modal').classList.add('visible');
document.getElementById('secret-key-input').focus();
}
function hideAuthModal() { document.getElementById('auth-modal').classList.remove('visible'); }
async function handleLogin() {
const input = document.getElementById('secret-key-input');
const key = input.value.trim();
if (!key) return;
try {
const res = await fetch('/api/v1/configs/auth', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ secretKey: key })
});
if (res.ok) { hideAuthModal(); input.value = ''; loadSettings(); showToast('Autenticado com sucesso'); }
else { input.classList.add('shake'); setTimeout(() => input.classList.remove('shake'), 450); }
} catch (err) { input.classList.add('shake'); setTimeout(() => input.classList.remove('shake'), 450); }
}
document.getElementById('auth-submit-btn').addEventListener('click', handleLogin);
document.getElementById('secret-key-input').addEventListener('keydown', (e) => { if (e.key === 'Enter') handleLogin(); });
document.getElementById('logout-btn').addEventListener('click', async () => {
await fetch('/api/v1/configs/logout', { method: 'POST' });
showAuthModal();
});
// 2. Carregar Configurações
async function loadSettings() {
try {
const res = await fetch('/api/v1/configs');
if (!res.ok) { if (res.status === 401) showAuthModal(); return; }
const data = await res.json();
currentSettings = data.settings || [];
renderSettings(activeCategory);
checkHealth();
} catch (err) { console.error('Erro ao carregar:', err); }
}
async function checkHealth() {
const summary = document.getElementById('health-summary');
const list = document.getElementById('health-components');
if (!summary || !list) return;
try {
const res = await fetch('/api/status');
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();
const entries = [
{ key: 'cms', status: data.cmsReachable ? 'healthy' : 'unhealthy', detail: data.cmsReachable ? 'Conectado' : 'Falha na conexão' },
{ key: 'db', status: 'healthy', detail: 'OK' },
{ key: 'scheduler', status: data.schedulerRunning ? 'healthy' : 'unhealthy', detail: data.schedulerRunning ? 'Rodando' : 'Parado' },
{ key: 'notifier', status: data.notifierReady ? 'healthy' : 'unhealthy', detail: data.notifierReady ? 'Pronto' : 'Config incompleta' },
];
const healthyCount = entries.filter(e => e.status === 'healthy').length;
summary.innerText = healthyCount === 4 ? 'Todos os componentes operacionais.' : 'Alguns componentes com problemas.';
list.replaceChildren();
entries.forEach(item => {
const healthy = item.status === 'healthy';
const row = document.createElement('div');
row.className = 'health-item';
const dot = document.createElement('span');
dot.className = 'health-dot ' + (healthy ? 'is-ok' : 'is-bad');
const text = document.createElement('div');
const name = document.createElement('strong');
name.textContent = healthLabels[item.key] || item.key;
const detail = document.createElement('small');
detail.textContent = item.detail;
text.append(name, detail);
const state = document.createElement('span');
state.className = 'health-status ' + (healthy ? 'is-ok' : 'is-bad');
state.textContent = healthy ? 'OK' : 'Atenção';
row.append(dot, text, state);
list.appendChild(row);
});
} catch {
summary.innerText = 'Não foi possível consultar a saúde.';
list.innerHTML = '';
}
}
document.getElementById('health-refresh').addEventListener('click', checkHealth);
setInterval(checkHealth, 30000);
// 3. Renderização
function renderSettings(filterCategory = 'all') {
activeCategory = filterCategory;
const container = document.getElementById('settings-container');
container.innerHTML = '';
const categories = [
{ id: 'sync', title: 'Sincronização & CMS' },
{ id: 'notifications', title: 'Notificações & Canais' },
{ id: 'general', title: 'Sistema & Operação' },
];
categories.forEach(cat => {
if (filterCategory !== 'all' && filterCategory !== cat.id) return;
const items = currentSettings.filter(s => s.category === cat.id);
if (items.length === 0) return;
const titleEl = document.createElement('div');
titleEl.className = 'section-title';
titleEl.innerText = cat.title;
container.appendChild(titleEl);
const card = document.createElement('div');
card.className = 'card-group';
items.forEach(item => {
const row = document.createElement('div');
row.className = 'setting-row';
const isBool = item.type === 'boolean' || item.value === 'true' || item.value === 'false';
let controlHtml = '';
if (isBool) {
const checked = item.value === 'true' || item.value === '1';
controlHtml = '<label class="switch"><input type="checkbox" data-key="' + item.key + '" ' + (checked ? 'checked' : '') + ' onchange="onSwitchChange(this)"><span class="slider"></span></label>';
} else {
const isSecret = item.isSecret;
controlHtml = '<input type="' + (isSecret ? 'password' : 'text') + '" class="input-field ' + (isSecret ? 'secret' : '') + '" data-key="' + item.key + '" value="' + item.value + '" oninput="onInputChange(this)" />';
}
row.innerHTML = '<div class="setting-info"><div class="setting-label">' + item.label + '</div><div class="setting-desc">' + (item.description || item.key) + '</div></div><div class="setting-control">' + controlHtml + '</div>';
card.appendChild(row);
});
container.appendChild(card);
});
}
function onSwitchChange(checkbox) { dirtyValues[checkbox.getAttribute('data-key')] = checkbox.checked ? 'true' : 'false'; }
function onInputChange(input) { dirtyValues[input.getAttribute('data-key')] = input.value.trim(); }
// 4. Salvar
document.getElementById('save-all-btn').addEventListener('click', async () => {
const keys = Object.keys(dirtyValues);
if (keys.length === 0) { showToast('Nenhuma alteração pendente'); return; }
try {
const res = await fetch('/api/v1/configs', {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ settings: dirtyValues })
});
if (res.ok) { showToast('Configurações salvas!'); dirtyValues = {}; loadSettings(); }
else { showToast('Erro ao salvar'); }
} catch (err) { showToast('Falha na conexão'); }
});
// 5. Abas
document.getElementById('category-tabs').addEventListener('click', (e) => {
const btn = e.target.closest('.segment-btn');
if (!btn) return;
document.querySelectorAll('.segment-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
renderSettings(btn.getAttribute('data-cat'));
});
function showToast(text) {
const toast = document.getElementById('toast');
toast.innerHTML = '<span>✓</span> ' + text;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 2400);
}
checkAuth();
</script>
</body>
</html>`;
}