feat(admin): add audited Refine staging console
This commit is contained in:
@@ -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