From a483fc07678e248b272f1e63557b72ececef6e69 Mon Sep 17 00:00:00 2001 From: Amiram_se Date: Sun, 4 Oct 2026 21:33:07 +0400 Subject: [PATCH] feat(market): app foundation, session handling and feature data layer Foundation - AppShell: query client, i18n, connection bar (NetworkBoundary), toast region, and reactions to sign-in and sign-out - error boundaries: ErrorFallback, PartBoundary (catchError), StatusEmptyState, readOnServer - typed ROUTES, platform env (API origin, support config), Persian locales (common, errors) with typed i18next keys - mapApiErrorBody adapts the gateway's error envelope; shared utils for E.164 phones, API URLs and field-error renames - session: refreshSessionInProxy renews an expired cookie session before render - guards: requireAccount, redirectIfSignedIn, requireRole Data layer (entities, repositories with mappers, query keys, server caches) - auth (with login, logout and registration actions), profile, channel, follow, notification, post, prediction, feed, pricing, checkout, subscription, transaction, overview, finance - shared domain enums live in shared/constants Co-Authored-By: Claude Opus 5.5 --- platforms/market/package.json | 1 + platforms/market/src/app/app-shell/.gitkeep | 0 .../market/src/app/app-shell/AppShell.tsx | 28 +++ .../app-shell/components/NetworkBoundary.tsx | 72 ++++++ .../market/src/app/app-shell/constants.ts | 21 ++ .../app/app-shell/hooks/use-session-events.ts | 28 +++ platforms/market/src/app/app-shell/index.ts | 2 + platforms/market/src/app/app-shell/types.ts | 14 ++ .../error-boundaries/error-fallback/.gitkeep | 0 .../error-fallback/ErrorFallback.tsx | 67 +++++ .../error-boundaries/error-fallback/index.ts | 6 + .../error-boundaries/error-fallback/types.ts | 19 ++ .../error-boundaries/error-fallback/utils.ts | 20 ++ .../market/src/app/error-boundaries/index.ts | 13 + .../error-boundaries/part-boundary/.gitkeep | 0 .../part-boundary/PartBoundary.tsx | 38 +++ .../error-boundaries/part-boundary/index.ts | 2 + .../error-boundaries/part-boundary/types.ts | 4 + .../error-boundaries/read-on-server/.gitkeep | 0 .../read-on-server/read-on-server.ts | 32 +++ .../error-boundaries/read-on-server/server.ts | 4 + .../error-boundaries/read-on-server/types.ts | 9 + .../market/src/app/error-boundaries/server.ts | 4 + .../status-empty-state/.gitkeep | 0 .../status-empty-state/StatusEmptyState.tsx | 37 +++ .../status-empty-state/constants.ts | 9 + .../status-empty-state/index.ts | 2 + .../status-empty-state/types.ts | 12 + .../market/src/app/guards/auth-guard/.gitkeep | 0 .../src/app/guards/auth-guard/auth-guard.ts | 27 ++ .../src/app/guards/auth-guard/server.ts | 4 + .../market/src/app/guards/auth-guard/types.ts | 4 + .../market/src/app/guards/role-guard/.gitkeep | 0 .../src/app/guards/role-guard/role-guard.ts | 19 ++ .../src/app/guards/role-guard/server.ts | 4 + .../market/src/app/guards/role-guard/types.ts | 12 + platforms/market/src/app/http/index.ts | 2 + .../market/src/app/http/map-error-body.ts | 45 ++++ platforms/market/src/app/http/types.ts | 10 + .../market/src/app/navigation/constants.ts | 2 + platforms/market/src/app/navigation/index.ts | 2 + .../market/src/app/navigation/navigation.ts | 40 +++ platforms/market/src/app/session/constants.ts | 11 + platforms/market/src/app/session/index.ts | 1 + .../src/app/session/refresh-in-proxy.ts | 77 ++++++ platforms/market/src/app/session/server.ts | 4 + platforms/market/src/app/session/types.ts | 7 + platforms/market/src/env/env.ts | 18 ++ platforms/market/src/env/index.ts | 2 + platforms/market/src/env/types.ts | 12 + .../market/src/features/auth/actions/.gitkeep | 0 .../features/auth/actions/login/actions.ts | 20 ++ .../src/features/auth/actions/login/index.ts | 1 + .../features/auth/actions/logout/actions.ts | 13 + .../src/features/auth/actions/logout/index.ts | 1 + .../auth/actions/register-creator/actions.ts | 23 ++ .../auth/actions/register-creator/index.ts | 1 + .../auth/actions/register-investor/actions.ts | 23 ++ .../auth/actions/register-investor/index.ts | 1 + .../market/src/features/auth/caches/.gitkeep | 0 .../market/src/features/auth/caches/server.ts | 3 + .../features/auth/caches/session-account.ts | 22 ++ .../market/src/features/auth/constants.ts | 6 + .../src/features/auth/entities/.gitkeep | 0 .../src/features/auth/entities/user/index.ts | 1 + .../src/features/auth/entities/user/types.ts | 17 ++ platforms/market/src/features/auth/http.ts | 3 + platforms/market/src/features/auth/index.ts | 22 ++ .../src/features/auth/repositories/.gitkeep | 0 .../auth/repositories/account/account.ts | 28 +++ .../auth/repositories/account/constants.ts | 6 + .../auth/repositories/account/index.ts | 3 + .../auth/repositories/account/mappers.ts | 28 +++ .../auth/repositories/account/types.ts | 24 ++ .../features/auth/repositories/auth/auth.ts | 131 ++++++++++ .../auth/repositories/auth/constants.ts | 16 ++ .../features/auth/repositories/auth/index.ts | 12 + .../auth/repositories/auth/mappers.ts | 79 ++++++ .../features/auth/repositories/auth/types.ts | 60 +++++ platforms/market/src/features/auth/types.ts | 12 + .../src/features/channel/caches/.gitkeep | 0 .../features/channel/caches/public-creator.ts | 12 + .../features/channel/caches/public-tiers.ts | 12 + .../src/features/channel/caches/server.ts | 4 + .../src/features/channel/entities/.gitkeep | 0 .../channel/entities/public-creator/index.ts | 1 + .../channel/entities/public-creator/types.ts | 17 ++ .../channel/entities/public-tier/index.ts | 1 + .../channel/entities/public-tier/types.ts | 44 ++++ platforms/market/src/features/channel/http.ts | 3 + .../market/src/features/channel/index.ts | 8 + .../features/channel/repositories/.gitkeep | 0 .../channel/repositories/channel/channel.ts | 40 +++ .../channel/repositories/channel/constants.ts | 15 ++ .../channel/repositories/channel/index.ts | 8 + .../channel/repositories/channel/mappers.ts | 54 ++++ .../channel/repositories/channel/types.ts | 60 +++++ .../src/features/checkout/caches/.gitkeep | 0 .../checkout/caches/checkout-screen.ts | 15 ++ .../src/features/checkout/caches/server.ts | 3 + .../src/features/checkout/entities/.gitkeep | 0 .../entities/checkout-result/index.ts | 5 + .../entities/checkout-result/types.ts | 76 ++++++ .../checkout/entities/subscription/index.ts | 1 + .../checkout/entities/subscription/types.ts | 22 ++ .../market/src/features/checkout/http.ts | 3 + .../market/src/features/checkout/index.ts | 20 ++ .../features/checkout/repositories/.gitkeep | 0 .../repositories/checkout/checkout.ts | 90 +++++++ .../repositories/checkout/constants.ts | 18 ++ .../checkout/repositories/checkout/index.ts | 16 ++ .../checkout/repositories/checkout/mappers.ts | 157 ++++++++++++ .../checkout/repositories/checkout/types.ts | 208 +++++++++++++++ .../market/src/features/feed/caches/.gitkeep | 0 .../market/src/features/feed/caches/feed.ts | 15 ++ .../market/src/features/feed/caches/server.ts | 3 + platforms/market/src/features/feed/http.ts | 3 + platforms/market/src/features/feed/index.ts | 7 + .../src/features/feed/repositories/.gitkeep | 0 .../feed/repositories/feed/constants.ts | 12 + .../features/feed/repositories/feed/feed.ts | 22 ++ .../features/feed/repositories/feed/index.ts | 3 + .../feed/repositories/feed/mappers.ts | 11 + .../features/feed/repositories/feed/types.ts | 16 ++ .../src/features/finance/caches/.gitkeep | 0 .../finance/caches/creator-payments.ts | 11 + .../src/features/finance/caches/server.ts | 3 + platforms/market/src/features/finance/http.ts | 3 + .../market/src/features/finance/index.ts | 5 + .../features/finance/repositories/.gitkeep | 0 .../repositories/creator-payment/constants.ts | 6 + .../creator-payment/creator-payment.ts | 23 ++ .../repositories/creator-payment/index.ts | 3 + .../repositories/creator-payment/mappers.ts | 20 ++ .../repositories/creator-payment/types.ts | 30 +++ .../src/features/follow/caches/.gitkeep | 0 .../features/follow/caches/follow-status.ts | 15 ++ .../src/features/follow/caches/server.ts | 3 + .../src/features/follow/entities/.gitkeep | 0 .../follow/entities/follow-status/index.ts | 1 + .../follow/entities/follow-status/types.ts | 12 + platforms/market/src/features/follow/http.ts | 3 + platforms/market/src/features/follow/index.ts | 6 + .../src/features/follow/repositories/.gitkeep | 0 .../follow/repositories/follow/constants.ts | 13 + .../follow/repositories/follow/follow.ts | 43 ++++ .../follow/repositories/follow/index.ts | 7 + .../follow/repositories/follow/mappers.ts | 24 ++ .../follow/repositories/follow/types.ts | 26 ++ .../src/features/notification/caches/.gitkeep | 0 .../src/features/notification/caches/inbox.ts | 11 + .../features/notification/caches/server.ts | 4 + .../notification/caches/unread-count.ts | 11 + .../src/features/notification/constants.ts | 2 + .../features/notification/entities/.gitkeep | 0 .../entities/notification/index.ts | 5 + .../entities/notification/types.ts | 39 +++ .../market/src/features/notification/http.ts | 3 + .../market/src/features/notification/index.ts | 12 + .../notification/repositories/.gitkeep | 0 .../repositories/notification/constants.ts | 12 + .../repositories/notification/index.ts | 8 + .../repositories/notification/mappers.ts | 38 +++ .../repositories/notification/notification.ts | 58 +++++ .../repositories/notification/types.ts | 47 ++++ .../src/features/overview/caches/.gitkeep | 0 .../overview/caches/creator-dashboard.ts | 12 + .../src/features/overview/caches/server.ts | 3 + .../src/features/overview/entities/.gitkeep | 0 .../overview/entities/creator-tier/index.ts | 1 + .../overview/entities/creator-tier/types.ts | 9 + .../market/src/features/overview/http.ts | 3 + .../market/src/features/overview/index.ts | 9 + .../features/overview/repositories/.gitkeep | 0 .../creator-dashboard/constants.ts | 6 + .../creator-dashboard/creator-dashboard.ts | 20 ++ .../repositories/creator-dashboard/index.ts | 7 + .../repositories/creator-dashboard/mappers.ts | 28 +++ .../repositories/creator-dashboard/types.ts | 45 ++++ .../market/src/features/post/caches/.gitkeep | 0 .../src/features/post/caches/creator-posts.ts | 20 ++ .../market/src/features/post/caches/post.ts | 14 ++ .../market/src/features/post/caches/server.ts | 4 + .../src/features/post/entities/.gitkeep | 0 .../src/features/post/entities/file/index.ts | 1 + .../src/features/post/entities/file/types.ts | 23 ++ .../src/features/post/entities/post/index.ts | 15 ++ .../src/features/post/entities/post/types.ts | 93 +++++++ platforms/market/src/features/post/http.ts | 8 + platforms/market/src/features/post/index.ts | 42 ++++ .../src/features/post/repositories/.gitkeep | 0 .../post/repositories/file/constants.ts | 14 ++ .../features/post/repositories/file/file.ts | 54 ++++ .../features/post/repositories/file/index.ts | 9 + .../post/repositories/file/mappers.ts | 41 +++ .../features/post/repositories/file/types.ts | 51 ++++ .../post/repositories/post/constants.ts | 22 ++ .../features/post/repositories/post/index.ts | 20 ++ .../post/repositories/post/mappers.ts | 137 ++++++++++ .../features/post/repositories/post/post.ts | 86 +++++++ .../features/post/repositories/post/types.ts | 182 ++++++++++++++ .../src/features/prediction/caches/.gitkeep | 0 .../prediction/caches/prediction-stats.ts | 12 + .../src/features/prediction/caches/server.ts | 3 + .../src/features/prediction/entities/.gitkeep | 0 .../entities/prediction-stats/index.ts | 1 + .../entities/prediction-stats/types.ts | 23 ++ .../market/src/features/prediction/http.ts | 3 + .../market/src/features/prediction/index.ts | 9 + .../features/prediction/repositories/.gitkeep | 0 .../repositories/prediction/constants.ts | 11 + .../repositories/prediction/index.ts | 3 + .../repositories/prediction/mappers.ts | 29 +++ .../repositories/prediction/prediction.ts | 42 ++++ .../repositories/prediction/types.ts | 32 +++ .../src/features/pricing/caches/.gitkeep | 0 .../features/pricing/caches/pricing-form.ts | 14 ++ .../src/features/pricing/caches/server.ts | 3 + .../src/features/pricing/entities/.gitkeep | 0 .../pricing/entities/pricing-tier/index.ts | 6 + .../pricing/entities/pricing-tier/types.ts | 62 +++++ platforms/market/src/features/pricing/http.ts | 3 + .../market/src/features/pricing/index.ts | 14 ++ .../features/pricing/repositories/.gitkeep | 0 .../pricing/repositories/pricing/constants.ts | 36 +++ .../pricing/repositories/pricing/index.ts | 15 ++ .../pricing/repositories/pricing/mappers.ts | 130 ++++++++++ .../pricing/repositories/pricing/pricing.ts | 82 ++++++ .../pricing/repositories/pricing/types.ts | 196 +++++++++++++++ .../src/features/profile/caches/.gitkeep | 0 .../src/features/profile/caches/my-profile.ts | 14 ++ .../src/features/profile/caches/server.ts | 3 + .../market/src/features/profile/constants.ts | 36 +++ .../src/features/profile/entities/.gitkeep | 0 .../profile/entities/creator-profile/index.ts | 7 + .../profile/entities/creator-profile/types.ts | 64 +++++ platforms/market/src/features/profile/http.ts | 3 + .../market/src/features/profile/index.ts | 14 ++ .../features/profile/repositories/.gitkeep | 0 .../profile/repositories/profile/constants.ts | 12 + .../profile/repositories/profile/index.ts | 9 + .../profile/repositories/profile/mappers.ts | 43 ++++ .../profile/repositories/profile/profile.ts | 63 +++++ .../profile/repositories/profile/types.ts | 61 +++++ .../src/features/subscription/caches/.gitkeep | 0 .../features/subscription/caches/server.ts | 4 + .../caches/subscription-dashboard.ts | 12 + .../caches/subscription-detail.ts | 12 + .../features/subscription/entities/.gitkeep | 0 .../entities/subscription/index.ts | 7 + .../entities/subscription/types.ts | 69 +++++ .../market/src/features/subscription/http.ts | 3 + .../market/src/features/subscription/index.ts | 18 ++ .../subscription/repositories/.gitkeep | 0 .../repositories/subscription/constants.ts | 23 ++ .../repositories/subscription/index.ts | 16 ++ .../repositories/subscription/mappers.ts | 118 +++++++++ .../repositories/subscription/subscription.ts | 127 ++++++++++ .../repositories/subscription/types.ts | 166 ++++++++++++ .../src/features/transaction/caches/.gitkeep | 0 .../transaction/caches/payment-detail.ts | 15 ++ .../src/features/transaction/caches/server.ts | 4 + .../caches/transactions-first-page.ts | 15 ++ .../features/transaction/entities/.gitkeep | 0 .../transaction/entities/payment/index.ts | 6 + .../transaction/entities/payment/types.ts | 101 ++++++++ .../market/src/features/transaction/http.ts | 3 + .../market/src/features/transaction/index.ts | 17 ++ .../transaction/repositories/.gitkeep | 0 .../repositories/transaction/constants.ts | 16 ++ .../repositories/transaction/index.ts | 11 + .../repositories/transaction/mappers.ts | 80 ++++++ .../repositories/transaction/transaction.ts | 44 ++++ .../repositories/transaction/types.ts | 97 +++++++ platforms/market/src/index.ts | 238 +++++++++++++++++- platforms/market/src/server.ts | 43 ++++ .../market/src/shared/constants/.gitkeep | 0 .../market/src/shared/constants/index.ts | 72 ++++++ .../market/src/shared/locales/fa/.gitkeep | 0 .../market/src/shared/locales/fa/common.json | 18 ++ .../market/src/shared/locales/fa/errors.json | 54 ++++ platforms/market/src/shared/locales/index.ts | 8 + .../market/src/shared/locales/resources.ts | 18 ++ platforms/market/src/shared/locales/types.ts | 9 + platforms/market/src/shared/utils/.gitkeep | 0 platforms/market/src/shared/utils/api-url.ts | 12 + platforms/market/src/shared/utils/index.ts | 3 + platforms/market/src/shared/utils/mobile.ts | 12 + .../src/shared/utils/rename-field-errors.ts | 19 ++ platforms/market/tsconfig.lib.json | 10 +- 290 files changed, 6345 insertions(+), 7 deletions(-) delete mode 100644 platforms/market/src/app/app-shell/.gitkeep create mode 100644 platforms/market/src/app/app-shell/AppShell.tsx create mode 100644 platforms/market/src/app/app-shell/components/NetworkBoundary.tsx create mode 100644 platforms/market/src/app/app-shell/constants.ts create mode 100644 platforms/market/src/app/app-shell/hooks/use-session-events.ts create mode 100644 platforms/market/src/app/app-shell/index.ts create mode 100644 platforms/market/src/app/app-shell/types.ts delete mode 100644 platforms/market/src/app/error-boundaries/error-fallback/.gitkeep create mode 100644 platforms/market/src/app/error-boundaries/error-fallback/ErrorFallback.tsx create mode 100644 platforms/market/src/app/error-boundaries/error-fallback/index.ts create mode 100644 platforms/market/src/app/error-boundaries/error-fallback/types.ts create mode 100644 platforms/market/src/app/error-boundaries/error-fallback/utils.ts create mode 100644 platforms/market/src/app/error-boundaries/index.ts delete mode 100644 platforms/market/src/app/error-boundaries/part-boundary/.gitkeep create mode 100644 platforms/market/src/app/error-boundaries/part-boundary/PartBoundary.tsx create mode 100644 platforms/market/src/app/error-boundaries/part-boundary/index.ts create mode 100644 platforms/market/src/app/error-boundaries/part-boundary/types.ts delete mode 100644 platforms/market/src/app/error-boundaries/read-on-server/.gitkeep create mode 100644 platforms/market/src/app/error-boundaries/read-on-server/read-on-server.ts create mode 100644 platforms/market/src/app/error-boundaries/read-on-server/server.ts create mode 100644 platforms/market/src/app/error-boundaries/read-on-server/types.ts create mode 100644 platforms/market/src/app/error-boundaries/server.ts delete mode 100644 platforms/market/src/app/error-boundaries/status-empty-state/.gitkeep create mode 100644 platforms/market/src/app/error-boundaries/status-empty-state/StatusEmptyState.tsx create mode 100644 platforms/market/src/app/error-boundaries/status-empty-state/constants.ts create mode 100644 platforms/market/src/app/error-boundaries/status-empty-state/index.ts create mode 100644 platforms/market/src/app/error-boundaries/status-empty-state/types.ts delete mode 100644 platforms/market/src/app/guards/auth-guard/.gitkeep create mode 100644 platforms/market/src/app/guards/auth-guard/auth-guard.ts create mode 100644 platforms/market/src/app/guards/auth-guard/server.ts create mode 100644 platforms/market/src/app/guards/auth-guard/types.ts delete mode 100644 platforms/market/src/app/guards/role-guard/.gitkeep create mode 100644 platforms/market/src/app/guards/role-guard/role-guard.ts create mode 100644 platforms/market/src/app/guards/role-guard/server.ts create mode 100644 platforms/market/src/app/guards/role-guard/types.ts create mode 100644 platforms/market/src/app/http/index.ts create mode 100644 platforms/market/src/app/http/map-error-body.ts create mode 100644 platforms/market/src/app/http/types.ts create mode 100644 platforms/market/src/app/navigation/constants.ts create mode 100644 platforms/market/src/app/navigation/index.ts create mode 100644 platforms/market/src/app/navigation/navigation.ts create mode 100644 platforms/market/src/app/session/constants.ts create mode 100644 platforms/market/src/app/session/index.ts create mode 100644 platforms/market/src/app/session/refresh-in-proxy.ts create mode 100644 platforms/market/src/app/session/server.ts create mode 100644 platforms/market/src/app/session/types.ts create mode 100644 platforms/market/src/env/env.ts create mode 100644 platforms/market/src/env/index.ts create mode 100644 platforms/market/src/env/types.ts delete mode 100644 platforms/market/src/features/auth/actions/.gitkeep create mode 100644 platforms/market/src/features/auth/actions/login/actions.ts create mode 100644 platforms/market/src/features/auth/actions/login/index.ts create mode 100644 platforms/market/src/features/auth/actions/logout/actions.ts create mode 100644 platforms/market/src/features/auth/actions/logout/index.ts create mode 100644 platforms/market/src/features/auth/actions/register-creator/actions.ts create mode 100644 platforms/market/src/features/auth/actions/register-creator/index.ts create mode 100644 platforms/market/src/features/auth/actions/register-investor/actions.ts create mode 100644 platforms/market/src/features/auth/actions/register-investor/index.ts delete mode 100644 platforms/market/src/features/auth/caches/.gitkeep create mode 100644 platforms/market/src/features/auth/caches/server.ts create mode 100644 platforms/market/src/features/auth/caches/session-account.ts create mode 100644 platforms/market/src/features/auth/constants.ts delete mode 100644 platforms/market/src/features/auth/entities/.gitkeep create mode 100644 platforms/market/src/features/auth/entities/user/index.ts create mode 100644 platforms/market/src/features/auth/entities/user/types.ts create mode 100644 platforms/market/src/features/auth/http.ts create mode 100644 platforms/market/src/features/auth/index.ts delete mode 100644 platforms/market/src/features/auth/repositories/.gitkeep create mode 100644 platforms/market/src/features/auth/repositories/account/account.ts create mode 100644 platforms/market/src/features/auth/repositories/account/constants.ts create mode 100644 platforms/market/src/features/auth/repositories/account/index.ts create mode 100644 platforms/market/src/features/auth/repositories/account/mappers.ts create mode 100644 platforms/market/src/features/auth/repositories/account/types.ts create mode 100644 platforms/market/src/features/auth/repositories/auth/auth.ts create mode 100644 platforms/market/src/features/auth/repositories/auth/constants.ts create mode 100644 platforms/market/src/features/auth/repositories/auth/index.ts create mode 100644 platforms/market/src/features/auth/repositories/auth/mappers.ts create mode 100644 platforms/market/src/features/auth/repositories/auth/types.ts create mode 100644 platforms/market/src/features/auth/types.ts delete mode 100644 platforms/market/src/features/channel/caches/.gitkeep create mode 100644 platforms/market/src/features/channel/caches/public-creator.ts create mode 100644 platforms/market/src/features/channel/caches/public-tiers.ts create mode 100644 platforms/market/src/features/channel/caches/server.ts delete mode 100644 platforms/market/src/features/channel/entities/.gitkeep create mode 100644 platforms/market/src/features/channel/entities/public-creator/index.ts create mode 100644 platforms/market/src/features/channel/entities/public-creator/types.ts create mode 100644 platforms/market/src/features/channel/entities/public-tier/index.ts create mode 100644 platforms/market/src/features/channel/entities/public-tier/types.ts create mode 100644 platforms/market/src/features/channel/http.ts create mode 100644 platforms/market/src/features/channel/index.ts delete mode 100644 platforms/market/src/features/channel/repositories/.gitkeep create mode 100644 platforms/market/src/features/channel/repositories/channel/channel.ts create mode 100644 platforms/market/src/features/channel/repositories/channel/constants.ts create mode 100644 platforms/market/src/features/channel/repositories/channel/index.ts create mode 100644 platforms/market/src/features/channel/repositories/channel/mappers.ts create mode 100644 platforms/market/src/features/channel/repositories/channel/types.ts delete mode 100644 platforms/market/src/features/checkout/caches/.gitkeep create mode 100644 platforms/market/src/features/checkout/caches/checkout-screen.ts create mode 100644 platforms/market/src/features/checkout/caches/server.ts delete mode 100644 platforms/market/src/features/checkout/entities/.gitkeep create mode 100644 platforms/market/src/features/checkout/entities/checkout-result/index.ts create mode 100644 platforms/market/src/features/checkout/entities/checkout-result/types.ts create mode 100644 platforms/market/src/features/checkout/entities/subscription/index.ts create mode 100644 platforms/market/src/features/checkout/entities/subscription/types.ts create mode 100644 platforms/market/src/features/checkout/http.ts create mode 100644 platforms/market/src/features/checkout/index.ts delete mode 100644 platforms/market/src/features/checkout/repositories/.gitkeep create mode 100644 platforms/market/src/features/checkout/repositories/checkout/checkout.ts create mode 100644 platforms/market/src/features/checkout/repositories/checkout/constants.ts create mode 100644 platforms/market/src/features/checkout/repositories/checkout/index.ts create mode 100644 platforms/market/src/features/checkout/repositories/checkout/mappers.ts create mode 100644 platforms/market/src/features/checkout/repositories/checkout/types.ts delete mode 100644 platforms/market/src/features/feed/caches/.gitkeep create mode 100644 platforms/market/src/features/feed/caches/feed.ts create mode 100644 platforms/market/src/features/feed/caches/server.ts create mode 100644 platforms/market/src/features/feed/http.ts create mode 100644 platforms/market/src/features/feed/index.ts delete mode 100644 platforms/market/src/features/feed/repositories/.gitkeep create mode 100644 platforms/market/src/features/feed/repositories/feed/constants.ts create mode 100644 platforms/market/src/features/feed/repositories/feed/feed.ts create mode 100644 platforms/market/src/features/feed/repositories/feed/index.ts create mode 100644 platforms/market/src/features/feed/repositories/feed/mappers.ts create mode 100644 platforms/market/src/features/feed/repositories/feed/types.ts delete mode 100644 platforms/market/src/features/finance/caches/.gitkeep create mode 100644 platforms/market/src/features/finance/caches/creator-payments.ts create mode 100644 platforms/market/src/features/finance/caches/server.ts create mode 100644 platforms/market/src/features/finance/http.ts create mode 100644 platforms/market/src/features/finance/index.ts delete mode 100644 platforms/market/src/features/finance/repositories/.gitkeep create mode 100644 platforms/market/src/features/finance/repositories/creator-payment/constants.ts create mode 100644 platforms/market/src/features/finance/repositories/creator-payment/creator-payment.ts create mode 100644 platforms/market/src/features/finance/repositories/creator-payment/index.ts create mode 100644 platforms/market/src/features/finance/repositories/creator-payment/mappers.ts create mode 100644 platforms/market/src/features/finance/repositories/creator-payment/types.ts delete mode 100644 platforms/market/src/features/follow/caches/.gitkeep create mode 100644 platforms/market/src/features/follow/caches/follow-status.ts create mode 100644 platforms/market/src/features/follow/caches/server.ts delete mode 100644 platforms/market/src/features/follow/entities/.gitkeep create mode 100644 platforms/market/src/features/follow/entities/follow-status/index.ts create mode 100644 platforms/market/src/features/follow/entities/follow-status/types.ts create mode 100644 platforms/market/src/features/follow/http.ts create mode 100644 platforms/market/src/features/follow/index.ts delete mode 100644 platforms/market/src/features/follow/repositories/.gitkeep create mode 100644 platforms/market/src/features/follow/repositories/follow/constants.ts create mode 100644 platforms/market/src/features/follow/repositories/follow/follow.ts create mode 100644 platforms/market/src/features/follow/repositories/follow/index.ts create mode 100644 platforms/market/src/features/follow/repositories/follow/mappers.ts create mode 100644 platforms/market/src/features/follow/repositories/follow/types.ts delete mode 100644 platforms/market/src/features/notification/caches/.gitkeep create mode 100644 platforms/market/src/features/notification/caches/inbox.ts create mode 100644 platforms/market/src/features/notification/caches/server.ts create mode 100644 platforms/market/src/features/notification/caches/unread-count.ts create mode 100644 platforms/market/src/features/notification/constants.ts delete mode 100644 platforms/market/src/features/notification/entities/.gitkeep create mode 100644 platforms/market/src/features/notification/entities/notification/index.ts create mode 100644 platforms/market/src/features/notification/entities/notification/types.ts create mode 100644 platforms/market/src/features/notification/http.ts create mode 100644 platforms/market/src/features/notification/index.ts delete mode 100644 platforms/market/src/features/notification/repositories/.gitkeep create mode 100644 platforms/market/src/features/notification/repositories/notification/constants.ts create mode 100644 platforms/market/src/features/notification/repositories/notification/index.ts create mode 100644 platforms/market/src/features/notification/repositories/notification/mappers.ts create mode 100644 platforms/market/src/features/notification/repositories/notification/notification.ts create mode 100644 platforms/market/src/features/notification/repositories/notification/types.ts delete mode 100644 platforms/market/src/features/overview/caches/.gitkeep create mode 100644 platforms/market/src/features/overview/caches/creator-dashboard.ts create mode 100644 platforms/market/src/features/overview/caches/server.ts delete mode 100644 platforms/market/src/features/overview/entities/.gitkeep create mode 100644 platforms/market/src/features/overview/entities/creator-tier/index.ts create mode 100644 platforms/market/src/features/overview/entities/creator-tier/types.ts create mode 100644 platforms/market/src/features/overview/http.ts create mode 100644 platforms/market/src/features/overview/index.ts delete mode 100644 platforms/market/src/features/overview/repositories/.gitkeep create mode 100644 platforms/market/src/features/overview/repositories/creator-dashboard/constants.ts create mode 100644 platforms/market/src/features/overview/repositories/creator-dashboard/creator-dashboard.ts create mode 100644 platforms/market/src/features/overview/repositories/creator-dashboard/index.ts create mode 100644 platforms/market/src/features/overview/repositories/creator-dashboard/mappers.ts create mode 100644 platforms/market/src/features/overview/repositories/creator-dashboard/types.ts delete mode 100644 platforms/market/src/features/post/caches/.gitkeep create mode 100644 platforms/market/src/features/post/caches/creator-posts.ts create mode 100644 platforms/market/src/features/post/caches/post.ts create mode 100644 platforms/market/src/features/post/caches/server.ts delete mode 100644 platforms/market/src/features/post/entities/.gitkeep create mode 100644 platforms/market/src/features/post/entities/file/index.ts create mode 100644 platforms/market/src/features/post/entities/file/types.ts create mode 100644 platforms/market/src/features/post/entities/post/index.ts create mode 100644 platforms/market/src/features/post/entities/post/types.ts create mode 100644 platforms/market/src/features/post/http.ts create mode 100644 platforms/market/src/features/post/index.ts delete mode 100644 platforms/market/src/features/post/repositories/.gitkeep create mode 100644 platforms/market/src/features/post/repositories/file/constants.ts create mode 100644 platforms/market/src/features/post/repositories/file/file.ts create mode 100644 platforms/market/src/features/post/repositories/file/index.ts create mode 100644 platforms/market/src/features/post/repositories/file/mappers.ts create mode 100644 platforms/market/src/features/post/repositories/file/types.ts create mode 100644 platforms/market/src/features/post/repositories/post/constants.ts create mode 100644 platforms/market/src/features/post/repositories/post/index.ts create mode 100644 platforms/market/src/features/post/repositories/post/mappers.ts create mode 100644 platforms/market/src/features/post/repositories/post/post.ts create mode 100644 platforms/market/src/features/post/repositories/post/types.ts delete mode 100644 platforms/market/src/features/prediction/caches/.gitkeep create mode 100644 platforms/market/src/features/prediction/caches/prediction-stats.ts create mode 100644 platforms/market/src/features/prediction/caches/server.ts delete mode 100644 platforms/market/src/features/prediction/entities/.gitkeep create mode 100644 platforms/market/src/features/prediction/entities/prediction-stats/index.ts create mode 100644 platforms/market/src/features/prediction/entities/prediction-stats/types.ts create mode 100644 platforms/market/src/features/prediction/http.ts create mode 100644 platforms/market/src/features/prediction/index.ts delete mode 100644 platforms/market/src/features/prediction/repositories/.gitkeep create mode 100644 platforms/market/src/features/prediction/repositories/prediction/constants.ts create mode 100644 platforms/market/src/features/prediction/repositories/prediction/index.ts create mode 100644 platforms/market/src/features/prediction/repositories/prediction/mappers.ts create mode 100644 platforms/market/src/features/prediction/repositories/prediction/prediction.ts create mode 100644 platforms/market/src/features/prediction/repositories/prediction/types.ts delete mode 100644 platforms/market/src/features/pricing/caches/.gitkeep create mode 100644 platforms/market/src/features/pricing/caches/pricing-form.ts create mode 100644 platforms/market/src/features/pricing/caches/server.ts delete mode 100644 platforms/market/src/features/pricing/entities/.gitkeep create mode 100644 platforms/market/src/features/pricing/entities/pricing-tier/index.ts create mode 100644 platforms/market/src/features/pricing/entities/pricing-tier/types.ts create mode 100644 platforms/market/src/features/pricing/http.ts create mode 100644 platforms/market/src/features/pricing/index.ts delete mode 100644 platforms/market/src/features/pricing/repositories/.gitkeep create mode 100644 platforms/market/src/features/pricing/repositories/pricing/constants.ts create mode 100644 platforms/market/src/features/pricing/repositories/pricing/index.ts create mode 100644 platforms/market/src/features/pricing/repositories/pricing/mappers.ts create mode 100644 platforms/market/src/features/pricing/repositories/pricing/pricing.ts create mode 100644 platforms/market/src/features/pricing/repositories/pricing/types.ts delete mode 100644 platforms/market/src/features/profile/caches/.gitkeep create mode 100644 platforms/market/src/features/profile/caches/my-profile.ts create mode 100644 platforms/market/src/features/profile/caches/server.ts create mode 100644 platforms/market/src/features/profile/constants.ts delete mode 100644 platforms/market/src/features/profile/entities/.gitkeep create mode 100644 platforms/market/src/features/profile/entities/creator-profile/index.ts create mode 100644 platforms/market/src/features/profile/entities/creator-profile/types.ts create mode 100644 platforms/market/src/features/profile/http.ts create mode 100644 platforms/market/src/features/profile/index.ts delete mode 100644 platforms/market/src/features/profile/repositories/.gitkeep create mode 100644 platforms/market/src/features/profile/repositories/profile/constants.ts create mode 100644 platforms/market/src/features/profile/repositories/profile/index.ts create mode 100644 platforms/market/src/features/profile/repositories/profile/mappers.ts create mode 100644 platforms/market/src/features/profile/repositories/profile/profile.ts create mode 100644 platforms/market/src/features/profile/repositories/profile/types.ts delete mode 100644 platforms/market/src/features/subscription/caches/.gitkeep create mode 100644 platforms/market/src/features/subscription/caches/server.ts create mode 100644 platforms/market/src/features/subscription/caches/subscription-dashboard.ts create mode 100644 platforms/market/src/features/subscription/caches/subscription-detail.ts delete mode 100644 platforms/market/src/features/subscription/entities/.gitkeep create mode 100644 platforms/market/src/features/subscription/entities/subscription/index.ts create mode 100644 platforms/market/src/features/subscription/entities/subscription/types.ts create mode 100644 platforms/market/src/features/subscription/http.ts create mode 100644 platforms/market/src/features/subscription/index.ts delete mode 100644 platforms/market/src/features/subscription/repositories/.gitkeep create mode 100644 platforms/market/src/features/subscription/repositories/subscription/constants.ts create mode 100644 platforms/market/src/features/subscription/repositories/subscription/index.ts create mode 100644 platforms/market/src/features/subscription/repositories/subscription/mappers.ts create mode 100644 platforms/market/src/features/subscription/repositories/subscription/subscription.ts create mode 100644 platforms/market/src/features/subscription/repositories/subscription/types.ts delete mode 100644 platforms/market/src/features/transaction/caches/.gitkeep create mode 100644 platforms/market/src/features/transaction/caches/payment-detail.ts create mode 100644 platforms/market/src/features/transaction/caches/server.ts create mode 100644 platforms/market/src/features/transaction/caches/transactions-first-page.ts delete mode 100644 platforms/market/src/features/transaction/entities/.gitkeep create mode 100644 platforms/market/src/features/transaction/entities/payment/index.ts create mode 100644 platforms/market/src/features/transaction/entities/payment/types.ts create mode 100644 platforms/market/src/features/transaction/http.ts create mode 100644 platforms/market/src/features/transaction/index.ts delete mode 100644 platforms/market/src/features/transaction/repositories/.gitkeep create mode 100644 platforms/market/src/features/transaction/repositories/transaction/constants.ts create mode 100644 platforms/market/src/features/transaction/repositories/transaction/index.ts create mode 100644 platforms/market/src/features/transaction/repositories/transaction/mappers.ts create mode 100644 platforms/market/src/features/transaction/repositories/transaction/transaction.ts create mode 100644 platforms/market/src/features/transaction/repositories/transaction/types.ts delete mode 100644 platforms/market/src/shared/constants/.gitkeep create mode 100644 platforms/market/src/shared/constants/index.ts delete mode 100644 platforms/market/src/shared/locales/fa/.gitkeep create mode 100644 platforms/market/src/shared/locales/fa/common.json create mode 100644 platforms/market/src/shared/locales/fa/errors.json create mode 100644 platforms/market/src/shared/locales/index.ts create mode 100644 platforms/market/src/shared/locales/resources.ts create mode 100644 platforms/market/src/shared/locales/types.ts delete mode 100644 platforms/market/src/shared/utils/.gitkeep create mode 100644 platforms/market/src/shared/utils/api-url.ts create mode 100644 platforms/market/src/shared/utils/index.ts create mode 100644 platforms/market/src/shared/utils/mobile.ts create mode 100644 platforms/market/src/shared/utils/rename-field-errors.ts diff --git a/platforms/market/package.json b/platforms/market/package.json index 0adb994..ae48a33 100644 --- a/platforms/market/package.json +++ b/platforms/market/package.json @@ -12,6 +12,7 @@ "./features/*/caches": "./src/features/*/caches/server.ts", "./features/*": "./src/features/*/index.ts", "./stores/*": "./src/stores/*/index.ts", + "./env": "./src/env/index.ts", "./shared/locales/*": "./src/shared/locales/*", "./shared/*": "./src/shared/*/index.ts", "./package.json": "./package.json" diff --git a/platforms/market/src/app/app-shell/.gitkeep b/platforms/market/src/app/app-shell/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/app/app-shell/AppShell.tsx b/platforms/market/src/app/app-shell/AppShell.tsx new file mode 100644 index 0000000..2722652 --- /dev/null +++ b/platforms/market/src/app/app-shell/AppShell.tsx @@ -0,0 +1,28 @@ +'use client'; + +import { Toaster } from '@lumina/island/molecules/toast'; +import { QueryClientProvider } from '@tanstack/react-query'; +import { I18nextProvider } from 'react-i18next'; + +import { NetworkBoundary } from './components/NetworkBoundary'; +import { useSessionEvents } from './hooks/use-session-events'; +import type { AppShellProps } from './types'; + +/** + * The provider shell shared by bull and bear: the query client, i18n, the connection bar, the + * one toast region, and the reactions to sign-in and sign-out. The app's root client component renders it after running the client + * bootstrap. + */ +export function AppShell({ queryClient, i18n, children }: AppShellProps) { + useSessionEvents(queryClient); + + return ( + + + + {children} + + + + ); +} diff --git a/platforms/market/src/app/app-shell/components/NetworkBoundary.tsx b/platforms/market/src/app/app-shell/components/NetworkBoundary.tsx new file mode 100644 index 0000000..407b99d --- /dev/null +++ b/platforms/market/src/app/app-shell/components/NetworkBoundary.tsx @@ -0,0 +1,72 @@ +'use client'; + +import { useOnline } from '@lumina/island/hooks/use-online'; +import { NetworkStatus } from '@lumina/island/molecules/network-status'; +import { useQueryClient } from '@tanstack/react-query'; +import { useRouter } from 'next/navigation'; +import { + startTransition, + useCallback, + useEffect, + useRef, + useState, +} from 'react'; +import { useTranslation } from 'react-i18next'; + +import { NETWORK_COPY, ONLINE_NOTICE_MS } from '../constants'; +import type { ReconnectPhase } from '../types'; + +/** + * The network boundary: owns the connection bar for the whole app. Offline, it says so and the + * page stays readable. When the device comes back it refreshes the route and the queries once + * («در حال اتصال دوباره…»), then confirms for 3 seconds. It never re-submits anything. + */ +export function NetworkBoundary() { + const { t } = useTranslation(); + const router = useRouter(); + const queryClient = useQueryClient(); + const isOnline = useOnline(); + const [phase, setPhase] = useState('idle'); + const noticeTimer = useRef>(undefined); + + // Started by the `online` event or the retry button. + const reconnect = useCallback(() => { + clearTimeout(noticeTimer.current); + setPhase('reconnecting'); + startTransition(() => router.refresh()); + void queryClient.invalidateQueries().finally(() => { + setPhase('online'); + noticeTimer.current = setTimeout( + () => setPhase('idle'), + ONLINE_NOTICE_MS, + ); + }); + }, [router, queryClient]); + + useEffect(() => { + window.addEventListener('online', reconnect); + return () => window.removeEventListener('online', reconnect); + }, [reconnect]); + + useEffect(() => () => clearTimeout(noticeTimer.current), []); + + const status = isOnline ? (phase === 'idle' ? null : phase) : 'offline'; + if (!status) return null; + const copy = NETWORK_COPY[status]; + + return ( + { + if (navigator.onLine) reconnect(); + } + : undefined + } + retryLabel={t('network.retry')} + /> + ); +} diff --git a/platforms/market/src/app/app-shell/constants.ts b/platforms/market/src/app/app-shell/constants.ts new file mode 100644 index 0000000..423fc5c --- /dev/null +++ b/platforms/market/src/app/app-shell/constants.ts @@ -0,0 +1,21 @@ +import type { NetworkState } from '@lumina/island/molecules/network-status'; + +/** How long «دوباره آنلاین شدید» stays before the bar leaves. */ +export const ONLINE_NOTICE_MS = 3000; + +/** Each bar's copy under `common:network`. */ +export const NETWORK_COPY = { + offline: { + title: 'network.offline', + description: 'network.offline-description', + }, + reconnecting: { title: 'network.reconnecting', description: undefined }, + online: { + title: 'network.online', + description: 'network.online-description', + }, + slow: { title: 'network.slow', description: 'network.slow-description' }, +} as const satisfies Record< + NetworkState, + { title: string; description: string | undefined } +>; diff --git a/platforms/market/src/app/app-shell/hooks/use-session-events.ts b/platforms/market/src/app/app-shell/hooks/use-session-events.ts new file mode 100644 index 0000000..138bd82 --- /dev/null +++ b/platforms/market/src/app/app-shell/hooks/use-session-events.ts @@ -0,0 +1,28 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; +import type { QueryClient } from '@tanstack/react-query'; +import { useRouter } from 'next/navigation'; +import { useEffect } from 'react'; + +import { AUTH_EVENTS } from '../../../features/auth'; + +/** + * Keeps the page in step with the session. Signing in or up re-renders the server components for + * the new account; signing out, or a refresh that failed, drops every cached query (they belonged + * to the old account) and re-renders as a guest. + */ +export function useSessionEvents(queryClient: QueryClient): void { + const router = useRouter(); + + useEffect(() => { + const refresh = () => router.refresh(); + const unsubscribers = [ + eventEmitter.on(AUTH_EVENTS.login, refresh), + eventEmitter.on(AUTH_EVENTS.register, refresh), + eventEmitter.on(AUTH_EVENTS.logout, () => { + queryClient.clear(); + router.refresh(); + }), + ]; + return () => unsubscribers.forEach((unsubscribe) => unsubscribe()); + }, [router, queryClient]); +} diff --git a/platforms/market/src/app/app-shell/index.ts b/platforms/market/src/app/app-shell/index.ts new file mode 100644 index 0000000..237554b --- /dev/null +++ b/platforms/market/src/app/app-shell/index.ts @@ -0,0 +1,2 @@ +export { AppShell } from './AppShell'; +export type { AppShellProps } from './types'; diff --git a/platforms/market/src/app/app-shell/types.ts b/platforms/market/src/app/app-shell/types.ts new file mode 100644 index 0000000..4dd041b --- /dev/null +++ b/platforms/market/src/app/app-shell/types.ts @@ -0,0 +1,14 @@ +import type { QueryClient } from '@tanstack/react-query'; +import type { i18n } from 'i18next'; +import type { ReactNode } from 'react'; + +export type AppShellProps = { + /** The app's query client: one per server request, one shared in the browser. */ + queryClient: QueryClient; + /** The app's i18n instance, initialised with the platform's resources. */ + i18n: i18n; + children: ReactNode; +}; + +/** The connection bar's moment after the device comes back: refreshing, then confirmed. */ +export type ReconnectPhase = 'idle' | 'reconnecting' | 'online'; diff --git a/platforms/market/src/app/error-boundaries/error-fallback/.gitkeep b/platforms/market/src/app/error-boundaries/error-fallback/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/app/error-boundaries/error-fallback/ErrorFallback.tsx b/platforms/market/src/app/error-boundaries/error-fallback/ErrorFallback.tsx new file mode 100644 index 0000000..64f44ef --- /dev/null +++ b/platforms/market/src/app/error-boundaries/error-fallback/ErrorFallback.tsx @@ -0,0 +1,67 @@ +'use client'; + +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { + classifyError, + describeError, + handleError, +} from '@lumina/libs/error-handler'; +import { useEffect, useRef } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { StatusEmptyState } from '../status-empty-state'; +import type { ErrorFallbackProps } from './types'; +import { errorKind } from './utils'; + +/** + * What every boundary renders. A silent error (aborted, or a 401 already redirecting) shows + * nothing; a 404 or 403 read shows its empty state; anything else shows ErrorState with Try again + * for a network cause or Reload page for a bug, and the reference ID. It reports the error once, + * and a page or app fallback moves focus to its heading. + */ +export function ErrorFallback({ + error, + size, + name, + onRetry, +}: ErrorFallbackProps) { + const { t } = useTranslation('errors'); + const headingRef = useRef(null); + const { read, cause } = classifyError(error); + + useEffect(() => { + handleError(error, { where: size, name }); + if (size !== 'part') headingRef.current?.focus(); + }, [error, size, name]); + + if (read === 'silent') return null; + if (read !== 'boundary') { + return ( + + ); + } + + const kind = errorKind(error); + // Only the reference ID is read here, so no copy goes through a translator. + const { referenceId } = describeError(error, (key) => key); + const isBug = cause === 'logic'; + + return ( + window.location.reload() : onRetry} + retryLabel={isBug ? t('fallback.reload') : t('fallback.retry')} + digest={referenceId} + digestLabel={t('fallback.reference')} + /> + ); +} diff --git a/platforms/market/src/app/error-boundaries/error-fallback/index.ts b/platforms/market/src/app/error-boundaries/error-fallback/index.ts new file mode 100644 index 0000000..392bc0c --- /dev/null +++ b/platforms/market/src/app/error-boundaries/error-fallback/index.ts @@ -0,0 +1,6 @@ +export { ErrorFallback } from './ErrorFallback'; +export type { + ErrorFallbackProps, + ErrorFallbackSize, + FallbackKind, +} from './types'; diff --git a/platforms/market/src/app/error-boundaries/error-fallback/types.ts b/platforms/market/src/app/error-boundaries/error-fallback/types.ts new file mode 100644 index 0000000..7e018ea --- /dev/null +++ b/platforms/market/src/app/error-boundaries/error-fallback/types.ts @@ -0,0 +1,19 @@ +import type { ErrorKind } from '@lumina/island/molecules/error-state'; + +/** The ErrorState kinds a boundary can show; each has its copy under `errors:fallback`. */ +export type FallbackKind = Exclude< + ErrorKind, + 'not-found' | 'forbidden' | 'session' +>; + +export type ErrorFallbackSize = 'app' | 'page' | 'part'; + +export type ErrorFallbackProps = { + error: unknown; + /** app: global-error. page: a route group's error.tsx. part: a PartBoundary. */ + size: ErrorFallbackSize; + /** The part or route, for the error report; never personal data. */ + name?: string; + /** Try again: resets the failed queries, then the boundary. */ + onRetry?: () => void; +}; diff --git a/platforms/market/src/app/error-boundaries/error-fallback/utils.ts b/platforms/market/src/app/error-boundaries/error-fallback/utils.ts new file mode 100644 index 0000000..1fca558 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/error-fallback/utils.ts @@ -0,0 +1,20 @@ +import { isHttpError } from '@lumina/libs/http'; + +import type { FallbackKind } from './types'; + +/** + * Which ErrorState a boundary shows, as the DS classifies it: offline when the device is, the + * HTTP lib's network and timeout codes, server for a 5xx or a server error's digest, else error. + * 404, 403 and 401 never get here: they are empty states or silent. + */ +export function errorKind(error: unknown): FallbackKind { + if (typeof navigator !== 'undefined' && !navigator.onLine) return 'offline'; + if (isHttpError(error)) { + if (error.code === 'NETWORK_ERROR') return 'network'; + if (error.code === 'TIMEOUT') return 'timeout'; + return error.status >= 500 ? 'server' : 'error'; + } + return typeof error === 'object' && error !== null && 'digest' in error + ? 'server' + : 'error'; +} diff --git a/platforms/market/src/app/error-boundaries/index.ts b/platforms/market/src/app/error-boundaries/index.ts new file mode 100644 index 0000000..e1ae6f7 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/index.ts @@ -0,0 +1,13 @@ +export { ErrorFallback } from './error-fallback'; +export type { + ErrorFallbackProps, + ErrorFallbackSize, + FallbackKind, +} from './error-fallback'; +export { PartBoundary } from './part-boundary'; +export type { PartBoundaryProps } from './part-boundary'; +export { StatusEmptyState } from './status-empty-state'; +export type { + StatusEmptyStateProps, + StatusVariant, +} from './status-empty-state'; diff --git a/platforms/market/src/app/error-boundaries/part-boundary/.gitkeep b/platforms/market/src/app/error-boundaries/part-boundary/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/app/error-boundaries/part-boundary/PartBoundary.tsx b/platforms/market/src/app/error-boundaries/part-boundary/PartBoundary.tsx new file mode 100644 index 0000000..0c95125 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/part-boundary/PartBoundary.tsx @@ -0,0 +1,38 @@ +'use client'; + +import { useQueryErrorResetBoundary } from '@tanstack/react-query'; +import { catchError } from 'next/error'; +import type { ErrorInfo } from 'next/error'; + +import { ErrorFallback } from '../error-fallback'; +import type { PartBoundaryProps } from './types'; + +function PartFallback( + { name }: PartBoundaryProps, + { error, retry, reset }: ErrorInfo, +) { + const queryErrors = useQueryErrorResetBoundary(); + // A digest means the part failed on the server: retry renders it there again. + const isServerError = + typeof error === 'object' && error !== null && 'digest' in error; + + return ( + { + queryErrors.reset(); + if (isServerError) retry(); + else reset(); + }} + /> + ); +} + +/** + * The part-size boundary (EB-S) around every part that loads on its own, outside its Suspense, so + * the fallback replaces the skeleton and the part together. Next.js's catchError lets notFound() + * and redirect() through and clears itself on navigation. + */ +export const PartBoundary = catchError(PartFallback); diff --git a/platforms/market/src/app/error-boundaries/part-boundary/index.ts b/platforms/market/src/app/error-boundaries/part-boundary/index.ts new file mode 100644 index 0000000..45b6f75 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/part-boundary/index.ts @@ -0,0 +1,2 @@ +export { PartBoundary } from './PartBoundary'; +export type { PartBoundaryProps } from './types'; diff --git a/platforms/market/src/app/error-boundaries/part-boundary/types.ts b/platforms/market/src/app/error-boundaries/part-boundary/types.ts new file mode 100644 index 0000000..15b640e --- /dev/null +++ b/platforms/market/src/app/error-boundaries/part-boundary/types.ts @@ -0,0 +1,4 @@ +export type PartBoundaryProps = { + /** The part, for the error report: «creator-stats», «feed». Never personal data. */ + name: string; +}; diff --git a/platforms/market/src/app/error-boundaries/read-on-server/.gitkeep b/platforms/market/src/app/error-boundaries/read-on-server/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/app/error-boundaries/read-on-server/read-on-server.ts b/platforms/market/src/app/error-boundaries/read-on-server/read-on-server.ts new file mode 100644 index 0000000..a399c06 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/read-on-server/read-on-server.ts @@ -0,0 +1,32 @@ +import 'server-only'; + +import { classifyError } from '@lumina/libs/error-handler'; +import { isHttpError } from '@lumina/libs/http'; +import { redirect } from 'next/navigation'; + +import { loginRoute } from '../../navigation'; +import type { ReadOnServerOptions, ServerRead } from './types'; + +/** + * Every server read of a page or a server part goes through it. A Server Component error reaches + * the browser with only its digest, so the expected answers are classified here: 404 and 410 are + * `not-found`, 403 `no-access`, 401 redirects to login with `returnTo`, and the rest is rethrown + * to the nearest boundary. + */ +export async function readOnServer( + read: () => Promise, + { returnTo }: ReadOnServerOptions = {}, +): Promise> { + try { + return { status: 'ok', data: await read() }; + } catch (error) { + const outcome = classifyError(error).read; + if (outcome === 'not-found' || outcome === 'no-access') { + return { status: outcome }; + } + if (returnTo && isHttpError(error) && error.status === 401) { + redirect(loginRoute(returnTo)); + } + throw error; + } +} diff --git a/platforms/market/src/app/error-boundaries/read-on-server/server.ts b/platforms/market/src/app/error-boundaries/read-on-server/server.ts new file mode 100644 index 0000000..9ae150f --- /dev/null +++ b/platforms/market/src/app/error-boundaries/read-on-server/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { readOnServer } from './read-on-server'; +export type { ReadOnServerOptions, ServerRead } from './types'; diff --git a/platforms/market/src/app/error-boundaries/read-on-server/types.ts b/platforms/market/src/app/error-boundaries/read-on-server/types.ts new file mode 100644 index 0000000..1003949 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/read-on-server/types.ts @@ -0,0 +1,9 @@ +/** A server read's outcome: its data, or the empty state a 404, 410 or 403 answer shows. */ +export type ServerRead = + | { status: 'ok'; data: T } + | { status: 'not-found' | 'no-access' }; + +export type ReadOnServerOptions = { + /** The page's own path: a 401 redirects to login and comes back here. */ + returnTo?: string; +}; diff --git a/platforms/market/src/app/error-boundaries/server.ts b/platforms/market/src/app/error-boundaries/server.ts new file mode 100644 index 0000000..47c9f42 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { readOnServer } from './read-on-server/server'; +export type { ReadOnServerOptions, ServerRead } from './read-on-server/server'; diff --git a/platforms/market/src/app/error-boundaries/status-empty-state/.gitkeep b/platforms/market/src/app/error-boundaries/status-empty-state/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/app/error-boundaries/status-empty-state/StatusEmptyState.tsx b/platforms/market/src/app/error-boundaries/status-empty-state/StatusEmptyState.tsx new file mode 100644 index 0000000..62bc831 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/status-empty-state/StatusEmptyState.tsx @@ -0,0 +1,37 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../navigation'; +import { STATUS_KINDS } from './constants'; +import type { StatusEmptyStateProps } from './types'; + +/** + * What a read that answered 404, 410 or 403 shows: not an alarm, no retry. At page size it adds the + * way home. A client component, so server pages and parts can render it too. + */ +export function StatusEmptyState({ + variant, + size, + headingRef, +}: StatusEmptyStateProps) { + const { t } = useTranslation('errors'); + + return ( + + {size === 'page' && ( + + )} + + ); +} diff --git a/platforms/market/src/app/error-boundaries/status-empty-state/constants.ts b/platforms/market/src/app/error-boundaries/status-empty-state/constants.ts new file mode 100644 index 0000000..b376cff --- /dev/null +++ b/platforms/market/src/app/error-boundaries/status-empty-state/constants.ts @@ -0,0 +1,9 @@ +import type { ErrorKind } from '@lumina/island/molecules/error-state'; + +import type { StatusVariant } from './types'; + +/** The DS draws a missing or forbidden read as ErrorState's calm not-found and forbidden kinds. */ +export const STATUS_KINDS: Record = { + 'not-found': 'not-found', + 'no-access': 'forbidden', +}; diff --git a/platforms/market/src/app/error-boundaries/status-empty-state/index.ts b/platforms/market/src/app/error-boundaries/status-empty-state/index.ts new file mode 100644 index 0000000..d793732 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/status-empty-state/index.ts @@ -0,0 +1,2 @@ +export { StatusEmptyState } from './StatusEmptyState'; +export type { StatusEmptyStateProps, StatusVariant } from './types'; diff --git a/platforms/market/src/app/error-boundaries/status-empty-state/types.ts b/platforms/market/src/app/error-boundaries/status-empty-state/types.ts new file mode 100644 index 0000000..3cd9c37 --- /dev/null +++ b/platforms/market/src/app/error-boundaries/status-empty-state/types.ts @@ -0,0 +1,12 @@ +import type { Ref } from 'react'; + +export type StatusVariant = 'not-found' | 'no-access'; + +export type StatusEmptyStateProps = { + /** not-found: a 404 or 410 read. no-access: a 403 read. */ + variant: StatusVariant; + /** page: a route, with a way home. part: one part of a page. */ + size: 'page' | 'part'; + /** A page fallback focuses its heading. */ + headingRef?: Ref; +}; diff --git a/platforms/market/src/app/guards/auth-guard/.gitkeep b/platforms/market/src/app/guards/auth-guard/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/app/guards/auth-guard/auth-guard.ts b/platforms/market/src/app/guards/auth-guard/auth-guard.ts new file mode 100644 index 0000000..6a9e8da --- /dev/null +++ b/platforms/market/src/app/guards/auth-guard/auth-guard.ts @@ -0,0 +1,27 @@ +import 'server-only'; + +import { redirect } from 'next/navigation'; + +import { getSessionAccount } from '../../../features/auth/caches/server'; +import type { AccountPayload } from '../../../features/auth'; +import { loginRoute, ROUTES } from '../../navigation'; +import type { RequireAccountOptions } from './types'; + +/** + * For pages that need a signed-in visitor: the account, or a redirect to login that comes back to + * `returnTo`. proxy.ts has already refreshed an expired session, so `null` here means a guest. + */ +export async function requireAccount({ + returnTo, +}: RequireAccountOptions): Promise { + const account = await getSessionAccount(); + if (!account) redirect(loginRoute(returnTo)); + return account; +} + +/** For login and registration: a signed-in visitor goes straight to `to` (home by default). */ +export async function redirectIfSignedIn( + to: string = ROUTES.home, +): Promise { + if (await getSessionAccount()) redirect(to); +} diff --git a/platforms/market/src/app/guards/auth-guard/server.ts b/platforms/market/src/app/guards/auth-guard/server.ts new file mode 100644 index 0000000..c35a4fb --- /dev/null +++ b/platforms/market/src/app/guards/auth-guard/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { redirectIfSignedIn, requireAccount } from './auth-guard'; +export type { RequireAccountOptions } from './types'; diff --git a/platforms/market/src/app/guards/auth-guard/types.ts b/platforms/market/src/app/guards/auth-guard/types.ts new file mode 100644 index 0000000..7dc8ac4 --- /dev/null +++ b/platforms/market/src/app/guards/auth-guard/types.ts @@ -0,0 +1,4 @@ +export type RequireAccountOptions = { + /** The page's own path: login sends the visitor back here afterwards. */ + returnTo: string; +}; diff --git a/platforms/market/src/app/guards/role-guard/.gitkeep b/platforms/market/src/app/guards/role-guard/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/app/guards/role-guard/role-guard.ts b/platforms/market/src/app/guards/role-guard/role-guard.ts new file mode 100644 index 0000000..0b436f7 --- /dev/null +++ b/platforms/market/src/app/guards/role-guard/role-guard.ts @@ -0,0 +1,19 @@ +import 'server-only'; + +import { requireAccount } from '../auth-guard/server'; +import type { RequireRoleOptions, RoleCheck } from './types'; + +/** + * For pages of one role (the creator dashboard, the investor's subscriptions). A guest is sent to + * login; the other role gets `no-access`, which the page renders as its page-size + * StatusEmptyState (a 403, never a redirect loop). + */ +export async function requireRole({ + role, + returnTo, +}: RequireRoleOptions): Promise { + const account = await requireAccount({ returnTo }); + return account.role === role + ? { status: 'ok', account } + : { status: 'no-access' }; +} diff --git a/platforms/market/src/app/guards/role-guard/server.ts b/platforms/market/src/app/guards/role-guard/server.ts new file mode 100644 index 0000000..efc868f --- /dev/null +++ b/platforms/market/src/app/guards/role-guard/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { requireRole } from './role-guard'; +export type { RequireRoleOptions, RoleCheck } from './types'; diff --git a/platforms/market/src/app/guards/role-guard/types.ts b/platforms/market/src/app/guards/role-guard/types.ts new file mode 100644 index 0000000..799760a --- /dev/null +++ b/platforms/market/src/app/guards/role-guard/types.ts @@ -0,0 +1,12 @@ +import type { AccountPayload, UserRole } from '../../../features/auth'; + +export type RequireRoleOptions = { + role: UserRole; + /** The page's own path, for the login redirect. */ + returnTo: string; +}; + +/** The account when it has the role, `no-access` when it is the other role. */ +export type RoleCheck = + | { status: 'ok'; account: AccountPayload } + | { status: 'no-access' }; diff --git a/platforms/market/src/app/http/index.ts b/platforms/market/src/app/http/index.ts new file mode 100644 index 0000000..82647c2 --- /dev/null +++ b/platforms/market/src/app/http/index.ts @@ -0,0 +1,2 @@ +export { mapApiErrorBody } from './map-error-body'; +export type { ApiErrorEnvelope } from './types'; diff --git a/platforms/market/src/app/http/map-error-body.ts b/platforms/market/src/app/http/map-error-body.ts new file mode 100644 index 0000000..5ae43ee --- /dev/null +++ b/platforms/market/src/app/http/map-error-body.ts @@ -0,0 +1,45 @@ +import type { HttpErrorShape } from '@lumina/libs/http'; + +import type { ApiErrorEnvelope } from './types'; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** `{ field: ['first message', …] }` → `{ field: 'first message' }`. */ +function toFieldErrors( + value: Record, +): Record | undefined { + const entries = Object.entries(value).flatMap(([field, messages]) => { + const message: unknown = Array.isArray(messages) ? messages[0] : messages; + return typeof message === 'string' ? [[field, message] as const] : []; + }); + return entries.length > 0 ? Object.fromEntries(entries) : undefined; +} + +/** + * Adapts the gateway's error contract to `HttpError`. Two shapes arrive: + * - the envelope `{ statusCode, error, message, details }`, where `message` is the server's text + * (already translated), a list, or a field map; + * - a bare field map `{ phone_number: ['…'] }` from DTO validation. + * Field names stay the server's; each repository's mappers rename them to its `*Args` names. + * `details` (a changed price, a frozen unfollow) passes through for the action that handles it. + */ +export function mapApiErrorBody(body: unknown): Partial { + if (!isRecord(body)) return {}; + if (typeof body.statusCode !== 'number') { + return { fieldErrors: toFieldErrors(body) }; + } + const { message, details } = body as ApiErrorEnvelope; + const retryAfter = details?.retryAfterSeconds; + return { + message: Array.isArray(message) + ? message[0] + : typeof message === 'string' + ? message + : undefined, + fieldErrors: isRecord(message) ? toFieldErrors(message) : undefined, + retryAfter: typeof retryAfter === 'number' ? retryAfter : undefined, + details: isRecord(details) ? details : undefined, + }; +} diff --git a/platforms/market/src/app/http/types.ts b/platforms/market/src/app/http/types.ts new file mode 100644 index 0000000..54f8b43 --- /dev/null +++ b/platforms/market/src/app/http/types.ts @@ -0,0 +1,10 @@ +/** + * The gateway's error envelope (`RpcToHttpFilter`). `message` is a string, or a field → messages + * map for validation errors; OTP blocks add `details.retryAfterSeconds`. + */ +export type ApiErrorEnvelope = { + statusCode: number; + error?: string; + message?: string | string[] | Record; + details?: { retryAfterSeconds?: number; [key: string]: unknown } | null; +}; diff --git a/platforms/market/src/app/navigation/constants.ts b/platforms/market/src/app/navigation/constants.ts new file mode 100644 index 0000000..0780c4e --- /dev/null +++ b/platforms/market/src/app/navigation/constants.ts @@ -0,0 +1,2 @@ +/** The public channel URL prefix; next.config rewrites `/@username` onto `channels/[username]`. */ +export const CHANNEL_PREFIX = '/@'; diff --git a/platforms/market/src/app/navigation/index.ts b/platforms/market/src/app/navigation/index.ts new file mode 100644 index 0000000..6603490 --- /dev/null +++ b/platforms/market/src/app/navigation/index.ts @@ -0,0 +1,2 @@ +export { CHANNEL_PREFIX } from './constants'; +export { loginRoute, ROUTES } from './navigation'; diff --git a/platforms/market/src/app/navigation/navigation.ts b/platforms/market/src/app/navigation/navigation.ts new file mode 100644 index 0000000..8444a30 --- /dev/null +++ b/platforms/market/src/app/navigation/navigation.ts @@ -0,0 +1,40 @@ +import { CHANNEL_PREFIX } from './constants'; + +const channel = (username: string) => + `${CHANNEL_PREFIX}${encodeURIComponent(username)}`; + +/** Every route path in bull and bear, which share one URL tree. Build links only from here. */ +export const ROUTES = { + home: '/', + login: '/auth/login', + account: '/account', + channel, + post: (username: string, id: string) => + `${channel(username)}/posts/${encodeURIComponent(id)}`, + trackRecord: (username: string) => `${channel(username)}/track-record`, + checkout: (username: string) => `/checkout/${encodeURIComponent(username)}`, + paymentReturn: '/payment/return', + composePost: '/compose/post', + composePrediction: '/compose/prediction', + dashboard: { + subscriptions: '/dashboard/subscriptions', + transactions: '/dashboard/transactions', + following: '/dashboard/following', + pricing: '/dashboard/pricing', + ledger: '/dashboard/finance/ledger', + sheba: '/dashboard/finance/sheba', + }, + onboarding: { + creatorIdentity: '/onboarding/creator-identity', + creatorProfile: '/onboarding/creator-profile', + investorProfile: '/onboarding/investor-profile', + }, + terms: '/terms/subscription', +} as const; + +/** `/auth/login?redirect=…`: auth returns to the page that asked for it. */ +export function loginRoute(returnTo?: string): string { + return returnTo + ? `${ROUTES.login}?redirect=${encodeURIComponent(returnTo)}` + : ROUTES.login; +} diff --git a/platforms/market/src/app/session/constants.ts b/platforms/market/src/app/session/constants.ts new file mode 100644 index 0000000..3ef4861 --- /dev/null +++ b/platforms/market/src/app/session/constants.ts @@ -0,0 +1,11 @@ +/** The gateway's HttpOnly session cookies; JavaScript never reads their values. */ +export const SESSION_COOKIES = { + access: 'access_token', + refresh: 'refresh_token', +} as const; + +/** Rotates the session from the refresh cookie; relative to the API base URL (`…/v1`). */ +export const SESSION_REFRESH_ENDPOINT = '/auth/refresh'; + +/** A refresh before rendering must never hold the page up for long. */ +export const PROXY_REFRESH_TIMEOUT_MS = 3000; diff --git a/platforms/market/src/app/session/index.ts b/platforms/market/src/app/session/index.ts new file mode 100644 index 0000000..d39010f --- /dev/null +++ b/platforms/market/src/app/session/index.ts @@ -0,0 +1 @@ +export { SESSION_COOKIES, SESSION_REFRESH_ENDPOINT } from './constants'; diff --git a/platforms/market/src/app/session/refresh-in-proxy.ts b/platforms/market/src/app/session/refresh-in-proxy.ts new file mode 100644 index 0000000..123b3fc --- /dev/null +++ b/platforms/market/src/app/session/refresh-in-proxy.ts @@ -0,0 +1,77 @@ +import { createHttpClient } from '@lumina/libs/http'; +import { NextResponse } from 'next/server'; +import type { NextRequest } from 'next/server'; + +import { + PROXY_REFRESH_TIMEOUT_MS, + SESSION_COOKIES, + SESSION_REFRESH_ENDPOINT, +} from './constants'; +import type { ProxySessionOptions, RefreshResponseDto } from './types'; + +/** `name=value; Path=/; …` → [name, value]. */ +function cookiePair(setCookie: string): [string, string] | undefined { + const pair = setCookie.split(';', 1)[0] ?? ''; + const index = pair.indexOf('='); + return index > 0 ? [pair.slice(0, index), pair.slice(index + 1)] : undefined; +} + +/** Copies the gateway's Set-Cookie headers to the browser's response. */ +function forwardCookies( + response: NextResponse, + setCookies: string[], +): NextResponse { + for (const setCookie of setCookies) + response.headers.append('set-cookie', setCookie); + return response; +} + +/** + * Refreshes an expired session before the page renders, so server components never render a + * signed-in visitor as a guest. It runs only when the access cookie is gone (it lives 15 minutes) + * and the refresh cookie is still there. The new cookies go to the browser, and into this + * request's Cookie header so this render's API calls already use them. + * + * A superseded refresh (a tab refreshed at the same moment) changes nothing. On any failure the + * page renders as a guest and the cookies stay as they are: the browser's next API call refreshes + * against the gateway itself, which clears a dead session's cookies on its own domain. Never + * throws: rendering goes on either way. + */ +export async function refreshSessionInProxy( + request: NextRequest, + { apiUrl }: ProxySessionOptions, +): Promise { + const refreshToken = request.cookies.get(SESSION_COOKIES.refresh)?.value; + if (!refreshToken || request.cookies.has(SESSION_COOKIES.access)) { + return NextResponse.next(); + } + + // A client of its own: the proxy runs before any bootstrap has configured the root client. + const client = createHttpClient({ + baseUrl: apiUrl, + retry: false, + timeout: PROXY_REFRESH_TIMEOUT_MS, + }); + try { + const response = await client.request({ + method: 'POST', + url: SESSION_REFRESH_ENDPOINT, + headers: { + cookie: `${SESSION_COOKIES.refresh}=${refreshToken}`, + 'user-agent': request.headers.get('user-agent') ?? '', + }, + skipRefresh: true, + }); + const setCookies = response.headers.getSetCookie(); + for (const setCookie of setCookies) { + const pair = cookiePair(setCookie); + if (pair) request.cookies.set(pair[0], pair[1]); + } + return forwardCookies( + NextResponse.next({ request: { headers: request.headers } }), + setCookies, + ); + } catch { + return NextResponse.next(); + } +} diff --git a/platforms/market/src/app/session/server.ts b/platforms/market/src/app/session/server.ts new file mode 100644 index 0000000..01ac205 --- /dev/null +++ b/platforms/market/src/app/session/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { refreshSessionInProxy } from './refresh-in-proxy'; +export type { ProxySessionOptions } from './types'; diff --git a/platforms/market/src/app/session/types.ts b/platforms/market/src/app/session/types.ts new file mode 100644 index 0000000..797778b --- /dev/null +++ b/platforms/market/src/app/session/types.ts @@ -0,0 +1,7 @@ +export type ProxySessionOptions = { + /** The API base URL as the server reaches it, with the version: `http://gateway:3000/v1`. */ + apiUrl: string; +}; + +/** `POST /auth/refresh` body: the user after a rotation, or `superseded` when another refresh won. */ +export type RefreshResponseDto = { superseded: true } | { user: unknown }; diff --git a/platforms/market/src/env/env.ts b/platforms/market/src/env/env.ts new file mode 100644 index 0000000..9efdaed --- /dev/null +++ b/platforms/market/src/env/env.ts @@ -0,0 +1,18 @@ +import type { MarketEnv } from './types'; + +let marketEnv: MarketEnv | undefined; + +/** Called by each app bootstrap, on the server and in the browser. Idempotent. */ +export function setEnv(env: MarketEnv): void { + marketEnv = env; +} + +/** Read inside functions, never at module top level: bootstrap may not have run yet. */ +export function getEnv(): Readonly { + if (!marketEnv) { + throw new Error( + 'market env is not set. The app bootstrap must call setEnv from @lumina/market/env first.', + ); + } + return marketEnv; +} diff --git a/platforms/market/src/env/index.ts b/platforms/market/src/env/index.ts new file mode 100644 index 0000000..8f74c33 --- /dev/null +++ b/platforms/market/src/env/index.ts @@ -0,0 +1,2 @@ +export { getEnv, setEnv } from './env'; +export type { MarketEnv } from './types'; diff --git a/platforms/market/src/env/types.ts b/platforms/market/src/env/types.ts new file mode 100644 index 0000000..9533cca --- /dev/null +++ b/platforms/market/src/env/types.ts @@ -0,0 +1,12 @@ +/** The platform's own settings, named for what they are, not for the variables behind them. */ +export type MarketEnv = { + /** + * The API's public origin (`https://api.lumina.ir`), for what the browser loads straight from it: + * post media, avatars and uploads (`/files/*` sits outside `/v1`). + */ + apiOrigin: string; + /** Support chat handles and hours: config values, never hard-coded in a component. */ + baleHandle: string; + telegramHandle: string; + supportHours: string; +}; diff --git a/platforms/market/src/features/auth/actions/.gitkeep b/platforms/market/src/features/auth/actions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/auth/actions/login/actions.ts b/platforms/market/src/features/auth/actions/login/actions.ts new file mode 100644 index 0000000..031382e --- /dev/null +++ b/platforms/market/src/features/auth/actions/login/actions.ts @@ -0,0 +1,20 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; +import type { SessionPayload, VerifyOtpArgs } from '../../repositories/auth'; + +/** Verifies the login code; the gateway sets the session cookies. Emits `auth.login`. */ +export async function login( + args: VerifyOtpArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const session = await authRepository.verifyLoginOtp(args); + if (emit) { + eventEmitter.emit(AUTH_EVENTS.login, { + userId: session.account.id, + role: session.account.role, + }); + } + return session; +} diff --git a/platforms/market/src/features/auth/actions/login/index.ts b/platforms/market/src/features/auth/actions/login/index.ts new file mode 100644 index 0000000..00d9ea2 --- /dev/null +++ b/platforms/market/src/features/auth/actions/login/index.ts @@ -0,0 +1 @@ +export { login } from './actions'; diff --git a/platforms/market/src/features/auth/actions/logout/actions.ts b/platforms/market/src/features/auth/actions/logout/actions.ts new file mode 100644 index 0000000..a205dc1 --- /dev/null +++ b/platforms/market/src/features/auth/actions/logout/actions.ts @@ -0,0 +1,13 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; + +/** Revokes the session and clears its cookies. Emits `auth.logout`. */ +export async function logout({ + emit = true, +}: { emit?: boolean } = {}): Promise<'ok'> { + await authRepository.logout(); + if (emit) eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'signed-out' }); + return 'ok'; +} diff --git a/platforms/market/src/features/auth/actions/logout/index.ts b/platforms/market/src/features/auth/actions/logout/index.ts new file mode 100644 index 0000000..0284a3e --- /dev/null +++ b/platforms/market/src/features/auth/actions/logout/index.ts @@ -0,0 +1 @@ +export { logout } from './actions'; diff --git a/platforms/market/src/features/auth/actions/register-creator/actions.ts b/platforms/market/src/features/auth/actions/register-creator/actions.ts new file mode 100644 index 0000000..cbe4f93 --- /dev/null +++ b/platforms/market/src/features/auth/actions/register-creator/actions.ts @@ -0,0 +1,23 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; +import type { + CreatorRegisteredPayload, + RegisterCreatorArgs, +} from '../../repositories/auth'; + +/** Creates a creator account with lite KYC and signs it in. Emits `auth.register`. */ +export async function registerCreator( + args: RegisterCreatorArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const registration = await authRepository.registerCreator(args); + if (emit) { + eventEmitter.emit(AUTH_EVENTS.register, { + userId: registration.account.id, + role: registration.account.role, + }); + } + return registration; +} diff --git a/platforms/market/src/features/auth/actions/register-creator/index.ts b/platforms/market/src/features/auth/actions/register-creator/index.ts new file mode 100644 index 0000000..63f7371 --- /dev/null +++ b/platforms/market/src/features/auth/actions/register-creator/index.ts @@ -0,0 +1 @@ +export { registerCreator } from './actions'; diff --git a/platforms/market/src/features/auth/actions/register-investor/actions.ts b/platforms/market/src/features/auth/actions/register-investor/actions.ts new file mode 100644 index 0000000..0f430d4 --- /dev/null +++ b/platforms/market/src/features/auth/actions/register-investor/actions.ts @@ -0,0 +1,23 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; +import type { + RegisterInvestorArgs, + SessionPayload, +} from '../../repositories/auth'; + +/** Creates an investor account and signs it in. Emits `auth.register`. */ +export async function registerInvestor( + args: RegisterInvestorArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const session = await authRepository.registerInvestor(args); + if (emit) { + eventEmitter.emit(AUTH_EVENTS.register, { + userId: session.account.id, + role: session.account.role, + }); + } + return session; +} diff --git a/platforms/market/src/features/auth/actions/register-investor/index.ts b/platforms/market/src/features/auth/actions/register-investor/index.ts new file mode 100644 index 0000000..f76f2e6 --- /dev/null +++ b/platforms/market/src/features/auth/actions/register-investor/index.ts @@ -0,0 +1 @@ +export { registerInvestor } from './actions'; diff --git a/platforms/market/src/features/auth/caches/.gitkeep b/platforms/market/src/features/auth/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/auth/caches/server.ts b/platforms/market/src/features/auth/caches/server.ts new file mode 100644 index 0000000..8e01f97 --- /dev/null +++ b/platforms/market/src/features/auth/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getSessionAccount } from './session-account'; diff --git a/platforms/market/src/features/auth/caches/session-account.ts b/platforms/market/src/features/auth/caches/session-account.ts new file mode 100644 index 0000000..755b736 --- /dev/null +++ b/platforms/market/src/features/auth/caches/session-account.ts @@ -0,0 +1,22 @@ +import 'server-only'; + +import { isHttpError } from '@lumina/libs/http'; +import { cache } from 'react'; + +import { accountRepository } from '../repositories/account'; +import type { AccountPayload } from '../repositories/account'; + +/** + * The signed-in account for this request, or `null` for a guest. One request per render however + * many server components ask; the cookies are forwarded by the server HTTP configuration. + */ +export const getSessionAccount = cache( + async (): Promise => { + try { + return await accountRepository.getCurrent(); + } catch (error) { + if (isHttpError(error) && error.status === 401) return null; + throw error; + } + }, +); diff --git a/platforms/market/src/features/auth/constants.ts b/platforms/market/src/features/auth/constants.ts new file mode 100644 index 0000000..f3fb1d0 --- /dev/null +++ b/platforms/market/src/features/auth/constants.ts @@ -0,0 +1,6 @@ +/** Events auth actions emit when they succeed; the AppShell reacts to them. */ +export const AUTH_EVENTS = { + login: 'auth.login', + register: 'auth.register', + logout: 'auth.logout', +} as const; diff --git a/platforms/market/src/features/auth/entities/.gitkeep b/platforms/market/src/features/auth/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/auth/entities/user/index.ts b/platforms/market/src/features/auth/entities/user/index.ts new file mode 100644 index 0000000..5cb3966 --- /dev/null +++ b/platforms/market/src/features/auth/entities/user/index.ts @@ -0,0 +1 @@ +export type { UserEntity, UserRole, UserStatus } from './types'; diff --git a/platforms/market/src/features/auth/entities/user/types.ts b/platforms/market/src/features/auth/entities/user/types.ts new file mode 100644 index 0000000..04f5f68 --- /dev/null +++ b/platforms/market/src/features/auth/entities/user/types.ts @@ -0,0 +1,17 @@ +/** The two account roles. Creators are «تحلیلگر» in every UI string, investors «سرمایه‌گذار». */ +export type UserRole = 'investor' | 'creator'; + +export type UserStatus = 'active' | 'suspended'; + +/** user-service's public projection of an account (`toPublicUser`). */ +export type UserEntity = { + id: string; + phone_number: string; + firstName?: string; + lastName?: string; + email?: string | null; + username: string; + role: UserRole; + phone_verified: boolean; + status: UserStatus; +}; diff --git a/platforms/market/src/features/auth/http.ts b/platforms/market/src/features/auth/http.ts new file mode 100644 index 0000000..28c6d44 --- /dev/null +++ b/platforms/market/src/features/auth/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const authHttp = http.extend({}); diff --git a/platforms/market/src/features/auth/index.ts b/platforms/market/src/features/auth/index.ts new file mode 100644 index 0000000..9e7c43a --- /dev/null +++ b/platforms/market/src/features/auth/index.ts @@ -0,0 +1,22 @@ +import './types'; + +export { login } from './actions/login'; +export { logout } from './actions/logout'; +export { registerCreator } from './actions/register-creator'; +export { registerInvestor } from './actions/register-investor'; +export { AUTH_EVENTS } from './constants'; +export type { UserRole, UserStatus } from './entities/user'; +export { accountKeys, accountRepository } from './repositories/account'; +export type { AccountPayload, UpdateAccountArgs } from './repositories/account'; +export { AUTH_ENDPOINTS, authRepository } from './repositories/auth'; +export type { + CreatorRegisteredPayload, + OtpSentPayload, + RegisterCreatorArgs, + RegisterInvestorArgs, + RegistrationVerifiedPayload, + SendOtpArgs, + SessionPayload, + VerifyOtpArgs, +} from './repositories/auth'; +export type { LogoutReason } from './types'; diff --git a/platforms/market/src/features/auth/repositories/.gitkeep b/platforms/market/src/features/auth/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/auth/repositories/account/account.ts b/platforms/market/src/features/auth/repositories/account/account.ts new file mode 100644 index 0000000..10947d2 --- /dev/null +++ b/platforms/market/src/features/auth/repositories/account/account.ts @@ -0,0 +1,28 @@ +import { authHttp } from '../../http'; +import { ACCOUNT_ENDPOINT } from './constants'; +import { toAccountPayload, toUpdateAccountDto } from './mappers'; +import type { + AccountPayload, + AccountResponseDto, + UpdateAccountArgs, +} from './types'; + +/** The signed-in account (`/users/profile`), any role. 401 without a session. */ +export const accountRepository = { + async getCurrent({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await authHttp.get(ACCOUNT_ENDPOINT, { + signal, + }); + return toAccountPayload(response); + }, + + async update(args: UpdateAccountArgs): Promise { + const response = await authHttp.patch( + ACCOUNT_ENDPOINT, + toUpdateAccountDto(args), + ); + return toAccountPayload(response); + }, +}; diff --git a/platforms/market/src/features/auth/repositories/account/constants.ts b/platforms/market/src/features/auth/repositories/account/constants.ts new file mode 100644 index 0000000..37c8b53 --- /dev/null +++ b/platforms/market/src/features/auth/repositories/account/constants.ts @@ -0,0 +1,6 @@ +export const ACCOUNT_ENDPOINT = '/users/profile'; + +export const accountKeys = { + all: ['auth', 'account'] as const, + current: () => [...accountKeys.all, 'current'] as const, +}; diff --git a/platforms/market/src/features/auth/repositories/account/index.ts b/platforms/market/src/features/auth/repositories/account/index.ts new file mode 100644 index 0000000..decb8d1 --- /dev/null +++ b/platforms/market/src/features/auth/repositories/account/index.ts @@ -0,0 +1,3 @@ +export { accountRepository } from './account'; +export { accountKeys } from './constants'; +export type { AccountPayload, UpdateAccountArgs } from './types'; diff --git a/platforms/market/src/features/auth/repositories/account/mappers.ts b/platforms/market/src/features/auth/repositories/account/mappers.ts new file mode 100644 index 0000000..b47ac6f --- /dev/null +++ b/platforms/market/src/features/auth/repositories/account/mappers.ts @@ -0,0 +1,28 @@ +import type { + AccountPayload, + AccountResponseDto, + UpdateAccountArgs, + UpdateAccountDto, +} from './types'; + +export function toAccountPayload(dto: AccountResponseDto): AccountPayload { + return { + id: dto.id, + phone: dto.phone_number, + firstName: dto.firstName ?? '', + lastName: dto.lastName ?? '', + email: dto.email ?? null, + username: dto.username, + role: dto.role, + phoneVerified: dto.phone_verified, + status: dto.status, + }; +} + +export function toUpdateAccountDto(args: UpdateAccountArgs): UpdateAccountDto { + return { + firstName: args.firstName?.trim(), + lastName: args.lastName?.trim(), + email: args.email?.trim().toLowerCase() || undefined, + }; +} diff --git a/platforms/market/src/features/auth/repositories/account/types.ts b/platforms/market/src/features/auth/repositories/account/types.ts new file mode 100644 index 0000000..86470de --- /dev/null +++ b/platforms/market/src/features/auth/repositories/account/types.ts @@ -0,0 +1,24 @@ +import type { UserEntity, UserRole, UserStatus } from '../../entities/user'; + +/** The signed-in account, as apps and stores use it. */ +export type AccountPayload = { + id: string; + phone: string; + firstName: string; + lastName: string; + email: string | null; + username: string; + role: UserRole; + phoneVerified: boolean; + status: UserStatus; +}; + +export type AccountResponseDto = UserEntity; + +export type UpdateAccountArgs = { + firstName?: string; + lastName?: string; + email?: string; +}; + +export type UpdateAccountDto = UpdateAccountArgs; diff --git a/platforms/market/src/features/auth/repositories/auth/auth.ts b/platforms/market/src/features/auth/repositories/auth/auth.ts new file mode 100644 index 0000000..3c35775 --- /dev/null +++ b/platforms/market/src/features/auth/repositories/auth/auth.ts @@ -0,0 +1,131 @@ +import { renameFieldErrors } from '../../../../shared/utils'; +import { authHttp } from '../../http'; +import { AUTH_ENDPOINTS, AUTH_FIELD_NAMES } from './constants'; +import { + toCreatorRegisteredPayload, + toOtpSentPayload, + toPhoneDto, + toRegisterCreatorFormData, + toRegisterInvestorDto, + toRegistrationVerifiedPayload, + toSessionPayload, + toVerifyOtpDto, +} from './mappers'; +import type { + CreatorRegisteredPayload, + CreatorRegisteredResponseDto, + OtpSentPayload, + OtpSentResponseDto, + RegisterCreatorArgs, + RegisterInvestorArgs, + RegistrationVerifiedPayload, + RegistrationVerifiedResponseDto, + SendOtpArgs, + SessionPayload, + SessionResponseDto, + VerifyOtpArgs, +} from './types'; + +/** + * Passwordless phone auth. Every request sends `skipRefresh`: these run without a session, and the + * API answers a wrong code with 400 and field errors, so a 401 here never means "refresh". A + * successful sign-in or registration sets the HttpOnly session cookies; the body is the account. + */ +async function send(request: () => Promise): Promise { + try { + return await request(); + } catch (error) { + throw renameFieldErrors(error, AUTH_FIELD_NAMES); + } +} + +export const authRepository = { + async sendRegistrationOtp(args: SendOtpArgs): Promise { + const response = await send(() => + authHttp.post( + AUTH_ENDPOINTS.sendRegistrationOtp, + toPhoneDto(args), + { skipRefresh: true }, + ), + ); + return toOtpSentPayload(response); + }, + + async verifyRegistrationOtp( + args: VerifyOtpArgs, + ): Promise { + const response = await send(() => + authHttp.post( + AUTH_ENDPOINTS.verifyRegistrationOtp, + toVerifyOtpDto(args), + { skipRefresh: true }, + ), + ); + return toRegistrationVerifiedPayload(response); + }, + + /** Registration or login code again; the server keeps its 60-second cooldown. */ + async resendOtp(args: SendOtpArgs): Promise { + const response = await send(() => + authHttp.post( + AUTH_ENDPOINTS.resendOtp, + toPhoneDto(args), + { skipRefresh: true }, + ), + ); + return toOtpSentPayload(response); + }, + + async registerInvestor(args: RegisterInvestorArgs): Promise { + const response = await send(() => + authHttp.post( + AUTH_ENDPOINTS.registerInvestor, + toRegisterInvestorDto(args), + { skipRefresh: true }, + ), + ); + return toSessionPayload(response); + }, + + async registerCreator( + args: RegisterCreatorArgs, + ): Promise { + const response = await send(() => + authHttp.upload( + AUTH_ENDPOINTS.registerCreator, + toRegisterCreatorFormData(args), + { skipRefresh: true }, + ), + ); + return toCreatorRegisteredPayload(response); + }, + + async requestLoginOtp(args: SendOtpArgs): Promise { + const response = await send(() => + authHttp.post( + AUTH_ENDPOINTS.requestLoginOtp, + toPhoneDto(args), + { skipRefresh: true }, + ), + ); + return toOtpSentPayload(response); + }, + + async verifyLoginOtp(args: VerifyOtpArgs): Promise { + const response = await send(() => + authHttp.post( + AUTH_ENDPOINTS.verifyLoginOtp, + toVerifyOtpDto(args), + { skipRefresh: true }, + ), + ); + return toSessionPayload(response); + }, + + /** Revokes the session and clears its cookies; succeeds even without one. */ + async logout(): Promise { + await authHttp.post(AUTH_ENDPOINTS.logout, undefined, { + skipRefresh: true, + }); + }, +}; diff --git a/platforms/market/src/features/auth/repositories/auth/constants.ts b/platforms/market/src/features/auth/repositories/auth/constants.ts new file mode 100644 index 0000000..1977993 --- /dev/null +++ b/platforms/market/src/features/auth/repositories/auth/constants.ts @@ -0,0 +1,16 @@ +export const AUTH_ENDPOINTS = { + sendRegistrationOtp: '/auth/send-otp', + verifyRegistrationOtp: '/auth/verify-registration-otp', + resendOtp: '/auth/resend-otp', + registerInvestor: '/auth/register/investor', + registerCreator: '/auth/register/creator', + requestLoginOtp: '/auth/login', + verifyLoginOtp: '/auth/login/verify', + logout: '/auth/logout', +} as const; + +/** Server field names → `*Args` names, so form errors land under the right field. */ +export const AUTH_FIELD_NAMES = { + phone_number: 'phone', + otp: 'code', +} as const; diff --git a/platforms/market/src/features/auth/repositories/auth/index.ts b/platforms/market/src/features/auth/repositories/auth/index.ts new file mode 100644 index 0000000..36e7781 --- /dev/null +++ b/platforms/market/src/features/auth/repositories/auth/index.ts @@ -0,0 +1,12 @@ +export { authRepository } from './auth'; +export { AUTH_ENDPOINTS } from './constants'; +export type { + CreatorRegisteredPayload, + OtpSentPayload, + RegisterCreatorArgs, + RegisterInvestorArgs, + RegistrationVerifiedPayload, + SendOtpArgs, + SessionPayload, + VerifyOtpArgs, +} from './types'; diff --git a/platforms/market/src/features/auth/repositories/auth/mappers.ts b/platforms/market/src/features/auth/repositories/auth/mappers.ts new file mode 100644 index 0000000..fa7d8f7 --- /dev/null +++ b/platforms/market/src/features/auth/repositories/auth/mappers.ts @@ -0,0 +1,79 @@ +import { toE164Mobile } from '../../../../shared/utils'; +import { toAccountPayload } from '../account/mappers'; +import type { + CreatorRegisteredPayload, + CreatorRegisteredResponseDto, + OtpSentPayload, + OtpSentResponseDto, + PhoneDto, + RegisterCreatorArgs, + RegisterInvestorArgs, + RegisterInvestorDto, + RegistrationVerifiedPayload, + RegistrationVerifiedResponseDto, + SendOtpArgs, + SessionPayload, + SessionResponseDto, + VerifyOtpArgs, + VerifyOtpDto, +} from './types'; + +export function toPhoneDto(args: SendOtpArgs): PhoneDto { + return { phone_number: toE164Mobile(args.phone) }; +} + +export function toVerifyOtpDto(args: VerifyOtpArgs): VerifyOtpDto { + return { phone_number: toE164Mobile(args.phone), otp: args.code }; +} + +export function toRegisterInvestorDto( + args: RegisterInvestorArgs, +): RegisterInvestorDto { + return { + phone_number: toE164Mobile(args.phone), + registrationToken: args.registrationToken, + username: args.username.trim(), + firstName: args.firstName.trim(), + lastName: args.lastName.trim(), + }; +} + +/** Creator registration is multipart: text fields plus the two national ID images. */ +export function toRegisterCreatorFormData(args: RegisterCreatorArgs): FormData { + const form = new FormData(); + const fields = { + ...toRegisterInvestorDto(args), + displayName: args.displayName.trim(), + nationalIdNumber: args.nationalIdNumber.trim(), + }; + for (const [name, value] of Object.entries(fields)) form.append(name, value); + form.append('nationalIdFrontImage', args.nationalIdFrontImage); + form.append('nationalIdBackImage', args.nationalIdBackImage); + return form; +} + +export function toOtpSentPayload(dto: OtpSentResponseDto): OtpSentPayload { + return { expiresInSeconds: dto.expiresInSeconds }; +} + +export function toRegistrationVerifiedPayload( + dto: RegistrationVerifiedResponseDto, +): RegistrationVerifiedPayload { + return { + registrationToken: dto.registrationToken, + expiresInSeconds: dto.expiresInSeconds, + }; +} + +export function toSessionPayload(dto: SessionResponseDto): SessionPayload { + return { account: toAccountPayload(dto.user) }; +} + +export function toCreatorRegisteredPayload( + dto: CreatorRegisteredResponseDto, +): CreatorRegisteredPayload { + return { + account: toAccountPayload(dto.account), + profileSetupRequired: dto.onboarding.profileSetupRequired, + }; +} diff --git a/platforms/market/src/features/auth/repositories/auth/types.ts b/platforms/market/src/features/auth/repositories/auth/types.ts new file mode 100644 index 0000000..b544666 --- /dev/null +++ b/platforms/market/src/features/auth/repositories/auth/types.ts @@ -0,0 +1,60 @@ +import type { UserEntity, UserRole } from '../../entities/user'; +import type { AccountPayload } from '../account'; + +// Phone numbers are typed in any digits and form; mappers send E.164. + +export type SendOtpArgs = { phone: string }; +export type PhoneDto = { phone_number: string }; +export type OtpSentResponseDto = { sent: true; expiresInSeconds: number }; +/** A code was sent; it works for this many seconds. */ +export type OtpSentPayload = { expiresInSeconds: number }; + +export type VerifyOtpArgs = { phone: string; code: string }; +export type VerifyOtpDto = { phone_number: string; otp: string }; + +export type RegistrationVerifiedResponseDto = { + verified: true; + registrationToken: string; + expiresInSeconds: number; +}; +/** The phone is proven; the token finishes registration within its lifetime (15 minutes). */ +export type RegistrationVerifiedPayload = { + registrationToken: string; + expiresInSeconds: number; +}; + +export type RegisterInvestorArgs = { + phone: string; + registrationToken: string; + username: string; + firstName: string; + lastName: string; +}; +export type RegisterInvestorDto = { + phone_number: string; + registrationToken: string; + username: string; + firstName: string; + lastName: string; +}; + +export type RegisterCreatorArgs = RegisterInvestorArgs & { + displayName: string; + nationalIdNumber: string; + nationalIdFrontImage: File; + nationalIdBackImage: File; +}; + +/** Sign-in and registration set the HttpOnly session cookies; the body carries the account. */ +export type SessionResponseDto = { user: UserEntity; userType: UserRole }; +export type SessionPayload = { account: AccountPayload }; + +export type CreatorRegisteredResponseDto = { + account: UserEntity; + onboarding: { nextStep: string; profileSetupRequired: boolean }; +}; +export type CreatorRegisteredPayload = { + account: AccountPayload; + /** The public profile (display name, markets) must be completed before publishing. */ + profileSetupRequired: boolean; +}; diff --git a/platforms/market/src/features/auth/types.ts b/platforms/market/src/features/auth/types.ts new file mode 100644 index 0000000..613288f --- /dev/null +++ b/platforms/market/src/features/auth/types.ts @@ -0,0 +1,12 @@ +import type { UserRole } from './entities/user'; + +/** Why the session ended: the user signed out, or the refresh token was dead. */ +export type LogoutReason = 'signed-out' | 'session-ended'; + +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'auth.login': { userId: string; role: UserRole }; + 'auth.register': { userId: string; role: UserRole }; + 'auth.logout': { reason: LogoutReason }; + } +} diff --git a/platforms/market/src/features/channel/caches/.gitkeep b/platforms/market/src/features/channel/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/channel/caches/public-creator.ts b/platforms/market/src/features/channel/caches/public-creator.ts new file mode 100644 index 0000000..d6f93db --- /dev/null +++ b/platforms/market/src/features/channel/caches/public-creator.ts @@ -0,0 +1,12 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { channelRepository } from '../repositories/channel'; +import type { PublicCreatorPayload } from '../repositories/channel'; + +/** An approved creator's public profile, once per render per id. 404 reaches the caller. */ +export const getPublicCreator = cache( + (creatorId: string): Promise => + channelRepository.getCreator({ creatorId }), +); diff --git a/platforms/market/src/features/channel/caches/public-tiers.ts b/platforms/market/src/features/channel/caches/public-tiers.ts new file mode 100644 index 0000000..af18b91 --- /dev/null +++ b/platforms/market/src/features/channel/caches/public-tiers.ts @@ -0,0 +1,12 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { channelRepository } from '../repositories/channel'; +import type { PublicTierPayload } from '../repositories/channel'; + +/** A creator's active tiers, once per render per id; the channel and checkout share it. */ +export const getPublicTiers = cache( + (creatorId: string): Promise => + channelRepository.listTiers({ creatorId }), +); diff --git a/platforms/market/src/features/channel/caches/server.ts b/platforms/market/src/features/channel/caches/server.ts new file mode 100644 index 0000000..0099998 --- /dev/null +++ b/platforms/market/src/features/channel/caches/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { getPublicCreator } from './public-creator'; +export { getPublicTiers } from './public-tiers'; diff --git a/platforms/market/src/features/channel/entities/.gitkeep b/platforms/market/src/features/channel/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/channel/entities/public-creator/index.ts b/platforms/market/src/features/channel/entities/public-creator/index.ts new file mode 100644 index 0000000..0b9810f --- /dev/null +++ b/platforms/market/src/features/channel/entities/public-creator/index.ts @@ -0,0 +1 @@ +export type { PublicCreatorEntity } from './types'; diff --git a/platforms/market/src/features/channel/entities/public-creator/types.ts b/platforms/market/src/features/channel/entities/public-creator/types.ts new file mode 100644 index 0000000..9512d28 --- /dev/null +++ b/platforms/market/src/features/channel/entities/public-creator/types.ts @@ -0,0 +1,17 @@ +import type { Market, TradingStyle } from '../../../profile'; + +/** + * trader-service's public projection of an approved creator (`toPublicProfile`). `id` is the + * profile id, `userId` the creator's account id. Unset fields are left out of the JSON. + */ +export type PublicCreatorEntity = { + id: string; + userId: string; + username: string; + displayName?: string; + bio?: string | null; + avatar?: string | null; + socialLinks?: { label: string; url: string; _id?: string }[]; + tradingStyle?: TradingStyle | null; + markets?: Market[]; +}; diff --git a/platforms/market/src/features/channel/entities/public-tier/index.ts b/platforms/market/src/features/channel/entities/public-tier/index.ts new file mode 100644 index 0000000..e38d049 --- /dev/null +++ b/platforms/market/src/features/channel/entities/public-tier/index.ts @@ -0,0 +1 @@ +export type { PublicTierEntity } from './types'; diff --git a/platforms/market/src/features/channel/entities/public-tier/types.ts b/platforms/market/src/features/channel/entities/public-tier/types.ts new file mode 100644 index 0000000..ada6c23 --- /dev/null +++ b/platforms/market/src/features/channel/entities/public-tier/types.ts @@ -0,0 +1,44 @@ +import type { + BillingPeriod, + CompareSource, +} from '../../../../shared/constants'; + +/** + * subscription-service's public tier (`toCheckoutTier` over `PricingService.toPublicDisplay`). The + * channel tiers, the checkout screen, the renewal preview and the creator dashboard all send it. + */ +export type PublicTierEntity = { + id: string; + traderId: string; + /** The Persian period label by default (legacy tiers could name themselves). */ + name: string; + billingPeriod: BillingPeriod; + labelFa: string; + /** Standing price in Rial. */ + price: number; + /** Standing price in Rial, despite the name. */ + price_monthly: number; + /** Live total in Toman: the promotional price while a promotion runs, else the standing one. */ + priceToman: number | null; + standingPriceToman: number | null; + perMonthToman: number | null; + compareAtToman: number | null; + compareSource: CompareSource | null; + /** Same as `priceToman`. */ + toman: number | null; + amountUnitFa: string; + currency: string; + /** Set only while a promotion is live (started and not ended). */ + promotion: { + percent: number; + badgeFa: string; + priceToman: number | null; + perMonthToman: number | null; + /** `null` when the promotion is indefinite; missing when a non-indefinite one has no end date. */ + endsAt?: string | null; + indefinite: boolean; + timeLabelFa: string | null; + } | null; + features: string[]; + perMonthLabelFa: string | null; +}; diff --git a/platforms/market/src/features/channel/http.ts b/platforms/market/src/features/channel/http.ts new file mode 100644 index 0000000..cc030a1 --- /dev/null +++ b/platforms/market/src/features/channel/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const channelHttp = http.extend({}); diff --git a/platforms/market/src/features/channel/index.ts b/platforms/market/src/features/channel/index.ts new file mode 100644 index 0000000..818931d --- /dev/null +++ b/platforms/market/src/features/channel/index.ts @@ -0,0 +1,8 @@ +export type { PublicTierEntity } from './entities/public-tier'; +export { channelKeys, channelRepository } from './repositories/channel'; +export type { + ChannelArgs, + PublicCreatorPayload, + PublicTierPayload, + TierPromotionPayload, +} from './repositories/channel'; diff --git a/platforms/market/src/features/channel/repositories/.gitkeep b/platforms/market/src/features/channel/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/channel/repositories/channel/channel.ts b/platforms/market/src/features/channel/repositories/channel/channel.ts new file mode 100644 index 0000000..4ef876e --- /dev/null +++ b/platforms/market/src/features/channel/repositories/channel/channel.ts @@ -0,0 +1,40 @@ +import { channelHttp } from '../../http'; +import { CHANNEL_ENDPOINTS } from './constants'; +import { toPublicCreatorPayload, toPublicTiersPayload } from './mappers'; +import type { + ChannelArgs, + PublicCreatorPayload, + PublicCreatorResponseDto, + PublicTierPayload, + PublicTiersResponseDto, +} from './types'; + +/** + * A creator's public channel; both reads work without a session. The API resolves creators by + * account or profile id only, never by username. + */ +export const channelRepository = { + /** 404 for an unknown or not yet approved creator. */ + async getCreator( + args: ChannelArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await channelHttp.get( + CHANNEL_ENDPOINTS.creator(args.creatorId), + { signal }, + ); + return toPublicCreatorPayload(response); + }, + + /** Active tiers, cheapest first; empty when pricing is not set (or the id is unknown). */ + async listTiers( + args: ChannelArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await channelHttp.get( + CHANNEL_ENDPOINTS.tiers(args.creatorId), + { signal }, + ); + return toPublicTiersPayload(response); + }, +}; diff --git a/platforms/market/src/features/channel/repositories/channel/constants.ts b/platforms/market/src/features/channel/repositories/channel/constants.ts new file mode 100644 index 0000000..7514d07 --- /dev/null +++ b/platforms/market/src/features/channel/repositories/channel/constants.ts @@ -0,0 +1,15 @@ +export const CHANNEL_ENDPOINTS = { + creator: (creatorId: string) => `/traders/${encodeURIComponent(creatorId)}`, + tiers: (creatorId: string) => + `/subscriptions/creators/${encodeURIComponent(creatorId)}/tiers`, +} as const; + +/** Keyed by the creator's account id, so invalidating `creator(id)` refreshes the whole channel. */ +export const channelKeys = { + all: ['channel'] as const, + creator: (creatorId: string) => [...channelKeys.all, creatorId] as const, + profile: (creatorId: string) => + [...channelKeys.creator(creatorId), 'profile'] as const, + tiers: (creatorId: string) => + [...channelKeys.creator(creatorId), 'tiers'] as const, +}; diff --git a/platforms/market/src/features/channel/repositories/channel/index.ts b/platforms/market/src/features/channel/repositories/channel/index.ts new file mode 100644 index 0000000..5b65b9d --- /dev/null +++ b/platforms/market/src/features/channel/repositories/channel/index.ts @@ -0,0 +1,8 @@ +export { channelRepository } from './channel'; +export { channelKeys } from './constants'; +export type { + ChannelArgs, + PublicCreatorPayload, + PublicTierPayload, + TierPromotionPayload, +} from './types'; diff --git a/platforms/market/src/features/channel/repositories/channel/mappers.ts b/platforms/market/src/features/channel/repositories/channel/mappers.ts new file mode 100644 index 0000000..e12bbb6 --- /dev/null +++ b/platforms/market/src/features/channel/repositories/channel/mappers.ts @@ -0,0 +1,54 @@ +import { toApiUrl } from '../../../../shared/utils'; +import type { PublicTierEntity } from '../../entities/public-tier'; +import type { + PublicCreatorPayload, + PublicCreatorResponseDto, + PublicTierPayload, + PublicTiersResponseDto, +} from './types'; + +export function toPublicCreatorPayload( + dto: PublicCreatorResponseDto, +): PublicCreatorPayload { + return { + profileId: dto.id, + creatorId: dto.userId, + username: dto.username, + displayName: dto.displayName || null, + bio: dto.bio || null, + avatarUrl: toApiUrl(dto.avatar), + socialLinks: (dto.socialLinks ?? []).map(({ label, url }) => ({ + label, + url, + })), + tradingStyle: dto.tradingStyle ?? null, + markets: dto.markets ?? [], + }; +} + +function toPublicTierPayload(tier: PublicTierEntity): PublicTierPayload { + return { + id: tier.id, + creatorId: tier.traderId, + billingPeriod: tier.billingPeriod, + priceToman: tier.priceToman, + standingPriceToman: tier.standingPriceToman, + perMonthToman: tier.perMonthToman, + compareAtToman: tier.compareAtToman, + compareSource: tier.compareSource, + promotion: tier.promotion && { + percent: tier.promotion.percent, + priceToman: tier.promotion.priceToman, + perMonthToman: tier.promotion.perMonthToman, + endsAt: tier.promotion.endsAt ?? null, + indefinite: tier.promotion.indefinite, + }, + features: tier.features, + }; +} + +export function toPublicTiersPayload( + dto: PublicTiersResponseDto, +): PublicTierPayload[] { + return dto.items.map(toPublicTierPayload); +} diff --git a/platforms/market/src/features/channel/repositories/channel/types.ts b/platforms/market/src/features/channel/repositories/channel/types.ts new file mode 100644 index 0000000..b11bf68 --- /dev/null +++ b/platforms/market/src/features/channel/repositories/channel/types.ts @@ -0,0 +1,60 @@ +import type { + BillingPeriod, + CompareSource, +} from '../../../../shared/constants'; +import type { Market, SocialLinkPayload, TradingStyle } from '../../../profile'; +import type { PublicCreatorEntity } from '../../entities/public-creator'; +import type { PublicTierEntity } from '../../entities/public-tier'; + +/** The creator's account id; the profile endpoint also accepts the profile id. Not a username. */ +export type ChannelArgs = { creatorId: string }; + +/** + * An approved creator's public page header. Unapproved creators answer 404, so every creator here + * is verified. Follower counts are never shown publicly, so none are fetched. + */ +export type PublicCreatorPayload = { + profileId: string; + /** The creator's account id; follow, tiers, posts and checkout all take this one. */ + creatorId: string; + username: string; + displayName: string | null; + bio: string | null; + avatarUrl: string | null; + socialLinks: SocialLinkPayload[]; + tradingStyle: TradingStyle | null; + markets: Market[]; +}; + +export type PublicCreatorResponseDto = PublicCreatorEntity; + +/** A live promotion on a tier; prices are its promotional totals in Toman. */ +export type TierPromotionPayload = { + percent: number; + priceToman: number | null; + perMonthToman: number | null; + /** ISO date; `null` when `indefinite`. */ + endsAt: string | null; + indefinite: boolean; +}; + +/** + * One active subscription tier as the channel and checkout show it. Money is Toman; `priceToman` + * is what the investor pays now (promotion applied), `standingPriceToman` the regular price. + */ +export type PublicTierPayload = { + id: string; + creatorId: string; + billingPeriod: BillingPeriod; + priceToman: number | null; + standingPriceToman: number | null; + /** `priceToman` spread over the period's months. */ + perMonthToman: number | null; + /** The struck-through price, when there is one. */ + compareAtToman: number | null; + compareSource: CompareSource | null; + promotion: TierPromotionPayload | null; + features: string[]; +}; + +export type PublicTiersResponseDto = { items: PublicTierEntity[] }; diff --git a/platforms/market/src/features/checkout/caches/.gitkeep b/platforms/market/src/features/checkout/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/checkout/caches/checkout-screen.ts b/platforms/market/src/features/checkout/caches/checkout-screen.ts new file mode 100644 index 0000000..fa2e774 --- /dev/null +++ b/platforms/market/src/features/checkout/caches/checkout-screen.ts @@ -0,0 +1,15 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { checkoutRepository } from '../repositories/checkout'; +import type { CheckoutPayload } from '../repositories/checkout'; + +/** + * The signed-in investor's U9 checkout for a creator, once per render. Throws the API's error as + * is: 401 without a session, 403 for a non-investor or a creator who is not approved or suspended. + */ +export const getCheckoutScreen = cache( + (creatorId: string): Promise => + checkoutRepository.getScreen(creatorId), +); diff --git a/platforms/market/src/features/checkout/caches/server.ts b/platforms/market/src/features/checkout/caches/server.ts new file mode 100644 index 0000000..1a32894 --- /dev/null +++ b/platforms/market/src/features/checkout/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getCheckoutScreen } from './checkout-screen'; diff --git a/platforms/market/src/features/checkout/entities/.gitkeep b/platforms/market/src/features/checkout/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/checkout/entities/checkout-result/index.ts b/platforms/market/src/features/checkout/entities/checkout-result/index.ts new file mode 100644 index 0000000..61bafec --- /dev/null +++ b/platforms/market/src/features/checkout/entities/checkout-result/index.ts @@ -0,0 +1,5 @@ +export type { + CheckoutResultEntity, + PriceChangedDetailsEntity, + WaitlistOfferEntity, +} from './types'; diff --git a/platforms/market/src/features/checkout/entities/checkout-result/types.ts b/platforms/market/src/features/checkout/entities/checkout-result/types.ts new file mode 100644 index 0000000..707e00c --- /dev/null +++ b/platforms/market/src/features/checkout/entities/checkout-result/types.ts @@ -0,0 +1,76 @@ +import type { AccessConfirmationEntity } from '../../../transaction'; +import type { SubscriptionEntity } from '../subscription'; + +/** referral-service's `waitlistOffer`: the code is valid, but the creator's capacity is full. */ +export type WaitlistOfferEntity = { + alreadyWaitlisted: boolean; + headingFa: string; + bodyFa: string; + ctaFa?: string; + joinCtaFa: string | null; + declineCtaFa: string; +}; + +/** The `details` of the 409 a subscribe answers when `expectedPriceToman` is stale (`HttpError.details`). */ +export type PriceChangedDetailsEntity = { + priceChanged: true; + headingFa: string; + bodyFa: string; + oldAmountToman: number; + newAmountToman: number; + newTotalToman: number; + confirmCtaFa: string; + cancelCtaFa: string; +}; + +/** Access is active now: the development grant (no payment gateway configured). */ +type GrantedCheckoutEntity = { + granted: true; + waitlist?: never; + url: null; + redirectUrl: null; + paymentId: string; + authority: null; + provider: string; + subscription: SubscriptionEntity | null; + subscriptionId?: string; + confirmation: AccessConfirmationEntity; + successMessageFa: string; + newExpiryConfirmationFa: string | null; + /** Subscribe only. */ + processingFa?: string; + subscriberStatusFa?: string; + channelLink?: string | null; +}; + +/** A pending payment: the browser goes to the bank. `url` and `redirectUrl` are the same link. */ +type RedirectCheckoutEntity = { + granted: false; + waitlist?: never; + url: string | null; + redirectUrl: string | null; + paymentId: string; + authority: string | null; + provider: string; + subscription: null; + /** Renew and reactivate only. */ + subscriptionId?: string; + pendingReviewMessageFa: string; + paymentFailureFa: string; + networkErrorFa: string; +}; + +/** Subscribe only: a valid code at capacity. */ +type WaitlistCheckoutEntity = WaitlistOfferEntity & { + granted: false; + waitlist: true; +}; + +/** + * `SubscriptionService.startCheckout`: what subscribe, renew and reactivate answer. Exported for + * sibling features: subscription's renew and reactivate read it with checkout's mappers. + */ +export type CheckoutResultEntity = + | GrantedCheckoutEntity + | RedirectCheckoutEntity + | WaitlistCheckoutEntity; diff --git a/platforms/market/src/features/checkout/entities/subscription/index.ts b/platforms/market/src/features/checkout/entities/subscription/index.ts new file mode 100644 index 0000000..7e9c0ba --- /dev/null +++ b/platforms/market/src/features/checkout/entities/subscription/index.ts @@ -0,0 +1 @@ +export type { SubscriptionEntity } from './types'; diff --git a/platforms/market/src/features/checkout/entities/subscription/types.ts b/platforms/market/src/features/checkout/entities/subscription/types.ts new file mode 100644 index 0000000..4833224 --- /dev/null +++ b/platforms/market/src/features/checkout/entities/subscription/types.ts @@ -0,0 +1,22 @@ +import type { SubscriptionRecordStatus } from '../../../../shared/constants'; + +/** subscription-service's `Subscription` document as JSON. `amount` is Rial. */ +export type SubscriptionEntity = { + _id: string; + userId: string; + traderId: string; + tierId: string; + status: SubscriptionRecordStatus; + currentPeriodStart: string; + currentPeriodEnd: string; + stripeSubscriptionId?: string; + provider: string; + providerRef?: string; + amount?: number; + currency?: string; + expiryWarningSentAt?: string; + expiredNotifiedAt?: string; + createdAt: string; + updatedAt: string; + __v: number; +}; diff --git a/platforms/market/src/features/checkout/http.ts b/platforms/market/src/features/checkout/http.ts new file mode 100644 index 0000000..deae298 --- /dev/null +++ b/platforms/market/src/features/checkout/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const checkoutHttp = http.extend({}); diff --git a/platforms/market/src/features/checkout/index.ts b/platforms/market/src/features/checkout/index.ts new file mode 100644 index 0000000..f3dd620 --- /dev/null +++ b/platforms/market/src/features/checkout/index.ts @@ -0,0 +1,20 @@ +export type { CheckoutResultEntity } from './entities/checkout-result'; +export { + checkoutKeys, + checkoutRepository, + toCheckoutResultPayload, + toPriceChangedPayload, +} from './repositories/checkout'; +export type { + CheckoutCtaState, + CheckoutPayload, + CheckoutResultPayload, + CheckoutTierPayload, + GrantedSubscriptionPayload, + PriceChangedPayload, + ReferralCodeArgs, + ReferralCodeStatus, + ReferralValidationPayload, + SubscribeArgs, + WaitlistJoinedPayload, +} from './repositories/checkout'; diff --git a/platforms/market/src/features/checkout/repositories/.gitkeep b/platforms/market/src/features/checkout/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/checkout/repositories/checkout/checkout.ts b/platforms/market/src/features/checkout/repositories/checkout/checkout.ts new file mode 100644 index 0000000..5c89c44 --- /dev/null +++ b/platforms/market/src/features/checkout/repositories/checkout/checkout.ts @@ -0,0 +1,90 @@ +import { checkoutHttp } from '../../http'; +import { CHECKOUT_ENDPOINTS } from './constants'; +import { + toCheckoutPayload, + toCheckoutResultPayload, + toPriceChangedPayload, + toReferralCodeDto, + toReferralValidationPayload, + toSubscribeDto, + toWaitlistJoinedPayload, +} from './mappers'; +import type { + CheckoutPayload, + CheckoutResponseDto, + CheckoutResultPayload, + ReferralCodeArgs, + ReferralValidationPayload, + ReferralValidationResponseDto, + SubscribeArgs, + SubscribeResponseDto, + WaitlistJoinedPayload, + WaitlistJoinedResponseDto, + WaitlistLeftResponseDto, +} from './types'; + +/** + * Invite-only subscription checkout for the signed-in investor (U9/U10). The creator must be + * approved (403 otherwise) and every subscribe needs a referral code; a valid code at capacity + * leads to the creator's waitlist. + */ +export const checkoutRepository = { + /** The U9 screen for a creator (`creatorId` is the creator's user id). */ + async getScreen( + creatorId: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await checkoutHttp.get( + CHECKOUT_ENDPOINTS.screen(creatorId), + { signal }, + ); + return toCheckoutPayload(response); + }, + + /** Advisory: subscribe checks the code again when the investor pays. */ + async validateReferral( + args: ReferralCodeArgs, + ): Promise { + const response = await checkoutHttp.post( + CHECKOUT_ENDPOINTS.validateReferral, + toReferralCodeDto(args), + ); + return toReferralValidationPayload(response); + }, + + /** Joins after a valid code at capacity; any other code is a 400. */ + async joinWaitlist(args: ReferralCodeArgs): Promise { + const response = await checkoutHttp.post( + CHECKOUT_ENDPOINTS.joinWaitlist, + toReferralCodeDto(args), + ); + return toWaitlistJoinedPayload(response); + }, + + /** Stops capacity notifications for this creator; succeeds when not on the list too. */ + async leaveWaitlist(creatorId: string): Promise { + await checkoutHttp.delete( + CHECKOUT_ENDPOINTS.leaveWaitlist(creatorId), + ); + }, + + /** + * Starts paying for a tier. The 409 for a moved price (`HttpError.details`) comes back as the + * `price-changed` outcome; every other failure throws: 400 for an invalid code, 409 for an active + * subscription or a payment already in flight. The payment's receipt and U10 phase are + * `transactionRepository.getDetail(paymentId)`. + */ + async subscribe(args: SubscribeArgs): Promise { + try { + const response = await checkoutHttp.post( + CHECKOUT_ENDPOINTS.subscribe, + toSubscribeDto(args), + ); + return toCheckoutResultPayload(response); + } catch (error) { + const priceChanged = toPriceChangedPayload(error); + if (priceChanged) return priceChanged; + throw error; + } + }, +}; diff --git a/platforms/market/src/features/checkout/repositories/checkout/constants.ts b/platforms/market/src/features/checkout/repositories/checkout/constants.ts new file mode 100644 index 0000000..c40fa5b --- /dev/null +++ b/platforms/market/src/features/checkout/repositories/checkout/constants.ts @@ -0,0 +1,18 @@ +const encode = encodeURIComponent; + +export const CHECKOUT_ENDPOINTS = { + screen: (creatorId: string) => + `/subscriptions/creators/${encode(creatorId)}/checkout`, + validateReferral: '/subscriptions/referral/validate', + joinWaitlist: '/subscriptions/waitlist', + leaveWaitlist: (creatorId: string) => + `/subscriptions/waitlist/${encode(creatorId)}`, + subscribe: '/subscribe', +} as const; + +export const checkoutKeys = { + all: ['checkout'] as const, + screens: () => [...checkoutKeys.all, 'screen'] as const, + screen: (creatorId: string) => + [...checkoutKeys.screens(), creatorId] as const, +}; diff --git a/platforms/market/src/features/checkout/repositories/checkout/index.ts b/platforms/market/src/features/checkout/repositories/checkout/index.ts new file mode 100644 index 0000000..be43e00 --- /dev/null +++ b/platforms/market/src/features/checkout/repositories/checkout/index.ts @@ -0,0 +1,16 @@ +export { checkoutRepository } from './checkout'; +export { checkoutKeys } from './constants'; +export { toCheckoutResultPayload, toPriceChangedPayload } from './mappers'; +export type { + CheckoutCtaState, + CheckoutPayload, + CheckoutResultPayload, + CheckoutTierPayload, + GrantedSubscriptionPayload, + PriceChangedPayload, + ReferralCodeArgs, + ReferralCodeStatus, + ReferralValidationPayload, + SubscribeArgs, + WaitlistJoinedPayload, +} from './types'; diff --git a/platforms/market/src/features/checkout/repositories/checkout/mappers.ts b/platforms/market/src/features/checkout/repositories/checkout/mappers.ts new file mode 100644 index 0000000..e4ad011 --- /dev/null +++ b/platforms/market/src/features/checkout/repositories/checkout/mappers.ts @@ -0,0 +1,157 @@ +import { isHttpError } from '@lumina/libs/http'; + +import { toApiUrl } from '../../../../shared/utils'; +import type { PublicTierEntity } from '../../../channel'; +import { toAccessConfirmationPayload } from '../../../transaction'; +import type { + CheckoutResultEntity, + PriceChangedDetailsEntity, +} from '../../entities/checkout-result'; +import type { SubscriptionEntity } from '../../entities/subscription'; +import type { + CheckoutPayload, + CheckoutResponseDto, + CheckoutResultPayload, + CheckoutTierPayload, + GrantedSubscriptionPayload, + PriceChangedPayload, + ReferralCodeArgs, + ReferralCodeDto, + ReferralValidationPayload, + ReferralValidationResponseDto, + SubscribeArgs, + SubscribeDto, + WaitlistJoinedPayload, + WaitlistJoinedResponseDto, +} from './types'; + +function toCheckoutTierPayload(dto: PublicTierEntity): CheckoutTierPayload { + return { + id: dto.id, + billingPeriod: dto.billingPeriod, + priceToman: dto.priceToman, + standingPriceToman: dto.standingPriceToman, + perMonthToman: dto.perMonthToman, + compareAtToman: dto.compareAtToman, + compareSource: dto.compareSource, + promotion: dto.promotion + ? { + percent: dto.promotion.percent, + endsAt: dto.promotion.endsAt ?? null, + indefinite: dto.promotion.indefinite, + } + : null, + features: dto.features, + }; +} + +export function toCheckoutPayload(dto: CheckoutResponseDto): CheckoutPayload { + return { + creator: { + id: dto.creator.id, + username: dto.creator.username, + avatarUrl: toApiUrl(dto.creator.avatar), + verified: dto.creator.verified, + }, + tiers: dto.items.map(toCheckoutTierPayload), + cta: { + state: dto.cta.state, + canPay: dto.cta.canPay, + pendingPaymentId: dto.cta.paymentId, + }, + waitlisted: dto.waitlist.joined, + }; +} + +export function toReferralCodeDto(args: ReferralCodeArgs): ReferralCodeDto { + return { traderId: args.creatorId, code: args.code.trim() }; +} + +export function toReferralValidationPayload( + dto: ReferralValidationResponseDto, +): ReferralValidationPayload { + if (!dto.valid) return { status: 'invalid', alreadyWaitlisted: false }; + return { + status: dto.capacityFull ? 'full' : 'valid', + alreadyWaitlisted: dto.alreadyWaitlisted, + }; +} + +export function toWaitlistJoinedPayload( + dto: WaitlistJoinedResponseDto, +): WaitlistJoinedPayload { + return { alreadyWaitlisted: dto.alreadyWaitlisted }; +} + +export function toSubscribeDto(args: SubscribeArgs): SubscribeDto { + return { + tierId: args.tierId, + referralCode: args.referralCode.trim(), + expectedPriceToman: args.expectedPriceToman, + confirmPriceChange: args.confirmPriceChange, + }; +} + +function toGrantedSubscriptionPayload( + dto: SubscriptionEntity, +): GrantedSubscriptionPayload { + return { + id: dto._id, + creatorId: dto.traderId, + tierId: dto.tierId, + status: dto.status, + startsAt: dto.currentPeriodStart, + endsAt: dto.currentPeriodEnd, + }; +} + +/** For sibling features: subscription's renew and reactivate answer the same union as subscribe. */ +export function toCheckoutResultPayload( + dto: CheckoutResultEntity, +): CheckoutResultPayload { + if (dto.granted) { + return { + outcome: 'granted', + paymentId: dto.paymentId, + subscription: dto.subscription + ? toGrantedSubscriptionPayload(dto.subscription) + : null, + confirmation: toAccessConfirmationPayload(dto.confirmation), + }; + } + if (dto.waitlist) { + return { outcome: 'waitlist', alreadyWaitlisted: dto.alreadyWaitlisted }; + } + return { + outcome: 'redirect', + paymentId: dto.paymentId, + redirectUrl: dto.redirectUrl ?? dto.url, + authority: dto.authority, + }; +} + +/** + * A checkout error → the `price-changed` outcome when it is the 409 for a stale + * `expectedPriceToman`, else `null`. For sibling features: subscription's renew and reactivate + * settle their errors with it too. + */ +export function toPriceChangedPayload( + error: unknown, +): PriceChangedPayload | null { + if (!isHttpError(error) || error.status !== 409) return null; + const details = error.details as + | Partial + | undefined; + if ( + details?.priceChanged !== true || + typeof details.oldAmountToman !== 'number' || + typeof details.newAmountToman !== 'number' + ) { + return null; + } + return { + outcome: 'price-changed', + oldAmountToman: details.oldAmountToman, + newAmountToman: details.newAmountToman, + }; +} diff --git a/platforms/market/src/features/checkout/repositories/checkout/types.ts b/platforms/market/src/features/checkout/repositories/checkout/types.ts new file mode 100644 index 0000000..7568491 --- /dev/null +++ b/platforms/market/src/features/checkout/repositories/checkout/types.ts @@ -0,0 +1,208 @@ +import type { + BillingPeriod, + CompareSource, + SubscriptionRecordStatus, +} from '../../../../shared/constants'; +import type { PublicTierEntity } from '../../../channel'; +import type { AccessConfirmationPayload } from '../../../transaction'; +import type { + CheckoutResultEntity, + WaitlistOfferEntity, +} from '../../entities/checkout-result'; + +// Money is whole Toman everywhere; dates are ISO strings. + +// GET /subscriptions/creators/:traderId/checkout + +/** + * The investor's standing with this creator: may pay (`subscribe`), already subscribed (`active`), + * a payment still in flight (`pending_review`), or their own channel (`own`). + */ +export type CheckoutCtaState = + | 'subscribe' + | 'active' + | 'pending_review' + | 'own'; + +export type CheckoutResponseDto = { + headingFa: string; + inviteOnlyNoteFa: string; + tierSectionLabelFa: string; + referral: { labelFa: string; placeholderFa: string }; + totalPayableLabelFa: string; + paymentCtaFa: string; + frozenCtaTooltipFa: string; + paymentFailureFa: string; + networkErrorFa: string; + creator: { + id: string; + avatar: string | null; + username: string | null; + verified: boolean; + }; + items: PublicTierEntity[]; + waitlist: + | { joined: false } + | { joined: true; noteFa: string; optOutFa: string }; + cta: { + state: CheckoutCtaState; + canPay: boolean; + labelFa: string; + explanationFa: string | null; + paymentId: string | null; + }; +}; + +/** A tier on the checkout screen. */ +export type CheckoutTierPayload = { + id: string; + billingPeriod: BillingPeriod; + /** What a new subscriber pays for the period now (promotion applied); send it as `expectedPriceToman`. */ + priceToman: number | null; + /** The price without a promotion. */ + standingPriceToman: number | null; + perMonthToman: number | null; + /** The struck-through price, if any; `compareSource` says where it comes from. */ + compareAtToman: number | null; + compareSource: CompareSource | null; + /** A live promotion; `endsAt` is `null` when it is indefinite. */ + promotion: { + percent: number; + endsAt: string | null; + indefinite: boolean; + } | null; + /** The creator's own bullet points for the tier. */ + features: string[]; +}; + +/** U9: the creator, their active tiers (cheapest first) and what the CTA may do. */ +export type CheckoutPayload = { + creator: { + id: string; + username: string | null; + avatarUrl: string | null; + verified: boolean; + }; + tiers: CheckoutTierPayload[]; + cta: { + state: CheckoutCtaState; + canPay: boolean; + /** The in-flight payment while `state` is `pending_review`. */ + pendingPaymentId: string | null; + }; + /** On this creator's capacity waitlist; paying stays possible. */ + waitlisted: boolean; +}; + +// POST /subscriptions/referral/validate and POST /subscriptions/waitlist + +export type ReferralCodeArgs = { creatorId: string; code: string }; +export type ReferralCodeDto = { traderId: string; code: string }; + +export type ReferralValidationResponseDto = + | { valid: false; capacityFull: false; messageFa: string } + | { + valid: true; + capacityFull: false; + alreadyWaitlisted: false; + messageFa: string; + } + | { + valid: true; + capacityFull: true; + alreadyWaitlisted: boolean; + messageFa: string; + waitlist: WaitlistOfferEntity; + }; + +/** `full`: the code is real but its capacity is used up, so the investor can only join the waitlist. */ +export type ReferralCodeStatus = 'valid' | 'invalid' | 'full'; + +/** An advisory check of an invite code; subscribe checks it again. */ +export type ReferralValidationPayload = { + status: ReferralCodeStatus; + alreadyWaitlisted: boolean; +}; + +export type WaitlistJoinedResponseDto = { + joined: true; + alreadyWaitlisted: boolean; + toastFa: string; + noteFa: string; + optOutFa: string; + waitlist: WaitlistOfferEntity; +}; + +/** On the waitlist now; `alreadyWaitlisted` when the investor was on it before this request. */ +export type WaitlistJoinedPayload = { alreadyWaitlisted: boolean }; + +// DELETE /subscriptions/waitlist/:traderId + +export type WaitlistLeftResponseDto = { + joined: false; + optedOut: true; + toastFa: string; +}; + +// POST /subscribe + +export type SubscribeArgs = { + tierId: string; + referralCode: string; + /** The `priceToman` the investor saw; a different live price answers `price-changed`. */ + expectedPriceToman?: number; + /** The investor accepted the new price; skips the price check. */ + confirmPriceChange?: boolean; +}; + +export type SubscribeDto = { + tierId: string; + referralCode: string; + expectedPriceToman?: number; + confirmPriceChange?: boolean; +}; + +export type SubscribeResponseDto = CheckoutResultEntity; + +/** The live price moved since checkout loaded; subscribe again with `confirmPriceChange`. */ +export type PriceChangedPayload = { + outcome: 'price-changed'; + oldAmountToman: number; + newAmountToman: number; +}; + +/** The subscription a granted checkout started or extended. */ +export type GrantedSubscriptionPayload = { + id: string; + /** The creator's account id. */ + creatorId: string; + tierId: string; + status: SubscriptionRecordStatus; + startsAt: string; + /** The new expiry. */ + endsAt: string; +}; + +/** + * What tapping pay led to, for subscribe and for subscription's renew and reactivate: + * - `granted`: access is active now (the development grant, no bank); `confirmation` is U10's; + * - `redirect`: send the browser to the bank's `redirectUrl`, then poll the payment; + * - `waitlist`: subscribe only, the code is valid but at capacity; offer the waitlist; + * - `price-changed`: subscribe only, the live price moved (HTTP 409); confirm `newAmountToman` and + * subscribe again. + */ +export type CheckoutResultPayload = + | { + outcome: 'granted'; + paymentId: string; + subscription: GrantedSubscriptionPayload | null; + confirmation: AccessConfirmationPayload; + } + | { + outcome: 'redirect'; + paymentId: string; + redirectUrl: string | null; + authority: string | null; + } + | { outcome: 'waitlist'; alreadyWaitlisted: boolean } + | PriceChangedPayload; diff --git a/platforms/market/src/features/feed/caches/.gitkeep b/platforms/market/src/features/feed/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/feed/caches/feed.ts b/platforms/market/src/features/feed/caches/feed.ts new file mode 100644 index 0000000..c11bb5f --- /dev/null +++ b/platforms/market/src/features/feed/caches/feed.ts @@ -0,0 +1,15 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { FEED_PAGE_LIMIT, feedRepository } from '../repositories/feed'; +import type { FeedPayload } from '../repositories/feed'; + +/** + * The signed-in investor's first feed page. Rejects with 401 for a guest and 403 for a creator; + * later pages load on the client with the same `FEED_PAGE_LIMIT`. + */ +export const getFeed = cache( + async (): Promise => + feedRepository.list({ page: 1, limit: FEED_PAGE_LIMIT }), +); diff --git a/platforms/market/src/features/feed/caches/server.ts b/platforms/market/src/features/feed/caches/server.ts new file mode 100644 index 0000000..d4e965c --- /dev/null +++ b/platforms/market/src/features/feed/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getFeed } from './feed'; diff --git a/platforms/market/src/features/feed/http.ts b/platforms/market/src/features/feed/http.ts new file mode 100644 index 0000000..75ec7c8 --- /dev/null +++ b/platforms/market/src/features/feed/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const feedHttp = http.extend({}); diff --git a/platforms/market/src/features/feed/index.ts b/platforms/market/src/features/feed/index.ts new file mode 100644 index 0000000..c382479 --- /dev/null +++ b/platforms/market/src/features/feed/index.ts @@ -0,0 +1,7 @@ +export { + FEED_ENDPOINT, + FEED_PAGE_LIMIT, + feedKeys, + feedRepository, +} from './repositories/feed'; +export type { FeedPayload, ListFeedArgs } from './repositories/feed'; diff --git a/platforms/market/src/features/feed/repositories/.gitkeep b/platforms/market/src/features/feed/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/feed/repositories/feed/constants.ts b/platforms/market/src/features/feed/repositories/feed/constants.ts new file mode 100644 index 0000000..0ef7b23 --- /dev/null +++ b/platforms/market/src/features/feed/repositories/feed/constants.ts @@ -0,0 +1,12 @@ +import type { ListFeedArgs } from './types'; + +export const FEED_ENDPOINT = '/posts/feed'; + +/** The page size the feed asks for, so a server-rendered first page and the next pages agree. */ +export const FEED_PAGE_LIMIT = 20; + +export const feedKeys = { + all: ['feed'] as const, + lists: () => [...feedKeys.all, 'list'] as const, + list: (args: ListFeedArgs = {}) => [...feedKeys.lists(), args] as const, +}; diff --git a/platforms/market/src/features/feed/repositories/feed/feed.ts b/platforms/market/src/features/feed/repositories/feed/feed.ts new file mode 100644 index 0000000..97eeadc --- /dev/null +++ b/platforms/market/src/features/feed/repositories/feed/feed.ts @@ -0,0 +1,22 @@ +import { feedHttp } from '../../http'; +import { FEED_ENDPOINT } from './constants'; +import { toFeedPayload } from './mappers'; +import type { FeedPayload, ListFeedArgs, ListFeedResponseDto } from './types'; + +/** + * The investor's home feed: published posts of every creator they follow, newest first, premium + * ones locked unless subscribed. Investors only: 401 for a guest, 403 for a creator. Following + * nobody gives an empty page. + */ +export const feedRepository = { + async list( + { page, limit }: ListFeedArgs = {}, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await feedHttp.get(FEED_ENDPOINT, { + params: { page, limit }, + signal, + }); + return toFeedPayload(response); + }, +}; diff --git a/platforms/market/src/features/feed/repositories/feed/index.ts b/platforms/market/src/features/feed/repositories/feed/index.ts new file mode 100644 index 0000000..7d4b98f --- /dev/null +++ b/platforms/market/src/features/feed/repositories/feed/index.ts @@ -0,0 +1,3 @@ +export { FEED_ENDPOINT, FEED_PAGE_LIMIT, feedKeys } from './constants'; +export { feedRepository } from './feed'; +export type { FeedPayload, ListFeedArgs } from './types'; diff --git a/platforms/market/src/features/feed/repositories/feed/mappers.ts b/platforms/market/src/features/feed/repositories/feed/mappers.ts new file mode 100644 index 0000000..56b814a --- /dev/null +++ b/platforms/market/src/features/feed/repositories/feed/mappers.ts @@ -0,0 +1,11 @@ +import { toPostPayload } from '../../../post'; +import type { FeedPayload, ListFeedResponseDto } from './types'; + +export function toFeedPayload(dto: ListFeedResponseDto): FeedPayload { + return { + items: dto.items.map(toPostPayload), + total: dto.total, + page: dto.page, + limit: dto.limit, + }; +} diff --git a/platforms/market/src/features/feed/repositories/feed/types.ts b/platforms/market/src/features/feed/repositories/feed/types.ts new file mode 100644 index 0000000..2f11609 --- /dev/null +++ b/platforms/market/src/features/feed/repositories/feed/types.ts @@ -0,0 +1,16 @@ +import type { PostEntity, PostPagePayload } from '../../../post'; + +export type ListFeedArgs = { + /** From 1; the API defaults to 1. */ + page?: number; + /** The API defaults to 20. */ + limit?: number; +}; +export type ListFeedResponseDto = { + items: PostEntity[]; + total: number; + page: number; + limit: number; +}; +/** A page of the home feed: the same posts and paging as a channel list. */ +export type FeedPayload = PostPagePayload; diff --git a/platforms/market/src/features/finance/caches/.gitkeep b/platforms/market/src/features/finance/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/finance/caches/creator-payments.ts b/platforms/market/src/features/finance/caches/creator-payments.ts new file mode 100644 index 0000000..d3a312d --- /dev/null +++ b/platforms/market/src/features/finance/caches/creator-payments.ts @@ -0,0 +1,11 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { creatorPaymentRepository } from '../repositories/creator-payment'; +import type { CreatorPaymentPayload } from '../repositories/creator-payment'; + +/** Payments the signed-in creator received, once per render. */ +export const getCreatorPayments = cache( + async (): Promise => creatorPaymentRepository.list(), +); diff --git a/platforms/market/src/features/finance/caches/server.ts b/platforms/market/src/features/finance/caches/server.ts new file mode 100644 index 0000000..73ae92f --- /dev/null +++ b/platforms/market/src/features/finance/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getCreatorPayments } from './creator-payments'; diff --git a/platforms/market/src/features/finance/http.ts b/platforms/market/src/features/finance/http.ts new file mode 100644 index 0000000..6391cc7 --- /dev/null +++ b/platforms/market/src/features/finance/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const financeHttp = http.extend({}); diff --git a/platforms/market/src/features/finance/index.ts b/platforms/market/src/features/finance/index.ts new file mode 100644 index 0000000..ddade89 --- /dev/null +++ b/platforms/market/src/features/finance/index.ts @@ -0,0 +1,5 @@ +export { + creatorPaymentRepository, + financeKeys, +} from './repositories/creator-payment'; +export type { CreatorPaymentPayload } from './repositories/creator-payment'; diff --git a/platforms/market/src/features/finance/repositories/.gitkeep b/platforms/market/src/features/finance/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/finance/repositories/creator-payment/constants.ts b/platforms/market/src/features/finance/repositories/creator-payment/constants.ts new file mode 100644 index 0000000..ae7b4ea --- /dev/null +++ b/platforms/market/src/features/finance/repositories/creator-payment/constants.ts @@ -0,0 +1,6 @@ +export const CREATOR_PAYMENTS_ENDPOINT = '/subscriptions/me/transactions'; + +export const financeKeys = { + all: ['finance'] as const, + payments: () => [...financeKeys.all, 'payments'] as const, +}; diff --git a/platforms/market/src/features/finance/repositories/creator-payment/creator-payment.ts b/platforms/market/src/features/finance/repositories/creator-payment/creator-payment.ts new file mode 100644 index 0000000..415fed8 --- /dev/null +++ b/platforms/market/src/features/finance/repositories/creator-payment/creator-payment.ts @@ -0,0 +1,23 @@ +import { financeHttp } from '../../http'; +import { CREATOR_PAYMENTS_ENDPOINT } from './constants'; +import { toCreatorPaymentPayload } from './mappers'; +import type { + CreatorPaymentPayload, + CreatorPaymentsResponseDto, +} from './types'; + +/** + * Payments the signed-in creator received (the latest 100, newest first, every status). Creator + * session only: an investor gets 403. Payouts, balances and شبا have no API yet. + */ +export const creatorPaymentRepository = { + async list({ signal }: { signal?: AbortSignal } = {}): Promise< + CreatorPaymentPayload[] + > { + const response = await financeHttp.get( + CREATOR_PAYMENTS_ENDPOINT, + { signal }, + ); + return response.items.map(toCreatorPaymentPayload); + }, +}; diff --git a/platforms/market/src/features/finance/repositories/creator-payment/index.ts b/platforms/market/src/features/finance/repositories/creator-payment/index.ts new file mode 100644 index 0000000..36dd371 --- /dev/null +++ b/platforms/market/src/features/finance/repositories/creator-payment/index.ts @@ -0,0 +1,3 @@ +export { financeKeys } from './constants'; +export { creatorPaymentRepository } from './creator-payment'; +export type { CreatorPaymentPayload } from './types'; diff --git a/platforms/market/src/features/finance/repositories/creator-payment/mappers.ts b/platforms/market/src/features/finance/repositories/creator-payment/mappers.ts new file mode 100644 index 0000000..8d387cb --- /dev/null +++ b/platforms/market/src/features/finance/repositories/creator-payment/mappers.ts @@ -0,0 +1,20 @@ +import type { PaymentEntity } from '../../../transaction'; +import type { CreatorPaymentPayload } from './types'; + +export function toCreatorPaymentPayload( + dto: PaymentEntity, +): CreatorPaymentPayload { + return { + id: dto.id, + subscriberId: dto.userId, + subscriptionId: dto.subscriptionId, + type: dto.type.value, + billingPeriod: dto.billingPeriod, + amountToman: dto.toman, + createdAt: dto.createdAt, + status: dto.status.value, + rawStatus: dto.rawStatus, + reference: dto.reference.value, + period: dto.period ? { from: dto.period.from, to: dto.period.to } : null, + }; +} diff --git a/platforms/market/src/features/finance/repositories/creator-payment/types.ts b/platforms/market/src/features/finance/repositories/creator-payment/types.ts new file mode 100644 index 0000000..4aef9bd --- /dev/null +++ b/platforms/market/src/features/finance/repositories/creator-payment/types.ts @@ -0,0 +1,30 @@ +import type { + BillingPeriod, + CheckoutKind, + PaymentStatus, + PaymentUiStatus, +} from '../../../../shared/constants'; +import type { PaymentEntity } from '../../../transaction'; + +/** + * A subscription payment the creator received, any status. The subscriber is a user id only: no + * username is sent. Amounts are what the subscriber paid; there is no commission or share yet. + */ +export type CreatorPaymentPayload = { + id: string; + subscriberId: string; + subscriptionId: string | null; + type: CheckoutKind; + billingPeriod: BillingPeriod; + amountToman: number | null; + createdAt: string | null; + status: PaymentUiStatus; + rawStatus: PaymentStatus; + /** Tracking code, else bank ref, else authority; `null` for a development grant. */ + reference: string | null; + /** The period bought; only on a successful payment. */ + period: { from: string | null; to: string | null } | null; +}; + +/** The latest 100, newest first; the server has no pagination. */ +export type CreatorPaymentsResponseDto = { items: PaymentEntity[] }; diff --git a/platforms/market/src/features/follow/caches/.gitkeep b/platforms/market/src/features/follow/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/follow/caches/follow-status.ts b/platforms/market/src/features/follow/caches/follow-status.ts new file mode 100644 index 0000000..d209f15 --- /dev/null +++ b/platforms/market/src/features/follow/caches/follow-status.ts @@ -0,0 +1,15 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { followRepository } from '../repositories/follow'; +import type { FollowStatusPayload } from '../repositories/follow'; + +/** + * The signed-in investor's follow state for a creator, once per render per id. Ask only for an + * investor session: guests get 401 and creators 403. + */ +export const getFollowStatus = cache( + (creatorId: string): Promise => + followRepository.getStatus({ creatorId }), +); diff --git a/platforms/market/src/features/follow/caches/server.ts b/platforms/market/src/features/follow/caches/server.ts new file mode 100644 index 0000000..7642da9 --- /dev/null +++ b/platforms/market/src/features/follow/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getFollowStatus } from './follow-status'; diff --git a/platforms/market/src/features/follow/entities/.gitkeep b/platforms/market/src/features/follow/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/follow/entities/follow-status/index.ts b/platforms/market/src/features/follow/entities/follow-status/index.ts new file mode 100644 index 0000000..3434bf3 --- /dev/null +++ b/platforms/market/src/features/follow/entities/follow-status/index.ts @@ -0,0 +1 @@ +export type { FollowStatusEntity } from './types'; diff --git a/platforms/market/src/features/follow/entities/follow-status/types.ts b/platforms/market/src/features/follow/entities/follow-status/types.ts new file mode 100644 index 0000000..e1d8c78 --- /dev/null +++ b/platforms/market/src/features/follow/entities/follow-status/types.ts @@ -0,0 +1,12 @@ +/** + * content-service's follow state between the signed-in investor and a creator (`getFollowStatus`). + * While a subscription is active the follow is frozen: `frozen === subscribed`, + * `canUnfollow === !subscribed`, and `noteFa` explains it. + */ +export type FollowStatusEntity = { + following: boolean; + subscribed: boolean; + frozen: boolean; + canUnfollow: boolean; + noteFa: string | null; +}; diff --git a/platforms/market/src/features/follow/http.ts b/platforms/market/src/features/follow/http.ts new file mode 100644 index 0000000..156d716 --- /dev/null +++ b/platforms/market/src/features/follow/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const followHttp = http.extend({}); diff --git a/platforms/market/src/features/follow/index.ts b/platforms/market/src/features/follow/index.ts new file mode 100644 index 0000000..bfddd9a --- /dev/null +++ b/platforms/market/src/features/follow/index.ts @@ -0,0 +1,6 @@ +export { followKeys, followRepository } from './repositories/follow'; +export type { + FollowArgs, + FollowChangePayload, + FollowStatusPayload, +} from './repositories/follow'; diff --git a/platforms/market/src/features/follow/repositories/.gitkeep b/platforms/market/src/features/follow/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/follow/repositories/follow/constants.ts b/platforms/market/src/features/follow/repositories/follow/constants.ts new file mode 100644 index 0000000..6be1613 --- /dev/null +++ b/platforms/market/src/features/follow/repositories/follow/constants.ts @@ -0,0 +1,13 @@ +const creatorPath = (creatorId: string) => + `/creators/${encodeURIComponent(creatorId)}`; + +export const FOLLOW_ENDPOINTS = { + follow: (creatorId: string) => `${creatorPath(creatorId)}/follow`, + status: (creatorId: string) => `${creatorPath(creatorId)}/follow-status`, +} as const; + +export const followKeys = { + all: ['follow'] as const, + statuses: () => [...followKeys.all, 'status'] as const, + status: (creatorId: string) => [...followKeys.statuses(), creatorId] as const, +}; diff --git a/platforms/market/src/features/follow/repositories/follow/follow.ts b/platforms/market/src/features/follow/repositories/follow/follow.ts new file mode 100644 index 0000000..032d2de --- /dev/null +++ b/platforms/market/src/features/follow/repositories/follow/follow.ts @@ -0,0 +1,43 @@ +import { followHttp } from '../../http'; +import { FOLLOW_ENDPOINTS } from './constants'; +import { toFollowChangePayload, toFollowStatusPayload } from './mappers'; +import type { + FollowArgs, + FollowChangePayload, + FollowResponseDto, + FollowStatusPayload, + FollowStatusResponseDto, + UnfollowResponseDto, +} from './types'; + +/** + * Investor follows (`/creators/:creatorId/follow`): 401 without a session, 403 for a creator. + * Following is idempotent, and subscribing follows automatically. Unfollow answers 409 while the + * investor has an active subscription to the creator (`FollowStatusPayload.frozen`). + */ +export const followRepository = { + async getStatus( + args: FollowArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await followHttp.get( + FOLLOW_ENDPOINTS.status(args.creatorId), + { signal }, + ); + return toFollowStatusPayload(response); + }, + + async follow(args: FollowArgs): Promise { + const response = await followHttp.post( + FOLLOW_ENDPOINTS.follow(args.creatorId), + ); + return toFollowChangePayload(response); + }, + + async unfollow(args: FollowArgs): Promise { + const response = await followHttp.delete( + FOLLOW_ENDPOINTS.follow(args.creatorId), + ); + return toFollowChangePayload(response); + }, +}; diff --git a/platforms/market/src/features/follow/repositories/follow/index.ts b/platforms/market/src/features/follow/repositories/follow/index.ts new file mode 100644 index 0000000..1848c8d --- /dev/null +++ b/platforms/market/src/features/follow/repositories/follow/index.ts @@ -0,0 +1,7 @@ +export { followKeys } from './constants'; +export { followRepository } from './follow'; +export type { + FollowArgs, + FollowChangePayload, + FollowStatusPayload, +} from './types'; diff --git a/platforms/market/src/features/follow/repositories/follow/mappers.ts b/platforms/market/src/features/follow/repositories/follow/mappers.ts new file mode 100644 index 0000000..2cf0735 --- /dev/null +++ b/platforms/market/src/features/follow/repositories/follow/mappers.ts @@ -0,0 +1,24 @@ +import type { + FollowChangePayload, + FollowResponseDto, + FollowStatusPayload, + FollowStatusResponseDto, + UnfollowResponseDto, +} from './types'; + +export function toFollowStatusPayload( + dto: FollowStatusResponseDto, +): FollowStatusPayload { + return { + following: dto.following, + subscribed: dto.subscribed, + frozen: dto.frozen, + canUnfollow: dto.canUnfollow, + }; +} + +export function toFollowChangePayload( + dto: FollowResponseDto | UnfollowResponseDto, +): FollowChangePayload { + return { following: dto.following }; +} diff --git a/platforms/market/src/features/follow/repositories/follow/types.ts b/platforms/market/src/features/follow/repositories/follow/types.ts new file mode 100644 index 0000000..2123ef5 --- /dev/null +++ b/platforms/market/src/features/follow/repositories/follow/types.ts @@ -0,0 +1,26 @@ +import type { FollowStatusEntity } from '../../entities/follow-status'; + +/** The creator's account id (`creatorId` of the channel payloads). */ +export type FollowArgs = { creatorId: string }; + +/** Whether the signed-in investor follows the creator, and whether they may stop. */ +export type FollowStatusPayload = { + following: boolean; + /** An active subscription to this creator. */ + subscribed: boolean; + /** Unfollow is blocked while subscribed (same as `subscribed`). */ + frozen: boolean; + canUnfollow: boolean; +}; + +export type FollowStatusResponseDto = FollowStatusEntity; + +export type FollowResponseDto = { following: true }; +export type UnfollowResponseDto = { + following: false; + frozen: false; + canUnfollow: true; +}; + +/** The follow state after a follow or unfollow. */ +export type FollowChangePayload = { following: boolean }; diff --git a/platforms/market/src/features/notification/caches/.gitkeep b/platforms/market/src/features/notification/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/notification/caches/inbox.ts b/platforms/market/src/features/notification/caches/inbox.ts new file mode 100644 index 0000000..5e98749 --- /dev/null +++ b/platforms/market/src/features/notification/caches/inbox.ts @@ -0,0 +1,11 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { notificationRepository } from '../repositories/notification'; +import type { InboxPayload } from '../repositories/notification'; + +/** The signed-in user's inbox, one request per render. 401 reaches the caller. */ +export const getNotificationInbox = cache( + (): Promise => notificationRepository.listInbox(), +); diff --git a/platforms/market/src/features/notification/caches/server.ts b/platforms/market/src/features/notification/caches/server.ts new file mode 100644 index 0000000..d97593c --- /dev/null +++ b/platforms/market/src/features/notification/caches/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { getNotificationInbox } from './inbox'; +export { getUnreadNotificationCount } from './unread-count'; diff --git a/platforms/market/src/features/notification/caches/unread-count.ts b/platforms/market/src/features/notification/caches/unread-count.ts new file mode 100644 index 0000000..2131fef --- /dev/null +++ b/platforms/market/src/features/notification/caches/unread-count.ts @@ -0,0 +1,11 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { notificationRepository } from '../repositories/notification'; +import type { UnreadCountPayload } from '../repositories/notification'; + +/** The signed-in user's unread badge count, one request per render. 401 reaches the caller. */ +export const getUnreadNotificationCount = cache( + (): Promise => notificationRepository.getUnreadCount(), +); diff --git a/platforms/market/src/features/notification/constants.ts b/platforms/market/src/features/notification/constants.ts new file mode 100644 index 0000000..ab4fb13 --- /dev/null +++ b/platforms/market/src/features/notification/constants.ts @@ -0,0 +1,2 @@ +/** The unread badge shows the count up to this, then `99+` (the server's `UNREAD_BADGE_CAP`). */ +export const UNREAD_BADGE_CAP = 99; diff --git a/platforms/market/src/features/notification/entities/.gitkeep b/platforms/market/src/features/notification/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/notification/entities/notification/index.ts b/platforms/market/src/features/notification/entities/notification/index.ts new file mode 100644 index 0000000..1751903 --- /dev/null +++ b/platforms/market/src/features/notification/entities/notification/index.ts @@ -0,0 +1,5 @@ +export type { + NotificationEntity, + NotificationType, + UnreadCountEntity, +} from './types'; diff --git a/platforms/market/src/features/notification/entities/notification/types.ts b/platforms/market/src/features/notification/entities/notification/types.ts new file mode 100644 index 0000000..a485adf --- /dev/null +++ b/platforms/market/src/features/notification/entities/notification/types.ts @@ -0,0 +1,39 @@ +/** + * Every in-app notification type the services emit today (all from subscription-service). + * `waitlist_capacity` is sticky and replaced in place; the others expire after 30 days. + */ +export type NotificationType = + | 'subscription_subscribe' + | 'subscription_renew' + | 'subscription_reactivate' + | 'subscription_delayed_confirm' + | 'subscription_expiry_warning' + | 'subscription_expired' + | 'payment_pending_review' + | 'waitlist_capacity' + | 'new_subscriber'; + +/** notification-service's inbox item (`toInboxItem`). `title` and `body` are composed Persian text. */ +export type NotificationEntity = { + id: string; + type: NotificationType; + title: string; + body: string; + ctaLabelFa: string | null; + /** An app path such as `/dashboard/subscriptions` or `/traders/`. */ + link: string | null; + subscriptionId: string | null; + traderId: string | null; + sticky: boolean; + read: boolean; + unreadBorderHex: string | null; + createdAt: string | null; +}; + +/** The unread badge (`unreadCount`). */ +export type UnreadCountEntity = { + count: number; + badgeLabelFa: string; + badgeHex: string; + unreadBorderHex: string; +}; diff --git a/platforms/market/src/features/notification/http.ts b/platforms/market/src/features/notification/http.ts new file mode 100644 index 0000000..b815e72 --- /dev/null +++ b/platforms/market/src/features/notification/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const notificationHttp = http.extend({}); diff --git a/platforms/market/src/features/notification/index.ts b/platforms/market/src/features/notification/index.ts new file mode 100644 index 0000000..bac3704 --- /dev/null +++ b/platforms/market/src/features/notification/index.ts @@ -0,0 +1,12 @@ +export { UNREAD_BADGE_CAP } from './constants'; +export type { NotificationType } from './entities/notification'; +export { + notificationKeys, + notificationRepository, +} from './repositories/notification'; +export type { + InboxPayload, + MarkReadArgs, + NotificationPayload, + UnreadCountPayload, +} from './repositories/notification'; diff --git a/platforms/market/src/features/notification/repositories/.gitkeep b/platforms/market/src/features/notification/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/notification/repositories/notification/constants.ts b/platforms/market/src/features/notification/repositories/notification/constants.ts new file mode 100644 index 0000000..56d1020 --- /dev/null +++ b/platforms/market/src/features/notification/repositories/notification/constants.ts @@ -0,0 +1,12 @@ +export const NOTIFICATION_ENDPOINTS = { + inbox: '/notifications', + unreadCount: '/notifications/unread-count', + markAllRead: '/notifications/open', + markRead: (id: string) => `/notifications/${encodeURIComponent(id)}/read`, +} as const; + +export const notificationKeys = { + all: ['notification'] as const, + inbox: () => [...notificationKeys.all, 'inbox'] as const, + unreadCount: () => [...notificationKeys.all, 'unread-count'] as const, +}; diff --git a/platforms/market/src/features/notification/repositories/notification/index.ts b/platforms/market/src/features/notification/repositories/notification/index.ts new file mode 100644 index 0000000..73ec830 --- /dev/null +++ b/platforms/market/src/features/notification/repositories/notification/index.ts @@ -0,0 +1,8 @@ +export { notificationKeys } from './constants'; +export { notificationRepository } from './notification'; +export type { + InboxPayload, + MarkReadArgs, + NotificationPayload, + UnreadCountPayload, +} from './types'; diff --git a/platforms/market/src/features/notification/repositories/notification/mappers.ts b/platforms/market/src/features/notification/repositories/notification/mappers.ts new file mode 100644 index 0000000..9c7b56e --- /dev/null +++ b/platforms/market/src/features/notification/repositories/notification/mappers.ts @@ -0,0 +1,38 @@ +import type { + InboxPayload, + InboxResponseDto, + NotificationPayload, + NotificationResponseDto, + UnreadCountPayload, + UnreadCountResponseDto, +} from './types'; + +export function toNotificationPayload( + dto: NotificationResponseDto, +): NotificationPayload { + return { + id: dto.id, + type: dto.type, + serverTitle: dto.title, + serverMessage: dto.body, + link: dto.link, + subscriptionId: dto.subscriptionId, + creatorId: dto.traderId, + sticky: dto.sticky, + read: dto.read, + createdAt: dto.createdAt, + }; +} + +export function toInboxPayload(dto: InboxResponseDto): InboxPayload { + return { + items: dto.items.map(toNotificationPayload), + unreadCount: dto.unread.count, + }; +} + +export function toUnreadCountPayload( + dto: UnreadCountResponseDto, +): UnreadCountPayload { + return { count: dto.count }; +} diff --git a/platforms/market/src/features/notification/repositories/notification/notification.ts b/platforms/market/src/features/notification/repositories/notification/notification.ts new file mode 100644 index 0000000..77d7d7f --- /dev/null +++ b/platforms/market/src/features/notification/repositories/notification/notification.ts @@ -0,0 +1,58 @@ +import { notificationHttp } from '../../http'; +import { NOTIFICATION_ENDPOINTS } from './constants'; +import { + toInboxPayload, + toNotificationPayload, + toUnreadCountPayload, +} from './mappers'; +import type { + InboxPayload, + InboxResponseDto, + MarkReadArgs, + NotificationPayload, + NotificationResponseDto, + UnreadCountPayload, + UnreadCountResponseDto, +} from './types'; + +/** + * The signed-in user's in-app inbox, either role; 401 without a session. Opening the notification + * center marks everything read. Marking another user's (or an unknown) id answers 404. + */ +export const notificationRepository = { + async listInbox({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await notificationHttp.get( + NOTIFICATION_ENDPOINTS.inbox, + { signal }, + ); + return toInboxPayload(response); + }, + + async getUnreadCount({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await notificationHttp.get( + NOTIFICATION_ENDPOINTS.unreadCount, + { signal }, + ); + return toUnreadCountPayload(response); + }, + + /** Marks every notification read; returns the new unread count (0). */ + async markAllRead(): Promise { + const response = await notificationHttp.post( + NOTIFICATION_ENDPOINTS.markAllRead, + ); + return toUnreadCountPayload(response); + }, + + /** Idempotent; returns the notification as now read. */ + async markRead(args: MarkReadArgs): Promise { + const response = await notificationHttp.post( + NOTIFICATION_ENDPOINTS.markRead(args.id), + ); + return toNotificationPayload(response); + }, +}; diff --git a/platforms/market/src/features/notification/repositories/notification/types.ts b/platforms/market/src/features/notification/repositories/notification/types.ts new file mode 100644 index 0000000..accf37c --- /dev/null +++ b/platforms/market/src/features/notification/repositories/notification/types.ts @@ -0,0 +1,47 @@ +import type { + NotificationEntity, + NotificationType, + UnreadCountEntity, +} from '../../entities/notification'; + +/** + * One inbox notification. The server composes its text in Persian with names, amounts and dates + * the item does not carry otherwise, so `serverTitle` and `serverMessage` are shown as they come. + * The call-to-action label comes from i18n by `type`; `link` says where it goes. + */ +export type NotificationPayload = { + id: string; + type: NotificationType; + serverTitle: string; + serverMessage: string; + /** An app path to open; `/traders/` links still need mapping to a channel route. */ + link: string | null; + subscriptionId: string | null; + /** The creator's account id, for subscription and waitlist notices. */ + creatorId: string | null; + /** Kept past the 30-day expiry until dismissed by the server (waitlist notices). */ + sticky: boolean; + read: boolean; + createdAt: string | null; +}; + +/** The newest 100 notifications, newest first (the API has no pagination), and the unread count. */ +export type InboxPayload = { + items: NotificationPayload[]; + unreadCount: number; +}; + +export type UnreadCountPayload = { count: number }; + +export type MarkReadArgs = { id: string }; + +export type NotificationResponseDto = NotificationEntity; +export type UnreadCountResponseDto = UnreadCountEntity; +export type InboxResponseDto = { + headingFa: string; + empty: boolean; + emptyMessageFa: string; + loadErrorFa: string; + unread: UnreadCountEntity; + items: NotificationEntity[]; +}; diff --git a/platforms/market/src/features/overview/caches/.gitkeep b/platforms/market/src/features/overview/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/overview/caches/creator-dashboard.ts b/platforms/market/src/features/overview/caches/creator-dashboard.ts new file mode 100644 index 0000000..fcda32c --- /dev/null +++ b/platforms/market/src/features/overview/caches/creator-dashboard.ts @@ -0,0 +1,12 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { creatorDashboardRepository } from '../repositories/creator-dashboard'; +import type { CreatorDashboardPayload } from '../repositories/creator-dashboard'; + +/** The signed-in creator's dashboard figures, once per render. */ +export const getCreatorDashboard = cache( + async (): Promise => + creatorDashboardRepository.get(), +); diff --git a/platforms/market/src/features/overview/caches/server.ts b/platforms/market/src/features/overview/caches/server.ts new file mode 100644 index 0000000..d659e3b --- /dev/null +++ b/platforms/market/src/features/overview/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getCreatorDashboard } from './creator-dashboard'; diff --git a/platforms/market/src/features/overview/entities/.gitkeep b/platforms/market/src/features/overview/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/overview/entities/creator-tier/index.ts b/platforms/market/src/features/overview/entities/creator-tier/index.ts new file mode 100644 index 0000000..e93b2dc --- /dev/null +++ b/platforms/market/src/features/overview/entities/creator-tier/index.ts @@ -0,0 +1 @@ +export type { CreatorTierEntity } from './types'; diff --git a/platforms/market/src/features/overview/entities/creator-tier/types.ts b/platforms/market/src/features/overview/entities/creator-tier/types.ts new file mode 100644 index 0000000..f067149 --- /dev/null +++ b/platforms/market/src/features/overview/entities/creator-tier/types.ts @@ -0,0 +1,9 @@ +import type { PublicTierEntity } from '../../../channel'; + +/** A tier on the creator dashboard (`toCreatorTier`), disabled ones included. */ +export type CreatorTierEntity = PublicTierEntity & { + active: boolean; + stripe_price_id: string | null; + /** Running subscriptions on this tier. */ + activeSubscribers: number; +}; diff --git a/platforms/market/src/features/overview/http.ts b/platforms/market/src/features/overview/http.ts new file mode 100644 index 0000000..6391ed9 --- /dev/null +++ b/platforms/market/src/features/overview/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const overviewHttp = http.extend({}); diff --git a/platforms/market/src/features/overview/index.ts b/platforms/market/src/features/overview/index.ts new file mode 100644 index 0000000..63f290e --- /dev/null +++ b/platforms/market/src/features/overview/index.ts @@ -0,0 +1,9 @@ +export { + creatorDashboardRepository, + overviewKeys, +} from './repositories/creator-dashboard'; +export type { + CreatorDashboardPayload, + CreatorTierPayload, + RecentPaymentPayload, +} from './repositories/creator-dashboard'; diff --git a/platforms/market/src/features/overview/repositories/.gitkeep b/platforms/market/src/features/overview/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/overview/repositories/creator-dashboard/constants.ts b/platforms/market/src/features/overview/repositories/creator-dashboard/constants.ts new file mode 100644 index 0000000..38bd249 --- /dev/null +++ b/platforms/market/src/features/overview/repositories/creator-dashboard/constants.ts @@ -0,0 +1,6 @@ +export const CREATOR_DASHBOARD_ENDPOINT = '/subscriptions/me/dashboard'; + +export const overviewKeys = { + all: ['overview'] as const, + dashboard: () => [...overviewKeys.all, 'dashboard'] as const, +}; diff --git a/platforms/market/src/features/overview/repositories/creator-dashboard/creator-dashboard.ts b/platforms/market/src/features/overview/repositories/creator-dashboard/creator-dashboard.ts new file mode 100644 index 0000000..2fccf6f --- /dev/null +++ b/platforms/market/src/features/overview/repositories/creator-dashboard/creator-dashboard.ts @@ -0,0 +1,20 @@ +import { overviewHttp } from '../../http'; +import { CREATOR_DASHBOARD_ENDPOINT } from './constants'; +import { toCreatorDashboardPayload } from './mappers'; +import type { + CreatorDashboardPayload, + CreatorDashboardResponseDto, +} from './types'; + +/** The signed-in creator's subscription figures. Creator session only: an investor gets 403. */ +export const creatorDashboardRepository = { + async get({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await overviewHttp.get( + CREATOR_DASHBOARD_ENDPOINT, + { signal }, + ); + return toCreatorDashboardPayload(response); + }, +}; diff --git a/platforms/market/src/features/overview/repositories/creator-dashboard/index.ts b/platforms/market/src/features/overview/repositories/creator-dashboard/index.ts new file mode 100644 index 0000000..5d90111 --- /dev/null +++ b/platforms/market/src/features/overview/repositories/creator-dashboard/index.ts @@ -0,0 +1,7 @@ +export { overviewKeys } from './constants'; +export { creatorDashboardRepository } from './creator-dashboard'; +export type { + CreatorDashboardPayload, + CreatorTierPayload, + RecentPaymentPayload, +} from './types'; diff --git a/platforms/market/src/features/overview/repositories/creator-dashboard/mappers.ts b/platforms/market/src/features/overview/repositories/creator-dashboard/mappers.ts new file mode 100644 index 0000000..26f37e1 --- /dev/null +++ b/platforms/market/src/features/overview/repositories/creator-dashboard/mappers.ts @@ -0,0 +1,28 @@ +import type { + CreatorDashboardPayload, + CreatorDashboardResponseDto, +} from './types'; + +export function toCreatorDashboardPayload( + dto: CreatorDashboardResponseDto, +): CreatorDashboardPayload { + return { + activeSubscribers: dto.activeSubscribers, + revenueToman: dto.toman, + tiers: dto.tiers.map((tier) => ({ + id: tier.id, + billingPeriod: tier.billingPeriod, + priceToman: tier.priceToman, + active: tier.active, + activeSubscribers: tier.activeSubscribers, + })), + recentPayments: dto.recentTransactions.map((payment) => ({ + id: payment.id, + subscriberId: payment.userId, + type: payment.type.value, + billingPeriod: payment.billingPeriod, + amountToman: payment.toman, + createdAt: payment.createdAt, + })), + }; +} diff --git a/platforms/market/src/features/overview/repositories/creator-dashboard/types.ts b/platforms/market/src/features/overview/repositories/creator-dashboard/types.ts new file mode 100644 index 0000000..d0923ef --- /dev/null +++ b/platforms/market/src/features/overview/repositories/creator-dashboard/types.ts @@ -0,0 +1,45 @@ +import type { BillingPeriod, CheckoutKind } from '../../../../shared/constants'; +import type { PaymentEntity } from '../../../transaction'; +import type { CreatorTierEntity } from '../../entities/creator-tier'; + +/** A tier with how many subscribers it carries now. */ +export type CreatorTierPayload = { + id: string; + billingPeriod: BillingPeriod; + /** The live price: a running promotion applied. */ + priceToman: number | null; + active: boolean; + activeSubscribers: number; +}; + +/** A completed payment to the creator. The subscriber is a user id only: no username is sent. */ +export type RecentPaymentPayload = { + id: string; + subscriberId: string; + type: CheckoutKind; + billingPeriod: BillingPeriod; + amountToman: number | null; + createdAt: string | null; +}; + +/** The creator's داشبورد figures. */ +export type CreatorDashboardPayload = { + /** Subscriptions running now, across tiers. */ + activeSubscribers: number; + /** Gross: every completed payment, before commission («درآمد ناخالص»). */ + revenueToman: number | null; + tiers: CreatorTierPayload[]; + /** The 20 latest completed payments, newest first. */ + recentPayments: RecentPaymentPayload[]; +}; + +export type CreatorDashboardResponseDto = { + activeSubscribers: number; + /** Rial. */ + revenueToDate: number; + currency: string; + toman: number | null; + amountUnitFa: string; + tiers: CreatorTierEntity[]; + recentTransactions: PaymentEntity[]; +}; diff --git a/platforms/market/src/features/post/caches/.gitkeep b/platforms/market/src/features/post/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/post/caches/creator-posts.ts b/platforms/market/src/features/post/caches/creator-posts.ts new file mode 100644 index 0000000..73c3896 --- /dev/null +++ b/platforms/market/src/features/post/caches/creator-posts.ts @@ -0,0 +1,20 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { POST_PAGE_LIMIT, postRepository } from '../repositories/post'; +import type { PostPagePayload } from '../repositories/post'; + +/** + * A channel's first page for this request's viewer: drafts included for the creator, premium + * posts locked for anyone without a subscription. Later pages load on the client with the same + * `POST_PAGE_LIMIT`. + */ +export const getCreatorPosts = cache( + async (creatorId: string): Promise => + postRepository.listByCreator({ + creatorId, + page: 1, + limit: POST_PAGE_LIMIT, + }), +); diff --git a/platforms/market/src/features/post/caches/post.ts b/platforms/market/src/features/post/caches/post.ts new file mode 100644 index 0000000..0718ddd --- /dev/null +++ b/platforms/market/src/features/post/caches/post.ts @@ -0,0 +1,14 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { postRepository } from '../repositories/post'; +import type { PostPayload } from '../repositories/post'; + +/** + * One post as this request's viewer may see it: in full, or locked for a premium post without a + * subscription. A missing post or someone else's draft rejects with a 404 for `readOnServer`. + */ +export const getPost = cache( + async (id: string): Promise => postRepository.get(id), +); diff --git a/platforms/market/src/features/post/caches/server.ts b/platforms/market/src/features/post/caches/server.ts new file mode 100644 index 0000000..aefddc9 --- /dev/null +++ b/platforms/market/src/features/post/caches/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { getCreatorPosts } from './creator-posts'; +export { getPost } from './post'; diff --git a/platforms/market/src/features/post/entities/.gitkeep b/platforms/market/src/features/post/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/post/entities/file/index.ts b/platforms/market/src/features/post/entities/file/index.ts new file mode 100644 index 0000000..7807b50 --- /dev/null +++ b/platforms/market/src/features/post/entities/file/index.ts @@ -0,0 +1 @@ +export type { FileEntity, FileKind, FileStatus, FileVisibility } from './types'; diff --git a/platforms/market/src/features/post/entities/file/types.ts b/platforms/market/src/features/post/entities/file/types.ts new file mode 100644 index 0000000..ac36976 --- /dev/null +++ b/platforms/market/src/features/post/entities/file/types.ts @@ -0,0 +1,23 @@ +export type FileVisibility = 'public' | 'private'; + +/** Videos are `video`; everything else, images included, is `file`. */ +export type FileKind = 'file' | 'video'; + +/** A video stays `pending` until it is processed; anything else is `ready` at once. */ +export type FileStatus = 'pending' | 'ready' | 'deleted'; + +/** The gateway's public projection of an uploaded file (`toPublicShape`). */ +export type FileEntity = { + id: string; + ownerId: string; + visibility: FileVisibility; + kind: FileKind; + originalName: string; + mimeType: string; + sizeBytes: number; + status: FileStatus; + video?: { durationSeconds?: number; resolution?: string; codec?: string }; + /** `/files/:id`, outside `/v1`. A private file streams to its owner only. */ + url: string; + createdAt: string; +}; diff --git a/platforms/market/src/features/post/entities/post/index.ts b/platforms/market/src/features/post/entities/post/index.ts new file mode 100644 index 0000000..63f2713 --- /dev/null +++ b/platforms/market/src/features/post/entities/post/index.ts @@ -0,0 +1,15 @@ +export type { + LockedPostEntity, + LockedPredictionEntity, + PostAccessLevel, + PostEntity, + PostMediaEntity, + PostMediaPreviewEntity, + PostStatus, + PostType, + PredictionDirection, + PredictionEntity, + PredictionOutcome, + PredictionStatus, + UnlockedPostEntity, +} from './types'; diff --git a/platforms/market/src/features/post/entities/post/types.ts b/platforms/market/src/features/post/entities/post/types.ts new file mode 100644 index 0000000..9b174d2 --- /dev/null +++ b/platforms/market/src/features/post/entities/post/types.ts @@ -0,0 +1,93 @@ +export type PostType = 'text' | 'image' | 'prediction'; + +/** `free` is open to everyone; `premium` is locked for anyone without an active subscription. */ +export type PostAccessLevel = 'free' | 'premium'; + +/** + * `draft` is visible to its creator only, `published` is live, `deleted` is a soft delete that no + * read returns. + */ +export type PostStatus = 'draft' | 'published' | 'deleted'; + +export type PredictionDirection = 'long' | 'short'; + +export type PredictionStatus = 'open' | 'closed'; + +/** Derived by the API on close: the close price against the entry, in the prediction's direction. */ +export type PredictionOutcome = 'win' | 'loss' | 'breakeven'; + +/** One image of an `image` post (content-service `PostMedia`). Always a `private` file. */ +export type PostMediaEntity = { + fileId: string; + /** `/v1/posts/:postId/media/:fileId`, gated by the post's paywall. */ + url: string; + order: number; + width?: number; + height?: number; + blurHash?: string; +}; + +/** A `prediction` post's structured data (content-service `PredictionData`). Frozen once published. */ +export type PredictionEntity = { + /** Uppercased by the API. */ + symbol: string; + /** A free-form market key (`crypto`, `gold`); the API does not restrict it. */ + market: string; + direction: PredictionDirection; + entryPrice: number; + targetPrices: number[]; + stopLoss?: number; + /** A timeframe label as the creator typed it: `1d`, `1w`. */ + horizon: string; + expiresAt?: string; + status: PredictionStatus; + outcome?: PredictionOutcome; + closedPrice?: number; + closedAt?: string; +}; + +/** A locked premium image: its box and blurHash only, never its file id or URL. */ +export type PostMediaPreviewEntity = { + order: number; + blurHash?: string; + width?: number; + height?: number; +}; + +/** A locked premium prediction: only these three fields are sent. */ +export type LockedPredictionEntity = Pick< + PredictionEntity, + 'symbol' | 'direction' | 'status' +>; + +type PostEntityBase = { + id: string; + creatorId: string; + type: PostType; + accessLevel: PostAccessLevel; + status: PostStatus; + createdAt: string; + /** Absent on a draft. */ + publishedAt?: string; +}; + +/** Free, or premium for the creator and active subscribers. */ +export type UnlockedPostEntity = PostEntityBase & { + locked: false; + caption?: string; + media: PostMediaEntity[]; + /** Absent on other types and on a draft prediction saved without one. */ + prediction?: PredictionEntity; +}; + +/** Premium for anyone else: a teaser with the caption cut to 140 characters and no media. */ +export type LockedPostEntity = PostEntityBase & { + locked: true; + captionPreview?: string; + mediaPreview: PostMediaPreviewEntity[]; + mediaCount: number; + prediction?: LockedPredictionEntity; +}; + +/** content-service `toPostView`: the post as the viewer may see it. */ +export type PostEntity = UnlockedPostEntity | LockedPostEntity; diff --git a/platforms/market/src/features/post/http.ts b/platforms/market/src/features/post/http.ts new file mode 100644 index 0000000..3687d5a --- /dev/null +++ b/platforms/market/src/features/post/http.ts @@ -0,0 +1,8 @@ +import { http } from '@lumina/libs/http'; + +import { getEnv } from '../../env'; + +export const postHttp = http.extend({}); + +/** `/files/*` sits outside `/v1`, on the API origin itself. */ +export const postFilesHttp = http.extend({ baseUrl: () => getEnv().apiOrigin }); diff --git a/platforms/market/src/features/post/index.ts b/platforms/market/src/features/post/index.ts new file mode 100644 index 0000000..313cf9e --- /dev/null +++ b/platforms/market/src/features/post/index.ts @@ -0,0 +1,42 @@ +export type { FileKind, FileStatus, FileVisibility } from './entities/file'; +export type { + PostAccessLevel, + PostEntity, + PostStatus, + PostType, + PredictionDirection, + PredictionOutcome, + PredictionStatus, +} from './entities/post'; +export { FILE_ENDPOINTS, fileKeys, fileRepository } from './repositories/file'; +export type { + FilePagePayload, + FilePayload, + ListMyFilesArgs, + UploadFileArgs, + UploadFileOptions, +} from './repositories/file'; +export { + POST_ENDPOINTS, + POST_PAGE_LIMIT, + postKeys, + postRepository, + toPostPayload, +} from './repositories/post'; +export type { + CreatePostArgs, + DeletedPostPayload, + ListCreatorPostsArgs, + LockedPostPayload, + LockedPredictionPayload, + PostImagePayload, + PostImagePreviewPayload, + PostMediaArgs, + PostPagePayload, + PostPayload, + PredictionArgs, + PredictionPayload, + PurgedPostPayload, + UnlockedPostPayload, + UpdatePostArgs, +} from './repositories/post'; diff --git a/platforms/market/src/features/post/repositories/.gitkeep b/platforms/market/src/features/post/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/post/repositories/file/constants.ts b/platforms/market/src/features/post/repositories/file/constants.ts new file mode 100644 index 0000000..0ee0f77 --- /dev/null +++ b/platforms/market/src/features/post/repositories/file/constants.ts @@ -0,0 +1,14 @@ +import type { ListMyFilesArgs } from './types'; + +/** Outside `/v1`: requests go through `postFilesHttp`. */ +export const FILE_ENDPOINTS = { + upload: '/files/upload', + mine: '/files/mine', + detail: (id: string) => `/files/${encodeURIComponent(id)}`, +} as const; + +export const fileKeys = { + all: ['post', 'file'] as const, + mine: (args: ListMyFilesArgs = {}) => + [...fileKeys.all, 'mine', args] as const, +}; diff --git a/platforms/market/src/features/post/repositories/file/file.ts b/platforms/market/src/features/post/repositories/file/file.ts new file mode 100644 index 0000000..8e57b90 --- /dev/null +++ b/platforms/market/src/features/post/repositories/file/file.ts @@ -0,0 +1,54 @@ +import { postFilesHttp } from '../../http'; +import { FILE_ENDPOINTS } from './constants'; +import { + toFilePagePayload, + toFilePayload, + toUploadFileFormData, +} from './mappers'; +import type { + DeleteFileResponseDto, + FilePagePayload, + FilePayload, + FileResponseDto, + ListMyFilesArgs, + ListMyFilesResponseDto, + UploadFileArgs, + UploadFileOptions, +} from './types'; + +/** + * The signed-in user's uploads (`/files/*`), for the post composer: upload an image, then pass its + * `id` as `media[].fileId`. A file a post already holds cannot go on a second post or be deleted. + */ +export const fileRepository = { + /** Reports progress through `onProgress`; `signal` cancels the upload. */ + async upload( + args: UploadFileArgs, + { onProgress, signal }: UploadFileOptions = {}, + ): Promise { + const response = await postFilesHttp.upload( + FILE_ENDPOINTS.upload, + toUploadFileFormData(args), + { onProgress, signal }, + ); + return toFilePayload(response); + }, + + /** Every file the user owns, attached or not, newest first. */ + async listMine( + { page, limit }: ListMyFilesArgs = {}, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await postFilesHttp.get( + FILE_ENDPOINTS.mine, + { params: { page, limit }, signal }, + ); + return toFilePagePayload(response); + }, + + async delete(id: string): Promise { + await postFilesHttp.delete( + FILE_ENDPOINTS.detail(id), + ); + }, +}; diff --git a/platforms/market/src/features/post/repositories/file/index.ts b/platforms/market/src/features/post/repositories/file/index.ts new file mode 100644 index 0000000..e20cd22 --- /dev/null +++ b/platforms/market/src/features/post/repositories/file/index.ts @@ -0,0 +1,9 @@ +export { FILE_ENDPOINTS, fileKeys } from './constants'; +export { fileRepository } from './file'; +export type { + FilePagePayload, + FilePayload, + ListMyFilesArgs, + UploadFileArgs, + UploadFileOptions, +} from './types'; diff --git a/platforms/market/src/features/post/repositories/file/mappers.ts b/platforms/market/src/features/post/repositories/file/mappers.ts new file mode 100644 index 0000000..38a0260 --- /dev/null +++ b/platforms/market/src/features/post/repositories/file/mappers.ts @@ -0,0 +1,41 @@ +import { toApiUrl } from '../../../../shared/utils'; +import type { + FilePagePayload, + FilePayload, + FileResponseDto, + ListMyFilesResponseDto, + UploadFileArgs, +} from './types'; + +/** Multipart: `visibility` first, then the file. Always `private`: the API rejects public post media. */ +export function toUploadFileFormData(args: UploadFileArgs): FormData { + const form = new FormData(); + form.append('visibility', 'private'); + form.append('file', args.file); + return form; +} + +export function toFilePayload(dto: FileResponseDto): FilePayload { + return { + id: dto.id, + kind: dto.kind, + visibility: dto.visibility, + name: dto.originalName, + mimeType: dto.mimeType, + sizeBytes: dto.sizeBytes, + status: dto.status, + url: toApiUrl(dto.url) ?? dto.url, + createdAt: dto.createdAt, + }; +} + +export function toFilePagePayload( + dto: ListMyFilesResponseDto, +): FilePagePayload { + return { + items: dto.items.map(toFilePayload), + total: dto.total, + page: dto.page, + limit: dto.limit, + }; +} diff --git a/platforms/market/src/features/post/repositories/file/types.ts b/platforms/market/src/features/post/repositories/file/types.ts new file mode 100644 index 0000000..d572a67 --- /dev/null +++ b/platforms/market/src/features/post/repositories/file/types.ts @@ -0,0 +1,51 @@ +import type { UploadProgress } from '@lumina/libs/http'; + +import type { + FileEntity, + FileKind, + FileStatus, + FileVisibility, +} from '../../entities/file'; + +/** One of the signed-in user's files. */ +export type FilePayload = { + id: string; + kind: FileKind; + visibility: FileVisibility; + /** The name it was uploaded with. */ + name: string; + mimeType: string; + sizeBytes: number; + /** Only a `ready` image can go on a post. */ + status: FileStatus; + /** Absolute; a private file streams to its owner only. */ + url: string; + createdAt: string; +}; + +export type FileResponseDto = FileEntity; + +/** An image for a post. Post media must be `private`, so that is what the upload sends. */ +export type UploadFileArgs = { file: File }; + +export type UploadFileOptions = { + onProgress?: (progress: UploadProgress) => void; + signal?: AbortSignal; +}; + +export type ListMyFilesArgs = { page?: number; limit?: number }; +export type ListMyFilesResponseDto = { + items: FileEntity[]; + total: number; + page: number; + limit: number; +}; +/** A page of files, newest first, as the API pages them. */ +export type FilePagePayload = { + items: FilePayload[]; + total: number; + page: number; + limit: number; +}; + +export type DeleteFileResponseDto = { success: true }; diff --git a/platforms/market/src/features/post/repositories/post/constants.ts b/platforms/market/src/features/post/repositories/post/constants.ts new file mode 100644 index 0000000..5678bd9 --- /dev/null +++ b/platforms/market/src/features/post/repositories/post/constants.ts @@ -0,0 +1,22 @@ +import type { ListCreatorPostsArgs } from './types'; + +const post = (id: string) => `/posts/${encodeURIComponent(id)}`; + +export const POST_ENDPOINTS = { + create: '/posts', + detail: post, + purge: (id: string) => `${post(id)}/purge`, + creatorPosts: (creatorId: string) => + `/creators/${encodeURIComponent(creatorId)}/posts`, +} as const; + +/** The page size lists ask for, so a server-rendered first page and the next pages agree. */ +export const POST_PAGE_LIMIT = 20; + +export const postKeys = { + all: ['post'] as const, + details: () => [...postKeys.all, 'detail'] as const, + detail: (id: string) => [...postKeys.details(), id] as const, + lists: () => [...postKeys.all, 'list'] as const, + list: (args: ListCreatorPostsArgs) => [...postKeys.lists(), args] as const, +}; diff --git a/platforms/market/src/features/post/repositories/post/index.ts b/platforms/market/src/features/post/repositories/post/index.ts new file mode 100644 index 0000000..8a65f52 --- /dev/null +++ b/platforms/market/src/features/post/repositories/post/index.ts @@ -0,0 +1,20 @@ +export { POST_ENDPOINTS, POST_PAGE_LIMIT, postKeys } from './constants'; +export { toPostPayload } from './mappers'; +export { postRepository } from './post'; +export type { + CreatePostArgs, + DeletedPostPayload, + ListCreatorPostsArgs, + LockedPostPayload, + LockedPredictionPayload, + PostImagePayload, + PostImagePreviewPayload, + PostMediaArgs, + PostPagePayload, + PostPayload, + PredictionArgs, + PredictionPayload, + PurgedPostPayload, + UnlockedPostPayload, + UpdatePostArgs, +} from './types'; diff --git a/platforms/market/src/features/post/repositories/post/mappers.ts b/platforms/market/src/features/post/repositories/post/mappers.ts new file mode 100644 index 0000000..f0210a2 --- /dev/null +++ b/platforms/market/src/features/post/repositories/post/mappers.ts @@ -0,0 +1,137 @@ +import { toApiUrl } from '../../../../shared/utils'; +import type { PostMediaEntity, PredictionEntity } from '../../entities/post'; +import type { + CreatePostArgs, + CreatePostDto, + DeletedPostPayload, + DeletePostResponseDto, + PostImagePayload, + PostPagePayload, + PostPageResponseDto, + PostPayload, + PostResponseDto, + PredictionArgs, + PredictionDto, + PredictionPayload, + PurgedPostPayload, + PurgePostResponseDto, + UpdatePostArgs, + UpdatePostDto, +} from './types'; + +export function toPredictionPayload( + entity: PredictionEntity, +): PredictionPayload { + return { + symbol: entity.symbol, + market: entity.market, + direction: entity.direction, + entryPrice: entity.entryPrice, + targetPrices: entity.targetPrices, + stopLoss: entity.stopLoss ?? null, + horizon: entity.horizon, + expiresAt: entity.expiresAt ?? null, + status: entity.status, + outcome: entity.outcome ?? null, + closedPrice: entity.closedPrice ?? null, + closedAt: entity.closedAt ?? null, + }; +} + +function toPostImagePayload(entity: PostMediaEntity): PostImagePayload { + return { + fileId: entity.fileId, + url: toApiUrl(entity.url) ?? entity.url, + order: entity.order, + width: entity.width ?? null, + height: entity.height ?? null, + }; +} + +/** For sibling features: feed and prediction map the posts they receive with it. */ +export function toPostPayload(dto: PostResponseDto): PostPayload { + const base = { + id: dto.id, + creatorId: dto.creatorId, + type: dto.type, + accessLevel: dto.accessLevel, + status: dto.status, + createdAt: dto.createdAt, + publishedAt: dto.publishedAt ?? null, + }; + if (dto.locked) { + return { + ...base, + locked: true, + captionPreview: dto.captionPreview ?? null, + mediaPreview: dto.mediaPreview.map(({ order, width, height }) => ({ + order, + width: width ?? null, + height: height ?? null, + })), + mediaCount: dto.mediaCount, + prediction: dto.prediction + ? { + symbol: dto.prediction.symbol, + direction: dto.prediction.direction, + status: dto.prediction.status, + } + : null, + }; + } + return { + ...base, + locked: false, + caption: dto.caption ?? null, + media: dto.media.map(toPostImagePayload), + prediction: dto.prediction ? toPredictionPayload(dto.prediction) : null, + }; +} + +export function toPostPagePayload(dto: PostPageResponseDto): PostPagePayload { + return { + items: dto.items.map(toPostPayload), + total: dto.total, + page: dto.page, + limit: dto.limit, + }; +} + +function toPredictionDto(args: PredictionArgs): PredictionDto { + return { + symbol: args.symbol.trim().toUpperCase(), + market: args.market.trim(), + direction: args.direction, + entryPrice: args.entryPrice, + targetPrices: args.targetPrices, + stopLoss: args.stopLoss ?? undefined, + horizon: args.horizon.trim(), + expiresAt: args.expiresAt ?? undefined, + }; +} + +export function toUpdatePostDto(args: UpdatePostArgs): UpdatePostDto { + return { + caption: args.caption?.trim(), + accessLevel: args.accessLevel, + status: args.status, + media: args.media?.map(({ fileId, order }) => ({ fileId, order })), + prediction: args.prediction && toPredictionDto(args.prediction), + }; +} + +export function toCreatePostDto(args: CreatePostArgs): CreatePostDto { + return { type: args.type, ...toUpdatePostDto(args) }; +} + +export function toDeletedPostPayload( + dto: DeletePostResponseDto, +): DeletedPostPayload { + return { id: dto.id, deletedAt: dto.deletedAt }; +} + +export function toPurgedPostPayload( + dto: PurgePostResponseDto, +): PurgedPostPayload { + return { id: dto.id }; +} diff --git a/platforms/market/src/features/post/repositories/post/post.ts b/platforms/market/src/features/post/repositories/post/post.ts new file mode 100644 index 0000000..7538b74 --- /dev/null +++ b/platforms/market/src/features/post/repositories/post/post.ts @@ -0,0 +1,86 @@ +import { postHttp } from '../../http'; +import { POST_ENDPOINTS } from './constants'; +import { + toCreatePostDto, + toDeletedPostPayload, + toPostPagePayload, + toPostPayload, + toPurgedPostPayload, + toUpdatePostDto, +} from './mappers'; +import type { + CreatePostArgs, + DeletedPostPayload, + DeletePostResponseDto, + ListCreatorPostsArgs, + PostPagePayload, + PostPageResponseDto, + PostPayload, + PostResponseDto, + PurgedPostPayload, + PurgePostResponseDto, + UpdatePostArgs, +} from './types'; + +/** + * Posts. Reads work without a session: a premium post the viewer is not subscribed to comes back + * locked (`locked: true`, a teaser), and a draft is a 404 for anyone but its creator. Writes are + * the creator's own posts only; another creator's post is a 404. Request field names match the + * `*Args` names, so field errors need no renaming. + */ +export const postRepository = { + async get( + id: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await postHttp.get( + POST_ENDPOINTS.detail(id), + { signal }, + ); + return toPostPayload(response); + }, + + /** Newest published first; the creator also sees their drafts, newest written first. */ + async listByCreator( + { creatorId, page, limit }: ListCreatorPostsArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await postHttp.get( + POST_ENDPOINTS.creatorPosts(creatorId), + { params: { page, limit }, signal }, + ); + return toPostPagePayload(response); + }, + + /** Needs a completed creator profile (403 otherwise). */ + async create(args: CreatePostArgs): Promise { + const response = await postHttp.post( + POST_ENDPOINTS.create, + toCreatePostDto(args), + ); + return toPostPayload(response); + }, + + async update(id: string, args: UpdatePostArgs): Promise { + const response = await postHttp.patch( + POST_ENDPOINTS.detail(id), + toUpdatePostDto(args), + ); + return toPostPayload(response); + }, + + async delete(id: string): Promise { + const response = await postHttp.delete( + POST_ENDPOINTS.detail(id), + ); + return toDeletedPostPayload(response); + }, + + /** Only after `delete`; destroys the post's files too. */ + async purge(id: string): Promise { + const response = await postHttp.delete( + POST_ENDPOINTS.purge(id), + ); + return toPurgedPostPayload(response); + }, +}; diff --git a/platforms/market/src/features/post/repositories/post/types.ts b/platforms/market/src/features/post/repositories/post/types.ts new file mode 100644 index 0000000..80638c8 --- /dev/null +++ b/platforms/market/src/features/post/repositories/post/types.ts @@ -0,0 +1,182 @@ +import type { + PostAccessLevel, + PostEntity, + PostStatus, + PostType, + PredictionDirection, + PredictionOutcome, + PredictionStatus, +} from '../../entities/post'; + +/** + * A prediction as the UI uses it; it fits the island PredictionCard's `PredictionData` as is. + * `market` is the raw key (`crypto`, `gold`), so the UI translates it before rendering. + */ +export type PredictionPayload = { + symbol: string; + market: string; + direction: PredictionDirection; + entryPrice: number; + /** Nearest first; the last one is the final target. */ + targetPrices: number[]; + stopLoss: number | null; + /** `1d`, `1w`, `3d`: formatted by the UI. */ + horizon: string; + expiresAt: string | null; + status: PredictionStatus; + /** Set once closed. */ + outcome: PredictionOutcome | null; + closedPrice: number | null; + closedAt: string | null; +}; + +/** A locked premium prediction's frame: the API sends nothing else, not even the outcome. */ +export type LockedPredictionPayload = { + symbol: string; + direction: PredictionDirection; + status: PredictionStatus; +}; + +/** One image of an image post. `url` is absolute and paywalled: it streams with the viewer's cookies. */ +export type PostImagePayload = { + fileId: string; + url: string; + order: number; + width: number | null; + height: number | null; +}; + +/** A locked image's box, to size its placeholder. The API's blurHash is dropped: it is never drawn. */ +export type PostImagePreviewPayload = { + order: number; + width: number | null; + height: number | null; +}; + +type PostPayloadBase = { + id: string; + creatorId: string; + type: PostType; + accessLevel: PostAccessLevel; + /** `draft` reaches its creator only; no read returns `deleted`. */ + status: PostStatus; + createdAt: string; + /** `null` on a draft. */ + publishedAt: string | null; +}; + +/** A post the viewer may read in full: free, or premium for its creator and active subscribers. */ +export type UnlockedPostPayload = PostPayloadBase & { + locked: false; + caption: string | null; + /** Image posts only; empty otherwise. */ + media: PostImagePayload[]; + /** Prediction posts only; `null` on a draft saved without one. */ + prediction: PredictionPayload | null; +}; + +/** A premium post for anyone else: the teaser, with the caption cut to 140 characters. */ +export type LockedPostPayload = PostPayloadBase & { + locked: true; + captionPreview: string | null; + mediaPreview: PostImagePreviewPayload[]; + mediaCount: number; + prediction: LockedPredictionPayload | null; +}; + +/** + * A post as the viewer may see it, told apart by `locked`. The API does not include the author: + * pair `creatorId` with the creator's profile for the username and avatar. + */ +export type PostPayload = UnlockedPostPayload | LockedPostPayload; + +export type PostResponseDto = PostEntity; + +/** A page of posts, as the API pages them. */ +export type PostPagePayload = { + items: PostPayload[]; + total: number; + page: number; + limit: number; +}; + +export type ListCreatorPostsArgs = { + creatorId: string; + /** From 1; the API defaults to 1. */ + page?: number; + /** The API defaults to 20. */ + limit?: number; +}; +export type PostPageResponseDto = { + items: PostEntity[]; + total: number; + page: number; + limit: number; +}; + +export type PostMediaArgs = { fileId: string; order?: number }; + +export type PredictionArgs = { + symbol: string; + market: string; + direction: PredictionDirection; + entryPrice: number; + targetPrices: number[]; + stopLoss?: number | null; + horizon: string; + /** ISO 8601. */ + expiresAt?: string | null; +}; + +/** + * A new post. A draft may be incomplete; publishing requires a caption (text), at least one + * image (image) or the prediction (prediction). Images are files from `fileRepository.upload`. + */ +export type CreatePostArgs = { + type: PostType; + caption?: string; + /** Defaults to `free`. */ + accessLevel?: PostAccessLevel; + /** Defaults to `published`. */ + status?: Exclude; + media?: PostMediaArgs[]; + prediction?: PredictionArgs; +}; + +/** + * A partial edit; only the keys given change. `status: 'published'` publishes a draft (one way); + * `prediction` is editable only while the post is a draft. + */ +export type UpdatePostArgs = Partial>; + +export type PostMediaDto = { fileId: string; order?: number }; +export type PredictionDto = { + symbol: string; + market: string; + direction: PredictionDirection; + entryPrice: number; + targetPrices: number[]; + stopLoss?: number; + horizon: string; + expiresAt?: string; +}; +export type UpdatePostDto = { + caption?: string; + accessLevel?: PostAccessLevel; + status?: Exclude; + media?: PostMediaDto[]; + prediction?: PredictionDto; +}; +export type CreatePostDto = UpdatePostDto & { type: PostType }; + +export type DeletePostResponseDto = { + id: string; + status: 'deleted'; + deletedAt: string; +}; +/** Soft-deleted: hidden from every read, files kept until a purge. */ +export type DeletedPostPayload = { id: string; deletedAt: string }; + +export type PurgePostResponseDto = { id: string; purged: true }; +/** Erased for good, with its files. */ +export type PurgedPostPayload = { id: string }; diff --git a/platforms/market/src/features/prediction/caches/.gitkeep b/platforms/market/src/features/prediction/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/prediction/caches/prediction-stats.ts b/platforms/market/src/features/prediction/caches/prediction-stats.ts new file mode 100644 index 0000000..e8d6946 --- /dev/null +++ b/platforms/market/src/features/prediction/caches/prediction-stats.ts @@ -0,0 +1,12 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { predictionRepository } from '../repositories/prediction'; +import type { PredictionStatsPayload } from '../repositories/prediction'; + +/** A creator's public track record, read once per render. */ +export const getPredictionStats = cache( + async (creatorId: string): Promise => + predictionRepository.getStats(creatorId), +); diff --git a/platforms/market/src/features/prediction/caches/server.ts b/platforms/market/src/features/prediction/caches/server.ts new file mode 100644 index 0000000..b08a7bf --- /dev/null +++ b/platforms/market/src/features/prediction/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getPredictionStats } from './prediction-stats'; diff --git a/platforms/market/src/features/prediction/entities/.gitkeep b/platforms/market/src/features/prediction/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/prediction/entities/prediction-stats/index.ts b/platforms/market/src/features/prediction/entities/prediction-stats/index.ts new file mode 100644 index 0000000..31eaac4 --- /dev/null +++ b/platforms/market/src/features/prediction/entities/prediction-stats/index.ts @@ -0,0 +1 @@ +export type { PredictionStatsEntity } from './types'; diff --git a/platforms/market/src/features/prediction/entities/prediction-stats/types.ts b/platforms/market/src/features/prediction/entities/prediction-stats/types.ts new file mode 100644 index 0000000..7b87d51 --- /dev/null +++ b/platforms/market/src/features/prediction/entities/prediction-stats/types.ts @@ -0,0 +1,23 @@ +import type { PredictionOutcome } from '../../../post'; + +/** + * content-service `getCreatorPredictionStats`: a creator's track record over their published + * predictions. Always answered, zeros included; there is no activation or hidden flag. + */ +export type PredictionStatsEntity = { + creatorId: string; + /** Published predictions, open and closed. */ + totalPredictions: number; + activePredictions: number; + /** Closed: wins + losses + breakeven. */ + pastPredictions: number; + wins: number; + losses: number; + breakeven: number; + /** A percentage with two decimals (`62.86`); 0 before the first close. */ + winRate: number; + /** The mean ROI of closed predictions, a percentage with two decimals. */ + avgRoiPercent: number; + /** The last 10 closed outcomes, oldest first. */ + accuracyTrend: PredictionOutcome[]; +}; diff --git a/platforms/market/src/features/prediction/http.ts b/platforms/market/src/features/prediction/http.ts new file mode 100644 index 0000000..d82f47e --- /dev/null +++ b/platforms/market/src/features/prediction/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const predictionHttp = http.extend({}); diff --git a/platforms/market/src/features/prediction/index.ts b/platforms/market/src/features/prediction/index.ts new file mode 100644 index 0000000..9bc60af --- /dev/null +++ b/platforms/market/src/features/prediction/index.ts @@ -0,0 +1,9 @@ +export { + PREDICTION_ENDPOINTS, + predictionKeys, + predictionRepository, +} from './repositories/prediction'; +export type { + ClosePredictionArgs, + PredictionStatsPayload, +} from './repositories/prediction'; diff --git a/platforms/market/src/features/prediction/repositories/.gitkeep b/platforms/market/src/features/prediction/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/prediction/repositories/prediction/constants.ts b/platforms/market/src/features/prediction/repositories/prediction/constants.ts new file mode 100644 index 0000000..dff67f0 --- /dev/null +++ b/platforms/market/src/features/prediction/repositories/prediction/constants.ts @@ -0,0 +1,11 @@ +export const PREDICTION_ENDPOINTS = { + close: (postId: string) => `/posts/${encodeURIComponent(postId)}/close`, + stats: (creatorId: string) => + `/creators/${encodeURIComponent(creatorId)}/prediction-stats`, +} as const; + +export const predictionKeys = { + all: ['prediction'] as const, + stats: (creatorId: string) => + [...predictionKeys.all, 'stats', creatorId] as const, +}; diff --git a/platforms/market/src/features/prediction/repositories/prediction/index.ts b/platforms/market/src/features/prediction/repositories/prediction/index.ts new file mode 100644 index 0000000..a3fdb8c --- /dev/null +++ b/platforms/market/src/features/prediction/repositories/prediction/index.ts @@ -0,0 +1,3 @@ +export { PREDICTION_ENDPOINTS, predictionKeys } from './constants'; +export { predictionRepository } from './prediction'; +export type { ClosePredictionArgs, PredictionStatsPayload } from './types'; diff --git a/platforms/market/src/features/prediction/repositories/prediction/mappers.ts b/platforms/market/src/features/prediction/repositories/prediction/mappers.ts new file mode 100644 index 0000000..a63fadc --- /dev/null +++ b/platforms/market/src/features/prediction/repositories/prediction/mappers.ts @@ -0,0 +1,29 @@ +import type { + ClosePredictionArgs, + ClosePredictionDto, + PredictionStatsPayload, + PredictionStatsResponseDto, +} from './types'; + +export function toClosePredictionDto( + args: ClosePredictionArgs, +): ClosePredictionDto { + return { closedPrice: args.closedPrice }; +} + +export function toPredictionStatsPayload( + dto: PredictionStatsResponseDto, +): PredictionStatsPayload { + return { + creatorId: dto.creatorId, + winRate: dto.winRate, + avgRoiPercent: dto.avgRoiPercent, + totalPredictions: dto.totalPredictions, + activePredictions: dto.activePredictions, + closedPredictions: dto.pastPredictions, + wins: dto.wins, + losses: dto.losses, + breakeven: dto.breakeven, + accuracyTrend: dto.accuracyTrend, + }; +} diff --git a/platforms/market/src/features/prediction/repositories/prediction/prediction.ts b/platforms/market/src/features/prediction/repositories/prediction/prediction.ts new file mode 100644 index 0000000..8eee6e9 --- /dev/null +++ b/platforms/market/src/features/prediction/repositories/prediction/prediction.ts @@ -0,0 +1,42 @@ +import { toPostPayload } from '../../../post'; +import type { PostPayload } from '../../../post'; +import { predictionHttp } from '../../http'; +import { PREDICTION_ENDPOINTS } from './constants'; +import { toClosePredictionDto, toPredictionStatsPayload } from './mappers'; +import type { + ClosePredictionArgs, + ClosePredictionResponseDto, + PredictionStatsPayload, + PredictionStatsResponseDto, +} from './types'; + +/** + * Prediction tracking. The prediction itself lives on its post (`PredictionPayload` in the post + * feature); this closes it and reads the creator's track record. Request field names match the + * `*Args` names. + */ +export const predictionRepository = { + /** + * The creator closes their own published, open prediction at a price; the API records the + * outcome and returns the updated post. A draft or an already closed prediction is a 400. + */ + async close(postId: string, args: ClosePredictionArgs): Promise { + const response = await predictionHttp.post( + PREDICTION_ENDPOINTS.close(postId), + toClosePredictionDto(args), + ); + return toPostPayload(response); + }, + + /** Public: no session needed. */ + async getStats( + creatorId: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await predictionHttp.get( + PREDICTION_ENDPOINTS.stats(creatorId), + { signal }, + ); + return toPredictionStatsPayload(response); + }, +}; diff --git a/platforms/market/src/features/prediction/repositories/prediction/types.ts b/platforms/market/src/features/prediction/repositories/prediction/types.ts new file mode 100644 index 0000000..5dd2ce5 --- /dev/null +++ b/platforms/market/src/features/prediction/repositories/prediction/types.ts @@ -0,0 +1,32 @@ +import type { PostEntity, PredictionOutcome } from '../../../post'; +import type { PredictionStatsEntity } from '../../entities/prediction-stats'; + +/** The price the creator closes at; the API derives the outcome from it. */ +export type ClosePredictionArgs = { closedPrice: number }; +export type ClosePredictionDto = { closedPrice: number }; +/** The closed post, always in full (the creator's own). */ +export type ClosePredictionResponseDto = PostEntity; + +/** + * A creator's track record; it fits the island CreatorStats' `CreatorStatsData` as is, with + * `trendOrder="oldest-first"`. The API has no activation threshold or hidden flag, so it always + * answers, zeros included. + */ +export type PredictionStatsPayload = { + creatorId: string; + /** A percentage: `62.86`. */ + winRate: number; + /** A percentage over closed predictions. */ + avgRoiPercent: number; + /** Published, open and closed. */ + totalPredictions: number; + activePredictions: number; + /** The API's `pastPredictions`: wins + losses + breakeven. */ + closedPredictions: number; + wins: number; + losses: number; + breakeven: number; + /** The last 10 closed outcomes, oldest first. */ + accuracyTrend: PredictionOutcome[]; +}; +export type PredictionStatsResponseDto = PredictionStatsEntity; diff --git a/platforms/market/src/features/pricing/caches/.gitkeep b/platforms/market/src/features/pricing/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/pricing/caches/pricing-form.ts b/platforms/market/src/features/pricing/caches/pricing-form.ts new file mode 100644 index 0000000..f26481c --- /dev/null +++ b/platforms/market/src/features/pricing/caches/pricing-form.ts @@ -0,0 +1,14 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { pricingRepository } from '../repositories/pricing'; +import type { PricingFormPayload } from '../repositories/pricing'; + +/** + * The signed-in creator's C7 pricing form, once per render. Throws the API's error as is: 401 + * without a session, 403 for a non-creator or an incomplete creator profile. + */ +export const getPricingForm = cache( + (): Promise => pricingRepository.getForm(), +); diff --git a/platforms/market/src/features/pricing/caches/server.ts b/platforms/market/src/features/pricing/caches/server.ts new file mode 100644 index 0000000..1d3c822 --- /dev/null +++ b/platforms/market/src/features/pricing/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getPricingForm } from './pricing-form'; diff --git a/platforms/market/src/features/pricing/entities/.gitkeep b/platforms/market/src/features/pricing/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/pricing/entities/pricing-tier/index.ts b/platforms/market/src/features/pricing/entities/pricing-tier/index.ts new file mode 100644 index 0000000..fda6fad --- /dev/null +++ b/platforms/market/src/features/pricing/entities/pricing-tier/index.ts @@ -0,0 +1,6 @@ +export type { + PricingCooldownEntity, + PricingRuleErrorEntity, + PricingTierEntity, + PricingTierPromotionEntity, +} from './types'; diff --git a/platforms/market/src/features/pricing/entities/pricing-tier/types.ts b/platforms/market/src/features/pricing/entities/pricing-tier/types.ts new file mode 100644 index 0000000..46d05f3 --- /dev/null +++ b/platforms/market/src/features/pricing/entities/pricing-tier/types.ts @@ -0,0 +1,62 @@ +import type { BillingPeriod } from '../../../../shared/constants'; + +/** A slot's promotion on the C7 form (`PricingService.toFormTier().promotion`). */ +export type PricingTierPromotionEntity = { + enabled: boolean; + percent: number | null; + startsAt: string | null; + endsAt: string | null; + indefinite: boolean; + live: boolean; + priceToman: number | null; + perMonthToman: number | null; + computedPriceFa: string | null; + sectionLabelFa: string; + percentLabelFa: string; + startLabelFa: string; + endLabelFa: string; + indefiniteLabelFa: string; + newSubscriptionsOnlyNoteFa: string; +}; + +/** One of the four C7 slots (`PricingService.toFormTier`). Money is whole Toman. */ +export type PricingTierEntity = { + billingPeriod: BillingPeriod; + labelFa: string; + mandatory: boolean; + enabled: boolean; + toggleable: boolean; + id: string | null; + priceToman: number | null; + perMonthToman: number | null; + perMonthEquivalentFa: string | null; + floorTomanPerMonth: number; + floorHelperFa: string; + priceFieldLabelFa: string; + suggestedPriceToman: number | null; + suggestionHintFa: string | null; + prefillSuggestion: boolean; + activeSubscribers: number; + disableNoteFa: string | null; + promotion: PricingTierPromotionEntity; +}; + +/** The standing-price cooldown that starts with the first purchase (`PricingService.getCooldown`). */ +export type PricingCooldownEntity = { + locked: boolean; + editableAt: string | null; + noticeFa: string | null; + prePurchaseNoteFa: string | null; + existingSubscribersNoteFa: string; + promotionsEditable: boolean; +}; + +/** + * A broken pricing rule (`PricingService.collectErrors`). `field` is relative to the slot: + * `enabled`, `priceToman`, `promotion.percent` or `promotion.endsAt`. + */ +export type PricingRuleErrorEntity = { + billingPeriod: BillingPeriod | null; + field: string; + messageFa: string; +}; diff --git a/platforms/market/src/features/pricing/http.ts b/platforms/market/src/features/pricing/http.ts new file mode 100644 index 0000000..e29c5db --- /dev/null +++ b/platforms/market/src/features/pricing/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const pricingHttp = http.extend({}); diff --git a/platforms/market/src/features/pricing/index.ts b/platforms/market/src/features/pricing/index.ts new file mode 100644 index 0000000..c4af5c1 --- /dev/null +++ b/platforms/market/src/features/pricing/index.ts @@ -0,0 +1,14 @@ +export { pricingKeys, pricingRepository } from './repositories/pricing'; +export type { + GetPricingFormArgs, + PricingConfirmationPayload, + PricingFieldName, + PricingFormPayload, + PricingPromotionArgs, + PricingTierArgs, + PricingTierField, + PricingTierPayload, + PricingTierPromotionPayload, + PricingValidationPayload, + SavePricingArgs, +} from './repositories/pricing'; diff --git a/platforms/market/src/features/pricing/repositories/.gitkeep b/platforms/market/src/features/pricing/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/pricing/repositories/pricing/constants.ts b/platforms/market/src/features/pricing/repositories/pricing/constants.ts new file mode 100644 index 0000000..b246e95 --- /dev/null +++ b/platforms/market/src/features/pricing/repositories/pricing/constants.ts @@ -0,0 +1,36 @@ +import { BILLING_PERIODS } from '../../../../shared/constants'; +import type { GetPricingFormArgs, PricingTierField } from './types'; + +export const PRICING_ENDPOINTS = { + form: '/subscriptions/pricing', + validate: '/subscriptions/pricing/validate', + save: '/subscriptions/pricing', +} as const; + +const TIER_FIELDS: readonly PricingTierField[] = [ + 'enabled', + 'priceToman', + 'promotion', + 'promotion.enabled', + 'promotion.percent', + 'promotion.startsAt', + 'promotion.endsAt', + 'promotion.indefinite', +]; + +/** DTO validation names (`tiers.3.priceToman`) → `PricingFieldName` (`tiers.yearly.priceToman`). */ +export const PRICING_FIELD_NAMES: Readonly> = + Object.fromEntries( + BILLING_PERIODS.flatMap((period, index) => + TIER_FIELDS.map((field) => [ + `tiers.${index}.${field}`, + `tiers.${period}.${field}`, + ]), + ), + ); + +export const pricingKeys = { + all: ['pricing'] as const, + form: (args: GetPricingFormArgs = {}) => + [...pricingKeys.all, 'form', args] as const, +}; diff --git a/platforms/market/src/features/pricing/repositories/pricing/index.ts b/platforms/market/src/features/pricing/repositories/pricing/index.ts new file mode 100644 index 0000000..96205f6 --- /dev/null +++ b/platforms/market/src/features/pricing/repositories/pricing/index.ts @@ -0,0 +1,15 @@ +export { pricingKeys } from './constants'; +export { pricingRepository } from './pricing'; +export type { + GetPricingFormArgs, + PricingConfirmationPayload, + PricingFieldName, + PricingFormPayload, + PricingPromotionArgs, + PricingTierArgs, + PricingTierField, + PricingTierPayload, + PricingTierPromotionPayload, + PricingValidationPayload, + SavePricingArgs, +} from './types'; diff --git a/platforms/market/src/features/pricing/repositories/pricing/mappers.ts b/platforms/market/src/features/pricing/repositories/pricing/mappers.ts new file mode 100644 index 0000000..726f4ce --- /dev/null +++ b/platforms/market/src/features/pricing/repositories/pricing/mappers.ts @@ -0,0 +1,130 @@ +import { BILLING_PERIODS } from '../../../../shared/constants'; +import type { + PricingRuleErrorEntity, + PricingTierEntity, +} from '../../entities/pricing-tier'; +import type { + PricingFormPayload, + PricingFormResponseDto, + PricingPromotionArgs, + PricingPromotionDto, + PricingTierPayload, + PricingValidationPayload, + PricingValidationResponseDto, + SavePricingArgs, + SavePricingDto, +} from './types'; + +function toPricingTierPayload(dto: PricingTierEntity): PricingTierPayload { + return { + id: dto.id, + billingPeriod: dto.billingPeriod, + mandatory: dto.mandatory, + toggleable: dto.toggleable, + enabled: dto.enabled, + priceToman: dto.priceToman, + perMonthToman: dto.perMonthToman, + floorTomanPerMonth: dto.floorTomanPerMonth, + suggestedPriceToman: dto.suggestedPriceToman, + prefillSuggestion: dto.prefillSuggestion, + activeSubscribers: dto.activeSubscribers, + promotion: { + enabled: dto.promotion.enabled, + percent: dto.promotion.percent, + startsAt: dto.promotion.startsAt, + endsAt: dto.promotion.endsAt, + indefinite: dto.promotion.indefinite, + live: dto.promotion.live, + priceToman: dto.promotion.priceToman, + perMonthToman: dto.promotion.perMonthToman, + }, + }; +} + +export function toPricingFormPayload( + dto: PricingFormResponseDto, +): PricingFormPayload { + return { + firstTimeSetup: dto.firstTimeSetup, + verification: { + status: dto.verification.status, + canBeSubscribedTo: dto.verification.canBeSubscribedTo, + }, + cooldown: { + locked: dto.cooldown.locked, + editableAt: dto.cooldown.editableAt, + promotionsEditable: dto.cooldown.promotionsEditable, + }, + tiers: dto.tiers.map(toPricingTierPayload), + }; +} + +function toPricingPromotionDto( + args: PricingPromotionArgs | null, +): PricingPromotionDto | undefined { + if (!args) return undefined; + return { + enabled: args.enabled, + percent: args.percent ?? undefined, + startsAt: args.startsAt ?? undefined, + endsAt: args.indefinite ? undefined : (args.endsAt ?? undefined), + indefinite: args.indefinite, + }; +} + +/** All four periods, in `BILLING_PERIODS` order (the form always sends all four), so DTO error indexes map back to periods. */ +export function toSavePricingDto(args: SavePricingArgs): SavePricingDto { + return { + tiers: BILLING_PERIODS.map((billingPeriod) => { + const tier = args.tiers[billingPeriod]; + return { + billingPeriod, + enabled: tier.enabled, + priceToman: tier.priceToman ?? undefined, + promotion: toPricingPromotionDto(tier.promotion), + }; + }), + }; +} + +/** Rule errors → `tiers..` field errors, first message per field. */ +export function toPricingFieldErrors( + errors: readonly PricingRuleErrorEntity[], +): Record { + const fieldErrors: Record = {}; + for (const { billingPeriod, field, messageFa } of errors) { + const name = billingPeriod ? `tiers.${billingPeriod}.${field}` : field; + fieldErrors[name] ??= messageFa; + } + return fieldErrors; +} + +/** The rule errors a rejected save carries in its error `details.errors`, if any. */ +export function pricingRuleErrorsOf( + details: Record | undefined, +): PricingRuleErrorEntity[] | null { + const errors = details?.errors; + return Array.isArray(errors) && errors.length > 0 + ? (errors as PricingRuleErrorEntity[]) + : null; +} + +export function toPricingValidationPayload( + dto: PricingValidationResponseDto, +): PricingValidationPayload { + if (!dto.valid || !dto.confirmation) { + return { valid: false, fieldErrors: toPricingFieldErrors(dto.errors) }; + } + return { + valid: true, + confirmation: { + tiers: dto.confirmation.tiers.map((tier) => ({ + billingPeriod: tier.billingPeriod, + priceToman: tier.priceToman, + promotion: tier.promotion + ? { percent: tier.promotion.percent, live: tier.promotion.live } + : null, + })), + }, + }; +} diff --git a/platforms/market/src/features/pricing/repositories/pricing/pricing.ts b/platforms/market/src/features/pricing/repositories/pricing/pricing.ts new file mode 100644 index 0000000..2d32be8 --- /dev/null +++ b/platforms/market/src/features/pricing/repositories/pricing/pricing.ts @@ -0,0 +1,82 @@ +import { HttpError, isHttpError } from '@lumina/libs/http'; + +import { renameFieldErrors } from '../../../../shared/utils'; +import { pricingHttp } from '../../http'; +import { PRICING_ENDPOINTS, PRICING_FIELD_NAMES } from './constants'; +import { + pricingRuleErrorsOf, + toPricingFieldErrors, + toPricingFormPayload, + toPricingValidationPayload, + toSavePricingDto, +} from './mappers'; +import type { + GetPricingFormArgs, + PricingFormPayload, + PricingFormResponseDto, + PricingValidationPayload, + PricingValidationResponseDto, + SavedPricingResponseDto, + SavePricingArgs, +} from './types'; + +/** + * A rejected save carries its rule errors in `details.errors`; DTO errors arrive as + * `tiers..`. Both become `tiers..` field errors. + */ +function toSaveError(error: unknown): unknown { + if (!isHttpError(error)) return error; + const ruleErrors = pricingRuleErrorsOf(error.details); + if (!ruleErrors) return renameFieldErrors(error, PRICING_FIELD_NAMES); + return new HttpError({ + ...error.toJSON(), + code: 'VALIDATION', + fieldErrors: toPricingFieldErrors(ruleErrors), + cause: error, + }); +} + +/** + * The signed-in creator's C7 pricing: four fixed period slots (monthly is mandatory), per-month + * floors, suggestions and promotions. 403 until the creator profile is complete. Standing prices + * lock for a cooldown after the first purchase (a save that changes them is a 409); promotions + * stay editable. + */ +export const pricingRepository = { + async getForm( + args: GetPricingFormArgs = {}, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await pricingHttp.get( + PRICING_ENDPOINTS.form, + { params: { monthlyPriceToman: args.monthlyPriceToman }, signal }, + ); + return toPricingFormPayload(response); + }, + + /** Checks a draft without saving; a valid one returns what the confirmation step shows. */ + async validate(args: SavePricingArgs): Promise { + try { + const response = await pricingHttp.post( + PRICING_ENDPOINTS.validate, + toSavePricingDto(args), + ); + return toPricingValidationPayload(response); + } catch (error) { + throw renameFieldErrors(error, PRICING_FIELD_NAMES); + } + }, + + /** Saves the draft and returns the refreshed form. Broken rules throw `tiers..` field errors. */ + async save(args: SavePricingArgs): Promise { + try { + const response = await pricingHttp.put( + PRICING_ENDPOINTS.save, + toSavePricingDto(args), + ); + return toPricingFormPayload(response); + } catch (error) { + throw toSaveError(error); + } + }, +}; diff --git a/platforms/market/src/features/pricing/repositories/pricing/types.ts b/platforms/market/src/features/pricing/repositories/pricing/types.ts new file mode 100644 index 0000000..e0f32b1 --- /dev/null +++ b/platforms/market/src/features/pricing/repositories/pricing/types.ts @@ -0,0 +1,196 @@ +import type { + BillingPeriod, + VerificationStatus, +} from '../../../../shared/constants'; +import type { + PricingCooldownEntity, + PricingRuleErrorEntity, + PricingTierEntity, +} from '../../entities/pricing-tier'; + +// Money is whole Toman everywhere; dates are ISO strings. + +// GET /subscriptions/pricing + +export type GetPricingFormArgs = { + /** Previews the longer periods' suggestions for this monthly price before it is saved. */ + monthlyPriceToman?: number; +}; + +export type PricingFormResponseDto = { + headingFa: string; + monthlyMandatoryNoteFa: string; + existingSubscribersNoteFa: string; + firstTimeSetup: boolean; + verification: { + status: VerificationStatus; + canBeSubscribedTo: boolean; + noteFa: string | null; + }; + cooldown: PricingCooldownEntity; + copy: { + headingFa: string; + pendingVerificationNoteFa: string; + monthlyMandatoryNoteFa: string; + blockedSaveMessageFa: string; + saveSuccessFa: string; + networkErrorFa: string; + confirmHeadingFa: string; + confirmCtaFa: string; + cancelCtaFa: string; + }; + tiers: PricingTierEntity[]; +}; + +/** A slot's promotion as saved. `live` means it applies to new subscriptions right now. */ +export type PricingTierPromotionPayload = { + enabled: boolean; + percent: number | null; + startsAt: string | null; + endsAt: string | null; + indefinite: boolean; + live: boolean; + /** The promotional period total, while `live`. */ + priceToman: number | null; + perMonthToman: number | null; +}; + +/** One of the four C7 slots. `priceToman` is the period total, prefilled from suggestions on first setup. */ +export type PricingTierPayload = { + /** The tier's id once it has been saved. */ + id: string | null; + billingPeriod: BillingPeriod; + /** Monthly is always on: mandatory and not toggleable. */ + mandatory: boolean; + toggleable: boolean; + enabled: boolean; + priceToman: number | null; + perMonthToman: number | null; + /** The lowest allowed price per month for this period. */ + floorTomanPerMonth: number; + /** Monthly × duration minus the period's discount, from the saved (or previewed) monthly price. */ + suggestedPriceToman: number | null; + prefillSuggestion: boolean; + activeSubscribers: number; + promotion: PricingTierPromotionPayload; +}; + +/** The creator's C7 pricing form: the four slots in period order, verification and cooldown. */ +export type PricingFormPayload = { + /** Nothing has been priced yet; the longer periods carry the suggestions as prices. */ + firstTimeSetup: boolean; + verification: { + status: VerificationStatus; + canBeSubscribedTo: boolean; + }; + cooldown: { + /** Standing prices are frozen until `editableAt`; promotions stay editable. */ + locked: boolean; + editableAt: string | null; + promotionsEditable: boolean; + }; + tiers: PricingTierPayload[]; +}; + +// POST /subscriptions/pricing/validate and PUT /subscriptions/pricing + +export type PricingPromotionArgs = { + enabled: boolean; + percent: number | null; + startsAt: string | null; + /** Ignored when `indefinite`. */ + endsAt: string | null; + indefinite: boolean; +}; + +export type PricingTierArgs = { + enabled: boolean; + /** The period total; `null` while the field is empty. */ + priceToman: number | null; + promotion: PricingPromotionArgs | null; +}; + +/** The whole C7 form, one entry per period. */ +export type SavePricingArgs = { tiers: Record }; + +/** Per-slot fields a server error can point at. */ +export type PricingTierField = + | 'enabled' + | 'priceToman' + | 'promotion' + | 'promotion.enabled' + | 'promotion.percent' + | 'promotion.startsAt' + | 'promotion.endsAt' + | 'promotion.indefinite'; + +/** A field error key: `tiers..`, e.g. `tiers.yearly.promotion.percent`. */ +export type PricingFieldName = `tiers.${BillingPeriod}.${PricingTierField}`; + +export type PricingPromotionDto = { + enabled: boolean; + percent?: number; + startsAt?: string; + endsAt?: string; + indefinite?: boolean; +}; + +export type PricingTierDto = { + billingPeriod: BillingPeriod; + enabled: boolean; + priceToman?: number; + promotion?: PricingPromotionDto; +}; + +export type SavePricingDto = { tiers: PricingTierDto[] }; + +export type PricingConfirmationTierResponseDto = { + billingPeriod: BillingPeriod; + labelFa: string; + priceToman: number; + priceFa: string; + perMonthSuffixFa: string; + promotion: { + percent: number; + lineFa: string; + equivalentFa: string; + live: boolean; + } | null; +}; + +export type PricingValidationResponseDto = { + valid: boolean; + errors: PricingRuleErrorEntity[]; + blockedSaveMessageFa: string | null; + confirmation: { + headingFa: string; + cooldownWarningFa: string; + safetyValveNoteFa: string; + promotionExemptionNoteFa: string; + confirmCtaFa: string; + cancelCtaFa: string; + tiers: PricingConfirmationTierResponseDto[]; + } | null; +}; + +/** What the creator confirms before saving: each enabled, priced slot. */ +export type PricingConfirmationPayload = { + tiers: { + billingPeriod: BillingPeriod; + priceToman: number; + promotion: { percent: number; live: boolean } | null; + }[]; +}; + +/** + * A draft checked without saving. Invalid drafts carry `fieldErrors` keyed by `PricingFieldName` + * (first message per field), the same keys a rejected save throws. + */ +export type PricingValidationPayload = + | { valid: true; confirmation: PricingConfirmationPayload } + | { valid: false; fieldErrors: Record }; + +/** PUT answers with the refreshed form plus a success line. */ +export type SavedPricingResponseDto = PricingFormResponseDto & { + successMessageFa: string; +}; diff --git a/platforms/market/src/features/profile/caches/.gitkeep b/platforms/market/src/features/profile/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/profile/caches/my-profile.ts b/platforms/market/src/features/profile/caches/my-profile.ts new file mode 100644 index 0000000..a0e68bb --- /dev/null +++ b/platforms/market/src/features/profile/caches/my-profile.ts @@ -0,0 +1,14 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { profileRepository } from '../repositories/profile'; +import type { CreatorProfilePayload } from '../repositories/profile'; + +/** + * The signed-in creator's own profile for this request, one request per render. 401 and 403 reach + * the caller (`readOnServer` turns them into login and no-access). + */ +export const getMyCreatorProfile = cache( + (): Promise => profileRepository.getMine(), +); diff --git a/platforms/market/src/features/profile/caches/server.ts b/platforms/market/src/features/profile/caches/server.ts new file mode 100644 index 0000000..7a8bfc4 --- /dev/null +++ b/platforms/market/src/features/profile/caches/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { getMyCreatorProfile } from './my-profile'; diff --git a/platforms/market/src/features/profile/constants.ts b/platforms/market/src/features/profile/constants.ts new file mode 100644 index 0000000..bad4282 --- /dev/null +++ b/platforms/market/src/features/profile/constants.ts @@ -0,0 +1,36 @@ +import type { Market, TradingStyle } from './entities/creator-profile'; + +/** Every market, in the server's order, for pickers. */ +export const MARKETS: readonly Market[] = [ + 'crypto', + 'gold', + 'equities', + 'forex', + 'funds', + 'real_estate', + 'automotive', + 'USDT', +]; + +/** Every trading style, in the server's order, for pickers. */ +export const TRADING_STYLES: readonly TradingStyle[] = [ + 'scalping', + 'day_trading', + 'swing', + 'position', + 'algorithmic', + 'discretionary', + 'options', +]; + +/** The server's profile rules (`CREATOR_PROFILE_LIMITS`), so forms reject what the API would. */ +export const PROFILE_LIMITS = { + displayNameMaxLength: 80, + bioMaxLength: 300, + bioMaxLineBreaks: 3, + socialLinkLabelMaxLength: 30, + socialLinkUrlMaxLength: 2048, + socialLinksMax: 8, + avatarMaxBytes: 5 * 1024 * 1024, + avatarMimeTypes: ['image/jpeg', 'image/png'], +} as const; diff --git a/platforms/market/src/features/profile/entities/.gitkeep b/platforms/market/src/features/profile/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/profile/entities/creator-profile/index.ts b/platforms/market/src/features/profile/entities/creator-profile/index.ts new file mode 100644 index 0000000..c09a3fb --- /dev/null +++ b/platforms/market/src/features/profile/entities/creator-profile/index.ts @@ -0,0 +1,7 @@ +export type { + CreatorProfileEntity, + KycStatus, + Market, + SocialLinkEntity, + TradingStyle, +} from './types'; diff --git a/platforms/market/src/features/profile/entities/creator-profile/types.ts b/platforms/market/src/features/profile/entities/creator-profile/types.ts new file mode 100644 index 0000000..4f881a5 --- /dev/null +++ b/platforms/market/src/features/profile/entities/creator-profile/types.ts @@ -0,0 +1,64 @@ +import type { VerificationStatus } from '../../../../shared/constants'; + +/** The markets a creator analyses (`MARKETS` in creator-profile-setup.dto). `USDT` is the dollar/tether market. */ +export type Market = + | 'crypto' + | 'gold' + | 'equities' + | 'forex' + | 'funds' + | 'real_estate' + | 'automotive' + | 'USDT'; + +/** How a creator trades (`TRADING_STYLES` in creator-profile-setup.dto). */ +export type TradingStyle = + | 'scalping' + | 'day_trading' + | 'swing' + | 'position' + | 'algorithmic' + | 'discretionary' + | 'options'; + +/** Lite KYC review of the national ID submitted at registration. */ +export type KycStatus = + | 'pending_review' + | 'approved' + | 'rejected' + | 'requires_resubmission' + | 'expired' + | 'suspended'; + +/** A stored social link; Mongo gives each one an `_id`. The server normalises `url` to `https://…`. */ +export type SocialLinkEntity = { label: string; url: string; _id?: string }; + +/** + * trader-service's `trader_profiles` document as `GET /traders/me/profile` sends it: the whole + * lean document plus the computed `profileComplete` (display name and at least one market). + */ +export type CreatorProfileEntity = { + _id: string; + userId: string; + username: string; + displayName?: string; + legalFullName?: string; + nationalIdNumber: string; + nationalIdFrontImage: string; + nationalIdBackImage: string; + dateOfBirth?: string; + country?: string; + kycStatus: KycStatus; + kycSubmittedAt: string; + verificationStatus: VerificationStatus; + bio?: string | null; + avatar?: string | null; + socialLinks?: SocialLinkEntity[]; + profileCompletedAt?: string; + tradingStyle?: TradingStyle | null; + markets: Market[]; + createdAt: string; + updatedAt: string; + __v: number; + profileComplete: boolean; +}; diff --git a/platforms/market/src/features/profile/http.ts b/platforms/market/src/features/profile/http.ts new file mode 100644 index 0000000..05b12cf --- /dev/null +++ b/platforms/market/src/features/profile/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const profileHttp = http.extend({}); diff --git a/platforms/market/src/features/profile/index.ts b/platforms/market/src/features/profile/index.ts new file mode 100644 index 0000000..e505862 --- /dev/null +++ b/platforms/market/src/features/profile/index.ts @@ -0,0 +1,14 @@ +export { MARKETS, PROFILE_LIMITS, TRADING_STYLES } from './constants'; +export type { + KycStatus, + Market, + TradingStyle, +} from './entities/creator-profile'; +export { profileKeys, profileRepository } from './repositories/profile'; +export type { + CreatorProfilePayload, + SocialLinkArgs, + SocialLinkPayload, + UpdateProfileArgs, + UploadAvatarArgs, +} from './repositories/profile'; diff --git a/platforms/market/src/features/profile/repositories/.gitkeep b/platforms/market/src/features/profile/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/profile/repositories/profile/constants.ts b/platforms/market/src/features/profile/repositories/profile/constants.ts new file mode 100644 index 0000000..547af3c --- /dev/null +++ b/platforms/market/src/features/profile/repositories/profile/constants.ts @@ -0,0 +1,12 @@ +export const PROFILE_ENDPOINTS = { + mine: '/traders/me/profile', + avatar: '/traders/me/profile/avatar', +} as const; + +/** The multipart field the avatar upload reads. */ +export const AVATAR_FIELD = 'avatar'; + +export const profileKeys = { + all: ['profile'] as const, + mine: () => [...profileKeys.all, 'mine'] as const, +}; diff --git a/platforms/market/src/features/profile/repositories/profile/index.ts b/platforms/market/src/features/profile/repositories/profile/index.ts new file mode 100644 index 0000000..3f51df3 --- /dev/null +++ b/platforms/market/src/features/profile/repositories/profile/index.ts @@ -0,0 +1,9 @@ +export { profileKeys } from './constants'; +export { profileRepository } from './profile'; +export type { + CreatorProfilePayload, + SocialLinkArgs, + SocialLinkPayload, + UpdateProfileArgs, + UploadAvatarArgs, +} from './types'; diff --git a/platforms/market/src/features/profile/repositories/profile/mappers.ts b/platforms/market/src/features/profile/repositories/profile/mappers.ts new file mode 100644 index 0000000..0db8107 --- /dev/null +++ b/platforms/market/src/features/profile/repositories/profile/mappers.ts @@ -0,0 +1,43 @@ +import { toApiUrl } from '../../../../shared/utils'; +import type { + CreatorProfilePayload, + CreatorProfileResponseDto, + UpdateProfileArgs, + UpdateProfileDto, +} from './types'; + +export function toCreatorProfilePayload( + dto: CreatorProfileResponseDto, +): CreatorProfilePayload { + return { + profileId: dto._id, + creatorId: dto.userId, + username: dto.username, + displayName: dto.displayName || null, + bio: dto.bio || null, + avatarUrl: toApiUrl(dto.avatar), + tradingStyle: dto.tradingStyle ?? null, + markets: dto.markets, + socialLinks: (dto.socialLinks ?? []).map(({ label, url }) => ({ + label, + url, + })), + verificationStatus: dto.verificationStatus, + kycStatus: dto.kycStatus, + kycSubmittedAt: dto.kycSubmittedAt, + profileComplete: dto.profileComplete, + }; +} + +export function toUpdateProfileDto(args: UpdateProfileArgs): UpdateProfileDto { + return { + displayName: args.displayName.trim(), + markets: args.markets, + bio: args.bio?.trim(), + tradingStyle: args.tradingStyle, + socialLinks: args.socialLinks?.map(({ label, url }) => ({ + label: label.trim(), + url: url.trim(), + })), + }; +} diff --git a/platforms/market/src/features/profile/repositories/profile/profile.ts b/platforms/market/src/features/profile/repositories/profile/profile.ts new file mode 100644 index 0000000..9bc00c6 --- /dev/null +++ b/platforms/market/src/features/profile/repositories/profile/profile.ts @@ -0,0 +1,63 @@ +import type { UploadProgress } from '@lumina/libs/http'; + +import { profileHttp } from '../../http'; +import { AVATAR_FIELD, PROFILE_ENDPOINTS } from './constants'; +import { toCreatorProfilePayload, toUpdateProfileDto } from './mappers'; +import type { + CreatorProfilePayload, + CreatorProfileResponseDto, + UpdateProfileArgs, + UploadAvatarArgs, +} from './types'; + +/** + * The signed-in creator's own profile (`/traders/me/profile`): 401 without a session, 403 for an + * investor. Writes answer 403 once verification is `rejected` (the profile is locked). Every call + * returns the whole updated profile. Field errors use the `*Args` names already; the avatar + * endpoints answer a wrong format or size with a plain 400 message. + */ +export const profileRepository = { + async getMine({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await profileHttp.get( + PROFILE_ENDPOINTS.mine, + { signal }, + ); + return toCreatorProfilePayload(response); + }, + + async update(args: UpdateProfileArgs): Promise { + const response = await profileHttp.put( + PROFILE_ENDPOINTS.mine, + toUpdateProfileDto(args), + ); + return toCreatorProfilePayload(response); + }, + + /** Uploads or replaces the avatar. */ + async uploadAvatar( + args: UploadAvatarArgs, + { + signal, + onProgress, + }: { + signal?: AbortSignal; + onProgress?: (progress: UploadProgress) => void; + } = {}, + ): Promise { + const response = await profileHttp.upload( + PROFILE_ENDPOINTS.avatar, + args.avatar, + { method: 'PUT', fieldName: AVATAR_FIELD, signal, onProgress }, + ); + return toCreatorProfilePayload(response); + }, + + async removeAvatar(): Promise { + const response = await profileHttp.delete( + PROFILE_ENDPOINTS.avatar, + ); + return toCreatorProfilePayload(response); + }, +}; diff --git a/platforms/market/src/features/profile/repositories/profile/types.ts b/platforms/market/src/features/profile/repositories/profile/types.ts new file mode 100644 index 0000000..041d06c --- /dev/null +++ b/platforms/market/src/features/profile/repositories/profile/types.ts @@ -0,0 +1,61 @@ +import type { VerificationStatus } from '../../../../shared/constants'; +import type { + CreatorProfileEntity, + KycStatus, + Market, + TradingStyle, +} from '../../entities/creator-profile'; + +/** A link on the creator's public page, e.g. `{ label: 'Telegram', url: 'https://t.me/…' }`. */ +export type SocialLinkPayload = { label: string; url: string }; + +/** + * The signed-in creator's own profile and verification state. National ID number and images stay + * out: no screen shows them after registration, and there is no API to resubmit them. + */ +export type CreatorProfilePayload = { + profileId: string; + /** The creator's account id; follow, tiers, posts and checkout all take this one. */ + creatorId: string; + username: string; + displayName: string | null; + bio: string | null; + avatarUrl: string | null; + tradingStyle: TradingStyle | null; + markets: Market[]; + socialLinks: SocialLinkPayload[]; + /** Only `approved` creators are public and can be subscribed to. */ + verificationStatus: VerificationStatus; + kycStatus: KycStatus; + kycSubmittedAt: string; + /** Display name and at least one market are set: the creator may publish. */ + profileComplete: boolean; +}; + +export type CreatorProfileResponseDto = CreatorProfileEntity; + +export type SocialLinkArgs = { label: string; url: string }; + +/** + * The profile setup form. Fields left out keep their stored value; `bio: ''` and + * `tradingStyle: null` clear them, and `socialLinks` replaces the whole list. URLs may omit + * `https://`; the server adds it. + */ +export type UpdateProfileArgs = { + displayName: string; + markets: Market[]; + bio?: string; + tradingStyle?: TradingStyle | null; + socialLinks?: SocialLinkArgs[]; +}; + +export type UpdateProfileDto = { + displayName: string; + markets: Market[]; + bio?: string; + tradingStyle?: TradingStyle | null; + socialLinks?: { label: string; url: string }[]; +}; + +/** A JPG or PNG of at most 5 MB (`PROFILE_LIMITS`). */ +export type UploadAvatarArgs = { avatar: File }; diff --git a/platforms/market/src/features/subscription/caches/.gitkeep b/platforms/market/src/features/subscription/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/subscription/caches/server.ts b/platforms/market/src/features/subscription/caches/server.ts new file mode 100644 index 0000000..ee9ec5c --- /dev/null +++ b/platforms/market/src/features/subscription/caches/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { getSubscriptionDashboard } from './subscription-dashboard'; +export { getSubscriptionDetail } from './subscription-detail'; diff --git a/platforms/market/src/features/subscription/caches/subscription-dashboard.ts b/platforms/market/src/features/subscription/caches/subscription-dashboard.ts new file mode 100644 index 0000000..97db942 --- /dev/null +++ b/platforms/market/src/features/subscription/caches/subscription-dashboard.ts @@ -0,0 +1,12 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { subscriptionRepository } from '../repositories/subscription'; +import type { SubscriptionDashboardPayload } from '../repositories/subscription'; + +/** The signed-in investor's اشتراک‌ها, once per render. Errors reach the page's `readOnServer`. */ +export const getSubscriptionDashboard = cache( + async (): Promise => + subscriptionRepository.getDashboard(), +); diff --git a/platforms/market/src/features/subscription/caches/subscription-detail.ts b/platforms/market/src/features/subscription/caches/subscription-detail.ts new file mode 100644 index 0000000..e1c6b7d --- /dev/null +++ b/platforms/market/src/features/subscription/caches/subscription-detail.ts @@ -0,0 +1,12 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { subscriptionRepository } from '../repositories/subscription'; +import type { SubscriptionDetailPayload } from '../repositories/subscription'; + +/** One subscription of the signed-in investor, once per render; someone else's is a 404. */ +export const getSubscriptionDetail = cache( + async (id: string): Promise => + subscriptionRepository.getDetail(id), +); diff --git a/platforms/market/src/features/subscription/entities/.gitkeep b/platforms/market/src/features/subscription/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/subscription/entities/subscription/index.ts b/platforms/market/src/features/subscription/entities/subscription/index.ts new file mode 100644 index 0000000..61ca092 --- /dev/null +++ b/platforms/market/src/features/subscription/entities/subscription/index.ts @@ -0,0 +1,7 @@ +export type { + InvestorSubscriptionEntity, + MoneyEntity, + RemainingTimeEntity, + SubscriptionCreatorEntity, + SubscriptionTierEntity, +} from './types'; diff --git a/platforms/market/src/features/subscription/entities/subscription/types.ts b/platforms/market/src/features/subscription/entities/subscription/types.ts new file mode 100644 index 0000000..553583c --- /dev/null +++ b/platforms/market/src/features/subscription/entities/subscription/types.ts @@ -0,0 +1,69 @@ +import type { + BillingPeriod, + SubscriptionRecordStatus, +} from '../../../../shared/constants'; + +/** subscription-service's `toMoney`. `toman` is `null` only for a non-Rial currency. */ +export type MoneyEntity = { + currency: string; + toman: number | null; + amountUnitFa: string; +}; + +/** The creator on a subscription card (`toCreatorCard`). `id` is the creator's user id. */ +export type SubscriptionCreatorEntity = { + id: string; + avatar: string | null; + username: string | null; + /** trader-service `kycStatus` (or `verificationStatus`) is `suspended`. */ + suspended: boolean; + noteFa: string | null; + /** `/traders/`, a back-end path; `null` while suspended. */ + channelLink: string | null; +}; + +/** The tier on a subscription card. `price` is Rial; `toman` is the tier's current price. */ +export type SubscriptionTierEntity = MoneyEntity & { + id: string; + name: string; + period: BillingPeriod; + labelFa: string; + price: number; +}; + +export type RemainingTimeEntity = { + /** Whole days, rounded up, at least 1. */ + daysRemaining: number; + labelFa: string; + color: 'ruby' | 'warning' | 'ink-mute'; + hex: string; +}; + +/** subscription-service's investor card (`toInvestorItem`). */ +export type InvestorSubscriptionEntity = { + id: string; + creator: SubscriptionCreatorEntity; + tier: SubscriptionTierEntity; + startDate: string | null; + startDateLabelFa: string; + expiryDate: string; + expiryDateLabelFa: string; + /** Only while active. */ + remainingTime: RemainingTimeEntity | null; + warning: { + show: boolean; + labelFa: string | null; + color: 'ruby' | null; + hex: string | null; + }; + status: { + value: SubscriptionRecordStatus; + labelFa: string; + color: 'primary' | 'ink-mute'; + hex: string; + }; + /** The last completed payment to this creator differs from the tier's current price. */ + priceChanged: boolean; + priceChangedNoteFa: string; + renewCta: { labelFa: string; subscriptionId: string; tierId: string | null }; +}; diff --git a/platforms/market/src/features/subscription/http.ts b/platforms/market/src/features/subscription/http.ts new file mode 100644 index 0000000..005cc2c --- /dev/null +++ b/platforms/market/src/features/subscription/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const subscriptionHttp = http.extend({}); diff --git a/platforms/market/src/features/subscription/index.ts b/platforms/market/src/features/subscription/index.ts new file mode 100644 index 0000000..a3e7ca1 --- /dev/null +++ b/platforms/market/src/features/subscription/index.ts @@ -0,0 +1,18 @@ +export { + subscriptionKeys, + subscriptionRepository, +} from './repositories/subscription'; +export type { + ReactivateArgs, + RenewalKind, + RenewalPreviewArgs, + RenewalPreviewPayload, + RenewalTierPayload, + RenewArgs, + SubscriptionCreatorPayload, + SubscriptionDashboardPayload, + SubscriptionDetailPayload, + SubscriptionPayload, + SubscriptionReceiptPayload, + SubscriptionStatus, +} from './repositories/subscription'; diff --git a/platforms/market/src/features/subscription/repositories/.gitkeep b/platforms/market/src/features/subscription/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/subscription/repositories/subscription/constants.ts b/platforms/market/src/features/subscription/repositories/subscription/constants.ts new file mode 100644 index 0000000..a8de019 --- /dev/null +++ b/platforms/market/src/features/subscription/repositories/subscription/constants.ts @@ -0,0 +1,23 @@ +const subscription = (id: string) => `/subscriptions/${encodeURIComponent(id)}`; + +export const SUBSCRIPTION_ENDPOINTS = { + dashboard: '/subscriptions/dashboard', + active: '/subscriptions/active', + expired: '/subscriptions/expired', + detail: subscription, + preview: (id: string) => `${subscription(id)}/preview`, + renew: (id: string) => `${subscription(id)}/renew`, + reactivate: (id: string) => `${subscription(id)}/reactivate`, +} as const; + +export const subscriptionKeys = { + all: ['subscription'] as const, + dashboard: () => [...subscriptionKeys.all, 'dashboard'] as const, + lists: () => [...subscriptionKeys.all, 'list'] as const, + list: (status: 'active' | 'expired') => + [...subscriptionKeys.lists(), status] as const, + details: () => [...subscriptionKeys.all, 'detail'] as const, + detail: (id: string) => [...subscriptionKeys.details(), id] as const, + preview: (id: string, tierId?: string) => + [...subscriptionKeys.detail(id), 'preview', tierId ?? null] as const, +}; diff --git a/platforms/market/src/features/subscription/repositories/subscription/index.ts b/platforms/market/src/features/subscription/repositories/subscription/index.ts new file mode 100644 index 0000000..c949a4d --- /dev/null +++ b/platforms/market/src/features/subscription/repositories/subscription/index.ts @@ -0,0 +1,16 @@ +export { subscriptionKeys } from './constants'; +export { subscriptionRepository } from './subscription'; +export type { + ReactivateArgs, + RenewalKind, + RenewalPreviewArgs, + RenewalPreviewPayload, + RenewalTierPayload, + RenewArgs, + SubscriptionCreatorPayload, + SubscriptionDashboardPayload, + SubscriptionDetailPayload, + SubscriptionPayload, + SubscriptionReceiptPayload, + SubscriptionStatus, +} from './types'; diff --git a/platforms/market/src/features/subscription/repositories/subscription/mappers.ts b/platforms/market/src/features/subscription/repositories/subscription/mappers.ts new file mode 100644 index 0000000..21c82d9 --- /dev/null +++ b/platforms/market/src/features/subscription/repositories/subscription/mappers.ts @@ -0,0 +1,118 @@ +import { toApiUrl } from '../../../../shared/utils'; +import type { + InvestorSubscriptionEntity, + SubscriptionCreatorEntity, +} from '../../entities/subscription'; +import type { + ReactivateArgs, + ReactivateDto, + RenewalPreviewArgs, + RenewalPreviewPayload, + RenewalPreviewQueryDto, + RenewalPreviewResponseDto, + RenewArgs, + RenewDto, + SubscriptionCreatorPayload, + SubscriptionDashboardPayload, + SubscriptionDashboardResponseDto, + SubscriptionDetailPayload, + SubscriptionDetailResponseDto, + SubscriptionPayload, +} from './types'; + +export function toSubscriptionCreatorPayload( + dto: SubscriptionCreatorEntity, +): SubscriptionCreatorPayload { + return { + id: dto.id, + username: dto.username, + avatarUrl: toApiUrl(dto.avatar), + suspended: dto.suspended, + }; +} + +export function toSubscriptionPayload( + dto: InvestorSubscriptionEntity, +): SubscriptionPayload { + const expired = dto.status.value === 'expired'; + return { + id: dto.id, + status: expired + ? 'expired' + : dto.creator.suspended + ? 'suspended' + : 'active', + creator: toSubscriptionCreatorPayload(dto.creator), + tier: { + id: dto.tier.id, + billingPeriod: dto.tier.period, + priceToman: dto.tier.toman, + }, + startsAt: dto.startDate, + endsAt: dto.expiryDate, + daysLeft: dto.remainingTime?.daysRemaining ?? null, + priceChanged: dto.priceChanged, + }; +} + +export function toSubscriptionDashboardPayload( + dto: SubscriptionDashboardResponseDto, +): SubscriptionDashboardPayload { + return { + activeCount: dto.summary.activeCount, + active: dto.active.map(toSubscriptionPayload), + expired: dto.expired.map(toSubscriptionPayload), + }; +} + +export function toSubscriptionDetailPayload( + dto: SubscriptionDetailResponseDto, +): SubscriptionDetailPayload { + const receipt = dto.lastReceipt; + return { + ...toSubscriptionPayload(dto), + lastReceipt: receipt + ? { + paymentId: receipt.paymentId, + reference: + receipt.trackingCode || receipt.refId || receipt.authority || null, + amountToman: receipt.toman, + } + : null, + }; +} + +export function toRenewalPreviewQueryDto( + args: RenewalPreviewArgs, +): RenewalPreviewQueryDto { + return args.tierId ? { tierId: args.tierId } : {}; +} + +export function toRenewalPreviewPayload( + dto: RenewalPreviewResponseDto, +): RenewalPreviewPayload { + return { + kind: dto.kind, + currentEndsAt: dto.currentExpiry, + currentTierId: dto.currentTierId, + selectedTierId: dto.selectedTierId, + creator: toSubscriptionCreatorPayload(dto.creator), + tiers: dto.tiers.map((tier) => ({ + id: tier.id, + billingPeriod: tier.billingPeriod, + amountToman: tier.toman, + selected: tier.selected, + periodFrom: tier.preview.from, + periodTo: tier.preview.to, + priceChanged: tier.priceChanged, + })), + }; +} + +export function toRenewDto(args: RenewArgs): RenewDto { + return args.tierId ? { tierId: args.tierId } : {}; +} + +export function toReactivateDto(args: ReactivateArgs): ReactivateDto { + return { tierId: args.tierId }; +} diff --git a/platforms/market/src/features/subscription/repositories/subscription/subscription.ts b/platforms/market/src/features/subscription/repositories/subscription/subscription.ts new file mode 100644 index 0000000..67b07a6 --- /dev/null +++ b/platforms/market/src/features/subscription/repositories/subscription/subscription.ts @@ -0,0 +1,127 @@ +import { + toCheckoutResultPayload, + toPriceChangedPayload, +} from '../../../checkout'; +import type { CheckoutResultPayload } from '../../../checkout'; +import { subscriptionHttp } from '../../http'; +import { SUBSCRIPTION_ENDPOINTS } from './constants'; +import { + toReactivateDto, + toRenewalPreviewPayload, + toRenewalPreviewQueryDto, + toRenewDto, + toSubscriptionDashboardPayload, + toSubscriptionDetailPayload, + toSubscriptionPayload, +} from './mappers'; +import type { + CheckoutResponseDto, + ReactivateArgs, + RenewalPreviewArgs, + RenewalPreviewPayload, + RenewalPreviewResponseDto, + RenewArgs, + SubscriptionDashboardPayload, + SubscriptionDashboardResponseDto, + SubscriptionDetailPayload, + SubscriptionDetailResponseDto, + SubscriptionListResponseDto, + SubscriptionPayload, +} from './types'; + +/** + * A renew or reactivate request, mapped as checkout maps subscribe. The 409 of a stale price is an + * outcome; every other error is thrown. + */ +async function checkout( + request: () => Promise, +): Promise { + try { + return toCheckoutResultPayload(await request()); + } catch (error) { + const priceChanged = toPriceChangedPayload(error); + if (priceChanged) return priceChanged; + throw error; + } +} + +/** + * The signed-in investor's subscriptions (U2/U3). Investor session only: a creator gets 403. A + * subscription of someone else is 404. Renew and reactivate answer 403 while the creator is + * suspended and 409 while a payment to that creator is still pending. + */ +export const subscriptionRepository = { + async getDashboard({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = + await subscriptionHttp.get( + SUBSCRIPTION_ENDPOINTS.dashboard, + { signal }, + ); + return toSubscriptionDashboardPayload(response); + }, + + async listActive({ signal }: { signal?: AbortSignal } = {}): Promise< + SubscriptionPayload[] + > { + const response = await subscriptionHttp.get( + SUBSCRIPTION_ENDPOINTS.active, + { signal }, + ); + return response.items.map(toSubscriptionPayload); + }, + + async listExpired({ signal }: { signal?: AbortSignal } = {}): Promise< + SubscriptionPayload[] + > { + const response = await subscriptionHttp.get( + SUBSCRIPTION_ENDPOINTS.expired, + { signal }, + ); + return response.items.map(toSubscriptionPayload); + }, + + async getDetail( + id: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await subscriptionHttp.get( + SUBSCRIPTION_ENDPOINTS.detail(id), + { signal }, + ); + return toSubscriptionDetailPayload(response); + }, + + /** The renew/reactivate sheet; `kind` follows the subscription, not the caller. */ + async getPreview( + args: RenewalPreviewArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await subscriptionHttp.get( + SUBSCRIPTION_ENDPOINTS.preview(args.subscriptionId), + { params: toRenewalPreviewQueryDto(args), signal }, + ); + return toRenewalPreviewPayload(response); + }, + + /** Extends from the current expiry. Outcomes: `granted` or `redirect`. */ + async renew(args: RenewArgs): Promise { + return checkout(() => + subscriptionHttp.post( + SUBSCRIPTION_ENDPOINTS.renew(args.subscriptionId), + toRenewDto(args), + ), + ); + }, + + /** Starts again from now; 400 while still active. Outcomes: `granted` or `redirect`. */ + async reactivate(args: ReactivateArgs): Promise { + return checkout(() => + subscriptionHttp.post( + SUBSCRIPTION_ENDPOINTS.reactivate(args.subscriptionId), + toReactivateDto(args), + ), + ); + }, +}; diff --git a/platforms/market/src/features/subscription/repositories/subscription/types.ts b/platforms/market/src/features/subscription/repositories/subscription/types.ts new file mode 100644 index 0000000..e8c88af --- /dev/null +++ b/platforms/market/src/features/subscription/repositories/subscription/types.ts @@ -0,0 +1,166 @@ +import type { BillingPeriod } from '../../../../shared/constants'; +import type { PublicTierEntity } from '../../../channel'; +import type { CheckoutResultEntity } from '../../../checkout'; +import type { + InvestorSubscriptionEntity, + MoneyEntity, + SubscriptionCreatorEntity, +} from '../../entities/subscription'; + +/** + * How a card reads, in the island SubscriptionCard's words. `suspended`: still running, but the + * creator's channel is suspended, so it stays in the active list. There is no `refunded` yet: the + * back end has no refunds. + */ +export type SubscriptionStatus = 'active' | 'suspended' | 'expired'; + +/** The creator behind a subscription. `id` is their user id; there is no display name. */ +export type SubscriptionCreatorPayload = { + id: string; + username: string | null; + avatarUrl: string | null; + /** The channel is blacked out: no link, and renew or reactivate answers 403. */ + suspended: boolean; +}; + +/** One subscription card of the investor (U2/U3). Dates are ISO. */ +export type SubscriptionPayload = { + id: string; + status: SubscriptionStatus; + creator: SubscriptionCreatorPayload; + /** `priceToman` is the tier's current price, not the amount paid (see `lastReceipt`). */ + tier: { id: string; billingPeriod: BillingPeriod; priceToman: number | null }; + startsAt: string | null; + endsAt: string; + /** While running (active or suspended): whole days left, rounded up, at least 1. */ + daysLeft: number | null; + /** The creator's price differs from what the investor last paid them. */ + priceChanged: boolean; +}; + +export type SubscriptionReceiptPayload = { + paymentId: string; + /** Tracking code, else bank ref, else authority; `null` for a development grant. */ + reference: string | null; + amountToman: number | null; +}; + +export type SubscriptionDetailPayload = SubscriptionPayload & { + /** The last completed payment of this subscription. */ + lastReceipt: SubscriptionReceiptPayload | null; +}; + +/** اشتراک‌ها: active cards by nearest expiry, then expired ones by latest expiry. */ +export type SubscriptionDashboardPayload = { + activeCount: number; + active: SubscriptionPayload[]; + expired: SubscriptionPayload[]; +}; + +export type SubscriptionDashboardResponseDto = { + labels: { + tabFa: string; + sectionFa: string; + startDateLabelFa: string; + expiryDateLabelFa: string; + }; + summary: { + activeCount: number; + labelFa: string; + empty: boolean; + showActiveEmpty: boolean; + emptyMessageFa: string; + emptyCta: { labelFa: string; href: string }; + }; + expiredSection: { show: boolean; headingFa: string }; + loadErrorFa: string; + active: InvestorSubscriptionEntity[]; + expired: InvestorSubscriptionEntity[]; +}; + +export type SubscriptionListResponseDto = { + items: InvestorSubscriptionEntity[]; +}; + +export type SubscriptionDetailResponseDto = InvestorSubscriptionEntity & { + lastReceipt: + | (MoneyEntity & { + paymentId: string; + authority: string | null; + refId: string | null; + trackingCode: string | null; + amount: number; + }) + | null; +}; + +/** Renew: a running subscription gets more time. Reactivate: an expired one starts again today. */ +export type RenewalKind = 'renew' | 'reactivate'; + +/** The renew/reactivate sheet. Without `tierId`, renew preselects the current tier, reactivate none. */ +export type RenewalPreviewArgs = { subscriptionId: string; tierId?: string }; + +export type RenewalPreviewQueryDto = { tierId?: string }; + +/** One period on the sheet, with the exact dates it would buy. */ +export type RenewalTierPayload = { + id: string; + billingPeriod: BillingPeriod; + /** What renew or reactivate charges: the standing price, as promotions apply to subscribe only. */ + amountToman: number | null; + selected: boolean; + /** Renew: from the current expiry. Reactivate: from now. */ + periodFrom: string; + periodTo: string; + priceChanged: boolean; +}; + +export type RenewalPreviewPayload = { + kind: RenewalKind; + currentEndsAt: string; + currentTierId: string; + selectedTierId: string | null; + creator: SubscriptionCreatorPayload; + tiers: RenewalTierPayload[]; +}; + +export type RenewalPreviewResponseDto = { + kind: RenewalKind; + currentExpiry: string; + currentTierId: string; + selectedTierId: string | null; + creator: SubscriptionCreatorEntity; + headingFa: string; + tierSelectionLabelFa: string; + totalAmountLabelFa: string; + paymentCtaFa: string; + successMessageFa: string; + paymentFailureFa: string; + networkErrorFa: string; + suspendedCreatorBlockFa: string; + priceChangedNoteFa: string; + currentStatementFa: string | null; + /** `toman` here is the charged (standing) price; `priceToman` may carry a subscribe-only promotion. */ + tiers: (PublicTierEntity & { + selected: boolean; + preview: { + from: string; + to: string; + fromLabelFa: string; + toLabelFa: string; + }; + amount: number; + priceChanged: boolean; + })[]; +}; + +/** Renew may switch to another period of the same creator; without one, the current tier. */ +export type RenewArgs = { subscriptionId: string; tierId?: string }; +export type RenewDto = { tierId?: string }; + +/** Reactivate always names the period. */ +export type ReactivateArgs = { subscriptionId: string; tierId: string }; +export type ReactivateDto = { tierId: string }; + +/** Renew and reactivate answer the checkout union (`startCheckout`); checkout's mapper reads it. */ +export type CheckoutResponseDto = CheckoutResultEntity; diff --git a/platforms/market/src/features/transaction/caches/.gitkeep b/platforms/market/src/features/transaction/caches/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/transaction/caches/payment-detail.ts b/platforms/market/src/features/transaction/caches/payment-detail.ts new file mode 100644 index 0000000..2e48462 --- /dev/null +++ b/platforms/market/src/features/transaction/caches/payment-detail.ts @@ -0,0 +1,15 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { transactionRepository } from '../repositories/transaction'; +import type { TransactionDetailPayload } from '../repositories/transaction'; + +/** + * One payment of the signed-in investor (جزئیات تراکنش, and the U10 result after the bank return), + * once per render; someone else's is a 404. + */ +export const getPaymentDetail = cache( + async (id: string): Promise => + transactionRepository.getDetail(id), +); diff --git a/platforms/market/src/features/transaction/caches/server.ts b/platforms/market/src/features/transaction/caches/server.ts new file mode 100644 index 0000000..fafdd72 --- /dev/null +++ b/platforms/market/src/features/transaction/caches/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { getPaymentDetail } from './payment-detail'; +export { getTransactionsFirstPage } from './transactions-first-page'; diff --git a/platforms/market/src/features/transaction/caches/transactions-first-page.ts b/platforms/market/src/features/transaction/caches/transactions-first-page.ts new file mode 100644 index 0000000..7820034 --- /dev/null +++ b/platforms/market/src/features/transaction/caches/transactions-first-page.ts @@ -0,0 +1,15 @@ +import 'server-only'; + +import { cache } from 'react'; + +import { transactionRepository } from '../repositories/transaction'; +import type { + TransactionFilter, + TransactionPagePayload, +} from '../repositories/transaction'; + +/** Page 1 of the signed-in investor's history for one status tab, once per render. */ +export const getTransactionsFirstPage = cache( + async (status: TransactionFilter = 'all'): Promise => + transactionRepository.list({ status, page: 1 }), +); diff --git a/platforms/market/src/features/transaction/entities/.gitkeep b/platforms/market/src/features/transaction/entities/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/transaction/entities/payment/index.ts b/platforms/market/src/features/transaction/entities/payment/index.ts new file mode 100644 index 0000000..e01223d --- /dev/null +++ b/platforms/market/src/features/transaction/entities/payment/index.ts @@ -0,0 +1,6 @@ +export type { + AccessConfirmationEntity, + PaymentCreatorEntity, + PaymentDetailEntity, + PaymentEntity, +} from './types'; diff --git a/platforms/market/src/features/transaction/entities/payment/types.ts b/platforms/market/src/features/transaction/entities/payment/types.ts new file mode 100644 index 0000000..6db6642 --- /dev/null +++ b/platforms/market/src/features/transaction/entities/payment/types.ts @@ -0,0 +1,101 @@ +import type { + BillingPeriod, + CheckoutKind, + ConfirmationLanding, + ConfirmationPhase, + PaymentStatus, + PaymentUiStatus, +} from '../../../../shared/constants'; + +/** + * subscription-service's `toAccessConfirmation`: where a payment stands after the bank return + * (U10). The payment detail and a granted checkout both send it. + */ +export type AccessConfirmationEntity = { + processingFa: string; + successToastFa: string; + pendingToastFa: string; + paymentFailureFa: string; + subscriberStatusFa: string | null; + /** `/traders/`, a back-end path. */ + channelLink: string | null; + phase: ConfirmationPhase; + landOn: ConfirmationLanding; + /** Set only for `failed`: what checkout reopens with. `traderId` is the creator's user id. */ + resume: { traderId: string; tierId: string } | null; +}; + +/** + * The creator as captured on the payment (`historical: true`), else read live. `id` is their + * user id. + */ +export type PaymentCreatorEntity = { + id: string; + username: string | null; + avatar: string | null; + historical: boolean; +}; + +/** + * One subscription payment (`toInvestorTransaction`). The investor history, the creator dashboard + * and the creator's payment list all send this row. `amount` is Rial, `toman` whole Toman. + */ +export type PaymentEntity = { + id: string; + /** The payer (the investor). */ + userId: string; + traderId: string; + creator: PaymentCreatorEntity; + tier: { + id: string; + name: string | null; + period: BillingPeriod; + labelFa: string; + }; + /** What the payment bought. */ + type: { value: CheckoutKind; labelFa: string }; + amount: number; + currency: string; + toman: number | null; + amountUnitFa: string; + amountLabelFa: string; + dateLabelFa: string; + createdAt: string | null; + status: { + value: PaymentUiStatus; + labelFa: string; + color: 'primary' | 'warning' | 'ruby'; + hex: string; + }; + rawStatus: PaymentStatus; + statusLabelFa: string; + noteFa: string | null; + /** `value`: tracking code, else bank ref, else authority. */ + reference: { value: string | null; labelFa: string }; + authority: string | null; + refId: string | null; + trackingCode: string | null; + provider: string; + providerRef: string | null; + subscriptionId: string | null; + billingPeriod: BillingPeriod; + /** The period bought; only on a successful payment. */ + period: { + from: string | null; + to: string | null; + labelFa: string | null; + } | null; +}; + +/** `GET /subscriptions/payments/:id`: the row plus the detail screen and the U10 confirmation. */ +export type PaymentDetailEntity = PaymentEntity & { + headingFa: string; + periodLabelFa: string; + loadErrorFa: string; + failedNoteFa: string | null; + pendingNoteFa: string | null; + messageFa: string | null; + supportCta: { labelFa: string } | null; + copyReferenceToastFa: string; + confirmation: AccessConfirmationEntity; +}; diff --git a/platforms/market/src/features/transaction/http.ts b/platforms/market/src/features/transaction/http.ts new file mode 100644 index 0000000..f6784b9 --- /dev/null +++ b/platforms/market/src/features/transaction/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const transactionHttp = http.extend({}); diff --git a/platforms/market/src/features/transaction/index.ts b/platforms/market/src/features/transaction/index.ts new file mode 100644 index 0000000..22473e9 --- /dev/null +++ b/platforms/market/src/features/transaction/index.ts @@ -0,0 +1,17 @@ +export type { + AccessConfirmationEntity, + PaymentEntity, +} from './entities/payment'; +export { + toAccessConfirmationPayload, + transactionKeys, + transactionRepository, +} from './repositories/transaction'; +export type { + AccessConfirmationPayload, + ListTransactionsArgs, + TransactionDetailPayload, + TransactionFilter, + TransactionPagePayload, + TransactionPayload, +} from './repositories/transaction'; diff --git a/platforms/market/src/features/transaction/repositories/.gitkeep b/platforms/market/src/features/transaction/repositories/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/transaction/repositories/transaction/constants.ts b/platforms/market/src/features/transaction/repositories/transaction/constants.ts new file mode 100644 index 0000000..d24ac1c --- /dev/null +++ b/platforms/market/src/features/transaction/repositories/transaction/constants.ts @@ -0,0 +1,16 @@ +import type { TransactionFilter } from './types'; + +export const TRANSACTION_ENDPOINTS = { + list: '/subscriptions/transactions', + detail: (id: string) => `/subscriptions/payments/${encodeURIComponent(id)}`, +} as const; + +export const transactionKeys = { + all: ['transaction'] as const, + lists: () => [...transactionKeys.all, 'list'] as const, + /** One infinite list per status tab; pages are its page params. */ + list: (status: TransactionFilter = 'all') => + [...transactionKeys.lists(), status] as const, + details: () => [...transactionKeys.all, 'detail'] as const, + detail: (id: string) => [...transactionKeys.details(), id] as const, +}; diff --git a/platforms/market/src/features/transaction/repositories/transaction/index.ts b/platforms/market/src/features/transaction/repositories/transaction/index.ts new file mode 100644 index 0000000..815d14c --- /dev/null +++ b/platforms/market/src/features/transaction/repositories/transaction/index.ts @@ -0,0 +1,11 @@ +export { transactionKeys } from './constants'; +export { toAccessConfirmationPayload } from './mappers'; +export { transactionRepository } from './transaction'; +export type { + AccessConfirmationPayload, + ListTransactionsArgs, + TransactionDetailPayload, + TransactionFilter, + TransactionPagePayload, + TransactionPayload, +} from './types'; diff --git a/platforms/market/src/features/transaction/repositories/transaction/mappers.ts b/platforms/market/src/features/transaction/repositories/transaction/mappers.ts new file mode 100644 index 0000000..74ad4e9 --- /dev/null +++ b/platforms/market/src/features/transaction/repositories/transaction/mappers.ts @@ -0,0 +1,80 @@ +import { toApiUrl } from '../../../../shared/utils'; +import type { + AccessConfirmationEntity, + PaymentEntity, +} from '../../entities/payment'; +import type { + AccessConfirmationPayload, + ListTransactionsArgs, + ListTransactionsQueryDto, + TransactionDetailPayload, + TransactionDetailResponseDto, + TransactionPagePayload, + TransactionPageResponseDto, + TransactionPayload, +} from './types'; + +export function toListTransactionsQueryDto( + args: ListTransactionsArgs, +): ListTransactionsQueryDto { + return { status: args.status ?? 'all', page: args.page ?? 1 }; +} + +export function toTransactionPayload(dto: PaymentEntity): TransactionPayload { + return { + id: dto.id, + creator: { + id: dto.creator.id, + username: dto.creator.username, + avatarUrl: toApiUrl(dto.creator.avatar), + }, + type: dto.type.value, + billingPeriod: dto.billingPeriod, + tierId: dto.tier.id, + amountToman: dto.toman, + createdAt: dto.createdAt, + status: dto.status.value, + rawStatus: dto.rawStatus, + reference: dto.reference.value, + subscriptionId: dto.subscriptionId, + period: dto.period ? { from: dto.period.from, to: dto.period.to } : null, + }; +} + +export function toTransactionPagePayload( + dto: TransactionPageResponseDto, +): TransactionPagePayload { + return { + status: dto.filter.value, + page: dto.page, + pageSize: dto.pageSize, + total: dto.total, + hasMore: dto.hasMore, + items: dto.items.map(toTransactionPayload), + }; +} + +/** For sibling features: checkout maps the confirmation of a granted checkout with it. */ +export function toAccessConfirmationPayload( + dto: AccessConfirmationEntity, +): AccessConfirmationPayload { + return { + phase: dto.phase, + landOn: dto.landOn, + resume: dto.resume + ? { creatorId: dto.resume.traderId, tierId: dto.resume.tierId } + : null, + }; +} + +export function toTransactionDetailPayload( + dto: TransactionDetailResponseDto, +): TransactionDetailPayload { + return { + ...toTransactionPayload(dto), + trackingCode: dto.trackingCode, + refId: dto.refId, + authority: dto.authority, + confirmation: toAccessConfirmationPayload(dto.confirmation), + }; +} diff --git a/platforms/market/src/features/transaction/repositories/transaction/transaction.ts b/platforms/market/src/features/transaction/repositories/transaction/transaction.ts new file mode 100644 index 0000000..031b9d5 --- /dev/null +++ b/platforms/market/src/features/transaction/repositories/transaction/transaction.ts @@ -0,0 +1,44 @@ +import { transactionHttp } from '../../http'; +import { TRANSACTION_ENDPOINTS } from './constants'; +import { + toListTransactionsQueryDto, + toTransactionDetailPayload, + toTransactionPagePayload, +} from './mappers'; +import type { + ListTransactionsArgs, + TransactionDetailPayload, + TransactionDetailResponseDto, + TransactionPagePayload, + TransactionPageResponseDto, +} from './types'; + +/** + * The signed-in investor's payment history (U4). Investor session only: a creator gets 403. Each + * read first expires stale pending payments on the server, so a row can turn `failed` between + * reads. Someone else's payment is a 404. + */ +export const transactionRepository = { + async list( + args: ListTransactionsArgs = {}, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await transactionHttp.get( + TRANSACTION_ENDPOINTS.list, + { params: toListTransactionsQueryDto(args), signal }, + ); + return toTransactionPagePayload(response); + }, + + /** One payment's receipt and U10 confirmation phase; poll it after the bank returns. */ + async getDetail( + id: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await transactionHttp.get( + TRANSACTION_ENDPOINTS.detail(id), + { signal }, + ); + return toTransactionDetailPayload(response); + }, +}; diff --git a/platforms/market/src/features/transaction/repositories/transaction/types.ts b/platforms/market/src/features/transaction/repositories/transaction/types.ts new file mode 100644 index 0000000..184915d --- /dev/null +++ b/platforms/market/src/features/transaction/repositories/transaction/types.ts @@ -0,0 +1,97 @@ +import type { + BillingPeriod, + CheckoutKind, + ConfirmationLanding, + ConfirmationPhase, + PaymentStatus, + PaymentUiStatus, +} from '../../../../shared/constants'; +import type { + PaymentDetailEntity, + PaymentEntity, +} from '../../entities/payment'; + +/** The history's status tabs. */ +export type TransactionFilter = 'all' | 'successful' | 'failed' | 'pending'; + +/** `page` starts at 1; the server sends 20 rows a page, pending ones always first. */ +export type ListTransactionsArgs = { + status?: TransactionFilter; + page?: number; +}; + +export type ListTransactionsQueryDto = { + status: TransactionFilter; + page: number; +}; + +/** One row of the investor's تراکنش‌ها (U4). Dates are ISO. */ +export type TransactionPayload = { + id: string; + /** As captured at payment time, so a later rename or suspension doesn't rewrite history. */ + creator: { id: string; username: string | null; avatarUrl: string | null }; + /** What the payment bought. */ + type: CheckoutKind; + billingPeriod: BillingPeriod; + tierId: string; + amountToman: number | null; + createdAt: string | null; + status: PaymentUiStatus; + /** The stored status behind `status`, e.g. `pending_review` or `cancelled`. */ + rawStatus: PaymentStatus; + /** Tracking code, else bank ref, else authority; `null` for a development grant. */ + reference: string | null; + subscriptionId: string | null; + /** The period bought; only on a successful payment. */ + period: { from: string | null; to: string | null } | null; +}; + +/** One page of the history, paginated exactly as the server does. */ +export type TransactionPagePayload = { + /** The filter the server applied (unknown values fall back to `all`). */ + status: TransactionFilter; + page: number; + pageSize: number; + total: number; + hasMore: boolean; + items: TransactionPayload[]; +}; + +export type TransactionPageResponseDto = { + labels: { tabFa: string; sectionFa: string }; + summary: { + empty: boolean; + emptyMessageFa: string; + emptyCta: { labelFa: string; href: string }; + }; + loadErrorFa: string; + filter: { + value: TransactionFilter; + labelFa: string; + options: { value: TransactionFilter; labelFa: string }[]; + }; + page: number; + pageSize: number; + total: number; + hasMore: boolean; + items: PaymentEntity[]; +}; + +/** U10: where a payment stands after the bank return and where the investor goes next. */ +export type AccessConfirmationPayload = { + phase: ConfirmationPhase; + landOn: ConfirmationLanding; + /** Set for `failed`: reopen checkout on this creator (their account id) and tier. */ + resume: { creatorId: string; tierId: string } | null; +}; + +/** جزئیات تراکنش, also the U10 payment result polled after the bank return. */ +export type TransactionDetailPayload = TransactionPayload & { + /** The bank's tracking code, ref id and authority behind `reference`; `null` for a development grant. */ + trackingCode: string | null; + refId: string | null; + authority: string | null; + confirmation: AccessConfirmationPayload; +}; + +export type TransactionDetailResponseDto = PaymentDetailEntity; diff --git a/platforms/market/src/index.ts b/platforms/market/src/index.ts index 2219612..dd329d1 100644 --- a/platforms/market/src/index.ts +++ b/platforms/market/src/index.ts @@ -1,2 +1,238 @@ // Public client-safe API. Re-export each module by name; never `export *`. -export {}; +export { AppShell } from './app/app-shell'; +export type { AppShellProps } from './app/app-shell'; +export { + ErrorFallback, + PartBoundary, + StatusEmptyState, +} from './app/error-boundaries'; +export type { + ErrorFallbackProps, + ErrorFallbackSize, + FallbackKind, + PartBoundaryProps, + StatusEmptyStateProps, + StatusVariant, +} from './app/error-boundaries'; +export { mapApiErrorBody } from './app/http'; +export type { ApiErrorEnvelope } from './app/http'; +export { CHANNEL_PREFIX, loginRoute, ROUTES } from './app/navigation'; +export { SESSION_COOKIES, SESSION_REFRESH_ENDPOINT } from './app/session'; +export { getEnv, setEnv } from './env'; +export type { MarketEnv } from './env'; +export { + DEFAULT_LOCALE, + DEFAULT_NAMESPACE, + NAMESPACES, + resources, +} from './shared/locales'; +export { + accountKeys, + accountRepository, + AUTH_ENDPOINTS, + AUTH_EVENTS, + authRepository, + login, + logout, + registerCreator, + registerInvestor, +} from './features/auth'; +export type { + AccountPayload, + CreatorRegisteredPayload, + LogoutReason, + OtpSentPayload, + RegisterCreatorArgs, + RegisterInvestorArgs, + RegistrationVerifiedPayload, + SendOtpArgs, + SessionPayload, + UpdateAccountArgs, + UserRole, + UserStatus, + VerifyOtpArgs, +} from './features/auth'; +export { renameFieldErrors, toApiUrl, toE164Mobile } from './shared/utils'; +export { + BILLING_PERIODS, + CHECKOUT_KINDS, + COMPARE_SOURCES, + CONFIRMATION_LANDINGS, + CONFIRMATION_PHASES, + PAYMENT_STATUSES, + PAYMENT_UI_STATUSES, + SUBSCRIPTION_RECORD_STATUSES, + VERIFICATION_STATUSES, +} from './shared/constants'; +export type { + BillingPeriod, + CheckoutKind, + CompareSource, + ConfirmationLanding, + ConfirmationPhase, + PaymentStatus, + PaymentUiStatus, + SubscriptionRecordStatus, + VerificationStatus, +} from './shared/constants'; +export { + MARKETS, + PROFILE_LIMITS, + profileKeys, + profileRepository, + TRADING_STYLES, +} from './features/profile'; +export type { + CreatorProfilePayload, + KycStatus, + Market, + SocialLinkArgs, + SocialLinkPayload, + TradingStyle, + UpdateProfileArgs, + UploadAvatarArgs, +} from './features/profile'; +export { channelKeys, channelRepository } from './features/channel'; +export type { + ChannelArgs, + PublicCreatorPayload, + PublicTierPayload, + TierPromotionPayload, +} from './features/channel'; +export { followKeys, followRepository } from './features/follow'; +export type { + FollowArgs, + FollowChangePayload, + FollowStatusPayload, +} from './features/follow'; +export { + notificationKeys, + notificationRepository, + UNREAD_BADGE_CAP, +} from './features/notification'; +export type { + InboxPayload, + MarkReadArgs, + NotificationPayload, + NotificationType, + UnreadCountPayload, +} from './features/notification'; +export { + FILE_ENDPOINTS, + fileKeys, + fileRepository, + POST_ENDPOINTS, + POST_PAGE_LIMIT, + postKeys, + postRepository, +} from './features/post'; +export type { + CreatePostArgs, + DeletedPostPayload, + FileKind, + FilePagePayload, + FilePayload, + FileStatus, + FileVisibility, + ListCreatorPostsArgs, + ListMyFilesArgs, + LockedPostPayload, + LockedPredictionPayload, + PostAccessLevel, + PostImagePayload, + PostImagePreviewPayload, + PostMediaArgs, + PostPagePayload, + PostPayload, + PostStatus, + PostType, + PredictionArgs, + PredictionDirection, + PredictionOutcome, + PredictionPayload, + PredictionStatus, + PurgedPostPayload, + UnlockedPostPayload, + UpdatePostArgs, + UploadFileArgs, + UploadFileOptions, +} from './features/post'; +export { + PREDICTION_ENDPOINTS, + predictionKeys, + predictionRepository, +} from './features/prediction'; +export type { + ClosePredictionArgs, + PredictionStatsPayload, +} from './features/prediction'; +export { + FEED_ENDPOINT, + FEED_PAGE_LIMIT, + feedKeys, + feedRepository, +} from './features/feed'; +export type { FeedPayload, ListFeedArgs } from './features/feed'; +export { pricingKeys, pricingRepository } from './features/pricing'; +export type { + GetPricingFormArgs, + PricingConfirmationPayload, + PricingFieldName, + PricingFormPayload, + PricingPromotionArgs, + PricingTierArgs, + PricingTierField, + PricingTierPayload, + PricingTierPromotionPayload, + PricingValidationPayload, + SavePricingArgs, +} from './features/pricing'; +export { checkoutKeys, checkoutRepository } from './features/checkout'; +export type { + CheckoutCtaState, + CheckoutPayload, + CheckoutResultPayload, + CheckoutTierPayload, + GrantedSubscriptionPayload, + PriceChangedPayload, + ReferralCodeArgs, + ReferralCodeStatus, + ReferralValidationPayload, + SubscribeArgs, + WaitlistJoinedPayload, +} from './features/checkout'; +export { + subscriptionKeys, + subscriptionRepository, +} from './features/subscription'; +export type { + ReactivateArgs, + RenewalKind, + RenewalPreviewArgs, + RenewalPreviewPayload, + RenewalTierPayload, + RenewArgs, + SubscriptionCreatorPayload, + SubscriptionDashboardPayload, + SubscriptionDetailPayload, + SubscriptionPayload, + SubscriptionReceiptPayload, + SubscriptionStatus, +} from './features/subscription'; +export { transactionKeys, transactionRepository } from './features/transaction'; +export type { + AccessConfirmationPayload, + ListTransactionsArgs, + TransactionDetailPayload, + TransactionFilter, + TransactionPagePayload, + TransactionPayload, +} from './features/transaction'; +export { creatorDashboardRepository, overviewKeys } from './features/overview'; +export type { + CreatorDashboardPayload, + CreatorTierPayload, + RecentPaymentPayload, +} from './features/overview'; +export { creatorPaymentRepository, financeKeys } from './features/finance'; +export type { CreatorPaymentPayload } from './features/finance'; diff --git a/platforms/market/src/server.ts b/platforms/market/src/server.ts index 9c66bed..0f583c7 100644 --- a/platforms/market/src/server.ts +++ b/platforms/market/src/server.ts @@ -1,3 +1,46 @@ import 'server-only'; // Public server-only API, exposed as the `/server` subpath. index.ts never imports this file. +export { readOnServer } from './app/error-boundaries/server'; +export type { + ReadOnServerOptions, + ServerRead, +} from './app/error-boundaries/server'; +export { refreshSessionInProxy } from './app/session/server'; +export type { ProxySessionOptions } from './app/session/server'; +export { getSessionAccount } from './features/auth/caches/server'; +export { + redirectIfSignedIn, + requireAccount, +} from './app/guards/auth-guard/server'; +export type { RequireAccountOptions } from './app/guards/auth-guard/server'; +export { requireRole } from './app/guards/role-guard/server'; +export type { + RequireRoleOptions, + RoleCheck, +} from './app/guards/role-guard/server'; +export { getMyCreatorProfile } from './features/profile/caches/server'; +export { + getPublicCreator, + getPublicTiers, +} from './features/channel/caches/server'; +export { getFollowStatus } from './features/follow/caches/server'; +export { + getNotificationInbox, + getUnreadNotificationCount, +} from './features/notification/caches/server'; +export { getCreatorPosts, getPost } from './features/post/caches/server'; +export { getPredictionStats } from './features/prediction/caches/server'; +export { getFeed } from './features/feed/caches/server'; +export { getPricingForm } from './features/pricing/caches/server'; +export { getCheckoutScreen } from './features/checkout/caches/server'; +export { + getSubscriptionDashboard, + getSubscriptionDetail, +} from './features/subscription/caches/server'; +export { + getPaymentDetail, + getTransactionsFirstPage, +} from './features/transaction/caches/server'; +export { getCreatorDashboard } from './features/overview/caches/server'; +export { getCreatorPayments } from './features/finance/caches/server'; diff --git a/platforms/market/src/shared/constants/.gitkeep b/platforms/market/src/shared/constants/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/shared/constants/index.ts b/platforms/market/src/shared/constants/index.ts new file mode 100644 index 0000000..3b952d3 --- /dev/null +++ b/platforms/market/src/shared/constants/index.ts @@ -0,0 +1,72 @@ +// Domain enums that more than one feature uses, exactly as the API sends them. Each is a const array +// (in the server's order, for pickers and checks) plus the union derived from it. + +/** The four fixed subscription periods, in display order. A price is always the total for the whole period; monthly is always on. */ +export const BILLING_PERIODS = [ + 'monthly', + 'quarterly', + 'semi_annual', + 'yearly', +] as const; +export type BillingPeriod = (typeof BILLING_PERIODS)[number]; + +/** What a checkout buys, and so a payment's `type`: a new subscription, more time on a running one, or a restart after expiry. There is no refund type yet. */ +export const CHECKOUT_KINDS = ['subscribe', 'renew', 'reactivate'] as const; +export type CheckoutKind = (typeof CHECKOUT_KINDS)[number]; + +/** + * Why a tier has a struck-through `compareAtToman`: the standing price while a promotion is live, or + * the monthly price times the period's months when the period is cheaper per month. + */ +export const COMPARE_SOURCES = ['standing', 'monthly_x_duration'] as const; +export type CompareSource = (typeof COMPARE_SOURCES)[number]; + +/** + * U10, after the bank: `processing` (still pending: wait and poll), `granted`, `pending_review` (the + * bank verify was ambiguous) or `failed`. + */ +export const CONFIRMATION_PHASES = [ + 'processing', + 'granted', + 'pending_review', + 'failed', +] as const; +export type ConfirmationPhase = (typeof CONFIRMATION_PHASES)[number]; + +/** Where the investor lands after U10: keep waiting, the creator's channel, or checkout again. */ +export const CONFIRMATION_LANDINGS = ['wait', 'channel', 'checkout'] as const; +export type ConfirmationLanding = (typeof CONFIRMATION_LANDINGS)[number]; + +/** + * `subscription_payments.status` as stored. A pending payment turns `pending_review` after a while + * and `expired` after its 30-minute TTL. + */ +export const PAYMENT_STATUSES = [ + 'pending', + 'pending_review', + 'completed', + 'failed', + 'cancelled', + 'expired', +] as const; +export type PaymentStatus = (typeof PAYMENT_STATUSES)[number]; + +/** The three payment states the UI shows: completed → successful; pending and pending_review → pending; failed, cancelled and expired → failed. */ +export const PAYMENT_UI_STATUSES = ['successful', 'pending', 'failed'] as const; +export type PaymentUiStatus = (typeof PAYMENT_UI_STATUSES)[number]; + +/** + * A subscription record's own status. Only these two exist: a creator's suspension lives on the + * creator, and there is no refunded state on the back end yet. + */ +export const SUBSCRIPTION_RECORD_STATUSES = ['active', 'expired'] as const; +export type SubscriptionRecordStatus = + (typeof SUBSCRIPTION_RECORD_STATUSES)[number]; + +/** trader-service's creator verification. Only `approved` creators are public and can be subscribed to. */ +export const VERIFICATION_STATUSES = [ + 'pending', + 'approved', + 'rejected', +] as const; +export type VerificationStatus = (typeof VERIFICATION_STATUSES)[number]; diff --git a/platforms/market/src/shared/locales/fa/.gitkeep b/platforms/market/src/shared/locales/fa/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/shared/locales/fa/common.json b/platforms/market/src/shared/locales/fa/common.json new file mode 100644 index 0000000..4f65abb --- /dev/null +++ b/platforms/market/src/shared/locales/fa/common.json @@ -0,0 +1,18 @@ +{ + "app": { + "name": "لومینا", + "description": "پیش‌بینی‌های ساختاریافته و ثبت‌شده‌ی تحلیلگران مالی ایرانی، با کارنامه‌ای که پیش از اشتراک می‌بینید." + }, + "toaster": "اعلان‌ها", + "network": { + "offline": "اینترنت قطع است", + "offline-description": "آخرین اطلاعات ذخیره‌شده را می‌بینید.", + "retry": "تلاش مجدد", + "reconnecting": "در حال اتصال دوباره…", + "online": "دوباره آنلاین شدید", + "online-description": "اطلاعات این صفحه به‌روز شد.", + "slow": "اتصال کند است", + "slow-description": "ممکن است بارگذاری کمی طول بکشد.", + "frozen": "برای این کار به اینترنت نیاز دارید." + } +} diff --git a/platforms/market/src/shared/locales/fa/errors.json b/platforms/market/src/shared/locales/fa/errors.json new file mode 100644 index 0000000..4461da8 --- /dev/null +++ b/platforms/market/src/shared/locales/fa/errors.json @@ -0,0 +1,54 @@ +{ + "http": { + "network": "پاسخی از سرور نرسید.", + "network-hint": "اتصال اینترنت را بررسی کنید و دوباره تلاش کنید.", + "timeout": "سرور دیرتر از همیشه پاسخ داد.", + "timeout-hint": "چند لحظه بعد دوباره تلاش کنید.", + "aborted": "درخواست لغو شد.", + "aborted-hint": "دوباره تلاش کنید.", + "parse": "پاسخ سرور قابل خواندن نبود.", + "parse-hint": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید.", + "interceptor": "درخواست ارسال نشد.", + "interceptor-hint": "صفحه را دوباره بارگذاری کنید.", + "unknown": "مشکلی پیش آمد.", + "unknown-hint": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید.", + "retry-after": "{{seconds}} ثانیه دیگر دوباره تلاش کنید." + }, + "fallback": { + "error": { + "title": "مشکلی پیش آمد", + "description": "این بخش بارگذاری نشد. دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید." + }, + "server": { + "title": "سرور پاسخ نمی‌دهد", + "description": "مشکل از سمت لومیناست و در حال رفع آن هستیم. چند دقیقه دیگر دوباره تلاش کنید." + }, + "network": { + "title": "اتصال برقرار نشد", + "description": "پاسخی از سرور نرسید. اتصال اینترنت را بررسی کنید و دوباره تلاش کنید." + }, + "offline": { + "title": "اینترنت شما قطع است", + "description": "به محض وصل شدن، این صفحه خودکار به‌روز می‌شود." + }, + "timeout": { + "title": "پاسخ طول کشید", + "description": "سرور دیرتر از همیشه پاسخ داد. دوباره تلاش کنید." + }, + "retry": "تلاش مجدد", + "retrying": "در حال تلاش…", + "reload": "بارگذاری دوباره صفحه", + "reference": "کد پیگیری:" + }, + "empty": { + "not-found": { + "title": "صفحه پیدا نشد", + "description": "نشانی را بررسی کنید؛ ممکن است این صفحه حذف شده باشد." + }, + "no-access": { + "title": "به این صفحه دسترسی ندارید", + "description": "اگر فکر می‌کنید اشتباهی رخ داده است، با پشتیبانی تماس بگیرید." + }, + "home": "بازگشت به خانه" + } +} diff --git a/platforms/market/src/shared/locales/index.ts b/platforms/market/src/shared/locales/index.ts new file mode 100644 index 0000000..6e4fc78 --- /dev/null +++ b/platforms/market/src/shared/locales/index.ts @@ -0,0 +1,8 @@ +import './types'; + +export { + DEFAULT_LOCALE, + DEFAULT_NAMESPACE, + NAMESPACES, + resources, +} from './resources'; diff --git a/platforms/market/src/shared/locales/resources.ts b/platforms/market/src/shared/locales/resources.ts new file mode 100644 index 0000000..668d758 --- /dev/null +++ b/platforms/market/src/shared/locales/resources.ts @@ -0,0 +1,18 @@ +import faCommon from './fa/common.json'; +import faErrors from './fa/errors.json'; + +/** The product is Persian only; every route loads both namespaces, because any route can fail. */ +export const DEFAULT_LOCALE = 'fa'; + +export const DEFAULT_NAMESPACE = 'common'; + +export const resources = { + fa: { + common: faCommon, + errors: faErrors, + }, +} as const; + +export const NAMESPACES = Object.keys( + resources.fa, +) as (keyof typeof resources.fa)[]; diff --git a/platforms/market/src/shared/locales/types.ts b/platforms/market/src/shared/locales/types.ts new file mode 100644 index 0000000..ae0ad72 --- /dev/null +++ b/platforms/market/src/shared/locales/types.ts @@ -0,0 +1,9 @@ +import type { DEFAULT_NAMESPACE, resources } from './resources'; + +// Types every `t` call against the Persian resources, so a missing key fails type-check. +declare module 'i18next' { + interface CustomTypeOptions { + defaultNS: typeof DEFAULT_NAMESPACE; + resources: (typeof resources)['fa']; + } +} diff --git a/platforms/market/src/shared/utils/.gitkeep b/platforms/market/src/shared/utils/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/shared/utils/api-url.ts b/platforms/market/src/shared/utils/api-url.ts new file mode 100644 index 0000000..5cbaf2c --- /dev/null +++ b/platforms/market/src/shared/utils/api-url.ts @@ -0,0 +1,12 @@ +import { getEnv } from '../../env'; + +/** + * A path the API returns (`/v1/posts/…/media/…`, `/files/…`) → an absolute URL the browser can + * load. Absolute URLs (legacy avatars carry the gateway's own host) pass through; empty stays + * `null`. Reads env inside the call, so bootstrap has always run. + */ +export function toApiUrl(path: string | null | undefined): string | null { + if (!path) return null; + if (/^https?:\/\//.test(path)) return path; + return `${getEnv().apiOrigin}${path.startsWith('/') ? '' : '/'}${path}`; +} diff --git a/platforms/market/src/shared/utils/index.ts b/platforms/market/src/shared/utils/index.ts new file mode 100644 index 0000000..1286383 --- /dev/null +++ b/platforms/market/src/shared/utils/index.ts @@ -0,0 +1,3 @@ +export { toApiUrl } from './api-url'; +export { toE164Mobile } from './mobile'; +export { renameFieldErrors } from './rename-field-errors'; diff --git a/platforms/market/src/shared/utils/mobile.ts b/platforms/market/src/shared/utils/mobile.ts new file mode 100644 index 0000000..962b1d1 --- /dev/null +++ b/platforms/market/src/shared/utils/mobile.ts @@ -0,0 +1,12 @@ +import { latinDigits } from '@lumina/tools/format'; + +/** + * An Iranian mobile number as typed (`۰۹۱۲ ۳۴۵ ۶۷۸۹`, `0912…`, `+98912…`, `98912…`) → E.164 + * (`+989123456789`), the one form the API stores. Anything else is returned trimmed, so the + * server can reject it with its own message. + */ +export function toE164Mobile(value: string): string { + const digits = latinDigits(value).replace(/[\s()-]/g, ''); + const match = /^(?:\+98|0098|98|0)?(9\d{9})$/.exec(digits); + return match ? `+98${match[1]}` : digits; +} diff --git a/platforms/market/src/shared/utils/rename-field-errors.ts b/platforms/market/src/shared/utils/rename-field-errors.ts new file mode 100644 index 0000000..7a27316 --- /dev/null +++ b/platforms/market/src/shared/utils/rename-field-errors.ts @@ -0,0 +1,19 @@ +import { HttpError, isHttpError } from '@lumina/libs/http'; + +/** + * Renames an error's server field names to the caller's `*Args` names (`phone_number` → `phone`), + * so a form can put each message under its own field. Anything else passes through unchanged. + */ +export function renameFieldErrors( + error: unknown, + names: Readonly>, +): unknown { + if (!isHttpError(error) || !error.fieldErrors) return error; + const fieldErrors = Object.fromEntries( + Object.entries(error.fieldErrors).map(([field, message]) => [ + names[field] ?? field, + message, + ]), + ); + return new HttpError({ ...error.toJSON(), fieldErrors, cause: error }); +} diff --git a/platforms/market/tsconfig.lib.json b/platforms/market/tsconfig.lib.json index 6b58672..032c2b0 100644 --- a/platforms/market/tsconfig.lib.json +++ b/platforms/market/tsconfig.lib.json @@ -10,11 +10,8 @@ "rootDir": "src", "jsx": "react-jsx", "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", - "lib": [ - "es2022", - "dom", - "dom.iterable" - ] + "lib": ["es2022", "dom", "dom.iterable"], + "resolveJsonModule": true }, "exclude": [ "out-tsc", @@ -37,7 +34,8 @@ "src/**/*.js", "src/**/*.jsx", "src/**/*.ts", - "src/**/*.tsx" + "src/**/*.tsx", + "src/**/*.json" ], "references": [ {