feat(user): sync entitlement snapshot

This commit is contained in:
2026-06-29 10:37:37 +08:00
parent 455204e1e4
commit 58cd2a7545
22 changed files with 479 additions and 54 deletions
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import { toView } from "@/stores/user/user-machine.helpers";
import {
applyEntitlementSnapshotToView,
toView,
} from "@/stores/user/user-machine.helpers";
describe("toView", () => {
it("fills optional user fields with stable defaults", () => {
@@ -11,6 +14,8 @@ describe("toView", () => {
avatarUrl: "",
intimacy: 0,
dolBalance: 0,
creditBalance: 0,
vipExpiresAt: null,
relationshipStage: "",
currentMood: "",
isGuest: false,
@@ -28,6 +33,8 @@ describe("toView", () => {
avatarUrl: "https://example.com/avatar.png",
intimacy: 42,
dolBalance: 12,
creditBalance: 120,
vipExpiresAt: "2026-07-26T00:00:00+00:00",
relationshipStage: "close_friend",
currentMood: "playful",
isGuest: true,
@@ -41,6 +48,8 @@ describe("toView", () => {
avatarUrl: "https://example.com/avatar.png",
intimacy: 42,
dolBalance: 12,
creditBalance: 120,
vipExpiresAt: "2026-07-26T00:00:00+00:00",
relationshipStage: "close_friend",
currentMood: "playful",
isGuest: true,
@@ -48,4 +57,19 @@ describe("toView", () => {
voiceMinutesRemaining: 30,
});
});
it("merges entitlement snapshot into user view fields", () => {
const user = toView({ id: "user-3", username: "Nora", isVip: false });
expect(
applyEntitlementSnapshotToView(user, {
isVip: true,
creditBalance: 120,
}),
).toMatchObject({
isVip: true,
creditBalance: 120,
dolBalance: 120,
});
});
});
+48 -13
View File
@@ -3,7 +3,10 @@ import { createActor, fromPromise, waitFor } from "xstate";
import type { UserView } from "@/data/dto/user";
import { userMachine } from "@/stores/user/user-machine";
import type { InitData } from "@/stores/user/user-machine.helpers";
import type {
InitData,
UserFetchData,
} from "@/stores/user/user-machine.helpers";
function makeUser(overrides: Partial<UserView> = {}): UserView {
return {
@@ -13,6 +16,8 @@ function makeUser(overrides: Partial<UserView> = {}): UserView {
avatarUrl: "https://example.com/avatar.png",
intimacy: 42,
dolBalance: 7,
creditBalance: 7,
vipExpiresAt: null,
relationshipStage: "close_friend",
currentMood: "happy",
isGuest: false,
@@ -22,10 +27,21 @@ function makeUser(overrides: Partial<UserView> = {}): UserView {
};
}
function makeEntitlementSnapshot(
overrides: Partial<InitData["snapshot"]> = {},
): NonNullable<InitData["snapshot"]> {
return {
isVip: false,
creditBalance: 7,
...overrides,
};
}
function createTestUserMachine(
overrides: Partial<{
initData: InitData;
fetchedUser: UserView | null;
fetchedData: UserFetchData;
logoutSpy: () => void;
}> = {},
) {
@@ -34,16 +50,26 @@ function createTestUserMachine(
return userMachine.provide({
actors: {
userInit: fromPromise<InitData>(async () => ({
user: makeUser(),
avatarUrl: "https://example.com/avatar.png",
...overrides.initData,
user: overrides.initData?.user ?? makeUser(),
avatarUrl:
overrides.initData?.avatarUrl ?? "https://example.com/avatar.png",
snapshot: overrides.initData?.snapshot ?? null,
})),
userFetch: fromPromise<UserView | null>(
async () =>
"fetchedUser" in overrides
? overrides.fetchedUser ?? null
: makeUser({ username: "Fetched" }),
),
userFetch: fromPromise<UserFetchData>(async () => {
if ("fetchedData" in overrides && overrides.fetchedData) {
return overrides.fetchedData;
}
if ("fetchedUser" in overrides) {
return {
user: overrides.fetchedUser ?? null,
snapshot: null,
};
}
return {
user: makeUser({ username: "Fetched" }),
snapshot: null,
};
}),
userLogout: fromPromise<void>(async () => {
logoutSpy();
}),
@@ -58,7 +84,9 @@ describe("userMachine", () => {
initData: {
user: makeUser({ username: "Local User" }),
avatarUrl: "https://example.com/local-avatar.png",
snapshot: null,
},
fetchedUser: null,
}),
).start();
@@ -78,10 +106,8 @@ describe("userMachine", () => {
actor.send({ type: "UserUpdate", user: makeUser({ username: "Before" }) });
actor.send({ type: "UserUpdateUsername", username: "After" });
actor.send({ type: "UserUpdatePronouns", pronouns: "They" });
expect(actor.getSnapshot().context.currentUser?.username).toBe("After");
expect(actor.getSnapshot().context.pronouns).toBe("They");
actor.stop();
});
@@ -89,7 +115,13 @@ describe("userMachine", () => {
it("fetches the latest user and clears loading state when done", async () => {
const actor = createActor(
createTestUserMachine({
fetchedUser: makeUser({ username: "Fresh User", isVip: true }),
fetchedData: {
user: makeUser({ username: "Fresh User" }),
snapshot: makeEntitlementSnapshot({
isVip: true,
creditBalance: 120,
}),
},
}),
).start();
@@ -101,6 +133,9 @@ describe("userMachine", () => {
const context = actor.getSnapshot().context;
expect(context.currentUser?.username).toBe("Fresh User");
expect(context.currentUser?.isVip).toBe(true);
expect(context.currentUser?.creditBalance).toBe(120);
expect(context.isVip).toBe(true);
expect(context.creditBalance).toBe(120);
expect(context.isLoading).toBe(false);
actor.stop();
+4 -4
View File
@@ -25,10 +25,10 @@ import type { UserState as MachineContext, UserEvent } from "./user-machine";
*/
interface UserState {
currentUser: MachineContext["currentUser"];
pronouns: string;
coinBalance: number;
isLoading: boolean;
avatarUrl: string | null;
isVip: boolean;
creditBalance: number;
}
const UserStateCtx = createContext<UserState | null>(null);
@@ -45,14 +45,14 @@ export function UserProvider({ children }: UserProviderProps) {
const userState = useMemo<UserState>(
() => ({
currentUser: state.context.currentUser,
pronouns: state.context.pronouns,
coinBalance: state.context.coinBalance,
isLoading:
state.matches("initializing") ||
state.matches("fetching") ||
state.matches("loggingOut") ||
state.context.isLoading,
avatarUrl: state.context.avatarUrl,
isVip: state.context.isVip,
creditBalance: state.context.creditBalance,
}),
[state],
);
-1
View File
@@ -8,7 +8,6 @@ export type UserEvent =
| { type: "UserFetch" }
| { type: "UserUpdate"; user: UserView }
| { type: "UserUpdateUsername"; username: string }
| { type: "UserUpdatePronouns"; pronouns: string }
| { type: "UserClearLocal" }
| { type: "UserLogout" }
| { type: "UserDeleteChatHistory" }
+39 -11
View File
@@ -14,7 +14,6 @@
import { fromPromise } from "xstate";
import type { UserView } from "@/data/dto/user";
import { userRepository } from "@/data/repositories/user_repository";
import { authRepository } from "@/data/repositories/auth_repository";
import type {
@@ -23,7 +22,15 @@ import type {
} from "@/data/repositories/interfaces";
import { Result } from "@/utils";
import { type InitData, readInitData, toView, userStorage } from "./user-machine.helpers";
import {
applyEntitlementSnapshotToView,
type InitData,
readInitData,
toEntitlementSnapshot,
toView,
type UserFetchData,
userStorage,
} from "./user-machine.helpers";
// ============================================================
// 仓库注入
@@ -46,17 +53,38 @@ export const userInitActor = fromPromise<InitData>(async () => readInitData());
// Fetch actor:调 API 拉当前用户 + 持久化
// ============================================================
/**
* 调 `userRepo.getCurrentUser` 拉当前 user
* - 成功 → 转 UserView + 写本地(userStorage.setUser→ 返回 View
* - 失败 → 返回 nullmachine 走 onDonecontext 保持不变;onError 兜底)
* 调 `userRepo.getCurrentUser + getEntitlements` 拉当前 user 与权益
* - user 成功 → 转 UserView + 写本地(userStorage.setUser
* - entitlements 成功 → 提取 isVip/creditBalance 写本地轻量快照
* - 任一失败都不阻断另一方,machine 层负责保留已有 context
*/
export const userFetchActor = fromPromise<UserView | null>(async () => {
const result = await userRepo.getCurrentUser();
if (Result.isErr(result)) return null;
const view = toView(result.data.toJson());
export const userFetchActor = fromPromise<UserFetchData>(async () => {
const [userResult, entitlementsResult] = await Promise.all([
userRepo.getCurrentUser(),
userRepo.getEntitlements(),
]);
const snapshot = Result.isOk(entitlementsResult)
? toEntitlementSnapshot({
isVip: entitlementsResult.data.isVip,
creditBalance: entitlementsResult.data.creditBalance,
})
: null;
if (snapshot) {
await userStorage.setEntitlementSnapshot(snapshot);
}
if (Result.isErr(userResult)) {
return { user: null, snapshot };
}
const view = applyEntitlementSnapshotToView(
toView(userResult.data.toJson()),
snapshot,
);
// 持久化到本地
await userStorage.setUser(result.data.toJson());
return view;
await userStorage.setUser(userResult.data.toJson());
return { user: view, snapshot };
});
// ============================================================
+46 -4
View File
@@ -14,6 +14,7 @@
*/
import type { UserView } from "@/data/dto/user";
import type { UserEntitlementSnapshotData } from "@/data/schemas/user";
import { UserStorage } from "@/data/storage/user/user_storage";
import { Result } from "@/utils";
@@ -36,6 +37,12 @@ export const userStorage = UserStorage.getInstance();
export interface InitData {
user: UserView | null;
avatarUrl: string | null;
snapshot: UserEntitlementSnapshotData | null;
}
export interface UserFetchData {
user: UserView | null;
snapshot: UserEntitlementSnapshotData | null;
}
// ============================================================
@@ -53,19 +60,25 @@ export function toView(u: {
avatarUrl?: string;
intimacy?: number;
dolBalance?: number;
creditBalance?: number;
vipExpiresAt?: string | null;
relationshipStage?: string;
currentMood?: string;
isGuest?: boolean;
isVip?: boolean;
voiceMinutesRemaining?: number;
}): UserView {
const creditBalance = u.creditBalance ?? u.dolBalance ?? 0;
return {
id: u.id,
username: u.username,
email: u.email ?? "",
avatarUrl: u.avatarUrl ?? "",
intimacy: u.intimacy ?? 0,
dolBalance: u.dolBalance ?? 0,
dolBalance: u.dolBalance ?? creditBalance,
creditBalance,
vipExpiresAt: u.vipExpiresAt ?? null,
relationshipStage: u.relationshipStage ?? "",
currentMood: u.currentMood ?? "",
isGuest: u.isGuest ?? false,
@@ -74,6 +87,29 @@ export function toView(u: {
};
}
export function applyEntitlementSnapshotToView(
user: UserView | null,
snapshot: UserEntitlementSnapshotData | null,
): UserView | null {
if (!user || !snapshot) return user;
return {
...user,
isVip: snapshot.isVip,
dolBalance: snapshot.creditBalance,
creditBalance: snapshot.creditBalance,
};
}
export function toEntitlementSnapshot(input: {
isVip: boolean;
creditBalance: number;
}): UserEntitlementSnapshotData {
return {
isVip: input.isVip,
creditBalance: input.creditBalance,
};
}
// ============================================================
// Init 数据加载(userInitActor 用)
// ============================================================
@@ -84,14 +120,20 @@ export function toView(u: {
* - Result.isOk(_) && data 双重判空:Result 包装层 + 业务 null
*/
export async function readInitData(): Promise<InitData> {
const [userResult, avatarResult] = await Promise.all([
const [userResult, avatarResult, snapshotResult] = await Promise.all([
userStorage.getUser(),
userStorage.getAvatarUrl(),
userStorage.getEntitlementSnapshot(),
]);
let snapshot: UserEntitlementSnapshotData | null = null;
if (Result.isOk(snapshotResult) && snapshotResult.data) {
snapshot = snapshotResult.data;
}
let user: UserView | null = null;
if (Result.isOk(userResult) && userResult.data) {
user = toView(userResult.data);
user = applyEntitlementSnapshotToView(toView(userResult.data), snapshot);
}
let avatarUrl: string | null = null;
@@ -99,5 +141,5 @@ export async function readInitData(): Promise<InitData> {
avatarUrl = avatarResult.data;
}
return { user, avatarUrl };
return { user, avatarUrl, snapshot };
}
+33 -15
View File
@@ -10,6 +10,7 @@ import {
userFetchActor,
userLogoutActor,
} from "./user-machine.actors";
import { applyEntitlementSnapshotToView } from "./user-machine.helpers";
// 重新导出 State / Event 类型,保持 machine 文件的公共 API 不变
export type { UserState } from "./user-state";
@@ -32,7 +33,11 @@ export const userMachine = setup({
actions: {
updateUser: assign(({ event }) => {
if (event.type !== "UserUpdate") return {};
return { currentUser: event.user };
return {
currentUser: event.user,
isVip: event.user.isVip,
creditBalance: event.user.creditBalance,
};
}),
updateUsername: assign(({ context, event }) => {
@@ -42,14 +47,11 @@ export const userMachine = setup({
};
}),
updatePronouns: assign(({ event }) => {
if (event.type !== "UserUpdatePronouns") return {};
return { pronouns: event.pronouns };
}),
clearUser: assign(() => ({
currentUser: null,
avatarUrl: null,
isVip: false,
creditBalance: 0,
})),
},
}).createMachine({
@@ -67,9 +69,6 @@ export const userMachine = setup({
UserUpdateUsername: {
actions: "updateUsername",
},
UserUpdatePronouns: {
actions: "updatePronouns",
},
UserClearLocal: {
actions: "clearUser",
},
@@ -83,14 +82,18 @@ export const userMachine = setup({
invoke: {
src: "userInit",
onDone: {
target: "idle",
target: "fetching",
actions: assign(({ event }) => ({
currentUser: event.output.user,
avatarUrl: event.output.avatarUrl,
isVip: event.output.snapshot?.isVip ?? initialState.isVip,
creditBalance:
event.output.snapshot?.creditBalance ??
initialState.creditBalance,
})),
},
onError: {
target: "idle",
target: "fetching",
},
},
},
@@ -100,10 +103,25 @@ export const userMachine = setup({
src: "userFetch",
onDone: {
target: "idle",
actions: assign(({ context, event }) => ({
currentUser: event.output ?? context.currentUser,
isLoading: false,
})),
actions: assign(({ context, event }) => {
const snapshot =
event.output.snapshot ??
(context.currentUser
? {
isVip: context.isVip,
creditBalance: context.creditBalance,
}
: null);
const baseUser = event.output.user ?? context.currentUser;
return {
currentUser:
applyEntitlementSnapshotToView(baseUser, snapshot) ??
context.currentUser,
isVip: snapshot?.isVip ?? context.isVip,
creditBalance: snapshot?.creditBalance ?? context.creditBalance,
isLoading: false,
};
}),
},
onError: {
target: "idle",
+4 -4
View File
@@ -5,16 +5,16 @@ import type { UserView } from "@/data/dto/user";
export interface UserState {
currentUser: UserView | null;
pronouns: string;
coinBalance: number;
isLoading: boolean;
avatarUrl: string | null;
isVip: boolean;
creditBalance: number;
}
export const initialState: UserState = {
currentUser: null,
pronouns: "He",
coinBalance: 45,
isLoading: false,
avatarUrl: null,
isVip: false,
creditBalance: 0,
};