8315d5660a
Project CI / AI game creator shell Rust crates (push) Successful in 1m27s
Project CI / AI game creator shell Rust smoke (push) Successful in 1m53s
Project CI / Frontend tests (push) Has been cancelled
Project CI / Repository checks (push) Has been cancelled
Project CI / AI game creator shell Rust lane 2/2 (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled
Project CI / AI game creator shell web tests (push) Has been cancelled
Project CI / AI game creator shell Rust lane 1/2 (push) Has been cancelled
- packages/shared/src/components/admin/ 新增 16 个后台共享组件(AdminPage/AdminPanel/AdminButton/AdminAlert/AdminTable/AdminField/AdminInfoList/AdminTagList/AdminPagination/AdminListPanel/AdminDialog 等)与随组件的 admin.css,经 @genarrative/shared/components 导出 - AdminListPanel 统一列表外壳:columns + renderRow、加载两口径(empty/line)、空态三态(state/text/row)、toolbar 与 pagination 槽位、showEmpty 判据、surface=plain(弹窗内列表) - AdminListPanel 新增列头排序(sortable/sortValue/sortDescription):正序→倒序→不排序循环、同步 th[aria-sort]、稳定排序 - AdminDialog 统一弹窗外壳(遮罩/标题行/关闭动作/role=dialog/aria-modal/Esc/点遮罩关闭/初始聚焦/as=form),12 处各页自写弹窗全部改用它 - AdminFormat 新增 formatAdminDateTime/formatAdminDate,删除 7 份重复的本地时间格式化实现,修掉列表里裸 ISO 时间 - 21 个文件里 26 处列表全部迁到 AdminListPanel(24 处 columns 形态、2 处弹窗内 plain),页内已无手写表头或 AdminTable 当 children 的写法;累计 45 个可排序列 - 页面壳归一:错误报告补 AdminPage wide + AdminPageHeading,详情弹窗移出列表面板;模板管理列表从共享 ui Table 换成 AdminTable - 样式收口:公共组件规则随组件进入共享 styles,清理 admin.css 重复按钮/面板规则,.admin-tag 与 .admin-table th 改 nowrap,埋点用户列参考按钮紧跟本行并留行距,错误报告修版心 - 新增 scripts/admin-web-fake-api.mjs 本地假 API(含 overview/dashboard/tracking/error-reports/feature-gates/邀请码/兑换码/任务/充值/项目工程/AGC 模型与模板/游戏/账号/用户详情夹具),用于本地核对渲染 - docs 同步:共享基础组件库与展示页(后台组件层/列表排序/收敛范围/本地核对)、decision-log 与 pitfalls 记录迁移口径、排序边界与踩坑 - 验证:npm run admin-web:typecheck、npx vitest run apps/admin-web packages/shared/src/components/admin(26 files / 244 tests)、npm run check:encoding、git diff --check、prettier、eslint 全部通过
561 lines
16 KiB
TypeScript
561 lines
16 KiB
TypeScript
import {
|
|
AdminActionRow,
|
|
AdminAlert,
|
|
AdminButton,
|
|
AdminDialog,
|
|
AdminField,
|
|
AdminInfoList,
|
|
AdminJsonPreview,
|
|
AdminListPanel,
|
|
AdminPage,
|
|
AdminPageHeading,
|
|
AdminPanel,
|
|
AdminStatusPill,
|
|
} from '@genarrative/shared/components';
|
|
import { Download, Eye, RefreshCcw, Search } from 'lucide-react';
|
|
import { FormEvent, useEffect, useMemo, useState } from 'react';
|
|
|
|
import {
|
|
listAdminTrackingEventKeys,
|
|
listAdminTrackingEvents,
|
|
} from '../api/adminApiClient';
|
|
import type {
|
|
AdminTrackingEventEntryPayload,
|
|
AdminTrackingEventKeyPayload,
|
|
TrackingScopeKind,
|
|
} from '../api/adminApiTypes';
|
|
import { AdminUserReferenceButton } from '../components/AdminUserReferenceButton';
|
|
import {
|
|
buildAdminTrackingEventKeyOptions,
|
|
filterAdminTrackingEventDefinitions,
|
|
filterAdminTrackingEventKeyOptions,
|
|
findAdminTrackingEventDefinition,
|
|
} from '../config/trackingEventDefinitions';
|
|
import { handlePageError } from './pageUtils';
|
|
|
|
interface AdminTrackingEventsPageProps {
|
|
token: string;
|
|
onUnauthorized: (message?: string) => void;
|
|
}
|
|
|
|
const scopeKindOptions: Array<{
|
|
value: TrackingScopeKind | '';
|
|
label: string;
|
|
}> = [
|
|
{ value: '', label: '全部' },
|
|
{ value: 'site', label: 'site' },
|
|
{ value: 'work', label: 'work' },
|
|
{ value: 'module', label: 'module' },
|
|
{ value: 'user', label: 'user' },
|
|
];
|
|
|
|
const exportColumns: Array<{
|
|
key: keyof AdminTrackingEventEntryPayload;
|
|
label: string;
|
|
}> = [
|
|
{ key: 'eventId', label: '事件 ID' },
|
|
{ key: 'eventKey', label: 'Event Key' },
|
|
{ key: 'eventTitle', label: '事件名称' },
|
|
{ key: 'scopeKind', label: 'Scope Kind' },
|
|
{ key: 'scopeId', label: 'Scope ID' },
|
|
{ key: 'dayKey', label: 'Day Key' },
|
|
{ key: 'userId', label: 'User ID' },
|
|
{ key: 'ownerUserId', label: 'Owner User ID' },
|
|
{ key: 'profileId', label: 'Profile ID' },
|
|
{ key: 'moduleKey', label: 'Module Key' },
|
|
{ key: 'metadataJson', label: 'Metadata JSON' },
|
|
{ key: 'occurredAt', label: '发生时间' },
|
|
];
|
|
|
|
export function AdminTrackingEventsPage({
|
|
token,
|
|
onUnauthorized,
|
|
}: AdminTrackingEventsPageProps) {
|
|
const [entries, setEntries] = useState<AdminTrackingEventEntryPayload[]>([]);
|
|
const [eventKey, setEventKey] = useState('');
|
|
const [userId, setUserId] = useState('');
|
|
const [scopeKind, setScopeKind] = useState<TrackingScopeKind | ''>('');
|
|
const [scopeId, setScopeId] = useState('');
|
|
const [startDate, setStartDate] = useState('');
|
|
const [endDate, setEndDate] = useState('');
|
|
const [limit, setLimit] = useState('200');
|
|
const [eventKeys, setEventKeys] = useState<AdminTrackingEventKeyPayload[]>(
|
|
[],
|
|
);
|
|
const [errorMessage, setErrorMessage] = useState('');
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [isExportingAll, setIsExportingAll] = useState(false);
|
|
const [detailEntry, setDetailEntry] =
|
|
useState<AdminTrackingEventEntryPayload | null>(null);
|
|
|
|
useEffect(() => {
|
|
void refreshTrackingEventKeys();
|
|
void refreshTrackingEvents();
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [token]);
|
|
|
|
const eventKeyOptions = useMemo(
|
|
() => buildAdminTrackingEventKeyOptions(eventKeys),
|
|
[eventKeys],
|
|
);
|
|
const filteredEventDefinitions = useMemo(() => {
|
|
const dynamicOptions = filterAdminTrackingEventKeyOptions(
|
|
eventKeyOptions,
|
|
eventKey,
|
|
);
|
|
if (dynamicOptions.length) {
|
|
return dynamicOptions;
|
|
}
|
|
return filterAdminTrackingEventDefinitions(eventKey);
|
|
}, [eventKey, eventKeyOptions]);
|
|
|
|
async function refreshTrackingEventKeys() {
|
|
try {
|
|
const response = await listAdminTrackingEventKeys(token);
|
|
setEventKeys(response.eventKeys);
|
|
} catch {
|
|
setEventKeys([]);
|
|
}
|
|
}
|
|
|
|
async function refreshTrackingEvents() {
|
|
setIsLoading(true);
|
|
setErrorMessage('');
|
|
try {
|
|
const response = await listAdminTrackingEvents(token, {
|
|
eventKey,
|
|
userId,
|
|
scopeKind,
|
|
scopeId,
|
|
startDate,
|
|
endDate,
|
|
limit: parseLimit(limit),
|
|
});
|
|
setEntries(response.entries);
|
|
} catch (error: unknown) {
|
|
handlePageError(error, onUnauthorized, setErrorMessage);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
}
|
|
|
|
function handleSearch(event: FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
void refreshTrackingEvents();
|
|
}
|
|
|
|
function handleExport() {
|
|
if (!entries.length) {
|
|
setErrorMessage('当前没有可导出的埋点数据');
|
|
return;
|
|
}
|
|
exportTrackingEventsAsExcel(entries);
|
|
}
|
|
|
|
async function handleExportAll() {
|
|
setIsExportingAll(true);
|
|
setErrorMessage('');
|
|
try {
|
|
const response = await listAdminTrackingEvents(token, {
|
|
eventKey,
|
|
userId,
|
|
scopeKind,
|
|
scopeId,
|
|
startDate,
|
|
endDate,
|
|
limit: 100_000,
|
|
exportAll: true,
|
|
});
|
|
if (!response.entries.length) {
|
|
setErrorMessage('当前没有可导出的埋点数据');
|
|
return;
|
|
}
|
|
exportTrackingEventsAsExcel(response.entries);
|
|
} catch (error: unknown) {
|
|
handlePageError(error, onUnauthorized, setErrorMessage);
|
|
} finally {
|
|
setIsExportingAll(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<AdminPage wide>
|
|
<AdminPageHeading
|
|
title="埋点数据"
|
|
description="原始事件明细"
|
|
actions={
|
|
<AdminActionRow>
|
|
<AdminButton
|
|
variant="secondary"
|
|
disabled={isLoading || isExportingAll}
|
|
type="button"
|
|
onClick={refreshTrackingEvents}
|
|
>
|
|
<RefreshCcw size={17} aria-hidden="true" />
|
|
<span>{isLoading ? '刷新中' : '刷新'}</span>
|
|
</AdminButton>
|
|
<AdminButton
|
|
variant="primary"
|
|
disabled={!entries.length}
|
|
type="button"
|
|
onClick={handleExport}
|
|
>
|
|
<Download size={17} aria-hidden="true" />
|
|
<span>导出 Excel</span>
|
|
</AdminButton>
|
|
<AdminButton
|
|
variant="secondary"
|
|
disabled={isExportingAll}
|
|
type="button"
|
|
onClick={handleExportAll}
|
|
>
|
|
<Download size={17} aria-hidden="true" />
|
|
<span>{isExportingAll ? '导出中' : '导出全部'}</span>
|
|
</AdminButton>
|
|
</AdminActionRow>
|
|
}
|
|
/>
|
|
|
|
<AdminPanel as="form" onSubmit={handleSearch}>
|
|
<div className="admin-filter-grid">
|
|
<AdminField label="Event Key">
|
|
<input
|
|
list="admin-tracking-event-keys"
|
|
placeholder="全部"
|
|
value={eventKey}
|
|
onChange={(event) => setEventKey(event.target.value)}
|
|
/>
|
|
<datalist id="admin-tracking-event-keys">
|
|
{filteredEventDefinitions.map((definition) => (
|
|
<option key={definition.key} value={definition.key}>
|
|
{definition.title}
|
|
</option>
|
|
))}
|
|
</datalist>
|
|
</AdminField>
|
|
<AdminField label="User ID">
|
|
<input
|
|
placeholder="全部"
|
|
value={userId}
|
|
onChange={(event) => setUserId(event.target.value)}
|
|
/>
|
|
</AdminField>
|
|
<AdminField label="Scope Kind">
|
|
<select
|
|
value={scopeKind}
|
|
onChange={(event) =>
|
|
setScopeKind(event.target.value as TrackingScopeKind | '')
|
|
}
|
|
>
|
|
{scopeKindOptions.map((option) => (
|
|
<option key={option.value || 'all'} value={option.value}>
|
|
{option.label}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</AdminField>
|
|
<AdminField label="Scope ID">
|
|
<input
|
|
placeholder="全部"
|
|
value={scopeId}
|
|
onChange={(event) => setScopeId(event.target.value)}
|
|
/>
|
|
</AdminField>
|
|
<AdminField label="条数">
|
|
<input
|
|
inputMode="numeric"
|
|
value={limit}
|
|
onChange={(event) => setLimit(event.target.value)}
|
|
/>
|
|
</AdminField>
|
|
<AdminField label="开始日期">
|
|
<input
|
|
type="date"
|
|
value={startDate}
|
|
onChange={(event) => setStartDate(event.target.value)}
|
|
/>
|
|
</AdminField>
|
|
<AdminField label="结束日期">
|
|
<input
|
|
type="date"
|
|
value={endDate}
|
|
onChange={(event) => setEndDate(event.target.value)}
|
|
/>
|
|
</AdminField>
|
|
<AdminButton variant="secondary" disabled={isLoading} type="submit">
|
|
<Search size={17} aria-hidden="true" />
|
|
<span>{isLoading ? '查询中' : '查询'}</span>
|
|
</AdminButton>
|
|
</div>
|
|
</AdminPanel>
|
|
|
|
{errorMessage ? <AdminAlert>{errorMessage}</AdminAlert> : null}
|
|
|
|
<AdminListPanel
|
|
busy={isLoading}
|
|
busyText="正在加载"
|
|
columns={[
|
|
{ key: 'event', label: '事件' },
|
|
{ key: 'scope', label: 'Scope' },
|
|
{ key: 'user', label: '用户' },
|
|
{ key: 'owner', label: '归属' },
|
|
{ key: 'metadata', label: 'Metadata' },
|
|
{ key: 'occurredAt', label: '时间' },
|
|
{ key: 'actions', label: '详情' },
|
|
]}
|
|
count={<>{entries.length} 条</>}
|
|
emptyText="暂无数据"
|
|
emptyVariant="row"
|
|
renderRow={(entry) => (
|
|
<tr key={entry.eventId}>
|
|
<td>
|
|
<strong>{resolveEventTitle(entry)}</strong>
|
|
<small>{entry.eventKey}</small>
|
|
<small>{entry.eventId}</small>
|
|
</td>
|
|
<td>
|
|
<AdminStatusPill tone="pending">
|
|
{entry.scopeKind}
|
|
</AdminStatusPill>
|
|
<small>{entry.scopeId || '-'}</small>
|
|
<small>dayKey: {entry.dayKey}</small>
|
|
</td>
|
|
<td>
|
|
<div className="admin-tracking-user-reference">
|
|
<span>{entry.userId || '-'}</span>
|
|
{entry.userId ? (
|
|
<AdminUserReferenceButton
|
|
token={token}
|
|
userId={entry.userId}
|
|
onUnauthorized={onUnauthorized}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
<div className="admin-tracking-user-reference">
|
|
<small>owner: {entry.ownerUserId || '-'}</small>
|
|
{/* 归属人和事件用户是同一人时不再重复给一个查询按钮。 */}
|
|
{entry.ownerUserId && entry.ownerUserId !== entry.userId ? (
|
|
<AdminUserReferenceButton
|
|
token={token}
|
|
userId={entry.ownerUserId}
|
|
onUnauthorized={onUnauthorized}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
</td>
|
|
<td>
|
|
{entry.profileId || '-'}
|
|
<small>module: {entry.moduleKey || '-'}</small>
|
|
</td>
|
|
<td>
|
|
<AdminJsonPreview>
|
|
{formatMetadataJson(entry.metadataJson)}
|
|
</AdminJsonPreview>
|
|
</td>
|
|
<td>{formatOccurredAt(entry.occurredAt)}</td>
|
|
<td>
|
|
<AdminButton
|
|
variant="secondary"
|
|
type="button"
|
|
onClick={() => setDetailEntry(entry)}
|
|
>
|
|
<Eye size={16} aria-hidden="true" />
|
|
<span>详情</span>
|
|
</AdminButton>
|
|
</td>
|
|
</tr>
|
|
)}
|
|
rows={entries}
|
|
size="wide"
|
|
title="事件明细"
|
|
/>
|
|
|
|
{detailEntry ? (
|
|
<TrackingEventDetailPanel
|
|
entry={detailEntry}
|
|
token={token}
|
|
onUnauthorized={onUnauthorized}
|
|
onClose={() => setDetailEntry(null)}
|
|
/>
|
|
) : null}
|
|
</AdminPage>
|
|
);
|
|
}
|
|
|
|
function TrackingEventDetailPanel({
|
|
entry,
|
|
token,
|
|
onUnauthorized,
|
|
onClose,
|
|
}: {
|
|
entry: AdminTrackingEventEntryPayload;
|
|
token: string;
|
|
onUnauthorized: (message?: string) => void;
|
|
onClose: () => void;
|
|
}) {
|
|
return (
|
|
<AdminDialog
|
|
ariaLabel="埋点详情"
|
|
closeLabel="关闭详情"
|
|
title={resolveEventTitle(entry)}
|
|
onClose={onClose}
|
|
>
|
|
<AdminInfoList className="admin-detail-list">
|
|
{exportColumns.map((column) => (
|
|
<div key={column.key}>
|
|
<dt>{column.label}</dt>
|
|
<dd>
|
|
{column.key === 'metadataJson' ? (
|
|
<pre className="admin-code-block">
|
|
{formatMetadataJson(entry.metadataJson)}
|
|
</pre>
|
|
) : column.key === 'userId' && entry.userId ? (
|
|
<div className="admin-inline-identity">
|
|
<span>{entry.userId}</span>
|
|
<AdminUserReferenceButton
|
|
token={token}
|
|
userId={entry.userId}
|
|
onUnauthorized={onUnauthorized}
|
|
/>
|
|
</div>
|
|
) : column.key === 'ownerUserId' && entry.ownerUserId ? (
|
|
<div className="admin-inline-identity">
|
|
<span>{entry.ownerUserId}</span>
|
|
<AdminUserReferenceButton
|
|
token={token}
|
|
userId={entry.ownerUserId}
|
|
onUnauthorized={onUnauthorized}
|
|
/>
|
|
</div>
|
|
) : (
|
|
formatExportCell(entry[column.key], column.key) || '-'
|
|
)}
|
|
</dd>
|
|
</div>
|
|
))}
|
|
</AdminInfoList>
|
|
</AdminDialog>
|
|
);
|
|
}
|
|
|
|
function parseLimit(value: string) {
|
|
const parsed = Number.parseInt(value.trim(), 10);
|
|
if (!Number.isFinite(parsed)) {
|
|
return 200;
|
|
}
|
|
return Math.min(Math.max(parsed, 1), 1000);
|
|
}
|
|
|
|
function resolveEventTitle(entry: AdminTrackingEventEntryPayload) {
|
|
return (
|
|
findAdminTrackingEventDefinition(entry.eventKey)?.title ||
|
|
entry.eventTitle ||
|
|
entry.eventKey
|
|
);
|
|
}
|
|
|
|
function formatMetadataJson(value: string) {
|
|
const trimmed = value.trim();
|
|
if (!trimmed) {
|
|
return '-';
|
|
}
|
|
try {
|
|
return JSON.stringify(JSON.parse(trimmed), null, 2);
|
|
} catch {
|
|
return trimmed;
|
|
}
|
|
}
|
|
|
|
function exportTrackingEventsAsExcel(
|
|
entries: AdminTrackingEventEntryPayload[],
|
|
) {
|
|
const tableRows = [
|
|
exportColumns
|
|
.map((column) => `<th>${escapeHtml(column.label)}</th>`)
|
|
.join(''),
|
|
...entries.map((entry) =>
|
|
exportColumns
|
|
.map(
|
|
(column) =>
|
|
`<td style="mso-number-format:'\\@';">${escapeHtml(formatExportCell(entry[column.key], column.key))}</td>`,
|
|
)
|
|
.join(''),
|
|
),
|
|
];
|
|
const html = `\uFEFF<html><head><meta charset="UTF-8" /></head><body><table>${tableRows
|
|
.map((row) => `<tr>${row}</tr>`)
|
|
.join('')}</table></body></html>`;
|
|
const blob = new Blob([html], {
|
|
type: 'application/vnd.ms-excel;charset=utf-8',
|
|
});
|
|
const url = URL.createObjectURL(blob);
|
|
const link = document.createElement('a');
|
|
link.href = url;
|
|
link.download = `tracking-events-${buildTimestamp()}.xls`;
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
link.remove();
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
|
|
function formatExportCell(
|
|
value: unknown,
|
|
key?: keyof AdminTrackingEventEntryPayload,
|
|
) {
|
|
if (value === null || typeof value === 'undefined') {
|
|
return '';
|
|
}
|
|
if (key === 'occurredAt') {
|
|
return formatOccurredAt(String(value));
|
|
}
|
|
return String(value);
|
|
}
|
|
|
|
function formatOccurredAt(value: string) {
|
|
const trimmed = value.trim();
|
|
if (!trimmed) {
|
|
return '-';
|
|
}
|
|
if (/^\d+$/.test(trimmed)) {
|
|
const micros = Number(trimmed);
|
|
if (Number.isSafeInteger(micros)) {
|
|
return formatDateTime(new Date(Math.floor(micros / 1000)));
|
|
}
|
|
}
|
|
const parsed = new Date(trimmed);
|
|
if (!Number.isNaN(parsed.getTime())) {
|
|
return formatDateTime(parsed);
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
function formatDateTime(date: Date) {
|
|
const pad = (value: number, size = 2) => String(value).padStart(size, '0');
|
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(
|
|
date.getHours(),
|
|
)}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
}
|
|
|
|
function escapeHtml(value: string) {
|
|
return value
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>')
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''');
|
|
}
|
|
|
|
function buildTimestamp() {
|
|
const now = new Date();
|
|
const pad = (value: number) => String(value).padStart(2, '0');
|
|
return [
|
|
now.getFullYear(),
|
|
pad(now.getMonth() + 1),
|
|
pad(now.getDate()),
|
|
'-',
|
|
pad(now.getHours()),
|
|
pad(now.getMinutes()),
|
|
pad(now.getSeconds()),
|
|
].join('');
|
|
}
|