feat(ui): editorial status and approve/reject actions on /ui
Node tests / test (push) Has been cancelled
Node tests / test (push) Has been cancelled
- Persist editorial_status on new article log rows; add updateArticleStatus() with atomic rewrite - Dashboard: badges, flash from ?flash=, POST /ui/articles/:id/approve|reject (ADMIN_TOKEN) - Tests for article log; README documents endpoints and proxy note Paperclip-Run: 5aeedb07-8f14-40bb-b737-79354c25d4c1 Paperclip-Task: ca360b61-1e05-47bc-ad3c-b1d78ce7d104
This commit is contained in:
1 parent
492918d861
commit
3727e11129
4 files changed
+221
-17
No files matched your search
@@ -50,11 +50,13 @@ Only when the app runs in **`listen`** mode (long-running service behind NPM):
|
||||
| `GET /ui/social` | View or edit `config/social.json` (X queries only; bearer stays in `.env`) |
|
||||
| `GET /ui/publishers` | Read-only WordPress targets (no passwords shown) |
|
||||
| `GET /ui/theme` | View or edit `config/ui-theme.json` (title + accent colour) |
|
||||
| `GET /api/ui/articles?limit=50` | JSON list of logged articles (titles/metadata; restrict NPM access if sensitive) |
|
||||
| `POST /ui/articles/:id/approve` | Set `editorial_status` to **approved** (`ADMIN_TOKEN` required) — `:id` is URL-encoded slug, or ISO `at` when slug is empty |
|
||||
| `POST /ui/articles/:id/reject` | Set `editorial_status` to **rejected** (`ADMIN_TOKEN` required) |
|
||||
| `GET /api/ui/articles?limit=50` | JSON list of logged articles (includes `editorial_status` on new rows; restrict NPM access if sensitive) |
|
||||
|
||||
Set **`ADMIN_TOKEN`** in `.env` to enable saving from the browser forms. Without it, pages are read-only. **`POST /ui/*` saves** must use **`Content-Type: application/x-www-form-urlencoded`** (browser default); other types get **415**. Protect `/ui` at the reverse proxy (VPN, SSO, IP allowlist) in production — this is a functional stopgap, not a hardened CMS.
|
||||
Set **`ADMIN_TOKEN`** in `.env` to enable saving from the browser forms and editorial actions. Without it, pages are read-only except viewing states. **`POST /ui/*` saves** must use **`Content-Type: application/x-www-form-urlencoded`** (browser default); other types get **415**. Protect `/ui` at the reverse proxy (VPN, SSO, IP allowlist) in production — this is a functional stopgap, not a hardened CMS. **Approve/reject endpoints mutate persisted article metadata** (`data/article-index.jsonl`); treat `/ui` like an internal admin surface.
|
||||
|
||||
There is **no** full editorial workflow yet (approve / reject / rich edit). That remains optional per BIT-353; combine `/ui` with CLI (`npm run write`), logs, and WordPress as needed.
|
||||
A minimal **editorial** flow is available on **`GET /ui`**: each row shows `editorial_status` (pending / approved / rejected). Records written before this field existed are shown as pending. Rich editing is still out of scope; combine `/ui` with CLI (`npm run write`), logs, and WordPress as needed.
|
||||
|
||||
## Architecture
|
||||
|
||||
|
||||
+124
-14
@@ -8,7 +8,7 @@ const { parseBodyReadTimeoutMs } = require('./body-read-timeout');
|
||||
const { isAllowedAdminFormContentType } = require('./ui-form-post');
|
||||
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('../config/loader');
|
||||
const { resolveWpTransport } = require('../publisher/wp-transport');
|
||||
const { readLastArticles } = require('../store/article-log');
|
||||
const { readLastArticles, updateArticleStatus, articleRowId } = require('../store/article-log');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..', '..');
|
||||
const SOURCES_PATH = path.join(ROOT, 'config', 'sources.json');
|
||||
@@ -195,6 +195,12 @@ function layout(title, innerHtml, theme) {
|
||||
.note { color: var(--muted); font-size: 0.9rem; margin: 0.5rem 0 1rem; }
|
||||
.err { color: #b91c1c; margin: 0.5rem 0; }
|
||||
.ok { color: #15803d; margin: 0.5rem 0; }
|
||||
.badge { display: inline-block; padding: 0.15rem 0.45rem; border-radius: 4px; font-size: 0.78rem; font-weight: 600; }
|
||||
.badge-pending { background: #e5e7eb; color: #374151; }
|
||||
.badge-approved { background: #dcfce7; color: #166534; }
|
||||
.badge-rejected { background: #fee2e2; color: #991b1b; }
|
||||
.row-actions { white-space: nowrap; }
|
||||
.row-actions .btn { padding: 0.25rem 0.5rem; font-size: 0.8rem; margin-right: 0.35rem; }
|
||||
label { display: block; margin: 0.75rem 0 0.25rem; font-size: 0.9rem; }
|
||||
input[type="password"], input[type="text"] { width: 100%; max-width: 24rem; padding: 0.4rem 0.5rem; }
|
||||
</style>
|
||||
@@ -219,24 +225,75 @@ function layout(title, innerHtml, theme) {
|
||||
</html>`;
|
||||
}
|
||||
|
||||
function pageDashboard(theme) {
|
||||
function editorialBadgeClass(status) {
|
||||
const s = status || 'pending';
|
||||
if (s === 'approved') {
|
||||
return 'badge-approved';
|
||||
}
|
||||
if (s === 'rejected') {
|
||||
return 'badge-rejected';
|
||||
}
|
||||
return 'badge-pending';
|
||||
}
|
||||
|
||||
function editorialLabel(status) {
|
||||
const s = status || 'pending';
|
||||
if (s === 'approved') {
|
||||
return 'Aprovado';
|
||||
}
|
||||
if (s === 'rejected') {
|
||||
return 'Rejeitado';
|
||||
}
|
||||
return 'Pendente';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ type: 'ok' | 'err', text: string } | null} flash
|
||||
*/
|
||||
function pageDashboard(theme, flash) {
|
||||
const articles = readLastArticles(80);
|
||||
const tokenSet = !!getAdminToken();
|
||||
let rows = articles
|
||||
.map(
|
||||
(a) =>
|
||||
`<tr><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${
|
||||
a.wp_link
|
||||
? `<a href="${escapeHtml(a.wp_link)}" rel="noopener">WP</a>`
|
||||
: '—'
|
||||
}</td></tr>`
|
||||
)
|
||||
.map((a) => {
|
||||
const st = a.editorial_status || 'pending';
|
||||
const badge = `<span class="badge ${editorialBadgeClass(st)}">${escapeHtml(editorialLabel(st))}</span>`;
|
||||
const rid = articleRowId(a);
|
||||
const enc = encodeURIComponent(rid);
|
||||
const actions = tokenSet
|
||||
? `<span class="row-actions"><form class="js-article-action" method="post" action="/ui/articles/${enc}/approve" style="display:inline"><input type="hidden" name="admin_token" value="" /><button type="submit" class="btn">Aprovar</button></form><form class="js-article-action" method="post" action="/ui/articles/${enc}/reject" style="display:inline"><input type="hidden" name="admin_token" value="" /><button type="submit" class="btn">Rejeitar</button></form></span>`
|
||||
: '—';
|
||||
return `<tr><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${
|
||||
a.wp_link ? `<a href="${escapeHtml(a.wp_link)}" rel="noopener">WP</a>` : '—'
|
||||
}</td><td>${badge}</td><td>${actions}</td></tr>`;
|
||||
})
|
||||
.join('');
|
||||
if (!rows) {
|
||||
rows = '<tr><td colspan="4">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
rows =
|
||||
'<tr><td colspan="6">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
}
|
||||
const flashHtml = flash
|
||||
? `<p class="${flash.type === 'err' ? 'err' : 'ok'}">${escapeHtml(flash.text)}</p>`
|
||||
: '';
|
||||
const tokenBlock = tokenSet
|
||||
? `<p class="note"><label for="dash_admin_token">Token admin</label><br /><input type="password" id="dash_admin_token" name="dash_admin_token" autocomplete="off" placeholder="ADMIN_TOKEN" style="max-width:24rem" /></p>`
|
||||
: '<p class="note"><strong>ADMIN_TOKEN</strong> não definido — só pode ver estados; não pode aprovar ou rejeitar.</p>';
|
||||
const inner = `<h1>Artigos gerados</h1>
|
||||
${flashHtml}
|
||||
${tokenBlock}
|
||||
<p class="note">Listagem simples dos títulos guardados em <code>data/article-index.jsonl</code> (últimos 80).</p>
|
||||
<table><thead><tr><th>Data</th><th>Título</th><th>Site</th><th>WP</th></tr></thead><tbody>${rows}</tbody></table>`;
|
||||
<table><thead><tr><th>Data</th><th>Título</th><th>Site</th><th>WP</th><th>Estado</th><th>Ações</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
<script>
|
||||
(function () {
|
||||
var tok = document.getElementById('dash_admin_token');
|
||||
if (!tok) return;
|
||||
document.querySelectorAll('form.js-article-action').forEach(function (f) {
|
||||
f.addEventListener('submit', function () {
|
||||
var h = f.querySelector('input[name="admin_token"]');
|
||||
if (h) h.value = tok.value;
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>`;
|
||||
return layout('Artigos', inner, theme);
|
||||
}
|
||||
|
||||
@@ -330,7 +387,16 @@ async function tryHandleAdminUi(req, res) {
|
||||
const theme = loadUiTheme();
|
||||
|
||||
if (req.method === 'GET' && pathname === '/ui') {
|
||||
const html = pageDashboard(theme);
|
||||
const flashParam = u.searchParams.get('flash');
|
||||
let flash = null;
|
||||
if (flashParam === 'approved') {
|
||||
flash = { type: 'ok', text: 'Estado editorial: aprovado.' };
|
||||
} else if (flashParam === 'rejected') {
|
||||
flash = { type: 'ok', text: 'Estado editorial: rejeitado.' };
|
||||
} else if (flashParam === 'err') {
|
||||
flash = { type: 'err', text: 'Não foi possível atualizar o estado (token ou artigo).' };
|
||||
}
|
||||
const html = pageDashboard(theme, flash);
|
||||
res.writeHead(200, mergeResponseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) }));
|
||||
res.end(html);
|
||||
return true;
|
||||
@@ -372,9 +438,11 @@ async function tryHandleAdminUi(req, res) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const isArticleActionPost = req.method === 'POST' && /^\/ui\/articles\/(.+)\/(approve|reject)$/.test(pathname);
|
||||
|
||||
if (
|
||||
req.method === 'POST' &&
|
||||
(pathname === '/ui/sources' || pathname === '/ui/social' || pathname === '/ui/theme')
|
||||
(pathname === '/ui/sources' || pathname === '/ui/social' || pathname === '/ui/theme' || isArticleActionPost)
|
||||
) {
|
||||
if (!isAllowedAdminFormContentType(req)) {
|
||||
logger.warn(`UI: rejected POST ${pathname} — unsupported Content-Type: ${String(req.headers['content-type'])}`);
|
||||
@@ -390,6 +458,48 @@ async function tryHandleAdminUi(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
if (isArticleActionPost) {
|
||||
const m = /^\/ui\/articles\/(.+)\/(approve|reject)$/.exec(pathname);
|
||||
if (!m) {
|
||||
return false;
|
||||
}
|
||||
if (!isAllowedAdminFormContentType(req)) {
|
||||
logger.warn(`UI: rejected POST ${pathname} — unsupported Content-Type: ${String(req.headers['content-type'])}`);
|
||||
res.writeHead(
|
||||
415,
|
||||
mergeResponseHeaders({
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
Accept: 'application/x-www-form-urlencoded',
|
||||
})
|
||||
);
|
||||
res.end('Unsupported Media Type: admin forms expect application/x-www-form-urlencoded');
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const raw = await collectBody(req);
|
||||
const params = new URLSearchParams(raw.toString('utf8'));
|
||||
const token = params.get('admin_token') || '';
|
||||
if (!adminOk(req, token)) {
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=err' }));
|
||||
res.end();
|
||||
return true;
|
||||
}
|
||||
const id = decodeURIComponent(m[1]);
|
||||
const newStatus = m[2] === 'approve' ? 'approved' : 'rejected';
|
||||
updateArticleStatus(id, newStatus);
|
||||
logger.info(`UI: editorial_status=${newStatus} for id=${id}`);
|
||||
const loc = m[2] === 'approve' ? '/ui?flash=approved' : '/ui?flash=rejected';
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: loc }));
|
||||
res.end();
|
||||
return true;
|
||||
} catch (err) {
|
||||
logger.warn(`UI: article status update failed: ${err.message}`);
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=err' }));
|
||||
res.end();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && pathname === '/ui/sources') {
|
||||
let msg = null;
|
||||
try {
|
||||
|
||||
@@ -73,6 +73,59 @@ function trimArticleLogIfNeeded() {
|
||||
* @param {string} [rec.site_name]
|
||||
* @param {string} [rec.mode] write | listen
|
||||
*/
|
||||
/**
|
||||
* Stable row id for matching: slug when non-empty, else ISO `at`.
|
||||
*
|
||||
* @param {{ slug?: string, at?: string }} rec
|
||||
* @returns {string}
|
||||
*/
|
||||
function articleRowId(rec) {
|
||||
const s = rec.slug && String(rec.slug).trim();
|
||||
if (s) {
|
||||
return s;
|
||||
}
|
||||
return String(rec.at || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @param {'pending' | 'approved' | 'rejected'} newStatus
|
||||
*/
|
||||
function updateArticleStatus(id, newStatus) {
|
||||
const allowed = new Set(['pending', 'approved', 'rejected']);
|
||||
if (!allowed.has(newStatus)) {
|
||||
throw new Error('invalid editorial status');
|
||||
}
|
||||
const logPath = getArticleLogPath();
|
||||
if (!fs.existsSync(logPath)) {
|
||||
throw new Error('article not found');
|
||||
}
|
||||
const raw = fs.readFileSync(logPath, 'utf8');
|
||||
const lines = raw.split('\n').filter((l) => l.trim().length > 0);
|
||||
const out = [];
|
||||
let found = false;
|
||||
for (const line of lines) {
|
||||
let rec;
|
||||
try {
|
||||
rec = JSON.parse(line);
|
||||
} catch (_err) {
|
||||
out.push(line);
|
||||
continue;
|
||||
}
|
||||
if (articleRowId(rec) === id) {
|
||||
rec.editorial_status = newStatus;
|
||||
found = true;
|
||||
}
|
||||
out.push(JSON.stringify(rec));
|
||||
}
|
||||
if (!found) {
|
||||
throw new Error('article not found');
|
||||
}
|
||||
const tmp = `${logPath}.${process.pid}.${Date.now()}.tmp`;
|
||||
fs.writeFileSync(tmp, `${out.join('\n')}\n`, 'utf8');
|
||||
fs.renameSync(tmp, logPath);
|
||||
}
|
||||
|
||||
function appendArticleRecord(rec) {
|
||||
ensureLogParentDir();
|
||||
const line = JSON.stringify({
|
||||
@@ -84,6 +137,7 @@ function appendArticleRecord(rec) {
|
||||
wp_link: rec.wp_link || null,
|
||||
site_name: rec.site_name || null,
|
||||
mode: rec.mode || 'unknown',
|
||||
editorial_status: 'pending',
|
||||
});
|
||||
const logPath = getArticleLogPath();
|
||||
fs.appendFileSync(logPath, `${line}\n`, 'utf8');
|
||||
@@ -127,6 +181,8 @@ function getArticleLogHealthFields() {
|
||||
|
||||
module.exports = {
|
||||
appendArticleRecord,
|
||||
updateArticleStatus,
|
||||
articleRowId,
|
||||
readLastArticles,
|
||||
getArticleLogPath,
|
||||
getArticleLogHealthFields,
|
||||
|
||||
@@ -57,4 +57,40 @@ describe('article-log', () => {
|
||||
const n = raw.split('\n').filter((l) => l.trim().length > 0).length;
|
||||
assert.equal(n, 5);
|
||||
});
|
||||
|
||||
it('appendArticleRecord sets editorial_status pending', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
al.appendArticleRecord({ title: 'T', slug: 'my-slug', mode: 'write' });
|
||||
const rows = al.readLastArticles(5);
|
||||
assert.equal(rows[0].editorial_status, 'pending');
|
||||
});
|
||||
|
||||
it('updateArticleStatus by slug', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
al.appendArticleRecord({ title: 'A', slug: 's1', mode: 'write' });
|
||||
al.appendArticleRecord({ title: 'B', slug: 's2', mode: 'write' });
|
||||
al.updateArticleStatus('s1', 'approved');
|
||||
const rows = al.readLastArticles(10);
|
||||
const a = rows.find((r) => r.slug === 's1');
|
||||
const b = rows.find((r) => r.slug === 's2');
|
||||
assert.equal(a.editorial_status, 'approved');
|
||||
assert.equal(b.editorial_status, 'pending');
|
||||
});
|
||||
|
||||
it('updateArticleStatus falls back to at when slug empty', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
al.appendArticleRecord({ title: 'No slug', slug: '', mode: 'write' });
|
||||
const rows = al.readLastArticles(1);
|
||||
const id = rows[0].at;
|
||||
assert.ok(id);
|
||||
al.updateArticleStatus(id, 'rejected');
|
||||
const again = al.readLastArticles(1);
|
||||
assert.equal(again[0].editorial_status, 'rejected');
|
||||
});
|
||||
|
||||
it('updateArticleStatus throws when id missing', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
al.appendArticleRecord({ title: 'X', slug: 'only', mode: 'write' });
|
||||
assert.throws(() => al.updateArticleStatus('nope', 'approved'), /article not found/);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user