修复泥点消耗刷新不及时 (#138)
Project CI / Repository checks (push) Successful in 50s
Project CI / Frontend tests (push) Has been cancelled
Project CI / Backend tests (push) Has been cancelled
Project CI / Native shell tests (push) Has been cancelled

refactor:
- 主站复用game agent的zustand store

fix:
- 修复旧请求覆盖问题
- 修复账号切换问题

- 主站原本已经每 4 秒轮询 external generation 任务状态, 在这里补充触发余额刷新的时机

---------

Co-authored-by: 段舒康 <kdletters@qq.com>
Reviewed-on: http://192.168.35.82/git/GenarrativeAI/Genarrative/pulls/138
Co-authored-by: 王德宇 <kvtodev@outlook.com>
Co-committed-by: 王德宇 <kvtodev@outlook.com>
This commit was merged in pull request #138.
This commit is contained in:
2026-08-08 10:25:02 +08:00
committed by 段舒康
parent 44de26d204
commit fc0dcb0782
36 changed files with 4160 additions and 491 deletions
@@ -48,6 +48,9 @@ describe('PlatformActiveProfileView', () => {
{...callbacks}
dashboard={null}
isLoadingDashboard={false}
isLoadingWalletBalance={false}
legacyWalletBalance={null}
mudPointBalance={null}
user={null}
/>,
);
@@ -68,6 +71,17 @@ describe('PlatformActiveProfileView', () => {
updatedAt: '2026-07-18T00:00:00.000Z',
}}
isLoadingDashboard={false}
isLoadingWalletBalance={false}
legacyWalletBalance={null}
mudPointBalance={{
totalPoints: 108,
permanentPoints: 88,
limitedPoints: 0,
limitedExpiresAt: null,
dailyFreePoints: 20,
dailyFreeResetPoints: 20,
dailyFreeResetsAt: '2026-08-04T00:00:00+08:00',
}}
user={authenticatedUser}
/>,
);
@@ -101,6 +115,9 @@ describe('PlatformActiveProfileView', () => {
{...callbacks}
dashboard={null}
isLoadingDashboard={false}
isLoadingWalletBalance={false}
legacyWalletBalance={null}
mudPointBalance={null}
user={authenticatedUser}
/>,
);
@@ -133,6 +150,9 @@ describe('PlatformActiveProfileView', () => {
{...callbacks}
dashboard={null}
isLoadingDashboard={false}
isLoadingWalletBalance={false}
legacyWalletBalance={null}
mudPointBalance={null}
user={authenticatedUser}
/>,
);
@@ -195,6 +215,9 @@ describe('PlatformActiveProfileView', () => {
{...callbacks}
dashboard={null}
isLoadingDashboard={false}
isLoadingWalletBalance={false}
legacyWalletBalance={null}
mudPointBalance={null}
user={authenticatedUser}
/>,
);
@@ -11,6 +11,12 @@ import {
} from 'lucide-react';
import { useCallback, useRef, useState } from 'react';
import type {
AuthUser,
ProfileDashboardSummary,
ProfileMudPointBalance,
} from '@/packages/shared/src';
import profileClockImage from '../../../media/profile/_Image (1).png';
import profileGamepadImage from '../../../media/profile/_Image (2).png';
import profileStillLifeImage from '../../../media/profile/_Image (3).png';
@@ -20,8 +26,6 @@ import profileCommunityImage from '../../../media/profile/_Image (7).png';
import profileFeedbackImage from '../../../media/profile/_Image (8).png';
import profileMascotImage from '../../../media/profile/_Image (9).png';
import profilePointImage from '../../../media/profile/_Image.png';
import type { AuthUser } from '../../../packages/shared/src/contracts/auth';
import type { ProfileDashboardSummary } from '../../../packages/shared/src/contracts/runtime';
import { updateAuthProfile } from '../../services/authService';
import {
canUseNativeHostCapability,
@@ -58,6 +62,9 @@ import {
type PlatformActiveProfileViewProps = {
dashboard: ProfileDashboardSummary | null;
isLoadingDashboard: boolean;
isLoadingWalletBalance: boolean;
legacyWalletBalance: number | null;
mudPointBalance: ProfileMudPointBalance | null;
onLogin: () => void;
onOpenApiKeys: () => void;
onOpenCommunity: () => void;
@@ -237,6 +244,23 @@ function formatDashboardCount(value: number) {
return Math.max(0, Math.round(value)).toLocaleString('zh-CN');
}
function formatWalletBalance(
balance: ProfileMudPointBalance | null,
legacyBalance: number | null,
isLoading: boolean,
) {
if (balance) {
return formatDashboardCount(balance.totalPoints);
}
if (legacyBalance !== null) {
return formatDashboardCount(legacyBalance);
}
if (isLoading) {
return '读取中';
}
return '暂不可用';
}
function formatTotalPlayTime(value: number) {
const hours = Math.max(0, Math.round(value / 360000) / 10);
return `${hours.toLocaleString('zh-CN', {
@@ -247,6 +271,9 @@ function formatTotalPlayTime(value: number) {
export function PlatformActiveProfileView({
dashboard,
isLoadingDashboard,
isLoadingWalletBalance,
legacyWalletBalance,
mudPointBalance,
onLogin,
onOpenApiKeys,
onOpenCommunity,
@@ -539,11 +566,11 @@ export function PlatformActiveProfileView({
<ProfileStatCard
cardKey="wallet"
label="泥点余额"
value={
dashboard
? formatDashboardCount(dashboard.walletBalance)
: '暂不可用'
}
value={formatWalletBalance(
mudPointBalance,
legacyWalletBalance,
isLoadingWalletBalance,
)}
icon={Coins}
imageSrc={profilePointImage}
onClick={onOpenWalletLedger}
@@ -1,15 +1,27 @@
/* @vitest-environment jsdom */
import { fireEvent, render, screen, within } from '@testing-library/react';
import { useState } from 'react';
import {
act,
fireEvent,
render as testingLibraryRender,
screen,
waitFor,
within,
} from '@testing-library/react';
import { type ReactElement, type ReactNode, useState } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { AuthUser } from '../../../packages/shared/src/contracts/auth';
import {
usePlatformWalletLifecycle,
usePlatformWalletStore,
} from '../../stores/usePlatformWalletStore';
import { PlatformEntryFlowShellImpl } from './PlatformEntryActiveFlowShell';
import type { SelectionStage } from './platformEntryActiveTypes';
const authUiMock = vi.hoisted(() => ({
value: {
user: null,
user: null as AuthUser | null,
canAccessProtectedData: false,
openLoginModal: vi.fn(),
openAccountModal: vi.fn(),
@@ -21,6 +33,16 @@ const responsiveMock = vi.hoisted(() => ({
isDesktopLayout: true,
}));
const profileClientMock = vi.hoisted(() => ({
getPlatformProfileDashboard: vi.fn(),
getPlatformProfileRechargeCenter: vi.fn(),
}));
const profileCenterMock = vi.hoisted(() => ({
isWalletLedgerOpen: false,
rechargeCenter: null as { walletBalance: number } | null,
}));
vi.mock('../auth/AuthUiContext', () => ({
useAuthUi: () => authUiMock.value,
}));
@@ -80,12 +102,22 @@ vi.mock('../project/ProjectGalleryView', () => ({
}));
vi.mock('../image-editor/ImageCanvasEditorView', () => ({
ImageCanvasEditorView: () => <main aria-label="图片画布编辑器" />,
ImageCanvasEditorView: ({
legacyWalletBalance,
}: {
legacyWalletBalance?: number | null;
}) => (
<main
aria-label="图片画布编辑器"
data-legacy-wallet-balance={legacyWalletBalance ?? ''}
/>
),
}));
vi.mock('../../services/platform-entry/platformProfileClient', () => ({
getPlatformProfileDashboard: vi.fn(),
}));
vi.mock(
'../../services/platform-entry/platformProfileClient',
() => profileClientMock,
);
vi.mock('./usePlatformProfileCenterController', () => ({
usePlatformProfileCenterController: () => ({
@@ -95,11 +127,11 @@ vi.mock('./usePlatformProfileCenterController', () => ({
isLoadingRechargeCenter: false,
isLoadingWalletLedger: false,
isRechargeOpen: false,
isWalletLedgerOpen: false,
isWalletLedgerOpen: profileCenterMock.isWalletLedgerOpen,
loadRechargeCenter: vi.fn(),
nativeWechatPayment: null,
openWalletLedgerPanel: vi.fn(),
rechargeCenter: null,
rechargeCenter: profileCenterMock.rechargeCenter,
rechargeError: null,
rechargePaymentResult: null,
setIsRechargeOpen: vi.fn(),
@@ -112,6 +144,24 @@ vi.mock('./usePlatformProfileCenterController', () => ({
}),
}));
function AuthWalletLifecycleTestBoundary({
children,
}: {
children: ReactNode;
}) {
usePlatformWalletLifecycle(
authUiMock.value.user?.id ?? null,
authUiMock.value.canAccessProtectedData,
);
return children;
}
function render(ui: ReactElement) {
return testingLibraryRender(ui, {
wrapper: AuthWalletLifecycleTestBoundary,
});
}
function StatefulPlatformEntryFlowShell({
initialStage,
}: {
@@ -130,10 +180,225 @@ function StatefulPlatformEntryFlowShell({
describe('PlatformEntryActiveFlowShell', () => {
beforeEach(() => {
window.history.replaceState(null, '', '/creation');
usePlatformWalletStore.getState().resetWalletBalance();
profileClientMock.getPlatformProfileDashboard.mockReset();
profileClientMock.getPlatformProfileRechargeCenter.mockReset();
profileCenterMock.isWalletLedgerOpen = false;
profileCenterMock.rechargeCenter = null;
authUiMock.value.user = null;
authUiMock.value.canAccessProtectedData = false;
authUiMock.value.openLoginModal.mockReset();
responsiveMock.isDesktopLayout = true;
});
it('uses one recharge-center snapshot for the topbar and profile wallet when dashboard differs', async () => {
authUiMock.value.user = {
id: 'user-1',
publicUserCode: '100001',
displayName: '测试用户',
avatarUrl: null,
phoneNumberMasked: null,
loginMethod: 'password',
bindingStatus: 'active',
wechatBound: false,
};
authUiMock.value.canAccessProtectedData = true;
profileClientMock.getPlatformProfileDashboard.mockResolvedValue({
walletBalance: 999,
totalPlayTimeMs: 0,
playedWorldCount: 0,
updatedAt: null,
});
profileClientMock.getPlatformProfileRechargeCenter.mockResolvedValue({
walletBalance: 888,
mudPointBalance: {
totalPoints: 207,
permanentPoints: 180,
limitedPoints: 7,
limitedExpiresAt: '2026-08-31T16:00:00Z',
dailyFreePoints: 20,
dailyFreeResetPoints: 20,
dailyFreeResetsAt: '2026-08-04T00:00:00+08:00',
},
});
const { rerender } = render(
<PlatformEntryFlowShellImpl
selectionStage="creation-home"
setSelectionStage={vi.fn()}
/>,
);
expect(await screen.findByLabelText('泥点 207')).toBeTruthy();
rerender(
<PlatformEntryFlowShellImpl
selectionStage="profile"
setSelectionStage={vi.fn()}
/>,
);
expect(
await screen.findByRole('button', { name: '泥点余额 207' }),
).toBeTruthy();
expect(screen.queryByText('999')).toBeNull();
});
it('passes the lifecycle legacy total to profile and editor without opening recharge', async () => {
authUiMock.value.user = {
id: 'user-1',
publicUserCode: '100001',
displayName: '测试用户',
avatarUrl: null,
phoneNumberMasked: null,
loginMethod: 'password',
bindingStatus: 'active',
wechatBound: false,
};
authUiMock.value.canAccessProtectedData = true;
profileClientMock.getPlatformProfileDashboard.mockResolvedValue(null);
profileClientMock.getPlatformProfileRechargeCenter.mockResolvedValue({
walletBalance: 37,
});
profileCenterMock.isWalletLedgerOpen = true;
const { rerender } = render(
<PlatformEntryFlowShellImpl
selectionStage="profile"
setSelectionStage={vi.fn()}
/>,
);
expect(
await screen.findByRole('button', { name: '泥点余额 37' }),
).toBeTruthy();
expect(await screen.findByText('37泥点')).toBeTruthy();
expect(screen.getByText('暂无账单记录')).toBeTruthy();
rerender(
<PlatformEntryFlowShellImpl
selectionStage="image-editor"
setSelectionStage={vi.fn()}
/>,
);
const imageEditor = await screen.findByRole('main', {
name: '图片画布编辑器',
});
expect(imageEditor.getAttribute('data-legacy-wallet-balance')).toBe('37');
});
it('clears the previous wallet synchronously when the authenticated account changes', async () => {
authUiMock.value.user = {
id: 'user-1',
publicUserCode: '100001',
displayName: '用户一',
avatarUrl: null,
phoneNumberMasked: null,
loginMethod: 'password',
bindingStatus: 'active',
wechatBound: false,
};
authUiMock.value.canAccessProtectedData = true;
profileClientMock.getPlatformProfileDashboard.mockResolvedValue(null);
profileClientMock.getPlatformProfileRechargeCenter.mockResolvedValue({
mudPointBalance: {
totalPoints: 66,
permanentPoints: 66,
limitedPoints: 0,
limitedExpiresAt: null,
dailyFreePoints: 0,
dailyFreeResetPoints: 20,
dailyFreeResetsAt: '2026-08-04T00:00:00+08:00',
},
});
const { rerender } = render(
<PlatformEntryFlowShellImpl
selectionStage="creation-home"
setSelectionStage={vi.fn()}
/>,
);
await screen.findByLabelText('泥点 66');
let resolveNextOwner!: (value: unknown) => void;
profileClientMock.getPlatformProfileRechargeCenter.mockImplementation(
() =>
new Promise((resolve) => {
resolveNextOwner = resolve;
}),
);
authUiMock.value.user = { ...authUiMock.value.user, id: 'user-2' };
rerender(
<PlatformEntryFlowShellImpl
selectionStage="creation-home"
setSelectionStage={vi.fn()}
/>,
);
expect(screen.queryByLabelText('泥点 66')).toBeNull();
await waitFor(() => {
expect(usePlatformWalletStore.getState()).toMatchObject({
ownerUserId: 'user-2',
mudPointBalance: null,
});
});
resolveNextOwner({
mudPointBalance: {
totalPoints: 67,
permanentPoints: 67,
limitedPoints: 0,
limitedExpiresAt: null,
dailyFreePoints: 0,
dailyFreeResetPoints: 20,
dailyFreeResetsAt: '2026-08-04T00:00:00+08:00',
},
});
await screen.findByLabelText('泥点 67');
});
it('coalesces visibility and focus refreshes when the page returns to the foreground', async () => {
authUiMock.value.user = {
id: 'user-1',
publicUserCode: '100001',
displayName: '测试用户',
avatarUrl: null,
phoneNumberMasked: null,
loginMethod: 'password',
bindingStatus: 'active',
wechatBound: false,
};
authUiMock.value.canAccessProtectedData = true;
profileClientMock.getPlatformProfileDashboard.mockResolvedValue(null);
profileClientMock.getPlatformProfileRechargeCenter.mockResolvedValue({
mudPointBalance: {
totalPoints: 10,
permanentPoints: 10,
limitedPoints: 0,
limitedExpiresAt: null,
dailyFreePoints: 0,
dailyFreeResetPoints: 20,
dailyFreeResetsAt: '2026-08-04T00:00:00+08:00',
},
});
render(
<PlatformEntryFlowShellImpl
selectionStage="creation-home"
setSelectionStage={vi.fn()}
/>,
);
await screen.findByLabelText('泥点 10');
await act(async () => {
document.dispatchEvent(new Event('visibilitychange'));
window.dispatchEvent(new Event('focus'));
});
await waitFor(() => {
expect(
profileClientMock.getPlatformProfileRechargeCenter,
).toHaveBeenCalledTimes(2);
});
});
it('keeps the active desktop rail and the shared account capsule', async () => {
const setSelectionStage = vi.fn();
const { container, rerender } = render(
@@ -241,13 +506,9 @@ describe('PlatformEntryActiveFlowShell', () => {
expect(
await screen.findByRole('main', { name: '桌面端创作提示' }),
).toBeTruthy();
expect(
screen.queryByRole('main', { name: '陶泥儿创作主页' }),
).toBeNull();
expect(screen.queryByRole('main', { name: '陶泥儿创作主页' })).toBeNull();
expect(screen.queryByRole('main', { name: '项目' })).toBeNull();
expect(
screen.queryByRole('main', { name: '图片画布编辑器' }),
).toBeNull();
expect(screen.queryByRole('main', { name: '图片画布编辑器' })).toBeNull();
},
);
@@ -263,9 +524,7 @@ describe('PlatformEntryActiveFlowShell', () => {
expect(
await screen.findByRole('main', { name: '桌面端创作提示' }),
).toBeTruthy();
expect(
screen.queryByRole('main', { name: '图片画布编辑器' }),
).toBeNull();
expect(screen.queryByRole('main', { name: '图片画布编辑器' })).toBeNull();
});
it('switches between creation and projects and passes search to the active page', async () => {
@@ -25,6 +25,7 @@ import {
replaceAppHistoryPath,
} from '../../routing/activeAppPageRoutes';
import { getPlatformProfileDashboard } from '../../services/platform-entry/platformProfileClient';
import { usePlatformWalletStore } from '../../stores/usePlatformWalletStore';
import { useAuthUi } from '../auth/AuthUiContext';
import { FLOATING_FEEDBACK_FORM_URL } from '../common/floatingFeedbackEntryModel';
import { PlatformActionButton } from '../common/PlatformActionButton';
@@ -224,6 +225,37 @@ export function PlatformEntryFlowShellImpl({
const [isMobileDesktopGuideOpen, setIsMobileDesktopGuideOpen] =
useState(false);
const isDesktopLayout = usePlatformDesktopLayout();
const currentWalletOwnerUserId =
authUi?.canAccessProtectedData && authUi.user?.id ? authUi.user.id : null;
const walletOwnerUserId = usePlatformWalletStore(
(state) => state.ownerUserId,
);
const storedMudPointBalance = usePlatformWalletStore(
(state) => state.mudPointBalance,
);
const storedLegacyWalletBalance = usePlatformWalletStore(
(state) => state.legacyWalletBalance,
);
const storedMudPointBalanceStatus = usePlatformWalletStore(
(state) => state.mudPointBalanceStatus,
);
const storedMudPointBalanceError = usePlatformWalletStore(
(state) => state.mudPointBalanceError,
);
const walletOwnerMatchesCurrentUser =
Boolean(currentWalletOwnerUserId) &&
walletOwnerUserId === currentWalletOwnerUserId;
const mudPointBalance = walletOwnerMatchesCurrentUser
? storedMudPointBalance
: null;
const mudPointBalanceError = walletOwnerMatchesCurrentUser
? storedMudPointBalanceError
: '';
const isWalletBalanceLoading =
Boolean(currentWalletOwnerUserId) &&
(!walletOwnerMatchesCurrentUser ||
storedMudPointBalanceStatus === 'idle' ||
storedMudPointBalanceStatus === 'loading');
const refreshDashboard = useCallback(async () => {
if (!authUi?.user || !authUi.canAccessProtectedData) {
@@ -250,10 +282,14 @@ export function PlatformEntryFlowShellImpl({
activeTab: isProfileStage ? 'profile' : 'project',
isAuthenticated: Boolean(authUi?.user),
showRechargeEntry: true,
onRechargeSuccess: refreshDashboard,
requestLogin: () => authUi?.openLoginModal(),
currentUser: authUi?.user,
});
const legacyWalletBalance = walletOwnerMatchesCurrentUser
? (storedLegacyWalletBalance ??
profileCenter.rechargeCenter?.walletBalance ??
null)
: null;
const openCreation = useCallback(() => {
if (!isDesktopLayout) {
@@ -329,6 +365,7 @@ export function PlatformEntryFlowShellImpl({
<div className="image-editor-stage-shell flex h-full min-h-0 min-w-0 flex-col overflow-hidden">
<Suspense fallback={<LoadingPanel label="正在加载编辑器..." />}>
<ImageCanvasEditorView
legacyWalletBalance={legacyWalletBalance}
onProjectAccessLost={replaceWithProjectGallery}
/>
</Suspense>
@@ -337,11 +374,7 @@ export function PlatformEntryFlowShellImpl({
}
const isAuthenticated = Boolean(authUi?.user);
const balance =
dashboard?.walletBalance ??
profileCenter.rechargeCenter?.mudPointBalance?.totalPoints ??
profileCenter.rechargeCenter?.walletBalance ??
null;
const balance = mudPointBalance?.totalPoints ?? legacyWalletBalance;
const isCreationStage =
!isProfileStage &&
(selectionStage === 'platform' || selectionStage === 'creation-home');
@@ -455,14 +488,9 @@ export function PlatformEntryFlowShellImpl({
<PlatformMudPointWalletEntry
variant={isDesktopLayout ? 'desktop' : 'mobile'}
balance={balance}
breakdown={
profileCenter.rechargeCenter?.mudPointBalance ?? null
}
isLoading={
isLoadingDashboard ||
profileCenter.isLoadingRechargeCenter
}
error={profileCenter.rechargeError}
breakdown={mudPointBalance}
isLoading={isWalletBalanceLoading}
error={mudPointBalanceError || null}
className={
isDesktopLayout
? 'platform-desktop-create-wallet-chip'
@@ -515,6 +543,9 @@ export function PlatformEntryFlowShellImpl({
<PlatformActiveProfileView
dashboard={dashboard}
isLoadingDashboard={isLoadingDashboard}
isLoadingWalletBalance={isWalletBalanceLoading}
legacyWalletBalance={legacyWalletBalance}
mudPointBalance={mudPointBalance}
user={authUi?.user}
onLogin={() => authUi?.openLoginModal()}
onOpenApiKeys={() => setIsApiKeysOpen(true)}
@@ -0,0 +1,370 @@
/* @vitest-environment jsdom */
import { act, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { ProfileRechargeProduct } from '../../../packages/shared/src/contracts/runtime';
import { usePlatformWalletStore } from '../../stores/usePlatformWalletStore';
import {
apiClientMocks,
hostBridgeMocks,
paymentPlatformMocks,
profileClientMocks,
renderController,
userA,
userB,
} from './usePlatformProfileCenterController.testSupport';
const rechargeProduct = {
productId: 'points-60',
kind: 'points',
} as ProfileRechargeProduct;
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, reject, resolve };
}
function mudPointBalance(totalPoints: number) {
return {
totalPoints,
permanentPoints: totalPoints,
limitedPoints: 0,
limitedExpiresAt: null,
dailyFreePoints: 0,
dailyFreeResetPoints: 20,
dailyFreeResetsAt: '2026-08-07T00:00:00+08:00',
};
}
function nativeRechargeResponse(totalPoints = 80, orderId = 'order-a') {
return {
order: {
orderId,
productTitle: '60 泥点',
amountCents: 600,
status: 'pending',
expirationCheckedAt: null,
},
center: {
walletBalance: totalPoints,
mudPointBalance: mudPointBalance(totalPoints),
},
wechatNativePayment: {
codeUrl: `weixin://wxpay/${orderId}`,
expiresAt: '2099-08-07T00:00:00+08:00',
},
};
}
describe('usePlatformProfileCenterController recharge fallback', () => {
beforeEach(() => {
window.history.replaceState(null, '', '/profile');
usePlatformWalletStore.getState().resetWalletBalance();
vi.clearAllMocks();
paymentPlatformMocks.resolveProfileRechargeProductPaymentChannel.mockReturnValue(
'wechat_native',
);
hostBridgeMocks.getHostRuntime.mockReturnValue({ kind: 'browser' });
profileClientMocks.watchWechatPlatformProfileRechargeOrder.mockReturnValue(
new Promise(() => undefined),
);
});
test('keeps the response legacy balance when no shared snapshot exists', async () => {
usePlatformWalletStore.getState().setWalletOwner('user-a');
profileClientMocks.getPlatformProfileRechargeCenter.mockResolvedValue({
walletBalance: 37,
membership: null,
pointProducts: [],
membershipProducts: [],
benefits: [],
latestOrder: null,
hasPointsRecharged: false,
});
const { result } = renderController(userA);
act(() => result.current.loadRechargeCenter());
await waitFor(() => {
expect(result.current.rechargeCenter?.walletBalance).toBe(37);
});
});
test('synchronously rejects a duplicate recharge submission before React commits state', async () => {
const pendingOrder = deferred<ReturnType<typeof nativeRechargeResponse>>();
profileClientMocks.createPlatformProfileRechargeOrder.mockReturnValue(
pendingOrder.promise,
);
usePlatformWalletStore.getState().setWalletOwner('user-a');
const { result } = renderController(userA);
act(() => {
result.current.buyRechargeProduct(rechargeProduct);
result.current.buyRechargeProduct(rechargeProduct);
});
expect(
profileClientMocks.createPlatformProfileRechargeOrder,
).toHaveBeenCalledTimes(1);
await act(async () => {
pendingOrder.resolve(nativeRechargeResponse());
await pendingOrder.promise;
});
});
test('does not let a late payment confirmation overwrite a newer wallet operation', async () => {
const pendingConfirmation = deferred<{
order: ReturnType<typeof nativeRechargeResponse>['order'];
center: ReturnType<typeof nativeRechargeResponse>['center'];
}>();
profileClientMocks.createPlatformProfileRechargeOrder.mockResolvedValue(
nativeRechargeResponse(80),
);
profileClientMocks.confirmWechatPlatformProfileRechargeOrder.mockReturnValue(
pendingConfirmation.promise,
);
profileClientMocks.getPlatformProfileRechargeCenter.mockRejectedValue(
new Error('refresh unavailable'),
);
usePlatformWalletStore.getState().setWalletOwner('user-a');
const { result } = renderController(userA);
act(() => result.current.buyRechargeProduct(rechargeProduct));
await waitFor(() => {
expect(result.current.nativeWechatPayment?.orderId).toBe('order-a');
});
act(() => result.current.confirmNativeWechatPayment());
act(() => {
const newerSnapshot = usePlatformWalletStore
.getState()
.captureWalletBalanceSnapshot('user-a');
usePlatformWalletStore
.getState()
.applyWalletBalanceSnapshot(newerSnapshot!, mudPointBalance(150));
});
await act(async () => {
pendingConfirmation.resolve({
order: {
...nativeRechargeResponse().order,
status: 'paid',
},
center: nativeRechargeResponse(100).center,
});
await pendingConfirmation.promise;
await Promise.resolve();
});
expect(usePlatformWalletStore.getState().mudPointBalance?.totalPoints).toBe(
150,
);
});
test('ignores an old owner order response after the account changes', async () => {
const pendingOrder = deferred<ReturnType<typeof nativeRechargeResponse>>();
profileClientMocks.createPlatformProfileRechargeOrder
.mockReturnValueOnce(pendingOrder.promise)
.mockResolvedValueOnce(nativeRechargeResponse(90, 'order-b'));
usePlatformWalletStore.getState().setWalletOwner('user-a');
const { result, rerender } = renderController(userA);
act(() => result.current.buyRechargeProduct(rechargeProduct));
const oldAccountSignal = profileClientMocks
.createPlatformProfileRechargeOrder.mock.calls[0]?.[2]
?.signal as AbortSignal;
expect(oldAccountSignal.aborted).toBe(false);
expect(result.current.submittingRechargeProductId).toBe('points-60');
act(() => {
rerender({ user: userB });
usePlatformWalletStore.getState().setWalletOwner('user-b');
});
expect(oldAccountSignal.aborted).toBe(true);
act(() => result.current.buyRechargeProduct(rechargeProduct));
await waitFor(() => {
expect(result.current.nativeWechatPayment?.orderId).toBe('order-b');
});
await act(async () => {
pendingOrder.resolve(nativeRechargeResponse());
await pendingOrder.promise;
await Promise.resolve();
});
expect(result.current.submittingRechargeProductId).toBeNull();
expect(result.current.nativeWechatPayment?.orderId).toBe('order-b');
expect(result.current.rechargePaymentResult).toBeNull();
expect(result.current.rechargeCenter?.walletBalance).toBe(90);
expect(usePlatformWalletStore.getState()).toMatchObject({
ownerUserId: 'user-b',
mudPointBalance: mudPointBalance(90),
});
});
test('aborts an in-flight recharge write when the controller unmounts', () => {
profileClientMocks.createPlatformProfileRechargeOrder.mockReturnValue(
new Promise(() => undefined),
);
usePlatformWalletStore.getState().setWalletOwner('user-a');
const { result, unmount } = renderController(userA);
act(() => result.current.buyRechargeProduct(rechargeProduct));
const signal = profileClientMocks.createPlatformProfileRechargeOrder.mock
.calls[0]?.[2]?.signal as AbortSignal;
expect(signal.aborted).toBe(false);
unmount();
expect(signal.aborted).toBe(true);
});
test('ignores an old owner native confirmation after the account changes', async () => {
const pendingConfirmation = deferred<{
order: ReturnType<typeof nativeRechargeResponse>['order'];
center: ReturnType<typeof nativeRechargeResponse>['center'];
}>();
const onRechargeSuccess = vi.fn();
profileClientMocks.createPlatformProfileRechargeOrder.mockResolvedValue(
nativeRechargeResponse(),
);
profileClientMocks.confirmWechatPlatformProfileRechargeOrder.mockReturnValue(
pendingConfirmation.promise,
);
usePlatformWalletStore.getState().setWalletOwner('user-a');
const { result, rerender } = renderController(userA, onRechargeSuccess);
act(() => result.current.buyRechargeProduct(rechargeProduct));
await waitFor(() => {
expect(result.current.nativeWechatPayment?.orderId).toBe('order-a');
});
act(() => result.current.confirmNativeWechatPayment());
act(() => {
rerender({ user: userB });
usePlatformWalletStore.getState().setWalletOwner('user-b');
});
await act(async () => {
pendingConfirmation.resolve({
order: {
...nativeRechargeResponse().order,
status: 'paid',
},
center: nativeRechargeResponse(100).center,
});
await pendingConfirmation.promise;
await Promise.resolve();
});
expect(result.current.nativeWechatPayment).toBeNull();
expect(result.current.rechargePaymentResult).toBeNull();
expect(result.current.wechatRechargeOrderConfirmationState).toBeNull();
expect(onRechargeSuccess).not.toHaveBeenCalled();
expect(usePlatformWalletStore.getState()).toMatchObject({
ownerUserId: 'user-b',
mudPointBalance: null,
});
});
test('aborts delayed confirmation retries when the account changes', async () => {
vi.useFakeTimers();
try {
profileClientMocks.createPlatformProfileRechargeOrder.mockResolvedValue(
nativeRechargeResponse(),
);
profileClientMocks.confirmWechatPlatformProfileRechargeOrder.mockResolvedValue(
{
order: nativeRechargeResponse().order,
center: nativeRechargeResponse().center,
},
);
usePlatformWalletStore.getState().setWalletOwner('user-a');
const { result, rerender } = renderController(userA);
await act(async () => {
result.current.buyRechargeProduct(rechargeProduct);
await Promise.resolve();
await Promise.resolve();
});
expect(result.current.nativeWechatPayment?.orderId).toBe('order-a');
await act(async () => {
result.current.confirmNativeWechatPayment();
await Promise.resolve();
await Promise.resolve();
});
expect(
profileClientMocks.confirmWechatPlatformProfileRechargeOrder,
).toHaveBeenCalledTimes(1);
const confirmationSignal = profileClientMocks
.confirmWechatPlatformProfileRechargeOrder.mock.calls[0]?.[1]
?.signal as AbortSignal;
expect(confirmationSignal.aborted).toBe(false);
expect(
profileClientMocks.watchWechatPlatformProfileRechargeOrder,
).toHaveBeenCalledWith('order-a', { signal: confirmationSignal });
act(() => {
rerender({ user: userB });
usePlatformWalletStore.getState().setWalletOwner('user-b');
});
expect(confirmationSignal.aborted).toBe(true);
await act(async () => {
await vi.advanceTimersByTimeAsync(5000);
});
expect(
profileClientMocks.confirmWechatPlatformProfileRechargeOrder,
).toHaveBeenCalledTimes(1);
expect(apiClientMocks.clearStoredAccessToken).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
test('does not clear the new owner token from an old owner payment error', async () => {
const pendingOrder = deferred<never>();
paymentPlatformMocks.resolveProfileRechargeProductPaymentChannel.mockReturnValue(
'wechat_mp_virtual',
);
hostBridgeMocks.getHostRuntime.mockReturnValue({
kind: 'wechat_mini_program',
});
profileClientMocks.createPlatformProfileRechargeOrder
.mockReturnValueOnce(pendingOrder.promise)
.mockResolvedValueOnce(nativeRechargeResponse(70, 'order-b'));
usePlatformWalletStore.getState().setWalletOwner('user-a');
const { result, rerender } = renderController(userA);
act(() => result.current.buyRechargeProduct(rechargeProduct));
act(() => {
rerender({ user: userB });
usePlatformWalletStore.getState().setWalletOwner('user-b');
});
paymentPlatformMocks.resolveProfileRechargeProductPaymentChannel.mockReturnValue(
'wechat_native',
);
act(() => result.current.buyRechargeProduct(rechargeProduct));
await waitFor(() => {
expect(result.current.nativeWechatPayment?.orderId).toBe('order-b');
});
await act(async () => {
pendingOrder.reject(new Error('当前登录设备不支持充值'));
await pendingOrder.promise.catch(() => undefined);
await Promise.resolve();
});
expect(apiClientMocks.clearStoredAccessToken).not.toHaveBeenCalled();
expect(hostBridgeMocks.requestHostLogin).not.toHaveBeenCalled();
expect(result.current.rechargeError).toBeNull();
expect(result.current.rechargePaymentResult).toBeNull();
expect(result.current.nativeWechatPayment?.orderId).toBe('order-b');
expect(usePlatformWalletStore.getState()).toMatchObject({
ownerUserId: 'user-b',
mudPointBalance: mudPointBalance(70),
});
});
});
@@ -0,0 +1,128 @@
/* @vitest-environment jsdom */
import { act } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { usePlatformWalletStore } from '../../stores/usePlatformWalletStore';
import {
profileClientMocks,
renderController,
userA,
userB,
} from './usePlatformProfileCenterController.testSupport';
describe('usePlatformProfileCenterController redemption lifecycle', () => {
beforeEach(() => {
window.history.replaceState(null, '', '/profile');
usePlatformWalletStore.getState().resetWalletBalance();
vi.clearAllMocks();
});
test('ignores a reward-code response after the account changes', async () => {
let resolveReward!: (value: {
walletBalance: number;
amountGranted: number;
ledgerEntry: never;
}) => void;
profileClientMocks.redeemPlatformProfileRewardCode.mockImplementation(
() =>
new Promise((resolve) => {
resolveReward = resolve;
}),
);
const onRechargeSuccess = vi.fn();
const { result, rerender } = renderController(userA, onRechargeSuccess);
act(() => result.current.setRewardCodeInput('reward-code'));
act(() => result.current.submitRewardCode());
const oldAccountSignal = profileClientMocks.redeemPlatformProfileRewardCode
.mock.calls[0]?.[1]?.signal as AbortSignal;
expect(oldAccountSignal.aborted).toBe(false);
rerender({ user: userB });
expect(oldAccountSignal.aborted).toBe(true);
await act(async () => {
resolveReward({
walletBalance: 100,
amountGranted: 20,
ledgerEntry: undefined as never,
});
});
expect(result.current.rewardCodeSuccess).toBeNull();
expect(result.current.isSubmittingRewardCode).toBe(false);
expect(onRechargeSuccess).not.toHaveBeenCalled();
});
test('ignores an invite-code response after the account changes', async () => {
let resolveReferral!: (value: {
center: never;
inviteeRewardGranted: boolean;
inviterRewardGranted: boolean;
inviteeBalanceAfter: number;
inviterBalanceAfter: number;
}) => void;
profileClientMocks.redeemPlatformProfileReferralInviteCode.mockImplementation(
() =>
new Promise((resolve) => {
resolveReferral = resolve;
}),
);
const onRechargeSuccess = vi.fn();
const { result, rerender } = renderController(userA, onRechargeSuccess);
act(() => result.current.setReferralRedeemCode('invite-code'));
act(() => result.current.submitReferralRedeemCode());
const oldAccountSignal = profileClientMocks
.redeemPlatformProfileReferralInviteCode.mock.calls[0]?.[1]
?.signal as AbortSignal;
expect(oldAccountSignal.aborted).toBe(false);
rerender({ user: userB });
expect(oldAccountSignal.aborted).toBe(true);
await act(async () => {
resolveReferral({
center: undefined as never,
inviteeRewardGranted: true,
inviterRewardGranted: false,
inviteeBalanceAfter: 100,
inviterBalanceAfter: 0,
});
});
expect(result.current.referralSuccess).toBeNull();
expect(result.current.isSubmittingReferralRedeem).toBe(false);
expect(onRechargeSuccess).not.toHaveBeenCalled();
});
test('clears referral UI and ignores a late referral-center read after account change', async () => {
let resolveReferralCenter!: (value: never) => void;
profileClientMocks.getPlatformProfileReferralInviteCenter.mockImplementation(
() =>
new Promise((resolve) => {
resolveReferralCenter = resolve;
}),
);
const { result, rerender } = renderController(userA);
act(() => {
result.current.openProfilePopupPanel('redeem');
result.current.setReferralRedeemCode('USER-A-CODE');
result.current.loadReferralCenter();
});
expect(result.current.profilePopupPanel).toBe('redeem');
expect(result.current.isLoadingReferral).toBe(true);
rerender({ user: userB });
expect(result.current.profilePopupPanel).toBeNull();
expect(result.current.referralRedeemCode).toBe('');
expect(result.current.referralCenter).toBeNull();
expect(result.current.isLoadingReferral).toBe(false);
await act(async () => {
resolveReferralCenter({
inviteCode: 'USER-A',
inviteLinkPath: '/?inviteCode=USER-A',
} as never);
});
expect(result.current.referralCenter).toBeNull();
expect(result.current.isLoadingReferral).toBe(false);
});
});
@@ -0,0 +1,102 @@
/* @vitest-environment jsdom */
import { renderHook } from '@testing-library/react';
import { vi } from 'vitest';
import type { AuthUser } from '../../services/authService';
const profileClientMocks = vi.hoisted(() => ({
confirmWechatPlatformProfileRechargeOrder: vi.fn(),
createPlatformProfileRechargeOrder: vi.fn(),
getPlatformProfileRechargeCenter: vi.fn(),
getPlatformProfileReferralInviteCenter: vi.fn(),
getPlatformProfileWalletLedger: vi.fn(),
redeemPlatformProfileReferralInviteCode: vi.fn(),
redeemPlatformProfileRewardCode: vi.fn(),
watchWechatPlatformProfileRechargeOrder: vi.fn(),
}));
const apiClientMocks = vi.hoisted(() => ({
clearStoredAccessToken: vi.fn(),
}));
const hostBridgeMocks = vi.hoisted(() => ({
getHostRuntime: vi.fn(() => ({ kind: 'browser' })),
requestHostLogin: vi.fn(),
requestHostPayment: vi.fn(),
}));
const paymentPlatformMocks = vi.hoisted(() => ({
resolveProfileRechargeProductPaymentChannel: vi.fn(() => 'wechat_native'),
}));
vi.mock(
'../../services/platform-entry/platformProfileClient',
() => profileClientMocks,
);
vi.mock('../../services/apiClient', async () => {
const actual = await vi.importActual<
typeof import('../../services/apiClient')
>('../../services/apiClient');
return { ...actual, ...apiClientMocks };
});
vi.mock('../../services/host-bridge/hostBridge', async () => {
const actual = await vi.importActual<
typeof import('../../services/host-bridge/hostBridge')
>('../../services/host-bridge/hostBridge');
return { ...actual, ...hostBridgeMocks };
});
vi.mock('../../services/payment/paymentPlatform', async () => {
const actual = await vi.importActual<
typeof import('../../services/payment/paymentPlatform')
>('../../services/payment/paymentPlatform');
return { ...actual, ...paymentPlatformMocks };
});
export {
apiClientMocks,
hostBridgeMocks,
paymentPlatformMocks,
profileClientMocks,
};
import { usePlatformProfileCenterController } from './usePlatformProfileCenterController';
const baseUser = {
publicUserCode: '100001',
displayName: '测试用户',
avatarUrl: null,
phoneNumberMasked: null,
loginMethod: 'password',
bindingStatus: 'active',
wechatBound: false,
} satisfies Omit<AuthUser, 'id'>;
export const userA = { ...baseUser, id: 'user-a' } satisfies AuthUser;
export const userB = {
...baseUser,
id: 'user-b',
publicUserCode: '100002',
} satisfies AuthUser;
export function renderController(
currentUser: AuthUser,
onRechargeSuccess = vi.fn(),
) {
const requestLogin = vi.fn();
return renderHook(
({ user }) =>
usePlatformProfileCenterController({
activeTab: 'settings',
isAuthenticated: true,
showRechargeEntry: true,
onRechargeSuccess,
requestLogin,
currentUser: user,
}),
{ initialProps: { user: currentUser } },
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,33 @@
/* @vitest-environment jsdom */
import { act, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { usePlatformWalletStore } from '../../stores/usePlatformWalletStore';
import {
profileClientMocks,
renderController,
userA,
} from './usePlatformProfileCenterController.testSupport';
describe('usePlatformProfileCenterController wallet ledger', () => {
beforeEach(() => {
window.history.replaceState(null, '', '/profile');
usePlatformWalletStore.getState().resetWalletBalance();
vi.clearAllMocks();
});
test('settles a valid read without depending on wallet-store owner initialization', async () => {
profileClientMocks.getPlatformProfileWalletLedger.mockResolvedValue({
entries: [],
});
const { result } = renderController(userA);
act(() => result.current.loadWalletLedger());
await waitFor(() => {
expect(result.current.walletLedger).toEqual({ entries: [] });
expect(result.current.isLoadingWalletLedger).toBe(false);
});
});
});