v1.2.0: 新增公告推送

- ca_announcements 表 + 管理端公告推送页
- 公开接口 GET /api/public/announcements (list/popup)
- 支持置顶/弹窗/定时/对象筛选/关联项目
- 仅 admin/project_admin 可发布
This commit is contained in:
root committed 2026-10-10 10:00:25 +08:00
1 parent 74ccc193d2
commit c64f46e2af
12 files changed
+811 -2

No files matched your search

@@ -0,0 +1,273 @@
<?php
namespace App\Controllers;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Validator;
/**
* 公告推送管理控制器
*/
class AnnouncementController extends Controller
{
/**
* 公告列表(管理端)
* GET /api/announcements
*/
public function list(): void
{
$db = Database::getInstance();
$page = max(1, (int) ($_GET['page'] ?? 1));
$pageSize = min((int) ($_GET['page_size'] ?? 20), 100);
$offset = ($page - 1) * $pageSize;
$keyword = trim($_GET['keyword'] ?? '');
$type = $_GET['type'] ?? '';
$target = $_GET['target'] ?? '';
$status = $_GET['status'] ?? '';
$where = 'WHERE 1=1';
$params = [];
if ($keyword !== '') {
$where .= ' AND (title LIKE ? OR content LIKE ?)';
$params[] = "%{$keyword}%";
$params[] = "%{$keyword}%";
}
if ($type !== '' && in_array($type, ['system', 'update', 'promo', 'notice'], true)) {
$where .= ' AND type = ?';
$params[] = $type;
}
if ($target !== '' && in_array($target, ['all', 'admin', 'agent', 'client'], true)) {
$where .= ' AND target = ?';
$params[] = $target;
}
if ($status !== '') {
$where .= ' AND status = ?';
$params[] = (int) $status;
}
$total = (int) $db->fetchColumn("SELECT COUNT(*) FROM {$db->table('announcements')} {$where}", $params);
$list = $db->fetchAll(
"SELECT * FROM {$db->table('announcements')} {$where}
ORDER BY is_top DESC, id DESC
LIMIT {$offset}, {$pageSize}",
$params
);
$this->success([
'list' => $list,
'total' => $total,
'page' => $page,
'page_size' => $pageSize,
]);
}
/**
* 创建公告
* POST /api/announcements
*/
public function create(): void
{
$role = $this->getUserRole();
if (!in_array($role, ['admin', 'project_admin'], true)) {
$this->error('仅管理员可发布公告', 403);
}
$input = $this->getJsonInput();
$validator = new Validator($input);
if (!$validator->validate([
'title' => 'required|min:1|max:200',
'content' => 'required|min:1',
])) {
$this->error($validator->getFirstError());
}
$type = in_array($input['type'] ?? '', ['system', 'update', 'promo', 'notice'], true)
? $input['type'] : 'notice';
$target = in_array($input['target'] ?? '', ['all', 'admin', 'agent', 'client'], true)
? $input['target'] : 'all';
$isTop = !empty($input['is_top']) ? 1 : 0;
$isPopup = !empty($input['is_popup']) ? 1 : 0;
$status = isset($input['status']) ? ((int) $input['status'] === 1 ? 1 : 0) : 1;
$projectId = !empty($input['project_id']) ? (int) $input['project_id'] : null;
$linkUrl = trim((string) ($input['link_url'] ?? ''));
$startAt = !empty($input['start_at']) ? $input['start_at'] : null;
$endAt = !empty($input['end_at']) ? $input['end_at'] : null;
// 项目管理员只能发到自己的项目
if ($role === 'project_admin') {
$user = $this->getCurrentUser();
$projectIds = $user['project_ids'] ?? [];
if ($projectId === null || !in_array($projectId, array_map('intval', $projectIds), true)) {
$this->error('只能发布到您绑定的项目', 403);
}
}
$db = Database::getInstance();
$id = $db->insert(
"INSERT INTO {$db->table('announcements')}
(title, content, type, target, project_id, is_top, is_popup, link_url, status, start_at, end_at, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
[
trim($input['title']),
$input['content'],
$type,
$target,
$projectId,
$isTop,
$isPopup,
$linkUrl,
$status,
$startAt,
$endAt,
(int) $this->getUserId(),
]
);
logger('announcement_create', 'announcement', $id, [
'title' => $input['title'],
'type' => $type,
'target' => $target,
]);
$row = $db->fetch("SELECT * FROM {$db->table('announcements')} WHERE id = ?", [$id]);
$this->success($row, '公告发布成功');
}
/**
* 更新公告
* PUT /api/announcements/{id}
*/
public function update(int $id): void
{
$role = $this->getUserRole();
if (!in_array($role, ['admin', 'project_admin'], true)) {
$this->error('仅管理员可修改公告', 403);
}
$db = Database::getInstance();
$row = $db->fetch("SELECT * FROM {$db->table('announcements')} WHERE id = ?", [$id]);
if (!$row) {
$this->error('公告不存在', 404);
}
if ($role === 'project_admin') {
$user = $this->getCurrentUser();
$projectIds = array_map('intval', $user['project_ids'] ?? []);
if ($row['project_id'] === null || !in_array((int) $row['project_id'], $projectIds, true)) {
$this->error('无权修改该公告', 403);
}
}
$input = $this->getJsonInput();
$title = array_key_exists('title', $input) ? trim((string) $input['title']) : $row['title'];
$content = array_key_exists('content', $input) ? (string) $input['content'] : $row['content'];
if ($title === '' || $content === '') {
$this->error('标题和内容不能为空');
}
$type = array_key_exists('type', $input) && in_array($input['type'], ['system', 'update', 'promo', 'notice'], true)
? $input['type'] : $row['type'];
$target = array_key_exists('target', $input) && in_array($input['target'], ['all', 'admin', 'agent', 'client'], true)
? $input['target'] : $row['target'];
$isTop = array_key_exists('is_top', $input) ? (!empty($input['is_top']) ? 1 : 0) : (int) $row['is_top'];
$isPopup = array_key_exists('is_popup', $input) ? (!empty($input['is_popup']) ? 1 : 0) : (int) $row['is_popup'];
$status = array_key_exists('status', $input) ? ((int) $input['status'] === 1 ? 1 : 0) : (int) $row['status'];
$linkUrl = array_key_exists('link_url', $input) ? trim((string) $input['link_url']) : ($row['link_url'] ?? '');
$startAt = array_key_exists('start_at', $input) ? ($input['start_at'] ?: null) : $row['start_at'];
$endAt = array_key_exists('end_at', $input) ? ($input['end_at'] ?: null) : $row['end_at'];
$db->execute(
"UPDATE {$db->table('announcements')}
SET title = ?, content = ?, type = ?, target = ?, is_top = ?, is_popup = ?,
link_url = ?, status = ?, start_at = ?, end_at = ?
WHERE id = ?",
[$title, $content, $type, $target, $isTop, $isPopup, $linkUrl, $status, $startAt, $endAt, $id]
);
logger('announcement_update', 'announcement', $id, ['title' => $title, 'status' => $status]);
$this->success($db->fetch("SELECT * FROM {$db->table('announcements')} WHERE id = ?", [$id]), '更新成功');
}
/**
* 删除公告
* DELETE /api/announcements/{id}
*/
public function delete(int $id): void
{
$role = $this->getUserRole();
if (!in_array($role, ['admin', 'project_admin'], true)) {
$this->error('仅管理员可删除公告', 403);
}
$db = Database::getInstance();
$row = $db->fetch("SELECT id, title, project_id FROM {$db->table('announcements')} WHERE id = ?", [$id]);
if (!$row) {
$this->error('公告不存在', 404);
}
if ($role === 'project_admin') {
$user = $this->getCurrentUser();
$projectIds = array_map('intval', $user['project_ids'] ?? []);
if ($row['project_id'] === null || !in_array((int) $row['project_id'], $projectIds, true)) {
$this->error('无权删除该公告', 403);
}
}
$db->execute("DELETE FROM {$db->table('announcements')} WHERE id = ?", [$id]);
logger('announcement_delete', 'announcement', $id, ['title' => $row['title']]);
$this->success(null, '公告已删除');
}
/**
* 批量删除
* POST /api/announcements/batch-delete
*/
public function batchDelete(): void
{
$role = $this->getUserRole();
if (!in_array($role, ['admin', 'project_admin'], true)) {
$this->error('仅管理员可删除公告', 403);
}
$input = $this->getJsonInput();
$ids = array_filter(array_map('intval', (array) ($input['ids'] ?? [])));
if (empty($ids)) {
$this->error('请选择要删除的公告');
}
$db = Database::getInstance();
$deleted = 0;
foreach ($ids as $id) {
$row = $db->fetch("SELECT id, project_id FROM {$db->table('announcements')} WHERE id = ?", [$id]);
if (!$row) {
continue;
}
if ($role === 'project_admin') {
$user = $this->getCurrentUser();
$projectIds = array_map('intval', $user['project_ids'] ?? []);
if ($row['project_id'] === null || !in_array((int) $row['project_id'], $projectIds, true)) {
continue;
}
}
$db->execute("DELETE FROM {$db->table('announcements')} WHERE id = ?", [$id]);
$deleted++;
}
$this->success(['deleted' => $deleted], "已删除 {$deleted} 条公告");
}
/**
* 公告详情
* GET /api/announcements/{id}
*/
public function detail(int $id): void
{
$db = Database::getInstance();
$row = $db->fetch("SELECT * FROM {$db->table('announcements')} WHERE id = ?", [$id]);
if (!$row) {
$this->error('公告不存在', 404);
}
$this->success($row);
}
}
@@ -749,6 +749,50 @@ class PublicController extends Controller
$this->success(['valid' => false, 'message' => '卡密状态异常'], 'ok');
}
/**
* 获取公告列表(公开/客户端)
* GET /api/public/announcements?target=client&project_id=1&limit=10
*/
public function announcements(): void
{
$db = Database::getInstance();
$target = trim((string) ($_GET['target'] ?? 'all'));
$projectId = !empty($_GET['project_id']) ? (int) $_GET['project_id'] : null;
$limit = min(max((int) ($_GET['limit'] ?? 10), 1), 50);
$where = "WHERE status = 1
AND (start_at IS NULL OR start_at <= NOW())
AND (end_at IS NULL OR end_at >= NOW())";
$params = [];
if (in_array($target, ['admin', 'agent', 'client'], true)) {
$where .= " AND (target = 'all' OR target = ?)";
$params[] = $target;
}
if ($projectId) {
$where .= ' AND (project_id IS NULL OR project_id = ?)';
$params[] = $projectId;
}
$list = $db->fetchAll(
"SELECT id, title, content, type, target, project_id, is_top, is_popup, link_url, created_at
FROM {$db->table('announcements')}
{$where}
ORDER BY is_top DESC, id DESC
LIMIT {$limit}",
$params
);
// 仅返回弹窗公告给客户端(方便一次拉取)
$popup = array_values(array_filter($list, static fn (array $r): bool => (int) $r['is_popup'] === 1));
$this->success([
'list' => $list,
'popup' => $popup,
], 'ok');
}
/**
* 查询订单状态
*/
@@ -0,0 +1,25 @@
-- 公告推送表
CREATE TABLE IF NOT EXISTS `ca_announcements` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`title` VARCHAR(200) NOT NULL COMMENT '公告标题',
`content` TEXT NOT NULL COMMENT '公告内容',
`type` ENUM('system','update','promo','notice') NOT NULL DEFAULT 'notice' COMMENT '类型: system=系统, update=更新, promo=活动, notice=通知',
`target` ENUM('all','admin','agent','client') NOT NULL DEFAULT 'all' COMMENT '推送对象: all=全部, admin=管理端, agent=代理端, client=客户端',
`project_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '关联项目ID(空=全部项目)',
`is_top` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否置顶: 0=否, 1=是',
`is_popup` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '客户端是否弹窗: 0=否, 1=是',
`link_url` VARCHAR(500) DEFAULT '' COMMENT '跳转链接(可空)',
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=草稿/下线, 1=发布中',
`start_at` DATETIME DEFAULT NULL COMMENT '生效时间(空=立即)',
`end_at` DATETIME DEFAULT NULL COMMENT '结束时间(空=永久)',
`created_by` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '发布人ID',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_status` (`status`),
KEY `idx_target` (`target`),
KEY `idx_is_top` (`is_top`),
KEY `idx_project_id` (`project_id`),
KEY `idx_start_end` (`start_at`, `end_at`),
KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='公告推送表';
+30 -1
View File
@@ -386,4 +386,33 @@ CREATE TABLE `ca_project_versions` (
UNIQUE KEY `uk_project_version` (`project_id`,`version`),
KEY `idx_project_id` (`project_id`),
KEY `idx_is_latest` (`project_id`,`is_latest`,`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='项目版本/安装包表';
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='项目版本/安装包表';
-- ============================================
-- 14. 公告推送表
-- ============================================
DROP TABLE IF EXISTS `ca_announcements`;
CREATE TABLE `ca_announcements` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`title` VARCHAR(200) NOT NULL COMMENT '公告标题',
`content` TEXT NOT NULL COMMENT '公告内容',
`type` ENUM('system','update','promo','notice') NOT NULL DEFAULT 'notice' COMMENT '类型: system=系统, update=更新, promo=活动, notice=通知',
`target` ENUM('all','admin','agent','client') NOT NULL DEFAULT 'all' COMMENT '推送对象: all=全部, admin=管理端, agent=代理端, client=客户端',
`project_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '关联项目ID(空=全部项目)',
`is_top` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否置顶: 0=否, 1=是',
`is_popup` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '客户端是否弹窗: 0=否, 1=是',
`link_url` VARCHAR(500) DEFAULT '' COMMENT '跳转链接(可空)',
`status` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '状态: 0=草稿/下线, 1=发布中',
`start_at` DATETIME DEFAULT NULL COMMENT '生效时间(空=立即)',
`end_at` DATETIME DEFAULT NULL COMMENT '结束时间(空=永久)',
`created_by` BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '发布人ID',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_status` (`status`),
KEY `idx_target` (`target`),
KEY `idx_is_top` (`is_top`),
KEY `idx_project_id` (`project_id`),
KEY `idx_start_end` (`start_at`, `end_at`),
KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='公告推送表';
+13
View File
@@ -18,6 +18,7 @@ use App\Controllers\BlacklistController;
use App\Controllers\NotificationController;
use App\Controllers\InstallationController;
use App\Controllers\ProjectVersionController;
use App\Controllers\AnnouncementController;
use App\Middleware\AuthMiddleware;
use App\Middleware\RateLimitMiddleware;
use App\Middleware\ApiKeyMiddleware;
@@ -43,6 +44,9 @@ $router->group('api/public', function ($router) {
// 卡密查询
$router->get('cards/query', [PublicController::class, 'queryCard']);
// 公告推送(客户端/商城)
$router->get('announcements', [PublicController::class, 'announcements']);
// 支付方式(前台展示用)
$router->get('payment/options', [PublicController::class, 'paymentOptions']);
@@ -204,6 +208,15 @@ $router->group('api', function ($router) {
$router->put('versions/{id}/latest', [ProjectVersionController::class, 'setLatest']);
$router->delete('versions/{id}', [ProjectVersionController::class, 'delete']);
// 公告推送管理 (admin / project_admin 发布; 代理只读不可见菜单)
$router->get('announcements', [AnnouncementController::class, 'list']);
$router->get('announcements/stats', [AnnouncementController::class, 'list']);
$router->get('announcements/{id}', [AnnouncementController::class, 'detail']);
$router->post('announcements', [AnnouncementController::class, 'create']);
$router->put('announcements/{id}', [AnnouncementController::class, 'update']);
$router->delete('announcements/{id}', [AnnouncementController::class, 'delete']);
$router->post('announcements/batch-delete', [AnnouncementController::class, 'batchDelete']);
// 黑名单管理(仅管理员)
$router->group('blacklists', function ($router) {
$router->get('', [BlacklistController::class, 'list']);