feat(admin): add audited Refine staging console
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { Descriptions, Tag, type TableColumnsType } from "antd";
|
||||
|
||||
import { formatAdminDate, ResourceTable } from "@/components/admin/resource-table";
|
||||
|
||||
type AuditRecord = {
|
||||
id: string;
|
||||
actorEmail: string;
|
||||
actorRole: string;
|
||||
action: string;
|
||||
targetId: string;
|
||||
before: Record<string, unknown> | null;
|
||||
after: Record<string, unknown> | null;
|
||||
requestId: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const columns: TableColumnsType<AuditRecord> = [
|
||||
{ title: "操作者", dataIndex: "actorEmail", sorter: true },
|
||||
{ title: "角色", dataIndex: "actorRole", render: (value) => <Tag>{value}</Tag> },
|
||||
{ title: "动作", dataIndex: "action", sorter: true },
|
||||
{ title: "目标 ID", dataIndex: "targetId" },
|
||||
{ title: "Request ID", dataIndex: "requestId" },
|
||||
{ title: "时间", dataIndex: "createdAt", sorter: true, render: formatAdminDate },
|
||||
];
|
||||
|
||||
export default function AuditLogsPage() {
|
||||
return <ResourceTable<AuditRecord>
|
||||
resource="audit-logs"
|
||||
title="审计日志(只读)"
|
||||
columns={columns}
|
||||
statusOptions={[
|
||||
{ label: "生成兑换码", value: "redemption_code.create" },
|
||||
{ label: "修改兑换码", value: "redemption_code.update" },
|
||||
{ label: "撤销兑换码", value: "redemption_code.revoke" },
|
||||
]}
|
||||
extra={<Descriptions size="small" items={[{ key: "policy", label: "策略", children: "仅保存脱敏前后值;日志只追加" }]} />}
|
||||
/>;
|
||||
}
|
||||
@@ -1,200 +1,167 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { FormEvent, useEffect, useRef, useState } from "react";
|
||||
import { useCreate, useDelete, useGetIdentity, usePermissions, useUpdate } from "@refinedev/core";
|
||||
import { Button, DatePicker, Form, Input, InputNumber, Modal, Space, Tag, Typography, type TableColumnsType } from "antd";
|
||||
import dayjs from "dayjs";
|
||||
import { useState } from "react";
|
||||
|
||||
import { formatAdminDate, ResourceTable } from "@/components/admin/resource-table";
|
||||
import type { AdminIdentity } from "@/lib/admin/providers";
|
||||
|
||||
type CodeRecord = {
|
||||
id: string;
|
||||
code?: string;
|
||||
mask: string;
|
||||
credits: number;
|
||||
expiresAt: string | null;
|
||||
redeemedBy: string | null;
|
||||
redeemedEmail: string | null;
|
||||
redeemedAt: string | null;
|
||||
note: string | null;
|
||||
createdAt: string;
|
||||
redeemedEmail: string | null;
|
||||
redeemedAt: string | null;
|
||||
revokedAt: string | null;
|
||||
status: "available" | "expired" | "redeemed" | "revoked";
|
||||
};
|
||||
type GeneratedCode = { code: string; credits: number; expiresAt: string | null };
|
||||
|
||||
const previewCodes: CodeRecord[] = [
|
||||
{ id: "preview-1", mask: "JYOT-••••-7Q9K", credits: 12, expiresAt: "2026-12-31T15:59:00.000Z", redeemedBy: null, redeemedEmail: null, redeemedAt: null, note: "秋季体验", createdAt: "2026-07-16T02:20:00.000Z" },
|
||||
{ id: "preview-2", mask: "JYOT-••••-2M8A", credits: 6, expiresAt: null, redeemedBy: "preview-user", redeemedEmail: "linyao@example.com", redeemedAt: "2026-07-15T08:30:00.000Z", note: "访谈用户", createdAt: "2026-07-14T03:10:00.000Z" },
|
||||
{ id: "preview-3", mask: "JYOT-••••-4D1R", credits: 20, expiresAt: "2026-07-01T15:59:00.000Z", redeemedBy: null, redeemedEmail: null, redeemedAt: null, note: null, createdAt: "2026-06-10T06:45:00.000Z" },
|
||||
];
|
||||
type CreateValues = {
|
||||
credits: number;
|
||||
count: number;
|
||||
expiresAt?: ReturnType<typeof dayjs>;
|
||||
note?: string;
|
||||
};
|
||||
type EditValues = { note?: string; expiresAt?: ReturnType<typeof dayjs> | null };
|
||||
|
||||
const dateFormatter = new Intl.DateTimeFormat("zh-CN", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
timeZone: "Asia/Taipei",
|
||||
});
|
||||
const statusColors: Record<CodeRecord["status"], string> = {
|
||||
available: "green",
|
||||
expired: "orange",
|
||||
redeemed: "blue",
|
||||
revoked: "red",
|
||||
};
|
||||
|
||||
function apiMessage(payload: unknown, fallback: string) {
|
||||
if (!payload || typeof payload !== "object") return fallback;
|
||||
const data = payload as Record<string, unknown>;
|
||||
return [data.message, data.error].find((value) => typeof value === "string") as string || fallback;
|
||||
}
|
||||
export default function CodesPage() {
|
||||
const { data: role } = usePermissions<"admin" | "viewer">({});
|
||||
const { data: identity } = useGetIdentity<AdminIdentity>();
|
||||
const { mutate: createCodes, mutation: createMutation } = useCreate<{ id: string; generated: CodeRecord[] }>();
|
||||
const { mutate: updateCode, mutation: updateMutation } = useUpdate<CodeRecord>();
|
||||
const { mutate: revokeCode, mutation: revokeMutation } = useDelete<CodeRecord>();
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editRecord, setEditRecord] = useState<CodeRecord | null>(null);
|
||||
const [generated, setGenerated] = useState<CodeRecord[]>([]);
|
||||
const [createForm] = Form.useForm<CreateValues>();
|
||||
const [editForm] = Form.useForm<EditValues>();
|
||||
const writable = role === "admin";
|
||||
|
||||
function redirectForAuth(response: Response) {
|
||||
if (response.status === 401) window.location.assign("/login");
|
||||
if (response.status === 403) window.location.assign("/");
|
||||
}
|
||||
|
||||
function codeStatus(code: CodeRecord) {
|
||||
if (code.redeemedAt) return "已兑换";
|
||||
if (code.expiresAt && new Date(code.expiresAt).getTime() <= Date.now()) return "已过期";
|
||||
return "可用";
|
||||
}
|
||||
|
||||
function formatDate(value: string | null) {
|
||||
return value ? dateFormatter.format(new Date(value)) : "—";
|
||||
}
|
||||
|
||||
export default function AdminCodesPage() {
|
||||
const [codes, setCodes] = useState<CodeRecord[]>([]);
|
||||
const [generated, setGenerated] = useState<GeneratedCode[]>([]);
|
||||
const [credits, setCredits] = useState(10);
|
||||
const [count, setCount] = useState(1);
|
||||
const [expiresAt, setExpiresAt] = useState("");
|
||||
const [note, setNote] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const previewMode = useRef(false);
|
||||
const [error, setError] = useState("");
|
||||
const [copyNotice, setCopyNotice] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (process.env.NODE_ENV === "development" && new URLSearchParams(window.location.search).get("preview") === "admin") {
|
||||
const previewFrame = window.requestAnimationFrame(() => {
|
||||
previewMode.current = true;
|
||||
setCodes(previewCodes);
|
||||
setLoading(false);
|
||||
});
|
||||
return () => window.cancelAnimationFrame(previewFrame);
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
void fetch("/api/admin/codes", { signal: controller.signal, cache: "no-store" })
|
||||
.then(async (response) => {
|
||||
redirectForAuth(response);
|
||||
const payload = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new Error(apiMessage(payload, "暂时无法读取兑换码"));
|
||||
setCodes((payload as { codes: CodeRecord[] }).codes);
|
||||
})
|
||||
.catch((caught) => {
|
||||
if ((caught as Error).name !== "AbortError") setError(caught instanceof Error ? caught.message : "暂时无法读取兑换码");
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
|
||||
async function reloadCodes() {
|
||||
const response = await fetch("/api/admin/codes", { cache: "no-store" });
|
||||
redirectForAuth(response);
|
||||
const payload = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new Error(apiMessage(payload, "暂时无法刷新兑换码"));
|
||||
setCodes((payload as { codes: CodeRecord[] }).codes);
|
||||
function submitCreate(values: CreateValues) {
|
||||
createCodes({
|
||||
resource: "codes",
|
||||
values: {
|
||||
credits: values.credits,
|
||||
count: values.count,
|
||||
expiresAt: values.expiresAt?.toISOString() ?? null,
|
||||
note: values.note?.trim() || null,
|
||||
},
|
||||
successNotification: false,
|
||||
}, {
|
||||
onSuccess(result) {
|
||||
setGenerated(result.data.generated);
|
||||
setCreateOpen(false);
|
||||
createForm.resetFields();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function createCodes(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (creating) return;
|
||||
setCreating(true);
|
||||
setError("");
|
||||
setGenerated([]);
|
||||
setCopyNotice("");
|
||||
if (process.env.NODE_ENV === "development" && previewMode.current) {
|
||||
setGenerated(Array.from({ length: count }, (_, index) => ({
|
||||
code: `PREVIEW-${String(index + 1).padStart(2, "0")}-JYOTISH`,
|
||||
credits,
|
||||
expiresAt: expiresAt ? new Date(expiresAt).toISOString() : null,
|
||||
})));
|
||||
setCreating(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch("/api/admin/codes", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
credits,
|
||||
count,
|
||||
...(expiresAt ? { expiresAt: new Date(expiresAt).toISOString() } : {}),
|
||||
...(note.trim() ? { note: note.trim() } : {}),
|
||||
}),
|
||||
});
|
||||
redirectForAuth(response);
|
||||
const payload = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new Error(apiMessage(payload, "生成兑换码失败"));
|
||||
setGenerated((payload as { codes: GeneratedCode[] }).codes);
|
||||
await reloadCodes();
|
||||
} catch (caught) {
|
||||
setError(caught instanceof Error ? caught.message : "生成兑换码失败");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
function submitEdit(values: EditValues) {
|
||||
if (!editRecord) return;
|
||||
updateCode({
|
||||
resource: "codes",
|
||||
id: editRecord.id,
|
||||
values: {
|
||||
note: values.note?.trim() || null,
|
||||
expiresAt: values.expiresAt?.toISOString() ?? null,
|
||||
},
|
||||
}, { onSuccess: () => setEditRecord(null) });
|
||||
}
|
||||
|
||||
async function copy(text: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopyNotice("已复制到剪贴板");
|
||||
} catch {
|
||||
setCopyNotice("无法自动复制,请手动选择兑换码");
|
||||
}
|
||||
function confirmRevoke(record: CodeRecord) {
|
||||
Modal.confirm({
|
||||
title: "撤销此兑换码?",
|
||||
content: `${record.mask} 撤销后不可兑换,且不能恢复。`,
|
||||
okText: "确认撤销",
|
||||
okButtonProps: { danger: true },
|
||||
cancelText: "取消",
|
||||
onOk: () => new Promise<void>((resolve, reject) => {
|
||||
revokeCode({ resource: "codes", id: record.id }, {
|
||||
onSuccess: () => resolve(),
|
||||
onError: () => reject(new Error("撤销失败")),
|
||||
});
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const columns: TableColumnsType<CodeRecord> = [
|
||||
{ title: "兑换码", dataIndex: "mask" },
|
||||
{ title: "点数", dataIndex: "credits", sorter: true },
|
||||
{ title: "状态", dataIndex: "status", sorter: true, render: (value) => <Tag color={statusColors[value as CodeRecord["status"]]}>{value}</Tag> },
|
||||
{ title: "到期时间", dataIndex: "expiresAt", sorter: true, render: formatAdminDate },
|
||||
{ title: "备注", dataIndex: "note", render: (value) => value || "—" },
|
||||
{ title: "兑换账户", dataIndex: "redeemedEmail", render: (value) => value || "—" },
|
||||
{ title: "兑换时间", dataIndex: "redeemedAt", render: formatAdminDate },
|
||||
{ title: "撤销时间", dataIndex: "revokedAt", render: formatAdminDate },
|
||||
{ title: "创建时间", dataIndex: "createdAt", sorter: true, render: formatAdminDate },
|
||||
{
|
||||
title: "操作",
|
||||
fixed: "right",
|
||||
render: (_, record) => writable && record.status !== "redeemed" && record.status !== "revoked" ? (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => {
|
||||
setEditRecord(record);
|
||||
editForm.setFieldsValue({
|
||||
note: record.note ?? undefined,
|
||||
expiresAt: record.expiresAt ? dayjs(record.expiresAt) : null,
|
||||
});
|
||||
}}>编辑</Button>
|
||||
<Button danger size="small" loading={revokeMutation.isPending} onClick={() => confirmRevoke(record)}>撤销</Button>
|
||||
</Space>
|
||||
) : "—",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<main className="standalone-page admin-page">
|
||||
<header className="admin-header">
|
||||
<h1>兑换码管理</h1>
|
||||
<Link className="button-secondary" href="/">返回对话</Link>
|
||||
</header>
|
||||
<>
|
||||
<ResourceTable<CodeRecord>
|
||||
resource="codes"
|
||||
title={`兑换码${identity ? ` · ${identity.email} (${identity.role})` : ""}`}
|
||||
columns={columns}
|
||||
statusOptions={[
|
||||
{ label: "可用", value: "available" },
|
||||
{ label: "已过期", value: "expired" },
|
||||
{ label: "已兑换", value: "redeemed" },
|
||||
{ label: "已撤销", value: "revoked" },
|
||||
]}
|
||||
extra={writable ? <Button type="primary" onClick={() => setCreateOpen(true)}>批量生成</Button> : <Tag>viewer 只读</Tag>}
|
||||
/>
|
||||
|
||||
<div className="admin-scroll">
|
||||
<section className="admin-section" aria-labelledby="create-codes-title">
|
||||
<div className="section-title"><div><h2 id="create-codes-title">生成兑换码</h2><p>完整兑换码只在本次生成结果中显示,<span className="phrase-nowrap">请立即复制保存。</span></p></div></div>
|
||||
<form className="code-form" onSubmit={createCodes}>
|
||||
<label><span>每个点数</span><input type="number" min={1} required value={credits} onChange={(event) => setCredits(Number(event.target.value))} /></label>
|
||||
<label><span>生成数量</span><input type="number" min={1} max={100} required value={count} onChange={(event) => setCount(Number(event.target.value))} /></label>
|
||||
<label><span>有效期 <em>可选</em></span><input type="datetime-local" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} /></label>
|
||||
<label className="note-field"><span>备注 <em>可选</em></span><input maxLength={200} value={note} onChange={(event) => setNote(event.target.value)} placeholder="例如:7 月活动" /></label>
|
||||
<button className="button-primary" type="submit" disabled={creating || credits < 1 || count < 1 || count > 100}>{creating ? "生成中" : "生成"}</button>
|
||||
</form>
|
||||
{error && <p className="form-error" role="alert">{error}</p>}
|
||||
</section>
|
||||
<Modal title="批量生成兑换码" open={createOpen} onCancel={() => setCreateOpen(false)} footer={null} destroyOnHidden>
|
||||
<Form form={createForm} layout="vertical" initialValues={{ credits: 10, count: 1 }} onFinish={submitCreate}>
|
||||
<Form.Item name="credits" label="每个点数" rules={[{ required: true }]}><InputNumber min={1} max={1_000_000} style={{ width: "100%" }} /></Form.Item>
|
||||
<Form.Item name="count" label="数量" rules={[{ required: true }]}><InputNumber min={1} max={100} style={{ width: "100%" }} /></Form.Item>
|
||||
<Form.Item name="expiresAt" label="到期时间"><DatePicker showTime style={{ width: "100%" }} /></Form.Item>
|
||||
<Form.Item name="note" label="备注"><Input maxLength={500} /></Form.Item>
|
||||
<Button block type="primary" htmlType="submit" loading={createMutation.isPending}>生成</Button>
|
||||
</Form>
|
||||
</Modal>
|
||||
|
||||
{generated.length > 0 && (
|
||||
<section className="admin-section generated-section" aria-labelledby="generated-title">
|
||||
<div className="section-title">
|
||||
<div><h2 id="generated-title">本次生成的完整码</h2><p>离开或刷新页面后将不再显示。</p></div>
|
||||
<button className="button-secondary" type="button" onClick={() => void copy(generated.map((item) => item.code).join("\n"))}>复制全部</button>
|
||||
</div>
|
||||
<div className="generated-list">
|
||||
{generated.map((item) => (
|
||||
<div key={item.code}><code>{item.code}</code><span>{item.credits} 点</span><button type="button" onClick={() => void copy(item.code)}>复制</button></div>
|
||||
))}
|
||||
</div>
|
||||
{copyNotice && <p className="form-success" role="status">{copyNotice}</p>}
|
||||
</section>
|
||||
)}
|
||||
<Modal title="完整兑换码(仅显示本次)" open={generated.length > 0} onCancel={() => setGenerated([])} footer={<Button onClick={() => setGenerated([])}>我已保存</Button>}>
|
||||
<Typography.Paragraph type="warning">关闭后无法再次查看完整兑换码,请立即安全保存。</Typography.Paragraph>
|
||||
{generated.map((record) => <Typography.Paragraph copyable key={record.code}><Typography.Text code>{record.code}</Typography.Text></Typography.Paragraph>)}
|
||||
</Modal>
|
||||
|
||||
<section className="admin-section" aria-labelledby="codes-list-title">
|
||||
<div className="section-title"><div><h2 id="codes-list-title">兑换码状态</h2><p>{loading ? "正在读取…" : `${codes.length} 条记录`}</p></div></div>
|
||||
<div className="admin-table-wrap">
|
||||
<table className="admin-table">
|
||||
<thead><tr><th>兑换码</th><th>点数</th><th>状态</th><th>有效期</th><th>兑换账户</th><th>兑换时间</th><th>备注</th><th>创建时间</th></tr></thead>
|
||||
<tbody>
|
||||
{codes.map((code) => (
|
||||
<tr key={code.id}>
|
||||
<td><code>{code.mask}</code></td><td>{code.credits}</td><td><span className={`code-status status-${codeStatus(code)}`}>{codeStatus(code)}</span></td><td>{formatDate(code.expiresAt)}</td><td>{code.redeemedEmail || code.redeemedBy || "—"}</td><td>{formatDate(code.redeemedAt)}</td><td>{code.note || "—"}</td><td>{formatDate(code.createdAt)}</td>
|
||||
</tr>
|
||||
))}
|
||||
{!loading && codes.length === 0 && <tr><td colSpan={8} className="empty-cell">尚未生成兑换码</td></tr>}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
<Modal title="编辑未兑换码" open={Boolean(editRecord)} onCancel={() => setEditRecord(null)} footer={null} destroyOnHidden>
|
||||
<Form form={editForm} layout="vertical" onFinish={submitEdit}>
|
||||
<Form.Item name="expiresAt" label="到期时间"><DatePicker showTime style={{ width: "100%" }} /></Form.Item>
|
||||
<Form.Item name="note" label="备注"><Input maxLength={500} /></Form.Item>
|
||||
<Button block type="primary" htmlType="submit" loading={updateMutation.isPending}>保存</Button>
|
||||
</Form>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { Tag, type TableColumnsType } from "antd";
|
||||
|
||||
import { formatAdminDate, ResourceTable } from "@/components/admin/resource-table";
|
||||
|
||||
type ConsultationRecord = {
|
||||
id: string;
|
||||
email: string | null;
|
||||
requestId: string;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
const colors: Record<string, string> = {
|
||||
reserved: "gold",
|
||||
completed: "green",
|
||||
cancelled: "default",
|
||||
};
|
||||
const columns: TableColumnsType<ConsultationRecord> = [
|
||||
{ title: "用户", dataIndex: "email", render: (value) => value || "—" },
|
||||
{ title: "请求 ID", dataIndex: "requestId" },
|
||||
{ title: "状态", dataIndex: "status", sorter: true, render: (value) => <Tag color={colors[value]}>{value}</Tag> },
|
||||
{ title: "创建时间", dataIndex: "createdAt", sorter: true, render: formatAdminDate },
|
||||
{ title: "更新时间", dataIndex: "updatedAt", sorter: true, render: formatAdminDate },
|
||||
];
|
||||
|
||||
export default function ConsultationsPage() {
|
||||
return <ResourceTable<ConsultationRecord>
|
||||
resource="consultations"
|
||||
title="咨询请求(只读)"
|
||||
columns={columns}
|
||||
statusOptions={[
|
||||
{ label: "已预扣", value: "reserved" },
|
||||
{ label: "已完成", value: "completed" },
|
||||
{ label: "已取消", value: "cancelled" },
|
||||
]}
|
||||
/>;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { Tag, type TableColumnsType } from "antd";
|
||||
|
||||
import { formatAdminDate, ResourceTable } from "@/components/admin/resource-table";
|
||||
|
||||
type TransactionRecord = {
|
||||
id: string;
|
||||
email: string | null;
|
||||
type: string;
|
||||
amount: number;
|
||||
balanceAfter: number;
|
||||
requestId: string;
|
||||
model: string | null;
|
||||
inputTokens: number | null;
|
||||
outputTokens: number | null;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
const columns: TableColumnsType<TransactionRecord> = [
|
||||
{ title: "用户", dataIndex: "email", render: (value) => value || "—" },
|
||||
{ title: "类型", dataIndex: "type", sorter: true, render: (value) => <Tag>{value}</Tag> },
|
||||
{ title: "变动", dataIndex: "amount", sorter: true, render: (value) => value > 0 ? `+${value}` : value },
|
||||
{ title: "余额", dataIndex: "balanceAfter", sorter: true },
|
||||
{ title: "请求 ID", dataIndex: "requestId" },
|
||||
{ title: "模型", dataIndex: "model", render: (value) => value || "—" },
|
||||
{ title: "输入/输出 token", render: (_, row) => `${row.inputTokens ?? "—"} / ${row.outputTokens ?? "—"}` },
|
||||
{ title: "时间", dataIndex: "createdAt", sorter: true, render: formatAdminDate },
|
||||
];
|
||||
|
||||
export default function CreditTransactionsPage() {
|
||||
return <ResourceTable<TransactionRecord>
|
||||
resource="credit-transactions"
|
||||
title="积分流水(只读)"
|
||||
columns={columns}
|
||||
statusOptions={[
|
||||
{ label: "兑换", value: "redeem" },
|
||||
{ label: "预扣", value: "reserve" },
|
||||
{ label: "退款", value: "refund" },
|
||||
]}
|
||||
/>;
|
||||
}
|
||||
@@ -1,18 +1,11 @@
|
||||
import { ReactNode } from "react";
|
||||
import { redirect } from "next/navigation";
|
||||
import { isAdminEmail } from "@/lib/supabase/admin";
|
||||
import { createServerSupabaseClient } from "@/lib/supabase/server";
|
||||
import "@refinedev/antd/dist/reset.css";
|
||||
import "antd/dist/reset.css";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { AdminApp } from "@/components/admin/admin-app";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AdminLayout({ children }: { children: ReactNode }) {
|
||||
if (process.env.NODE_ENV === "development" && process.env.ENABLE_ADMIN_PREVIEW === "1") return children;
|
||||
|
||||
const supabase = await createServerSupabaseClient();
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
|
||||
if (!user) redirect("/login");
|
||||
if (!isAdminEmail(user.email)) redirect("/");
|
||||
|
||||
return children;
|
||||
export default function AdminLayout({ children }: { children: ReactNode }) {
|
||||
return <AdminApp>{children}</AdminApp>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function AdminPage() {
|
||||
redirect("/admin/codes");
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { Tag, type TableColumnsType } from "antd";
|
||||
|
||||
import { formatAdminDate, ResourceTable } from "@/components/admin/resource-table";
|
||||
|
||||
type UserRecord = {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
role: string;
|
||||
emailVerified: boolean;
|
||||
banned: boolean;
|
||||
createdAt: string;
|
||||
credits: number;
|
||||
birthDate: string | null;
|
||||
birthTimeStatus: string | null;
|
||||
birthPlace: string | null;
|
||||
};
|
||||
|
||||
const columns: TableColumnsType<UserRecord> = [
|
||||
{ title: "邮箱", dataIndex: "email", sorter: true },
|
||||
{ title: "姓名", dataIndex: "name", sorter: true, render: (value) => value || "—" },
|
||||
{ title: "角色", dataIndex: "role", render: (value) => <Tag>{value}</Tag> },
|
||||
{ title: "积分", dataIndex: "credits", sorter: true },
|
||||
{ title: "出生日期", dataIndex: "birthDate", render: (value) => value || "—" },
|
||||
{ title: "出生时间状态", dataIndex: "birthTimeStatus", render: (value) => value || "—" },
|
||||
{ title: "出生地", dataIndex: "birthPlace", render: (value) => value || "—" },
|
||||
{ title: "邮箱验证", dataIndex: "emailVerified", render: (value) => value ? "已验证" : "未验证" },
|
||||
{ title: "状态", dataIndex: "banned", render: (value) => value ? <Tag color="red">已禁用</Tag> : <Tag color="green">正常</Tag> },
|
||||
{ title: "注册时间", dataIndex: "createdAt", sorter: true, render: formatAdminDate },
|
||||
];
|
||||
|
||||
export default function UsersPage() {
|
||||
return <ResourceTable<UserRecord> resource="users" title="用户资料(只读)" columns={columns} />;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { requireAdminSession } from "@/lib/admin/auth";
|
||||
import { pageOffset, queryAdminRows } from "@/lib/admin/database";
|
||||
import {
|
||||
adminErrorResponse,
|
||||
invalidQueryResponse,
|
||||
parseListQuery,
|
||||
readonlyAdminMutation,
|
||||
} from "@/lib/admin/http";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
type AuditRow = {
|
||||
id: string;
|
||||
actor_user_id: string;
|
||||
actor_email: string;
|
||||
actor_role: string;
|
||||
action: string;
|
||||
target_type: string;
|
||||
target_id: string;
|
||||
before_value: Record<string, unknown> | null;
|
||||
after_value: Record<string, unknown> | null;
|
||||
request_id: string;
|
||||
created_at: Date;
|
||||
total_count: string;
|
||||
};
|
||||
|
||||
const sortColumns = new Map([
|
||||
["createdAt", "a.created_at"],
|
||||
["action", "a.action"],
|
||||
["actorEmail", "a.actor_email"],
|
||||
]);
|
||||
|
||||
export const POST = readonlyAdminMutation;
|
||||
export const PUT = readonlyAdminMutation;
|
||||
export const PATCH = readonlyAdminMutation;
|
||||
export const DELETE = readonlyAdminMutation;
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
await requireAdminSession();
|
||||
const parsed = parseListQuery(request);
|
||||
if (!parsed.success) return invalidQueryResponse(parsed.error.flatten());
|
||||
const { page, pageSize, sort, order, q, status } = parsed.data;
|
||||
const values: unknown[] = [];
|
||||
const conditions: string[] = [];
|
||||
if (q) {
|
||||
values.push(`%${q}%`);
|
||||
conditions.push(`(a.actor_email ilike $${values.length} or a.request_id ilike $${values.length})`);
|
||||
}
|
||||
if (status) {
|
||||
values.push(status);
|
||||
conditions.push(`a.action = $${values.length}`);
|
||||
}
|
||||
values.push(pageSize, pageOffset(page, pageSize));
|
||||
const sortColumn = sortColumns.get(sort ?? "createdAt") ?? "a.created_at";
|
||||
const rows = await queryAdminRows<AuditRow>(`
|
||||
select a.*, count(*) over()::text as total_count
|
||||
from audit.admin_audit_logs a
|
||||
${conditions.length ? `where ${conditions.join(" and ")}` : ""}
|
||||
order by ${sortColumn} ${order === "asc" ? "asc" : "desc"}, a.id asc
|
||||
limit $${values.length - 1} offset $${values.length}
|
||||
`, values);
|
||||
return NextResponse.json({
|
||||
data: rows.map((row) => ({
|
||||
id: row.id,
|
||||
actorUserId: row.actor_user_id,
|
||||
actorEmail: row.actor_email,
|
||||
actorRole: row.actor_role,
|
||||
action: row.action,
|
||||
targetType: row.target_type,
|
||||
targetId: row.target_id,
|
||||
before: row.before_value,
|
||||
after: row.after_value,
|
||||
requestId: row.request_id,
|
||||
createdAt: row.created_at.toISOString(),
|
||||
})),
|
||||
total: Number(rows[0]?.total_count ?? 0),
|
||||
});
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { requireAdminSession } from "@/lib/admin/auth";
|
||||
import { runCodeRpc } from "@/lib/admin/codes";
|
||||
import {
|
||||
adminErrorResponse,
|
||||
invalidQueryResponse,
|
||||
requestId,
|
||||
} from "@/lib/admin/http";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const paramsSchema = z.object({ id: z.string().uuid() });
|
||||
const updateCodeSchema = z.object({
|
||||
note: z.string().trim().max(500).nullable().optional(),
|
||||
expiresAt: z.string().datetime({ offset: true }).nullable().optional(),
|
||||
}).refine((value) => "note" in value || "expiresAt" in value, {
|
||||
message: "至少提供一个可修改字段",
|
||||
});
|
||||
|
||||
export async function PATCH(
|
||||
request: Request,
|
||||
context: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const session = await requireAdminSession("write");
|
||||
const parsedParams = paramsSchema.safeParse(await context.params);
|
||||
const parsedBody = updateCodeSchema.safeParse(await request.json().catch(() => null));
|
||||
if (!parsedParams.success || !parsedBody.success) {
|
||||
return invalidQueryResponse();
|
||||
}
|
||||
const body = parsedBody.data;
|
||||
const rows = await runCodeRpc(
|
||||
"admin_update_redemption_code",
|
||||
session,
|
||||
requestId(request),
|
||||
{
|
||||
p_code_id: parsedParams.data.id,
|
||||
p_set_note: "note" in body,
|
||||
p_note: body.note ?? null,
|
||||
p_set_expires_at: "expiresAt" in body,
|
||||
p_expires_at: body.expiresAt ?? null,
|
||||
},
|
||||
);
|
||||
return NextResponse.json({ data: rows[0] });
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
context: { params: Promise<{ id: string }> },
|
||||
) {
|
||||
try {
|
||||
const session = await requireAdminSession("write");
|
||||
const parsed = paramsSchema.safeParse(await context.params);
|
||||
if (!parsed.success) return invalidQueryResponse();
|
||||
const rows = await runCodeRpc(
|
||||
"admin_revoke_redemption_code",
|
||||
session,
|
||||
requestId(request),
|
||||
{ p_code_id: parsed.data.id },
|
||||
);
|
||||
return NextResponse.json({ data: rows[0] });
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -1,113 +1,143 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import { requireAdminSession } from "@/lib/admin/auth";
|
||||
import { mapCode, runCodeRpc, type RedemptionCodeRecord } from "@/lib/admin/codes";
|
||||
import { pageOffset, queryAdminRows } from "@/lib/admin/database";
|
||||
import {
|
||||
createAdminSupabaseClient,
|
||||
isAdminEmail,
|
||||
} from "@/lib/supabase/admin";
|
||||
adminErrorResponse,
|
||||
invalidQueryResponse,
|
||||
parseListQuery,
|
||||
requestId,
|
||||
} from "@/lib/admin/http";
|
||||
import {
|
||||
generateRedeemCode,
|
||||
hashRedeemCode,
|
||||
maskRedeemCode,
|
||||
} from "@/lib/supabase/codes";
|
||||
import {
|
||||
isSupabaseConfigurationError,
|
||||
SupabaseConfigurationError,
|
||||
} from "@/lib/supabase/config";
|
||||
import { createServerSupabaseClient } from "@/lib/supabase/server";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const createCodesSchema = z.object({
|
||||
credits: z.number().int().positive().max(1_000_000),
|
||||
count: z.number().int().min(1).max(100),
|
||||
expiresAt: z.string().datetime({ offset: true }).optional(),
|
||||
note: z.string().trim().max(500).optional(),
|
||||
expiresAt: z.string().datetime({ offset: true }).nullable().optional(),
|
||||
note: z.string().trim().max(500).nullable().optional(),
|
||||
});
|
||||
|
||||
async function requireAdmin() {
|
||||
if (!process.env.ADMIN_EMAILS?.trim()) {
|
||||
throw new SupabaseConfigurationError(["ADMIN_EMAILS"]);
|
||||
}
|
||||
type CodeRow = {
|
||||
id: string;
|
||||
code_mask: string;
|
||||
credits: number;
|
||||
expires_at: Date | null;
|
||||
note: string | null;
|
||||
created_at: Date;
|
||||
redeemed_by: string | null;
|
||||
redeemed_email: string | null;
|
||||
redeemed_at: Date | null;
|
||||
revoked_by: string | null;
|
||||
revoked_at: Date | null;
|
||||
total_count: string;
|
||||
};
|
||||
|
||||
const supabase = await createServerSupabaseClient();
|
||||
const { data: { user }, error } = await supabase.auth.getUser();
|
||||
if (error || !user) return { response: NextResponse.json({ error: "请先登录" }, { status: 401 }) };
|
||||
if (!isAdminEmail(user.email)) {
|
||||
return { response: NextResponse.json({ error: "无管理员权限" }, { status: 403 }) };
|
||||
}
|
||||
return { user };
|
||||
const sortColumns = new Map([
|
||||
["createdAt", "c.created_at"],
|
||||
["expiresAt", "c.expires_at"],
|
||||
["credits", "c.credits"],
|
||||
["status", "status"],
|
||||
]);
|
||||
|
||||
function serializedCodeRow(row: CodeRow) {
|
||||
return mapCode({
|
||||
...row,
|
||||
expires_at: row.expires_at?.toISOString() ?? null,
|
||||
created_at: row.created_at.toISOString(),
|
||||
redeemed_at: row.redeemed_at?.toISOString() ?? null,
|
||||
revoked_at: row.revoked_at?.toISOString() ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const auth = await requireAdmin();
|
||||
if ("response" in auth) return auth.response;
|
||||
|
||||
const admin = createAdminSupabaseClient();
|
||||
const { data, error } = await admin
|
||||
.from("redemption_codes")
|
||||
.select("id,code_mask,credits,expires_at,note,created_at,redeemed_by,redeemed_email,redeemed_at")
|
||||
.order("created_at", { ascending: false })
|
||||
.limit(100);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: "暂时无法读取兑换码列表" }, { status: 500 });
|
||||
await requireAdminSession();
|
||||
const parsed = parseListQuery(request);
|
||||
if (!parsed.success) return invalidQueryResponse(parsed.error.flatten());
|
||||
const { page, pageSize, sort, order, q, status } = parsed.data;
|
||||
const values: unknown[] = [];
|
||||
const conditions: string[] = [];
|
||||
if (q) {
|
||||
values.push(`%${q}%`);
|
||||
conditions.push(`(c.code_mask ilike $${values.length} or c.note ilike $${values.length})`);
|
||||
}
|
||||
|
||||
if (status && ["available", "expired", "redeemed", "revoked"].includes(status)) {
|
||||
const clauses = {
|
||||
available: "c.redeemed_at is null and c.revoked_at is null and (c.expires_at is null or c.expires_at > now())",
|
||||
expired: "c.redeemed_at is null and c.revoked_at is null and c.expires_at <= now()",
|
||||
redeemed: "c.redeemed_at is not null",
|
||||
revoked: "c.revoked_at is not null",
|
||||
};
|
||||
conditions.push(clauses[status as keyof typeof clauses]);
|
||||
}
|
||||
values.push(pageSize, pageOffset(page, pageSize));
|
||||
const sortColumn = sortColumns.get(sort ?? "createdAt") ?? "c.created_at";
|
||||
const rows = await queryAdminRows<CodeRow>(`
|
||||
select c.id, c.code_mask, c.credits, c.expires_at, c.note,
|
||||
c.created_at, c.redeemed_by, c.redeemed_email, c.redeemed_at,
|
||||
c.revoked_by, c.revoked_at,
|
||||
case
|
||||
when c.redeemed_at is not null then 'redeemed'
|
||||
when c.revoked_at is not null then 'revoked'
|
||||
when c.expires_at is not null and c.expires_at <= now() then 'expired'
|
||||
else 'available'
|
||||
end as status,
|
||||
count(*) over()::text as total_count
|
||||
from public.redemption_codes c
|
||||
${conditions.length ? `where ${conditions.join(" and ")}` : ""}
|
||||
order by ${sortColumn} ${order === "asc" ? "asc" : "desc"}, c.id asc
|
||||
limit $${values.length - 1} offset $${values.length}
|
||||
`, values);
|
||||
return NextResponse.json({
|
||||
codes: data.map((code) => ({
|
||||
id: code.id,
|
||||
mask: code.code_mask,
|
||||
credits: code.credits,
|
||||
expiresAt: code.expires_at,
|
||||
note: code.note,
|
||||
createdAt: code.created_at,
|
||||
redeemedBy: code.redeemed_by,
|
||||
redeemedEmail: code.redeemed_email,
|
||||
redeemedAt: code.redeemed_at,
|
||||
})),
|
||||
data: rows.map(serializedCodeRow),
|
||||
total: Number(rows[0]?.total_count ?? 0),
|
||||
});
|
||||
} catch (error) {
|
||||
if (isSupabaseConfigurationError(error)) {
|
||||
return NextResponse.json({ error: "Supabase 或管理员白名单尚未配置", code: "SUPABASE_NOT_CONFIGURED" }, { status: 503 });
|
||||
}
|
||||
return NextResponse.json({ error: "兑换码管理服务暂时不可用" }, { status: 500 });
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const auth = await requireAdmin();
|
||||
if ("response" in auth) return auth.response;
|
||||
|
||||
const session = await requireAdminSession("write");
|
||||
const parsed = createCodesSchema.safeParse(await request.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "兑换码参数不正确" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { credits, count, expiresAt, note } = parsed.data;
|
||||
const codes = Array.from({ length: count }, generateRedeemCode);
|
||||
const admin = createAdminSupabaseClient();
|
||||
const { error } = await admin.from("redemption_codes").insert(codes.map((code) => ({
|
||||
code_hash: hashRedeemCode(code),
|
||||
code_mask: maskRedeemCode(code),
|
||||
credits,
|
||||
expires_at: expiresAt ?? null,
|
||||
note: note || null,
|
||||
created_by: auth.user.id,
|
||||
})));
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: "生成兑换码失败,请重试" }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!parsed.success) return invalidQueryResponse(parsed.error.flatten());
|
||||
const plainCodes = Array.from({ length: parsed.data.count }, generateRedeemCode);
|
||||
const records = plainCodes.map((code) => ({
|
||||
codeHash: hashRedeemCode(code),
|
||||
codeMask: maskRedeemCode(code),
|
||||
credits: parsed.data.credits,
|
||||
expiresAt: parsed.data.expiresAt ?? null,
|
||||
note: parsed.data.note || null,
|
||||
}));
|
||||
const operationRequestId = requestId(request);
|
||||
const stored = await runCodeRpc(
|
||||
"admin_create_redemption_codes",
|
||||
session,
|
||||
operationRequestId,
|
||||
{ p_codes: records },
|
||||
);
|
||||
const byMask = new Map<string, RedemptionCodeRecord>(
|
||||
stored.map((record) => [record.mask, record]),
|
||||
);
|
||||
return NextResponse.json({
|
||||
codes: codes.map((code) => ({ code, credits, expiresAt: expiresAt ?? null, note: note || null })),
|
||||
data: {
|
||||
id: operationRequestId,
|
||||
generated: plainCodes.map((code) => ({
|
||||
...(byMask.get(maskRedeemCode(code)) ?? {}),
|
||||
code,
|
||||
})),
|
||||
},
|
||||
}, { status: 201 });
|
||||
} catch (error) {
|
||||
if (isSupabaseConfigurationError(error)) {
|
||||
return NextResponse.json({ error: "Supabase 或管理员白名单尚未配置", code: "SUPABASE_NOT_CONFIGURED" }, { status: 503 });
|
||||
}
|
||||
return NextResponse.json({ error: "兑换码管理服务暂时不可用" }, { status: 500 });
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { requireAdminSession } from "@/lib/admin/auth";
|
||||
import { pageOffset, queryAdminRows } from "@/lib/admin/database";
|
||||
import {
|
||||
adminErrorResponse,
|
||||
invalidQueryResponse,
|
||||
parseListQuery,
|
||||
readonlyAdminMutation,
|
||||
} from "@/lib/admin/http";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
type ConsultationRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
email: string | null;
|
||||
request_id: string;
|
||||
status: string;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
total_count: string;
|
||||
};
|
||||
|
||||
const sortColumns = new Map([
|
||||
["createdAt", "c.created_at"],
|
||||
["updatedAt", "c.updated_at"],
|
||||
["status", "c.status"],
|
||||
]);
|
||||
|
||||
export const POST = readonlyAdminMutation;
|
||||
export const PUT = readonlyAdminMutation;
|
||||
export const PATCH = readonlyAdminMutation;
|
||||
export const DELETE = readonlyAdminMutation;
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
await requireAdminSession();
|
||||
const parsed = parseListQuery(request);
|
||||
if (!parsed.success) return invalidQueryResponse(parsed.error.flatten());
|
||||
const { page, pageSize, sort, order, q, status } = parsed.data;
|
||||
const values: unknown[] = [];
|
||||
const conditions: string[] = [];
|
||||
if (q) {
|
||||
values.push(`%${q}%`);
|
||||
conditions.push(`(p.email ilike $${values.length} or c.request_id ilike $${values.length})`);
|
||||
}
|
||||
if (status && ["reserved", "completed", "cancelled"].includes(status)) {
|
||||
values.push(status);
|
||||
conditions.push(`c.status = $${values.length}`);
|
||||
}
|
||||
values.push(pageSize, pageOffset(page, pageSize));
|
||||
const sortColumn = sortColumns.get(sort ?? "createdAt") ?? "c.created_at";
|
||||
const rows = await queryAdminRows<ConsultationRow>(`
|
||||
select c.user_id || ':' || c.request_id as id, c.user_id, p.email,
|
||||
c.request_id, c.status, c.created_at, c.updated_at,
|
||||
count(*) over()::text as total_count
|
||||
from public.consultation_requests c
|
||||
left join public.profiles p on p.id = c.user_id
|
||||
${conditions.length ? `where ${conditions.join(" and ")}` : ""}
|
||||
order by ${sortColumn} ${order === "asc" ? "asc" : "desc"}, c.request_id asc
|
||||
limit $${values.length - 1} offset $${values.length}
|
||||
`, values);
|
||||
return NextResponse.json({
|
||||
data: rows.map((row) => ({
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
email: row.email,
|
||||
requestId: row.request_id,
|
||||
status: row.status,
|
||||
createdAt: row.created_at.toISOString(),
|
||||
updatedAt: row.updated_at.toISOString(),
|
||||
})),
|
||||
total: Number(rows[0]?.total_count ?? 0),
|
||||
});
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { requireAdminSession } from "@/lib/admin/auth";
|
||||
import { pageOffset, queryAdminRows } from "@/lib/admin/database";
|
||||
import {
|
||||
adminErrorResponse,
|
||||
invalidQueryResponse,
|
||||
parseListQuery,
|
||||
readonlyAdminMutation,
|
||||
} from "@/lib/admin/http";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
type TransactionRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
email: string | null;
|
||||
transaction_type: string;
|
||||
amount: number;
|
||||
balance_after: number;
|
||||
request_id: string;
|
||||
model: string | null;
|
||||
input_tokens: number | null;
|
||||
output_tokens: number | null;
|
||||
created_at: Date;
|
||||
total_count: string;
|
||||
};
|
||||
|
||||
const sortColumns = new Map([
|
||||
["createdAt", "t.created_at"],
|
||||
["amount", "t.amount"],
|
||||
["balanceAfter", "t.balance_after"],
|
||||
["type", "t.transaction_type"],
|
||||
]);
|
||||
|
||||
export const POST = readonlyAdminMutation;
|
||||
export const PUT = readonlyAdminMutation;
|
||||
export const PATCH = readonlyAdminMutation;
|
||||
export const DELETE = readonlyAdminMutation;
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
await requireAdminSession();
|
||||
const parsed = parseListQuery(request);
|
||||
if (!parsed.success) return invalidQueryResponse(parsed.error.flatten());
|
||||
const { page, pageSize, sort, order, q, status } = parsed.data;
|
||||
const values: unknown[] = [];
|
||||
const conditions: string[] = [];
|
||||
if (q) {
|
||||
values.push(`%${q}%`);
|
||||
conditions.push(`(p.email ilike $${values.length} or t.request_id ilike $${values.length})`);
|
||||
}
|
||||
if (status && ["redeem", "reserve", "refund"].includes(status)) {
|
||||
values.push(status);
|
||||
conditions.push(`t.transaction_type = $${values.length}`);
|
||||
}
|
||||
values.push(pageSize, pageOffset(page, pageSize));
|
||||
const sortColumn = sortColumns.get(sort ?? "createdAt") ?? "t.created_at";
|
||||
const rows = await queryAdminRows<TransactionRow>(`
|
||||
select t.id, t.user_id, p.email, t.transaction_type, t.amount,
|
||||
t.balance_after, t.request_id, t.model, t.input_tokens,
|
||||
t.output_tokens, t.created_at, count(*) over()::text as total_count
|
||||
from public.credit_transactions t
|
||||
left join public.profiles p on p.id = t.user_id
|
||||
${conditions.length ? `where ${conditions.join(" and ")}` : ""}
|
||||
order by ${sortColumn} ${order === "asc" ? "asc" : "desc"}, t.id asc
|
||||
limit $${values.length - 1} offset $${values.length}
|
||||
`, values);
|
||||
return NextResponse.json({
|
||||
data: rows.map((row) => ({
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
email: row.email,
|
||||
type: row.transaction_type,
|
||||
amount: row.amount,
|
||||
balanceAfter: row.balance_after,
|
||||
requestId: row.request_id,
|
||||
model: row.model,
|
||||
inputTokens: row.input_tokens,
|
||||
outputTokens: row.output_tokens,
|
||||
createdAt: row.created_at.toISOString(),
|
||||
})),
|
||||
total: Number(rows[0]?.total_count ?? 0),
|
||||
});
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { requireAdminSession } from "@/lib/admin/auth";
|
||||
import { adminErrorResponse } from "@/lib/admin/http";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const { user, role } = await requireAdminSession();
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { requireAdminSession } from "@/lib/admin/auth";
|
||||
import { pageOffset, queryAdminRows } from "@/lib/admin/database";
|
||||
import {
|
||||
adminErrorResponse,
|
||||
invalidQueryResponse,
|
||||
parseListQuery,
|
||||
readonlyAdminMutation,
|
||||
} from "@/lib/admin/http";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
type UserRow = {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string | null;
|
||||
role: string;
|
||||
email_verified: boolean;
|
||||
banned: boolean;
|
||||
created_at: Date;
|
||||
credits: number;
|
||||
birth_date: string | null;
|
||||
birth_time_status: string | null;
|
||||
birth_place_label: string | null;
|
||||
total_count: string;
|
||||
};
|
||||
|
||||
const sortColumns = new Map([
|
||||
["createdAt", "u.created_at"],
|
||||
["email", "u.email"],
|
||||
["credits", "p.credits"],
|
||||
["name", "u.name"],
|
||||
]);
|
||||
|
||||
export const POST = readonlyAdminMutation;
|
||||
export const PUT = readonlyAdminMutation;
|
||||
export const PATCH = readonlyAdminMutation;
|
||||
export const DELETE = readonlyAdminMutation;
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
await requireAdminSession();
|
||||
const parsed = parseListQuery(request);
|
||||
if (!parsed.success) return invalidQueryResponse(parsed.error.flatten());
|
||||
const { page, pageSize, sort, order, q } = parsed.data;
|
||||
const values: unknown[] = [];
|
||||
const conditions: string[] = [];
|
||||
if (q) {
|
||||
values.push(`%${q}%`);
|
||||
conditions.push(`(u.email ilike $${values.length} or u.name ilike $${values.length})`);
|
||||
}
|
||||
values.push(pageSize, pageOffset(page, pageSize));
|
||||
const sortColumn = sortColumns.get(sort ?? "createdAt") ?? "u.created_at";
|
||||
const rows = await queryAdminRows<UserRow>(`
|
||||
select
|
||||
u.id, u.email, u.name, u.role, u.email_verified, u.banned,
|
||||
u.created_at, p.credits, p.birth_date, p.birth_time_status,
|
||||
p.birth_place_label, count(*) over()::text as total_count
|
||||
from identity.users u
|
||||
join public.profiles p on p.id = u.id
|
||||
${conditions.length ? `where ${conditions.join(" and ")}` : ""}
|
||||
order by ${sortColumn} ${order === "asc" ? "asc" : "desc"}, u.id asc
|
||||
limit $${values.length - 1} offset $${values.length}
|
||||
`, values);
|
||||
return NextResponse.json({
|
||||
data: rows.map((row) => ({
|
||||
id: row.id,
|
||||
email: row.email,
|
||||
name: row.name,
|
||||
role: row.role,
|
||||
emailVerified: row.email_verified,
|
||||
banned: row.banned,
|
||||
createdAt: row.created_at.toISOString(),
|
||||
credits: row.credits,
|
||||
birthDate: row.birth_date,
|
||||
birthTimeStatus: row.birth_time_status,
|
||||
birthPlace: row.birth_place_label,
|
||||
})),
|
||||
total: Number(rows[0]?.total_count ?? 0),
|
||||
});
|
||||
} catch (error) {
|
||||
return adminErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ const redeemErrors: Record<string, { status: number; message: string }> = {
|
||||
unauthorized: { status: 401, message: "请先登录" },
|
||||
invalid_code: { status: 404, message: "兑换码不存在" },
|
||||
expired_code: { status: 410, message: "兑换码已过期" },
|
||||
revoked_code: { status: 410, message: "兑换码已撤销" },
|
||||
already_redeemed: { status: 409, message: "兑换码已被使用" },
|
||||
profile_missing: { status: 500, message: "账户资料不存在,请稍后重试" },
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user