feat(private-room): migrate to album APIs

This commit is contained in:
2026-07-14 12:30:22 +08:00
parent 9612a28b3c
commit 538af6d45f
48 changed files with 1529 additions and 2092 deletions
@@ -2,259 +2,208 @@ import { describe, expect, it } from "vitest";
import { createActor, fromPromise, waitFor } from "xstate";
import {
PrivateRoomMomentsResponse,
PrivateRoomUnlockResponse,
PrivateAlbumsResponse,
PrivateAlbumUnlockResponse,
} from "@/data/dto/private-room";
import { privateRoomMachine } from "@/stores/private-room/private-room-machine";
const baseMoment = {
momentId: "schedule:91",
source: "elio_schedules",
sourceId: "91",
characterId: "elio",
author: {
id: "elio",
name: "Elio Silvestri",
avatarUrl: null,
},
createdAt: "2026-07-01T08:11:35+00:00",
publishedAt: "2026-07-01T08:11:35+00:00",
timeText: "7 days ago",
title: "Paris morning",
content: null,
text: null,
textPreview: "Unlock to view private room photos",
mediaCount: 1,
images: [
{
url: null,
type: "image",
locked: true,
index: 0,
},
],
locked: true,
unlocked: false,
unlockCost: 40,
unlockCostPerImage: 40,
requiredCredits: 40,
currency: "credits",
lockDetail: {
locked: true,
showContent: false,
showUpgrade: true,
reason: "private_room_moment",
hint: "40 credits · Unlock photo",
actionLabel: "Unlock",
type: "private_room_moment",
requiredCredits: 40,
currentCredits: 100,
shortfallCredits: 0,
mediaCount: 1,
unlockCostPerImage: 40,
},
};
const ALBUM_ID = "a1b2c3d4-0000-0000-0000-000000000000";
const COVER_URL =
"https://dbapi.banlv-ai.com/storage/v1/object/public/elio-schedules/01.jpg";
function makeMomentsResponse(
overrides: Partial<Parameters<typeof PrivateRoomMomentsResponse.from>[0]> = {},
): PrivateRoomMomentsResponse {
return PrivateRoomMomentsResponse.from({
profile: {
characterId: "elio",
displayName: "Elio Silvestri",
authorName: "Elio Silvestri",
avatarUrl: null,
coverUrl: null,
title: "Elio Private room",
subtitle: "Join me, unlock my private room",
},
items: [baseMoment],
nextCursor: null,
hasMore: false,
creditBalance: 100,
unlockCostDefault: 40,
unlockCostPerImage: 40,
currency: "credits",
source: "elio_schedules",
function makeAlbum(index = 0) {
return {
albumId: index === 0 ? ALBUM_ID : `album-${index}`,
title: `Private album ${index + 1}`,
content: null,
previewText: "Only for you.",
imageCount: 8,
images: [{ url: `${COVER_URL}?album=${index}`, locked: true, index: 0 }],
locked: true,
unlocked: false,
unlockCost: 320,
publishedAt: "2026-07-13T00:00:00+00:00",
lockDetail: { locked: true },
};
}
function makeAlbumsResponse(
overrides: Partial<Parameters<typeof PrivateAlbumsResponse.from>[0]> = {},
): PrivateAlbumsResponse {
return PrivateAlbumsResponse.from({
items: [makeAlbum()],
creditBalance: 500,
...overrides,
});
}
function makeUnlockResponse(
overrides: Partial<Parameters<typeof PrivateRoomUnlockResponse.from>[0]> = {},
): PrivateRoomUnlockResponse {
return PrivateRoomUnlockResponse.from({
...baseMoment,
overrides: Partial<Parameters<typeof PrivateAlbumUnlockResponse.from>[0]> = {},
): PrivateAlbumUnlockResponse {
return PrivateAlbumUnlockResponse.from({
albumId: ALBUM_ID,
locked: false,
unlocked: true,
images: [
{
url: "https://example.supabase.co/storage/v1/object/public/elio-schedules/photo.jpg",
type: "image",
locked: false,
index: 0,
},
],
reason: "ok",
creditsCharged: 40,
creditBalance: 60,
unlockCost: 320,
requiredCredits: 320,
creditBalance: 180,
shortfallCredits: 0,
images: Array.from({ length: 8 }, (_, index) => ({
url: `${COVER_URL}?image=${index}`,
locked: false,
index,
})),
...overrides,
});
}
function createTestMachine(
options: {
firstPage?: PrivateRoomMomentsResponse;
morePage?: PrivateRoomMomentsResponse;
unlockResponse?: PrivateRoomUnlockResponse;
} = {},
) {
function createTestMachine(options: {
loadResponse?: PrivateAlbumsResponse;
unlockResponse?: PrivateAlbumUnlockResponse;
onLoad?: () => void;
} = {}) {
return privateRoomMachine.provide({
actors: {
loadMoments: fromPromise(async () => options.firstPage ?? makeMomentsResponse()),
loadMoreMoments: fromPromise(async () =>
options.morePage ??
makeMomentsResponse({
items: [
{
...baseMoment,
momentId: "schedule:92",
sourceId: "92",
},
],
hasMore: false,
nextCursor: null,
}),
),
unlockMoment: fromPromise(async () =>
options.unlockResponse ?? makeUnlockResponse(),
loadAlbums: fromPromise(async () => {
options.onLoad?.();
return options.loadResponse ?? makeAlbumsResponse();
}),
unlockAlbum: fromPromise(async () =>
(options.unlockResponse ?? makeUnlockResponse()),
),
},
});
}
async function loadMachine(options: Parameters<typeof createTestMachine>[0] = {}) {
const actor = createActor(createTestMachine(options)).start();
actor.send({ type: "PrivateRoomInit" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
return actor;
}
async function unlockFirstAlbum(
actor: Awaited<ReturnType<typeof loadMachine>>,
) {
actor.send({
type: "PrivateRoomUnlockRequested",
albumId: ALBUM_ID,
});
actor.send({ type: "PrivateRoomUnlockConfirmed" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
}
describe("privateRoomMachine", () => {
it("loads the first page", async () => {
const actor = createActor(createTestMachine()).start();
actor.send({ type: "PrivateRoomInit" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
const context = actor.getSnapshot().context;
expect(context.profile?.displayName).toBe("Elio Silvestri");
expect(context.items).toHaveLength(1);
expect(context.creditBalance).toBe(100);
actor.stop();
});
it("appends more moments without overwriting existing items", async () => {
const actor = createActor(
createTestMachine({
firstPage: makeMomentsResponse({
hasMore: true,
nextCursor: "cursor-1",
}),
it("loads only the first album page into its non-paginated state", async () => {
const actor = await loadMachine({
loadResponse: makeAlbumsResponse({
items: Array.from({ length: 20 }, (_, index) => makeAlbum(index)),
}),
).start();
actor.send({ type: "PrivateRoomInit" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
actor.send({ type: "PrivateRoomLoadMore" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
expect(actor.getSnapshot().context.items.map((item) => item.momentId)).toEqual([
"schedule:91",
"schedule:92",
]);
});
const context = actor.getSnapshot().context;
expect(context.items).toHaveLength(20);
expect(context.creditBalance).toBe(500);
expect(context).not.toHaveProperty("hasMore");
expect(context).not.toHaveProperty("nextCursor");
actor.stop();
});
it("replaces a locked moment after unlock success", async () => {
const actor = createActor(createTestMachine()).start();
actor.send({ type: "PrivateRoomInit" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
actor.send({
type: "PrivateRoomUnlockRequested",
momentId: "schedule:91",
});
actor.send({ type: "PrivateRoomUnlockConfirmed" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
it("patches the album images after a successful unlock", async () => {
const actor = await loadMachine();
await unlockFirstAlbum(actor);
const context = actor.getSnapshot().context;
expect(context.items[0]?.locked).toBe(false);
expect(context.items[0]?.images[0]?.url).toContain("https://");
expect(context.items[0]).toMatchObject({
albumId: ALBUM_ID,
locked: false,
unlocked: true,
title: "Private album 1",
});
expect(context.items[0]?.images).toHaveLength(8);
expect(context.items[0]?.lockDetail).toEqual({ locked: false });
expect(context.unlockSuccessNonce).toBe(1);
actor.stop();
});
it("exposes a paywall request for insufficient credits", async () => {
const actor = createActor(
createTestMachine({
unlockResponse: makeUnlockResponse({
...baseMoment,
reason: "insufficient_credits",
locked: true,
unlocked: false,
creditBalance: 10,
currentCredits: 10,
shortfallCredits: 30,
}),
it("keeps the album locked and exposes a paywall request when credits are low", async () => {
const actor = await loadMachine({
unlockResponse: makeUnlockResponse({
locked: true,
unlocked: false,
reason: "insufficient_credits",
creditBalance: 100,
shortfallCredits: 220,
images: [{ url: COVER_URL, locked: true, index: 0 }],
}),
).start();
actor.send({ type: "PrivateRoomInit" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
actor.send({
type: "PrivateRoomUnlockRequested",
momentId: "schedule:91",
});
actor.send({ type: "PrivateRoomUnlockConfirmed" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
await unlockFirstAlbum(actor);
const context = actor.getSnapshot().context;
expect(context.items[0]?.locked).toBe(true);
expect(context.unlockPaywallRequest).toMatchObject({
momentId: "schedule:91",
reason: "insufficient_credits",
shortfallCredits: 30,
});
expect(context.items[0]?.locked).toBe(true);
expect(context.unlockPaywallRequest).toEqual({
albumId: ALBUM_ID,
reason: "insufficient_credits",
requiredCredits: 320,
currentCredits: 100,
shortfallCredits: 220,
});
actor.stop();
});
it("refreshes and keeps an unlock error when the cost changes", async () => {
const actor = createActor(
createTestMachine({
unlockResponse: makeUnlockResponse({
...baseMoment,
reason: "cost_changed",
locked: true,
unlocked: false,
}),
it("reloads the first page when the expected cost changed", async () => {
let loadCount = 0;
const actor = await loadMachine({
onLoad: () => {
loadCount += 1;
},
unlockResponse: makeUnlockResponse({
locked: true,
unlocked: false,
reason: "cost_changed",
}),
).start();
actor.send({ type: "PrivateRoomInit" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
actor.send({
type: "PrivateRoomUnlockRequested",
momentId: "schedule:91",
});
actor.send({ type: "PrivateRoomUnlockConfirmed" });
await waitFor(actor, (snapshot) => snapshot.matches("ready"));
await unlockFirstAlbum(actor);
expect(loadCount).toBe(2);
expect(actor.getSnapshot().context.unlockErrorMessage).toBe(
"Unlock price changed. Please confirm again.",
);
actor.stop();
});
it("removes an album that no longer exists", async () => {
const actor = await loadMachine({
unlockResponse: makeUnlockResponse({
locked: true,
unlocked: false,
reason: "not_found",
images: [],
}),
});
await unlockFirstAlbum(actor);
expect(actor.getSnapshot().context.items).toHaveLength(0);
actor.stop();
});
it("keeps a refunded persistence failure locked and updates the balance", async () => {
const actor = await loadMachine({
unlockResponse: makeUnlockResponse({
locked: true,
unlocked: false,
reason: "persist_failed_refunded",
creditBalance: 500,
images: [{ url: COVER_URL, locked: true, index: 0 }],
}),
});
await unlockFirstAlbum(actor);
const context = actor.getSnapshot().context;
expect(context.items[0]?.locked).toBe(true);
expect(context.creditBalance).toBe(500);
expect(context.unlockErrorMessage).toContain("refunded");
actor.stop();
});
});
@@ -12,19 +12,15 @@ import type {
export interface PrivateRoomContextState {
status: string;
profile: MachineContext["profile"];
items: MachineContext["items"];
nextCursor: string | null;
hasMore: boolean;
creditBalance: number;
errorMessage: string | null;
unlockingMomentId: string | null;
unlockingAlbumId: string | null;
unlockErrorMessage: string | null;
pendingConfirmMomentId: string | null;
pendingConfirmAlbumId: string | null;
unlockPaywallRequest: MachineContext["unlockPaywallRequest"];
unlockSuccessNonce: number;
isLoading: boolean;
isLoadingMore: boolean;
isUnlocking: boolean;
}
@@ -63,19 +59,15 @@ function selectPrivateRoomState(
): PrivateRoomContextState {
return {
status: String(state.value),
profile: state.context.profile,
items: state.context.items,
nextCursor: state.context.nextCursor,
hasMore: state.context.hasMore,
creditBalance: state.context.creditBalance,
errorMessage: state.context.errorMessage,
unlockingMomentId: state.context.unlockingMomentId,
unlockingAlbumId: state.context.unlockingAlbumId,
unlockErrorMessage: state.context.unlockErrorMessage,
pendingConfirmMomentId: state.context.pendingConfirmMomentId,
pendingConfirmAlbumId: state.context.pendingConfirmAlbumId,
unlockPaywallRequest: state.context.unlockPaywallRequest,
unlockSuccessNonce: state.context.unlockSuccessNonce,
isLoading: state.matches("loading"),
isLoadingMore: state.matches("loadingMore"),
isUnlocking: state.matches("unlocking"),
};
}
@@ -1,8 +1,7 @@
export type PrivateRoomEvent =
| { type: "PrivateRoomInit" }
| { type: "PrivateRoomRefresh" }
| { type: "PrivateRoomLoadMore" }
| { type: "PrivateRoomUnlockRequested"; momentId: string }
| { type: "PrivateRoomUnlockRequested"; albumId: string }
| { type: "PrivateRoomUnlockConfirmed" }
| { type: "PrivateRoomUnlockCancelled" }
| { type: "PrivateRoomUnlockPaywallConsumed" };
@@ -1,8 +1,8 @@
import { fromPromise } from "xstate";
import type {
PrivateRoomMomentsResponse,
PrivateRoomUnlockResponse,
PrivateAlbumsResponse,
PrivateAlbumUnlockResponse,
} from "@/data/dto/private-room";
import { getPrivateRoomRepository } from "@/data/repositories/private_room_repository";
import { Result } from "@/utils";
@@ -12,10 +12,10 @@ import {
PRIVATE_ROOM_PAGE_SIZE,
} from "./private-room-machine.helpers";
export const loadPrivateRoomMomentsActor =
fromPromise<PrivateRoomMomentsResponse>(async () => {
export const loadPrivateAlbumsActor =
fromPromise<PrivateAlbumsResponse>(async () => {
const repo = getPrivateRoomRepository();
const result = await repo.getMoments({
const result = await repo.getAlbums({
character: PRIVATE_ROOM_CHARACTER,
limit: PRIVATE_ROOM_PAGE_SIZE,
});
@@ -23,27 +23,13 @@ export const loadPrivateRoomMomentsActor =
return result.data;
});
export const loadMorePrivateRoomMomentsActor = fromPromise<
PrivateRoomMomentsResponse,
{ cursor: string | null }
export const unlockPrivateAlbumActor = fromPromise<
PrivateAlbumUnlockResponse,
{ albumId: string; expectedCost: number }
>(async ({ input }) => {
const repo = getPrivateRoomRepository();
const result = await repo.getMoments({
character: PRIVATE_ROOM_CHARACTER,
limit: PRIVATE_ROOM_PAGE_SIZE,
cursor: input.cursor,
});
if (Result.isErr(result)) throw result.error;
return result.data;
});
export const unlockPrivateRoomMomentActor = fromPromise<
PrivateRoomUnlockResponse,
{ momentId: string; expectedCost: number }
>(async ({ input }) => {
const repo = getPrivateRoomRepository();
const result = await repo.unlockMoment(
input.momentId,
const result = await repo.unlockAlbum(
input.albumId,
input.expectedCost,
);
if (Result.isErr(result)) throw result.error;
@@ -1,7 +1,7 @@
import type {
PrivateRoomMoment,
PrivateRoomMomentsResponse,
PrivateRoomUnlockResponse,
import {
PrivateAlbum,
type PrivateAlbumsResponse,
type PrivateAlbumUnlockResponse,
} from "@/data/dto/private-room";
import type {
@@ -12,77 +12,82 @@ import type {
export const PRIVATE_ROOM_CHARACTER = "elio";
export const PRIVATE_ROOM_PAGE_SIZE = 20;
export function applyMomentsResponse(
response: PrivateRoomMomentsResponse,
export function applyAlbumsResponse(
response: PrivateAlbumsResponse,
): Partial<PrivateRoomState> {
return {
profile: response.profile,
items: response.items,
nextCursor: response.nextCursor,
hasMore: response.hasMore,
creditBalance: response.creditBalance,
errorMessage: null,
};
}
export function appendMomentsResponse(
context: PrivateRoomState,
response: PrivateRoomMomentsResponse,
): Partial<PrivateRoomState> {
const knownIds = new Set(context.items.map((item) => item.momentId));
const nextItems = [
...context.items,
...response.items.filter((item) => !knownIds.has(item.momentId)),
];
return {
profile: response.profile,
items: nextItems,
nextCursor: response.nextCursor,
hasMore: response.hasMore,
creditBalance: response.creditBalance,
errorMessage: null,
};
export function patchAlbumFromUnlock(
album: PrivateAlbum,
response: PrivateAlbumUnlockResponse,
): PrivateAlbum {
return PrivateAlbum.from({
...album.toJson(),
locked: response.locked,
unlocked: response.unlocked,
unlockCost: response.unlockCost || album.unlockCost,
images: response.images.length > 0 ? response.images : album.images,
lockDetail: { locked: response.locked },
});
}
export function replaceMoment(
items: readonly PrivateRoomMoment[],
nextMoment: PrivateRoomMoment,
): PrivateRoomMoment[] {
return items.map((item) =>
item.momentId === nextMoment.momentId ? nextMoment : item,
export function patchAlbumInList(
items: readonly PrivateAlbum[],
response: PrivateAlbumUnlockResponse,
): PrivateAlbum[] {
return items.map((album) =>
album.albumId === response.albumId
? patchAlbumFromUnlock(album, response)
: album,
);
}
export function removeAlbum(
items: readonly PrivateAlbum[],
albumId: string,
): PrivateAlbum[] {
return items.filter((album) => album.albumId !== albumId);
}
export function toPrivateRoomErrorMessage(error: unknown): string {
if (error instanceof Error && error.message) return error.message;
return "Private room is temporarily unavailable. Please try again.";
}
export function toUnlockErrorMessage(
response: PrivateRoomUnlockResponse,
response: PrivateAlbumUnlockResponse,
): string | null {
switch (response.reason) {
case "cost_changed":
return "Unlock price changed. Please confirm again.";
case "not_found":
return "This private room post is no longer available.";
case "no_media":
return "This private room post has no photos to unlock.";
case "unlock_in_progress":
return "This album is already unlocking. Please try again shortly.";
case "deduct_failed":
return "Credit deduction failed. Please try again.";
case "persist_failed_refunded":
return "Unlock failed and your credits were refunded. Please try again.";
case "not_found":
return "This private album is no longer available.";
default:
return response.unlocked ? null : "Unlock failed. Please try again.";
return response.unlocked && !response.locked
? null
: "Unlock failed. Please try again.";
}
}
export function toPaywallRequest(
response: PrivateRoomUnlockResponse,
response: PrivateAlbumUnlockResponse,
): PrivateRoomUnlockPaywallRequest {
return {
momentId: response.momentId,
albumId: response.albumId,
reason: response.reason,
requiredCredits: response.requiredCredits,
currentCredits: response.currentCredits || response.creditBalance,
requiredCredits: response.requiredCredits || response.unlockCost,
currentCredits: response.creditBalance,
shortfallCredits: response.shortfallCredits,
};
}
+53 -78
View File
@@ -1,20 +1,19 @@
import { assign, setup } from "xstate";
import type { PrivateRoomMoment } from "@/data/dto/private-room";
import type { PrivateAlbum } from "@/data/dto/private-room";
import type { PrivateRoomEvent } from "./private-room-events";
import {
appendMomentsResponse,
applyMomentsResponse,
replaceMoment,
applyAlbumsResponse,
patchAlbumInList,
removeAlbum,
toPaywallRequest,
toPrivateRoomErrorMessage,
toUnlockErrorMessage,
} from "./private-room-machine.helpers";
import {
loadMorePrivateRoomMomentsActor,
loadPrivateRoomMomentsActor,
unlockPrivateRoomMomentActor,
loadPrivateAlbumsActor,
unlockPrivateAlbumActor,
} from "./private-room-machine.actors";
import { initialState, type PrivateRoomState } from "./private-room-state";
@@ -22,11 +21,11 @@ export type { PrivateRoomEvent } from "./private-room-events";
export type { PrivateRoomState } from "./private-room-state";
export { initialState } from "./private-room-state";
function getPendingMoment(context: PrivateRoomState): PrivateRoomMoment | null {
if (!context.pendingConfirmMomentId) return null;
function getPendingAlbum(context: PrivateRoomState): PrivateAlbum | null {
if (!context.pendingConfirmAlbumId) return null;
return (
context.items.find(
(item) => item.momentId === context.pendingConfirmMomentId,
(album) => album.albumId === context.pendingConfirmAlbumId,
) ?? null
);
}
@@ -37,9 +36,8 @@ export const privateRoomMachine = setup({
events: {} as PrivateRoomEvent,
},
actors: {
loadMoments: loadPrivateRoomMomentsActor,
loadMoreMoments: loadMorePrivateRoomMomentsActor,
unlockMoment: unlockPrivateRoomMomentActor,
loadAlbums: loadPrivateAlbumsActor,
unlockAlbum: unlockPrivateAlbumActor,
},
}).createMachine({
id: "privateRoom",
@@ -58,10 +56,10 @@ export const privateRoomMachine = setup({
unlockPaywallRequest: null,
}),
invoke: {
src: "loadMoments",
src: "loadAlbums",
onDone: {
target: "ready",
actions: assign(({ event }) => applyMomentsResponse(event.output)),
actions: assign(({ event }) => applyAlbumsResponse(event.output)),
},
onError: {
target: "failed",
@@ -81,90 +79,55 @@ export const privateRoomMachine = setup({
ready: {
on: {
PrivateRoomInit: {
target: "loading",
},
PrivateRoomRefresh: {
target: "loading",
},
PrivateRoomLoadMore: [
{
guard: ({ context }) =>
context.hasMore && context.nextCursor !== null,
target: "loadingMore",
},
],
PrivateRoomInit: "loading",
PrivateRoomRefresh: "loading",
PrivateRoomUnlockRequested: {
actions: assign(({ event }) => ({
pendingConfirmMomentId: event.momentId,
pendingConfirmAlbumId: event.albumId,
unlockErrorMessage: null,
unlockPaywallRequest: null,
})),
},
PrivateRoomUnlockCancelled: {
actions: assign({
pendingConfirmMomentId: null,
}),
actions: assign({ pendingConfirmAlbumId: null }),
},
PrivateRoomUnlockConfirmed: [
{
guard: ({ context }) => getPendingMoment(context) !== null,
guard: ({ context }) => getPendingAlbum(context) !== null,
target: "unlocking",
},
],
PrivateRoomUnlockPaywallConsumed: {
actions: assign({
unlockPaywallRequest: null,
}),
},
},
},
loadingMore: {
invoke: {
src: "loadMoreMoments",
input: ({ context }) => ({
cursor: context.nextCursor,
}),
onDone: {
target: "ready",
actions: assign(({ context, event }) =>
appendMomentsResponse(context, event.output),
),
},
onError: {
target: "ready",
actions: assign(({ event }) => ({
errorMessage: toPrivateRoomErrorMessage(event.error),
})),
actions: assign({ unlockPaywallRequest: null }),
},
},
},
unlocking: {
entry: assign(({ context }) => ({
unlockingMomentId: context.pendingConfirmMomentId,
unlockingAlbumId: context.pendingConfirmAlbumId,
unlockErrorMessage: null,
unlockPaywallRequest: null,
})),
invoke: {
src: "unlockMoment",
src: "unlockAlbum",
input: ({ context }) => {
const pendingMoment = getPendingMoment(context);
const pendingAlbum = getPendingAlbum(context);
return {
momentId: pendingMoment?.momentId ?? "",
expectedCost: pendingMoment?.unlockCost ?? 0,
albumId: pendingAlbum?.albumId ?? "",
expectedCost: pendingAlbum?.unlockCost ?? 0,
};
},
onDone: [
{
guard: ({ event }) => event.output.unlocked,
guard: ({ event }) =>
event.output.unlocked && !event.output.locked,
target: "ready",
actions: assign(({ context, event }) => ({
items: replaceMoment(context.items, event.output),
creditBalance: event.output.creditBalance || context.creditBalance,
pendingConfirmMomentId: null,
unlockingMomentId: null,
items: patchAlbumInList(context.items, event.output),
creditBalance: event.output.creditBalance,
pendingConfirmAlbumId: null,
unlockingAlbumId: null,
unlockErrorMessage: null,
unlockSuccessNonce: context.unlockSuccessNonce + 1,
})),
@@ -174,10 +137,10 @@ export const privateRoomMachine = setup({
event.output.reason === "insufficient_credits",
target: "ready",
actions: assign(({ context, event }) => ({
items: replaceMoment(context.items, event.output),
creditBalance: event.output.creditBalance || context.creditBalance,
pendingConfirmMomentId: null,
unlockingMomentId: null,
items: patchAlbumInList(context.items, event.output),
creditBalance: event.output.creditBalance,
pendingConfirmAlbumId: null,
unlockingAlbumId: null,
unlockErrorMessage: null,
unlockPaywallRequest: toPaywallRequest(event.output),
})),
@@ -186,17 +149,29 @@ export const privateRoomMachine = setup({
guard: ({ event }) => event.output.reason === "cost_changed",
target: "loading",
actions: assign(({ event }) => ({
pendingConfirmMomentId: null,
unlockingMomentId: null,
pendingConfirmAlbumId: null,
unlockingAlbumId: null,
unlockErrorMessage: toUnlockErrorMessage(event.output),
})),
},
{
guard: ({ event }) => event.output.reason === "not_found",
target: "ready",
actions: assign(({ context, event }) => ({
items: removeAlbum(context.items, event.output.albumId),
creditBalance: event.output.creditBalance,
pendingConfirmAlbumId: null,
unlockingAlbumId: null,
unlockErrorMessage: toUnlockErrorMessage(event.output),
})),
},
{
target: "ready",
actions: assign(({ context, event }) => ({
items: replaceMoment(context.items, event.output),
pendingConfirmMomentId: null,
unlockingMomentId: null,
items: patchAlbumInList(context.items, event.output),
creditBalance: event.output.creditBalance,
pendingConfirmAlbumId: null,
unlockingAlbumId: null,
unlockErrorMessage: toUnlockErrorMessage(event.output),
})),
},
@@ -204,8 +179,8 @@ export const privateRoomMachine = setup({
onError: {
target: "ready",
actions: assign(({ event }) => ({
pendingConfirmMomentId: null,
unlockingMomentId: null,
pendingConfirmAlbumId: null,
unlockingAlbumId: null,
unlockErrorMessage: toPrivateRoomErrorMessage(event.error),
})),
},
+7 -16
View File
@@ -1,10 +1,7 @@
import type {
PrivateRoomMoment,
PrivateRoomProfile,
} from "@/data/dto/private-room";
import type { PrivateAlbum } from "@/data/dto/private-room";
export interface PrivateRoomUnlockPaywallRequest {
momentId: string;
albumId: string;
reason: string;
requiredCredits: number;
currentCredits: number;
@@ -12,29 +9,23 @@ export interface PrivateRoomUnlockPaywallRequest {
}
export interface PrivateRoomState {
profile: PrivateRoomProfile | null;
items: PrivateRoomMoment[];
nextCursor: string | null;
hasMore: boolean;
items: PrivateAlbum[];
creditBalance: number;
errorMessage: string | null;
unlockingMomentId: string | null;
unlockingAlbumId: string | null;
unlockErrorMessage: string | null;
pendingConfirmMomentId: string | null;
pendingConfirmAlbumId: string | null;
unlockPaywallRequest: PrivateRoomUnlockPaywallRequest | null;
unlockSuccessNonce: number;
}
export const initialState: PrivateRoomState = {
profile: null,
items: [],
nextCursor: null,
hasMore: false,
creditBalance: 0,
errorMessage: null,
unlockingMomentId: null,
unlockingAlbumId: null,
unlockErrorMessage: null,
pendingConfirmMomentId: null,
pendingConfirmAlbumId: null,
unlockPaywallRequest: null,
unlockSuccessNonce: 0,
};