Implement ops operational closure

This commit is contained in:
2569718930@qq.com
2026-06-23 17:07:25 +08:00
parent 24415ee427
commit 0c76874418
27 changed files with 2196 additions and 24 deletions
+47
View File
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { buildProxyExceptionResponse } from "@/lib/api-proxy";
import {
applyAuthResponseCookies,
buildBackendRequestHeaders,
} from "@/lib/backend-auth";
import { requireOpsProxyAuth } from "@/lib/ops-proxy-auth";
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
export async function GET(req: NextRequest) {
if (!API_BASE) {
return NextResponse.json(
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
{ status: 500 },
);
}
try {
const auth = await buildBackendRequestHeaders(req);
const authError = requireOpsProxyAuth(req, auth);
if (authError) return authError;
const upstream = new URL(`${API_BASE}/api/ops/audit-log`);
req.nextUrl.searchParams.forEach((value, key) => {
upstream.searchParams.set(key, value);
});
const res = await fetch(upstream.toString(), {
cache: "no-store",
headers: auth.headers,
});
const raw = await res.text();
const response = new NextResponse(raw, {
status: res.status,
headers: {
"Cache-Control": "no-store",
"Content-Type": res.headers.get("content-type") || "application/json",
},
});
return applyAuthResponseCookies(response, auth.response);
} catch (error) {
return buildProxyExceptionResponse(error, {
publicMessage: "Failed to fetch ops audit log",
});
}
}
@@ -22,8 +22,9 @@ export async function GET(req: NextRequest) {
if (authError) return authError;
const url = new URL(`${API_BASE}/api/ops/payments/incidents`);
const limit = req.nextUrl.searchParams.get("limit");
if (limit) url.searchParams.set("limit", limit);
req.nextUrl.searchParams.forEach((value, key) => {
url.searchParams.set(key, value);
});
const res = await fetch(url.toString(), {
headers: auth.headers,
@@ -0,0 +1,53 @@
import { NextRequest, NextResponse } from "next/server";
import { buildProxyExceptionResponse } from "@/lib/api-proxy";
import {
applyAuthResponseCookies,
buildBackendRequestHeaders,
buildJsonBackendRequestHeaders,
} from "@/lib/backend-auth";
import { requireOpsProxyAuth } from "@/lib/ops-proxy-auth";
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
export async function PATCH(
req: NextRequest,
{ params }: { params: Promise<{ caseId: string }> },
) {
if (!API_BASE) {
return NextResponse.json(
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
{ status: 500 },
);
}
try {
const auth = await buildBackendRequestHeaders(req);
const authError = requireOpsProxyAuth(req, auth);
if (authError) return authError;
const resolved = await params;
const body = await req.text();
const res = await fetch(
`${API_BASE}/api/ops/refunds/${encodeURIComponent(resolved.caseId)}`,
{
method: "PATCH",
cache: "no-store",
headers: buildJsonBackendRequestHeaders(auth.headers),
body,
},
);
const raw = await res.text();
const response = new NextResponse(raw, {
status: res.status,
headers: {
"Cache-Control": "no-store",
"Content-Type": res.headers.get("content-type") || "application/json",
},
});
return applyAuthResponseCookies(response, auth.response);
} catch (error) {
return buildProxyExceptionResponse(error, {
publicMessage: "Failed to update refund case",
});
}
}
+84
View File
@@ -0,0 +1,84 @@
import { NextRequest, NextResponse } from "next/server";
import { buildProxyExceptionResponse } from "@/lib/api-proxy";
import {
applyAuthResponseCookies,
buildBackendRequestHeaders,
buildJsonBackendRequestHeaders,
} from "@/lib/backend-auth";
import { requireOpsProxyAuth } from "@/lib/ops-proxy-auth";
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
export async function GET(req: NextRequest) {
if (!API_BASE) {
return NextResponse.json(
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
{ status: 500 },
);
}
try {
const auth = await buildBackendRequestHeaders(req);
const authError = requireOpsProxyAuth(req, auth);
if (authError) return authError;
const upstream = new URL(`${API_BASE}/api/ops/refunds`);
req.nextUrl.searchParams.forEach((value, key) => {
upstream.searchParams.set(key, value);
});
const res = await fetch(upstream.toString(), {
cache: "no-store",
headers: auth.headers,
});
const raw = await res.text();
const response = new NextResponse(raw, {
status: res.status,
headers: {
"Cache-Control": "no-store",
"Content-Type": res.headers.get("content-type") || "application/json",
},
});
return applyAuthResponseCookies(response, auth.response);
} catch (error) {
return buildProxyExceptionResponse(error, {
publicMessage: "Failed to fetch refund cases",
});
}
}
export async function POST(req: NextRequest) {
if (!API_BASE) {
return NextResponse.json(
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
{ status: 500 },
);
}
try {
const auth = await buildBackendRequestHeaders(req);
const authError = requireOpsProxyAuth(req, auth);
if (authError) return authError;
const body = await req.text();
const res = await fetch(`${API_BASE}/api/ops/refunds`, {
method: "POST",
cache: "no-store",
headers: buildJsonBackendRequestHeaders(auth.headers),
body,
});
const raw = await res.text();
const response = new NextResponse(raw, {
status: res.status,
headers: {
"Cache-Control": "no-store",
"Content-Type": res.headers.get("content-type") || "application/json",
},
});
return applyAuthResponseCookies(response, auth.response);
} catch (error) {
return buildProxyExceptionResponse(error, {
publicMessage: "Failed to create refund case",
});
}
}
+5
View File
@@ -0,0 +1,5 @@
import { AuditLogPageClient } from "@/components/ops/audit/AuditLogPageClient";
export default function OpsAuditLogPage() {
return <AuditLogPageClient />;
}
@@ -70,6 +70,17 @@ import { getTurnstileTokenForAction } from "@/lib/turnstile-client";
// --- Main Component ---
function pointSourceLabel(source?: string, isEn = false) {
const key = String(source || "").trim().toLowerCase();
if (key === "feedback_reward") return isEn ? "Feedback reward" : "反馈奖励";
if (key === "ops_manual_grant") return isEn ? "Ops manual grant" : "后台补发";
if (key === "paid_referral") return isEn ? "Paid referral" : "有效付费邀请";
if (key === "growth_milestone_reward") return isEn ? "Growth reward" : "增长奖励";
if (key === "points_redemption") return isEn ? "Payment redemption" : "支付抵扣";
if (key === "ops_subscription_deduction") return isEn ? "Ops deduction" : "后台订阅扣分";
return key || (isEn ? "Unknown source" : "未知来源");
}
export function AccountCenter() {
const router = useRouter();
const searchParams = useSearchParams();
@@ -535,6 +546,9 @@ export function AccountCenter() {
const monthlyReferralPointsLimit = Number.isFinite(monthlyReferralPointsLimitRaw)
? Math.max(0, monthlyReferralPointsLimitRaw)
: monthlyReferralLimit * referralRewardPoints;
const pointsLedger = backend?.points_ledger;
const pointSourceRows = Object.entries(pointsLedger?.by_source ?? {});
const recentPointEvents = pointsLedger?.recent ?? [];
// ── Telegram bind command ──────────────────────────────
const bindCommand = telegramBindCommand || copy.telegramBindCommandPlaceholder;
@@ -897,6 +911,64 @@ export function AccountCenter() {
</div>
)}
<section className="lg:col-span-12 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
<div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
<h3 className="flex items-center gap-2 text-lg font-bold text-slate-950">
<Coins size={20} className="text-yellow-500" />
{isEn ? "Point Sources" : "积分来源"}
</h3>
<span className="text-xs font-semibold text-slate-500">
{isEn ? "Current balance" : "当前余额"} {Number(pointsLedger?.balance ?? totalPoints).toLocaleString()}
</span>
</div>
{pointSourceRows.length === 0 && recentPointEvents.length === 0 ? (
<p className="mt-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-xs text-slate-500">
{copy.pointsRule}
</p>
) : (
<div className="mt-4 grid gap-4 lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]">
<div className="grid gap-2 sm:grid-cols-2">
{pointSourceRows.map(([source, item]) => (
<div key={source} className="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3">
<div className="text-xs font-bold text-slate-600">
{pointSourceLabel(source, isEn)}
</div>
<div className="mt-1 text-lg font-black text-slate-950">
{Number(item?.points ?? 0).toLocaleString()}
</div>
<div className="mt-0.5 text-[11px] text-slate-500">
{Number(item?.count ?? 0).toLocaleString()} {isEn ? "events" : "笔记录"} · {source}
</div>
</div>
))}
</div>
<div className="rounded-xl border border-slate-200">
<div className="border-b border-slate-200 px-4 py-2 text-xs font-bold uppercase text-slate-500">
{isEn ? "Recent point ledger" : "最近积分流水"}
</div>
<div className="divide-y divide-slate-100">
{recentPointEvents.slice(0, 5).map((event, index) => (
<div key={`${event.id ?? index}-${event.source}`} className="grid grid-cols-[minmax(0,1fr)_auto] gap-3 px-4 py-2 text-sm">
<div className="min-w-0">
<div className="truncate font-semibold text-slate-800">
{pointSourceLabel(event.source, isEn)}
</div>
<div className="mt-0.5 truncate text-[11px] text-slate-500">
{event.reference_type || "ledger"} · {event.created_at ? formatTime(event.created_at, locale) : "--"}
</div>
</div>
<div className={`font-mono font-bold ${Number(event.delta_points ?? 0) >= 0 ? "text-emerald-600" : "text-red-600"}`}>
{Number(event.delta_points ?? 0) >= 0 ? "+" : ""}
{Number(event.delta_points ?? 0).toLocaleString()}
</div>
</div>
))}
</div>
</div>
</div>
)}
</section>
{/* Subscription Info & Paywall */}
<div className="lg:col-span-12 relative">
<div
@@ -0,0 +1,29 @@
import fs from "node:fs";
import path from "node:path";
function assert(condition: unknown, message: string) {
if (!condition) throw new Error(message);
}
export function runTests() {
const projectRoot = process.cwd();
const types = fs.readFileSync(path.join(projectRoot, "components", "account", "types.ts"), "utf8");
const accountCenter = fs.readFileSync(
path.join(projectRoot, "components", "account", "AccountCenter.tsx"),
"utf8",
);
assert(
types.includes("points_ledger") &&
types.includes("PointsLedgerSummary") &&
types.includes("PointsLedgerEntry"),
"auth/me account types must include points ledger summary and entries",
);
assert(
accountCenter.includes("points_ledger") &&
accountCenter.includes("积分来源") &&
accountCenter.includes("feedback_reward") &&
accountCenter.includes("ops_manual_grant"),
"account center must display point source explainability from auth/me",
);
}
+19
View File
@@ -3,6 +3,7 @@ export type AuthMeResponse = {
user_id?: string | null;
email?: string | null;
points?: number;
points_ledger?: PointsLedgerSummary;
weekly_points?: number;
weekly_rank?: number | string | null;
entitlement_mode?: string | null;
@@ -25,6 +26,24 @@ export type AuthMeResponse = {
entitlement_snapshot_reason?: string | null;
};
export type PointsLedgerEntry = {
id?: number;
source?: string;
delta_points?: number;
balance_after?: number;
actor_email?: string;
reference_type?: string;
reference_id?: string;
metadata?: Record<string, unknown>;
created_at?: string;
};
export type PointsLedgerSummary = {
balance?: number;
recent?: PointsLedgerEntry[];
by_source?: Record<string, { points?: number; count?: number }>;
};
export type ReferralSummary = {
code?: string;
discount_usdc?: string;
@@ -239,6 +239,72 @@
line-height: 1.75;
}
.searchWrap {
display: flex;
align-items: center;
gap: 10px;
max-width: 620px;
min-height: 42px;
margin-top: 18px;
padding: 0 12px;
border: 1px solid #cbd5e1;
border-radius: 8px;
background: #ffffff;
color: #64748b;
}
.searchInput {
min-width: 0;
width: 100%;
border: 0;
outline: 0;
background: transparent;
color: #0f172a;
font-size: 0.94rem;
font-weight: 650;
}
.searchInput::placeholder {
color: #94a3b8;
}
.searchResults {
display: grid;
gap: 8px;
max-width: 720px;
margin-top: 10px;
}
.searchResult,
.searchEmpty {
display: grid;
gap: 3px;
padding: 10px 12px;
border: 1px solid #dbeafe;
border-radius: 8px;
background: #f8fbff;
color: #1d4ed8;
text-decoration: none;
}
.searchResult span {
color: #0f172a;
font-size: 0.9rem;
font-weight: 850;
}
.searchResult small,
.searchEmpty {
color: #64748b;
font-size: 0.78rem;
line-height: 1.45;
}
.searchResult:hover {
border-color: #93c5fd;
background: #eff6ff;
}
.pageMeta {
display: flex;
flex-wrap: wrap;
+72 -1
View File
@@ -4,7 +4,7 @@ import Link from "next/link";
import { useMemo, useState } from "react";
import { usePathname } from "next/navigation";
import clsx from "clsx";
import { ArrowLeft, BookOpen, Menu } from "lucide-react";
import { ArrowLeft, BookOpen, Menu, Search } from "lucide-react";
import styles from "./DocsLayout.module.css";
import {
DocsLocale,
@@ -171,8 +171,49 @@ export function DocsScreen({ page }: { page: DocsPage }) {
const pathname = usePathname();
const { locale } = useI18n();
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const localizedPage = useMemo(() => page.content[locale], [locale, page]);
const currentSlug = pathname?.split("/").filter(Boolean).at(-1) || page.slug;
const searchResults = useMemo(() => {
const query = searchQuery.trim().toLowerCase();
if (!query) return [];
return DOCS_PAGES.flatMap((doc) => {
const content = doc.content[locale];
const sectionText = content.sections
.flatMap((section) => [
section.title,
...section.blocks.flatMap((block) => {
if (block.type === "paragraph") return [block.text];
if (block.type === "callout") return [block.title || "", block.text];
if (block.type === "bullets" || block.type === "steps") return block.items;
if (block.type === "link") return [block.label, block.caption || ""];
if (block.type === "image") return [block.alt, block.caption || ""];
return [];
}),
])
.join(" ");
const haystack = `${content.title} ${content.description} ${sectionText}`.toLowerCase();
if (!haystack.includes(query)) return [];
const matchedSection =
content.sections.find((section) => section.title.toLowerCase().includes(query)) ||
content.sections.find((section) =>
section.blocks.some((block) => {
if (block.type === "paragraph") return block.text.toLowerCase().includes(query);
if (block.type === "callout") return `${block.title || ""} ${block.text}`.toLowerCase().includes(query);
if (block.type === "bullets" || block.type === "steps") return block.items.join(" ").toLowerCase().includes(query);
return false;
}),
) ||
content.sections[0];
return [{
slug: doc.slug,
title: content.title,
description: content.description,
sectionId: matchedSection?.id,
sectionTitle: matchedSection?.title,
}];
}).slice(0, 8);
}, [locale, searchQuery]);
return (
<div className={styles.docsShell}>
@@ -198,6 +239,36 @@ export function DocsScreen({ page }: { page: DocsPage }) {
</div>
<h1 className={styles.pageTitle}>{localizedPage.title}</h1>
<p className={styles.pageDescription}>{localizedPage.description}</p>
<div className={styles.searchWrap}>
<Search size={16} aria-hidden="true" />
<input
className={styles.searchInput}
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder={locale === "zh-CN" ? "搜索文档、章节或关键词" : "Search docs, sections, or keywords"}
aria-label={locale === "zh-CN" ? "搜索文档" : "Search docs"}
/>
</div>
{searchQuery.trim() ? (
<div className={styles.searchResults}>
{searchResults.length === 0 ? (
<div className={styles.searchEmpty}>
{locale === "zh-CN" ? "没有匹配文档" : "No matching docs"}
</div>
) : (
searchResults.map((result) => (
<Link
key={`${result.slug}-${result.sectionId || "top"}`}
href={`/docs/${result.slug}${result.sectionId ? `#${result.sectionId}` : ""}`}
className={styles.searchResult}
>
<span>{result.title}</span>
<small>{result.sectionTitle || result.description}</small>
</Link>
))
)}
</div>
) : null}
<div className={styles.pageMeta} aria-label={locale === "zh-CN" ? "文档范围" : "Document scope"}>
<span>{locale === "zh-CN" ? "当前工作台" : "Current terminal"}</span>
<span>{locale === "zh-CN" ? `${DOCS_PAGES.length} 篇文档` : `${DOCS_PAGES.length} docs`}</span>
@@ -0,0 +1,33 @@
import fs from "node:fs";
import path from "node:path";
function assert(condition: unknown, message: string) {
if (!condition) throw new Error(message);
}
export function runTests() {
const projectRoot = process.cwd();
const source = fs.readFileSync(
path.join(projectRoot, "components", "docs", "DocsScreen.tsx"),
"utf8",
);
const css = fs.readFileSync(
path.join(projectRoot, "components", "docs", "DocsLayout.module.css"),
"utf8",
);
assert(
source.includes("Search") &&
source.includes("searchQuery") &&
source.includes("searchResults") &&
source.includes("DOCS_PAGES.flatMap") &&
source.includes("block.type === \"paragraph\""),
"docs screen must build a local search index from page titles, sections, and paragraph text",
);
assert(
css.includes(".searchWrap") &&
css.includes(".searchInput") &&
css.includes(".searchResults"),
"docs layout must style the search input and result list",
);
}
@@ -0,0 +1,58 @@
import fs from "node:fs";
import path from "node:path";
function assert(condition: unknown, message: string) {
if (!condition) throw new Error(message);
}
export function runTests() {
const projectRoot = process.cwd();
const opsApi = fs.readFileSync(path.join(projectRoot, "lib", "ops-api.ts"), "utf8");
const opsTypes = fs.readFileSync(path.join(projectRoot, "types", "ops.ts"), "utf8");
const sidebar = fs.readFileSync(
path.join(projectRoot, "components", "ops", "layout", "AdminSidebar.tsx"),
"utf8",
);
const paymentsPage = fs.readFileSync(
path.join(projectRoot, "components", "ops", "payments", "PaymentsPageClient.tsx"),
"utf8",
);
assert(
opsApi.includes("auditLog(") &&
opsApi.includes("/api/ops/audit-log") &&
opsApi.includes("refunds(") &&
opsApi.includes("/api/ops/refunds") &&
opsApi.includes("updateRefund("),
"ops API client must expose audit log and refund case endpoints",
);
assert(
opsTypes.includes("OpsAuditEvent") &&
opsTypes.includes("RefundCase") &&
opsTypes.includes("refund_case_id") &&
opsTypes.includes("refund_status"),
"ops types must model audit events, refund cases, and incident refund metadata",
);
assert(
sidebar.includes("/ops/audit-log") && sidebar.includes("审计日志"),
"ops sidebar must expose the unified audit log page",
);
assert(
paymentsPage.includes("退款工单") &&
paymentsPage.includes("refund_case_id") &&
paymentsPage.includes("refund_status") &&
paymentsPage.includes("opsApi.refunds"),
"ops payment page must surface refund cases next to payment incidents",
);
const auditRoute = path.join(projectRoot, "app", "api", "ops", "audit-log", "route.ts");
const refundsRoute = path.join(projectRoot, "app", "api", "ops", "refunds", "route.ts");
const refundUpdateRoute = path.join(projectRoot, "app", "api", "ops", "refunds", "[caseId]", "route.ts");
for (const route of [auditRoute, refundsRoute, refundUpdateRoute]) {
const source = fs.readFileSync(route, "utf8");
assert(
source.includes("requireOpsProxyAuth") && source.includes("no-store"),
`${path.basename(path.dirname(route))} ops proxy route must be admin-protected and uncached`,
);
}
}
@@ -0,0 +1,110 @@
"use client";
import { useEffect, useState } from "react";
import { RefreshCcw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { opsApi } from "@/lib/ops-api";
import type { OpsAuditEvent } from "@/types/ops";
function compactDate(value?: string) {
if (!value) return "--";
return value.slice(0, 19).replace("T", " ");
}
function actionLabel(action?: string) {
const key = String(action || "").trim().toLowerCase();
if (key === "manual_points_grant") return "手动补分";
if (key === "feedback_reward_grant") return "反馈奖励";
if (key === "subscription_manual_grant") return "手动开通";
if (key === "subscription_manual_extend") return "会员延期";
if (key === "refund_case_create") return "创建退款工单";
if (key === "refund_case_update") return "更新退款工单";
return key || "未知操作";
}
export function AuditLogPageClient() {
const [loading, setLoading] = useState(true);
const [events, setEvents] = useState<OpsAuditEvent[]>([]);
const load = async () => {
setLoading(true);
try {
const payload = (await opsApi.auditLog(150)) as { events?: OpsAuditEvent[] };
setEvents(payload.events ?? []);
} catch {
setEvents([]);
}
setLoading(false);
};
useEffect(() => {
void load();
}, []);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold text-white"></h1>
<Button variant="outline" size="sm" onClick={load} className="gap-1.5">
<RefreshCcw className="h-3.5 w-3.5" />
</Button>
</div>
<Card>
<CardHeader>
<CardTitle> ({events.length})</CardTitle>
</CardHeader>
<CardContent>
{loading ? (
<div className="text-sm text-slate-500">...</div>
) : events.length === 0 ? (
<div className="text-sm text-slate-500"></div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-slate-200 text-left text-slate-500">
<th className="py-2 pr-4 font-bold"></th>
<th className="py-2 pr-4 font-bold"></th>
<th className="py-2 pr-4 font-bold"></th>
<th className="py-2 pr-4 font-bold"></th>
<th className="py-2 pr-4 font-bold"></th>
</tr>
</thead>
<tbody>
{events.map((event) => (
<tr key={event.id} className="border-b border-slate-100">
<td className="whitespace-nowrap py-2 pr-4 font-mono text-xs text-slate-500">
{compactDate(event.created_at)}
</td>
<td className="py-2 pr-4 font-bold text-slate-900">
{actionLabel(event.action)}
</td>
<td className="py-2 pr-4 text-xs text-slate-600">
{event.actor_email || "--"}
</td>
<td className="py-2 pr-4">
<div className="font-mono text-xs text-blue-700">
{event.target_email || event.target_user_id || event.target_id || "--"}
</div>
<div className="mt-0.5 text-[11px] text-slate-500">
{event.target_type || "--"}
</div>
</td>
<td className="max-w-md py-2 pr-4">
<code className="block truncate rounded bg-slate-100 px-2 py-1 text-[11px] text-slate-600">
{JSON.stringify(event.payload ?? {})}
</code>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
</div>
);
}
@@ -44,6 +44,7 @@ const navGroups = [
items: [
{ href: "/ops/config", icon: Settings, label: "系统配置" },
{ href: "/ops/subscriptions", icon: ScrollText, label: "订阅操作" },
{ href: "/ops/audit-log", icon: FileText, label: "审计日志" },
{ href: "/ops/view-logs", icon: FileText, label: "日志查看" },
],
},
@@ -12,6 +12,7 @@ import type {
PaymentRuntimePayload,
PaymentIncident,
PaymentRecord,
RefundCase,
} from "@/types/ops";
const PaymentIncidentPieChart = dynamic(
@@ -60,6 +61,8 @@ function paymentReasonLabel(reason?: string) {
if (key === "expired") return "订单已过期";
if (key === "event_mismatch") return "支付事件不匹配";
if (key === "direct_transfer_mismatch") return "直接转账不匹配";
if (key === "refund_required") return "需要退款处理";
if (key === "duplicate_payment") return "重复付款";
if (key === "unknown") return "未知原因";
return key || "未知原因";
}
@@ -96,21 +99,24 @@ export function PaymentsPageClient() {
const [runtime, setRuntime] = useState<PaymentRuntimePayload | null>(null);
const [incidents, setIncidents] = useState<PaymentIncident[]>([]);
const [payments, setPayments] = useState<PaymentRecord[]>([]);
const [refunds, setRefunds] = useState<RefundCase[]>([]);
const [risk, setRisk] = useState<BillingRiskPayload | null>(null);
const [resolving, setResolving] = useState<Set<number>>(new Set());
const load = async () => {
setLoading(true);
try {
const [rt, inc, pay, riskPayload] = await Promise.all([
const [rt, inc, pay, refundPayload, riskPayload] = await Promise.all([
opsApi.paymentRuntime() as Promise<PaymentRuntimePayload>,
opsApi.incidents(50),
opsApi.listPayments(50),
opsApi.refunds(50),
opsApi.billingRisk(30, 80) as Promise<BillingRiskPayload>,
]);
setRuntime(rt);
setIncidents((inc as unknown as { incidents?: PaymentIncident[] }).incidents ?? []);
setPayments((pay as unknown as { payments?: PaymentRecord[] }).payments ?? []);
setRefunds((refundPayload as unknown as { refunds?: RefundCase[] }).refunds ?? []);
setRisk(riskPayload);
} catch { /* */ }
setLoading(false);
@@ -328,6 +334,11 @@ export function PaymentsPageClient() {
<div className="mt-0.5 max-w-xl truncate text-xs text-slate-500" title={inc.detail || inc.reason || ""}>
{inc.detail || inc.reason || "—"}
</div>
{inc.refund_case_id ? (
<div className="mt-1 text-[11px] font-semibold text-blue-700">
退 #{inc.refund_case_id} · {inc.refund_status || "open"}
</div>
) : null}
</td>
<td className="py-2 pr-4 text-xs text-slate-500">
<div className="font-mono" title={inc.user_id || ""}>{compactMono(inc.user_id)}</div>
@@ -355,6 +366,54 @@ export function PaymentsPageClient() {
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle>退 ({refunds.length})</CardTitle></CardHeader>
<CardContent>
{refunds.length === 0 ? (
<span className="text-sm text-slate-500">退</span>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-white/10 text-left text-slate-400">
<th className="py-2 pr-4 font-medium">ID</th>
<th className="py-2 pr-4 font-medium"> / </th>
<th className="py-2 pr-4 font-medium"> / Intent</th>
<th className="py-2 pr-4 font-medium">Tx Hash</th>
<th className="py-2 pr-4 font-medium"></th>
<th className="py-2 pr-4 font-medium"></th>
</tr>
</thead>
<tbody>
{refunds.map((refund) => (
<tr key={refund.id} className="border-b border-white/5">
<td className="py-2 pr-4 font-mono text-xs text-slate-500">{refund.id}</td>
<td className="py-2 pr-4">
<div className="font-bold text-slate-900">{refund.status || "open"}</div>
<div className="text-xs text-amber-600">{paymentReasonLabel(refund.reason)}</div>
</td>
<td className="py-2 pr-4 text-xs text-slate-500">
<div className="font-mono" title={refund.user_id || ""}>{compactMono(refund.user_id)}</div>
<div className="mt-0.5 font-mono text-blue-700" title={refund.intent_id || ""}>{compactMono(refund.intent_id, 12, 6)}</div>
</td>
<td className="py-2 pr-4 font-mono text-xs text-slate-500" title={refund.tx_hash || ""}>
{compactMono(refund.tx_hash)}
</td>
<td className="py-2 pr-4 text-xs text-slate-500">
{refund.handled_by || refund.created_by || "—"}
</td>
<td className="py-2 pr-4 whitespace-nowrap text-xs text-slate-500">
{compactDate(refund.updated_at || refund.created_at)}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader><CardTitle> ({payments.length})</CardTitle></CardHeader>
<CardContent>
+31
View File
@@ -109,6 +109,37 @@ export const opsApi = {
if (reason) params.set("reason", reason);
return opsFetch<Record<string, unknown>>(`/api/ops/payments/incidents?${params}`);
},
auditLog(limit = 100, action?: string) {
const params = new URLSearchParams({ limit: String(limit) });
if (action) params.set("action", action);
return opsFetch<Record<string, unknown>>(`/api/ops/audit-log?${params}`);
},
refunds(limit = 50, status?: string) {
const params = new URLSearchParams({ limit: String(limit) });
if (status) params.set("status", status);
return opsFetch<Record<string, unknown>>(`/api/ops/refunds?${params}`);
},
createRefund(input: {
reason: string;
intent_id?: string;
tx_hash?: string;
user_id?: string;
amount_usdc?: string;
note?: string;
}) {
return opsFetch<Record<string, unknown>>("/api/ops/refunds", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
},
updateRefund(caseId: string | number, input: { status: string; note?: string }) {
return opsFetch<Record<string, unknown>>(`/api/ops/refunds/${caseId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
},
feedback(limit = 100, status?: string) {
const params = new URLSearchParams({ limit: String(limit) });
if (status) params.set("status", status);
+38
View File
@@ -155,6 +155,8 @@ export type PaymentIncident = {
intent_id?: string;
user_id?: string;
tx_hash?: string;
refund_case_id?: number | string | null;
refund_status?: string;
payload_json?: string;
created_at?: string;
resolved?: boolean;
@@ -166,6 +168,42 @@ export type PaymentIncident = {
last_seen_at?: string;
};
export type RefundCase = {
id: number;
status?: string;
reason?: string;
intent_id?: string;
tx_hash?: string;
user_id?: string;
amount_usdc?: string;
created_by?: string;
handled_by?: string;
notes?: Array<{ note?: string; by?: string; at?: string }>;
created_at?: string;
updated_at?: string;
};
export type RefundCasesPayload = {
refunds?: RefundCase[];
};
export type OpsAuditEvent = {
id: number;
action?: string;
actor_email?: string;
target_user_id?: string;
target_email?: string;
target_type?: string;
target_id?: string;
payload?: Record<string, unknown>;
created_at?: string;
};
export type OpsAuditPayload = {
events?: OpsAuditEvent[];
total?: number;
};
export type IncidentsPayload = {
incidents?: PaymentIncident[];
total?: number;