From c46b9b4cdd7138081ab430d8cb30b535432004f0 Mon Sep 17 00:00:00 2001 From: chenhang Date: Wed, 8 Jul 2026 16:29:08 +0800 Subject: [PATCH] feat(private-room): connect moments feed --- docs/backend/FRONTEND_PRIVATE_ROOM_API.md | 973 ++++++++++++++++++ docs/backend/frontend.md | 7 + src/app/chat/hooks/use-chat-guest-login.ts | 67 +- src/app/private-room/page.tsx | 5 + .../private-room-screen.module.css} | 231 ++++- src/app/private-room/private-room-screen.tsx | 440 ++++++++ src/app/profile/page.tsx | 4 +- src/app/profile/profile-screen.tsx | 164 --- .../__tests__/private_room.test.ts | 133 +++ src/data/dto/private-room/index.ts | 3 + .../dto/private-room/private_room_moment.ts | 51 + src/data/dto/private-room/request/index.ts | 1 + .../unlock_private_room_moment_request.ts | 31 + src/data/dto/private-room/response/index.ts | 2 + .../response/private_room_moments_response.ts | 54 + .../response/private_room_unlock_response.ts | 41 + src/data/repositories/index.ts | 2 + src/data/repositories/interfaces/index.ts | 1 + .../interfaces/iprivate_room_repository.ts | 22 + .../repositories/private_room_repository.ts | 45 + src/data/schemas/private-room/index.ts | 4 + src/data/schemas/private-room/private_room.ts | 102 ++ .../private_room_moments_response.ts | 41 + .../private_room_unlock_response.ts | 36 + .../unlock_private_room_moment_request.ts | 14 + src/data/services/api/api_path.ts | 10 + src/data/services/api/index.ts | 1 + src/data/services/api/private_room_api.ts | 49 + src/hooks/use-guest-login-bootstrap.ts | 65 ++ src/providers/root-providers.tsx | 13 +- src/router/__tests__/route-meta.test.ts | 6 +- src/router/route-meta.ts | 2 +- src/router/routes.ts | 4 +- .../__tests__/private-room-machine.test.ts | 260 +++++ src/stores/private-room/index.ts | 4 + .../private-room/private-room-context.tsx | 96 ++ .../private-room/private-room-events.ts | 8 + .../private-room-machine.actors.ts | 51 + .../private-room-machine.helpers.ts | 88 ++ .../private-room/private-room-machine.ts | 217 ++++ src/stores/private-room/private-room-state.ts | 40 + 41 files changed, 3107 insertions(+), 281 deletions(-) create mode 100644 docs/backend/FRONTEND_PRIVATE_ROOM_API.md create mode 100644 docs/backend/frontend.md create mode 100644 src/app/private-room/page.tsx rename src/app/{profile/profile-screen.module.css => private-room/private-room-screen.module.css} (75%) create mode 100644 src/app/private-room/private-room-screen.tsx delete mode 100644 src/app/profile/profile-screen.tsx create mode 100644 src/data/dto/private-room/__tests__/private_room.test.ts create mode 100644 src/data/dto/private-room/index.ts create mode 100644 src/data/dto/private-room/private_room_moment.ts create mode 100644 src/data/dto/private-room/request/index.ts create mode 100644 src/data/dto/private-room/request/unlock_private_room_moment_request.ts create mode 100644 src/data/dto/private-room/response/index.ts create mode 100644 src/data/dto/private-room/response/private_room_moments_response.ts create mode 100644 src/data/dto/private-room/response/private_room_unlock_response.ts create mode 100644 src/data/repositories/interfaces/iprivate_room_repository.ts create mode 100644 src/data/repositories/private_room_repository.ts create mode 100644 src/data/schemas/private-room/index.ts create mode 100644 src/data/schemas/private-room/private_room.ts create mode 100644 src/data/schemas/private-room/private_room_moments_response.ts create mode 100644 src/data/schemas/private-room/private_room_unlock_response.ts create mode 100644 src/data/schemas/private-room/unlock_private_room_moment_request.ts create mode 100644 src/data/services/api/private_room_api.ts create mode 100644 src/hooks/use-guest-login-bootstrap.ts create mode 100644 src/stores/private-room/__tests__/private-room-machine.test.ts create mode 100644 src/stores/private-room/index.ts create mode 100644 src/stores/private-room/private-room-context.tsx create mode 100644 src/stores/private-room/private-room-events.ts create mode 100644 src/stores/private-room/private-room-machine.actors.ts create mode 100644 src/stores/private-room/private-room-machine.helpers.ts create mode 100644 src/stores/private-room/private-room-machine.ts create mode 100644 src/stores/private-room/private-room-state.ts diff --git a/docs/backend/FRONTEND_PRIVATE_ROOM_API.md b/docs/backend/FRONTEND_PRIVATE_ROOM_API.md new file mode 100644 index 00000000..631871fe --- /dev/null +++ b/docs/backend/FRONTEND_PRIVATE_ROOM_API.md @@ -0,0 +1,973 @@ +# Cozsweet Private Room / Moments Frontend API + +Last verified: 2026-07-08 + +This document is for the frontend integration of the Elio private room / Moments-like feed. The feature is backend-only in phase 1: posts come from existing schedule images, all posts are locked by default, and users spend credits to unlock the real image URLs. + +## 1. Scope + +The frontend needs to support three backend endpoints: + +| Purpose | Method | Path | +| --- | --- | --- | +| Get private-room config | `GET` | `/api/private-room/config` | +| Get locked/unlocked Moments feed | `GET` | `/api/private-room/moments` | +| Unlock one Moment post | `POST` | `/api/private-room/moments/{momentId}/unlock` | + +Recommended production base for cozsweet frontend: + +```text +https://api.cozsweet.com +``` + +Project production API base is also: + +```text +https://api.banlv-ai.com +``` + +Use the same API base already used by the cozsweet frontend login/chat client. Do not hardcode both in the same frontend flow. + +## 2. Authentication + +All three endpoints require the normal user Bearer token. + +```http +Authorization: Bearer +``` + +If the token is missing or invalid, production returns: + +```json +{ + "code": 401, + "message": "Not authenticated", + "success": false, + "data": null +} +``` + +Frontend action: + +- If the user is a guest, use the existing guest token flow first. +- If the user is logged in, use the existing login token. +- If this API returns 401, refresh/re-login using the existing auth behavior. + +## 3. Field Mapping vs Payment Plans + +Do not treat private-room unlock price as a payment amount. + +| Area | Price field | Currency field | Meaning | +| --- | --- | --- | --- | +| Payment plans | `amountCents` | `currency`, for example `PHP` or `USD` | Cash price in display cents. `14990` + `PHP` means `PHP 149.90`. | +| Payment plans | `originalAmountCents` | `currency` | Original crossed-out cash price. | +| Payment plans | `dailyPriceCents` | `currency` | VIP daily cash price, if applicable. | +| Private room | `unlockCost` | `currency: "credits"` | Total credits required to unlock this post. | +| Private room | `unlockCostPerImage` | `currency: "credits"` | Credits required per image. Currently `40`. | +| Private room | `requiredCredits` | `currency: "credits"` | Same unlock requirement, useful for lock/paywall UI. | + +Unlock state fields: + +| Field | Type | Meaning | Frontend usage | +| --- | --- | --- | --- | +| `locked` | boolean | `true` means the post is locked. | Primary field for locked UI. | +| `unlocked` | boolean | `true` means the post has been unlocked for this user. | Primary field for unlocked UI if preferred. | +| `lockDetail.locked` | boolean | Same lock decision in chat-compatible structure. | Useful if sharing lock/paywall components with chat. | +| `images[].locked` | boolean | Whether this image placeholder is locked. | Use for image tile state. | +| `images[].url` | string or null | Real image URL only after unlock. | Render `` only when not null. | + +Recommended frontend condition: + +```ts +const isLocked = item.locked || item.lockDetail?.locked; +``` + +## 4. Data Source and Image Access + +Phase 1 data source: + +| Source | Meaning | +| --- | --- | +| Table | `elio_schedules` | +| Single image field | `image_url` | +| Multi-image fields | `image_urls`, `image_paths`, metadata inside `content` | +| Returned post id | `momentId`, for example `schedule:91` | + +Locked posts deliberately do not expose real image URLs: + +```json +{ + "images": [ + { + "url": null, + "type": "image", + "locked": true, + "index": 0 + } + ] +} +``` + +After unlock, the same image item returns a real public Supabase Storage URL: + +```json +{ + "images": [ + { + "url": "https://lehwkihwnlqkavhcspel.supabase.co/storage/v1/object/public/elio-schedules/schedules/91/0502fee0-4755-460a-adac-8e4d71a72343.jpg", + "type": "image", + "locked": false, + "index": 0 + } + ] +} +``` + +Frontend can render it directly: + +```tsx +{image.url ? : } +``` + +Production image accessibility was verified on 2026-07-08: + +```text +HTTP 200 OK +Content-Type: image/jpeg +Access-Control-Allow-Origin: * +``` + +So the frontend does not need an extra image proxy for the current Supabase public URLs. + +## 5. Common Response Wrapper + +All successful API calls use the standard wrapper: + +```ts +interface ApiResponse { + code: number; + message: string; + success: boolean; + data: T | null; +} +``` + +Important: unlock business failures can still return HTTP 200 with `success: true`, but `data.unlocked` is `false`. For unlock UI, check `data.unlocked`, `data.locked`, and `data.reason`, not only HTTP status. + +## 6. GET /api/private-room/config + +### Purpose + +Get the current user's private-room config, default unlock price, current credit balance, and Elio profile info. + +### Request URL + +```http +GET https://api.cozsweet.com/api/private-room/config +``` + +### Request Format + +No query params and no body. + +### Request Example + +```bash +curl -X GET "https://api.cozsweet.com/api/private-room/config" \ + -H "Authorization: Bearer " +``` + +### Success Response + +```json +{ + "code": 200, + "message": "success", + "success": true, + "data": { + "currency": "credits", + "unlockCostDefault": 40, + "unlockCostPerImage": 40, + "source": "elio_schedules", + "creditBalance": 100, + "profile": { + "characterId": "elio", + "displayName": "Elio Silvestri", + "authorName": "Elio Silvestri", + "avatarUrl": null, + "coverUrl": null, + "title": "Elio Private room", + "subtitle": "Join me, unlock my private room" + } + } +} +``` + +### Key Fields + +| Field | Type | Meaning | +| --- | --- | --- | +| `currency` | string | Always `"credits"` for this feature. | +| `unlockCostDefault` | number | Default single-image unlock price. Currently `40`. | +| `unlockCostPerImage` | number | Price per image. Currently `40`. | +| `creditBalance` | number | User's current credits. | +| `profile` | object | Elio private-room profile. | + +### Frontend Usage + +Call it when entering the private room page if the frontend needs profile/header data before loading the feed. Otherwise, the feed endpoint also returns `profile`, `creditBalance`, and pricing fields. + +## 7. GET /api/private-room/moments + +### Purpose + +Get the private-room feed. Locked posts return placeholders and unlock prices; already-unlocked posts return real image URLs. + +### Request URL + +```http +GET https://api.cozsweet.com/api/private-room/moments?character=elio&limit=20 +``` + +### Query Parameters + +| Field | Type | Required | Example | Meaning | Validation | +| --- | --- | --- | --- | --- | --- | +| `character` | string | No | `elio` | Character/private-room id. Phase 1 supports `elio`. | Defaults to `elio`. | +| `limit` | number | No | `20` | Page size. | Min `1`, max `50`, defaults to `20`. | +| `cursor` | string | No | `1783488000` | Pagination cursor from previous `data.nextCursor`. | Omit for first page. | + +### Request Example + +```bash +curl -X GET "https://api.cozsweet.com/api/private-room/moments?character=elio&limit=20" \ + -H "Authorization: Bearer " +``` + +### Locked Post Response Example + +```json +{ + "code": 200, + "message": "success", + "success": true, + "data": { + "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": [ + { + "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天前", + "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, + "detail": { + "type": "private_room_moment", + "requiredCredits": 40, + "currentCredits": 100, + "shortfallCredits": 0, + "mediaCount": 1, + "unlockCostPerImage": 40 + } + } + } + ], + "nextCursor": null, + "hasMore": false, + "creditBalance": 100, + "unlockCostDefault": 40, + "unlockCostPerImage": 40, + "currency": "credits", + "source": "elio_schedules" + } +} +``` + +### Already-Unlocked Post Shape + +When the user has already unlocked the post, the list endpoint returns real image URLs directly: + +```json +{ + "momentId": "schedule:91", + "locked": false, + "unlocked": true, + "content": "A quiet morning in Paris.", + "text": "A quiet morning in Paris.", + "mediaCount": 1, + "images": [ + { + "url": "https://lehwkihwnlqkavhcspel.supabase.co/storage/v1/object/public/elio-schedules/schedules/91/0502fee0-4755-460a-adac-8e4d71a72343.jpg", + "type": "image", + "locked": false, + "index": 0 + } + ], + "lockDetail": { + "locked": false, + "showContent": true, + "showUpgrade": false + } +} +``` + +### Key Item Fields + +| Field | Type | Meaning | +| --- | --- | --- | +| `momentId` | string | Post id. Use this for unlock. Example: `schedule:91`. | +| `source` | string | Current source table, `elio_schedules`. | +| `sourceId` | string | Schedule row id. | +| `title` | string | Optional post title. | +| `content` | string or null | Real text content. Null when locked. | +| `text` | string or null | Same as content, for frontend naming compatibility. | +| `textPreview` | string | Preview text shown while locked. | +| `mediaCount` | number | Number of images in this post. | +| `images` | array | Image placeholders when locked; real URLs when unlocked. | +| `locked` | boolean | Whether this post is locked. | +| `unlocked` | boolean | Whether this post is unlocked. | +| `unlockCost` | number | Total credits required for this post. | +| `unlockCostPerImage` | number | Credits per image. | +| `requiredCredits` | number | Required credits for lock UI. | +| `currency` | string | Always `"credits"`. | +| `lockDetail` | object | Chat-compatible lock detail. | + +### Pagination + +If `data.hasMore` is true, call the same endpoint with: + +```text +cursor= +``` + +## 8. POST /api/private-room/moments/{momentId}/unlock + +### Purpose + +Unlock one private-room post, deduct credits, persist the unlock state, and return real image URLs. + +### Request URL + +`momentId` must be URL encoded because it contains `:`. + +```http +POST https://api.cozsweet.com/api/private-room/moments/schedule%3A91/unlock +``` + +Frontend example: + +```ts +const url = `/api/private-room/moments/${encodeURIComponent(momentId)}/unlock`; +``` + +### Request Format + +Content-Type: + +```http +Content-Type: application/json +``` + +Body is optional, but recommended: + +```json +{ + "expectedCost": 40 +} +``` + +### Body Parameters + +| Field | Type | Required | Example | Meaning | +| --- | --- | --- | --- | --- | +| `expectedCost` | number | No | `40` | The price shown to the user. If backend price changed, unlock returns `reason: "cost_changed"` instead of charging. | + +### Request Example + +```bash +curl -X POST "https://api.cozsweet.com/api/private-room/moments/schedule%3A91/unlock" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{"expectedCost":40}' +``` + +### Unlock Success Response + +```json +{ + "code": 200, + "message": "success", + "success": true, + "data": { + "momentId": "schedule:91", + "source": "elio_schedules", + "sourceId": "91", + "characterId": "elio", + "content": "A quiet morning in Paris.", + "text": "A quiet morning in Paris.", + "mediaCount": 1, + "images": [ + { + "url": "https://lehwkihwnlqkavhcspel.supabase.co/storage/v1/object/public/elio-schedules/schedules/91/0502fee0-4755-460a-adac-8e4d71a72343.jpg", + "type": "image", + "locked": false, + "index": 0 + } + ], + "locked": false, + "unlocked": true, + "unlockCost": 40, + "unlockCostPerImage": 40, + "requiredCredits": 40, + "currency": "credits", + "reason": "ok", + "creditsCharged": 40, + "creditBalance": 60, + "previousCreditBalance": 100, + "persisted": true, + "lockDetail": { + "locked": false, + "showContent": true, + "showUpgrade": false, + "reason": null, + "hint": null, + "actionLabel": null, + "type": "private_room_moment", + "requiredCredits": 40, + "currentCredits": 60, + "shortfallCredits": 0, + "mediaCount": 1, + "unlockCostPerImage": 40 + } + } +} +``` + +### Already Unlocked Response + +If the same user unlocks the same post again, backend does not charge again: + +```json +{ + "code": 200, + "message": "success", + "success": true, + "data": { + "momentId": "schedule:91", + "locked": false, + "unlocked": true, + "reason": "already_unlocked", + "creditsCharged": 0, + "creditBalance": 60, + "images": [ + { + "url": "https://lehwkihwnlqkavhcspel.supabase.co/storage/v1/object/public/elio-schedules/schedules/91/0502fee0-4755-460a-adac-8e4d71a72343.jpg", + "type": "image", + "locked": false, + "index": 0 + } + ] + } +} +``` + +### Insufficient Credits Response + +This is a business failure, but it still returns HTTP 200 and `success: true`. + +```json +{ + "code": 200, + "message": "success", + "success": true, + "data": { + "momentId": "schedule:91", + "locked": true, + "unlocked": false, + "reason": "insufficient_credits", + "requiredCredits": 40, + "currentCredits": 10, + "shortfallCredits": 30, + "creditBalance": 10, + "images": [ + { + "url": null, + "type": "image", + "locked": true, + "index": 0 + } + ], + "lockDetail": { + "locked": true, + "showContent": false, + "showUpgrade": true, + "reason": "insufficient_credits", + "hint": "Not enough credits to unlock this private room post.", + "actionLabel": "Unlock", + "requiredCredits": 40, + "currentCredits": 10, + "shortfallCredits": 30, + "mediaCount": 1, + "unlockCostPerImage": 40 + } + } +} +``` + +Frontend action: + +- Keep the post locked. +- Show recharge / insufficient credits UI. +- Do not try to render `images[].url` because it remains null. + +### Cost Changed Response + +If `expectedCost` does not match the backend price: + +```json +{ + "code": 200, + "message": "success", + "success": true, + "data": { + "momentId": "schedule:91", + "locked": true, + "unlocked": false, + "reason": "cost_changed", + "requiredCredits": 40, + "lockDetail": { + "locked": true, + "reason": "cost_changed", + "hint": "Unlock price changed. Please refresh and try again." + } + } +} +``` + +Frontend action: + +- Refresh the feed item. +- Ask the user to confirm again with the latest `unlockCost`. + +### Other Business Reasons + +| `data.reason` | Meaning | Frontend action | +| --- | --- | --- | +| `ok` | Unlock succeeded and credits were charged. | Show real images and refresh credit balance. | +| `already_unlocked` | User had unlocked before. No charge. | Show real images. | +| `insufficient_credits` | Not enough credits. No charge. | Keep locked and open recharge UI. | +| `cost_changed` | Frontend expected cost differs from backend. No charge. | Refresh and ask user to confirm again. | +| `not_found` | Post no longer exists. | Remove item or show unavailable state. | +| `no_media` | Post has no images to unlock. | Hide unlock button. | +| `deduct_failed` | Credit deduction failed. | Keep locked and allow retry. | +| `ok_persist_failed` | Credits charged and images returned, but unlock record fallback may have been used. | Show images; optionally refresh list. | + +## 9. TypeScript Types + +```ts +export interface PrivateRoomProfile { + characterId: string; + displayName: string; + authorName: string; + avatarUrl: string | null; + coverUrl: string | null; + title: string; + subtitle: string; +} + +export interface PrivateRoomImage { + url: string | null; + type: "image"; + locked: boolean; + index: number; +} + +export interface PrivateRoomLockDetail { + locked: boolean; + showContent: boolean; + showUpgrade: boolean; + reason?: string | null; + hint?: string | null; + actionLabel?: string | null; + type?: "private_room_moment"; + requiredCredits?: number; + currentCredits?: number | null; + shortfallCredits?: number; + mediaCount?: number; + unlockCostPerImage?: number; + detail?: { + type: "private_room_moment"; + requiredCredits: number; + currentCredits: number | null; + shortfallCredits: number; + mediaCount: number; + unlockCostPerImage: number; + }; +} + +export interface PrivateRoomMoment { + momentId: string; + source: "elio_schedules"; + sourceId: string; + characterId: string; + author: { + id: string; + name: string; + avatarUrl: string | null; + }; + createdAt: string | null; + publishedAt: string | null; + timeText: string; + title: string; + content: string | null; + text: string | null; + textPreview: string; + mediaCount: number; + images: PrivateRoomImage[]; + locked: boolean; + unlocked: boolean; + unlockCost: number; + unlockCostPerImage: number; + requiredCredits: number; + currency: "credits"; + lockDetail: PrivateRoomLockDetail; +} + +export interface PrivateRoomMomentsData { + profile: PrivateRoomProfile; + items: PrivateRoomMoment[]; + nextCursor: string | null; + hasMore: boolean; + creditBalance: number; + unlockCostDefault: number; + unlockCostPerImage: number; + currency: "credits"; + source: "elio_schedules"; +} + +export interface PrivateRoomUnlockData extends PrivateRoomMoment { + reason: + | "ok" + | "already_unlocked" + | "insufficient_credits" + | "cost_changed" + | "not_found" + | "no_media" + | "deduct_failed" + | "ok_persist_failed"; + creditsCharged?: number; + creditBalance?: number; + previousCreditBalance?: number; + currentCredits?: number; + shortfallCredits?: number; + persisted?: boolean; +} +``` + +## 10. Recommended Frontend Flow + +1. User enters private room page. +2. Call `GET /api/private-room/moments?character=elio&limit=20`. +3. Render each item: + - If `item.locked === true`, show locked image tiles and unlock price. + - If `item.locked === false`, render `images[].url`. +4. User taps unlock. +5. Show confirm UI with `item.unlockCost` and `item.currency`. +6. Call: + +```ts +await api.post( + `/api/private-room/moments/${encodeURIComponent(item.momentId)}/unlock`, + { expectedCost: item.unlockCost }, +); +``` + +7. On response: + - If `data.unlocked === true`, replace the current card with response `data`. + - If `data.reason === "insufficient_credits"`, keep locked and open recharge UI. + - If `data.reason === "cost_changed"`, refresh list and ask for confirmation again. + - For other failure reasons, show a retry/unavailable message. +8. Update visible credit balance from `data.creditBalance` if present. + +## 11. UI Rules + +- Locked state must never render `images[].url` if it is null. +- Do not show broken images for locked posts; use lock tiles based on `mediaCount`. +- Use `unlockCost` for the button price, not `amountCents`. +- Use `currency === "credits"` to display "credits", not PHP/USD. +- For multi-image posts, display total price: + +```ts +`${item.unlockCost} credits` +``` + +Optionally show per-image detail: + +```ts +`${item.unlockCostPerImage} credits/photo` +``` + +- After successful unlock, do not call any separate image API. Use `data.images`. +- To avoid double tapping, disable the unlock button while the POST request is pending. + +## 12. Failure Handling + +| Case | How to detect | Frontend handling | +| --- | --- | --- | +| Not logged in | HTTP 401 or wrapper `code: 401` | Refresh token, guest token, or login. | +| Validation error | HTTP 422 | Check path/body format, especially encoded `momentId`. | +| Insufficient credits | HTTP 200 with `data.reason === "insufficient_credits"` | Open recharge UI. | +| Price changed | HTTP 200 with `data.reason === "cost_changed"` | Refresh item and reconfirm. | +| Already unlocked | HTTP 200 with `data.reason === "already_unlocked"` | Show returned images, no charge. | +| Deduct failed | HTTP 200 with `data.reason === "deduct_failed"` | Keep locked and allow retry. | +| Network/API error | request failed or 5xx | Keep current state and show retry. | + +## 13. Production-Safe Test Method + +These tests do not require creating posts. + +### 13.1 Auth Required + +```bash +curl -i "https://api.cozsweet.com/api/private-room/moments?character=elio&limit=1" +``` + +Expected: + +```text +HTTP/1.1 401 Unauthorized +``` + +### 13.2 Get Config + +```bash +curl -X GET "https://api.cozsweet.com/api/private-room/config" \ + -H "Authorization: Bearer " +``` + +Expected: + +- `data.currency === "credits"` +- `data.unlockCostPerImage === 40` +- `data.creditBalance` is a number + +### 13.3 Get Locked Feed + +```bash +curl -X GET "https://api.cozsweet.com/api/private-room/moments?character=elio&limit=1" \ + -H "Authorization: Bearer " +``` + +Expected for a not-yet-unlocked post: + +- `data.items[0].locked === true` +- `data.items[0].unlocked === false` +- `data.items[0].unlockCost === data.items[0].mediaCount * 40` +- `data.items[0].images[0].url === null` + +### 13.4 Unlock With Insufficient Credits + +Use a test/guest account with fewer credits than `unlockCost`. + +```bash +curl -X POST "https://api.cozsweet.com/api/private-room/moments/schedule%3A91/unlock" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -d '{"expectedCost":40}' +``` + +Expected: + +- HTTP 200 +- `data.unlocked === false` +- `data.locked === true` +- `data.reason === "insufficient_credits"` +- `data.images[0].url === null` + +### 13.5 Unlock Success + +Use only a test account that intentionally has enough credits. This deducts real credits. + +Expected: + +- `data.unlocked === true` +- `data.locked === false` +- `data.creditsCharged === data.unlockCost` +- `data.images[0].url` is a non-empty HTTPS URL +- Repeating the same unlock should return `reason: "already_unlocked"` and `creditsCharged: 0` + +## 14. Confirmed Production Evidence + +Verified on 2026-07-08: + +```text +GET https://api.cozsweet.com/health +HTTP 200 +``` + +Private-room endpoints require auth: + +```text +GET /api/private-room/moments without Bearer token +HTTP 401 Not authenticated +``` + +Backend generated locked item shape: + +```json +{ + "momentId": "schedule:91", + "mediaCount": 1, + "unlockCost": 40, + "unlockCostPerImage": 40, + "currency": "credits", + "locked": true, + "unlocked": false, + "requiredCredits": 40, + "images": [ + { + "url": null, + "type": "image", + "locked": true, + "index": 0 + } + ], + "lockDetail": { + "locked": true, + "requiredCredits": 40 + } +} +``` + +Backend generated unlocked image shape: + +```json +{ + "momentId": "schedule:91", + "locked": false, + "unlocked": true, + "unlockCost": 40, + "currency": "credits", + "images": [ + { + "url": "https://lehwkihwnlqkavhcspel.supabase.co/storage/v1/object/public/elio-schedules/schedules/91/0502fee0-4755-460a-adac-8e4d71a72343.jpg", + "type": "image", + "locked": false, + "index": 0 + } + ], + "lockDetail": { + "locked": false + } +} +``` + +The sample real image URL returned: + +```text +HTTP 200 OK +Content-Type: image/jpeg +Access-Control-Allow-Origin: * +``` + +## 15. Database / Persistence Notes + +Migration file: + +```text +database/private-room-migration.sql +``` + +Full local path: + +```text +C:\windows_banlv\ai-boyfriend\ai-boyfriend-unified\database\private-room-migration.sql +``` + +Purpose: + +- Create `private_room_unlocks` +- Persist `user_id + moment_key` +- Prevent charging again for already-unlocked posts + +Current production backend also has a fallback to `users.preferences.private_room_unlocked_moment_keys` if the unlock table is missing, so the feature can work before/without the migration. Running the migration is still recommended for cleaner persistence and future analytics. + +## 16. Frontend Integration Checklist + +- Use Bearer token for all three endpoints. +- Encode `momentId` in unlock path with `encodeURIComponent`. +- Render locked placeholders when `locked === true`. +- Render real images only when `images[].url` is not null. +- Use `unlockCost` and `currency: "credits"` for unlock price. +- Send `{ expectedCost: item.unlockCost }` when unlocking. +- Treat `data.unlocked === false` as an unlock business failure even if HTTP is 200. +- Update displayed credit balance from `data.creditBalance`. +- On insufficient credits, open recharge flow. +- On success, replace the card with returned `data` or reload the feed. + +## 17. Rollback / Compatibility Notes + +This document describes the currently deployed backend behavior. Frontend can integrate it without changing existing payment plan fields. + +Compatibility: + +- Existing payment `/api/payment/plans` is unchanged. +- Existing chat lock UI can reuse `lockDetail.locked`, `requiredCredits`, and `shortfallCredits`. +- Locked private-room items do not leak image URLs. + +Rollback if frontend needs to disable the feature: + +- Hide the private-room entry point. +- Do not call `/api/private-room/*`. +- No existing chat/payment flow needs to be rolled back. + +## 18. Needs Confirmation + +- `avatarUrl` and `coverUrl` currently return `null`; frontend should use local/default Elio assets until final profile images are provided. +- Phase 1 content source is `elio_schedules`; if product wants separate Moments content, backend can keep the API contract and change only the source implementation later. diff --git a/docs/backend/frontend.md b/docs/backend/frontend.md new file mode 100644 index 00000000..4c1ef931 --- /dev/null +++ b/docs/backend/frontend.md @@ -0,0 +1,7 @@ +前端核心逻辑是: +列表接口:GET /api/private-room/moments?character=elio&limit=20 +解锁接口:POST /api/private-room/moments/${encodeURIComponent(momentId)}/unlock +价格看 unlockCost,单位是 currency: "credits" +是否解锁看 locked/unlocked +锁定时 images[].url = null +解锁成功后直接用返回的 images[].url \ No newline at end of file diff --git a/src/app/chat/hooks/use-chat-guest-login.ts b/src/app/chat/hooks/use-chat-guest-login.ts index 15ae172b..3712d225 100644 --- a/src/app/chat/hooks/use-chat-guest-login.ts +++ b/src/app/chat/hooks/use-chat-guest-login.ts @@ -1,63 +1,14 @@ "use client"; -import { type Dispatch, useEffect, useRef } from "react"; +import { + type UseGuestLoginBootstrapInput, + shouldSubmitGuestLogin, + useGuestLoginBootstrap, +} from "@/hooks/use-guest-login-bootstrap"; -import type { LoginStatus } from "@/data/dto/auth"; -import type { AuthEvent } from "@/stores/auth/auth-events"; +export type UseChatGuestLoginInput = UseGuestLoginBootstrapInput; +export { shouldSubmitGuestLogin }; -export interface GuestLoginState { - hasInitialized: boolean; - isLoading: boolean; - loginStatus: LoginStatus; -} - -export interface ShouldSubmitGuestLoginInput extends GuestLoginState { - alreadyRequested: boolean; -} - -export interface UseChatGuestLoginInput extends GuestLoginState { - dispatch: Dispatch; -} - -export function shouldSubmitGuestLogin({ - alreadyRequested, - hasInitialized, - isLoading, - loginStatus, -}: ShouldSubmitGuestLoginInput): boolean { - if (!hasInitialized || isLoading) return false; - if (loginStatus !== "notLoggedIn") return false; - return !alreadyRequested; -} - -export function useChatGuestLogin({ - dispatch, - hasInitialized, - isLoading, - loginStatus, -}: UseChatGuestLoginInput): void { - const guestLoginRequestedRef = useRef(false); - - useEffect(() => { - if (!hasInitialized || isLoading) return; - - if (loginStatus !== "notLoggedIn") { - guestLoginRequestedRef.current = false; - return; - } - - if ( - !shouldSubmitGuestLogin({ - alreadyRequested: guestLoginRequestedRef.current, - hasInitialized, - isLoading, - loginStatus, - }) - ) { - return; - } - - guestLoginRequestedRef.current = true; - dispatch({ type: "AuthGuestLoginSubmitted" }); - }, [dispatch, hasInitialized, isLoading, loginStatus]); +export function useChatGuestLogin(input: UseChatGuestLoginInput): void { + useGuestLoginBootstrap(input); } diff --git a/src/app/private-room/page.tsx b/src/app/private-room/page.tsx new file mode 100644 index 00000000..1afd2f4a --- /dev/null +++ b/src/app/private-room/page.tsx @@ -0,0 +1,5 @@ +import { PrivateRoomScreen } from "./private-room-screen"; + +export default function PrivateRoomPage() { + return ; +} diff --git a/src/app/profile/profile-screen.module.css b/src/app/private-room/private-room-screen.module.css similarity index 75% rename from src/app/profile/profile-screen.module.css rename to src/app/private-room/private-room-screen.module.css index 5aeb3a2a..e432343b 100644 --- a/src/app/profile/profile-screen.module.css +++ b/src/app/private-room/private-room-screen.module.css @@ -90,7 +90,6 @@ } .avatarFrame { - position: relative; display: grid; width: clamp(68px, 16.667vw, 90px); height: clamp(68px, 16.667vw, 90px); @@ -122,9 +121,13 @@ line-height: 0.95; } +.handle, +.bio { + color: #755f66; +} + .handle { margin: 7px 0 0; - color: #a56f7b; font-size: clamp(13px, 3.148vw, 17px); font-weight: 720; } @@ -132,39 +135,32 @@ .bio { max-width: 360px; margin: 0; - color: #755f66; font-size: clamp(14px, 3.333vw, 18px); font-weight: 620; line-height: 1.55; } -.primaryCta { +.primaryCta, +.loadMoreButton { display: inline-flex; min-height: 48px; align-items: center; justify-content: center; gap: 9px; - padding: 0 18px; border: 0; border-radius: 999px; - background: linear-gradient(135deg, #262026, #7f5861); - color: #ffffff; cursor: pointer; font: inherit; - font-size: clamp(13px, 3.148vw, 16px); font-weight: 850; - box-shadow: 0 14px 30px rgba(47, 35, 40, 0.18); transition: transform 0.18s ease, box-shadow 0.18s ease, filter 0.18s ease; } -.primaryCta:hover { - filter: brightness(1.04); - box-shadow: 0 18px 36px rgba(47, 35, 40, 0.23); - transform: translateY(-1px); -} - -.primaryCta:active { - transform: translateY(1px) scale(0.99); +.primaryCta { + padding: 0 18px; + background: linear-gradient(135deg, #262026, #7f5861); + color: #ffffff; + font-size: clamp(13px, 3.148vw, 16px); + box-shadow: 0 14px 30px rgba(47, 35, 40, 0.18); } .postsSection { @@ -217,13 +213,17 @@ gap: 14px; } -.postCard { - padding: clamp(14px, 3.704vw, 20px); +.postCard, +.statusCard { border: 1px solid rgba(44, 29, 34, 0.07); border-radius: clamp(22px, 5.926vw, 32px); background: rgba(255, 255, 255, 0.86); box-shadow: 0 16px 42px rgba(131, 72, 85, 0.1); backdrop-filter: blur(18px); +} + +.postCard { + padding: clamp(14px, 3.704vw, 20px); animation: riseIn 0.42s ease both; animation-delay: calc(var(--reveal-index, 0) * 90ms + 80ms); } @@ -250,8 +250,13 @@ box-shadow: 0 8px 18px rgba(131, 72, 85, 0.12); } -.authorName { +.authorName, +.authorSubline, +.postText { margin: 0; +} + +.authorName { color: #26191d; font-size: clamp(14px, 3.333vw, 17px); font-weight: 820; @@ -259,7 +264,7 @@ } .authorSubline { - margin: 3px 0 0; + margin-top: 3px; color: #a58b92; font-size: clamp(11px, 2.778vw, 13px); font-weight: 680; @@ -272,6 +277,14 @@ font-weight: 760; } +.postText { + margin-top: 14px; + color: #4c3a40; + font-size: clamp(14px, 3.333vw, 17px); + font-weight: 650; + line-height: 1.55; +} + .lockedPreview { display: grid; width: 100%; @@ -293,21 +306,9 @@ transition: border-color 0.18s ease, box-shadow 0.18s ease, transform 0.18s ease; } -.lockedPreview:hover { - border-color: rgba(255, 82, 139, 0.45); - box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.9), 0 18px 36px rgba(255, 116, 159, 0.18); - transform: translateY(-1px); -} - -.lockedPreview:active { - transform: translateY(1px) scale(0.995); -} - -.lockedPreview:focus-visible, -.primaryCta:focus-visible, -.navButton:focus-visible { - outline: 2px solid #ff5d95; - outline-offset: 3px; +.lockedPreview:disabled { + cursor: wait; + opacity: 0.72; } .previewIcon { @@ -350,6 +351,49 @@ font-weight: 760; } +.imageGrid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); + gap: 10px; + margin-top: 14px; +} + +.unlockedImage { + width: 100%; + height: auto; + aspect-ratio: 1; + border-radius: 22px; + object-fit: cover; + box-shadow: 0 14px 32px rgba(131, 72, 85, 0.14); +} + +.statusCard { + display: grid; + gap: 12px; + margin-bottom: 14px; + padding: 18px; + color: #755f66; + font-size: 15px; + font-weight: 700; + text-align: center; +} + +.statusCard p { + margin: 0; +} + +.statusCard button, +.loadMoreButton { + padding: 0 18px; + background: rgba(255, 93, 149, 0.12); + color: #a94c64; +} + +.loadMoreButton { + width: 100%; + margin-top: 16px; +} + .bottomNav { position: fixed; right: max(calc((100vw - var(--app-max-width, 540px)) / 2), 0px); @@ -386,16 +430,6 @@ font: inherit; font-size: clamp(12px, 2.963vw, 14px); font-weight: 820; - transition: background 0.18s ease, color 0.18s ease, transform 0.18s ease; -} - -.navButton:hover { - background: rgba(255, 116, 159, 0.08); - color: #2d2024; -} - -.navButton:active { - transform: scale(0.98); } .navButtonActive { @@ -405,6 +439,111 @@ box-shadow: 0 10px 24px rgba(255, 116, 159, 0.12); } +.dialogOverlay { + position: fixed; + inset: 0; + z-index: 40; + display: grid; + place-items: center; + padding: 24px; + background: rgba(34, 23, 28, 0.36); + backdrop-filter: blur(10px); +} + +.dialog { + width: min(100%, 360px); + padding: 22px; + border-radius: 26px; + background: #ffffff; + box-shadow: 0 24px 70px rgba(34, 23, 28, 0.22); +} + +.dialogTitle { + margin: 0; + color: #21171b; + font-size: 22px; + font-weight: 900; +} + +.dialogCopy, +.dialogError { + margin: 10px 0 0; + color: #755f66; + font-size: 15px; + font-weight: 650; + line-height: 1.45; +} + +.dialogError { + color: #c63f67; +} + +.dialogActions { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; + margin-top: 20px; +} + +.dialogPrimary, +.dialogSecondary { + min-height: 46px; + border: 0; + border-radius: 999px; + cursor: pointer; + font: inherit; + font-weight: 850; +} + +.dialogPrimary { + background: linear-gradient(135deg, #ff7aa9, #ffb36d); + color: #ffffff; +} + +.dialogSecondary { + background: rgba(44, 29, 34, 0.08); + color: #5f4b52; +} + +.toast { + position: fixed; + right: max(calc((100vw - var(--app-max-width, 540px)) / 2 + 18px), 18px); + bottom: calc(var(--app-safe-bottom, 0px) + 92px); + left: max(calc((100vw - var(--app-max-width, 540px)) / 2 + 18px), 18px); + z-index: 45; + padding: 14px 16px; + border-radius: 18px; + background: rgba(33, 23, 27, 0.88); + color: #ffffff; + font-size: 14px; + font-weight: 750; + text-align: center; +} + +.primaryCta:hover, +.lockedPreview:hover, +.loadMoreButton:hover { + filter: brightness(1.04); + transform: translateY(-1px); +} + +.primaryCta:active, +.lockedPreview:active, +.loadMoreButton:active, +.navButton:active { + transform: translateY(1px) scale(0.99); +} + +.primaryCta:focus-visible, +.lockedPreview:focus-visible, +.navButton:focus-visible, +.loadMoreButton:focus-visible, +.dialogPrimary:focus-visible, +.dialogSecondary:focus-visible { + outline: 2px solid #ff5d95; + outline-offset: 3px; +} + @keyframes riseIn { from { opacity: 0; diff --git a/src/app/private-room/private-room-screen.tsx b/src/app/private-room/private-room-screen.tsx new file mode 100644 index 00000000..726a3eea --- /dev/null +++ b/src/app/private-room/private-room-screen.tsx @@ -0,0 +1,440 @@ +"use client"; + +import type { CSSProperties } from "react"; +import { useEffect, useMemo, useRef } from "react"; +import Image from "next/image"; +import { + Camera, + ImageIcon, + LockKeyhole, + MessageCircle, + RefreshCw, + Sparkles, +} from "lucide-react"; + +import type { PrivateRoomMoment } from "@/data/dto/private-room"; +import { MobileShell } from "@/app/_components/core"; +import { useGuestLoginBootstrap } from "@/hooks/use-guest-login-bootstrap"; +import { ROUTES } from "@/router/routes"; +import { useAppNavigator } from "@/router/use-app-navigator"; +import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context"; +import { + usePrivateRoomDispatch, + usePrivateRoomState, +} from "@/stores/private-room"; +import { useUserDispatch } from "@/stores/user/user-context"; + +import styles from "./private-room-screen.module.css"; + +const FALLBACK_PROFILE = { + name: "Elio Silvestri", + handle: "@elio.private", + avatar: "/images/chat/pic-chat-elio.png", + title: "Elio Private room", + subtitle: "Join me, unlock my private room", + bio: "Soft moments, private photos, and a little sweetness just for you.", +} as const; + +export function PrivateRoomScreen() { + const navigator = useAppNavigator(); + const authState = useAuthState(); + const authDispatch = useAuthDispatch(); + const userDispatch = useUserDispatch(); + const state = usePrivateRoomState(); + const dispatch = usePrivateRoomDispatch(); + const previousLoginStatusRef = useRef(authState.loginStatus); + const lastUnlockSuccessNonceRef = useRef(0); + + useGuestLoginBootstrap({ + dispatch: authDispatch, + hasInitialized: authState.hasInitialized, + isLoading: authState.isLoading, + loginStatus: authState.loginStatus, + }); + + useEffect(() => { + if (!authState.hasInitialized || authState.isLoading) return; + if (authState.loginStatus === "notLoggedIn") return; + + const previousLoginStatus = previousLoginStatusRef.current; + previousLoginStatusRef.current = authState.loginStatus; + + if (state.status === "idle") { + dispatch({ type: "PrivateRoomInit" }); + return; + } + + if ( + previousLoginStatus !== authState.loginStatus && + state.status !== "loading" + ) { + dispatch({ type: "PrivateRoomRefresh" }); + } + }, [ + authState.hasInitialized, + authState.isLoading, + authState.loginStatus, + dispatch, + state.status, + ]); + + useEffect(() => { + const request = state.unlockPaywallRequest; + if (!request) return; + + if ( + authState.loginStatus === "guest" || + authState.loginStatus === "notLoggedIn" + ) { + navigator.openAuth(ROUTES.privateRoom); + } else { + navigator.openSubscription({ type: "topup" }); + } + dispatch({ type: "PrivateRoomUnlockPaywallConsumed" }); + }, [ + authState.loginStatus, + dispatch, + navigator, + state.unlockPaywallRequest, + ]); + + useEffect(() => { + if (state.unlockSuccessNonce <= lastUnlockSuccessNonceRef.current) return; + lastUnlockSuccessNonceRef.current = state.unlockSuccessNonce; + userDispatch({ type: "UserFetch" }); + }, [state.unlockSuccessNonce, userDispatch]); + + const profile = state.profile; + const displayName = + profile?.displayName || profile?.authorName || FALLBACK_PROFILE.name; + const avatarUrl = profile?.avatarUrl || FALLBACK_PROFILE.avatar; + const title = profile?.title || FALLBACK_PROFILE.title; + const subtitle = profile?.subtitle || FALLBACK_PROFILE.subtitle; + const pendingMoment = useMemo( + () => + state.items.find( + (item) => item.momentId === state.pendingConfirmMomentId, + ) ?? null, + [state.items, state.pendingConfirmMomentId], + ); + + const handleTopUpClick = () => { + if ( + authState.loginStatus === "guest" || + authState.loginStatus === "notLoggedIn" + ) { + navigator.openAuth(ROUTES.privateRoom); + return; + } + navigator.openSubscription({ type: "topup" }); + }; + + return ( + +
+
+
+ +
+
+
+ +
+
+ {displayName} +
+ +
+

+ {displayName} +

+

{title}

+
+
+ +

{subtitle || FALLBACK_PROFILE.bio}

+ + +
+ +
+
+
+

Posts

+

+ Private moments +

+
+ {state.items.length} +
+ + {state.errorMessage ? ( + dispatch({ type: "PrivateRoomRefresh" })} + /> + ) : null} + + {state.isLoading && state.items.length === 0 ? ( + + ) : null} + + {!state.isLoading && state.items.length === 0 && !state.errorMessage ? ( + dispatch({ type: "PrivateRoomRefresh" })} + /> + ) : null} + +
+ {state.items.map((moment, index) => ( + + dispatch({ + type: "PrivateRoomUnlockRequested", + momentId: moment.momentId, + }) + } + /> + ))} +
+ + {state.hasMore ? ( + + ) : null} +
+ + + + {pendingMoment ? ( + dispatch({ type: "PrivateRoomUnlockCancelled" })} + onConfirm={() => dispatch({ type: "PrivateRoomUnlockConfirmed" })} + /> + ) : state.unlockErrorMessage ? ( +
+ {state.unlockErrorMessage} +
+ ) : null} +
+
+ ); +} + +function PrivateRoomPostCard({ + moment, + displayName, + avatarUrl, + index, + isUnlocking, + onUnlock, +}: { + moment: PrivateRoomMoment; + displayName: string; + avatarUrl: string; + index: number; + isUnlocking: boolean; + onUnlock: () => void; +}) { + const isLocked = moment.locked || moment.lockDetail.locked; + const imageUrls = moment.images + .filter((image) => !image.locked && image.url) + .map((image) => image.url as string); + const photoCount = moment.mediaCount || moment.images.length || 1; + + return ( +
+
+
+ +
+

{moment.author.name || displayName}

+

+ {moment.title || "Private room drop"} +

+
+
+ +
+ + {moment.text || moment.content ? ( +

{moment.text || moment.content}

+ ) : null} + + {isLocked ? ( + + ) : ( +
+ {imageUrls.map((url, imageIndex) => ( + + ))} +
+ )} +
+ ); +} + +function UnlockConfirmDialog({ + moment, + isUnlocking, + errorMessage, + onCancel, + onConfirm, +}: { + moment: PrivateRoomMoment; + isUnlocking: boolean; + errorMessage: string | null; + onCancel: () => void; + onConfirm: () => void; +}) { + return ( +
+
+

Unlock private moment?

+

+ This will use {moment.unlockCost} credits. +

+ {errorMessage ? ( +

{errorMessage}

+ ) : null} +
+ + +
+
+
+ ); +} + +function StatusCard({ + message, + actionLabel, + onAction, +}: { + message: string; + actionLabel?: string; + onAction?: () => void; +}) { + return ( +
+

{message}

+ {actionLabel && onAction ? ( + + ) : null} +
+ ); +} + +function formatMomentTime(value: string | null): string { + if (!value) return ""; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return ""; + return date.toLocaleDateString(undefined, { + month: "short", + day: "numeric", + }); +} diff --git a/src/app/profile/page.tsx b/src/app/profile/page.tsx index b26ed174..08ab49d6 100644 --- a/src/app/profile/page.tsx +++ b/src/app/profile/page.tsx @@ -1,5 +1,5 @@ -import { ProfileScreen } from "./profile-screen"; +import { redirect } from "next/navigation"; export default function ProfilePage() { - return ; + redirect("/private-room"); } diff --git a/src/app/profile/profile-screen.tsx b/src/app/profile/profile-screen.tsx deleted file mode 100644 index 2f24c318..00000000 --- a/src/app/profile/profile-screen.tsx +++ /dev/null @@ -1,164 +0,0 @@ -"use client"; - -import Image from "next/image"; -import { Camera, ImageIcon, LockKeyhole, MessageCircle, Sparkles } from "lucide-react"; - -import { MobileShell } from "@/app/_components/core"; -import { useAppNavigator } from "@/router/use-app-navigator"; - -import styles from "./profile-screen.module.css"; - -const PROFILE = { - name: "Elio Silvestri", - handle: "@elio.private", - avatar: "/images/chat/pic-chat-elio.png", - postsCount: 10, - cta: "Join Me, unlock my private zoom", - bio: "Soft moments, private photos, and a little sweetness just for you.", -} as const; - -const POSTS = [ - { - id: "private-zoom-1", - timeAgo: "1 day ago", - price: "XXX coins", - photoCount: "7 photos", - }, - { - id: "private-zoom-2", - timeAgo: "30 days ago", - price: "XXX coins", - photoCount: "7 photos", - }, -] as const; - -export function ProfileScreen() { - const navigator = useAppNavigator(); - - const openVipSubscription = () => { - navigator.openSubscription({ type: "vip" }); - }; - - return ( - -
-
-
- -
-
-
- -
-
- {PROFILE.name} -
- -
-

- {PROFILE.name} -

-

{PROFILE.handle}

-
-
- -

{PROFILE.bio}

- - -
- -
-
-
-

Posts

-

- Private moments -

-
- {PROFILE.postsCount} -
- -
- {POSTS.map((post, index) => ( -
-
-
- -
-

{PROFILE.name}

-

Private zoom drop

-
-
- -
- - -
- ))} -
-
- - -
-
- ); -} diff --git a/src/data/dto/private-room/__tests__/private_room.test.ts b/src/data/dto/private-room/__tests__/private_room.test.ts new file mode 100644 index 00000000..f6df6ebe --- /dev/null +++ b/src/data/dto/private-room/__tests__/private_room.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it } from "vitest"; + +import { + PrivateRoomMomentsResponse, + PrivateRoomUnlockResponse, +} from "@/data/dto/private-room"; +import { ApiPath } from "@/data/services/api"; + +const lockedMoment = { + 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, + }, +}; + +describe("PrivateRoom DTOs", () => { + it("parses locked moments without image URLs", () => { + const response = 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: [lockedMoment], + nextCursor: null, + hasMore: false, + creditBalance: 100, + unlockCostDefault: 40, + unlockCostPerImage: 40, + currency: "credits", + source: "elio_schedules", + }); + + expect(response.items[0]?.locked).toBe(true); + expect(response.items[0]?.images[0]?.url).toBeNull(); + expect(response.items[0]?.unlockCost).toBe(40); + expect(response.profile.displayName).toBe("Elio Silvestri"); + }); + + it("parses unlock success with real image URLs", () => { + const response = PrivateRoomUnlockResponse.from({ + ...lockedMoment, + locked: false, + unlocked: true, + content: "A quiet morning in Paris.", + text: "A quiet morning in Paris.", + images: [ + { + url: "https://lehwkihwnlqkavhcspel.supabase.co/storage/v1/object/public/elio-schedules/schedules/91/photo.jpg", + type: "image", + locked: false, + index: 0, + }, + ], + reason: "ok", + creditsCharged: 40, + creditBalance: 60, + previousCreditBalance: 100, + persisted: true, + }); + + expect(response.unlocked).toBe(true); + expect(response.reason).toBe("ok"); + expect(response.images[0]?.url).toContain("https://"); + expect(response.creditBalance).toBe(60); + }); + + it("parses insufficient credits as business data", () => { + const response = PrivateRoomUnlockResponse.from({ + ...lockedMoment, + reason: "insufficient_credits", + currentCredits: 10, + shortfallCredits: 30, + creditBalance: 10, + }); + + expect(response.unlocked).toBe(false); + expect(response.locked).toBe(true); + expect(response.reason).toBe("insufficient_credits"); + expect(response.images[0]?.url).toBeNull(); + }); + + it("encodes moment id in the unlock path", () => { + expect(ApiPath.privateRoomMomentUnlock("schedule:91")).toBe( + "/api/private-room/moments/schedule%3A91/unlock", + ); + }); +}); diff --git a/src/data/dto/private-room/index.ts b/src/data/dto/private-room/index.ts new file mode 100644 index 00000000..42b1dd43 --- /dev/null +++ b/src/data/dto/private-room/index.ts @@ -0,0 +1,3 @@ +export * from "./private_room_moment"; +export * from "./request"; +export * from "./response"; diff --git a/src/data/dto/private-room/private_room_moment.ts b/src/data/dto/private-room/private_room_moment.ts new file mode 100644 index 00000000..9baf1843 --- /dev/null +++ b/src/data/dto/private-room/private_room_moment.ts @@ -0,0 +1,51 @@ +import { + PrivateRoomMomentSchema, + type PrivateRoomMomentData, + type PrivateRoomMomentInput, +} from "@/data/schemas/private-room"; + +export class PrivateRoomMoment { + declare readonly momentId: string; + declare readonly source: string; + declare readonly sourceId: string; + declare readonly characterId: string; + declare readonly author: PrivateRoomMomentData["author"]; + declare readonly createdAt: string | null; + declare readonly publishedAt: string | null; + declare readonly timeText: string; + declare readonly title: string; + declare readonly content: string | null; + declare readonly text: string | null; + declare readonly textPreview: string; + declare readonly mediaCount: number; + declare readonly images: PrivateRoomMomentData["images"]; + declare readonly locked: boolean; + declare readonly unlocked: boolean; + declare readonly unlockCost: number; + declare readonly unlockCostPerImage: number; + declare readonly requiredCredits: number; + declare readonly currency: string; + declare readonly lockDetail: PrivateRoomMomentData["lockDetail"]; + + protected constructor(input: PrivateRoomMomentInput, freeze = true) { + const data = PrivateRoomMomentSchema.parse(input); + Object.assign(this, data); + if (freeze) Object.freeze(this); + } + + static from(input: PrivateRoomMomentInput): PrivateRoomMoment { + return new PrivateRoomMoment(input); + } + + static fromJson(json: unknown): PrivateRoomMoment { + return PrivateRoomMoment.from(json as PrivateRoomMomentInput); + } + + toJson(): PrivateRoomMomentData { + return PrivateRoomMomentSchema.parse(this); + } +} + +export type PrivateRoomProfile = import("@/data/schemas/private-room").PrivateRoomProfileData; +export type PrivateRoomImage = import("@/data/schemas/private-room").PrivateRoomImageData; +export type PrivateRoomLockDetail = import("@/data/schemas/private-room").PrivateRoomLockDetailData; diff --git a/src/data/dto/private-room/request/index.ts b/src/data/dto/private-room/request/index.ts new file mode 100644 index 00000000..38e853e0 --- /dev/null +++ b/src/data/dto/private-room/request/index.ts @@ -0,0 +1 @@ +export * from "./unlock_private_room_moment_request"; diff --git a/src/data/dto/private-room/request/unlock_private_room_moment_request.ts b/src/data/dto/private-room/request/unlock_private_room_moment_request.ts new file mode 100644 index 00000000..28acc0c5 --- /dev/null +++ b/src/data/dto/private-room/request/unlock_private_room_moment_request.ts @@ -0,0 +1,31 @@ +import { + UnlockPrivateRoomMomentRequestSchema, + type UnlockPrivateRoomMomentRequestData, + type UnlockPrivateRoomMomentRequestInput, +} from "@/data/schemas/private-room"; + +export class UnlockPrivateRoomMomentRequest { + declare readonly expectedCost: number; + + private constructor(input: UnlockPrivateRoomMomentRequestInput) { + const data = UnlockPrivateRoomMomentRequestSchema.parse(input); + Object.assign(this, data); + Object.freeze(this); + } + + static from( + input: UnlockPrivateRoomMomentRequestInput, + ): UnlockPrivateRoomMomentRequest { + return new UnlockPrivateRoomMomentRequest(input); + } + + static fromJson(json: unknown): UnlockPrivateRoomMomentRequest { + return UnlockPrivateRoomMomentRequest.from( + json as UnlockPrivateRoomMomentRequestInput, + ); + } + + toJson(): UnlockPrivateRoomMomentRequestData { + return UnlockPrivateRoomMomentRequestSchema.parse(this); + } +} diff --git a/src/data/dto/private-room/response/index.ts b/src/data/dto/private-room/response/index.ts new file mode 100644 index 00000000..243a7043 --- /dev/null +++ b/src/data/dto/private-room/response/index.ts @@ -0,0 +1,2 @@ +export * from "./private_room_moments_response"; +export * from "./private_room_unlock_response"; diff --git a/src/data/dto/private-room/response/private_room_moments_response.ts b/src/data/dto/private-room/response/private_room_moments_response.ts new file mode 100644 index 00000000..fdd874ce --- /dev/null +++ b/src/data/dto/private-room/response/private_room_moments_response.ts @@ -0,0 +1,54 @@ +import { + PrivateRoomMomentsResponseSchema, + type PrivateRoomMomentsResponseData, + type PrivateRoomMomentsResponseInput, +} from "@/data/schemas/private-room"; + +import { PrivateRoomMoment } from "../private_room_moment"; + +export class PrivateRoomMomentsResponse { + declare readonly profile: PrivateRoomMomentsResponseData["profile"]; + declare readonly items: PrivateRoomMoment[]; + declare readonly nextCursor: string | null; + declare readonly hasMore: boolean; + declare readonly creditBalance: number; + declare readonly unlockCostDefault: number; + declare readonly unlockCostPerImage: number; + declare readonly currency: string; + declare readonly source: string; + + private constructor(input: PrivateRoomMomentsResponseInput) { + const data = PrivateRoomMomentsResponseSchema.parse(input); + Object.assign(this, { + ...data, + items: data.items.map((item) => PrivateRoomMoment.from(item)), + }); + Object.freeze(this); + } + + static from( + input: PrivateRoomMomentsResponseInput, + ): PrivateRoomMomentsResponse { + return new PrivateRoomMomentsResponse(input); + } + + static fromJson(json: unknown): PrivateRoomMomentsResponse { + return PrivateRoomMomentsResponse.from( + json as PrivateRoomMomentsResponseInput, + ); + } + + toJson(): PrivateRoomMomentsResponseData { + return { + profile: this.profile, + items: this.items.map((item) => item.toJson()), + nextCursor: this.nextCursor, + hasMore: this.hasMore, + creditBalance: this.creditBalance, + unlockCostDefault: this.unlockCostDefault, + unlockCostPerImage: this.unlockCostPerImage, + currency: this.currency, + source: this.source, + }; + } +} diff --git a/src/data/dto/private-room/response/private_room_unlock_response.ts b/src/data/dto/private-room/response/private_room_unlock_response.ts new file mode 100644 index 00000000..3c5d933f --- /dev/null +++ b/src/data/dto/private-room/response/private_room_unlock_response.ts @@ -0,0 +1,41 @@ +import { + PrivateRoomUnlockResponseSchema, + type PrivateRoomUnlockReason, + type PrivateRoomUnlockResponseData, + type PrivateRoomUnlockResponseInput, +} from "@/data/schemas/private-room"; + +import { PrivateRoomMoment } from "../private_room_moment"; + +export class PrivateRoomUnlockResponse extends PrivateRoomMoment { + declare readonly reason: PrivateRoomUnlockReason | string; + declare readonly creditsCharged: number; + declare readonly creditBalance: number; + declare readonly previousCreditBalance: number; + declare readonly currentCredits: number; + declare readonly shortfallCredits: number; + declare readonly persisted: boolean; + + private constructor(input: PrivateRoomUnlockResponseInput) { + const data = PrivateRoomUnlockResponseSchema.parse(input); + super(data, false); + Object.assign(this, data); + Object.freeze(this); + } + + static override from( + input: PrivateRoomUnlockResponseInput, + ): PrivateRoomUnlockResponse { + return new PrivateRoomUnlockResponse(input); + } + + static override fromJson(json: unknown): PrivateRoomUnlockResponse { + return PrivateRoomUnlockResponse.from( + json as PrivateRoomUnlockResponseInput, + ); + } + + override toJson(): PrivateRoomUnlockResponseData { + return PrivateRoomUnlockResponseSchema.parse(this); + } +} diff --git a/src/data/repositories/index.ts b/src/data/repositories/index.ts index 84e43c4c..0dea2574 100644 --- a/src/data/repositories/index.ts +++ b/src/data/repositories/index.ts @@ -6,9 +6,11 @@ export * from "./auth_repository"; export * from "./chat_repository"; export * from "./metrics_repository"; export * from "./payment_repository"; +export * from "./private_room_repository"; export * from "./user_repository"; export * from "./interfaces/iauth_repository"; export * from "./interfaces/ichat_repository"; export * from "./interfaces/imetrics_repository"; export * from "./interfaces/ipayment_repository"; +export * from "./interfaces/iprivate_room_repository"; export * from "./interfaces/iuser_repository"; diff --git a/src/data/repositories/interfaces/index.ts b/src/data/repositories/interfaces/index.ts index 4fb1821a..d5877353 100644 --- a/src/data/repositories/interfaces/index.ts +++ b/src/data/repositories/interfaces/index.ts @@ -6,4 +6,5 @@ export * from "./iauth_repository"; export * from "./ichat_repository"; export * from "./imetrics_repository"; export * from "./ipayment_repository"; +export * from "./iprivate_room_repository"; export * from "./iuser_repository"; diff --git a/src/data/repositories/interfaces/iprivate_room_repository.ts b/src/data/repositories/interfaces/iprivate_room_repository.ts new file mode 100644 index 00000000..957cbda5 --- /dev/null +++ b/src/data/repositories/interfaces/iprivate_room_repository.ts @@ -0,0 +1,22 @@ +import type { + PrivateRoomMomentsResponse, + PrivateRoomUnlockResponse, +} from "@/data/dto/private-room"; +import type { Result } from "@/utils/result"; + +export interface GetPrivateRoomMomentsInput { + character?: string; + limit?: number; + cursor?: string | null; +} + +export interface IPrivateRoomRepository { + getMoments( + input?: GetPrivateRoomMomentsInput, + ): Promise>; + + unlockMoment( + momentId: string, + expectedCost: number, + ): Promise>; +} diff --git a/src/data/repositories/private_room_repository.ts b/src/data/repositories/private_room_repository.ts new file mode 100644 index 00000000..b7c15164 --- /dev/null +++ b/src/data/repositories/private_room_repository.ts @@ -0,0 +1,45 @@ +"use client"; + +import { + UnlockPrivateRoomMomentRequest, + type PrivateRoomMomentsResponse, + type PrivateRoomUnlockResponse, +} from "@/data/dto/private-room"; +import { + PrivateRoomApi, + privateRoomApi, +} from "@/data/services/api/private_room_api"; +import type { + GetPrivateRoomMomentsInput, + IPrivateRoomRepository, +} from "@/data/repositories/interfaces"; +import { Result } from "@/utils/result"; + +import { createLazySingleton } from "./lazy_singleton"; + +export class PrivateRoomRepository implements IPrivateRoomRepository { + constructor(private readonly api: PrivateRoomApi) {} + + getMoments( + input: GetPrivateRoomMomentsInput = {}, + ): Promise> { + return Result.wrap(() => this.api.getMoments(input)); + } + + unlockMoment( + momentId: string, + expectedCost: number, + ): Promise> { + return Result.wrap(() => + this.api.unlockMoment( + momentId, + UnlockPrivateRoomMomentRequest.from({ expectedCost }), + ), + ); + } +} + +export const getPrivateRoomRepository = + createLazySingleton( + () => new PrivateRoomRepository(privateRoomApi), + ); diff --git a/src/data/schemas/private-room/index.ts b/src/data/schemas/private-room/index.ts new file mode 100644 index 00000000..328c63c6 --- /dev/null +++ b/src/data/schemas/private-room/index.ts @@ -0,0 +1,4 @@ +export * from "./private_room"; +export * from "./private_room_moments_response"; +export * from "./private_room_unlock_response"; +export * from "./unlock_private_room_moment_request"; diff --git a/src/data/schemas/private-room/private_room.ts b/src/data/schemas/private-room/private_room.ts new file mode 100644 index 00000000..479f7d8d --- /dev/null +++ b/src/data/schemas/private-room/private_room.ts @@ -0,0 +1,102 @@ +import { z } from "zod"; + +import { + arrayOrEmpty, + booleanOrFalse, + numberOrZero, + schemaOr, + stringOrEmpty, + stringOrNull, +} from "../nullable-defaults"; + +export const PrivateRoomProfileSchema = z.object({ + characterId: stringOrEmpty, + displayName: stringOrEmpty, + authorName: stringOrEmpty, + avatarUrl: stringOrNull, + coverUrl: stringOrNull, + title: stringOrEmpty, + subtitle: stringOrEmpty, +}); + +export const PrivateRoomImageSchema = z.object({ + url: stringOrNull, + type: stringOrEmpty, + locked: booleanOrFalse, + index: numberOrZero, +}); + +export const PrivateRoomLockDetailSchema = z.object({ + locked: booleanOrFalse, + showContent: booleanOrFalse, + showUpgrade: booleanOrFalse, + reason: stringOrNull, + hint: stringOrNull, + actionLabel: stringOrNull, + type: stringOrNull, + requiredCredits: numberOrZero, + currentCredits: numberOrZero, + shortfallCredits: numberOrZero, + mediaCount: numberOrZero, + unlockCostPerImage: numberOrZero, + detail: z.unknown().nullable().default(null), +}); + +export const PrivateRoomAuthorSchema = z.object({ + id: stringOrEmpty, + name: stringOrEmpty, + avatarUrl: stringOrNull, +}); + +export const PrivateRoomMomentSchema = z.object({ + momentId: stringOrEmpty, + source: stringOrEmpty, + sourceId: stringOrEmpty, + characterId: stringOrEmpty, + author: schemaOr(PrivateRoomAuthorSchema, { + id: "", + name: "", + avatarUrl: null, + }), + createdAt: stringOrNull, + publishedAt: stringOrNull, + timeText: stringOrEmpty, + title: stringOrEmpty, + content: stringOrNull, + text: stringOrNull, + textPreview: stringOrEmpty, + mediaCount: numberOrZero, + images: arrayOrEmpty(PrivateRoomImageSchema), + locked: booleanOrFalse, + unlocked: booleanOrFalse, + unlockCost: numberOrZero, + unlockCostPerImage: numberOrZero, + requiredCredits: numberOrZero, + currency: stringOrEmpty, + lockDetail: schemaOr(PrivateRoomLockDetailSchema, { + locked: false, + showContent: false, + showUpgrade: false, + reason: null, + hint: null, + actionLabel: null, + type: null, + requiredCredits: 0, + currentCredits: 0, + shortfallCredits: 0, + mediaCount: 0, + unlockCostPerImage: 0, + detail: null, + }), +}); + +export type PrivateRoomProfileData = z.output< + typeof PrivateRoomProfileSchema +>; +export type PrivateRoomImageData = z.output; +export type PrivateRoomLockDetailData = z.output< + typeof PrivateRoomLockDetailSchema +>; +export type PrivateRoomAuthorData = z.output; +export type PrivateRoomMomentInput = z.input; +export type PrivateRoomMomentData = z.output; diff --git a/src/data/schemas/private-room/private_room_moments_response.ts b/src/data/schemas/private-room/private_room_moments_response.ts new file mode 100644 index 00000000..0257f253 --- /dev/null +++ b/src/data/schemas/private-room/private_room_moments_response.ts @@ -0,0 +1,41 @@ +import { z } from "zod"; + +import { + arrayOrEmpty, + booleanOrFalse, + numberOrZero, + schemaOr, + stringOrEmpty, + stringOrNull, +} from "../nullable-defaults"; +import { + PrivateRoomMomentSchema, + PrivateRoomProfileSchema, +} from "./private_room"; + +export const PrivateRoomMomentsResponseSchema = z.object({ + profile: schemaOr(PrivateRoomProfileSchema, { + characterId: "elio", + displayName: "Elio Silvestri", + authorName: "Elio Silvestri", + avatarUrl: null, + coverUrl: null, + title: "Elio Private room", + subtitle: "Join me, unlock my private room", + }), + items: arrayOrEmpty(PrivateRoomMomentSchema), + nextCursor: stringOrNull, + hasMore: booleanOrFalse, + creditBalance: numberOrZero, + unlockCostDefault: numberOrZero, + unlockCostPerImage: numberOrZero, + currency: stringOrEmpty, + source: stringOrEmpty, +}); + +export type PrivateRoomMomentsResponseInput = z.input< + typeof PrivateRoomMomentsResponseSchema +>; +export type PrivateRoomMomentsResponseData = z.output< + typeof PrivateRoomMomentsResponseSchema +>; diff --git a/src/data/schemas/private-room/private_room_unlock_response.ts b/src/data/schemas/private-room/private_room_unlock_response.ts new file mode 100644 index 00000000..d2feae04 --- /dev/null +++ b/src/data/schemas/private-room/private_room_unlock_response.ts @@ -0,0 +1,36 @@ +import { z } from "zod"; + +import { booleanOrFalse, numberOrZero, stringOrEmpty } from "../nullable-defaults"; +import { PrivateRoomMomentSchema } from "./private_room"; + +export const PrivateRoomUnlockReasonSchema = z.enum([ + "ok", + "already_unlocked", + "insufficient_credits", + "cost_changed", + "not_found", + "no_media", + "deduct_failed", + "ok_persist_failed", +]); + +export const PrivateRoomUnlockResponseSchema = + PrivateRoomMomentSchema.extend({ + reason: PrivateRoomUnlockReasonSchema.or(stringOrEmpty), + creditsCharged: numberOrZero, + creditBalance: numberOrZero, + previousCreditBalance: numberOrZero, + currentCredits: numberOrZero, + shortfallCredits: numberOrZero, + persisted: booleanOrFalse, + }); + +export type PrivateRoomUnlockReason = z.output< + typeof PrivateRoomUnlockReasonSchema +>; +export type PrivateRoomUnlockResponseInput = z.input< + typeof PrivateRoomUnlockResponseSchema +>; +export type PrivateRoomUnlockResponseData = z.output< + typeof PrivateRoomUnlockResponseSchema +>; diff --git a/src/data/schemas/private-room/unlock_private_room_moment_request.ts b/src/data/schemas/private-room/unlock_private_room_moment_request.ts new file mode 100644 index 00000000..07705c7d --- /dev/null +++ b/src/data/schemas/private-room/unlock_private_room_moment_request.ts @@ -0,0 +1,14 @@ +import { z } from "zod"; + +import { numberOrZero } from "../nullable-defaults"; + +export const UnlockPrivateRoomMomentRequestSchema = z.object({ + expectedCost: numberOrZero, +}); + +export type UnlockPrivateRoomMomentRequestInput = z.input< + typeof UnlockPrivateRoomMomentRequestSchema +>; +export type UnlockPrivateRoomMomentRequestData = z.output< + typeof UnlockPrivateRoomMomentRequestSchema +>; diff --git a/src/data/services/api/api_path.ts b/src/data/services/api/api_path.ts index 6e2502d4..7d59f448 100644 --- a/src/data/services/api/api_path.ts +++ b/src/data/services/api/api_path.ts @@ -14,6 +14,7 @@ export class ApiPath { private static readonly _user = `${ApiPath._baseUrl}/user`; private static readonly _payment = `${ApiPath._baseUrl}/payment`; private static readonly _chat = `${ApiPath._baseUrl}/chat`; + private static readonly _privateRoom = `${ApiPath._baseUrl}/private-room`; // ============ 认证相关 ============ /** 邮箱密码登录 */ @@ -73,6 +74,15 @@ export class ApiPath { /** 一键解锁历史锁定消息 */ static readonly chatUnlockHistory = `${ApiPath._chat}/unlock-history`; + // ============ 私密空间相关 ============ + /** 获取私密空间动态列表 */ + static readonly privateRoomMoments = `${ApiPath._privateRoom}/moments`; + + /** 解锁私密空间动态 */ + static privateRoomMomentUnlock(momentId: string): string { + return `${ApiPath.privateRoomMoments}/${encodeURIComponent(momentId)}/unlock`; + } + // ============ 数据看板相关 ============ private static readonly _metrics = `${ApiPath._baseUrl}/metrics`; diff --git a/src/data/services/api/index.ts b/src/data/services/api/index.ts index d2bad177..34fd9242 100644 --- a/src/data/services/api/index.ts +++ b/src/data/services/api/index.ts @@ -9,5 +9,6 @@ export * from "./chat_api"; export * from "./http_client"; export * from "./metrics_api"; export * from "./payment_api"; +export * from "./private_room_api"; export * from "./response_helper"; export * from "./user_api"; diff --git a/src/data/services/api/private_room_api.ts b/src/data/services/api/private_room_api.ts new file mode 100644 index 00000000..ea4b64b3 --- /dev/null +++ b/src/data/services/api/private_room_api.ts @@ -0,0 +1,49 @@ +import { + PrivateRoomMomentsResponse, + PrivateRoomUnlockResponse, + UnlockPrivateRoomMomentRequest, +} from "@/data/dto/private-room"; + +import { ApiPath } from "./api_path"; +import { httpClient } from "./http_client"; +import { type ApiEnvelope, unwrap } from "./response_helper"; + +export interface GetPrivateRoomMomentsInput { + character?: string; + limit?: number; + cursor?: string | null; +} + +export class PrivateRoomApi { + async getMoments( + input: GetPrivateRoomMomentsInput = {}, + ): Promise { + const env = await httpClient>( + ApiPath.privateRoomMoments, + { + query: { + character: input.character ?? "elio", + limit: input.limit ?? 20, + ...(input.cursor ? { cursor: input.cursor } : {}), + }, + }, + ); + return PrivateRoomMomentsResponse.fromJson(unwrap(env)); + } + + async unlockMoment( + momentId: string, + body: UnlockPrivateRoomMomentRequest, + ): Promise { + const env = await httpClient>( + ApiPath.privateRoomMomentUnlock(momentId), + { + method: "POST", + body: body.toJson(), + }, + ); + return PrivateRoomUnlockResponse.fromJson(unwrap(env)); + } +} + +export const privateRoomApi = new PrivateRoomApi(); diff --git a/src/hooks/use-guest-login-bootstrap.ts b/src/hooks/use-guest-login-bootstrap.ts new file mode 100644 index 00000000..0b0a9266 --- /dev/null +++ b/src/hooks/use-guest-login-bootstrap.ts @@ -0,0 +1,65 @@ +"use client"; + +import { type Dispatch, useEffect, useRef } from "react"; + +import type { LoginStatus } from "@/data/dto/auth"; +import type { AuthEvent } from "@/stores/auth/auth-events"; + +export interface GuestLoginBootstrapState { + hasInitialized: boolean; + isLoading: boolean; + loginStatus: LoginStatus; +} + +export interface ShouldSubmitGuestLoginInput + extends GuestLoginBootstrapState { + alreadyRequested: boolean; +} + +export interface UseGuestLoginBootstrapInput + extends GuestLoginBootstrapState { + dispatch: Dispatch; +} + +export function shouldSubmitGuestLogin({ + alreadyRequested, + hasInitialized, + isLoading, + loginStatus, +}: ShouldSubmitGuestLoginInput): boolean { + if (!hasInitialized || isLoading) return false; + if (loginStatus !== "notLoggedIn") return false; + return !alreadyRequested; +} + +export function useGuestLoginBootstrap({ + dispatch, + hasInitialized, + isLoading, + loginStatus, +}: UseGuestLoginBootstrapInput): void { + const guestLoginRequestedRef = useRef(false); + + useEffect(() => { + if (!hasInitialized || isLoading) return; + + if (loginStatus !== "notLoggedIn") { + guestLoginRequestedRef.current = false; + return; + } + + if ( + !shouldSubmitGuestLogin({ + alreadyRequested: guestLoginRequestedRef.current, + hasInitialized, + isLoading, + loginStatus, + }) + ) { + return; + } + + guestLoginRequestedRef.current = true; + dispatch({ type: "AuthGuestLoginSubmitted" }); + }, [dispatch, hasInitialized, isLoading, loginStatus]); +} diff --git a/src/providers/root-providers.tsx b/src/providers/root-providers.tsx index b1f54f9a..b4edf8a9 100644 --- a/src/providers/root-providers.tsx +++ b/src/providers/root-providers.tsx @@ -4,7 +4,7 @@ * 根级 Client Providers 包装 * * 把所有功能 Provider 串起来: - * AuthProvider → UserProvider → PaymentProvider → ChatProvider + * AuthProvider → UserProvider → PaymentProvider → ChatProvider → PrivateRoomProvider * + AuthStatusChecker(启动时一次:派发 AuthInit) * + OAuthSessionSync (持续监听 NextAuth session → auth machine) * + UserAuthSync (auth 登录态恢复后 hydrate user machine) @@ -23,6 +23,7 @@ import { AuthStatusChecker } from "@/stores/auth/auth-status-checker"; import { OAuthSessionSync } from "@/stores/auth/oauth-session-sync"; import { ChatProvider } from "@/stores/chat/chat-context"; import { PaymentProvider } from "@/stores/payment"; +import { PrivateRoomProvider } from "@/stores/private-room"; import { ChatAuthSync, PaymentSuccessSync, @@ -48,10 +49,12 @@ export function RootProviders({ children }: RootProvidersProps) { - - - {children} -
+ + + + {children} +
+ diff --git a/src/router/__tests__/route-meta.test.ts b/src/router/__tests__/route-meta.test.ts index 196ef44c..01bafd4e 100644 --- a/src/router/__tests__/route-meta.test.ts +++ b/src/router/__tests__/route-meta.test.ts @@ -8,7 +8,7 @@ describe("route meta", () => { expect(getRouteAccess(ROUTES.splash)).toBe("authOnly"); expect(getRouteAccess(ROUTES.auth)).toBe("authOnly"); expect(getRouteAccess(ROUTES.chat)).toBe("guestEntry"); - expect(getRouteAccess(ROUTES.profile)).toBe("public"); + expect(getRouteAccess(ROUTES.privateRoom)).toBe("guestEntry"); expect(getRouteAccess(ROUTES.sidebar)).toBe("session"); expect(getRouteAccess(ROUTES.subscription)).toBe("realUser"); expect(getRouteAccess(ROUTES.coinsRules)).toBe("public"); @@ -19,8 +19,8 @@ describe("route meta", () => { expect(getRouteAccess("/chat/deviceid/device_1")).toBe("public"); }); - it("includes profile in static routes", () => { - expect(ALL_STATIC_ROUTES).toContain(ROUTES.profile); + it("includes private room in static routes", () => { + expect(ALL_STATIC_ROUTES).toContain(ROUTES.privateRoom); }); it("treats unknown routes as public by default", () => { diff --git a/src/router/route-meta.ts b/src/router/route-meta.ts index d535d091..a3548414 100644 --- a/src/router/route-meta.ts +++ b/src/router/route-meta.ts @@ -12,7 +12,7 @@ const STATIC_ROUTE_ACCESS: Partial> = { [ROUTES.splash]: "authOnly", [ROUTES.auth]: "authOnly", [ROUTES.chat]: "guestEntry", - [ROUTES.profile]: "public", + [ROUTES.privateRoom]: "guestEntry", [ROUTES.sidebar]: "session", [ROUTES.subscription]: "realUser", [ROUTES.coinsRules]: "public", diff --git a/src/router/routes.ts b/src/router/routes.ts index 539ee761..4752e52b 100644 --- a/src/router/routes.ts +++ b/src/router/routes.ts @@ -21,7 +21,7 @@ export const ROUTES = { root: "/", splash: "/splash", chat: "/chat", - profile: "/profile", + privateRoom: "/private-room", auth: "/auth", sidebar: "/sidebar", subscription: "/subscription", @@ -53,7 +53,7 @@ export const ROUTE_BUILDERS = { export const ALL_STATIC_ROUTES: readonly StaticRoute[] = [ ROUTES.splash, ROUTES.chat, - ROUTES.profile, + ROUTES.privateRoom, ROUTES.auth, ROUTES.sidebar, ROUTES.coinsRules, diff --git a/src/stores/private-room/__tests__/private-room-machine.test.ts b/src/stores/private-room/__tests__/private-room-machine.test.ts new file mode 100644 index 00000000..9e387491 --- /dev/null +++ b/src/stores/private-room/__tests__/private-room-machine.test.ts @@ -0,0 +1,260 @@ +import { describe, expect, it } from "vitest"; +import { createActor, fromPromise, waitFor } from "xstate"; + +import { + PrivateRoomMomentsResponse, + PrivateRoomUnlockResponse, +} 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, + }, +}; + +function makeMomentsResponse( + overrides: Partial[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", + ...overrides, + }); +} + +function makeUnlockResponse( + overrides: Partial[0]> = {}, +): PrivateRoomUnlockResponse { + return PrivateRoomUnlockResponse.from({ + ...baseMoment, + 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, + ...overrides, + }); +} + +function createTestMachine( + options: { + firstPage?: PrivateRoomMomentsResponse; + morePage?: PrivateRoomMomentsResponse; + unlockResponse?: PrivateRoomUnlockResponse; + } = {}, +) { + 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(), + ), + }, + }); +} + +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", + }), + }), + ).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", + ]); + + 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")); + + const context = actor.getSnapshot().context; + expect(context.items[0]?.unlocked).toBe(true); + expect(context.items[0]?.images[0]?.url).toContain("https://"); + 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, + }), + }), + ).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")); + + const context = actor.getSnapshot().context; + expect(context.items[0]?.unlocked).toBe(false); + expect(context.unlockPaywallRequest).toMatchObject({ + momentId: "schedule:91", + reason: "insufficient_credits", + shortfallCredits: 30, + }); + + 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, + }), + }), + ).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")); + + expect(actor.getSnapshot().context.unlockErrorMessage).toBe( + "Unlock price changed. Please confirm again.", + ); + + actor.stop(); + }); +}); diff --git a/src/stores/private-room/index.ts b/src/stores/private-room/index.ts new file mode 100644 index 00000000..a2001286 --- /dev/null +++ b/src/stores/private-room/index.ts @@ -0,0 +1,4 @@ +export * from "./private-room-context"; +export * from "./private-room-events"; +export * from "./private-room-machine"; +export * from "./private-room-state"; diff --git a/src/stores/private-room/private-room-context.tsx b/src/stores/private-room/private-room-context.tsx new file mode 100644 index 00000000..533916fa --- /dev/null +++ b/src/stores/private-room/private-room-context.tsx @@ -0,0 +1,96 @@ +"use client"; + +import { + type Dispatch, + type ReactNode, + createContext, + useContext, + useMemo, +} from "react"; +import { useMachine } from "@xstate/react"; + +import { privateRoomMachine } from "./private-room-machine"; +import type { + PrivateRoomEvent, + PrivateRoomState as MachineContext, +} from "./private-room-machine"; + +export interface PrivateRoomContextState { + status: string; + profile: MachineContext["profile"]; + items: MachineContext["items"]; + nextCursor: string | null; + hasMore: boolean; + creditBalance: number; + errorMessage: string | null; + unlockingMomentId: string | null; + unlockErrorMessage: string | null; + pendingConfirmMomentId: string | null; + unlockPaywallRequest: MachineContext["unlockPaywallRequest"]; + unlockSuccessNonce: number; + isLoading: boolean; + isLoadingMore: boolean; + isUnlocking: boolean; +} + +const PrivateRoomStateCtx = createContext(null); +const PrivateRoomDispatchCtx = createContext | null>( + null, +); + +export interface PrivateRoomProviderProps { + children: ReactNode; +} + +export function PrivateRoomProvider({ children }: PrivateRoomProviderProps) { + const [state, send] = useMachine(privateRoomMachine); + + const privateRoomState = useMemo( + () => ({ + 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, + unlockErrorMessage: state.context.unlockErrorMessage, + pendingConfirmMomentId: state.context.pendingConfirmMomentId, + unlockPaywallRequest: state.context.unlockPaywallRequest, + unlockSuccessNonce: state.context.unlockSuccessNonce, + isLoading: state.matches("loading"), + isLoadingMore: state.matches("loadingMore"), + isUnlocking: state.matches("unlocking"), + }), + [state], + ); + + return ( + + + {children} + + + ); +} + +export function usePrivateRoomState(): PrivateRoomContextState { + const ctx = useContext(PrivateRoomStateCtx); + if (!ctx) { + throw new Error( + "usePrivateRoomState must be used inside ", + ); + } + return ctx; +} + +export function usePrivateRoomDispatch(): Dispatch { + const ctx = useContext(PrivateRoomDispatchCtx); + if (!ctx) { + throw new Error( + "usePrivateRoomDispatch must be used inside ", + ); + } + return ctx; +} diff --git a/src/stores/private-room/private-room-events.ts b/src/stores/private-room/private-room-events.ts new file mode 100644 index 00000000..4cfe63c0 --- /dev/null +++ b/src/stores/private-room/private-room-events.ts @@ -0,0 +1,8 @@ +export type PrivateRoomEvent = + | { type: "PrivateRoomInit" } + | { type: "PrivateRoomRefresh" } + | { type: "PrivateRoomLoadMore" } + | { type: "PrivateRoomUnlockRequested"; momentId: string } + | { type: "PrivateRoomUnlockConfirmed" } + | { type: "PrivateRoomUnlockCancelled" } + | { type: "PrivateRoomUnlockPaywallConsumed" }; diff --git a/src/stores/private-room/private-room-machine.actors.ts b/src/stores/private-room/private-room-machine.actors.ts new file mode 100644 index 00000000..913ed720 --- /dev/null +++ b/src/stores/private-room/private-room-machine.actors.ts @@ -0,0 +1,51 @@ +import { fromPromise } from "xstate"; + +import type { + PrivateRoomMomentsResponse, + PrivateRoomUnlockResponse, +} from "@/data/dto/private-room"; +import { getPrivateRoomRepository } from "@/data/repositories/private_room_repository"; +import { Result } from "@/utils"; + +import { + PRIVATE_ROOM_CHARACTER, + PRIVATE_ROOM_PAGE_SIZE, +} from "./private-room-machine.helpers"; + +export const loadPrivateRoomMomentsActor = + fromPromise(async () => { + const repo = getPrivateRoomRepository(); + const result = await repo.getMoments({ + character: PRIVATE_ROOM_CHARACTER, + limit: PRIVATE_ROOM_PAGE_SIZE, + }); + if (Result.isErr(result)) throw result.error; + return result.data; + }); + +export const loadMorePrivateRoomMomentsActor = fromPromise< + PrivateRoomMomentsResponse, + { cursor: string | null } +>(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, + input.expectedCost, + ); + if (Result.isErr(result)) throw result.error; + return result.data; +}); diff --git a/src/stores/private-room/private-room-machine.helpers.ts b/src/stores/private-room/private-room-machine.helpers.ts new file mode 100644 index 00000000..fa001022 --- /dev/null +++ b/src/stores/private-room/private-room-machine.helpers.ts @@ -0,0 +1,88 @@ +import type { + PrivateRoomMoment, + PrivateRoomMomentsResponse, + PrivateRoomUnlockResponse, +} from "@/data/dto/private-room"; + +import type { + PrivateRoomState, + PrivateRoomUnlockPaywallRequest, +} from "./private-room-state"; + +export const PRIVATE_ROOM_CHARACTER = "elio"; +export const PRIVATE_ROOM_PAGE_SIZE = 20; + +export function applyMomentsResponse( + response: PrivateRoomMomentsResponse, +): Partial { + 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 { + 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 replaceMoment( + items: readonly PrivateRoomMoment[], + nextMoment: PrivateRoomMoment, +): PrivateRoomMoment[] { + return items.map((item) => + item.momentId === nextMoment.momentId ? nextMoment : item, + ); +} + +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, +): 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 "deduct_failed": + return "Credit deduction failed. Please try again."; + default: + return response.unlocked ? null : "Unlock failed. Please try again."; + } +} + +export function toPaywallRequest( + response: PrivateRoomUnlockResponse, +): PrivateRoomUnlockPaywallRequest { + return { + momentId: response.momentId, + reason: response.reason, + requiredCredits: response.requiredCredits, + currentCredits: response.currentCredits || response.creditBalance, + shortfallCredits: response.shortfallCredits, + }; +} diff --git a/src/stores/private-room/private-room-machine.ts b/src/stores/private-room/private-room-machine.ts new file mode 100644 index 00000000..37f51dba --- /dev/null +++ b/src/stores/private-room/private-room-machine.ts @@ -0,0 +1,217 @@ +import { assign, setup } from "xstate"; + +import type { PrivateRoomMoment } from "@/data/dto/private-room"; + +import type { PrivateRoomEvent } from "./private-room-events"; +import { + appendMomentsResponse, + applyMomentsResponse, + replaceMoment, + toPaywallRequest, + toPrivateRoomErrorMessage, + toUnlockErrorMessage, +} from "./private-room-machine.helpers"; +import { + loadMorePrivateRoomMomentsActor, + loadPrivateRoomMomentsActor, + unlockPrivateRoomMomentActor, +} from "./private-room-machine.actors"; +import { initialState, type PrivateRoomState } from "./private-room-state"; + +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; + return ( + context.items.find( + (item) => item.momentId === context.pendingConfirmMomentId, + ) ?? null + ); +} + +export const privateRoomMachine = setup({ + types: { + context: {} as PrivateRoomState, + events: {} as PrivateRoomEvent, + }, + actors: { + loadMoments: loadPrivateRoomMomentsActor, + loadMoreMoments: loadMorePrivateRoomMomentsActor, + unlockMoment: unlockPrivateRoomMomentActor, + }, +}).createMachine({ + id: "privateRoom", + initial: "idle", + context: initialState, + states: { + idle: { + on: { + PrivateRoomInit: "loading", + }, + }, + + loading: { + entry: assign({ + errorMessage: null, + unlockPaywallRequest: null, + }), + invoke: { + src: "loadMoments", + onDone: { + target: "ready", + actions: assign(({ event }) => applyMomentsResponse(event.output)), + }, + onError: { + target: "failed", + actions: assign(({ event }) => ({ + errorMessage: toPrivateRoomErrorMessage(event.error), + })), + }, + }, + }, + + failed: { + on: { + PrivateRoomInit: "loading", + PrivateRoomRefresh: "loading", + }, + }, + + ready: { + on: { + PrivateRoomInit: { + target: "loading", + }, + PrivateRoomRefresh: { + target: "loading", + }, + PrivateRoomLoadMore: [ + { + guard: ({ context }) => + context.hasMore && context.nextCursor !== null, + target: "loadingMore", + }, + ], + PrivateRoomUnlockRequested: { + actions: assign(({ event }) => ({ + pendingConfirmMomentId: event.momentId, + unlockErrorMessage: null, + unlockPaywallRequest: null, + })), + }, + PrivateRoomUnlockCancelled: { + actions: assign({ + pendingConfirmMomentId: null, + }), + }, + PrivateRoomUnlockConfirmed: [ + { + guard: ({ context }) => getPendingMoment(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), + })), + }, + }, + }, + + unlocking: { + entry: assign(({ context }) => ({ + unlockingMomentId: context.pendingConfirmMomentId, + unlockErrorMessage: null, + unlockPaywallRequest: null, + })), + invoke: { + src: "unlockMoment", + input: ({ context }) => { + const pendingMoment = getPendingMoment(context); + return { + momentId: pendingMoment?.momentId ?? "", + expectedCost: pendingMoment?.unlockCost ?? 0, + }; + }, + onDone: [ + { + guard: ({ event }) => event.output.unlocked, + target: "ready", + actions: assign(({ context, event }) => ({ + items: replaceMoment(context.items, event.output), + creditBalance: event.output.creditBalance || context.creditBalance, + pendingConfirmMomentId: null, + unlockingMomentId: null, + unlockErrorMessage: null, + unlockSuccessNonce: context.unlockSuccessNonce + 1, + })), + }, + { + guard: ({ event }) => + 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, + unlockErrorMessage: null, + unlockPaywallRequest: toPaywallRequest(event.output), + })), + }, + { + guard: ({ event }) => event.output.reason === "cost_changed", + target: "loading", + actions: assign(({ event }) => ({ + pendingConfirmMomentId: null, + unlockingMomentId: null, + unlockErrorMessage: toUnlockErrorMessage(event.output), + })), + }, + { + target: "ready", + actions: assign(({ context, event }) => ({ + items: replaceMoment(context.items, event.output), + pendingConfirmMomentId: null, + unlockingMomentId: null, + unlockErrorMessage: toUnlockErrorMessage(event.output), + })), + }, + ], + onError: { + target: "ready", + actions: assign(({ event }) => ({ + pendingConfirmMomentId: null, + unlockingMomentId: null, + unlockErrorMessage: toPrivateRoomErrorMessage(event.error), + })), + }, + }, + }, + }, +}); + +export type PrivateRoomMachine = typeof privateRoomMachine; diff --git a/src/stores/private-room/private-room-state.ts b/src/stores/private-room/private-room-state.ts new file mode 100644 index 00000000..16f87d6b --- /dev/null +++ b/src/stores/private-room/private-room-state.ts @@ -0,0 +1,40 @@ +import type { + PrivateRoomMoment, + PrivateRoomProfile, +} from "@/data/dto/private-room"; + +export interface PrivateRoomUnlockPaywallRequest { + momentId: string; + reason: string; + requiredCredits: number; + currentCredits: number; + shortfallCredits: number; +} + +export interface PrivateRoomState { + profile: PrivateRoomProfile | null; + items: PrivateRoomMoment[]; + nextCursor: string | null; + hasMore: boolean; + creditBalance: number; + errorMessage: string | null; + unlockingMomentId: string | null; + unlockErrorMessage: string | null; + pendingConfirmMomentId: string | null; + unlockPaywallRequest: PrivateRoomUnlockPaywallRequest | null; + unlockSuccessNonce: number; +} + +export const initialState: PrivateRoomState = { + profile: null, + items: [], + nextCursor: null, + hasMore: false, + creditBalance: 0, + errorMessage: null, + unlockingMomentId: null, + unlockErrorMessage: null, + pendingConfirmMomentId: null, + unlockPaywallRequest: null, + unlockSuccessNonce: 0, +};