feat(admin): /api/admin 全套管理端点 + 公开公告接口 + showcase is_hidden
This commit is contained in:
1 parent
89466d08a8
commit
c48b1c74c2
4 files changed
+760
-2
No files matched your search
@@ -0,0 +1,751 @@
|
|||||||
|
/**
|
||||||
|
* 管理后台 API。
|
||||||
|
*
|
||||||
|
* 全部挂在 /api/admin 下,由 requireAdmin 保护(Bearer token + 数据库 role 校验)。
|
||||||
|
* 同时导出公开公告接口 createPublicAnnouncementsRouter(挂 /api/announcements,无需登录)。
|
||||||
|
*
|
||||||
|
* 端点(均返回 JSON):
|
||||||
|
* GET /stats 看板聚合计数
|
||||||
|
* GET /users?phone=&page=&pageSize= 用户列表(phone LIKE/ILIKE 过滤 + 分页)
|
||||||
|
* POST /users/:id/ban 封禁(role='banned')
|
||||||
|
* POST /users/:id/unban 解封(role='user')
|
||||||
|
* GET /orders?page=&pageSize= 订单列表(created_at 倒序)
|
||||||
|
* GET /codes?status=&page=&pageSize= 兑换码列表(status 过滤可选)
|
||||||
|
* POST /codes/generate 批量生成兑换码 { packageType, count }
|
||||||
|
* GET /showcase?page=&pageSize= 作品列表(倒序,仅可见作品)
|
||||||
|
* POST /showcase/:id/hide 隐藏作品(is_hidden=1)
|
||||||
|
* POST /showcase/:id/show 恢复作品(is_hidden=0)
|
||||||
|
* GET/POST /announcements 公告管理(含未发布)
|
||||||
|
* DELETE /announcements/:id 删除公告
|
||||||
|
* POST /announcements/:id/publish 发布公告
|
||||||
|
* POST /announcements/:id/unpublish 下架公告
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Router } from "express";
|
||||||
|
import type { NextFunction, Request, Response } from "express";
|
||||||
|
import type { Db, DualSql } from "../db/index.js";
|
||||||
|
import { getDb, dbGet, dbAll, dbRun } from "../db/index.js";
|
||||||
|
import { requireAdmin } from "../auth/middleware.js";
|
||||||
|
import { generateCodes, insertCodes, PACKAGE_DEFINITIONS } from "../codes/service.js";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 常量
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const DEFAULT_PAGE = 1;
|
||||||
|
const DEFAULT_PAGE_SIZE = 20;
|
||||||
|
const MAX_PAGE_SIZE = 100;
|
||||||
|
const MAX_GENERATE_COUNT = 500;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 行类型
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
interface UserListRow {
|
||||||
|
id: string;
|
||||||
|
phone: string;
|
||||||
|
nickname: string | null;
|
||||||
|
role: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OrderListRow {
|
||||||
|
order_no: string;
|
||||||
|
package_name: string;
|
||||||
|
amount_cents: number;
|
||||||
|
payment_method: string;
|
||||||
|
status: string;
|
||||||
|
access_code: string | null;
|
||||||
|
created_at: string;
|
||||||
|
paid_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CodeListRow {
|
||||||
|
code: string;
|
||||||
|
package_type: string;
|
||||||
|
total_uses: number;
|
||||||
|
used_uses: number;
|
||||||
|
status: string;
|
||||||
|
created_at: string;
|
||||||
|
expired_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ShowcaseListRow {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
image_data: string;
|
||||||
|
tags: string;
|
||||||
|
source: string;
|
||||||
|
created_at: string;
|
||||||
|
width: number | null;
|
||||||
|
height: number | null;
|
||||||
|
brand: string | null;
|
||||||
|
materials: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AnnouncementRow {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
body: string;
|
||||||
|
version: string | null;
|
||||||
|
published_at: string;
|
||||||
|
is_published: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 工具函数
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** 解析数据库实例:优先使用注入实例(测试),否则用全局单例。 */
|
||||||
|
function resolveDb(injectedDb?: Db): Db {
|
||||||
|
return injectedDb ?? getDb();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析正整数查询参数;非法回退到 fallback。 */
|
||||||
|
function parsePositiveInt(raw: unknown, fallback: number): number {
|
||||||
|
if (typeof raw !== "string" || raw.trim() === "") return fallback;
|
||||||
|
const n = Number(raw.trim());
|
||||||
|
if (!Number.isInteger(n) || n < 1) return fallback;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析分页参数:page>=1、pageSize 1..100,非法用默认值。 */
|
||||||
|
function parsePagination(
|
||||||
|
pageRaw: unknown,
|
||||||
|
pageSizeRaw: unknown,
|
||||||
|
): { page: number; pageSize: number } {
|
||||||
|
const page = parsePositiveInt(pageRaw, DEFAULT_PAGE);
|
||||||
|
const pageSizeRawN = parsePositiveInt(pageSizeRaw, DEFAULT_PAGE_SIZE);
|
||||||
|
const pageSize = Math.min(pageSizeRawN, MAX_PAGE_SIZE);
|
||||||
|
return { page, pageSize };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析路径参数 :id 为合法正整数。 */
|
||||||
|
function parsePathId(raw: unknown): number | null {
|
||||||
|
if (typeof raw !== "string" || raw.trim() === "") return null;
|
||||||
|
if (!/^[1-9]\d*$/.test(raw.trim())) return null;
|
||||||
|
const n = Number(raw.trim());
|
||||||
|
if (!Number.isSafeInteger(n) || n < 1) return null;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析可选字符串查询参数;null 表示缺省。 */
|
||||||
|
function parseQueryString(raw: unknown): string | null {
|
||||||
|
if (typeof raw !== "string") return null;
|
||||||
|
const trimmed = raw.trim();
|
||||||
|
return trimmed === "" ? null : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 解析 tags JSON 文本为字符串数组。 */
|
||||||
|
function parseTags(raw: string): string[] {
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(raw);
|
||||||
|
if (Array.isArray(parsed)) {
|
||||||
|
return parsed.filter((t): t is string => typeof t === "string");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 脏数据回退为空数组
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造 LIKE 过滤的 DualSql 与参数。
|
||||||
|
* SQLite: WHERE col LIKE ? + ['%kw%']
|
||||||
|
* PG: WHERE col ILIKE $1 + ['%kw%']
|
||||||
|
* 返回 null 当参数缺省。
|
||||||
|
*/
|
||||||
|
function buildLikeFilter(
|
||||||
|
column: string,
|
||||||
|
keyword: string | null,
|
||||||
|
): { whereSqlite: string; wherePg: string; params: string[] } | null {
|
||||||
|
if (keyword === null) return null;
|
||||||
|
return {
|
||||||
|
whereSqlite: ` WHERE ${column} LIKE ?`,
|
||||||
|
wherePg: ` WHERE ${column} ILIKE $1`,
|
||||||
|
params: [`%${keyword}%`],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构造简单条件(等值)过滤的 DualSql 与参数。
|
||||||
|
* SQLite: WHERE col = ?
|
||||||
|
* PG: WHERE col = $1
|
||||||
|
*/
|
||||||
|
function buildEqualsFilter(
|
||||||
|
column: string,
|
||||||
|
value: string | null,
|
||||||
|
): { whereSqlite: string; wherePg: string; params: string[] } | null {
|
||||||
|
if (value === null) return null;
|
||||||
|
return {
|
||||||
|
whereSqlite: ` WHERE ${column} = ?`,
|
||||||
|
wherePg: ` WHERE ${column} = $1`,
|
||||||
|
params: [value],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行分页总数 + 列表查询(DualSql 统一辅助)。
|
||||||
|
* filter 返回 null 表示无过滤条件。
|
||||||
|
* orderBy 为 ORDER BY 及以后片段(含前导空格),如 " ORDER BY created_at DESC"。
|
||||||
|
*/
|
||||||
|
async function fetchPage<T>(
|
||||||
|
db: Db,
|
||||||
|
table: string,
|
||||||
|
columns: string,
|
||||||
|
orderBy: string,
|
||||||
|
filter: { whereSqlite: string; wherePg: string; params: unknown[] } | null,
|
||||||
|
page: number,
|
||||||
|
pageSize: number,
|
||||||
|
): Promise<{ total: number; rows: T[] }> {
|
||||||
|
const hasFilter = filter !== null;
|
||||||
|
const whereSqlite = hasFilter ? filter!.whereSqlite : "";
|
||||||
|
const wherePg = hasFilter ? filter!.wherePg : "";
|
||||||
|
const whereParams = hasFilter ? filter!.params : [];
|
||||||
|
|
||||||
|
// 占位符位次:过滤条件最先(PG 风格 $1/$2...),随后 LIMIT/OFFSET。
|
||||||
|
const pgN = hasFilter ? whereParams.length + 1 : 1;
|
||||||
|
const limitPhPg = `$${pgN}`;
|
||||||
|
const offsetPhPg = `$${pgN + 1}`;
|
||||||
|
|
||||||
|
const countSql: DualSql = {
|
||||||
|
sqlite: `SELECT COUNT(*) AS total FROM ${table}${whereSqlite}`,
|
||||||
|
pg: `SELECT COUNT(*)::int AS total FROM ${table}${wherePg}`,
|
||||||
|
};
|
||||||
|
const totalRow = await dbGet<{ total: number }>(db, countSql, whereParams);
|
||||||
|
const total = totalRow?.total ?? 0;
|
||||||
|
|
||||||
|
const listSql: DualSql = {
|
||||||
|
sqlite: `SELECT ${columns} FROM ${table}${whereSqlite}${orderBy} LIMIT ? OFFSET ?`,
|
||||||
|
pg: `SELECT ${columns} FROM ${table}${wherePg}${orderBy} LIMIT ${limitPhPg} OFFSET ${offsetPhPg}`,
|
||||||
|
};
|
||||||
|
const rows = await dbAll<T>(db, listSql, [...whereParams, pageSize, (page - 1) * pageSize]);
|
||||||
|
return { total, rows };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// createAdminRouter
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createAdminRouter(injectedDb?: Db): Router {
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// requireAdmin 是 async 中间件;Express 4 不自动 catch 返回的 Promise,
|
||||||
|
// 需手包一层捕获 rejection 转发给 next,避免未处理 rejection。
|
||||||
|
router.use((req: Request, res: Response, next: NextFunction): void => {
|
||||||
|
void requireAdmin(req, res, next).catch(next);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** GET /stats — 看板聚合计数。 */
|
||||||
|
router.get("/stats", async (_req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const countSql = (table: string, where = ""): DualSql => {
|
||||||
|
const whereSqlite = where === "" ? "" : ` WHERE ${where}`;
|
||||||
|
const wherePg = where === "" ? "" : ` WHERE ${where}`;
|
||||||
|
return {
|
||||||
|
sqlite: `SELECT COUNT(*) AS total FROM ${table}${whereSqlite}`,
|
||||||
|
pg: `SELECT COUNT(*)::int AS total FROM ${table}${wherePg}`,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const [users, orders, chibiGens, codesRes, activeCodes] = await Promise.all([
|
||||||
|
dbGet<{ total: number }>(db, countSql("users")),
|
||||||
|
dbGet<{ total: number }>(db, countSql("orders")),
|
||||||
|
dbGet<{ total: number }>(db, countSql("chibi_generations")),
|
||||||
|
dbGet<{ total: number }>(db, countSql("codes")),
|
||||||
|
dbGet<{ total: number }>(db, countSql("codes", "status = 'active'")),
|
||||||
|
]);
|
||||||
|
|
||||||
|
res.status(200).json({
|
||||||
|
users: users?.total ?? 0,
|
||||||
|
orders: orders?.total ?? 0,
|
||||||
|
chibiGens: chibiGens?.total ?? 0,
|
||||||
|
codes: codesRes?.total ?? 0,
|
||||||
|
activeCodes: activeCodes?.total ?? 0,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error("GET /api/admin/stats error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** GET /users — 用户列表(phone 过滤 + 分页)。 */
|
||||||
|
router.get("/users", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const { page, pageSize } = parsePagination(req.query["page"], req.query["pageSize"]);
|
||||||
|
const phone = parseQueryString(req.query["phone"]);
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const filter = buildLikeFilter("phone", phone);
|
||||||
|
|
||||||
|
const { total, rows } = await fetchPage<UserListRow>(
|
||||||
|
db,
|
||||||
|
"users",
|
||||||
|
"id, phone, nickname, role, created_at",
|
||||||
|
" ORDER BY created_at DESC",
|
||||||
|
filter,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
);
|
||||||
|
|
||||||
|
const items = rows.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
phone: r.phone,
|
||||||
|
nickname: r.nickname,
|
||||||
|
role: r.role,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
}));
|
||||||
|
res.status(200).json({ total, items });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("GET /api/admin/users error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** POST /users/:id/ban — 封禁。 */
|
||||||
|
router.post("/users/:id/ban", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const id = req.params["id"];
|
||||||
|
if (typeof id !== "string" || id.trim() === "") {
|
||||||
|
res.status(400).json({ error: "用户 ID 无效" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const found = await dbGet<{ id: string }>(
|
||||||
|
db,
|
||||||
|
{ sqlite: "SELECT id FROM users WHERE id = ?", pg: "SELECT id FROM users WHERE id = $1" },
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
if (found === undefined) {
|
||||||
|
res.status(404).json({ error: "用户不存在" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await dbRun(
|
||||||
|
db,
|
||||||
|
{ sqlite: "UPDATE users SET role = 'banned' WHERE id = ?", pg: "UPDATE users SET role = 'banned' WHERE id = $1" },
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
res.status(200).json({ ok: true });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("POST /api/admin/users/:id/ban error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** POST /users/:id/unban — 解封。 */
|
||||||
|
router.post("/users/:id/unban", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const id = req.params["id"];
|
||||||
|
if (typeof id !== "string" || id.trim() === "") {
|
||||||
|
res.status(400).json({ error: "用户 ID 无效" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const found = await dbGet<{ id: string }>(
|
||||||
|
db,
|
||||||
|
{ sqlite: "SELECT id FROM users WHERE id = ?", pg: "SELECT id FROM users WHERE id = $1" },
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
if (found === undefined) {
|
||||||
|
res.status(404).json({ error: "用户不存在" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await dbRun(
|
||||||
|
db,
|
||||||
|
{ sqlite: "UPDATE users SET role = 'user' WHERE id = ?", pg: "UPDATE users SET role = 'user' WHERE id = $1" },
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
res.status(200).json({ ok: true });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("POST /api/admin/users/:id/unban error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** GET /orders — 订单列表(created_at 倒序)。 */
|
||||||
|
router.get("/orders", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const { page, pageSize } = parsePagination(req.query["page"], req.query["pageSize"]);
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
|
||||||
|
const { total, rows } = await fetchPage<OrderListRow>(
|
||||||
|
db,
|
||||||
|
"orders",
|
||||||
|
"order_no, package_name, amount_cents, payment_method, status, access_code, created_at, paid_at",
|
||||||
|
" ORDER BY created_at DESC",
|
||||||
|
null,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
);
|
||||||
|
|
||||||
|
const items = rows.map((r) => ({
|
||||||
|
orderNo: r.order_no,
|
||||||
|
packageName: r.package_name,
|
||||||
|
amountCents: r.amount_cents,
|
||||||
|
paymentMethod: r.payment_method,
|
||||||
|
status: r.status,
|
||||||
|
accessCode: r.access_code,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
paidAt: r.paid_at,
|
||||||
|
}));
|
||||||
|
res.status(200).json({ total, items });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("GET /api/admin/orders error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** GET /codes — 兑换码列表(status 过滤可选)。 */
|
||||||
|
router.get("/codes", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const { page, pageSize } = parsePagination(req.query["page"], req.query["pageSize"]);
|
||||||
|
const status = parseQueryString(req.query["status"]);
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const filter = buildEqualsFilter("status", status);
|
||||||
|
|
||||||
|
const { total, rows } = await fetchPage<CodeListRow>(
|
||||||
|
db,
|
||||||
|
"codes",
|
||||||
|
"code, package_type, total_uses, used_uses, status, created_at, expired_at",
|
||||||
|
" ORDER BY created_at DESC",
|
||||||
|
filter,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
);
|
||||||
|
|
||||||
|
const items = rows.map((r) => ({
|
||||||
|
code: r.code,
|
||||||
|
packageType: r.package_type,
|
||||||
|
totalUses: r.total_uses,
|
||||||
|
usedUses: r.used_uses,
|
||||||
|
status: r.status,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
expiredAt: r.expired_at,
|
||||||
|
}));
|
||||||
|
res.status(200).json({ total, items });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("GET /api/admin/codes error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** POST /codes/generate — 批量生成兑换码。 */
|
||||||
|
router.post("/codes/generate", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||||
|
const packageType = typeof body["packageType"] === "string" ? body["packageType"].trim() : "";
|
||||||
|
if (packageType === "" || !(packageType in PACKAGE_DEFINITIONS)) {
|
||||||
|
res.status(400).json({ error: "套餐类型无效" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let count: number;
|
||||||
|
if (typeof body["count"] === "number") {
|
||||||
|
count = body["count"];
|
||||||
|
} else if (typeof body["count"] === "string" && /^\d+$/.test(body["count"].trim())) {
|
||||||
|
count = Number(body["count"].trim());
|
||||||
|
} else {
|
||||||
|
res.status(400).json({ error: "数量需在 1-500 之间" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!Number.isInteger(count) || count < 1 || count > MAX_GENERATE_COUNT) {
|
||||||
|
res.status(400).json({ error: "数量需在 1-500 之间" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const def = PACKAGE_DEFINITIONS[packageType];
|
||||||
|
if (def === undefined) {
|
||||||
|
res.status(400).json({ error: "套餐类型无效" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const codes = generateCodes(count);
|
||||||
|
await insertCodes(db, codes, packageType, def.uses);
|
||||||
|
res.status(200).json({ codes });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("POST /api/admin/codes/generate error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** GET /showcase — 作品列表(倒序,仅可见)。 */
|
||||||
|
router.get("/showcase", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const { page, pageSize } = parsePagination(req.query["page"], req.query["pageSize"]);
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
// is_hidden 缺省视为 0(旧数据行无该列),隐藏作品不出现在管理作品列表。
|
||||||
|
const filter: { whereSqlite: string; wherePg: string; params: unknown[] } = {
|
||||||
|
whereSqlite: " WHERE is_hidden IS NULL OR is_hidden = 0",
|
||||||
|
wherePg: " WHERE is_hidden IS NULL OR is_hidden = 0",
|
||||||
|
params: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const { total, rows } = await fetchPage<ShowcaseListRow>(
|
||||||
|
db,
|
||||||
|
"showcase_works",
|
||||||
|
"id, title, image_data, tags, source, created_at, width, height, brand, materials",
|
||||||
|
" ORDER BY created_at DESC, id DESC",
|
||||||
|
filter,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
);
|
||||||
|
|
||||||
|
const items = rows.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
title: r.title,
|
||||||
|
imageData: r.image_data,
|
||||||
|
tags: parseTags(r.tags),
|
||||||
|
source: r.source,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
width: r.width,
|
||||||
|
height: r.height,
|
||||||
|
brand: r.brand,
|
||||||
|
materials: r.materials,
|
||||||
|
}));
|
||||||
|
res.status(200).json({ total, items });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("GET /api/admin/showcase error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 隐藏 / 恢复作品(共用实现)。 */
|
||||||
|
async function setShowcaseHiddenFlag(
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
isHidden: 0 | 1,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const id = parsePathId(req.params["id"]);
|
||||||
|
if (id === null) {
|
||||||
|
res.status(400).json({ error: "作品 ID 无效" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const found = await dbGet<{ id: number }>(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite: "SELECT id FROM showcase_works WHERE id = ?",
|
||||||
|
pg: "SELECT id FROM showcase_works WHERE id = $1",
|
||||||
|
},
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
if (found === undefined) {
|
||||||
|
res.status(404).json({ error: "作品不存在" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await dbRun(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite: "UPDATE showcase_works SET is_hidden = ? WHERE id = ?",
|
||||||
|
pg: "UPDATE showcase_works SET is_hidden = $1 WHERE id = $2",
|
||||||
|
},
|
||||||
|
[isHidden, id],
|
||||||
|
);
|
||||||
|
res.status(200).json({ ok: true });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("POST /api/admin/showcase/:id hide/show error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /showcase/:id/hide — 隐藏作品。 */
|
||||||
|
router.post("/showcase/:id/hide", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
await setShowcaseHiddenFlag(req, res, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** POST /showcase/:id/show — 恢复作品。 */
|
||||||
|
router.post("/showcase/:id/show", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
await setShowcaseHiddenFlag(req, res, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** GET /announcements — 全量公告列表(含未发布,倒序)。 */
|
||||||
|
router.get("/announcements", async (_req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const rows = await dbAll<AnnouncementRow>(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite:
|
||||||
|
"SELECT id, title, body, version, published_at, is_published FROM announcements ORDER BY published_at DESC, id DESC",
|
||||||
|
pg:
|
||||||
|
"SELECT id, title, body, version, published_at, is_published FROM announcements ORDER BY published_at DESC, id DESC",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
res.status(200).json(rows);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("GET /api/admin/announcements error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** POST /announcements — 创建公告。 */
|
||||||
|
router.post("/announcements", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||||
|
const title = typeof body["title"] === "string" ? body["title"].trim() : "";
|
||||||
|
if (title === "") {
|
||||||
|
res.status(400).json({ error: "标题不能为空" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const text = typeof body["body"] === "string" ? body["body"] : "";
|
||||||
|
const version =
|
||||||
|
typeof body["version"] === "string" && body["version"].trim() !== ""
|
||||||
|
? body["version"].trim()
|
||||||
|
: null;
|
||||||
|
const isPublished = body["isPublished"] === true ? 1 : 0;
|
||||||
|
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const sql: DualSql = {
|
||||||
|
sqlite:
|
||||||
|
"INSERT INTO announcements (title, body, version, is_published) VALUES (?, ?, ?, ?)",
|
||||||
|
pg: "INSERT INTO announcements (title, body, version, is_published) VALUES ($1, $2, $3, $4)",
|
||||||
|
};
|
||||||
|
await dbRun(db, sql, [title, text, version, isPublished]);
|
||||||
|
|
||||||
|
// 回查刚插入的 id(按标题 + 发布时间倒序取最新一条)。
|
||||||
|
const row = await dbGet<{ id: number }>(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite:
|
||||||
|
"SELECT id FROM announcements WHERE title = ? ORDER BY id DESC LIMIT 1",
|
||||||
|
pg: "SELECT id FROM announcements WHERE title = $1 ORDER BY id DESC LIMIT 1",
|
||||||
|
},
|
||||||
|
[title],
|
||||||
|
);
|
||||||
|
res.status(200).json({ id: row?.id ?? 0 });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("POST /api/admin/announcements error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** DELETE /announcements/:id — 删除公告。 */
|
||||||
|
router.delete("/announcements/:id", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const id = parsePathId(req.params["id"]);
|
||||||
|
if (id === null) {
|
||||||
|
res.status(400).json({ error: "公告 ID 无效" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const found = await dbGet<{ id: number }>(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite: "SELECT id FROM announcements WHERE id = ?",
|
||||||
|
pg: "SELECT id FROM announcements WHERE id = $1",
|
||||||
|
},
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
if (found === undefined) {
|
||||||
|
res.status(404).json({ error: "公告不存在" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await dbRun(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite: "DELETE FROM announcements WHERE id = ?",
|
||||||
|
pg: "DELETE FROM announcements WHERE id = $1",
|
||||||
|
},
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
res.status(200).json({ ok: true });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("DELETE /api/admin/announcements/:id error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 发布 / 下架公告(共用实现)。 */
|
||||||
|
async function setAnnouncementPublished(
|
||||||
|
req: Request,
|
||||||
|
res: Response,
|
||||||
|
isPublished: 0 | 1,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const id = parsePathId(req.params["id"]);
|
||||||
|
if (id === null) {
|
||||||
|
res.status(400).json({ error: "公告 ID 无效" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const found = await dbGet<{ id: number }>(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite: "SELECT id FROM announcements WHERE id = ?",
|
||||||
|
pg: "SELECT id FROM announcements WHERE id = $1",
|
||||||
|
},
|
||||||
|
[id],
|
||||||
|
);
|
||||||
|
if (found === undefined) {
|
||||||
|
res.status(404).json({ error: "公告不存在" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await dbRun(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite: "UPDATE announcements SET is_published = ? WHERE id = ?",
|
||||||
|
pg: "UPDATE announcements SET is_published = $1 WHERE id = $2",
|
||||||
|
},
|
||||||
|
[isPublished, id],
|
||||||
|
);
|
||||||
|
res.status(200).json({ ok: true });
|
||||||
|
} catch (err) {
|
||||||
|
console.error("POST /api/admin/announcements/:id publish/unpublish error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /announcements/:id/publish — 发布。 */
|
||||||
|
router.post("/announcements/:id/publish", async (req: Request, res: Response): Promise<void> => {
|
||||||
|
await setAnnouncementPublished(req, res, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** POST /announcements/:id/unpublish — 下架。 */
|
||||||
|
router.post(
|
||||||
|
"/announcements/:id/unpublish",
|
||||||
|
async (req: Request, res: Response): Promise<void> => {
|
||||||
|
await setAnnouncementPublished(req, res, 0);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// createPublicAnnouncementsRouter(公开公告接口,无需登录)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function createPublicAnnouncementsRouter(injectedDb?: Db): Router {
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
/** GET / — 仅返回已发布公告,按 published_at 倒序。 */
|
||||||
|
router.get("/", async (_req: Request, res: Response): Promise<void> => {
|
||||||
|
try {
|
||||||
|
const db = resolveDb(injectedDb);
|
||||||
|
const rows = await dbAll<AnnouncementRow>(
|
||||||
|
db,
|
||||||
|
{
|
||||||
|
sqlite:
|
||||||
|
"SELECT id, title, body, version, published_at FROM announcements WHERE is_published = 1 ORDER BY published_at DESC, id DESC",
|
||||||
|
pg:
|
||||||
|
"SELECT id, title, body, version, published_at FROM announcements WHERE is_published = 1 ORDER BY published_at DESC, id DESC",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const items = rows.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
title: r.title,
|
||||||
|
body: r.body,
|
||||||
|
version: r.version,
|
||||||
|
publishedAt: r.published_at,
|
||||||
|
}));
|
||||||
|
res.status(200).json(items);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("GET /api/announcements error:", err);
|
||||||
|
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return router;
|
||||||
|
}
|
||||||
@@ -146,6 +146,7 @@ function migrateShowcaseSpecSqlite(db: SqliteDb): void {
|
|||||||
["height", "INTEGER"],
|
["height", "INTEGER"],
|
||||||
["brand", "TEXT"],
|
["brand", "TEXT"],
|
||||||
["materials", "TEXT"],
|
["materials", "TEXT"],
|
||||||
|
["is_hidden", "INTEGER NOT NULL DEFAULT 0"],
|
||||||
];
|
];
|
||||||
for (const [name, declaration] of additions) {
|
for (const [name, declaration] of additions) {
|
||||||
if (!columns.has(name)) {
|
if (!columns.has(name)) {
|
||||||
@@ -170,6 +171,7 @@ async function migrateShowcaseSpecPg(pool: PgDb): Promise<void> {
|
|||||||
["height", "INTEGER"],
|
["height", "INTEGER"],
|
||||||
["brand", "TEXT"],
|
["brand", "TEXT"],
|
||||||
["materials", "TEXT"],
|
["materials", "TEXT"],
|
||||||
|
["is_hidden", "INTEGER NOT NULL DEFAULT 0"],
|
||||||
];
|
];
|
||||||
for (const [name, declaration] of additions) {
|
for (const [name, declaration] of additions) {
|
||||||
if (!columns.has(name)) {
|
if (!columns.has(name)) {
|
||||||
|
|||||||
@@ -116,7 +116,8 @@ CREATE TABLE IF NOT EXISTS showcase_works (
|
|||||||
width INTEGER,
|
width INTEGER,
|
||||||
height INTEGER,
|
height INTEGER,
|
||||||
brand TEXT,
|
brand TEXT,
|
||||||
materials TEXT
|
materials TEXT,
|
||||||
|
is_hidden INTEGER NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
|
|
||||||
-- 索引:按创建时间倒序查询作品列表(Showcase 展示页主路径)
|
-- 索引:按创建时间倒序查询作品列表(Showcase 展示页主路径)
|
||||||
@@ -265,7 +266,8 @@ CREATE TABLE IF NOT EXISTS showcase_works (
|
|||||||
width INTEGER,
|
width INTEGER,
|
||||||
height INTEGER,
|
height INTEGER,
|
||||||
brand TEXT,
|
brand TEXT,
|
||||||
materials TEXT
|
materials TEXT,
|
||||||
|
is_hidden INTEGER NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
|
|
||||||
-- 索引:按创建时间倒序查询作品列表
|
-- 索引:按创建时间倒序查询作品列表
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { createColorChartRouter } from "./color-chart/routes.js";
|
|||||||
import { createShowcaseRouter } from "./showcase/routes.js";
|
import { createShowcaseRouter } from "./showcase/routes.js";
|
||||||
import { createAuthRouter } from "./auth/routes.js";
|
import { createAuthRouter } from "./auth/routes.js";
|
||||||
import { createBeadsRouter } from "./beads/routes.js";
|
import { createBeadsRouter } from "./beads/routes.js";
|
||||||
|
import { createAdminRouter, createPublicAnnouncementsRouter } from "./admin/routes.js";
|
||||||
|
|
||||||
const PORT = parseInt(process.env["PORT"] ?? "8788", 10);
|
const PORT = parseInt(process.env["PORT"] ?? "8788", 10);
|
||||||
|
|
||||||
@@ -66,6 +67,8 @@ export function createApp(db?: Db): Express {
|
|||||||
app.use("/api/showcase", createShowcaseRouter(db));
|
app.use("/api/showcase", createShowcaseRouter(db));
|
||||||
app.use("/api/auth", createAuthRouter(db));
|
app.use("/api/auth", createAuthRouter(db));
|
||||||
app.use("/api/beads", createBeadsRouter(db));
|
app.use("/api/beads", createBeadsRouter(db));
|
||||||
|
app.use("/api/admin", createAdminRouter(db));
|
||||||
|
app.use("/api/announcements", createPublicAnnouncementsRouter(db));
|
||||||
|
|
||||||
// ---- 404 handler ----
|
// ---- 404 handler ----
|
||||||
app.use((_req, res) => {
|
app.use((_req, res) => {
|
||||||
|
|||||||
Reference in new issue
Block a user