feat: add plain-text announcements and user drawer
parent
5f5f89c68b
commit
6902215b2f
@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\AnnouncementService;
|
||||
use App\Services\Cloud\CloudAccess;
|
||||
|
||||
/** Authenticated database-only notice feed; no engine session is needed. */
|
||||
final class AnnouncementController
|
||||
{
|
||||
public function index($request, $response)
|
||||
{
|
||||
return $response->withJson(AnnouncementService::published(
|
||||
$request->getAttribute('cloud_actor') ?? CloudAccess::actor(false), $request->getQueryParams()
|
||||
))->withHeader('Cache-Control', 'private, no-store');
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Explicit cloudInit migration only. Never called by HTTP request handlers. */
|
||||
final class AnnouncementSchema
|
||||
{
|
||||
public static function upgrade($connection): void
|
||||
{
|
||||
$schema = $connection->getSchemaBuilder();
|
||||
if (!$schema->hasTable('announcement')) {
|
||||
throw new \RuntimeException('缺少 announcement 表,请先导入 web/sql/ss.sql');
|
||||
}
|
||||
$legacy = array_values(array_filter(['date', 'content', 'markdown'],
|
||||
static fn (string $column): bool => $schema->hasColumn('announcement', $column)));
|
||||
// Check before any DDL: this rollout only retires an EMPTY legacy table.
|
||||
if ($legacy !== [] && $connection->table('announcement')->exists()) {
|
||||
throw new \RuntimeException('旧公告表仍有数据,已停止升级且未修改公告表;请先备份并明确处理旧公告后重试');
|
||||
}
|
||||
$mysql = $connection->getDriverName() === 'mysql';
|
||||
$columns = ['title', 'type', 'status', 'body', 'published_at', 'updated_at'];
|
||||
foreach ($columns as $column) {
|
||||
if ($schema->hasColumn('announcement', $column)) {
|
||||
continue;
|
||||
}
|
||||
$schema->table('announcement', static function ($table) use ($column, $mysql): void {
|
||||
if ($column === 'title') {
|
||||
$field = $table->string('title', 120)->default('');
|
||||
if ($mysql) $field->charset('utf8mb4')->collation('utf8mb4_unicode_ci');
|
||||
} elseif ($column === 'type') {
|
||||
$table->string('type', 20)->default('notice');
|
||||
} elseif ($column === 'status') {
|
||||
$table->string('status', 20)->default('withdrawn');
|
||||
} elseif ($column === 'body') {
|
||||
$field = $table->longText('body');
|
||||
if ($mysql) $field->charset('utf8mb4')->collation('utf8mb4_unicode_ci');
|
||||
} elseif ($column === 'published_at') {
|
||||
$table->dateTime($column)->nullable();
|
||||
} else {
|
||||
$table->dateTime($column);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!$schema->hasIndex('announcement', 'announcement_published')) {
|
||||
$schema->table('announcement', static function ($table): void {
|
||||
$table->index(['status', 'published_at', 'id'], 'announcement_published');
|
||||
});
|
||||
}
|
||||
if ($legacy !== []) {
|
||||
$schema->table('announcement', static function ($table) use ($legacy): void {
|
||||
$table->dropColumn($legacy);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Ann;
|
||||
use App\Services\Cloud\CloudError;
|
||||
|
||||
/** Plain-text publication; only explicit status actions publish existing records. */
|
||||
final class AnnouncementService
|
||||
{
|
||||
private const TYPES = ['notice' => '通知', 'maintenance' => '维护', 'incident' => '故障'];
|
||||
private const COLUMNS = ['id', 'title', 'type', 'body', 'status', 'published_at', 'updated_at'];
|
||||
|
||||
public static function page(array $actor, array $input = []): array
|
||||
{
|
||||
self::authorize($actor);
|
||||
$filters = self::filters($input, true);
|
||||
$query = Ann::query();
|
||||
if ($filters['type'] !== 'all') {
|
||||
$query->where('type', $filters['type']);
|
||||
}
|
||||
if ($filters['status'] !== 'all') {
|
||||
$query->where('status', $filters['status']);
|
||||
}
|
||||
if ($filters['q'] !== '') {
|
||||
$pattern = '%' . str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $filters['q']) . '%';
|
||||
$query->where(static function ($query) use ($pattern): void {
|
||||
$query->whereRaw("title LIKE ? ESCAPE '!'", [$pattern])
|
||||
->orWhereRaw("body LIKE ? ESCAPE '!'", [$pattern]);
|
||||
});
|
||||
}
|
||||
return self::listing($query, $filters) + ['filters' => $filters];
|
||||
}
|
||||
|
||||
public static function published(array $actor, array $input = []): array
|
||||
{
|
||||
self::authorize($actor, false, false);
|
||||
$filters = self::filters($input, false);
|
||||
return self::listing(Ann::query()->where('status', 'published'), $filters);
|
||||
}
|
||||
|
||||
public static function detail(array $actor, string $id): array
|
||||
{
|
||||
self::authorize($actor);
|
||||
return self::dto(self::find($id));
|
||||
}
|
||||
|
||||
public static function save(array $actor, array $input, ?string $id = null): array
|
||||
{
|
||||
self::authorize($actor, true);
|
||||
$values = self::validate($input);
|
||||
return (new Ann())->getConnection()->transaction(static function () use ($id, $values): array {
|
||||
$ann = $id === null ? new Ann() : self::find($id, true);
|
||||
$now = date('Y-m-d H:i:s');
|
||||
if ($id === null) {
|
||||
$ann->published_at = null;
|
||||
} else {
|
||||
// A stale editor must not republish an announcement withdrawn by
|
||||
// another administrator. Existing status changes are explicit.
|
||||
$values['status'] = (string) $ann->status;
|
||||
}
|
||||
if ($values['status'] === 'published' && ($id === null || $ann->status !== 'published')) {
|
||||
$ann->published_at = $now;
|
||||
}
|
||||
foreach ($values as $field => $value) {
|
||||
$ann->$field = $value;
|
||||
}
|
||||
$ann->updated_at = $now;
|
||||
$ann->save();
|
||||
return self::dto($ann);
|
||||
});
|
||||
}
|
||||
|
||||
public static function setStatus(array $actor, string $id, array $input): array
|
||||
{
|
||||
self::authorize($actor, true);
|
||||
$status = self::choice($input, 'status', ['published', 'withdrawn']);
|
||||
return (new Ann())->getConnection()->transaction(static function () use ($id, $status): array {
|
||||
$ann = self::find($id, true);
|
||||
if ($ann->status !== $status) {
|
||||
if ($status === 'published' && (trim((string) $ann->title) === '' || trim((string) $ann->body) === '')) {
|
||||
throw new CloudError('请先填写公告标题和正文', 400);
|
||||
}
|
||||
$ann->status = $status;
|
||||
$ann->updated_at = date('Y-m-d H:i:s');
|
||||
if ($status === 'published') {
|
||||
$ann->published_at = $ann->updated_at;
|
||||
}
|
||||
$ann->save();
|
||||
}
|
||||
return self::dto($ann);
|
||||
});
|
||||
}
|
||||
|
||||
public static function authorize(array $actor, bool $write = false, bool $admin = true): void
|
||||
{
|
||||
if ((int) ($actor['user_id'] ?? 0) < 1) {
|
||||
throw new CloudError('请先登录', 401);
|
||||
}
|
||||
if (($admin && !($actor['is_admin'] ?? false))
|
||||
|| ($write && (!($actor['is_super_admin'] ?? false) || !($actor['can_manage'] ?? false)))) {
|
||||
throw new CloudError($write ? '只有超级管理员可以管理公告' : '需要管理员权限', 403);
|
||||
}
|
||||
}
|
||||
|
||||
private static function listing($query, array &$filters): array
|
||||
{
|
||||
$total = (clone $query)->count();
|
||||
$totalPages = max(1, (int) ceil($total / $filters['per_page']));
|
||||
$filters['page'] = min($filters['page'], $totalPages);
|
||||
$items = $query->orderByDesc('published_at')->orderByDesc('id')
|
||||
->offset(($filters['page'] - 1) * $filters['per_page'])->limit($filters['per_page'])
|
||||
->get(self::COLUMNS)->map(static fn ($row): array => self::dto($row))->all();
|
||||
return ['items' => $items, 'pagination' => ['page' => $filters['page'], 'per_page' => $filters['per_page'],
|
||||
'total' => $total, 'total_pages' => $totalPages], 'generated_at' => time()];
|
||||
}
|
||||
|
||||
private static function filters(array $input, bool $admin): array
|
||||
{
|
||||
$page = self::integer($input['page'] ?? 1, '页码', 1, 1000000);
|
||||
$perPage = self::integer($input['per_page'] ?? ($admin ? 20 : 10), '每页条数', 1, 100);
|
||||
if (!in_array($perPage, $admin ? [20, 50, 100] : [10, 20, 50], true)) {
|
||||
throw new CloudError('每页条数不受支持', 400);
|
||||
}
|
||||
if (!$admin) {
|
||||
return ['page' => $page, 'per_page' => $perPage];
|
||||
}
|
||||
return ['q' => self::text($input['q'] ?? '', '关键词', 80, false),
|
||||
'type' => self::choice($input, 'type', ['all', 'notice', 'maintenance', 'incident'], 'all'),
|
||||
'status' => self::choice($input, 'status', ['all', 'published', 'withdrawn'], 'all'),
|
||||
'page' => $page, 'per_page' => $perPage];
|
||||
}
|
||||
|
||||
private static function validate(array $input): array
|
||||
{
|
||||
return ['title' => self::text($input['title'] ?? null, '标题', 120),
|
||||
'type' => self::choice($input, 'type', array_keys(self::TYPES)),
|
||||
'body' => self::text($input['body'] ?? null, '正文', 20000),
|
||||
'status' => self::choice($input, 'status', ['published', 'withdrawn'])];
|
||||
}
|
||||
|
||||
private static function text($value, string $label, int $limit, bool $required = true): string
|
||||
{
|
||||
if (!is_string($value) || !mb_check_encoding($value, 'UTF-8')
|
||||
|| preg_match('/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/', $value)) {
|
||||
throw new CloudError($label . '格式不正确', 400);
|
||||
}
|
||||
$value = trim(str_replace(["\r\n", "\r"], "\n", $value));
|
||||
if (($required && $value === '') || mb_strlen($value, 'UTF-8') > $limit
|
||||
|| ($label === '标题' && str_contains($value, "\n"))) {
|
||||
throw new CloudError($label . '不能为空且最多 ' . $limit . ' 个字符', 400);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function choice(array $input, string $key, array $allowed, ?string $default = null): string
|
||||
{
|
||||
$value = $input[$key] ?? $default;
|
||||
if (!is_string($value) || !in_array($value, $allowed, true)) {
|
||||
throw new CloudError('公告' . ($key === 'type' ? '类型' : '状态') . '不正确', 400);
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function integer($value, string $label, int $min, int $max): int
|
||||
{
|
||||
if ((!is_int($value) && !is_string($value)) || !preg_match('/^[0-9]+$/D', (string) $value)
|
||||
|| strlen((string) $value) > 9 || (int) $value < $min || (int) $value > $max) {
|
||||
throw new CloudError($label . '不正确', 400);
|
||||
}
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
private static function find(string $id, bool $lock = false): Ann
|
||||
{
|
||||
if (!preg_match('/^[1-9][0-9]{0,9}$/D', $id) || (int) $id > 2147483647) {
|
||||
throw new CloudError('公告编号不正确', 400);
|
||||
}
|
||||
$query = Ann::query()->where('id', $id);
|
||||
if ($lock) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
$ann = $query->first(self::COLUMNS);
|
||||
if ($ann === null) {
|
||||
throw new CloudError('公告不存在', 404);
|
||||
}
|
||||
return $ann;
|
||||
}
|
||||
|
||||
private static function dto(Ann $ann): array
|
||||
{
|
||||
$type = (string) $ann->type;
|
||||
return ['id' => (string) $ann->id, 'title' => (string) $ann->title,
|
||||
'type' => $type, 'type_label' => self::TYPES[$type] ?? '通知', 'body' => (string) $ann->body,
|
||||
'status' => (string) $ann->status,
|
||||
'published_at' => $ann->published_at === null ? null : (string) $ann->published_at,
|
||||
'updated_at' => (string) $ann->updated_at];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,194 @@
|
||||
// User announcements are independent of the VM session and engine bootstrap.
|
||||
const dialog = document.getElementById('panel-announcements-drawer');
|
||||
const byId = id => document.getElementById(id);
|
||||
const state = {
|
||||
items: [], pagination: null, request: null, serial: 0, loading: false,
|
||||
stale: false, receivedAt: '', opener: null, scroll: null,
|
||||
};
|
||||
|
||||
function element(tag, className = '', value) {
|
||||
const node = document.createElement(tag);
|
||||
node.className = className;
|
||||
if (value !== undefined) node.textContent = String(value);
|
||||
return node;
|
||||
}
|
||||
|
||||
function setMessage(message, tone = '') {
|
||||
const node = byId('panel-announcements-state');
|
||||
node.textContent = message;
|
||||
node.className = `panel-announcements-state${tone ? ` is-${tone}` : ''}`;
|
||||
node.setAttribute('role', tone === 'error' ? 'alert' : 'status');
|
||||
}
|
||||
|
||||
function dateText(value) {
|
||||
// The API supplies the publication time in the site's timezone. Do not parse
|
||||
// an unzoned SQL date as UTC or substitute a browser-generated publication time.
|
||||
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value) ? value : '时间未记录';
|
||||
}
|
||||
|
||||
function renderItems() {
|
||||
const list = byId('panel-announcements-list');
|
||||
list.replaceChildren();
|
||||
for (const item of state.items) {
|
||||
const article = element('article', 'panel-announcements-item');
|
||||
article.dataset.announcementId = String(item.id);
|
||||
const meta = element('div', 'panel-announcements-meta');
|
||||
const type = ['notice', 'maintenance', 'incident'].includes(item.type) ? item.type : 'notice';
|
||||
const fallback = { notice: '通知', maintenance: '维护', incident: '故障' }[type];
|
||||
meta.append(element('span', `panel-announcements-type is-${type}`, item.type_label || fallback));
|
||||
const published = element('time', '', `发布于 ${dateText(item.published_at)}`);
|
||||
if (dateText(item.published_at) !== '时间未记录') published.dateTime = item.published_at.replace(' ', 'T');
|
||||
meta.append(published);
|
||||
if (item.updated_at && item.updated_at !== item.published_at) {
|
||||
meta.append(element('span', '', `更新于 ${dateText(item.updated_at)}`));
|
||||
}
|
||||
article.append(meta, element('h3', '', item.title || '站点公告'), element('p', 'panel-announcements-body', item.body ?? ''));
|
||||
list.append(article);
|
||||
}
|
||||
if (!state.items.length) list.append(element('p', 'panel-announcements-empty', '暂无已发布的公告。'));
|
||||
}
|
||||
|
||||
function renderControls() {
|
||||
byId('panel-announcements-refresh').disabled = state.loading;
|
||||
const more = byId('panel-announcements-more');
|
||||
more.hidden = !state.pagination || state.pagination.page >= state.pagination.total_pages;
|
||||
more.disabled = state.loading || state.stale;
|
||||
byId('panel-announcements-count').textContent = state.pagination
|
||||
? `已加载 ${state.items.length} / ${state.pagination.total} 条${state.stale ? '(旧内容)' : ''}` : '';
|
||||
byId('panel-announcements-list').setAttribute('aria-busy', String(state.loading));
|
||||
}
|
||||
|
||||
async function requestPage(page, controller) {
|
||||
const timeout = setTimeout(() => controller.abort('timeout'), 15000);
|
||||
try {
|
||||
const response = await fetch(`/api/v1/announcements?page=${page}&per_page=10`, {
|
||||
headers: { Accept: 'application/json' }, credentials: 'same-origin',
|
||||
cache: 'no-store', signal: controller.signal,
|
||||
});
|
||||
if (response.status === 401) throw new Error('登录已过期,请重新登录后查看公告。');
|
||||
if (response.status === 403) throw new Error('当前账号无法读取公告。');
|
||||
let payload;
|
||||
try { payload = await response.json(); }
|
||||
catch { throw new Error('公告服务返回异常,请稍后重试。'); }
|
||||
if (!response.ok || payload?.ret === 0) {
|
||||
throw new Error(typeof payload?.detail === 'string' ? payload.detail : `公告读取失败 (${response.status})。`);
|
||||
}
|
||||
const pagination = payload?.pagination;
|
||||
if (!Array.isArray(payload?.items) || !pagination
|
||||
|| ![pagination.page, pagination.per_page, pagination.total, pagination.total_pages].every(Number.isInteger)
|
||||
|| pagination.page < 1 || pagination.per_page !== 10 || pagination.total < 0 || pagination.total_pages < 1) {
|
||||
throw new Error('公告数据格式无效,请稍后重试。');
|
||||
}
|
||||
return payload;
|
||||
} catch (error) {
|
||||
if (controller.signal.reason === 'timeout') throw new Error('公告读取超时,请稍后重试。');
|
||||
throw error;
|
||||
} finally { clearTimeout(timeout); }
|
||||
}
|
||||
|
||||
async function load(page = 1) {
|
||||
if (!dialog?.open) return;
|
||||
if (page !== 1 && (state.loading || state.stale || !state.pagination)) return;
|
||||
state.request?.abort();
|
||||
const controller = new AbortController(); state.request = controller;
|
||||
const serial = ++state.serial;
|
||||
state.loading = true;
|
||||
if (page === 1 && state.pagination) state.stale = true;
|
||||
setMessage(page === 1
|
||||
? (state.pagination ? `正在刷新;下方暂显示 ${state.receivedAt} 读取的旧内容。` : '正在读取最新公告…')
|
||||
: '正在加载更多公告…', state.stale ? 'stale' : '');
|
||||
renderControls();
|
||||
try {
|
||||
const payload = await requestPage(page, controller);
|
||||
if (controller.signal.aborted || serial !== state.serial || !dialog.open) return;
|
||||
const published = payload.items.filter(item => item && item.status === 'published');
|
||||
// Offset pagination can repeat an item if a new notice is published between
|
||||
// requests. Keep one record per ID without changing server publication order.
|
||||
const replaces = page === 1 || payload.pagination.page === 1;
|
||||
const combined = replaces ? published : [...state.items, ...published];
|
||||
const seen = new Set();
|
||||
state.items = combined.filter(item => {
|
||||
const id = String(item.id);
|
||||
if (seen.has(id)) return false;
|
||||
seen.add(id); return true;
|
||||
});
|
||||
state.pagination = payload.pagination; state.stale = false;
|
||||
state.receivedAt = new Date().toLocaleTimeString('zh-CN', { hour12: false });
|
||||
renderItems();
|
||||
setMessage(`读取于 ${state.receivedAt};按发布时间倒序显示。`);
|
||||
if (replaces) byId('panel-announcements-scroll').scrollTop = 0;
|
||||
} catch (error) {
|
||||
if (serial !== state.serial || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
|
||||
state.stale = Boolean(state.pagination);
|
||||
setMessage(`${error.message}${state.pagination ? ` 下方保留 ${state.receivedAt} 读取的旧内容,请刷新确认最新公告。` : ''}`, 'error');
|
||||
} finally {
|
||||
if (serial === state.serial) { state.request = null; state.loading = false; renderControls(); }
|
||||
}
|
||||
}
|
||||
|
||||
function historyData(changes = {}) {
|
||||
return { ...(history.state && typeof history.state === 'object' ? history.state : {}), ...changes };
|
||||
}
|
||||
|
||||
function close() {
|
||||
state.request?.abort(); state.request = null; state.serial += 1; state.loading = false;
|
||||
if (dialog.open) dialog.close();
|
||||
document.documentElement.classList.remove('panel-announcements-open');
|
||||
document.body.style.removeProperty('--panel-announcements-scroll-top');
|
||||
if (state.scroll) { window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' }); state.scroll = null; }
|
||||
document.querySelectorAll('[data-announcements-open]').forEach(button => button.setAttribute('aria-expanded', 'false'));
|
||||
if (state.opener?.isConnected) state.opener.focus({ preventScroll: true });
|
||||
state.opener = null;
|
||||
if (history.state?.panelAnnouncementsScroll) history.replaceState(historyData({ panelAnnouncementsScroll: undefined }), '', location.href);
|
||||
renderControls();
|
||||
}
|
||||
|
||||
function open(opener) {
|
||||
if (dialog.open) return;
|
||||
state.opener = opener || document.querySelector('[data-announcements-open]');
|
||||
state.scroll = { x: window.scrollX, y: window.scrollY };
|
||||
document.body.style.setProperty('--panel-announcements-scroll-top', `${-state.scroll.y}px`);
|
||||
document.documentElement.classList.add('panel-announcements-open');
|
||||
dialog.showModal();
|
||||
byId('panel-announcements-close').focus({ preventScroll: true });
|
||||
document.querySelectorAll('[data-announcements-open]').forEach(button => button.setAttribute('aria-expanded', 'true'));
|
||||
// Always refresh page one on reopening: a previously published notice may
|
||||
// have been withdrawn. Do not treat the old in-memory list as current data.
|
||||
void load(1);
|
||||
}
|
||||
|
||||
if (dialog) {
|
||||
document.addEventListener('click', event => {
|
||||
const trigger = event.target.closest('[data-announcements-open]');
|
||||
if (!trigger || event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||
event.preventDefault(); open(trigger);
|
||||
});
|
||||
byId('panel-announcements-close').addEventListener('click', close);
|
||||
byId('panel-announcements-refresh').addEventListener('click', () => { void load(1); });
|
||||
byId('panel-announcements-more').addEventListener('click', () => { void load(state.pagination.page + 1); });
|
||||
dialog.addEventListener('cancel', event => { event.preventDefault(); close(); });
|
||||
dialog.addEventListener('click', event => {
|
||||
if (event.target !== dialog) return;
|
||||
const rect = dialog.getBoundingClientRect();
|
||||
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) close();
|
||||
});
|
||||
window.addEventListener('popstate', () => { if (dialog.open) close(); });
|
||||
window.addEventListener('pagehide', () => {
|
||||
state.request?.abort(); state.serial += 1; state.loading = false;
|
||||
if (state.scroll) history.replaceState(historyData({ panelAnnouncementsScroll: state.scroll }), '', location.href);
|
||||
});
|
||||
window.addEventListener('pageshow', event => { if (event.persisted && dialog.open) close(); });
|
||||
const stored = history.state?.panelAnnouncementsScroll;
|
||||
if (stored && Number.isFinite(stored.x) && Number.isFinite(stored.y)) {
|
||||
requestAnimationFrame(() => {
|
||||
window.scrollTo({ left: stored.x, top: stored.y, behavior: 'instant' });
|
||||
history.replaceState(historyData({ panelAnnouncementsScroll: undefined }), '', location.href);
|
||||
});
|
||||
}
|
||||
const url = new URL(location.href);
|
||||
if (url.searchParams.get('announcements') === '1') {
|
||||
url.searchParams.delete('announcements');
|
||||
history.replaceState(historyData(), '', url);
|
||||
open();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,172 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var root = document.querySelector('[data-admin-announcements]');
|
||||
if (!root) return;
|
||||
var canManage = window.ADMIN_CAN_MANAGE === true && root.dataset.annCanManage === '1';
|
||||
var form = document.getElementById('announcement-form');
|
||||
var feedback = document.getElementById('announcement-feedback');
|
||||
var busy = false;
|
||||
var unconfirmed = false;
|
||||
var controller = null;
|
||||
var leaving = false;
|
||||
|
||||
function inform(message, state) {
|
||||
if (!feedback) return;
|
||||
feedback.textContent = message;
|
||||
feedback.className = 'admin-config-status' + (state ? ' is-' + state : '');
|
||||
}
|
||||
|
||||
function controls() {
|
||||
var locked = !canManage || busy || unconfirmed;
|
||||
root.querySelectorAll('[data-ann-write], [data-ann-status-button]').forEach(function (button) {
|
||||
button.disabled = locked;
|
||||
});
|
||||
if (form) {
|
||||
form.elements.namedItem('title').readOnly = locked;
|
||||
form.elements.namedItem('body').readOnly = locked;
|
||||
form.elements.namedItem('type').disabled = locked;
|
||||
}
|
||||
}
|
||||
|
||||
function formValue() {
|
||||
if (!form) return '';
|
||||
return JSON.stringify(['title', 'type', 'body'].map(function (name) {
|
||||
return form.elements.namedItem(name).value;
|
||||
}));
|
||||
}
|
||||
|
||||
var savedValue = formValue();
|
||||
|
||||
function countCharacters() {
|
||||
root.querySelectorAll('[data-ann-counter]').forEach(function (field) {
|
||||
var counter = document.getElementById(field.dataset.annCounter);
|
||||
if (counter) counter.textContent = field.value.length + ' / ' + field.maxLength + ' 字';
|
||||
});
|
||||
}
|
||||
|
||||
function uncertainResult() {
|
||||
unconfirmed = true;
|
||||
inform('请求结果未确认,请刷新页面核对后再操作;不要重复提交。', 'error');
|
||||
}
|
||||
|
||||
async function write(url, method, payload) {
|
||||
// admin-csrf.js adds the existing X-Admin-CSRF-Token header.
|
||||
controller = new AbortController();
|
||||
var timeout = window.setTimeout(function () { controller.abort(); }, 30000);
|
||||
try {
|
||||
var response = await window.fetch(url, {
|
||||
method: method,
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
},
|
||||
body: payload,
|
||||
signal: controller.signal
|
||||
});
|
||||
var result = await response.json();
|
||||
if (!response.ok || !result || result.ret !== 1) {
|
||||
if (response.status >= 500 || !result || result.ret !== 0) {
|
||||
uncertainResult();
|
||||
} else {
|
||||
inform(typeof result.msg === 'string' ? result.msg : '操作未完成,请检查输入与权限。', 'error');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!result.announcement || !/^[1-9][0-9]*$/.test(String(result.announcement.id))
|
||||
|| ['published', 'withdrawn'].indexOf(result.announcement.status) === -1) {
|
||||
uncertainResult();
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
} catch (error) {
|
||||
uncertainResult();
|
||||
return null;
|
||||
} finally {
|
||||
window.clearTimeout(timeout);
|
||||
controller = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (form) {
|
||||
form.addEventListener('input', function () {
|
||||
countCharacters();
|
||||
if (canManage && !busy && !unconfirmed) inform(formValue() === savedValue ? '尚未修改' : '有未保存的修改');
|
||||
});
|
||||
form.addEventListener('change', function () {
|
||||
if (canManage && !busy && !unconfirmed) inform(formValue() === savedValue ? '尚未修改' : '有未保存的修改');
|
||||
});
|
||||
form.addEventListener('submit', async function (event) {
|
||||
event.preventDefault();
|
||||
if (!canManage || busy || unconfirmed || !form.reportValidity()) return;
|
||||
var title = form.elements.namedItem('title').value;
|
||||
var body = form.elements.namedItem('body').value;
|
||||
if (!title.trim() || !body.trim()) {
|
||||
inform('标题和正文不能为空或只有空格。', 'error');
|
||||
return;
|
||||
}
|
||||
var payload = new URLSearchParams();
|
||||
payload.set('title', title);
|
||||
payload.set('type', form.elements.namedItem('type').value);
|
||||
payload.set('body', body);
|
||||
payload.set('status', form.elements.namedItem('status').value);
|
||||
busy = true;
|
||||
controls();
|
||||
inform('正在保存…');
|
||||
var result = await write(form.getAttribute('action'), form.dataset.method, payload);
|
||||
if (result && !leaving) {
|
||||
savedValue = formValue();
|
||||
inform(result.msg || '公告已保存', 'success');
|
||||
window.location.assign('/admin/announcement');
|
||||
return;
|
||||
}
|
||||
busy = false;
|
||||
controls();
|
||||
});
|
||||
}
|
||||
|
||||
root.addEventListener('click', async function (event) {
|
||||
var button = event.target.closest('[data-ann-status-button]');
|
||||
if (!button || !root.contains(button)) return;
|
||||
event.preventDefault();
|
||||
if (!canManage || busy || unconfirmed || button.disabled) return;
|
||||
var id = button.dataset.annId;
|
||||
var next = button.dataset.annNextStatus;
|
||||
if (!/^[1-9][0-9]*$/.test(id) || ['published', 'withdrawn'].indexOf(next) === -1) return;
|
||||
if (form && formValue() !== savedValue) {
|
||||
inform('请先保存修改,再发布或撤下公告。', 'error');
|
||||
return;
|
||||
}
|
||||
var prompt = next === 'published' ? '确认发布此公告?发布后用户可见。'
|
||||
: '确认撤下此公告?用户将不再看到它,后台仍保留内容。';
|
||||
if (!window.confirm(prompt)) return;
|
||||
busy = true;
|
||||
controls();
|
||||
inform(next === 'published' ? '正在发布…' : '正在撤下…');
|
||||
var payload = new URLSearchParams();
|
||||
payload.set('status', next);
|
||||
var result = await write('/admin/announcement/' + id + '/status', 'POST', payload);
|
||||
if (result && !leaving) {
|
||||
inform(result.msg || '公告状态已更新', 'success');
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
busy = false;
|
||||
controls();
|
||||
});
|
||||
|
||||
window.addEventListener('pagehide', function () {
|
||||
leaving = true;
|
||||
if (controller) controller.abort();
|
||||
});
|
||||
window.addEventListener('pageshow', function (event) {
|
||||
leaving = false;
|
||||
if (event.persisted && busy) uncertainResult();
|
||||
controls();
|
||||
countCharacters();
|
||||
});
|
||||
countCharacters();
|
||||
controls();
|
||||
})();
|
||||
@ -1,116 +1,6 @@
|
||||
{assign var=admin_title value='添加公告'}
|
||||
{assign var=admin_title value='发布公告'}
|
||||
{assign var=admin_active value='announcement'}
|
||||
{assign var=admin_extra_css value='<link rel="stylesheet" href="/theme/venix/editor/css/editormd.min.css" />'}
|
||||
{assign var=announcement_mode value='create'}
|
||||
{include file='admin/static_header.tpl'}
|
||||
|
||||
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column">
|
||||
<div class="flex-grow-1">
|
||||
<h4 class="fs-20 fw-semibold mb-1">添加公告</h4>
|
||||
<p class="text-muted mb-0">使用 Markdown 编写公告,提交后会同步通知。</p>
|
||||
</div>
|
||||
<div class="text-sm-end mt-3 mt-sm-0">
|
||||
<a class="btn btn-light" href="/admin/announcement"><i class="mdi mdi-arrow-left me-1"></i>返回列表</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">公告内容</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="editormd" class="admin-editor">
|
||||
<textarea style="display:none;" id="content"></textarea>
|
||||
</div>
|
||||
<div class="admin-form-actions">
|
||||
<button id="submit" type="button" class="btn btn-primary">
|
||||
<i class="mdi mdi-content-save-outline me-1"></i>添加公告
|
||||
</button>
|
||||
<a class="btn btn-light" href="/admin/announcement">取消</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-toast" id="annToast"></div>
|
||||
|
||||
<script src="/theme/venix/js/jquery.js?v={$venix_asset_version}"></script>
|
||||
<script>
|
||||
window.__venixDefine = window.define;
|
||||
window.define = undefined;
|
||||
</script>
|
||||
<script src="/theme/venix/editor/editormd.min.js?v={$venix_asset_version}"></script>
|
||||
<script>
|
||||
window.define = window.__venixDefine;
|
||||
</script>
|
||||
{literal}
|
||||
<script>
|
||||
(function () {
|
||||
var editor = null;
|
||||
var submit = document.getElementById('submit');
|
||||
var toast = document.getElementById('annToast');
|
||||
|
||||
function showToast(text, type) {
|
||||
toast.textContent = text;
|
||||
toast.className = 'admin-toast is-show ' + (type || '');
|
||||
window.setTimeout(function () {
|
||||
toast.className = 'admin-toast';
|
||||
}, 2200);
|
||||
}
|
||||
|
||||
function initEditor() {
|
||||
if (!window.jQuery || !window.editormd) {
|
||||
showToast('编辑器资源加载失败,请刷新页面', 'is-error');
|
||||
return;
|
||||
}
|
||||
|
||||
editor = editormd('editormd', {
|
||||
path: '/theme/venix/editor/lib/',
|
||||
width: '100%',
|
||||
height: 720,
|
||||
saveHTMLToTextarea: true
|
||||
});
|
||||
}
|
||||
|
||||
$(function () {
|
||||
initEditor();
|
||||
|
||||
$('#submit').on('click', function () {
|
||||
if (!editor || typeof editor.getHTML !== 'function' || typeof editor.getMarkdown !== 'function') {
|
||||
showToast('编辑器未加载完成,请稍后再试', 'is-error');
|
||||
return;
|
||||
}
|
||||
|
||||
submit.disabled = true;
|
||||
$.ajax({
|
||||
type: 'POST',
|
||||
url: '/admin/announcement',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
content: editor.getHTML(),
|
||||
markdown: editor.getMarkdown()
|
||||
},
|
||||
success: function (data) {
|
||||
showToast(data.msg || '操作完成', data.ret ? 'is-success' : 'is-error');
|
||||
if (data.ret) {
|
||||
window.setTimeout(function () {
|
||||
location.href = '/admin/announcement';
|
||||
}, 800);
|
||||
}
|
||||
},
|
||||
error: function (jqXHR) {
|
||||
showToast('发生错误:' + jqXHR.status, 'is-error');
|
||||
},
|
||||
complete: function () {
|
||||
submit.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener('pageshow', function () {
|
||||
submit.disabled = false;
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{/literal}
|
||||
|
||||
{include file='admin/announcement/form.tpl'}
|
||||
{include file='admin/static_footer.tpl'}
|
||||
|
||||
@ -1,117 +1,6 @@
|
||||
{assign var=admin_title value='编辑公告'}
|
||||
{assign var=admin_active value='announcement'}
|
||||
{assign var=admin_extra_css value='<link rel="stylesheet" href="/theme/venix/editor/css/editormd.min.css" />'}
|
||||
{assign var=announcement_mode value='edit'}
|
||||
{include file='admin/static_header.tpl'}
|
||||
|
||||
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column">
|
||||
<div class="flex-grow-1">
|
||||
<h4 class="fs-20 fw-semibold mb-1">编辑公告 #{$ann->id}</h4>
|
||||
<p class="text-muted mb-0">修改公告后会重新推送更新通知。</p>
|
||||
</div>
|
||||
<div class="text-sm-end mt-3 mt-sm-0">
|
||||
<a class="btn btn-light" href="/admin/announcement"><i class="mdi mdi-arrow-left me-1"></i>返回列表</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">公告内容</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div id="editormd" class="admin-editor">
|
||||
<textarea style="display:none;" id="content">{$ann->markdown|escape:'html'}</textarea>
|
||||
</div>
|
||||
<div class="admin-form-actions">
|
||||
<button id="submit" type="button" class="btn btn-primary">
|
||||
<i class="mdi mdi-content-save-outline me-1"></i>保存修改
|
||||
</button>
|
||||
<a class="btn btn-light" href="/admin/announcement">取消</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-toast" id="annToast"></div>
|
||||
|
||||
<script src="/theme/venix/js/jquery.js?v={$venix_asset_version}"></script>
|
||||
<script>
|
||||
window.__venixDefine = window.define;
|
||||
window.define = undefined;
|
||||
</script>
|
||||
<script src="/theme/venix/editor/editormd.min.js?v={$venix_asset_version}"></script>
|
||||
<script>
|
||||
window.define = window.__venixDefine;
|
||||
var announcementUrl = '/admin/announcement/{$ann->id}';
|
||||
</script>
|
||||
{literal}
|
||||
<script>
|
||||
(function () {
|
||||
var editor = null;
|
||||
var submit = document.getElementById('submit');
|
||||
var toast = document.getElementById('annToast');
|
||||
|
||||
function showToast(text, type) {
|
||||
toast.textContent = text;
|
||||
toast.className = 'admin-toast is-show ' + (type || '');
|
||||
window.setTimeout(function () {
|
||||
toast.className = 'admin-toast';
|
||||
}, 2200);
|
||||
}
|
||||
|
||||
function initEditor() {
|
||||
if (!window.jQuery || !window.editormd) {
|
||||
showToast('编辑器资源加载失败,请刷新页面', 'is-error');
|
||||
return;
|
||||
}
|
||||
|
||||
editor = editormd('editormd', {
|
||||
path: '/theme/venix/editor/lib/',
|
||||
width: '100%',
|
||||
height: 720,
|
||||
saveHTMLToTextarea: true
|
||||
});
|
||||
}
|
||||
|
||||
$(function () {
|
||||
initEditor();
|
||||
|
||||
$('#submit').on('click', function () {
|
||||
if (!editor || typeof editor.getHTML !== 'function' || typeof editor.getMarkdown !== 'function') {
|
||||
showToast('编辑器未加载完成,请稍后再试', 'is-error');
|
||||
return;
|
||||
}
|
||||
|
||||
submit.disabled = true;
|
||||
$.ajax({
|
||||
type: 'PUT',
|
||||
url: announcementUrl,
|
||||
dataType: 'json',
|
||||
data: {
|
||||
content: editor.getHTML(),
|
||||
markdown: editor.getMarkdown()
|
||||
},
|
||||
success: function (data) {
|
||||
showToast(data.msg || '操作完成', data.ret ? 'is-success' : 'is-error');
|
||||
if (data.ret) {
|
||||
window.setTimeout(function () {
|
||||
location.href = '/admin/announcement';
|
||||
}, 800);
|
||||
}
|
||||
},
|
||||
error: function (jqXHR) {
|
||||
showToast('发生错误:' + jqXHR.status, 'is-error');
|
||||
},
|
||||
complete: function () {
|
||||
submit.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener('pageshow', function () {
|
||||
submit.disabled = false;
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{/literal}
|
||||
|
||||
{include file='admin/announcement/form.tpl'}
|
||||
{include file='admin/static_footer.tpl'}
|
||||
|
||||
@ -0,0 +1,53 @@
|
||||
{assign var=ann_can_manage value=$admin_can_manage|default:false}
|
||||
{if isset($announcement_can_manage) && !$announcement_can_manage}{assign var=ann_can_manage value=false}{/if}
|
||||
{assign var=ann_is_create value=($announcement_mode == 'create')}
|
||||
{assign var=ann_types value=['notice'=>'通知','maintenance'=>'维护','incident'=>'故障']}
|
||||
<main data-admin-announcements data-ann-can-manage="{if $ann_can_manage}1{else}0{/if}">
|
||||
<div class="py-3 d-flex align-items-xl-center flex-xl-row flex-column gap-3">
|
||||
<div class="flex-grow-1">
|
||||
<h1 class="fs-20 fw-semibold mb-1">{if $ann_is_create}发布公告{else}编辑公告{/if}</h1>
|
||||
<p class="text-muted mb-0">{if $ann_is_create}填写标题与正文,发布后将在用户公告中显示。{else}正文按纯文本显示;保存修改不会改变当前发布状态。{/if}</p>
|
||||
</div>
|
||||
<div class="admin-config-actions flex-shrink-0">
|
||||
<span class="admin-config-status" id="announcement-feedback" role="status" aria-live="polite">{if !$ann_can_manage}只读模式{else}尚未修改{/if}</span>
|
||||
<a class="btn btn-light" href="/admin/announcement">返回公告列表</a>
|
||||
{if !$ann_is_create}
|
||||
<button class="btn btn-light" type="button" data-ann-status-button data-ann-id="{$announcement.id|escape}" data-ann-next-status="{if $announcement.status == 'published'}withdrawn{else}published{/if}" {if !$ann_can_manage}disabled{/if}>{if $announcement.status == 'published'}撤下公告{else}发布公告{/if}</button>
|
||||
{/if}
|
||||
<button class="btn btn-primary" id="announcement-submit" type="submit" form="announcement-form" data-ann-write {if !$ann_can_manage}disabled{/if}>{if $ann_is_create}发布公告{else}保存修改{/if}</button>
|
||||
</div>
|
||||
</div>
|
||||
{if !$ann_can_manage}<p class="alert alert-light border">当前为只读模式,仅超级管理员可以发布、修改或撤下公告。</p>{/if}
|
||||
<form class="card" id="announcement-form" method="post" action="/admin/announcement{if !$ann_is_create}/{$announcement.id|escape}{/if}" data-method="{if $ann_is_create}POST{else}PUT{/if}" data-ann-id="{if !$ann_is_create}{$announcement.id|escape}{/if}">
|
||||
<div class="card-body">
|
||||
{if !$ann_is_create}
|
||||
<div class="d-flex flex-wrap align-items-center gap-3 mb-4 text-muted fs-13">
|
||||
<span>公告 #{$announcement.id|escape}</span>
|
||||
<span class="badge {if $announcement.status == 'published'}text-bg-success{else}text-bg-light{/if}" id="announcement-current-status">{if $announcement.status == 'published'}已发布{else}已撤下{/if}</span>
|
||||
<span>发布时间:<span id="announcement-published-at">{$announcement.published_at|default:'未发布'|escape}</span></span>
|
||||
<span>最近更新:<span id="announcement-updated-at">{$announcement.updated_at|default:'—'|escape}</span></span>
|
||||
</div>
|
||||
{/if}
|
||||
<input type="hidden" name="status" id="announcement-status" value="{if $ann_is_create}published{else}{$announcement.status|escape}{/if}">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-8">
|
||||
<div class="d-flex align-items-center justify-content-between gap-2"><label class="form-label" for="announcement-title">公告标题</label><span class="text-muted fs-12" id="announcement-title-count">最多 120 字</span></div>
|
||||
<input class="form-control" id="announcement-title" name="title" type="text" maxlength="120" required value="{$announcement.title|default:''|escape}" aria-describedby="announcement-title-count" data-ann-counter="announcement-title-count" {if !$ann_can_manage}readonly{/if}>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" for="announcement-type">公告类型</label>
|
||||
<select class="form-select" id="announcement-type" name="type" required {if !$ann_can_manage}disabled{/if}>
|
||||
{foreach $ann_types as $value=>$label}<option value="{$value}" {if $announcement.type|default:'notice' == $value}selected{/if}>{$label}</option>{/foreach}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="d-flex align-items-center justify-content-between gap-2"><label class="form-label" for="announcement-body">公告正文</label><span class="text-muted fs-12" id="announcement-body-count">最多 20000 字</span></div>
|
||||
<textarea class="form-control" id="announcement-body" name="body" rows="14" maxlength="20000" required aria-describedby="announcement-body-help announcement-body-count" data-ann-counter="announcement-body-count" {if !$ann_can_manage}readonly{/if}>{$announcement.body|default:''|escape}</textarea>
|
||||
<p class="form-text mb-0" id="announcement-body-help">仅保存纯文本,保留换行。撤下后用户不可见,内容仍保留在后台。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<noscript><p class="alert alert-info">请启用 JavaScript 后再保存或切换公告状态。</p></noscript>
|
||||
</main>
|
||||
<script src="/theme/venix/js/admin-announcements.js?v={$venix_asset_version}" defer></script>
|
||||
@ -1,291 +1,66 @@
|
||||
{assign var=admin_title value='公告管理'}
|
||||
{assign var=admin_active value='announcement'}
|
||||
{include file='admin/static_header.tpl'}
|
||||
|
||||
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column">
|
||||
<div class="flex-grow-1">
|
||||
<h4 class="fs-20 fw-semibold mb-1">公告管理</h4>
|
||||
<p class="text-muted mb-0">管理用户中心展示的系统公告,支持编辑、删除和快速搜索。</p>
|
||||
</div>
|
||||
<div class="text-sm-end mt-3 mt-sm-0">
|
||||
<a class="btn btn-primary" href="/admin/announcement/create">
|
||||
<i class="mdi mdi-plus-circle-outline me-1"></i>新增公告
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-xl-8">
|
||||
<div class="card h-100">
|
||||
<div class="card-header d-flex align-items-center justify-content-between">
|
||||
<div>
|
||||
<h5 class="card-title mb-0">公告列表</h5>
|
||||
<span class="text-muted fs-13">数据来自原有公告接口</span>
|
||||
</div>
|
||||
<span class="badge text-bg-light" id="annTotal">读取中</span>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="admin-ann-toolbar">
|
||||
<div class="position-relative flex-grow-1">
|
||||
<i class="mdi mdi-magnify admin-ann-search-icon"></i>
|
||||
<input id="annSearch" class="form-control admin-ann-search" type="text" placeholder="搜索公告内容或 ID">
|
||||
</div>
|
||||
<button id="annReload" class="btn btn-light" type="button">
|
||||
<i class="mdi mdi-refresh me-1"></i>刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive mt-3">
|
||||
<table class="table table-hover align-middle mb-0 admin-ann-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 90px;">ID</th>
|
||||
<th style="width: 190px;">时间</th>
|
||||
<th>内容</th>
|
||||
<th style="width: 160px;" class="text-end">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="annRows">
|
||||
<tr>
|
||||
<td colspan="4" class="text-center text-muted py-4">公告加载中</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{assign var=ann_can_manage value=$admin_can_manage|default:false}
|
||||
{if isset($announcement_can_manage) && !$announcement_can_manage}{assign var=ann_can_manage value=false}{/if}
|
||||
{assign var=ann_filters value=$announcements_page.filters|default:[]}
|
||||
{assign var=ann_types value=['notice'=>'通知','maintenance'=>'维护','incident'=>'故障']}
|
||||
<main data-admin-announcements data-ann-can-manage="{if $ann_can_manage}1{else}0{/if}">
|
||||
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column gap-3">
|
||||
<div class="flex-grow-1"><h1 class="fs-20 fw-semibold mb-1">公告管理</h1><p class="text-muted mb-0">发布通知、维护与故障公告;撤下后保留记录,不再向用户展示。</p></div>
|
||||
<div class="admin-config-actions flex-shrink-0">
|
||||
<span class="admin-config-status {if $announcements_error|default:''}is-error{/if}" id="announcement-feedback" role="status" aria-live="polite">{if $announcements_error|default:''}{$announcements_error|escape}{elseif !$ann_can_manage}只读模式{else}仅已发布的公告对用户可见{/if}</span>
|
||||
{if $ann_can_manage}<a class="btn btn-primary" href="/admin/announcement/create"><i class="mdi mdi-plus me-1" aria-hidden="true"></i>发布公告</a>{else}<button class="btn btn-primary" type="button" disabled>发布公告</button>{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-4">
|
||||
<div class="card h-100">
|
||||
<div class="card-header">
|
||||
<h5 class="card-title mb-0">操作说明</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="admin-ann-guide">
|
||||
<div>
|
||||
<i class="mdi mdi-bullhorn-outline"></i>
|
||||
<span>公告内容会展示在用户中心公告页面。</span>
|
||||
</div>
|
||||
<div>
|
||||
<i class="mdi mdi-language-markdown-outline"></i>
|
||||
<span>新增和编辑页面支持 Markdown 编辑器。</span>
|
||||
</div>
|
||||
<div>
|
||||
<i class="mdi mdi-delete-outline"></i>
|
||||
<span>删除前会二次确认,避免误删。</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<section class="card mb-3" aria-labelledby="announcement-filter-title">
|
||||
<div class="card-header"><h2 class="h5 card-title mb-0" id="announcement-filter-title">查找公告</h2></div>
|
||||
<div class="card-body">
|
||||
<form class="row g-2 align-items-end" method="get" action="/admin/announcement" id="announcement-filter">
|
||||
<div class="col-lg-5"><label class="form-label" for="announcement-query">关键词</label><input class="form-control" type="search" id="announcement-query" name="q" maxlength="80" value="{$ann_filters.q|default:''|escape}" placeholder="搜索标题或正文"></div>
|
||||
<div class="col-lg-2 col-6"><label class="form-label" for="announcement-filter-type">公告类型</label><select class="form-select" name="type" id="announcement-filter-type"><option value="all" {if $ann_filters.type|default:'all' == 'all'}selected{/if}>全部类型</option>{foreach $ann_types as $value=>$label}<option value="{$value}" {if $ann_filters.type|default:'all' == $value}selected{/if}>{$label}</option>{/foreach}</select></div>
|
||||
<div class="col-lg-2 col-6"><label class="form-label" for="announcement-filter-status">发布状态</label><select class="form-select" name="status" id="announcement-filter-status"><option value="all" {if $ann_filters.status|default:'all' == 'all'}selected{/if}>全部状态</option><option value="published" {if $ann_filters.status|default:'all' == 'published'}selected{/if}>已发布</option><option value="withdrawn" {if $ann_filters.status|default:'all' == 'withdrawn'}selected{/if}>已撤下</option></select></div>
|
||||
<div class="col-lg-3 col-12"><label class="form-label" for="announcement-per-page">每页显示</label><select class="form-select" name="per_page" id="announcement-per-page">{foreach [20,50,100] as $size}<option value="{$size}" {if $announcements_page.pagination.per_page|default:20 == $size}selected{/if}>{$size} 条</option>{/foreach}</select></div>
|
||||
<div class="col-12 admin-form-actions mt-3"><a class="btn btn-light" href="/admin/announcement">重置筛选</a><button class="btn btn-primary" type="submit">查询公告</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-modal" id="deleteModal" aria-hidden="true">
|
||||
<div class="admin-modal-panel">
|
||||
<button class="admin-modal-close" type="button" data-ann-cancel aria-label="关闭">
|
||||
<i class="mdi mdi-close"></i>
|
||||
</button>
|
||||
<div class="admin-modal-icon"><i class="mdi mdi-delete-outline"></i></div>
|
||||
<p class="admin-eyebrow mb-1">Delete</p>
|
||||
<h3>确认删除公告?</h3>
|
||||
<p class="text-muted mb-0">删除后无法在公告列表中恢复。</p>
|
||||
<div class="admin-modal-actions">
|
||||
<button class="btn btn-light" type="button" data-ann-cancel>取消</button>
|
||||
<button class="btn btn-danger" id="annDeleteConfirm" type="button">确认删除</button>
|
||||
</section>
|
||||
<section class="card" aria-labelledby="announcement-list-title">
|
||||
<div class="card-header d-flex align-items-center justify-content-between gap-2 flex-wrap"><h2 class="h5 card-title mb-0" id="announcement-list-title">公告列表</h2><span class="badge text-bg-light" id="announcement-total">{if $announcements_page}共 {$announcements_page.pagination.total|escape} 条{else}数据未获取{/if}</span></div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle mb-0 admin-ann-table">
|
||||
<caption class="visually-hidden">管理员公告列表</caption>
|
||||
<thead><tr><th scope="col">公告</th><th scope="col">类型</th><th scope="col">状态</th><th scope="col">发布时间</th><th scope="col">最近更新</th><th scope="col" class="text-end">操作</th></tr></thead>
|
||||
<tbody id="announcement-rows">
|
||||
{if !$announcements_page}
|
||||
<tr><td colspan="6" class="text-center text-muted py-4">公告暂不可用,请刷新重试。</td></tr>
|
||||
{else}
|
||||
{foreach $announcements_page.items as $item}
|
||||
<tr data-ann-row="{$item.id|escape}">
|
||||
<td><div class="admin-ann-content text-break">{$item.title|escape}</div><div class="text-muted fs-13 text-break">{$item.body|truncate:110:'…'|escape}</div><span class="text-muted fs-12">#{$item.id|escape}</span><details class="mt-2"><summary class="text-primary fs-13">查看正文</summary><p class="admin-ann-body text-muted fs-13 mt-2 mb-0">{$item.body|escape}</p></details></td>
|
||||
<td><span class="badge {if $item.type == 'incident'}text-bg-danger{elseif $item.type == 'maintenance'}text-bg-warning{else}text-bg-light{/if}">{$item.type_label|escape}</span></td>
|
||||
<td><span class="badge {if $item.status == 'published'}text-bg-success{else}text-bg-light{/if}">{if $item.status == 'published'}已发布{else}已撤下{/if}</span></td>
|
||||
<td class="text-muted fs-13">{$item.published_at|default:'未发布'|escape}</td>
|
||||
<td class="text-muted fs-13">{$item.updated_at|default:'—'|escape}</td>
|
||||
<td>{if $ann_can_manage}<div class="d-flex justify-content-end gap-2 flex-wrap"><a class="btn btn-sm btn-light" href="/admin/announcement/{$item.id|escape}/edit">编辑</a><button class="btn btn-sm btn-light" type="button" data-ann-status-button data-ann-id="{$item.id|escape}" data-ann-next-status="{if $item.status == 'published'}withdrawn{else}published{/if}">{if $item.status == 'published'}撤下{else}发布{/if}</button></div>{else}<span class="text-muted fs-13">只读</span>{/if}</td>
|
||||
</tr>
|
||||
{foreachelse}
|
||||
<tr><td colspan="6" class="text-center text-muted py-4">没有符合条件的公告。</td></tr>
|
||||
{/foreach}
|
||||
{/if}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{if $announcements_page && $announcements_page.pagination.total > 0}
|
||||
<nav class="admin-user-pagination" aria-label="公告列表分页">
|
||||
{if $announcements_page.pagination.page > 1}<a class="btn btn-light" rel="prev" href="/admin/announcement?q={$ann_filters.q|default:''|escape:'url'}&type={$ann_filters.type|default:'all'|escape:'url'}&status={$ann_filters.status|default:'all'|escape:'url'}&per_page={$announcements_page.pagination.per_page|escape}&page={$announcements_page.pagination.page - 1}">上一页</a>{else}<span class="btn btn-light disabled" aria-disabled="true">上一页</span>{/if}
|
||||
<span>第 {$announcements_page.pagination.page|escape} / {$announcements_page.pagination.total_pages|escape} 页 · 共 {$announcements_page.pagination.total|escape} 条</span>
|
||||
{if $announcements_page.pagination.page < $announcements_page.pagination.total_pages}<a class="btn btn-light" rel="next" href="/admin/announcement?q={$ann_filters.q|default:''|escape:'url'}&type={$ann_filters.type|default:'all'|escape:'url'}&status={$ann_filters.status|default:'all'|escape:'url'}&per_page={$announcements_page.pagination.per_page|escape}&page={$announcements_page.pagination.page + 1}">下一页</a>{else}<span class="btn btn-light disabled" aria-disabled="true">下一页</span>{/if}
|
||||
</nav>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="admin-toast" id="annToast"></div>
|
||||
|
||||
{literal}
|
||||
<script>
|
||||
(function () {
|
||||
var rows = document.getElementById('annRows');
|
||||
var total = document.getElementById('annTotal');
|
||||
var search = document.getElementById('annSearch');
|
||||
var reload = document.getElementById('annReload');
|
||||
var modal = document.getElementById('deleteModal');
|
||||
var confirmButton = document.getElementById('annDeleteConfirm');
|
||||
var toast = document.getElementById('annToast');
|
||||
var deleteId = null;
|
||||
var allRows = [];
|
||||
|
||||
if (window.VenixAdminSearchState) {
|
||||
window.VenixAdminSearchState.bind(search);
|
||||
}
|
||||
|
||||
function showToast(text, type) {
|
||||
toast.textContent = text;
|
||||
toast.className = 'admin-toast is-show ' + (type || '');
|
||||
window.setTimeout(function () {
|
||||
toast.className = 'admin-toast';
|
||||
}, 2200);
|
||||
}
|
||||
|
||||
function textFromHtml(html) {
|
||||
var holder = document.createElement('div');
|
||||
holder.innerHTML = html || '';
|
||||
return holder.textContent.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
function openDelete(id) {
|
||||
deleteId = id;
|
||||
modal.classList.add('is-open');
|
||||
modal.setAttribute('aria-hidden', 'false');
|
||||
}
|
||||
|
||||
function closeDelete() {
|
||||
deleteId = null;
|
||||
modal.classList.remove('is-open');
|
||||
modal.setAttribute('aria-hidden', 'true');
|
||||
}
|
||||
|
||||
function render(data) {
|
||||
var keyword = (search.value || '').toLowerCase().trim();
|
||||
var filtered = data.map(function (item) {
|
||||
return {
|
||||
id: item.id || item[1] || '',
|
||||
date: item.date || item[2] || '',
|
||||
content: item.content || item[3] || ''
|
||||
};
|
||||
}).filter(function (item) {
|
||||
var content = textFromHtml(item.content);
|
||||
return !keyword || String(item.id).indexOf(keyword) !== -1 || content.toLowerCase().indexOf(keyword) !== -1;
|
||||
});
|
||||
|
||||
total.textContent = '共 ' + filtered.length + ' 条';
|
||||
|
||||
if (!filtered.length) {
|
||||
rows.innerHTML = '<tr><td colspan="4" class="text-center text-muted py-4">暂无公告</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
rows.innerHTML = '';
|
||||
filtered.forEach(function (item) {
|
||||
var tr = document.createElement('tr');
|
||||
var content = textFromHtml(item.content);
|
||||
if (content.length > 120) {
|
||||
content = content.slice(0, 120) + '...';
|
||||
}
|
||||
|
||||
tr.innerHTML =
|
||||
'<td><span class="badge text-bg-light">#' + item.id + '</span></td>' +
|
||||
'<td class="text-muted">' + (item.date || '-') + '</td>' +
|
||||
'<td><div class="admin-ann-content"></div></td>' +
|
||||
'<td class="text-end">' +
|
||||
'<a class="btn btn-sm btn-primary me-1" href="/admin/announcement/' + item.id + '/edit">编辑</a>' +
|
||||
'<button class="btn btn-sm btn-light" type="button" data-delete="' + item.id + '">删除</button>' +
|
||||
'</td>';
|
||||
tr.querySelector('.admin-ann-content').textContent = content || '-';
|
||||
rows.appendChild(tr);
|
||||
});
|
||||
}
|
||||
|
||||
function buildParams() {
|
||||
var params = new URLSearchParams();
|
||||
params.set('draw', '1');
|
||||
params.set('start', '0');
|
||||
params.set('length', '500');
|
||||
params.set('search[value]', '');
|
||||
params.set('order[0][column]', '1');
|
||||
params.set('order[0][dir]', 'desc');
|
||||
['op', 'id', 'date', 'content'].forEach(function (column, index) {
|
||||
params.set('columns[' + index + '][data]', column);
|
||||
params.set('columns[' + index + '][name]', '');
|
||||
params.set('columns[' + index + '][searchable]', 'true');
|
||||
params.set('columns[' + index + '][orderable]', 'true');
|
||||
params.set('columns[' + index + '][search][value]', '');
|
||||
params.set('columns[' + index + '][search][regex]', 'false');
|
||||
});
|
||||
return params;
|
||||
}
|
||||
|
||||
function loadAnnouncements() {
|
||||
rows.innerHTML = '<tr><td colspan="4" class="text-center text-muted py-4">公告加载中</td></tr>';
|
||||
total.textContent = '读取中';
|
||||
|
||||
fetch('/admin/announcement/ajax', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
},
|
||||
body: buildParams()
|
||||
}).then(function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error('request failed');
|
||||
}
|
||||
return response.json();
|
||||
}).then(function (json) {
|
||||
allRows = json.data || [];
|
||||
render(allRows);
|
||||
}).catch(function () {
|
||||
rows.innerHTML = '<tr><td colspan="4" class="text-center text-danger py-4">公告读取失败</td></tr>';
|
||||
total.textContent = '读取失败';
|
||||
});
|
||||
}
|
||||
|
||||
function deleteAnnouncement() {
|
||||
if (!deleteId) {
|
||||
return;
|
||||
}
|
||||
|
||||
var params = new URLSearchParams();
|
||||
params.set('id', deleteId);
|
||||
confirmButton.disabled = true;
|
||||
|
||||
fetch('/admin/announcement', {
|
||||
method: 'DELETE',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
},
|
||||
body: params
|
||||
}).then(function (response) {
|
||||
return response.json();
|
||||
}).then(function (json) {
|
||||
showToast(json.msg || '操作完成', json.ret ? 'is-success' : 'is-error');
|
||||
closeDelete();
|
||||
if (json.ret) {
|
||||
loadAnnouncements();
|
||||
}
|
||||
}).catch(function () {
|
||||
showToast('删除失败,请稍后重试', 'is-error');
|
||||
}).finally(function () {
|
||||
confirmButton.disabled = false;
|
||||
});
|
||||
}
|
||||
|
||||
rows.addEventListener('click', function (event) {
|
||||
var button = event.target.closest('[data-delete]');
|
||||
if (button) {
|
||||
openDelete(button.getAttribute('data-delete'));
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-ann-cancel]').forEach(function (button) {
|
||||
button.addEventListener('click', closeDelete);
|
||||
});
|
||||
|
||||
modal.addEventListener('click', function (event) {
|
||||
if (event.target === modal) {
|
||||
closeDelete();
|
||||
}
|
||||
});
|
||||
|
||||
confirmButton.addEventListener('click', deleteAnnouncement);
|
||||
reload.addEventListener('click', loadAnnouncements);
|
||||
search.addEventListener('input', function () {
|
||||
render(allRows);
|
||||
});
|
||||
|
||||
loadAnnouncements();
|
||||
})();
|
||||
</script>
|
||||
{/literal}
|
||||
|
||||
</section>
|
||||
</main>
|
||||
<script src="/theme/venix/js/admin-announcements.js?v={$venix_asset_version}" defer></script>
|
||||
{include file='admin/static_footer.tpl'}
|
||||
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026093007' scope='global'}
|
||||
{assign var=venix_asset_version value='2026093008' scope='global'}
|
||||
|
||||
@ -1,84 +0,0 @@
|
||||
{include file='user/layout_header.tpl' vu_title='公告' vu_active='announcement'}
|
||||
<header class="vu-topbar">
|
||||
<div>
|
||||
<p class="vu-kicker">用户中心</p>
|
||||
<h1>公告</h1>
|
||||
</div>
|
||||
<div class="vu-top-actions">
|
||||
<a class="vu-btn vu-btn-ghost" href="/user/cloud/instances"><i class="mdi mdi-arrow-left"></i><span>返回实例</span></a>
|
||||
{if !empty($ticket_navigation_enabled)}
|
||||
<a class="vu-btn" href="/user/ticket"><i class="mdi mdi-lifebuoy"></i><span>提交工单</span></a>
|
||||
{/if}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section class="vu-announcement-hero">
|
||||
<article class="vu-announcement-hero-main">
|
||||
<span class="vu-status is-live">最近两个月</span>
|
||||
<h2>服务公告与使用提醒</h2>
|
||||
<p>这里汇总近期公告、维护安排和重要变更。使用前建议先查看最新公告,避免错过服务相关调整。</p>
|
||||
</article>
|
||||
<aside class="vu-announcement-summary">
|
||||
<div>
|
||||
<span>公告数量</span>
|
||||
<strong>{count($anns)}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>最新公告</span>
|
||||
<strong>{if $latestAnn == null}暂无{else}{$latestAnn->date|escape:"html"}{/if}</strong>
|
||||
</div>
|
||||
</aside>
|
||||
</section>
|
||||
|
||||
<section class="vu-announcement-layout">
|
||||
<div class="vu-announcement-list">
|
||||
{if $anns->isEmpty()}
|
||||
<article class="vu-card vu-announcement-card">
|
||||
<div class="vu-empty-state">
|
||||
<i class="mdi mdi-bullhorn-outline"></i>
|
||||
<strong>暂无公告</strong>
|
||||
<span>最近两个月没有新的公告内容。</span>
|
||||
</div>
|
||||
</article>
|
||||
{else}
|
||||
{foreach $anns as $ann}
|
||||
<article class="vu-card vu-announcement-card">
|
||||
<div class="vu-card-head">
|
||||
<div>
|
||||
<p class="vu-kicker">Announcement</p>
|
||||
<h2>公告日期:{$ann->date|escape:"html"}</h2>
|
||||
</div>
|
||||
<i class="mdi mdi-bullhorn-outline vu-card-icon"></i>
|
||||
</div>
|
||||
{if $ann != null}
|
||||
<div class="vu-announcement-content">{$ann->content}</div>
|
||||
{/if}
|
||||
</article>
|
||||
{/foreach}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<aside class="vu-announcement-side">
|
||||
<article class="vu-card vu-announcement-card">
|
||||
<div class="vu-card-head">
|
||||
<div>
|
||||
<p class="vu-kicker">Notice</p>
|
||||
<h2>阅读建议</h2>
|
||||
</div>
|
||||
<i class="mdi mdi-information-outline vu-card-icon"></i>
|
||||
</div>
|
||||
<div class="vu-profile-tips">
|
||||
<div><i class="mdi mdi-clock-outline"></i><span>维护公告通常会包含具体时间,请留意服务可用性变化。</span></div>
|
||||
<div><i class="mdi mdi-cart-outline"></i><span>套餐、价格和续费规则调整会优先在公告中说明。</span></div>
|
||||
<div><i class="mdi mdi-lifebuoy"></i><span>公告说明无法解决的问题,可以提交工单继续确认。</span></div>
|
||||
</div>
|
||||
</article>
|
||||
</aside>
|
||||
</section>
|
||||
{include file='user/layout_footer.tpl'}
|
||||
|
||||
{include file='user/layout_modal.tpl'}
|
||||
|
||||
{include file='user/layout_scripts.tpl'}
|
||||
</body>
|
||||
</html>
|
||||
@ -0,0 +1,12 @@
|
||||
<dialog class="panel-announcements-drawer" id="panel-announcements-drawer" aria-labelledby="panel-announcements-title" aria-describedby="panel-announcements-description">
|
||||
<header class="panel-announcements-header">
|
||||
<div><h2 id="panel-announcements-title">公告与维护信息</h2><p id="panel-announcements-description">按发布时间查看站点通知、维护安排与故障说明。</p></div>
|
||||
<button class="button button-ghost panel-announcements-close" id="panel-announcements-close" type="button" aria-label="关闭公告" autofocus><i class="mdi mdi-close" aria-hidden="true"></i></button>
|
||||
</header>
|
||||
<div class="panel-announcements-toolbar"><p id="panel-announcements-state" class="panel-announcements-state" role="status" aria-live="polite">打开后读取最新公告。</p><button class="button button-outline small" id="panel-announcements-refresh" type="button">刷新</button></div>
|
||||
<div class="panel-announcements-scroll" id="panel-announcements-scroll" tabindex="0" aria-label="公告内容">
|
||||
<div class="panel-announcements-list" id="panel-announcements-list" aria-busy="false"></div>
|
||||
<div class="panel-announcements-pagination"><p id="panel-announcements-count"></p><button class="button button-outline" id="panel-announcements-more" type="button" hidden>加载更多</button></div>
|
||||
</div>
|
||||
</dialog>
|
||||
<script type="module" src="/cloud/announcements.js?v={$venix_asset_version|escape:'html'}"></script>
|
||||
@ -0,0 +1,284 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services {
|
||||
final class Auth
|
||||
{
|
||||
public static $user = null;
|
||||
public static function getUser() { return self::$user; }
|
||||
}
|
||||
final class AdminPermission
|
||||
{
|
||||
public static bool $superAdmin = false;
|
||||
public static function isSuperAdmin(): bool { return self::$superAdmin; }
|
||||
}
|
||||
}
|
||||
|
||||
namespace App\Services\Cloud {
|
||||
final class CloudSessionService
|
||||
{
|
||||
public static int $calls = 0;
|
||||
public static function current($user): string
|
||||
{
|
||||
self::$calls++;
|
||||
throw new \RuntimeException('Announcement requested an engine session');
|
||||
}
|
||||
}
|
||||
final class CloudEngineClient
|
||||
{
|
||||
public static int $calls = 0;
|
||||
public function __construct()
|
||||
{
|
||||
self::$calls++;
|
||||
throw new \RuntimeException('Announcement contacted the engine');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Controllers\Admin\AnnController;
|
||||
use App\Controllers\AnnouncementController;
|
||||
use App\Models\Ann;
|
||||
use App\Models\User;
|
||||
use App\Services\AdminCsrf;
|
||||
use App\Services\AdminPermission;
|
||||
use App\Services\AnnouncementSchema;
|
||||
use App\Services\AnnouncementService as Announcements;
|
||||
use App\Services\Auth;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudEngineClient;
|
||||
use App\Services\Cloud\CloudSessionService;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Slim\Http\Environment;
|
||||
use Slim\Http\Request;
|
||||
use Slim\Http\Response;
|
||||
|
||||
$System_Config = ['cookie_secure' => 'false'];
|
||||
$assert = static function (bool $ok, string $message): void {
|
||||
if (!$ok) throw new RuntimeException($message);
|
||||
};
|
||||
$reject = static function (callable $call, int $status) use ($assert): void {
|
||||
try { $call(); } catch (CloudError $error) {
|
||||
$assert($error->httpStatus === $status, 'Unexpected rejection status: ' . $error->httpStatus);
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException('Expected rejection was accepted.');
|
||||
};
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$connection = $capsule->getConnection();
|
||||
$schema = $connection->getSchemaBuilder();
|
||||
$schema->create('announcement', static function (Blueprint $table): void {
|
||||
$table->increments('id'); $table->dateTime('date');
|
||||
$table->longText('content'); $table->longText('markdown');
|
||||
});
|
||||
// This rollout intentionally supports empty legacy tables only. Existing
|
||||
// records must stop it before the very first DDL statement, not be converted.
|
||||
$connection->table('announcement')->insert(['id' => 1, 'date' => '2020-01-02 03:04:05',
|
||||
'content' => '<p>do not delete this record</p>', 'markdown' => '**archive**']);
|
||||
$originalColumns = $schema->getColumnListing('announcement');
|
||||
$originalData = $connection->table('announcement')->get()->toJson();
|
||||
$connection->enableQueryLog(); $connection->flushQueryLog();
|
||||
try {
|
||||
AnnouncementSchema::upgrade($connection);
|
||||
throw new LogicException('Nonempty legacy schema was silently changed.');
|
||||
} catch (RuntimeException $error) {
|
||||
$assert(str_contains($error->getMessage(), '旧公告表仍有数据'), 'Unsafe legacy migration had no clear error.');
|
||||
}
|
||||
foreach ($connection->getQueryLog() as $query) {
|
||||
$assert(!preg_match('/^(?:alter|create|drop|update|delete|insert)\b/i', $query['query']),
|
||||
'Legacy data guard ran after a schema/data mutation.');
|
||||
}
|
||||
$assert($schema->getColumnListing('announcement') === $originalColumns
|
||||
&& $connection->table('announcement')->get()->toJson() === $originalData, 'Rejected migration changed legacy structure/data.');
|
||||
// Remove only the test fixture, then exercise an interrupted empty migration.
|
||||
$connection->table('announcement')->where('id', 1)->delete();
|
||||
$schema->table('announcement', static function (Blueprint $table): void { $table->string('title', 120)->default(''); });
|
||||
AnnouncementSchema::upgrade($connection);
|
||||
$assert($schema->hasIndex('announcement', 'announcement_published')
|
||||
&& !$schema->hasColumn('announcement', 'content') && !$schema->hasColumn('announcement', 'markdown')
|
||||
&& !$schema->hasColumn('announcement', 'date') && $connection->table('announcement')->count() === 0,
|
||||
'Empty legacy migration left rich-text fields or created content.');
|
||||
AnnouncementSchema::upgrade($connection);
|
||||
for ($id = 1; $id <= 205; $id++) {
|
||||
$connection->table('announcement')->insert(['id' => $id, 'title' => '通知 ' . $id,
|
||||
'body' => $id === 1 ? "第一段\n\n第二段 链接文字" : '纯文本通知 ' . $id,
|
||||
'type' => 'notice', 'status' => 'published', 'published_at' => '2020-01-02 03:04:05',
|
||||
'updated_at' => '2020-01-02 03:04:05']);
|
||||
}
|
||||
$snapshot = static fn (): string => $connection->table('announcement')->orderBy('id')->get()->toJson();
|
||||
$migrated = $snapshot();
|
||||
AnnouncementSchema::upgrade($connection);
|
||||
$assert($snapshot() === $migrated, 'Repeated migration was not idempotent.');
|
||||
|
||||
$customer = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false];
|
||||
$admin = ['user_id' => 2, 'is_admin' => true, 'is_super_admin' => false, 'can_manage' => false];
|
||||
$super = ['user_id' => 3, 'is_admin' => true, 'is_super_admin' => true, 'can_manage' => true];
|
||||
$page = Announcements::page($admin);
|
||||
$assert($page['pagination']['total'] === 205 && count($page['items']) === 20
|
||||
&& $page['filters']['status'] === 'all', 'Admin pagination lost historical announcements.');
|
||||
$seen = [];
|
||||
for ($pageNo = 1; $pageNo <= 21; $pageNo++) {
|
||||
$published = Announcements::published($customer, ['page' => $pageNo]);
|
||||
foreach ($published['items'] as $item) {
|
||||
$assert($item['status'] === 'published' && is_string($item['id'])
|
||||
&& !array_key_exists('content', $item) && !array_key_exists('markdown', $item), 'Public DTO exposed archives or unpublished records.');
|
||||
$seen[] = $item['id'];
|
||||
}
|
||||
}
|
||||
$assert(count(array_unique($seen)) === 205 && in_array('1', $seen, true), 'Public pagination clipped old records at two months or 200 rows.');
|
||||
$lastPage = Announcements::published($customer, ['page' => 999]);
|
||||
$assert($lastPage['pagination']['page'] === 21 && count($lastPage['items']) === 5,
|
||||
'User out-of-range page was not clamped to the final page.');
|
||||
$lastAdminPage = Announcements::page($admin, ['page' => 999]);
|
||||
$assert($lastAdminPage['pagination']['page'] === 11 && $lastAdminPage['filters']['page'] === 11
|
||||
&& count($lastAdminPage['items']) === 5, 'Admin filters and pagination disagree after clamping.');
|
||||
$assert(Announcements::page($admin, ['q' => '链接文字'])['pagination']['total'] === 1, 'Plain-text search failed.');
|
||||
|
||||
$input = ['title' => '维护通知 🛠', 'type' => 'maintenance', 'body' => "第一行\r\n第二行 <script>只是文本</script>", 'status' => 'published'];
|
||||
$new = Announcements::save($super, $input);
|
||||
$assert($new['type_label'] === '维护' && $new['status'] === 'published' && $new['published_at'] !== null
|
||||
&& $new['body'] === "第一行\n第二行 <script>只是文本</script>", 'New announcement was not stored as literal plain text.');
|
||||
$stored = $connection->table('announcement')->where('id', $new['id'])->first();
|
||||
$assert(!property_exists($stored, 'content') && !property_exists($stored, 'markdown'), 'New schema retained legacy rich-text fields.');
|
||||
$connection->table('announcement')->where('id', $new['id'])->update(['published_at' => '2021-01-01 00:00:00']);
|
||||
$withdrawn = Announcements::setStatus($super, $new['id'], ['status' => 'withdrawn']);
|
||||
$assert($withdrawn['status'] === 'withdrawn' && $withdrawn['published_at'] === '2021-01-01 00:00:00'
|
||||
&& Announcements::published($customer)['pagination']['total'] === 205, 'Withdraw did not hide the announcement or destroyed publication history.');
|
||||
// The old edit form still says published; only an explicit status action may republish.
|
||||
$staleEdit = Announcements::save($super, array_replace($input, ['title' => '陈旧表单更新']), $new['id']);
|
||||
$assert($staleEdit['status'] === 'withdrawn' && $staleEdit['published_at'] === '2021-01-01 00:00:00',
|
||||
'A stale edit form republished a concurrently withdrawn announcement.');
|
||||
$republished = Announcements::setStatus($super, $new['id'], ['status' => 'published']);
|
||||
$assert($republished['status'] === 'published' && $republished['published_at'] > '2021-01-01 00:00:00',
|
||||
'Explicit republish did not record a real publication time.');
|
||||
$connection->table('announcement')->where('id', $new['id'])->update(['updated_at' => '2021-02-03 00:00:00']);
|
||||
$same = Announcements::setStatus($super, $new['id'], ['status' => 'published']);
|
||||
$assert($same['updated_at'] === '2021-02-03 00:00:00', 'Idempotent status request forged an update event.');
|
||||
Announcements::save($super, array_replace($input, ['title' => '50%_! literal', 'type' => 'incident', 'status' => 'withdrawn']));
|
||||
$assert(Announcements::page($admin, ['q' => '%_!'])['pagination']['total'] === 1
|
||||
&& Announcements::page($admin, ['q' => "' OR 1=1 --"])['pagination']['total'] === 0
|
||||
&& Announcements::page($admin, ['type' => 'incident', 'status' => 'withdrawn'])['pagination']['total'] === 1,
|
||||
'Filters did not bind literal keywords, type and status safely.');
|
||||
$saved = $snapshot();
|
||||
AnnouncementSchema::upgrade($connection);
|
||||
$assert($snapshot() === $saved, 'Repeated upgrade changed published or withdrawn records.');
|
||||
|
||||
foreach (['title', 'body', 'type', 'status'] as $key) {
|
||||
$reject(static fn () => Announcements::save($super, array_replace($input, [$key => ['bad']])), 400);
|
||||
}
|
||||
foreach ([['title' => ''], ['body' => ' '], ['title' => str_repeat('字', 121)], ['body' => str_repeat('字', 20001)],
|
||||
['title' => "multi\nline"], ['body' => "nul\0byte"], ['type' => 'html'], ['status' => 'deleted']] as $invalid) {
|
||||
$reject(static fn () => Announcements::save($super, array_replace($input, $invalid)), 400);
|
||||
}
|
||||
$withoutStatus = $input; unset($withoutStatus['status']);
|
||||
$reject(static fn () => Announcements::save($super, $withoutStatus), 400);
|
||||
foreach (['page', 'per_page', 'q', 'type', 'status'] as $key) {
|
||||
$reject(static fn () => Announcements::page($admin, [$key => ['bad']]), 400);
|
||||
}
|
||||
foreach ([['page' => 0], ['page' => '1.1'], ['per_page' => 500], ['q' => str_repeat('a', 81)],
|
||||
['type' => 'wrong'], ['status' => 'deleted']] as $invalid) {
|
||||
$reject(static fn () => Announcements::page($admin, $invalid), 400);
|
||||
}
|
||||
$reject(static fn () => Announcements::published($customer, ['per_page' => 100]), 400);
|
||||
$reject(static fn () => Announcements::published([], []), 401);
|
||||
$reject(static fn () => Announcements::page($customer), 403);
|
||||
$reject(static fn () => Announcements::save($admin, $input), 403);
|
||||
$reject(static fn () => Announcements::setStatus($admin, '1', ['status' => 'withdrawn']), 403);
|
||||
$reject(static fn () => Announcements::detail($admin, '0'), 400);
|
||||
$reject(static fn () => Announcements::detail($admin, '999999'), 404);
|
||||
$reject(static fn () => Announcements::save($super, $input, '999999'), 404);
|
||||
$reject(static fn () => Announcements::setStatus($super, '999999', ['status' => 'withdrawn']), 404);
|
||||
$assert(!method_exists(AnnController::class, 'delete') && !method_exists(AnnController::class, 'ajax'), 'Legacy rich-text deletion/list endpoints remain.');
|
||||
|
||||
$connection->enableQueryLog();
|
||||
$counts = [];
|
||||
foreach ([20, 100] as $size) {
|
||||
$connection->flushQueryLog();
|
||||
Announcements::page($admin, ['per_page' => $size]);
|
||||
$log = $connection->getQueryLog(); $counts[] = count($log);
|
||||
foreach ($log as $query) {
|
||||
$sql = strtolower($query['query']);
|
||||
$assert(str_starts_with($sql, 'select ') && !str_contains($sql, 'content')
|
||||
&& !str_contains($sql, 'markdown'), 'Read path performs DDL/writes or reads archived rich text.');
|
||||
}
|
||||
}
|
||||
$assert($counts === [2, 2], 'Announcement pagination has per-row queries.');
|
||||
$beforeReads = $snapshot();
|
||||
$login = static function (bool $isAdmin, bool $isSuper = false, bool $enabled = true): void {
|
||||
$user = new User(); $user->id = $isSuper ? 3 : ($isAdmin ? 2 : 1);
|
||||
$user->enable = $enabled ? 1 : 0; $user->is_admin = $isAdmin; $user->isLogin = true;
|
||||
Auth::$user = $user; AdminPermission::$superAdmin = $isSuper;
|
||||
};
|
||||
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
|
||||
require dirname(__DIR__) . '/config/routes_cloud.php';
|
||||
$request = static function (string $method, string $path, ?array $body = null, array $query = []): Request {
|
||||
$request = Request::createFromEnvironment(Environment::mock(['REQUEST_METHOD' => $method, 'REQUEST_URI' => $path]));
|
||||
return $request->withQueryParams($query)->withParsedBody($body);
|
||||
};
|
||||
$login(false);
|
||||
$response = $app->process($request('GET', '/api/v1/announcements'), new Response());
|
||||
$public = json_decode((string) $response->getBody(), true);
|
||||
$assert($response->getStatusCode() === 200 && $response->getHeaderLine('Cache-Control') === 'private, no-store'
|
||||
&& count($public['items']) === 10 && $public['pagination']['total'] === 206, 'Registered user API contract failed.');
|
||||
$response = $app->process($request('GET', '/api/v1/announcements', null, ['page' => ['bad']]), new Response());
|
||||
$assert($response->getStatusCode() === 400, 'User API did not reject array parameters.');
|
||||
$login(false, false, false);
|
||||
$response = $app->process($request('GET', '/api/v1/announcements'), new Response());
|
||||
$assert($response->getStatusCode() === 401 && str_contains($response->getHeaderLine('Cache-Control'), 'no-store'),
|
||||
'Disabled user reached the notice feed.');
|
||||
Auth::$user = null;
|
||||
$response = $app->process($request('GET', '/api/v1/announcements'), new Response());
|
||||
$assert($response->getStatusCode() === 401, 'Anonymous user reached the notice feed.');
|
||||
$login(false);
|
||||
$response = (new AnnouncementController())->index($request('GET', '/api/v1/announcements'), new Response());
|
||||
$assert($response->getStatusCode() === 200 && $snapshot() === $beforeReads, 'Direct API fallback wrote business state.');
|
||||
|
||||
$controller = (new ReflectionClass(AnnController::class))->newInstanceWithoutConstructor();
|
||||
foreach (['anonymous' => 401, 'disabled' => 401, 'customer' => 403] as $identity => $status) {
|
||||
$login($identity !== 'customer', true, $identity !== 'disabled');
|
||||
if ($identity === 'anonymous') Auth::$user = null;
|
||||
$response = $controller->index($request('GET', '/admin/announcement'), new Response(), []);
|
||||
$assert($response->getStatusCode() === $status && (string) $response->getBody() === ''
|
||||
&& $response->getHeaderLine('Cache-Control') === 'private, no-store', 'Unauthorized SSR rendered an admin shell.');
|
||||
}
|
||||
$login(true);
|
||||
foreach (['create', 'edit'] as $method) {
|
||||
$response = $controller->$method($request('GET', '/admin/announcement/1/edit'), new Response(), ['id' => '1']);
|
||||
$assert($response->getStatusCode() === 403, 'Read-only administrator gained an edit form.');
|
||||
}
|
||||
$response = $controller->add($request('POST', '/admin/announcement', $input), new Response(), []);
|
||||
$assert($response->getStatusCode() === 403 && json_decode((string) $response->getBody(), true)['ret'] === 0,
|
||||
'Controller accepted a read-only administrator write.');
|
||||
$login(true, true);
|
||||
$response = $controller->add($request('POST', '/admin/announcement', array_replace($input, ['title' => 'Controller created'])), new Response(), []);
|
||||
$created = json_decode((string) $response->getBody(), true);
|
||||
$assert($response->getStatusCode() === 200 && $created['ret'] === 1
|
||||
&& $created['announcement']['title'] === 'Controller created'
|
||||
&& $response->getHeaderLine('Cache-Control') === 'private, no-store', 'Admin JSON create contract failed.');
|
||||
$response = $controller->update($request('PUT', '/admin/announcement/999999', $input), new Response(), ['id' => '999999']);
|
||||
$assert($response->getStatusCode() === 404 && json_decode((string) $response->getBody(), true)['ret'] === 0,
|
||||
'Missing update did not return JSON 404.');
|
||||
$response = $controller->add($request('POST', '/admin/announcement'), new Response(), []);
|
||||
$assert($response->getStatusCode() === 400, 'Malformed request body did not return 400.');
|
||||
|
||||
// Exercise the existing CSRF and super-admin middleware around the actual status handler.
|
||||
$protected = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
|
||||
$protected->post('/admin/announcement/{id}/status', [$controller, 'status'])->add(new \App\Middleware\SuperAdmin());
|
||||
$path = '/admin/announcement/' . $created['announcement']['id'] . '/status';
|
||||
$response = $protected->process($request('POST', $path, ['status' => 'withdrawn']), new Response());
|
||||
$assert($response->getStatusCode() === 419, 'Status changes bypassed existing CSRF protection: '
|
||||
. $response->getStatusCode() . ' ' . (string) $response->getBody());
|
||||
$token = AdminCsrf::token();
|
||||
$response = $protected->process($request('POST', $path, ['status' => 'withdrawn'])
|
||||
->withHeader(AdminCsrf::HEADER_NAME, $token), new Response());
|
||||
$assert($response->getStatusCode() === 200
|
||||
&& json_decode((string) $response->getBody(), true)['announcement']['status'] === 'withdrawn',
|
||||
'Valid CSRF-protected status request failed.');
|
||||
$assert(CloudEngineClient::$calls === 0 && CloudSessionService::$calls === 0, 'Announcements acquired engine state.');
|
||||
echo "Announcement guarded/idempotent empty-schema migration, plain text, clamped pagination, stale edits, publication, API/auth/CSRF and read-only queries passed.\n";
|
||||
}
|
||||
Loading…
Reference in New Issue