From 49372bc77ea9f99a9a044f7a355f10158a23b8e4 Mon Sep 17 00:00:00 2001 From: Amiram_se Date: Thu, 8 Oct 2026 22:36:22 +0400 Subject: [PATCH] feat(market): checkout, payment return and result, investor subscriptions and transactions, notification centre Checkout draft store survives the bank round trip; the app shell settles an abandoned payment on return. Renewal sheet lists periods as tier options. Notification bell opens the centre as a panel on desktop. Co-Authored-By: Claude Opus 5.5 --- .../market/src/app/app-shell/AppShell.tsx | 4 + .../src/app/app-shell/hooks/use-session.ts | 2 + .../hooks/use-settle-abandoned-payment.ts | 75 ++++ .../desktop-header/DesktopHeader.tsx | 29 +- .../desktop-page-title/DesktopPageTitle.tsx | 25 ++ .../components/desktop-page-title/index.ts | 2 + .../components/desktop-page-title/types.ts | 6 + .../mobile-top-bar/MobileTopBar.tsx | 32 +- .../components/mobile-top-bar/types.ts | 6 + .../notification-bell/NotificationBell.tsx | 84 ++++ .../components/notification-bell/index.ts | 2 + .../components/notification-bell/types.ts | 4 + platforms/market/src/app/navigation/index.ts | 2 + .../market/src/app/navigation/navigation.ts | 6 + .../checkout-creator/CheckoutCreator.tsx | 49 +++ .../CheckoutCreatorSkeleton.tsx | 15 + .../organisms/checkout-creator/index.ts | 3 + .../organisms/checkout-creator/types.ts | 11 + .../checkout-panel/CheckoutPanel.tsx | 32 ++ .../checkout-panel/CheckoutSkeleton.tsx | 66 +++ .../components/CheckoutCode.tsx | 48 +++ .../components/CheckoutFooter.tsx | 87 ++++ .../components/CheckoutForm.tsx | 82 ++++ .../components/CheckoutFrame.tsx | 77 ++++ .../components/CheckoutHalts.tsx | 148 +++++++ .../components/CheckoutTiers.tsx | 90 +++++ .../checkout-panel/components/HaltDialog.tsx | 42 ++ .../organisms/checkout-panel/index.ts | 7 + .../organisms/checkout-panel/types.ts | 53 +++ .../payment-result/PaymentResult.tsx | 62 +++ .../payment-result/PaymentResultSkeleton.tsx | 61 +++ .../components/ResultActions.tsx | 86 ++++ .../payment-result/components/ResultFrame.tsx | 42 ++ .../payment-result/components/ResultHead.tsx | 38 ++ .../components/ResultReceipt.tsx | 112 ++++++ .../organisms/payment-result/index.ts | 7 + .../organisms/payment-result/types.ts | 40 ++ .../payment-confirming/PaymentConfirming.tsx | 44 ++ .../organisms/payment-confirming/index.ts | 2 + .../organisms/payment-confirming/types.ts | 11 + .../payment-return/PaymentReturn.tsx | 13 + .../return/organisms/payment-return/index.ts | 2 + .../return/organisms/payment-return/types.ts | 8 + .../subscription-terms/SubscriptionTerms.tsx | 85 ++++ .../organisms/subscription-terms/index.ts | 7 + .../organisms/subscription-terms/labels.ts | 54 +++ .../organisms/subscription-terms/types.ts | 29 ++ .../organisms/renewal-sheet/RenewalSheet.tsx | 58 +++ .../renewal-sheet/components/RenewalForm.tsx | 236 +++++++++++ .../components/RenewalSkeleton.tsx | 35 ++ .../organisms/renewal-sheet/index.ts | 2 + .../organisms/renewal-sheet/types.ts | 16 + .../subscription-list/SubscriptionList.tsx | 84 ++++ .../components/SubscriptionItem.tsx | 51 +++ .../components/SubscriptionsEmpty.tsx | 30 ++ .../organisms/subscription-list/index.ts | 2 + .../organisms/subscription-list/types.ts | 13 + .../transaction-list/TransactionList.tsx | 97 +++++ .../components/TransactionDetail.tsx | 221 +++++++++++ .../components/TransactionRow.tsx | 154 +++++++ .../components/TransactionsEmpty.tsx | 30 ++ .../components/use-transaction-title.ts | 23 ++ .../organisms/transaction-list/index.ts | 2 + .../organisms/transaction-list/types.ts | 21 + .../NotificationCentre.tsx | 48 +++ .../notification-centre/NotificationPanel.tsx | 37 ++ .../components/NotificationItem.tsx | 206 ++++++++++ .../notification-centre/constants.ts | 57 +++ .../organisms/notification-centre/index.ts | 8 + .../organisms/notification-centre/types.ts | 26 ++ .../organisms/support-entry/SupportDialog.tsx | 44 ++ .../organisms/support-entry/SupportEntry.tsx | 21 +- .../screens/organisms/support-entry/index.ts | 7 +- .../screens/organisms/support-entry/types.ts | 7 + .../checkout/actions/join-waitlist/actions.ts | 25 ++ .../checkout/actions/join-waitlist/index.ts | 1 + .../settle-abandoned-payment/actions.ts | 71 ++++ .../actions/settle-abandoned-payment/index.ts | 1 + .../actions/start-checkout/actions.ts | 44 ++ .../checkout/actions/start-checkout/index.ts | 1 + .../market/src/features/checkout/constants.ts | 14 + .../market/src/features/checkout/index.ts | 34 +- .../src/features/checkout/models/.gitkeep | 0 .../checkout/models/checkout/index.ts | 9 + .../checkout/models/checkout/types.ts | 80 ++++ .../models/checkout/use-checkout-page.ts | 375 ++++++++++++++++++ .../checkout/models/payment-result/index.ts | 6 + .../checkout/models/payment-result/types.ts | 14 + .../payment-result/use-payment-result-page.ts | 90 +++++ .../checkout/models/payment-return/index.ts | 2 + .../checkout/models/payment-return/types.ts | 4 + .../payment-return/use-payment-return-page.ts | 68 ++++ .../repositories/checkout/checkout.ts | 22 +- .../repositories/checkout/constants.ts | 48 +++ .../checkout/repositories/checkout/errors.ts | 35 ++ .../checkout/repositories/checkout/index.ts | 10 +- .../checkout/repositories/checkout/mappers.ts | 8 + .../checkout/repositories/checkout/types.ts | 41 ++ .../market/src/features/checkout/types.ts | 11 +- .../repositories/creator-payment/types.ts | 4 +- .../features/notification/actions/.gitkeep | 0 .../entities/notification/types.ts | 12 +- .../market/src/features/notification/index.ts | 6 + .../src/features/notification/models/.gitkeep | 0 .../models/notification-centre/index.ts | 2 + .../models/notification-centre/types.ts | 17 + .../use-notification-centre.ts | 101 +++++ .../notification/models/unread-count/index.ts | 1 + .../models/unread-count/use-unread-count.ts | 23 ++ .../repositories/creator-dashboard/types.ts | 7 +- .../features/subscription/actions/.gitkeep | 0 .../actions/start-renewal/actions.ts | 52 +++ .../actions/start-renewal/index.ts | 2 + .../src/features/subscription/constants.ts | 5 + .../entities/subscription/types.ts | 5 + .../market/src/features/subscription/index.ts | 13 + .../src/features/subscription/models/.gitkeep | 0 .../subscription/models/renewal/index.ts | 6 + .../subscription/models/renewal/types.ts | 26 ++ .../models/renewal/use-renewal-sheet.ts | 118 ++++++ .../models/subscriptions/index.ts | 2 + .../models/subscriptions/types.ts | 18 + .../subscriptions/use-subscriptions-part.ts | 41 ++ .../repositories/subscription/mappers.ts | 21 +- .../repositories/subscription/subscription.ts | 6 +- .../repositories/subscription/types.ts | 26 +- .../market/src/features/subscription/types.ts | 11 + .../src/features/transaction/actions/.gitkeep | 0 .../transaction/entities/payment/index.ts | 1 + .../transaction/entities/payment/types.ts | 23 +- .../market/src/features/transaction/index.ts | 4 + .../src/features/transaction/models/.gitkeep | 0 .../transaction/models/transactions/index.ts | 2 + .../transaction/models/transactions/types.ts | 31 ++ .../transactions/use-transactions-part.ts | 101 +++++ .../repositories/transaction/constants.ts | 11 + .../repositories/transaction/index.ts | 6 +- .../repositories/transaction/mappers.ts | 9 + .../repositories/transaction/types.ts | 28 +- platforms/market/src/index.ts | 24 ++ .../market/src/shared/constants/index.ts | 18 +- .../src/shared/labels/content-labels.tsx | 2 + platforms/market/src/shared/labels/index.ts | 4 +- .../src/shared/labels/payment-labels.tsx | 36 ++ .../src/shared/labels/subscription-labels.tsx | 53 +++ platforms/market/src/shared/labels/types.ts | 9 + .../market/src/shared/locales/fa/common.json | 14 +- .../market/src/shared/locales/fa/content.json | 2 + .../src/shared/locales/fa/dashboard.json | 111 ++++++ .../market/src/shared/locales/fa/errors.json | 8 + .../src/shared/locales/fa/notifications.json | 23 ++ .../market/src/shared/locales/fa/payment.json | 111 ++++++ .../market/src/shared/locales/fa/terms.json | 54 +++ .../market/src/shared/locales/resources.ts | 4 + .../src/shared/locales/server-resources.ts | 7 +- .../src/shared/utils/copy-with-toast.ts | 25 ++ platforms/market/src/shared/utils/index.ts | 3 + .../src/shared/utils/is-connection-error.ts | 9 + .../market/src/shared/validations/index.ts | 3 + .../shared/validations/payment-validations.ts | 13 + .../market/src/shared/validations/types.ts | 3 + .../checkout-draft/checkout-draft-store.ts | 60 +++ .../market/src/stores/checkout-draft/index.ts | 6 + .../market/src/stores/checkout-draft/types.ts | 41 ++ 164 files changed, 5636 insertions(+), 90 deletions(-) create mode 100644 platforms/market/src/app/app-shell/hooks/use-settle-abandoned-payment.ts create mode 100644 platforms/market/src/app/navigation/components/desktop-page-title/DesktopPageTitle.tsx create mode 100644 platforms/market/src/app/navigation/components/desktop-page-title/index.ts create mode 100644 platforms/market/src/app/navigation/components/desktop-page-title/types.ts create mode 100644 platforms/market/src/app/navigation/components/notification-bell/NotificationBell.tsx create mode 100644 platforms/market/src/app/navigation/components/notification-bell/index.ts create mode 100644 platforms/market/src/app/navigation/components/notification-bell/types.ts create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-creator/CheckoutCreator.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-creator/CheckoutCreatorSkeleton.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-creator/index.ts create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-creator/types.ts create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/CheckoutPanel.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/CheckoutSkeleton.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutCode.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutFooter.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutForm.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutFrame.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutHalts.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutTiers.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/HaltDialog.tsx create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/index.ts create mode 100644 platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/types.ts create mode 100644 platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResult.tsx create mode 100644 platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResultSkeleton.tsx create mode 100644 platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultActions.tsx create mode 100644 platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultFrame.tsx create mode 100644 platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultHead.tsx create mode 100644 platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultReceipt.tsx create mode 100644 platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/index.ts create mode 100644 platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/types.ts create mode 100644 platforms/market/src/app/screens/(flow)/payment/return/organisms/payment-confirming/PaymentConfirming.tsx create mode 100644 platforms/market/src/app/screens/(flow)/payment/return/organisms/payment-confirming/index.ts create mode 100644 platforms/market/src/app/screens/(flow)/payment/return/organisms/payment-confirming/types.ts create mode 100644 platforms/market/src/app/screens/(flow)/payment/return/organisms/payment-return/PaymentReturn.tsx create mode 100644 platforms/market/src/app/screens/(flow)/payment/return/organisms/payment-return/index.ts create mode 100644 platforms/market/src/app/screens/(flow)/payment/return/organisms/payment-return/types.ts create mode 100644 platforms/market/src/app/screens/(flow)/terms/subscription/organisms/subscription-terms/SubscriptionTerms.tsx create mode 100644 platforms/market/src/app/screens/(flow)/terms/subscription/organisms/subscription-terms/index.ts create mode 100644 platforms/market/src/app/screens/(flow)/terms/subscription/organisms/subscription-terms/labels.ts create mode 100644 platforms/market/src/app/screens/(flow)/terms/subscription/organisms/subscription-terms/types.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/RenewalSheet.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalForm.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalSkeleton.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/index.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/types.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/SubscriptionList.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/components/SubscriptionItem.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/components/SubscriptionsEmpty.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/index.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/types.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/TransactionList.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/TransactionDetail.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/TransactionRow.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/TransactionsEmpty.tsx create mode 100644 platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/use-transaction-title.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/index.ts create mode 100644 platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/types.ts create mode 100644 platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/NotificationCentre.tsx create mode 100644 platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/NotificationPanel.tsx create mode 100644 platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/components/NotificationItem.tsx create mode 100644 platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/constants.ts create mode 100644 platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/index.ts create mode 100644 platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/types.ts create mode 100644 platforms/market/src/app/screens/organisms/support-entry/SupportDialog.tsx create mode 100644 platforms/market/src/features/checkout/actions/join-waitlist/actions.ts create mode 100644 platforms/market/src/features/checkout/actions/join-waitlist/index.ts create mode 100644 platforms/market/src/features/checkout/actions/settle-abandoned-payment/actions.ts create mode 100644 platforms/market/src/features/checkout/actions/settle-abandoned-payment/index.ts create mode 100644 platforms/market/src/features/checkout/actions/start-checkout/actions.ts create mode 100644 platforms/market/src/features/checkout/actions/start-checkout/index.ts delete mode 100644 platforms/market/src/features/checkout/models/.gitkeep create mode 100644 platforms/market/src/features/checkout/models/checkout/index.ts create mode 100644 platforms/market/src/features/checkout/models/checkout/types.ts create mode 100644 platforms/market/src/features/checkout/models/checkout/use-checkout-page.ts create mode 100644 platforms/market/src/features/checkout/models/payment-result/index.ts create mode 100644 platforms/market/src/features/checkout/models/payment-result/types.ts create mode 100644 platforms/market/src/features/checkout/models/payment-result/use-payment-result-page.ts create mode 100644 platforms/market/src/features/checkout/models/payment-return/index.ts create mode 100644 platforms/market/src/features/checkout/models/payment-return/types.ts create mode 100644 platforms/market/src/features/checkout/models/payment-return/use-payment-return-page.ts create mode 100644 platforms/market/src/features/checkout/repositories/checkout/errors.ts delete mode 100644 platforms/market/src/features/notification/actions/.gitkeep delete mode 100644 platforms/market/src/features/notification/models/.gitkeep create mode 100644 platforms/market/src/features/notification/models/notification-centre/index.ts create mode 100644 platforms/market/src/features/notification/models/notification-centre/types.ts create mode 100644 platforms/market/src/features/notification/models/notification-centre/use-notification-centre.ts create mode 100644 platforms/market/src/features/notification/models/unread-count/index.ts create mode 100644 platforms/market/src/features/notification/models/unread-count/use-unread-count.ts delete mode 100644 platforms/market/src/features/subscription/actions/.gitkeep create mode 100644 platforms/market/src/features/subscription/actions/start-renewal/actions.ts create mode 100644 platforms/market/src/features/subscription/actions/start-renewal/index.ts create mode 100644 platforms/market/src/features/subscription/constants.ts delete mode 100644 platforms/market/src/features/subscription/models/.gitkeep create mode 100644 platforms/market/src/features/subscription/models/renewal/index.ts create mode 100644 platforms/market/src/features/subscription/models/renewal/types.ts create mode 100644 platforms/market/src/features/subscription/models/renewal/use-renewal-sheet.ts create mode 100644 platforms/market/src/features/subscription/models/subscriptions/index.ts create mode 100644 platforms/market/src/features/subscription/models/subscriptions/types.ts create mode 100644 platforms/market/src/features/subscription/models/subscriptions/use-subscriptions-part.ts create mode 100644 platforms/market/src/features/subscription/types.ts delete mode 100644 platforms/market/src/features/transaction/actions/.gitkeep delete mode 100644 platforms/market/src/features/transaction/models/.gitkeep create mode 100644 platforms/market/src/features/transaction/models/transactions/index.ts create mode 100644 platforms/market/src/features/transaction/models/transactions/types.ts create mode 100644 platforms/market/src/features/transaction/models/transactions/use-transactions-part.ts create mode 100644 platforms/market/src/shared/labels/payment-labels.tsx create mode 100644 platforms/market/src/shared/labels/subscription-labels.tsx create mode 100644 platforms/market/src/shared/locales/fa/notifications.json create mode 100644 platforms/market/src/shared/locales/fa/payment.json create mode 100644 platforms/market/src/shared/locales/fa/terms.json create mode 100644 platforms/market/src/shared/utils/copy-with-toast.ts create mode 100644 platforms/market/src/shared/utils/is-connection-error.ts create mode 100644 platforms/market/src/shared/validations/payment-validations.ts create mode 100644 platforms/market/src/stores/checkout-draft/checkout-draft-store.ts create mode 100644 platforms/market/src/stores/checkout-draft/index.ts create mode 100644 platforms/market/src/stores/checkout-draft/types.ts diff --git a/platforms/market/src/app/app-shell/AppShell.tsx b/platforms/market/src/app/app-shell/AppShell.tsx index 21b038f..9bef1e4 100644 --- a/platforms/market/src/app/app-shell/AppShell.tsx +++ b/platforms/market/src/app/app-shell/AppShell.tsx @@ -5,9 +5,11 @@ import { QueryClientProvider } from '@tanstack/react-query'; import { useEffect } from 'react'; import { I18nextProvider } from 'react-i18next'; +import { useCheckoutDraftStore } from '../../stores/checkout-draft'; import { usePostDraftStore } from '../../stores/post-draft'; import { NetworkBoundary } from './components/NetworkBoundary'; import { useSession } from './hooks/use-session'; +import { useSettleAbandonedPayment } from './hooks/use-settle-abandoned-payment'; import type { AppShellProps } from './types'; /** @@ -17,9 +19,11 @@ import type { AppShellProps } from './types'; */ export function AppShell({ queryClient, i18n, children }: AppShellProps) { useSession(queryClient); + useSettleAbandonedPayment(queryClient); // Persisted stores wait for the first browser render, so it matches the server's. useEffect(() => { void usePostDraftStore.persist.rehydrate(); + void useCheckoutDraftStore.persist.rehydrate(); }, []); return ( diff --git a/platforms/market/src/app/app-shell/hooks/use-session.ts b/platforms/market/src/app/app-shell/hooks/use-session.ts index 98b09f9..2ebb3d9 100644 --- a/platforms/market/src/app/app-shell/hooks/use-session.ts +++ b/platforms/market/src/app/app-shell/hooks/use-session.ts @@ -6,6 +6,7 @@ import { useEffect } from 'react'; import { AUTH_EVENTS, restoreSession } from '../../../features/auth'; import { useAuthStore } from '../../../stores/auth'; +import { useCheckoutDraftStore } from '../../../stores/checkout-draft'; import { usePostDraftStore } from '../../../stores/post-draft'; /** @@ -32,6 +33,7 @@ export function useSession(queryClient: QueryClient): void { // The account's own drafts and choices stay with it, not with the device. The stores go // first: a persisted store writes its key again on every change. usePostDraftStore.getState().clearDraft(); + useCheckoutDraftStore.getState().clearDraft(); storage.clearByPrefix('session.'); }); return () => { diff --git a/platforms/market/src/app/app-shell/hooks/use-settle-abandoned-payment.ts b/platforms/market/src/app/app-shell/hooks/use-settle-abandoned-payment.ts new file mode 100644 index 0000000..9f55bf0 --- /dev/null +++ b/platforms/market/src/app/app-shell/hooks/use-settle-abandoned-payment.ts @@ -0,0 +1,75 @@ +import { handleError } from '@lumina/libs/error-handler'; +import { eventEmitter } from '@lumina/libs/event-emitter'; +import type { QueryClient } from '@tanstack/react-query'; +import { useEffect } from 'react'; + +import { channelKeys } from '../../../features/channel'; +import { + CHECKOUT_EVENTS, + checkoutKeys, + settleAbandonedPayment, +} from '../../../features/checkout'; +import { subscriptionKeys } from '../../../features/subscription'; +import { transactionKeys } from '../../../features/transaction'; +import { useCurrentAccount, useViewerStatus } from '../../../stores/auth'; +import { useCheckoutDraftStore } from '../../../stores/checkout-draft'; +import { ROUTES } from '../../navigation/navigation'; + +// The return and result pages read the bank's answer themselves. +const isPaymentPage = (pathname: string) => + pathname === ROUTES.paymentReturn || + pathname.startsWith(ROUTES.paymentResult('')); + +/** + * A payment handed to the bank whose callback never came: the investor backed out of the bank to + * any page but the return and result pages, as a fresh load or a page restored from the back + * cache. Once the draft is loaded and the viewer is a signed-in investor, the settle action asks + * the bank (it decides whether this page is the one that came back), and whatever shows this + * creator's standing, the subscriptions or the transactions reads again (U10 ۶.۳). Moving between + * pages asks nothing. + */ +export function useSettleAbandonedPayment(queryClient: QueryClient): void { + const status = useViewerStatus(); + const account = useCurrentAccount(); + const isInvestor = status === 'member' && account?.role === 'investor'; + + useEffect( + () => + eventEmitter.on( + CHECKOUT_EVENTS.paymentSettled, + ({ creatorId, outcome }) => { + if (outcome === 'pending') return; + void queryClient.invalidateQueries({ queryKey: checkoutKeys.all }); + void queryClient.invalidateQueries({ + queryKey: channelKeys.creator(creatorId), + }); + void queryClient.invalidateQueries({ + queryKey: subscriptionKeys.all, + }); + void queryClient.invalidateQueries({ queryKey: transactionKeys.all }); + }, + ), + [queryClient], + ); + + useEffect(() => { + if (!isInvestor) return; + const settle = () => { + if (isPaymentPage(window.location.pathname)) return; + settleAbandonedPayment().catch((error: unknown) => + handleError(error, { where: 'app', name: 'settle-abandoned-payment' }), + ); + }; + const onPageShow = (event: PageTransitionEvent) => { + if (event.persisted) settle(); + }; + const offHydrated = useCheckoutDraftStore.persist.hasHydrated() + ? (settle(), undefined) + : useCheckoutDraftStore.persist.onFinishHydration(settle); + window.addEventListener('pageshow', onPageShow); + return () => { + offHydrated?.(); + window.removeEventListener('pageshow', onPageShow); + }; + }, [isInvestor]); +} diff --git a/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx b/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx index 2704665..1b9a586 100644 --- a/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx +++ b/platforms/market/src/app/navigation/components/desktop-header/DesktopHeader.tsx @@ -4,8 +4,8 @@ import { Avatar } from '@lumina/island/atoms/avatar'; import { Button } from '@lumina/island/atoms/button'; import { FlexBox } from '@lumina/island/atoms/flex-box'; import { GridBox } from '@lumina/island/atoms/grid-box'; -import { Skeleton } from '@lumina/island/atoms/skeleton'; import { Typography } from '@lumina/island/atoms/typography'; +import { Element } from '@lumina/island/primitives/element'; import NextLink from 'next/link'; import { usePathname } from 'next/navigation'; import { useTranslation } from 'react-i18next'; @@ -15,15 +15,16 @@ import { SupportEntry } from '../../../screens/organisms/support-entry'; import { activeTab } from '../../active-tab'; import { useHomeHref } from '../../hooks/use-home-href'; import { loginRoute, ROUTES } from '../../navigation'; +import { NotificationBell } from '../notification-bell'; import { PublishMenu } from '../publish-menu'; import { HeaderNavLink } from './components/HeaderNavLink'; /** - * The desktop header on every main page: the brand, the nav, then support and the account at the - * end. An investor's nav is خانه · داشبورد; a creator's is کانال · داشبورد, with «انتشار» before - * support. A guest sees only the brand, support and «ورود/ثبت‌نام», which returns here. The brand - * goes home, or to a creator's own channel. Who is looking is known only in the browser; until then - * the account's place is a skeleton. + * The desktop header on every main page: the brand, the nav, then support, the bell and the + * account at the end. An investor's nav is خانه · داشبورد; a creator's is کانال · داشبورد, with + * «انتشار» before support. A guest sees only the brand, support and «ورود/ثبت‌نام», which returns + * here. The brand goes home, or to a creator's own channel. Who is looking is known only in the + * browser; until then the guest's end holds its place. */ export function DesktopHeader() { const { t } = useTranslation(); @@ -87,15 +88,15 @@ export function DesktopHeader() { {isCreator && } + {status === 'member' && } {status === 'unknown' && ( - // The account link's size, so the end doesn't move when the session arrives. - - - + // Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so it + // doesn't move when the session arrives. + + + )} {status === 'guest' && ( )} - {status === 'unknown' && isTabBar && ( - - - + {status === 'unknown' && ( + // Most visitors are guests: their «ورود/ثبت‌نام» holds the end's place, unseen, so the bar + // doesn't move when the session arrives. + + + )} {status === 'member' && isTabBar && account && ( void; + /** + * `false`: nothing behind the page to go back to, such as the payment result with the bank behind + * it (U10 ۹.۱), so the bar has only the name and support. + */ + back?: boolean; /** The title while the page is in the creator's preview (`?preview`): «پیش‌نمایش پست». */ previewTitle?: string; }; @@ -21,6 +26,7 @@ type TabBarProps = { title?: string; tabOwnerId?: never; onBack?: never; + back?: never; previewTitle?: never; }; diff --git a/platforms/market/src/app/navigation/components/notification-bell/NotificationBell.tsx b/platforms/market/src/app/navigation/components/notification-bell/NotificationBell.tsx new file mode 100644 index 0000000..1f83f41 --- /dev/null +++ b/platforms/market/src/app/navigation/components/notification-bell/NotificationBell.tsx @@ -0,0 +1,84 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { CountBadge } from '@lumina/island/atoms/count-badge'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import dynamic from 'next/dynamic'; +import { usePathname } from 'next/navigation'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { + UNREAD_BADGE_CAP, + useUnreadCount, +} from '../../../../features/notification'; +import { ROUTES } from '../../navigation'; +import type { NotificationBellProps } from './types'; + +// The centre's code loads on the first open, not with every page's header. +const NotificationPanel = dynamic( + () => + import( + '../../../screens/(main)/notifications/organisms/notification-centre' + ).then((module) => module.NotificationPanel), + { ssr: false }, +); + +/** + * The bell (U5 ۲.۲), for a signed-in member of either role, between support and the account: the + * unread count on it in red up to «۹۹+», gone at 0 and once the centre is opened. Mobile goes to + * the centre's page; desktop opens it as a side panel over the page, which closes when an item + * leads elsewhere. + */ +export function NotificationBell({ placement }: NotificationBellProps) { + const { t } = useTranslation('notifications'); + const count = useUnreadCount(); + const pathname = usePathname(); + // Open on the page it was opened on: an item that leads to another page closes it. + const [openedOn, setOpenedOn] = useState(null); + const [hasOpened, setHasOpened] = useState(false); + const isOpen = openedOn === pathname; + const label = count > 0 ? t('bell-unread', { count }) : t('bell'); + + const badge = ( + + ); + + if (placement === 'link') { + return ( + + + ) : ( + + )} + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutForm.tsx b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutForm.tsx new file mode 100644 index 0000000..fb023b2 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutForm.tsx @@ -0,0 +1,82 @@ +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { useTranslation } from 'react-i18next'; + +import { useCheckoutPage } from '../../../../../../../../features/checkout'; +import { CheckoutSkeleton } from '../CheckoutSkeleton'; +import type { CheckoutFormProps } from '../types'; +import { CheckoutCode } from './CheckoutCode'; +import { CheckoutFooter } from './CheckoutFooter'; +import { CheckoutFrame } from './CheckoutFrame'; +import { CheckoutHalts } from './CheckoutHalts'; +import { CheckoutTiers } from './CheckoutTiers'; + +const SKELETON_LABELS = { + pending: 'checkout.loading', + settling: 'checkout.settling', + away: 'checkout.leaving', +} as const; + +/** + * The signed-in investor's checkout: the screen loads in the browser behind the skeleton, which + * also covers settling a payment left at the gateway and the way to the channel for an investor + * who can't pay here. An ended subscription reactivates: the note that the period starts today in + * place of the invite note and code (U11 ۳.۱). + */ +export function CheckoutForm({ + creatorId, + channelHref, + layout, + creator, +}: CheckoutFormProps) { + const { t } = useTranslation('payment'); + const model = useCheckoutPage({ creatorId, channelHref }); + + if (model.status !== 'ready') { + return ( + + ); + } + + return ( + <> + { + event.preventDefault(); + model.pay(); + }} + banner={ + model.isOffline && ( + + ) + } + body={ + model.mode === 'reactivate' ? ( + <> + + {t('checkout.reactivation-note')} + + + + ) : ( + <> + + {t('checkout.invite-note')} + + + + + ) + } + footer={} + /> + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutFrame.tsx b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutFrame.tsx new file mode 100644 index 0000000..78dcc6c --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutFrame.tsx @@ -0,0 +1,77 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Card } from '@lumina/island/molecules/card'; +import { Element } from '@lumina/island/primitives/element'; + +import type { CheckoutFrameProps } from '../types'; + +/** + * Checkout's blocks in their fixed order (U9 §۲) under the page's bar: who is paid, why a code is + * needed, the tiers, the code, then the amount and «پرداخت». Mobile pins the pay block to the + * bottom of the screen while the tiers scroll; desktop sets the blocks in one panel of the 480 + * column, and the pay block in its own panel stuck 24px above the window's bottom (۹.۱), so the + * last figure seen is always beside the button. + */ +export function CheckoutFrame({ + layout, + creator, + banner, + body, + footer, + onSubmit, +}: CheckoutFrameProps) { + const top = ( + <> + {banner} + {creator} + + {body} + + ); + + if (layout === 'mobile') { + return ( + + + {top} + + + {footer} + + + ); + } + + return ( + + + {top} + + + {footer} + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutHalts.tsx b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutHalts.tsx new file mode 100644 index 0000000..aa82ec9 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutHalts.tsx @@ -0,0 +1,148 @@ +import { Amount } from '@lumina/island/atoms/amount'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StateArt } from '@lumina/island/atoms/state-art'; +import { Typography } from '@lumina/island/atoms/typography'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../../../../navigation/navigation'; +import type { CheckoutPartProps } from '../types'; +import { HaltDialog } from './HaltDialog'; + +/** + * What stops a payment before the bank (U9 §۵–۶), each a blocking sheet or modal: + * - the price moved: old and new price, the new total, «تأیید و پرداخت» at the new figure or + * «انصراف» back to a checkout read again at current prices (۵.۱); + * - the creator was suspended in between: nothing was charged, and home is the one way on (۵.۵); + * - the code is valid but the channel is full: join the waitlist or not, both back to the channel + * (۶.۱); already on it, one way back (۶.۲). + */ +export function CheckoutHalts({ model, layout }: CheckoutPartProps) { + const { t } = useTranslation('payment'); + const { halt, phase } = model; + const size = layout === 'mobile' ? 'lg' : 'md'; + const currency = t('tier.currency'); + const priceChange = halt?.kind === 'price-changed' ? halt : null; + + return ( + <> + + + + + } + > + {priceChange && ( + + + {t('checkout.price-changed.from')}{' '} + {' '} + {t('checkout.price-changed.to')}{' '} + {' '} + {t('checkout.price-changed.changed')} + + + + {t('checkout.price-changed.total')} + + + + + )} + + + } + title={t('checkout.unavailable.title')} + buttons={ + + } + /> + + + + + + } + > + {t('checkout.waitlist.body')} + + + } + title={t('checkout.waitlist.title')} + buttons={ + + } + > + + {t('checkout.waitlist.already')} + + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutTiers.tsx b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutTiers.tsx new file mode 100644 index 0000000..5481873 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/CheckoutTiers.tsx @@ -0,0 +1,90 @@ +import { Countdown } from '@lumina/island/atoms/countdown'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { TierOption } from '@lumina/island/organisms/tier-option'; +import { useId } from 'react'; +import { Controller } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { BILLING_PERIOD_MONTHS } from '../../../../../../../../shared/constants'; +import { + promotionCountdownLabels, + tierOptionLabels, +} from '../../../../../../../../shared/labels'; +import type { CheckoutPartProps } from '../types'; + +/** + * «دوره اشتراک»: one radio card per active period, cheapest first, none picked (U9 ۲.۱); a creator + * with one period shows one card, and it still needs a tap (۲.۳). A promoted tier strikes its + * standing price and, unless open-ended, says when the promotion ends: a date, then hours inside + * 48, then «کمتر از ۱ ساعت» (§۳). Changing the period never re-checks the code (۴.۲). + */ +export function CheckoutTiers({ model, layout }: CheckoutPartProps) { + const { t } = useTranslation('payment'); + const { t: tCommon } = useTranslation('common'); + const headingId = useId(); + const labels = tierOptionLabels(t); + const countdownLabels = promotionCountdownLabels(t); + + return ( + + + {t('checkout.tiers')} + + ( + + {model.tiers.map((tier) => { + const { promotion } = tier; + const isPromotion = + promotion !== null && + tier.standingPriceToman !== null && + tier.priceToman !== null && + tier.standingPriceToman > tier.priceToman; + return ( + + {isPromotion && promotion.endsAt && !promotion.indefinite && ( + + )} + + ); + })} + + )} + /> + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/HaltDialog.tsx b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/HaltDialog.tsx new file mode 100644 index 0000000..a8778ce --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/components/HaltDialog.tsx @@ -0,0 +1,42 @@ +import { Modal } from '@lumina/island/molecules/modal'; +import { Sheet } from '@lumina/island/molecules/sheet'; + +import type { HaltDialogProps } from '../types'; + +/** + * A halt on checkout: a bottom sheet on mobile, a centred modal on desktop (U9 ۹.۲), with no ✕, + * and Escape and the scrim doing nothing. Its buttons are the only ways out, confirm first. + */ +export function HaltDialog({ + layout, + open, + title, + icon, + alert = false, + buttons, + children, +}: HaltDialogProps) { + return layout === 'mobile' ? ( + + {children} + + ) : ( + + {children} + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/index.ts b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/index.ts new file mode 100644 index 0000000..bb465f6 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/index.ts @@ -0,0 +1,7 @@ +export { CheckoutPanel } from './CheckoutPanel'; +export { CheckoutSkeleton } from './CheckoutSkeleton'; +export type { + CheckoutLayout, + CheckoutPanelProps, + CheckoutSkeletonProps, +} from './types'; diff --git a/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/types.ts b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/types.ts new file mode 100644 index 0000000..0b71aa8 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/checkout/[username]/organisms/checkout-panel/types.ts @@ -0,0 +1,53 @@ +import type { FormEvent, ReactNode } from 'react'; + +import type { CheckoutPageModel } from '../../../../../../../features/checkout'; + +export type CheckoutLayout = 'mobile' | 'desktop'; + +export type CheckoutPanelProps = { + /** The creator's account id. */ + creatorId: string; + /** The creator's channel: a declined waitlist and «بازگشت به کانال» go there. */ + channelHref: string; + layout: CheckoutLayout; + /** Who is being paid, rendered on the server: CheckoutCreator. */ + creator: ReactNode; +}; + +export type CheckoutFormProps = CheckoutPanelProps; + +export type CheckoutFrameProps = { + layout: CheckoutLayout; + creator: ReactNode; + /** Above everything, such as the connection error (U9 ۵.۳). */ + banner?: ReactNode; + /** The invite note, the tiers and the code. */ + body: ReactNode; + /** The total, the terms line and «پرداخت». */ + footer: ReactNode; + onSubmit?: (event: FormEvent) => void; +}; + +export type CheckoutPartProps = { + model: CheckoutPageModel; + layout: CheckoutLayout; +}; + +export type CheckoutSkeletonProps = { + layout: CheckoutLayout; + creator: ReactNode; + label: string; +}; + +export type HaltDialogProps = { + layout: CheckoutLayout; + open: boolean; + title: ReactNode; + /** Art above the title, such as the suspended creator's ban. */ + icon?: ReactNode; + /** It interrupts a payment: `role="alertdialog"`. */ + alert?: boolean; + /** Stacked, confirm first. */ + buttons: ReactNode; + children?: ReactNode; +}; diff --git a/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResult.tsx b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResult.tsx new file mode 100644 index 0000000..74b0e11 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResult.tsx @@ -0,0 +1,62 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { useTranslation } from 'react-i18next'; + +import { usePaymentResultPage } from '../../../../../../../../features/checkout'; +import { SupportEntry } from '../../../../../../organisms/support-entry'; +import { ResultActions } from './components/ResultActions'; +import { ResultFrame } from './components/ResultFrame'; +import { ResultHead } from './components/ResultHead'; +import { ResultReceipt } from './components/ResultReceipt'; +import { PaymentResultSkeleton } from './PaymentResultSkeleton'; +import type { PaymentResultProps } from './types'; + +/** + * The end of every payment (U10 §۹): success, failed or in review, with the receipt and the + * bank's reference. A failure and a payment in review say what happens to the money and keep + * «تماس با پشتیبانی» under the note. The investor's own payment, so it loads in the browser. + */ +export function PaymentResult({ paymentId, layout }: PaymentResultProps) { + const { t } = useTranslation('payment'); + const { payment, kind, copyReference } = usePaymentResultPage({ paymentId }); + + if (!payment || !kind) { + return ( + + ); + } + + return ( + + + + + + {t(`result.${kind}.note`)} + + {kind !== 'success' && ( + + )} + + + } + actions={} + /> + ); +} diff --git a/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResultSkeleton.tsx b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResultSkeleton.tsx new file mode 100644 index 0000000..529df87 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/PaymentResultSkeleton.tsx @@ -0,0 +1,61 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; +import { Card } from '@lumina/island/molecules/card'; + +import { ResultFrame } from './components/ResultFrame'; +import type { PaymentResultSkeletonProps } from './types'; + +const RECEIPT_ROWS = ['period', 'amount', 'date', 'expiry', 'reference']; + +/** The result before the payment arrives: the icon, two lines, the receipt and two buttons. */ +export function PaymentResultSkeleton({ + layout, + label, +}: PaymentResultSkeletonProps) { + return ( + + + + + + + + + + + + + + + {RECEIPT_ROWS.map((row) => ( + + + + + ))} + + + + } + actions={ + <> + + + + } + /> + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultActions.tsx b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultActions.tsx new file mode 100644 index 0000000..63692dd --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultActions.tsx @@ -0,0 +1,86 @@ +import { Button } from '@lumina/island/atoms/button'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../../../../../navigation/navigation'; +import type { ResultActionsProps } from '../types'; + +/** + * Where to go from the result, primary then secondary (U10 ۹.۱–۹.۳). Success: the channel paid + * for, open now, then the subscriptions. Failed: «تلاش دوباره», back to checkout with the period + * and code kept (a renewal retries from its card in اشتراک‌ها), then the channel. + * In review: the channel, which shows the frozen indicator so nobody pays twice, then the + * transactions. A payment whose creator has no handle left offers those lists only. + */ +export function ResultActions({ kind, payment }: ResultActionsProps) { + const { t } = useTranslation('payment'); + const { username, displayName } = payment.creator; + const name = + displayName ?? (username ? t('result.handle', { username }) : ''); + + const channel = username ? ( + + ) : null; + + if (kind === 'failed') { + return ( + <> + {payment.type === 'renew' ? ( + + ) : username ? ( + + ) : ( + + )} + {channel} + + ); + } + + return ( + <> + {channel} + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultFrame.tsx b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultFrame.tsx new file mode 100644 index 0000000..b01589e --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultFrame.tsx @@ -0,0 +1,42 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Card } from '@lumina/island/molecules/card'; + +import type { ResultFrameProps } from '../types'; + +/** + * The result's layout. Mobile: the head, receipt and note on white, with the two buttons pinned to + * the bottom. Desktop: all of it in one panel of the 480 column, the buttons last (U10 ۹.۴). + */ +export function ResultFrame({ layout, body, actions }: ResultFrameProps) { + if (layout === 'mobile') { + return ( + + + {body} + + + {actions} + + + ); + } + + return ( + + {body} + + {actions} + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultHead.tsx b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultHead.tsx new file mode 100644 index 0000000..c3089b9 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultHead.tsx @@ -0,0 +1,38 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import type { IconName } from '@lumina/island/atoms/icon'; +import { StateArt } from '@lumina/island/atoms/state-art'; +import type { StateTone } from '@lumina/island/atoms/state-art'; +import { Typography } from '@lumina/island/atoms/typography'; +import { useTranslation } from 'react-i18next'; + +import type { PaymentResultKind } from '../../../../../../../../../features/checkout'; +import type { ResultHeadProps } from '../types'; + +const ART: Record = { + success: { icon: 'check-circle', tone: 'success' }, + failed: { icon: 'x-circle', tone: 'danger' }, + pending: { icon: 'clock', tone: 'warning' }, +}; + +/** What happened, first and in one look: the tone's icon, the outcome, and what it means now. */ +export function ResultHead({ kind }: ResultHeadProps) { + const { t } = useTranslation('payment'); + + return ( + + + + {t(`result.${kind}.title`)} + + + {t(`result.${kind}.description`)} + + + ); +} diff --git a/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultReceipt.tsx b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultReceipt.tsx new file mode 100644 index 0000000..92a1595 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/payment/result/[paymentId]/organisms/payment-result/components/ResultReceipt.tsx @@ -0,0 +1,112 @@ +import { Amount } from '@lumina/island/atoms/amount'; +import { Avatar } from '@lumina/island/atoms/avatar'; +import { Button } from '@lumina/island/atoms/button'; +import { DateTime } from '@lumina/island/atoms/date-time'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { Element } from '@lumina/island/primitives/element'; +import { useTranslation } from 'react-i18next'; + +import type { ResultReceiptProps } from '../types'; + +/** + * The receipt (U10 ۹.۱–۹.۳): who was paid with the payment's status, then the period, the amount, + * when, the expiry once it is active, and the bank's reference with a copy button, which is what + * support asks for first. A failed attempt shows when it was tried instead. + */ +export function ResultReceipt({ + kind, + payment, + onCopyReference, +}: ResultReceiptProps) { + const { t } = useTranslation('payment'); + const { t: tCommon } = useTranslation('common'); + const { creator } = payment; + + return ( + + + + + + {creator.displayName ?? + (creator.username && ( + + @{creator.username} + + ))} + + {creator.displayName && creator.username && ( + + + @{creator.username} + + + )} + + + {tCommon(`status.payment.${payment.status}`)} + + + + + {tCommon(`billing-periods.${payment.billingPeriod}`)} + + {payment.amountToman !== null && ( + + + + )} + {payment.createdAt && ( + + + + )} + {kind === 'success' && payment.period?.to && ( + + + + )} + {payment.reference && ( + + + + {payment.reference} + + + ) : ( + + )} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalSkeleton.tsx b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalSkeleton.tsx new file mode 100644 index 0000000..d2eef97 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalSkeleton.tsx @@ -0,0 +1,35 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; +import { Card } from '@lumina/island/molecules/card'; + +const TIER_ROWS = ['monthly', 'quarterly', 'semi-annual', 'yearly']; + +/** The sheet's body before the periods arrive: the creator, four periods, the dates and the total. */ +export function RenewalSkeleton({ label }: { label: string }) { + return ( + + + + + + + + + {TIER_ROWS.map((row) => ( + + + + + + + + + + ))} + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/index.ts b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/index.ts new file mode 100644 index 0000000..caac856 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/index.ts @@ -0,0 +1,2 @@ +export { RenewalSheet } from './RenewalSheet'; +export type { DashboardLayout, RenewalSheetProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/types.ts b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/types.ts new file mode 100644 index 0000000..dc29105 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/types.ts @@ -0,0 +1,16 @@ +import type { SubscriptionPayload } from '../../../../../../../features/subscription'; + +export type DashboardLayout = 'mobile' | 'desktop'; + +export type RenewalSheetProps = { + /** The card whose «تمدید» or «فعال‌سازی مجدد» opened it. */ + target: SubscriptionPayload; + open: boolean; + layout: DashboardLayout; + onClose: () => void; +}; + +export type RenewalFormProps = { + subscriptionId: string; + layout: DashboardLayout; +}; diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/SubscriptionList.tsx b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/SubscriptionList.tsx new file mode 100644 index 0000000..d472f1f --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/SubscriptionList.tsx @@ -0,0 +1,84 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import { useSubscriptionsPart } from '../../../../../../../features/subscription'; +import { SupportDialog } from '../../../../../organisms/support-entry'; +import { RenewalSheet } from '../renewal-sheet'; +import { SubscriptionItem } from './components/SubscriptionItem'; +import { SubscriptionsEmpty } from './components/SubscriptionsEmpty'; +import type { SubscriptionListProps } from './types'; + +/** + * داشبورد › اشتراک‌ها (U2, U11): how many are active, then the active cards by nearest expiry, a + * suspended creator's among them, then «اشتراک‌های منقضی‌شده». No active one: the empty state, + * with the expired ones still under it (۳.۲). «تمدید» and «فعال‌سازی مجدد» open the renewal sheet; + * support opens the support sheet, a bottom sheet on mobile and a centred modal on desktop, where + * the card's link can't anchor a popover. + */ +export function SubscriptionList({ layout }: SubscriptionListProps) { + const { t } = useTranslation('dashboard'); + const model = useSubscriptionsPart(); + const { active, expired, activeCount } = model.dashboard; + const gap = layout === 'desktop' ? 'gap-4' : 'gap-3'; + + const list = (items: typeof active) => ( + + {items.map((subscription) => ( + model.openRenewal(subscription)} + onSupport={model.openSupport} + /> + ))} + + ); + + return ( + <> + + + {activeCount > 0 + ? t('subscriptions.active-count', { n: number(activeCount) }) + : t('subscriptions.no-active')} + + {active.length > 0 ? ( + list(active) + ) : ( + + )} + {expired.length > 0 && ( + <> + + {t('subscriptions.expired')} + + {list(expired)} + + )} + + {model.renewalTarget && ( + + )} + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/components/SubscriptionItem.tsx b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/components/SubscriptionItem.tsx new file mode 100644 index 0000000..bfdebb6 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/components/SubscriptionItem.tsx @@ -0,0 +1,51 @@ +import { SubscriptionCard } from '@lumina/island/organisms/subscription-card'; +import { Element } from '@lumina/island/primitives/element'; +import { useTranslation } from 'react-i18next'; + +import { subscriptionCardLabels } from '../../../../../../../../shared/labels'; +import { ROUTES } from '../../../../../../../navigation/navigation'; +import type { SubscriptionItemProps } from '../types'; + +/** + * One subscription as its card (U2): an active one opens its channel and offers «تمدید»; a + * suspended creator's is dimmed with support and the terms, and opens nothing (۱.۳); an expired + * one offers «فعال‌سازی مجدد», or support while its creator is still suspended (۲.۲); a refunded + * one reads «پایان یافته · بازگشت وجه» with its end date. The creator's display name heads the + * card, their handle under it; without a display name the handle stands for both. + */ +export function SubscriptionItem({ + subscription, + onRenew, + onSupport, +}: SubscriptionItemProps) { + const { t } = useTranslation('dashboard'); + const { t: tCommon } = useTranslation('common'); + const { creator, status } = subscription; + const username = creator.username ?? ''; + + return ( + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/components/SubscriptionsEmpty.tsx b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/components/SubscriptionsEmpty.tsx new file mode 100644 index 0000000..0ebf481 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/components/SubscriptionsEmpty.tsx @@ -0,0 +1,30 @@ +import { Button } from '@lumina/island/atoms/button'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../../../../navigation/navigation'; +import type { SubscriptionsEmptyProps } from '../types'; + +/** + * No active subscription (U2 ۳.۲): one way on, to خانه. Mobile centres it in the tab at page size; + * desktop puts it in a card in the column at section size, as the sibling tabs do. + */ +export function SubscriptionsEmpty({ layout }: SubscriptionsEmptyProps) { + const { t } = useTranslation('dashboard'); + const isDesktop = layout === 'desktop'; + const state = ( + + + + ); + + return isDesktop ? {state} : state; +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/index.ts b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/index.ts new file mode 100644 index 0000000..b9e283a --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/index.ts @@ -0,0 +1,2 @@ +export { SubscriptionList } from './SubscriptionList'; +export type { DashboardLayout, SubscriptionListProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/types.ts b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/types.ts new file mode 100644 index 0000000..aab5806 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/subscription-list/types.ts @@ -0,0 +1,13 @@ +import type { SubscriptionPayload } from '../../../../../../../features/subscription'; + +export type DashboardLayout = 'mobile' | 'desktop'; + +export type SubscriptionListProps = { layout: DashboardLayout }; + +export type SubscriptionsEmptyProps = { layout: DashboardLayout }; + +export type SubscriptionItemProps = { + subscription: SubscriptionPayload; + onRenew: () => void; + onSupport: () => void; +}; diff --git a/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/TransactionList.tsx b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/TransactionList.tsx new file mode 100644 index 0000000..27e86e7 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/TransactionList.tsx @@ -0,0 +1,97 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { FilterChips } from '@lumina/island/molecules/filter-chips'; +import { useTranslation } from 'react-i18next'; + +import { + TRANSACTION_FILTERS, + useTransactionsPart, +} from '../../../../../../../features/transaction'; +import { TransactionDetail } from './components/TransactionDetail'; +import { TransactionRow } from './components/TransactionRow'; +import { TransactionsEmpty } from './components/TransactionsEmpty'; +import type { TransactionListProps } from './types'; + +/** + * داشبورد › تراکنش‌ها (U4): the status chips (همه · موفق · در حال بررسی · ناموفق), which apply at + * once and keep the rows until the new ones arrive, then the payments, pending first, then newest + * first, 20 at a time. No payment at all: the empty state without chips (۴.۲); none for a status: + * a quiet line under the chips (۳.۴). A row opens its detail. + */ +export function TransactionList({ layout }: TransactionListProps) { + const { t } = useTranslation(['dashboard', 'errors']); + const model = useTransactionsPart(); + const gap = layout === 'desktop' ? 'gap-4' : 'gap-3'; + + if (model.isEmpty) return ; + + return ( + <> + + ({ + value, + label: t(`transactions.filters.${value}`), + }))} + value={model.filter} + onChange={model.setFilter} + /> + {model.rows.length === 0 ? ( + + ) : ( + + {model.rows.map((row) => ( + model.openDetail(row)} + /> + ))} + + )} + {model.loadMoreError ? ( + + ) : ( + model.hasMore && ( + + ) + )} + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/TransactionDetail.tsx b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/TransactionDetail.tsx new file mode 100644 index 0000000..d30f612 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/TransactionDetail.tsx @@ -0,0 +1,221 @@ +import { Amount } from '@lumina/island/atoms/amount'; +import { Button } from '@lumina/island/atoms/button'; +import { DateTime } from '@lumina/island/atoms/date-time'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { Typography } from '@lumina/island/atoms/typography'; +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { Element } from '@lumina/island/primitives/element'; +import { date } from '@lumina/tools/format'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { SupportDialog } from '../../../../../../organisms/support-entry'; +import type { TransactionDetailProps } from '../types'; +import { useTransactionTitle } from './use-transaction-title'; + +/** + * «تماس با پشتیبانی» under a failed or pending payment: the support sheet over the detail (۴.۱), + * or a popover under it on desktop. Its open state lives inside the detail's content, which closes + * with the detail, and is keyed by the row, so it never reopens over another payment. + */ +function DetailSupport({ isDesktop }: { isDesktop: boolean }) { + const { t } = useTranslation('dashboard'); + const [isSupportOpen, setIsSupportOpen] = useState(false); + + return ( + // A popover hangs from a positioned parent that also holds its trigger. + + + setIsSupportOpen(false)} + /> + + ); +} + +/** + * A payment's detail (U4 ۱.۳, ۲.۱, ۲.۳): a bottom sheet on mobile, a side panel on desktop, the + * list still behind it. A payment in review leads with the bank's reference, the first thing + * support asks for; a successful one with what was paid and the period it bought. The reference + * copies with a toast. Failed and pending ones end with what happens to the money and «تماس با + * پشتیبانی», which opens the support sheet over the detail (۴.۱), or a popover under it on desktop. + * A refund (S3 ۱.۲) leads with the amount paid back, then the channel, the date, the transfer's + * tracking number and the masked شبا it went to; the payment it refunded ends its period on the + * refund date and says so (۱.۳). + */ +export function TransactionDetail({ model, layout }: TransactionDetailProps) { + const { t } = useTranslation('dashboard'); + const { t: tCommon } = useTranslation('common'); + const titleOf = useTransactionTitle(); + const row = model.detail; + if (!row) return null; + + const isDesktop = layout === 'desktop'; + const copy = row.reference && ( + + + ); + + return isDesktop ? {state} : state; +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/use-transaction-title.ts b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/use-transaction-title.ts new file mode 100644 index 0000000..c81b4d8 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/components/use-transaction-title.ts @@ -0,0 +1,23 @@ +import { useTranslation } from 'react-i18next'; + +import type { TransactionPayload } from '../../../../../../../../features/transaction'; + +/** + * «اشتراک سالانه — رضا احمدی»: what the payment bought, from whom, by the creator's display name or + * else their handle. A refund row is «بازگشت وجه». + */ +export function useTransactionTitle(): (row: TransactionPayload) => string { + const { t } = useTranslation('dashboard'); + const { t: tCommon } = useTranslation('common'); + + return (row) => + row.type === 'refund' + ? t('transactions.refund-title') + : t('transactions.title', { + kind: t(`transactions.kinds.${row.type}`), + period: tCommon(`billing-periods.${row.billingPeriod}`), + name: + row.creator.displayName ?? + t('transactions.handle', { username: row.creator.username ?? '' }), + }); +} diff --git a/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/index.ts b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/index.ts new file mode 100644 index 0000000..0457944 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/index.ts @@ -0,0 +1,2 @@ +export { TransactionList } from './TransactionList'; +export type { DashboardLayout, TransactionListProps } from './types'; diff --git a/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/types.ts b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/types.ts new file mode 100644 index 0000000..95936ac --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/transactions/organisms/transaction-list/types.ts @@ -0,0 +1,21 @@ +import type { + TransactionPayload, + TransactionsPartModel, +} from '../../../../../../../features/transaction'; + +export type DashboardLayout = 'mobile' | 'desktop'; + +export type TransactionListProps = { layout: DashboardLayout }; + +export type TransactionRowProps = { + row: TransactionPayload; + layout: DashboardLayout; + onOpen: () => void; +}; + +export type TransactionDetailProps = { + model: TransactionsPartModel; + layout: DashboardLayout; +}; + +export type TransactionsEmptyProps = { layout: DashboardLayout }; diff --git a/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/NotificationCentre.tsx b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/NotificationCentre.tsx new file mode 100644 index 0000000..6ccc122 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/NotificationCentre.tsx @@ -0,0 +1,48 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import { useNotificationCentre } from '../../../../../../features/notification'; +import { NotificationItem } from './components/NotificationItem'; +import type { NotificationCentreProps } from './types'; + +/** + * اعلان‌ها (U5 §۲): every notification of the last 30 days, newest first, in one list whatever its + * type. Opening it clears the bell. Nothing there: one calm line, with no action (۲.۳). + */ +export function NotificationCentre({ + layout, + supportPlacement, +}: NotificationCentreProps) { + const { t } = useTranslation('notifications'); + const model = useNotificationCentre(); + + if (model.items.length === 0) { + return ( + + ); + } + + return ( + + {model.items.map((item) => ( + model.open(item)} + isOpening={model.openingId === item.id} + supportPlacement={supportPlacement} + /> + ))} + + ); +} diff --git a/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/NotificationPanel.tsx b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/NotificationPanel.tsx new file mode 100644 index 0000000..320d602 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/NotificationPanel.tsx @@ -0,0 +1,37 @@ +'use client'; + +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { Suspense } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { PartBoundary } from '../../../../../error-boundaries'; +import { NotificationCentre } from './NotificationCentre'; +import type { NotificationPanelProps } from './types'; + +/** + * The centre on desktop (U5 ۴.۱): a 400px side panel from the header's bell, over whatever page is + * open. ✕, Escape and the scrim close it. The list loads inside it with its own skeleton and error. + */ +export function NotificationPanel({ open, onClose }: NotificationPanelProps) { + const { t } = useTranslation('notifications'); + const skeleton = ( + + ); + + return ( + + + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/components/NotificationItem.tsx b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/components/NotificationItem.tsx new file mode 100644 index 0000000..946ae6b --- /dev/null +++ b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/components/NotificationItem.tsx @@ -0,0 +1,206 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Link } from '@lumina/island/atoms/link'; +import { LinkButton } from '@lumina/island/atoms/link-button'; +import { SupportLink } from '@lumina/island/atoms/support-link'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { Element } from '@lumina/island/primitives/element'; +import { cn } from '@lumina/island/tools/cn'; +import { relative } from '@lumina/tools/format'; +import NextLink from 'next/link'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { SupportDialog } from '../../../../../organisms/support-entry'; +import { + NOTIFICATION_ART, + NOTIFICATION_CTA_TYPES, + NOTIFICATION_FALLBACK_ART, + NOTIFICATION_SUPPORT_TYPES, + NOTIFICATION_TONE_CLASS, +} from '../constants'; +import type { NotificationItemProps } from '../types'; + +type CtaType = (typeof NOTIFICATION_CTA_TYPES)[number]; + +const CTA_TYPES: ReadonlySet = new Set(NOTIFICATION_CTA_TYPES); + +const isCtaType = (type: string): type is CtaType => CTA_TYPES.has(type); + +const SUPPORT_TYPES: ReadonlySet = new Set(NOTIFICATION_SUPPORT_TYPES); + +/** + * One notification (U5 ۱.۱, ۲.۱): its icon tile, the title, the body, when it came — relative + * while recent, then the Shamsi date and time — and its call to action where one applies. The + * server writes the title and body with the names and amounts in them. An unread one carries the + * brand start border. An item that leads somewhere opens it from anywhere on the card, its body + * clamped to 2 lines; one that leads nowhere (a receipt) opens its full body on tap instead. An + * app path is a real link; a creator's channel is looked up first, so it is a button. The expiry + * notice of a suspended creator's channel offers «تماس با پشتیبانی» in place (U5 ۳.۱, ۳.۲). + */ +export function NotificationItem({ + item, + target, + onOpen, + isOpening, + supportPlacement, +}: NotificationItemProps) { + const { t } = useTranslation('notifications'); + const [isExpanded, setIsExpanded] = useState(false); + const [isSupportOpen, setIsSupportOpen] = useState(false); + const opensSupport = SUPPORT_TYPES.has(item.type); + // The type comes from the server, which may send one added after this build. + const art = Object.hasOwn(NOTIFICATION_ART, item.type) + ? NOTIFICATION_ART[item.type] + : NOTIFICATION_FALLBACK_ART; + const leads = target.kind !== 'none'; + const cta = leads && isCtaType(item.type) ? item.type : null; + + const title = ( + + {item.serverTitle} + + ); + const unread = !item.read && ( + + {` (${t('unread')})`} + + ); + const stretched = + 'cursor-pointer text-start text-text-primary no-underline outline-none after:absolute after:inset-0 after:rounded-lg'; + + return ( + + + + + + + + + {target.kind === 'path' ? ( + + {title} + {unread} + + ) : target.kind === 'creator' ? ( + + {title} + {unread} + + ) : ( + <> + {title} + {unread} + + )} + + {leads ? ( + + {item.serverMessage} + + ) : ( + setIsExpanded((expanded) => !expanded)} + className={stretched} + > + + {item.serverMessage} + + + )} + + {item.createdAt && ( + + {relative(item.createdAt)} + + )} + {/* Above the stretched link, so it keeps its own tap and focus. */} + {cta && target.kind === 'path' && ( + + {t(`cta.${cta}`)} + + )} + {cta && target.kind === 'creator' && ( + + {t(`cta.${cta}`)} + + )} + {opensSupport && ( + // A popover hangs from a positioned parent that also holds its trigger. + + setIsSupportOpen((open) => !open)} + > + {t('support')} + + setIsSupportOpen(false)} + /> + + )} + + + + + + ); +} diff --git a/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/constants.ts b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/constants.ts new file mode 100644 index 0000000..ef84440 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/constants.ts @@ -0,0 +1,57 @@ +import type { IconName } from '@lumina/island/atoms/icon'; + +import type { NotificationType } from '../../../../../../features/notification'; + +/** The tile's tone: its subtle ground and icon colour. */ +export type NotificationTone = 'success' | 'warning' | 'neutral' | 'brand'; + +/** Each notification type's icon tile (U5 ۲.۱): a payment confirmed is a check on success, etc. */ +export const NOTIFICATION_ART: Record< + NotificationType, + { icon: IconName; tone: NotificationTone } +> = { + subscription_subscribe: { icon: 'check', tone: 'success' }, + subscription_renew: { icon: 'check', tone: 'success' }, + subscription_reactivate: { icon: 'check', tone: 'success' }, + subscription_delayed_confirm: { icon: 'check', tone: 'success' }, + subscription_expiry_warning: { icon: 'clock', tone: 'warning' }, + subscription_expired: { icon: 'clock', tone: 'neutral' }, + payment_pending_review: { icon: 'clock', tone: 'warning' }, + subscription_expired_suspended: { icon: 'clock', tone: 'neutral' }, + waitlist_capacity: { icon: 'users', tone: 'brand' }, + new_subscriber: { icon: 'users', tone: 'brand' }, + creator_suspended: { icon: 'ban', tone: 'warning' }, + access_restored: { icon: 'check', tone: 'brand' }, + account_suspended: { icon: 'ban', tone: 'warning' }, + account_reinstated: { icon: 'check', tone: 'brand' }, +}; + +/** A type this front end doesn't know yet (a newer service, an old row): a plain bell. */ +export const NOTIFICATION_FALLBACK_ART: { + icon: IconName; + tone: NotificationTone; +} = { icon: 'bell', tone: 'neutral' }; + +/** Tile classes per tone: the `-subtle` ground with the matching text colour. */ +export const NOTIFICATION_TONE_CLASS: Record = { + success: 'bg-success-subtle text-success-text', + warning: 'bg-warning-subtle text-warning-text', + neutral: 'bg-surface-sunken text-text-secondary', + brand: 'bg-action-primary-subtle text-action-primary', +}; + +/** The types whose item carries a call to action; the rest lead nowhere or are a receipt. */ +export const NOTIFICATION_CTA_TYPES = [ + 'subscription_expiry_warning', + 'subscription_expired', + 'subscription_delayed_confirm', + 'waitlist_capacity', + 'payment_pending_review', + 'creator_suspended', + 'access_restored', +] as const satisfies readonly NotificationType[]; + +/** Types whose call to action is support itself, opened in place (U5 ۳.۱, ۳.۲). */ +export const NOTIFICATION_SUPPORT_TYPES = [ + 'subscription_expired_suspended', +] as const satisfies readonly NotificationType[]; diff --git a/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/index.ts b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/index.ts new file mode 100644 index 0000000..44e6cfe --- /dev/null +++ b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/index.ts @@ -0,0 +1,8 @@ +export { NOTIFICATION_ART } from './constants'; +export { NotificationCentre } from './NotificationCentre'; +export { NotificationPanel } from './NotificationPanel'; +export type { + NotificationCentreLayout, + NotificationCentreProps, + NotificationPanelProps, +} from './types'; diff --git a/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/types.ts b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/types.ts new file mode 100644 index 0000000..87ff37e --- /dev/null +++ b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/types.ts @@ -0,0 +1,26 @@ +import type { + NotificationPayload, + NotificationTarget, +} from '../../../../../../features/notification'; + +/** `page`: the mobile centre (and desktop's direct visit). `panel`: desktop's side panel. */ +export type NotificationCentreLayout = 'page' | 'panel'; + +export type NotificationCentreProps = { + layout: NotificationCentreLayout; + /** Where an item's «تماس با پشتیبانی» opens support: a bottom sheet, or a popover under it. */ + supportPlacement: 'bottom' | 'popover'; +}; + +export type NotificationItemProps = { + item: NotificationPayload; + target: NotificationTarget; + onOpen: () => void; + isOpening: boolean; + supportPlacement: 'bottom' | 'popover'; +}; + +export type NotificationPanelProps = { + open: boolean; + onClose: () => void; +}; diff --git a/platforms/market/src/app/screens/organisms/support-entry/SupportDialog.tsx b/platforms/market/src/app/screens/organisms/support-entry/SupportDialog.tsx new file mode 100644 index 0000000..e3ffa4b --- /dev/null +++ b/platforms/market/src/app/screens/organisms/support-entry/SupportDialog.tsx @@ -0,0 +1,44 @@ +'use client'; + +import { SupportSheet } from '@lumina/island/organisms/support-sheet'; +import { useTranslation } from 'react-i18next'; + +import { getEnv } from '../../../../env'; +import { ROUTES } from '../../../navigation/navigation'; +import { supportChatUrls } from './support-chats'; +import type { SupportDialogProps } from './types'; + +/** + * The support sheet with the chats and hours from config, opened by a trigger the caller owns, + * such as «تماس با پشتیبانی» inside a subscription card. A bottom sheet on mobile; on desktop a + * popover under its trigger, or a centred modal where the trigger can't anchor one. + */ +export function SupportDialog({ + placement, + open, + onClose, +}: SupportDialogProps) { + const { t } = useTranslation('auth'); + const { supportHours } = getEnv(); + const chats = supportChatUrls(); + + return ( + + ); +} diff --git a/platforms/market/src/app/screens/organisms/support-entry/SupportEntry.tsx b/platforms/market/src/app/screens/organisms/support-entry/SupportEntry.tsx index 09d1fb9..64d3554 100644 --- a/platforms/market/src/app/screens/organisms/support-entry/SupportEntry.tsx +++ b/platforms/market/src/app/screens/organisms/support-entry/SupportEntry.tsx @@ -3,13 +3,10 @@ import { Button } from '@lumina/island/atoms/button'; import { FlexBox } from '@lumina/island/atoms/flex-box'; import { SupportLink } from '@lumina/island/atoms/support-link'; -import { SupportSheet } from '@lumina/island/organisms/support-sheet'; import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { getEnv } from '../../../../env'; -import { ROUTES } from '../../../navigation/navigation'; -import { supportChatUrls } from './support-chats'; +import { SupportDialog } from './SupportDialog'; import type { SupportEntryProps } from './types'; /** @@ -23,8 +20,6 @@ export function SupportEntry({ }: SupportEntryProps) { const { t } = useTranslation('auth'); const [isOpen, setIsOpen] = useState(false); - const { supportHours } = getEnv(); - const chats = supportChatUrls(); const toggle = () => setIsOpen((open) => !open); const dialogProps = { 'aria-haspopup': 'dialog', @@ -57,22 +52,10 @@ export function SupportEntry({ ); const sheet = ( - setIsOpen(false)} - baleHref={chats.bale} - telegramHref={chats.telegram} - termsHref={ROUTES.terms} - labels={{ - title: t('support.title'), - bale: t('support.bale'), - telegram: t('support.telegram'), - hours: t('support.hours', { hours: supportHours }), - terms: t('support.terms'), - close: t('support.close'), - opensNewTab: t('support.opens-new-tab'), - }} /> ); diff --git a/platforms/market/src/app/screens/organisms/support-entry/index.ts b/platforms/market/src/app/screens/organisms/support-entry/index.ts index 7ef63b4..c5de5d5 100644 --- a/platforms/market/src/app/screens/organisms/support-entry/index.ts +++ b/platforms/market/src/app/screens/organisms/support-entry/index.ts @@ -1,3 +1,8 @@ export { supportChatUrls } from './support-chats'; +export { SupportDialog } from './SupportDialog'; export { SupportEntry } from './SupportEntry'; -export type { SupportChats, SupportEntryProps } from './types'; +export type { + SupportChats, + SupportDialogProps, + SupportEntryProps, +} from './types'; diff --git a/platforms/market/src/app/screens/organisms/support-entry/types.ts b/platforms/market/src/app/screens/organisms/support-entry/types.ts index fdf8491..5f8e0ee 100644 --- a/platforms/market/src/app/screens/organisms/support-entry/types.ts +++ b/platforms/market/src/app/screens/organisms/support-entry/types.ts @@ -14,3 +14,10 @@ export type SupportEntryProps = { /** The support chats' addresses. */ export type SupportChats = { bale: string; telegram: string }; + +export type SupportDialogProps = { + /** bottom: mobile. popover: desktop, inside the trigger's positioned parent. modal: no anchor. */ + placement: Extract; + open: boolean; + onClose: () => void; +}; diff --git a/platforms/market/src/features/checkout/actions/join-waitlist/actions.ts b/platforms/market/src/features/checkout/actions/join-waitlist/actions.ts new file mode 100644 index 0000000..0b38a1c --- /dev/null +++ b/platforms/market/src/features/checkout/actions/join-waitlist/actions.ts @@ -0,0 +1,25 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { CHECKOUT_EVENTS } from '../../constants'; +import { checkoutRepository } from '../../repositories/checkout'; +import type { + ReferralCodeArgs, + WaitlistJoinedPayload, +} from '../../repositories/checkout'; + +/** + * Puts the investor on a full channel's waitlist with their valid code (U9 ۶.۱): they hear when a + * seat opens, and subscribing stays open. Emits `checkout.waitlist-joined`. + */ +export async function joinWaitlist( + args: ReferralCodeArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await checkoutRepository.joinWaitlist(args); + if (emit) { + eventEmitter.emit(CHECKOUT_EVENTS.waitlistJoined, { + creatorId: args.creatorId, + }); + } + return result; +} diff --git a/platforms/market/src/features/checkout/actions/join-waitlist/index.ts b/platforms/market/src/features/checkout/actions/join-waitlist/index.ts new file mode 100644 index 0000000..d4b0dd3 --- /dev/null +++ b/platforms/market/src/features/checkout/actions/join-waitlist/index.ts @@ -0,0 +1 @@ +export { joinWaitlist } from './actions'; diff --git a/platforms/market/src/features/checkout/actions/settle-abandoned-payment/actions.ts b/platforms/market/src/features/checkout/actions/settle-abandoned-payment/actions.ts new file mode 100644 index 0000000..a3d86df --- /dev/null +++ b/platforms/market/src/features/checkout/actions/settle-abandoned-payment/actions.ts @@ -0,0 +1,71 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { useCheckoutDraftStore } from '../../../../stores/checkout-draft'; +import { CHECKOUT_EVENTS } from '../../constants'; +import { checkoutRepository } from '../../repositories/checkout'; +import type { AbandonPaymentPayload } from '../../repositories/checkout'; + +// One settlement at a time: the AppShell and checkout's screen read may both ask on one page load. +let inFlight: Promise | null = null; + +/** This document was opened from the history (back or forward), as when backing out of the bank. */ +function isHistoryLoad(): boolean { + const [entry] = performance.getEntriesByType('navigation') as + | PerformanceNavigationTiming[] + | []; + return entry?.type === 'back_forward'; +} + +/** + * The investor is back in the app while the draft still holds a payment handed to the bank, so + * the bank's callback never came. The API asks the bank: the money was taken (`completed`, active + * now), it wasn't (`abandoned`, as if never started), or it can't say yet (`pending`, which stays + * in review). Only the page that came back settles: one restored from the back cache that sent + * the payment itself, or one opened from the history. A new tab or a reload never does, because + * the bank's page may still be open elsewhere; the API reviews that payment in its own time. A + * `pending` answer is not asked again in this page load. Once settled, the draft keeps the period + * and code but forgets the payment. The store's `settlement` follows every step, and + * `checkout.payment-settled` is emitted. Nothing to settle: `null`. + */ +export function settleAbandonedPayment({ + emit = true, +}: { emit?: boolean } = {}): Promise { + inFlight ??= settle(emit).finally(() => { + inFlight = null; + }); + return inFlight; +} + +async function settle(emit: boolean): Promise { + const { draft, sentHere, settlement, setSettlement } = + useCheckoutDraftStore.getState(); + const paymentId = draft?.paymentId; + if (!draft || !paymentId) return null; + if (sentHere !== paymentId && !isHistoryLoad()) return null; + if (settlement?.paymentId === paymentId && settlement.outcome === 'pending') + return null; + + const { creatorId } = draft; + setSettlement({ paymentId, creatorId, outcome: null }); + let result: AbandonPaymentPayload; + try { + result = await checkoutRepository.abandonPayment(paymentId); + } catch (error) { + // Asked again by the next trigger. + setSettlement(null); + throw error; + } + const state = useCheckoutDraftStore.getState(); + if (result.outcome !== 'pending' && state.draft?.paymentId === paymentId) { + state.forgetPayment(); + } + setSettlement({ paymentId, creatorId, outcome: result.outcome }); + if (emit) { + eventEmitter.emit(CHECKOUT_EVENTS.paymentSettled, { + creatorId, + paymentId: result.paymentId, + outcome: result.outcome, + }); + } + return result; +} diff --git a/platforms/market/src/features/checkout/actions/settle-abandoned-payment/index.ts b/platforms/market/src/features/checkout/actions/settle-abandoned-payment/index.ts new file mode 100644 index 0000000..68bec16 --- /dev/null +++ b/platforms/market/src/features/checkout/actions/settle-abandoned-payment/index.ts @@ -0,0 +1 @@ +export { settleAbandonedPayment } from './actions'; diff --git a/platforms/market/src/features/checkout/actions/start-checkout/actions.ts b/platforms/market/src/features/checkout/actions/start-checkout/actions.ts new file mode 100644 index 0000000..9b34a7c --- /dev/null +++ b/platforms/market/src/features/checkout/actions/start-checkout/actions.ts @@ -0,0 +1,44 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { useCheckoutDraftStore } from '../../../../stores/checkout-draft'; +import { CHECKOUT_EVENTS } from '../../constants'; +import { checkoutRepository } from '../../repositories/checkout'; +import type { + CheckoutResultPayload, + SubscribeArgs, +} from '../../repositories/checkout'; + +/** + * Starts paying for a tier of a creator. Once a payment exists (`redirect` to the bank, or access + * `granted` at once), the period and invite code are kept as the checkout draft, so back from the + * bank and «تلاش دوباره» on the result page find them again (U10 ۶.۳, ۹.۲), with the payment when + * it goes to the bank, and `checkout.started` is emitted. `waitlist` and `price-changed` change + * nothing. Errors reach the caller with their checkout code. + */ +export async function startCheckout( + args: SubscribeArgs & { creatorId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const { creatorId, ...subscribe } = args; + const result = await checkoutRepository.subscribe(subscribe); + if (result.outcome === 'granted' || result.outcome === 'redirect') { + useCheckoutDraftStore.getState().keepDraft({ + creatorId, + tierId: subscribe.tierId, + referralCode: subscribe.referralCode, + // Only a payment handed to the bank can be left there; one without a bank URL goes + // straight to its result page, which reads it. + paymentId: + result.outcome === 'redirect' && result.redirectUrl + ? result.paymentId + : null, + }); + if (emit) { + eventEmitter.emit(CHECKOUT_EVENTS.started, { + creatorId, + paymentId: result.paymentId, + }); + } + } + return result; +} diff --git a/platforms/market/src/features/checkout/actions/start-checkout/index.ts b/platforms/market/src/features/checkout/actions/start-checkout/index.ts new file mode 100644 index 0000000..ad77a2b --- /dev/null +++ b/platforms/market/src/features/checkout/actions/start-checkout/index.ts @@ -0,0 +1 @@ +export { startCheckout } from './actions'; diff --git a/platforms/market/src/features/checkout/constants.ts b/platforms/market/src/features/checkout/constants.ts index 690b0fe..6c349bc 100644 --- a/platforms/market/src/features/checkout/constants.ts +++ b/platforms/market/src/features/checkout/constants.ts @@ -1,4 +1,18 @@ /** Events checkout actions emit when they succeed. */ export const CHECKOUT_EVENTS = { + /** A payment exists: the bank is next, or access was granted at once. */ + started: 'checkout.started', + waitlistJoined: 'checkout.waitlist-joined', waitlistLeft: 'checkout.waitlist-left', + /** A payment left at the gateway was settled with the bank (U10 ۶.۳). */ + paymentSettled: 'checkout.payment-settled', } as const; + +/** How often the return and result pages read a payment the bank hasn't settled yet. */ +export const PAYMENT_POLL_MS = 2_000; + +/** + * How long the return page waits for the payment to settle before showing the result anyway, as + * «در حال بررسی», so the confirming screen is never a trap (U10 ۱.۴). + */ +export const PAYMENT_CONFIRM_TIMEOUT_MS = 30_000; diff --git a/platforms/market/src/features/checkout/index.ts b/platforms/market/src/features/checkout/index.ts index dcb9f0a..aa786c7 100644 --- a/platforms/market/src/features/checkout/index.ts +++ b/platforms/market/src/features/checkout/index.ts @@ -1,16 +1,46 @@ import './types'; +export { joinWaitlist } from './actions/join-waitlist'; export { leaveWaitlist } from './actions/leave-waitlist'; -export { CHECKOUT_EVENTS } from './constants'; -export type { CheckoutResultEntity } from './entities/checkout-result'; +export { settleAbandonedPayment } from './actions/settle-abandoned-payment'; +export { startCheckout } from './actions/start-checkout'; export { + CHECKOUT_EVENTS, + PAYMENT_CONFIRM_TIMEOUT_MS, + PAYMENT_POLL_MS, +} from './constants'; +export type { CheckoutResultEntity } from './entities/checkout-result'; +export { useCheckoutPage } from './models/checkout'; +export type { + CheckoutHalt, + CheckoutMode, + CheckoutPageModel, + CheckoutPhase, + CodeCheck, + UseCheckoutPageOptions, +} from './models/checkout'; +export { usePaymentResultPage } from './models/payment-result'; +export type { + PaymentResultKind, + PaymentResultPageModel, + UsePaymentResultPageOptions, +} from './models/payment-result'; +export { usePaymentReturnPage } from './models/payment-return'; +export type { UsePaymentReturnPageOptions } from './models/payment-return'; +export { + CHECKOUT_ERROR_CODES, + checkoutErrorCode, checkoutKeys, checkoutRepository, + toCheckoutError, toCheckoutResultPayload, toPriceChangedPayload, } from './repositories/checkout'; export type { + AbandonOutcome, + AbandonPaymentPayload, CheckoutCtaState, + CheckoutErrorCode, CheckoutPayload, CheckoutResultPayload, CheckoutTierPayload, diff --git a/platforms/market/src/features/checkout/models/.gitkeep b/platforms/market/src/features/checkout/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/checkout/models/checkout/index.ts b/platforms/market/src/features/checkout/models/checkout/index.ts new file mode 100644 index 0000000..d5c5e23 --- /dev/null +++ b/platforms/market/src/features/checkout/models/checkout/index.ts @@ -0,0 +1,9 @@ +export { useCheckoutPage } from './use-checkout-page'; +export type { + CheckoutHalt, + CheckoutMode, + CheckoutPageModel, + CheckoutPhase, + CodeCheck, + UseCheckoutPageOptions, +} from './types'; diff --git a/platforms/market/src/features/checkout/models/checkout/types.ts b/platforms/market/src/features/checkout/models/checkout/types.ts new file mode 100644 index 0000000..93f43d4 --- /dev/null +++ b/platforms/market/src/features/checkout/models/checkout/types.ts @@ -0,0 +1,80 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { + CheckoutFormOutput, + CheckoutFormValues, +} from '../../../../shared/validations'; +import type { + CheckoutPayload, + CheckoutTierPayload, +} from '../../repositories/checkout'; + +export type UseCheckoutPageOptions = { + /** The creator's account id. */ + creatorId: string; + /** Where back, a decline and «بازگشت به کانال» go. */ + channelHref: string; +}; + +/** + * What stops a payment before the bank, as a blocking sheet (mobile) or modal (desktop): + * - `price-changed`: the live price moved since checkout loaded (U9 ۵.۱); + * - `unavailable`: the creator was suspended in between; nothing was charged (۵.۵); + * - `waitlist-offer`: the code is valid but the channel is full (۶.۱); + * - `waitlisted`: full, and the investor is already on its list (۶.۲). + */ +export type CheckoutHalt = + | { kind: 'price-changed'; oldAmountToman: number; newAmountToman: number } + | { kind: 'unavailable' } + | { kind: 'waitlist-offer' } + | { kind: 'waitlisted' }; + +/** + * idle → paying → leaving, for the bank or the result page; a halt or a failure returns to idle. + * `joining`: the waitlist request. + */ +export type CheckoutPhase = 'idle' | 'paying' | 'leaving' | 'joining'; + +/** The blur's advisory check of the code (U9 ۴.۲–۴.۴); a failed check shows nothing. */ +export type CodeCheck = 'idle' | 'checking' | 'valid'; + +/** + * `subscribe`: a new subscription, with an invite code. `reactivate`: the investor's subscription + * to this creator ended, so it starts again from today, with no code (U11 ۳.۱). + */ +export type CheckoutMode = 'subscribe' | 'reactivate'; + +export type CheckoutPageModel = { + /** + * `pending`: the screen isn't loaded yet; `settling`: a payment left at the gateway is being + * settled with the bank, or the bank took it and its result page is next; `away`: the investor + * can't pay here (already subscribed, or a payment in review), so they are on their way to the + * channel. + */ + status: 'pending' | 'settling' | 'ready' | 'away'; + mode: CheckoutMode; + screen: CheckoutPayload | undefined; + /** The tiers the investor can pay for: the creator's active ones with a price, cheapest first. */ + tiers: CheckoutTierPayload[]; + form: UseFormReturn; + selectedTier: CheckoutTierPayload | null; + /** The monthly tier's standing price, for every longer tier's «n٪ کمتر از ماهانه». */ + monthlyPrice: number | undefined; + /** A period is chosen, and a code typed unless reactivating: «پرداخت» is live. */ + canPay: boolean; + codeCheck: CodeCheck; + /** Field blur: the quiet advisory check. */ + checkCode: () => void; + /** Any edit of the code drops the last check's message. */ + codeEdited: () => void; + pay: () => void; + phase: CheckoutPhase; + /** The last tap never reached the server: the banner, and «تلاش دوباره» (U9 ۵.۳). */ + isOffline: boolean; + halt: CheckoutHalt | null; + confirmPriceChange: () => void; + cancelPriceChange: () => void; + joinWaitlist: () => void; + /** Declining the waitlist, or «بازگشت به کانال»: both go back to the channel. */ + leaveToChannel: () => void; +}; diff --git a/platforms/market/src/features/checkout/models/checkout/use-checkout-page.ts b/platforms/market/src/features/checkout/models/checkout/use-checkout-page.ts new file mode 100644 index 0000000..567ade8 --- /dev/null +++ b/platforms/market/src/features/checkout/models/checkout/use-checkout-page.ts @@ -0,0 +1,375 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { showToast } from '@lumina/island/molecules/toast'; +import { handleError } from '@lumina/libs/error-handler'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { useRouter } from 'next/navigation'; +import { useEffect, useRef, useState } from 'react'; +import { useForm, useWatch } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../app/navigation/navigation'; +import { + applyServerErrors, + isConnectionError, + showActionError, +} from '../../../../shared/utils'; +import { checkoutSchema } from '../../../../shared/validations'; +import type { + CheckoutFormOutput, + CheckoutFormValues, +} from '../../../../shared/validations'; +import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth'; +import { useCheckoutDraftStore } from '../../../../stores/checkout-draft'; +import { channelKeys } from '../../../channel'; +import { startRenewal } from '../../../subscription'; +import { joinWaitlist } from '../../actions/join-waitlist'; +import { settleAbandonedPayment } from '../../actions/settle-abandoned-payment'; +import { startCheckout } from '../../actions/start-checkout'; +import { + CHECKOUT_ERROR_CODES, + CHECKOUT_ERROR_COPY, + checkoutErrorCode, + checkoutKeys, + checkoutRepository, +} from '../../repositories/checkout'; +import type { + CheckoutPayload, + CheckoutResultPayload, +} from '../../repositories/checkout'; +import type { + CheckoutPageModel, + CheckoutHalt, + CheckoutPhase, + CodeCheck, + UseCheckoutPageOptions, +} from './types'; + +/** + * U9: one screen, no wizard. Nothing is pre-selected; «پرداخت» stays frozen until a period is + * chosen and a code typed, and says so when tapped (۴.۱). The code gets a quiet advisory check on + * blur (۴.۲–۴.۴); the tap re-checks it on the server and decides. A payment goes to the bank, or + * (no gateway configured) straight to the result page. A moved price, a suspended creator and a + * full channel halt it in a sheet (§۵–۶); a tap that never reached the server keeps everything and + * offers «تلاش دوباره» (۵.۳). An investor who is already subscribed, or whose payment is in review, + * can't pay here and goes to the channel, which says why (۱.۳, ۱.۴). The last checkout's period + * and code come back after the bank (U10 ۶.۳, ۹.۲); a payment this page left at the gateway is + * settled with the bank before the screen is read, so backing out leaves checkout as it was, and a + * payment the bank took after all goes to its result page. An investor whose subscription to this + * creator ended reactivates it here: no code, a period from today (U11 ۳.۱). + */ +export function useCheckoutPage({ + creatorId, + channelHref, +}: UseCheckoutPageOptions): CheckoutPageModel { + const { t } = useTranslation('payment'); + const router = useRouter(); + const queryClient = useQueryClient(); + const status = useViewerStatus(); + const account = useCurrentAccount(); + const [phase, setPhase] = useState('idle'); + const [halt, setHalt] = useState(null); + const [isOffline, setIsOffline] = useState(false); + const [codeCheck, setCodeCheck] = useState('idle'); + const restoredDraft = useRef(false); + const screenKey = checkoutKeys.screen(creatorId); + + const screen = useQuery({ + queryKey: screenKey, + // A payment this page left at the bank is settled first, so the screen never reads it as in + // review by mistake (U10 ۶.۳). A failed settle leaves it in review, as the API then says; the + // AppShell, which asks on the same load, reports it. + queryFn: async ({ signal }) => { + await settleAbandonedPayment().catch(() => null); + return checkoutRepository.getScreen(creatorId, { signal }); + }, + enabled: status === 'member' && account?.role === 'investor', + }); + + const form = useForm({ + resolver: valibotResolver(checkoutSchema), + mode: 'onSubmit', + defaultValues: { tierId: '', referralCode: '' }, + }); + const [tierId, referralCode] = useWatch({ + control: form.control, + name: ['tierId', 'referralCode'], + }); + + const tiers = (screen.data?.tiers ?? []).filter( + (tier) => tier.priceToman !== null, + ); + const selectedTier = tiers.find((tier) => tier.id === tierId) ?? null; + const monthly = tiers.find((tier) => tier.billingPeriod === 'monthly'); + const ctaState = screen.data?.cta.state; + const reactivation = + ctaState === 'subscribe' + ? (screen.data?.expiredSubscription ?? null) + : null; + const mode = reactivation ? 'reactivate' : 'subscribe'; + const draft = useCheckoutDraftStore((state) => state.draft); + const settlement = useCheckoutDraftStore((state) => + state.settlement?.creatorId === creatorId ? state.settlement : null, + ); + const isSettling = settlement !== null && settlement.outcome === null; + const paidAtBank = + settlement?.outcome === 'completed' ? settlement.paymentId : null; + // Subscribed, in review or their own: the channel shows why, with no second checkout. A page + // already leaving for the bank or a result goes nowhere else. + const isAway = + phase !== 'leaving' && + (ctaState === 'active' || + ctaState === 'own' || + ctaState === 'pending_review'); + // One way out: the bank took the money after all, so its result page says so; else the channel. + const leaveTo = paidAtBank + ? ROUTES.paymentResult(paidAtBank) + : isAway + ? channelHref + : null; + + useEffect(() => { + if (leaveTo) router.replace(leaveTo); + }, [leaveTo, router]); + + // The period and code of the last checkout of this creator, once, if nothing was touched yet. + useEffect(() => { + if (restoredDraft.current || !screen.data || draft?.creatorId !== creatorId) + return; + restoredDraft.current = true; + if (form.formState.isDirty) return; + const hasTier = screen.data.tiers.some((tier) => tier.id === draft.tierId); + form.reset({ + tierId: hasTier ? draft.tierId : '', + referralCode: draft.referralCode, + }); + }, [draft, screen.data, creatorId, form]); + + // Back from the bank restores this page as it was left, spinner and all: start over from it. + // The screen from before the bank is dropped, so nothing is payable until it is read again, + // after the settle. + useEffect(() => { + const onPageShow = (event: PageTransitionEvent) => { + if (!event.persisted) return; + setPhase('idle'); + void queryClient.resetQueries({ + queryKey: checkoutKeys.screen(creatorId), + }); + }; + window.addEventListener('pageshow', onPageShow); + return () => window.removeEventListener('pageshow', onPageShow); + }, [queryClient, creatorId]); + + const markCodeInvalid = () => + form.setError('referralCode', { + type: 'server', + message: CHECKOUT_ERROR_COPY.codeInvalid, + }); + + const checkCode = () => { + const code = form.getValues('referralCode').trim(); + if (!code || codeCheck === 'checking') return; + setCodeCheck('checking'); + checkoutRepository + .validateReferral({ creatorId, code }) + .then(({ status: codeStatus }) => { + // Edited since: this answer is about another code. + if (form.getValues('referralCode').trim() !== code) return; + if (codeStatus === 'invalid') { + setCodeCheck('idle'); + markCodeInvalid(); + return; + } + // A full channel's code is still valid; the tap offers the waitlist. + setCodeCheck('valid'); + }) + .catch((error: unknown) => { + // Advisory only: no message, and the tap still checks (۴.۴). Bugs are still reported. + handleError(error, { where: 'action', name: 'checkout-code-check' }); + setCodeCheck('idle'); + }); + }; + + const codeEdited = () => { + setCodeCheck('idle'); + if (form.formState.errors.referralCode) form.clearErrors('referralCode'); + }; + + const refreshScreen = () => + void queryClient.invalidateQueries({ queryKey: screenKey }); + + const handleOutcome = (result: CheckoutResultPayload) => { + switch (result.outcome) { + case 'redirect': + setPhase('leaving'); + if (result.redirectUrl) window.location.assign(result.redirectUrl); + else router.replace(ROUTES.paymentResult(result.paymentId)); + return; + case 'granted': + setPhase('leaving'); + router.replace(ROUTES.paymentResult(result.paymentId)); + return; + case 'waitlist': + setPhase('idle'); + setHalt({ + kind: result.alreadyWaitlisted ? 'waitlisted' : 'waitlist-offer', + }); + return; + case 'price-changed': + setPhase('idle'); + setHalt({ + kind: 'price-changed', + oldAmountToman: result.oldAmountToman, + newAmountToman: result.newAmountToman, + }); + return; + } + }; + + const failed = (error: unknown) => { + setPhase('idle'); + const code = checkoutErrorCode(error); + // The halt explains it: nothing was charged and there is nothing to retry (۵.۵). + if (code === CHECKOUT_ERROR_CODES.unavailable) { + setHalt({ kind: 'unavailable' }); + return; + } + if (isConnectionError(error)) setIsOffline(true); + // An active subscription or a payment in flight: reloading sends the investor to the channel. + const options = { + t, + failedMessage: t('checkout.pay-failed'), + reload: refreshScreen, + }; + if (code === CHECKOUT_ERROR_CODES.codeInvalid) { + setCodeCheck('idle'); + applyServerErrors(form, error, options); + return; + } + showActionError(error, options); + }; + + const submit = async ( + { tierId: chosen, referralCode: code }: CheckoutFormOutput, + confirmPriceChange = false, + ) => { + const tier = tiers.find((item) => item.id === chosen); + setPhase('paying'); + setIsOffline(false); + try { + handleOutcome( + await startCheckout({ + creatorId, + tierId: chosen, + referralCode: code, + expectedPriceToman: tier?.priceToman ?? undefined, + confirmPriceChange: confirmPriceChange || undefined, + }), + ); + } catch (error) { + failed(error); + } + }; + + // Reactivation needs no code, so no form check: the period is all there is to choose. + const reactivate = async (chosen: string, subscriptionId: string) => { + setPhase('paying'); + setIsOffline(false); + try { + handleOutcome( + await startRenewal({ + kind: 'reactivate', + subscriptionId, + tierId: chosen, + creatorId, + }), + ); + } catch (error) { + failed(error); + } + }; + + const pay = () => { + // Frozen until what is needed is there; Enter in the code field lands here too. + if (!selectedTier || phase !== 'idle') return; + if (reactivation) { + void reactivate(selectedTier.id, reactivation.id); + return; + } + if (!referralCode.trim()) return; + void form.handleSubmit((values) => submit(values))(); + }; + + const join = async () => { + setPhase('joining'); + try { + await joinWaitlist({ + creatorId, + code: form.getValues('referralCode'), + }); + setHalt(null); + queryClient.setQueryData( + screenKey, + (current) => current && { ...current, waitlisted: true }, + ); + void queryClient.invalidateQueries({ + queryKey: channelKeys.standing(creatorId), + }); + showToast({ tone: 'success', message: t('checkout.waitlist.joined') }); + router.push(channelHref); + } catch (error) { + setPhase('idle'); + // Joining twice is harmless, so the toast may offer to try again. + showActionError(error, { + t, + failedMessage: t('checkout.waitlist.join-failed'), + retry: () => void join(), + }); + } + }; + + return { + status: + isSettling || paidAtBank + ? 'settling' + : isAway + ? 'away' + : screen.data + ? 'ready' + : 'pending', + mode, + screen: screen.data, + tiers, + form, + selectedTier, + monthlyPrice: + monthly?.standingPriceToman ?? monthly?.priceToman ?? undefined, + canPay: + selectedTier !== null && + (mode === 'reactivate' || referralCode.trim() !== ''), + codeCheck, + checkCode, + codeEdited, + pay, + phase, + isOffline, + halt, + confirmPriceChange: () => { + setHalt(null); + // Reactivation pays the live price with no confirmation to send, so it simply goes again. + if (reactivation && selectedTier) { + void reactivate(selectedTier.id, reactivation.id); + return; + } + void form.handleSubmit((values) => submit(values, true))(); + }, + cancelPriceChange: () => { + setHalt(null); + refreshScreen(); + }, + joinWaitlist: () => void join(), + leaveToChannel: () => { + setHalt(null); + router.push(channelHref); + }, + }; +} diff --git a/platforms/market/src/features/checkout/models/payment-result/index.ts b/platforms/market/src/features/checkout/models/payment-result/index.ts new file mode 100644 index 0000000..7ebd898 --- /dev/null +++ b/platforms/market/src/features/checkout/models/payment-result/index.ts @@ -0,0 +1,6 @@ +export { usePaymentResultPage } from './use-payment-result-page'; +export type { + PaymentResultKind, + PaymentResultPageModel, + UsePaymentResultPageOptions, +} from './types'; diff --git a/platforms/market/src/features/checkout/models/payment-result/types.ts b/platforms/market/src/features/checkout/models/payment-result/types.ts new file mode 100644 index 0000000..5a40063 --- /dev/null +++ b/platforms/market/src/features/checkout/models/payment-result/types.ts @@ -0,0 +1,14 @@ +import type { TransactionDetailPayload } from '../../../transaction'; + +export type UsePaymentResultPageOptions = { paymentId: string }; + +/** U10 §۹: paid and active, declined or cancelled at the bank, or not confirmed yet (in review). */ +export type PaymentResultKind = 'success' | 'failed' | 'pending'; + +export type PaymentResultPageModel = { + /** `undefined` until it loads. */ + payment: TransactionDetailPayload | undefined; + kind: PaymentResultKind | null; + /** Copies the bank's reference and says so. */ + copyReference: () => void; +}; diff --git a/platforms/market/src/features/checkout/models/payment-result/use-payment-result-page.ts b/platforms/market/src/features/checkout/models/payment-result/use-payment-result-page.ts new file mode 100644 index 0000000..3ccfd4e --- /dev/null +++ b/platforms/market/src/features/checkout/models/payment-result/use-payment-result-page.ts @@ -0,0 +1,90 @@ +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { useEffect } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { PaymentUiStatus } from '../../../../shared/constants'; +import { copyWithToast } from '../../../../shared/utils'; +import { useCurrentAccount, useViewerStatus } from '../../../../stores/auth'; +import { useCheckoutDraftStore } from '../../../../stores/checkout-draft'; +import { channelKeys } from '../../../channel'; +import { feedKeys } from '../../../feed'; +import { followKeys } from '../../../follow'; +import { subscriptionKeys } from '../../../subscription'; +import { transactionKeys, transactionRepository } from '../../../transaction'; +import { PAYMENT_CONFIRM_TIMEOUT_MS, PAYMENT_POLL_MS } from '../../constants'; +import { checkoutKeys } from '../../repositories/checkout'; +import type { + PaymentResultKind, + PaymentResultPageModel, + UsePaymentResultPageOptions, +} from './types'; + +const KINDS: Record = { + successful: 'success', + failed: 'failed', + pending: 'pending', +}; + +/** + * U10 §۹: the end of every payment, read in the browser with the investor's session. A payment + * still unsettled shows «در حال بررسی» and is read again for a while, then when the tab comes back. Once settled, + * everything that shows this creator's standing or the investor's subscriptions reads again; a + * success also drops the kept checkout draft, which only a retry needs. + */ +export function usePaymentResultPage({ + paymentId, +}: UsePaymentResultPageOptions): PaymentResultPageModel { + const { t } = useTranslation('payment'); + const queryClient = useQueryClient(); + const status = useViewerStatus(); + const account = useCurrentAccount(); + + const query = useQuery({ + queryKey: transactionKeys.detail(paymentId), + queryFn: ({ signal }) => + transactionRepository.getDetail(paymentId, { signal }), + enabled: status === 'member' && account?.role === 'investor', + // Every 2 s while the bank is settling, for 30 s in all with the return page's reads; then + // the page says «در حال بررسی» and reads again only when the tab comes back into view. + refetchInterval: (current) => + current.state.data?.confirmation.phase === 'processing' && + current.state.dataUpdateCount * PAYMENT_POLL_MS < + PAYMENT_CONFIRM_TIMEOUT_MS + ? PAYMENT_POLL_MS + : false, + }); + const payment = query.data; + const kind = payment ? KINDS[payment.status] : null; + const creatorId = payment?.creator.id; + + useEffect(() => { + if (!creatorId || !kind || kind === 'pending') return; + if (kind === 'success') { + const { draft, clearDraft } = useCheckoutDraftStore.getState(); + if (draft?.creatorId === creatorId) clearDraft(); + // Subscribing follows the creator (U10 ۲.۳), so خانه and the following list change too. + void queryClient.invalidateQueries({ queryKey: subscriptionKeys.all }); + void queryClient.invalidateQueries({ queryKey: feedKeys.all }); + void queryClient.invalidateQueries({ queryKey: followKeys.all }); + } + void queryClient.invalidateQueries({ + queryKey: channelKeys.creator(creatorId), + }); + void queryClient.invalidateQueries({ + queryKey: checkoutKeys.screen(creatorId), + }); + void queryClient.invalidateQueries({ queryKey: transactionKeys.lists() }); + }, [creatorId, kind, queryClient]); + + const copyReference = () => { + const reference = payment?.reference; + if (!reference) return; + copyWithToast(reference, { + copied: t('result.reference-copied'), + failed: t('result.copy-failed'), + failedDescription: t('result.copy-failed-description'), + }); + }; + + return { payment, kind, copyReference }; +} diff --git a/platforms/market/src/features/checkout/models/payment-return/index.ts b/platforms/market/src/features/checkout/models/payment-return/index.ts new file mode 100644 index 0000000..e0d3d21 --- /dev/null +++ b/platforms/market/src/features/checkout/models/payment-return/index.ts @@ -0,0 +1,2 @@ +export { usePaymentReturnPage } from './use-payment-return-page'; +export type { UsePaymentReturnPageOptions } from './types'; diff --git a/platforms/market/src/features/checkout/models/payment-return/types.ts b/platforms/market/src/features/checkout/models/payment-return/types.ts new file mode 100644 index 0000000..19dc445 --- /dev/null +++ b/platforms/market/src/features/checkout/models/payment-return/types.ts @@ -0,0 +1,4 @@ +export type UsePaymentReturnPageOptions = { + /** The `paymentId` the API's bank callback put on the return URL; `null` when it's missing. */ + paymentId: string | null; +}; diff --git a/platforms/market/src/features/checkout/models/payment-return/use-payment-return-page.ts b/platforms/market/src/features/checkout/models/payment-return/use-payment-return-page.ts new file mode 100644 index 0000000..70571b6 --- /dev/null +++ b/platforms/market/src/features/checkout/models/payment-return/use-payment-return-page.ts @@ -0,0 +1,68 @@ +import { useQuery } from '@tanstack/react-query'; +import { useRouter } from 'next/navigation'; +import { useEffect } from 'react'; + +import { ROUTES } from '../../../../app/navigation/navigation'; +import { useViewerStatus } from '../../../../stores/auth'; +import { useCheckoutDraftStore } from '../../../../stores/checkout-draft'; +import { transactionKeys, transactionRepository } from '../../../transaction'; +import { PAYMENT_CONFIRM_TIMEOUT_MS, PAYMENT_POLL_MS } from '../../constants'; +import type { UsePaymentReturnPageOptions } from './types'; + +/** + * U10 ۱.۱: where the API sends the browser back from the bank, once it has verified the payment. + * It reads the payment until it is settled, then replaces itself with the result page, so refresh + * and back never land here again. A payment still unsettled after the timeout shows its result as + * in review (§۵). No payment id: the investor's transactions, which list every attempt. + */ +export function usePaymentReturnPage({ + paymentId, +}: UsePaymentReturnPageOptions): void { + const router = useRouter(); + const status = useViewerStatus(); + + const payment = useQuery({ + queryKey: transactionKeys.detail(paymentId ?? ''), + queryFn: ({ signal }) => + transactionRepository.getDetail(paymentId ?? '', { signal }), + enabled: paymentId !== null && status === 'member', + refetchInterval: (query) => + query.state.data?.confirmation.phase === 'processing' + ? PAYMENT_POLL_MS + : false, + }); + const phase = payment.data?.confirmation.phase; + + useEffect(() => { + if (paymentId === null) { + router.replace(ROUTES.dashboard.transactions); + return; + } + if (phase && phase !== 'processing') { + router.replace(ROUTES.paymentResult(paymentId)); + } + }, [paymentId, phase, router]); + + // The bank's callback brought the browser here: nothing is left at the gateway to settle. The + // AppShell loads the draft after this page's first effects, so this waits for it. + useEffect(() => { + if (paymentId === null) return; + const forget = () => { + const { draft, forgetPayment } = useCheckoutDraftStore.getState(); + if (draft?.paymentId === paymentId) forgetPayment(); + }; + const offHydrated = useCheckoutDraftStore.persist.hasHydrated() + ? (forget(), undefined) + : useCheckoutDraftStore.persist.onFinishHydration(forget); + return () => offHydrated?.(); + }, [paymentId]); + + useEffect(() => { + if (paymentId === null) return; + const timer = window.setTimeout( + () => router.replace(ROUTES.paymentResult(paymentId)), + PAYMENT_CONFIRM_TIMEOUT_MS, + ); + return () => window.clearTimeout(timer); + }, [paymentId, router]); +} diff --git a/platforms/market/src/features/checkout/repositories/checkout/checkout.ts b/platforms/market/src/features/checkout/repositories/checkout/checkout.ts index 5c89c44..085391f 100644 --- a/platforms/market/src/features/checkout/repositories/checkout/checkout.ts +++ b/platforms/market/src/features/checkout/repositories/checkout/checkout.ts @@ -1,5 +1,6 @@ import { checkoutHttp } from '../../http'; import { CHECKOUT_ENDPOINTS } from './constants'; +import { toCheckoutError } from './errors'; import { toCheckoutPayload, toCheckoutResultPayload, @@ -10,6 +11,8 @@ import { toWaitlistJoinedPayload, } from './mappers'; import type { + AbandonPaymentPayload, + AbandonPaymentResponseDto, CheckoutPayload, CheckoutResponseDto, CheckoutResultPayload, @@ -61,6 +64,16 @@ export const checkoutRepository = { return toWaitlistJoinedPayload(response); }, + /** + * The investor came back from the gateway without its callback: the API asks the bank and + * completes the payment, abandons it, or leaves it pending. Safe to send twice. + */ + async abandonPayment(paymentId: string): Promise { + return checkoutHttp.post( + CHECKOUT_ENDPOINTS.abandon(paymentId), + ); + }, + /** Stops capacity notifications for this creator; succeeds when not on the list too. */ async leaveWaitlist(creatorId: string): Promise { await checkoutHttp.delete( @@ -70,9 +83,10 @@ export const checkoutRepository = { /** * 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)`. + * `price-changed` outcome; every other failure throws, the known ones with a checkout code + * (`checkoutErrorCode`): an invalid or missing code (on `referralCode`), an active subscription + * or a payment already in flight (409), the creator unavailable (403). The payment's receipt and + * U10 phase are `transactionRepository.getDetail(paymentId)`. */ async subscribe(args: SubscribeArgs): Promise { try { @@ -84,7 +98,7 @@ export const checkoutRepository = { } catch (error) { const priceChanged = toPriceChangedPayload(error); if (priceChanged) return priceChanged; - throw error; + throw toCheckoutError(error); } }, }; diff --git a/platforms/market/src/features/checkout/repositories/checkout/constants.ts b/platforms/market/src/features/checkout/repositories/checkout/constants.ts index c40fa5b..e7d493b 100644 --- a/platforms/market/src/features/checkout/repositories/checkout/constants.ts +++ b/platforms/market/src/features/checkout/repositories/checkout/constants.ts @@ -8,6 +8,8 @@ export const CHECKOUT_ENDPOINTS = { leaveWaitlist: (creatorId: string) => `/subscriptions/waitlist/${encode(creatorId)}`, subscribe: '/subscribe', + abandon: (paymentId: string) => + `/subscriptions/payments/${encode(paymentId)}/abandon`, } as const; export const checkoutKeys = { @@ -16,3 +18,49 @@ export const checkoutKeys = { screen: (creatorId: string) => [...checkoutKeys.screens(), creatorId] as const, }; + +/** + * Checkout failures the pages tell apart: the API's stable `code` for each (back + * `libs/shared/src/constants/error-codes.ts`), kept as `HttpError.code`. + */ +export const CHECKOUT_ERROR_CODES = { + codeInvalid: 'CHECKOUT_CODE_INVALID', + codeRequired: 'CHECKOUT_CODE_REQUIRED', + alreadyActive: 'CHECKOUT_ALREADY_ACTIVE', + paymentPending: 'CHECKOUT_PAYMENT_PENDING', + /** 403: the creator was suspended (or is no longer approved) since checkout opened. */ + unavailable: 'CHECKOUT_UNAVAILABLE', +} as const; + +/** Each checkout failure's copy, an `errors:` key the error handler and the fields translate. */ +export const CHECKOUT_ERROR_COPY = { + codeInvalid: 'errors:checkout.code-invalid', + codeRequired: 'errors:checkout.code-required', + alreadyActive: 'errors:checkout.already-active', + paymentPending: 'errors:checkout.payment-pending', + unavailable: 'errors:checkout.unavailable', +} as const; + +/** Each checkout code's copy, and the `*Args` field it belongs to when it has one. */ +export const CHECKOUT_ERROR_RULES: Record< + (typeof CHECKOUT_ERROR_CODES)[keyof typeof CHECKOUT_ERROR_CODES], + { message: string; field?: 'referralCode' } +> = { + [CHECKOUT_ERROR_CODES.codeInvalid]: { + message: CHECKOUT_ERROR_COPY.codeInvalid, + field: 'referralCode', + }, + [CHECKOUT_ERROR_CODES.codeRequired]: { + message: CHECKOUT_ERROR_COPY.codeRequired, + field: 'referralCode', + }, + [CHECKOUT_ERROR_CODES.alreadyActive]: { + message: CHECKOUT_ERROR_COPY.alreadyActive, + }, + [CHECKOUT_ERROR_CODES.paymentPending]: { + message: CHECKOUT_ERROR_COPY.paymentPending, + }, + [CHECKOUT_ERROR_CODES.unavailable]: { + message: CHECKOUT_ERROR_COPY.unavailable, + }, +}; diff --git a/platforms/market/src/features/checkout/repositories/checkout/errors.ts b/platforms/market/src/features/checkout/repositories/checkout/errors.ts new file mode 100644 index 0000000..fee40c4 --- /dev/null +++ b/platforms/market/src/features/checkout/repositories/checkout/errors.ts @@ -0,0 +1,35 @@ +import { HttpError, isHttpError } from '@lumina/libs/http'; + +import { CHECKOUT_ERROR_CODES, CHECKOUT_ERROR_RULES } from './constants'; +import type { CheckoutErrorCode } from './types'; + +const CODES: ReadonlySet = new Set(Object.values(CHECKOUT_ERROR_CODES)); + +const isCheckoutErrorCode = (code: string): code is CheckoutErrorCode => + CODES.has(code); + +/** + * Gives a checkout failure the API marked with its code its Persian copy (an `errors:` key the + * error handler translates) and its field, so the page can branch on the code and the invite-code + * field shows its message. Any other error, such as another 403 (a suspended account, a rejected + * origin), passes through unchanged. + */ +export function toCheckoutError(error: unknown): unknown { + if (!isHttpError(error) || !isCheckoutErrorCode(error.code)) return error; + const rule = CHECKOUT_ERROR_RULES[error.code]; + return new HttpError({ + ...error.toJSON(), + message: rule.message, + fieldErrors: rule.field + ? { [rule.field]: rule.message } + : error.fieldErrors, + cause: error, + }); +} + +/** The checkout failure an error stands for, or `null` for any other error. */ +export function checkoutErrorCode(error: unknown): CheckoutErrorCode | null { + return isHttpError(error) && isCheckoutErrorCode(error.code) + ? error.code + : null; +} diff --git a/platforms/market/src/features/checkout/repositories/checkout/index.ts b/platforms/market/src/features/checkout/repositories/checkout/index.ts index be43e00..79d697a 100644 --- a/platforms/market/src/features/checkout/repositories/checkout/index.ts +++ b/platforms/market/src/features/checkout/repositories/checkout/index.ts @@ -1,8 +1,16 @@ export { checkoutRepository } from './checkout'; -export { checkoutKeys } from './constants'; +export { + CHECKOUT_ERROR_CODES, + CHECKOUT_ERROR_COPY, + checkoutKeys, +} from './constants'; +export { checkoutErrorCode, toCheckoutError } from './errors'; export { toCheckoutResultPayload, toPriceChangedPayload } from './mappers'; export type { + AbandonOutcome, + AbandonPaymentPayload, CheckoutCtaState, + CheckoutErrorCode, CheckoutPayload, CheckoutResultPayload, CheckoutTierPayload, diff --git a/platforms/market/src/features/checkout/repositories/checkout/mappers.ts b/platforms/market/src/features/checkout/repositories/checkout/mappers.ts index 65d703a..96198dd 100644 --- a/platforms/market/src/features/checkout/repositories/checkout/mappers.ts +++ b/platforms/market/src/features/checkout/repositories/checkout/mappers.ts @@ -50,6 +50,7 @@ export function toCheckoutPayload(dto: CheckoutResponseDto): CheckoutPayload { creator: { id: dto.creator.id, username: dto.creator.username, + displayName: dto.creator.displayName ?? null, avatarUrl: toApiUrl(dto.creator.avatar), verified: dto.creator.verified, }, @@ -74,6 +75,13 @@ export function toCheckoutPayload(dto: CheckoutResponseDto): CheckoutPayload { billingPeriod: dto.activeSubscription.billingPeriod, } : null, + expiredSubscription: dto.expiredSubscription + ? { + id: dto.expiredSubscription.subscriptionId, + endedAt: dto.expiredSubscription.endedAt, + refunded: dto.expiredSubscription.refunded, + } + : null, }; } diff --git a/platforms/market/src/features/checkout/repositories/checkout/types.ts b/platforms/market/src/features/checkout/repositories/checkout/types.ts index dee76d5..deff3f4 100644 --- a/platforms/market/src/features/checkout/repositories/checkout/types.ts +++ b/platforms/market/src/features/checkout/repositories/checkout/types.ts @@ -9,6 +9,10 @@ import type { CheckoutResultEntity, WaitlistOfferEntity, } from '../../entities/checkout-result'; +import type { CHECKOUT_ERROR_CODES } from './constants'; + +export type CheckoutErrorCode = + (typeof CHECKOUT_ERROR_CODES)[keyof typeof CHECKOUT_ERROR_CODES]; // Money is whole Toman everywhere; dates are ISO strings. @@ -38,6 +42,7 @@ export type CheckoutResponseDto = { id: string; avatar: string | null; username: string | null; + displayName?: string | null; verified: boolean; }; items: PublicTierEntity[]; @@ -70,6 +75,16 @@ export type CheckoutResponseDto = { endsAt: string; billingPeriod: BillingPeriod; } | null; + /** + * `subscribe` only: the investor's ended subscription to this creator (expired, or ended by a + * refund), which checkout reactivates. An API older than this field leaves it out. + */ + expiredSubscription?: { + subscriptionId: string; + endedAt: string; + billingPeriod: BillingPeriod; + refunded: boolean; + } | null; }; /** A tier on the checkout screen. */ @@ -99,6 +114,7 @@ export type CheckoutPayload = { creator: { id: string; username: string | null; + displayName: string | null; avatarUrl: string | null; verified: boolean; }; @@ -130,8 +146,33 @@ export type CheckoutPayload = { endsAt: string; billingPeriod: BillingPeriod; } | null; + /** + * While `cta.state` is `subscribe`: the investor's ended subscription to this creator. Checkout + * then reactivates it: no invite code, a period from today (U11 ۳.۱). `null` otherwise. + */ + expiredSubscription: { + id: string; + endedAt: string; + refunded: boolean; + } | null; }; +// POST /subscriptions/payments/:id/abandon + +/** + * What the bank said about a payment left at the gateway: it took the money (`completed`, active + * now), it did not (`abandoned`, as if never started), it can't say yet (`pending`), or the payment + * was settled already (`closed`). + */ +export type AbandonOutcome = 'completed' | 'abandoned' | 'pending' | 'closed'; + +export type AbandonPaymentResponseDto = { + outcome: AbandonOutcome; + paymentId: string; +}; + +export type AbandonPaymentPayload = AbandonPaymentResponseDto; + // POST /subscriptions/referral/validate and POST /subscriptions/waitlist export type ReferralCodeArgs = { creatorId: string; code: string }; diff --git a/platforms/market/src/features/checkout/types.ts b/platforms/market/src/features/checkout/types.ts index 261aa89..abf43e5 100644 --- a/platforms/market/src/features/checkout/types.ts +++ b/platforms/market/src/features/checkout/types.ts @@ -1,7 +1,14 @@ +import type { AbandonOutcome } from './repositories/checkout'; + declare module '@lumina/libs/event-emitter' { interface EventMap { + 'checkout.started': { creatorId: string; paymentId: string }; + 'checkout.waitlist-joined': { creatorId: string }; 'checkout.waitlist-left': { creatorId: string }; + 'checkout.payment-settled': { + creatorId: string; + paymentId: string; + outcome: AbandonOutcome; + }; } } - -export {}; diff --git a/platforms/market/src/features/finance/repositories/creator-payment/types.ts b/platforms/market/src/features/finance/repositories/creator-payment/types.ts index 4aef9bd..2d56c0a 100644 --- a/platforms/market/src/features/finance/repositories/creator-payment/types.ts +++ b/platforms/market/src/features/finance/repositories/creator-payment/types.ts @@ -1,8 +1,8 @@ import type { BillingPeriod, - CheckoutKind, PaymentStatus, PaymentUiStatus, + TransactionKind, } from '../../../../shared/constants'; import type { PaymentEntity } from '../../../transaction'; @@ -14,7 +14,7 @@ export type CreatorPaymentPayload = { id: string; subscriberId: string; subscriptionId: string | null; - type: CheckoutKind; + type: TransactionKind; billingPeriod: BillingPeriod; amountToman: number | null; createdAt: string | null; diff --git a/platforms/market/src/features/notification/actions/.gitkeep b/platforms/market/src/features/notification/actions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/notification/entities/notification/types.ts b/platforms/market/src/features/notification/entities/notification/types.ts index a485adf..9dc594f 100644 --- a/platforms/market/src/features/notification/entities/notification/types.ts +++ b/platforms/market/src/features/notification/entities/notification/types.ts @@ -1,6 +1,9 @@ /** * 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. + * `waitlist_capacity` is sticky and replaced in place; the others expire after 30 days. The S7 + * ones follow an admin's suspension of a creator: `creator_suspended` and `access_restored` to its + * subscribers, `account_suspended` and `account_reinstated` to the creator, and + * `subscription_expired_suspended`, the expiry notice that points to support instead. */ export type NotificationType = | 'subscription_subscribe' @@ -9,9 +12,14 @@ export type NotificationType = | 'subscription_delayed_confirm' | 'subscription_expiry_warning' | 'subscription_expired' + | 'subscription_expired_suspended' | 'payment_pending_review' | 'waitlist_capacity' - | 'new_subscriber'; + | 'new_subscriber' + | 'creator_suspended' + | 'access_restored' + | 'account_suspended' + | 'account_reinstated'; /** notification-service's inbox item (`toInboxItem`). `title` and `body` are composed Persian text. */ export type NotificationEntity = { diff --git a/platforms/market/src/features/notification/index.ts b/platforms/market/src/features/notification/index.ts index bac3704..db3a76e 100644 --- a/platforms/market/src/features/notification/index.ts +++ b/platforms/market/src/features/notification/index.ts @@ -1,5 +1,11 @@ export { UNREAD_BADGE_CAP } from './constants'; export type { NotificationType } from './entities/notification'; +export { useNotificationCentre } from './models/notification-centre'; +export type { + NotificationCentreModel, + NotificationTarget, +} from './models/notification-centre'; +export { useUnreadCount } from './models/unread-count'; export { notificationKeys, notificationRepository, diff --git a/platforms/market/src/features/notification/models/.gitkeep b/platforms/market/src/features/notification/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/notification/models/notification-centre/index.ts b/platforms/market/src/features/notification/models/notification-centre/index.ts new file mode 100644 index 0000000..56ed272 --- /dev/null +++ b/platforms/market/src/features/notification/models/notification-centre/index.ts @@ -0,0 +1,2 @@ +export { useNotificationCentre } from './use-notification-centre'; +export type { NotificationCentreModel, NotificationTarget } from './types'; diff --git a/platforms/market/src/features/notification/models/notification-centre/types.ts b/platforms/market/src/features/notification/models/notification-centre/types.ts new file mode 100644 index 0000000..43e94be --- /dev/null +++ b/platforms/market/src/features/notification/models/notification-centre/types.ts @@ -0,0 +1,17 @@ +import type { NotificationPayload } from '../../repositories/notification'; + +/** Where a notification leads: an app path, a creator's channel by their profile id, or nowhere. */ +export type NotificationTarget = + | { kind: 'path'; href: string } + | { kind: 'creator'; profileId: string } + | { kind: 'none' }; + +export type NotificationCentreModel = { + /** Newest first, as the API keeps them: the last 30 days, waitlist notices until dismissed. */ + items: NotificationPayload[]; + targetOf: (item: NotificationPayload) => NotificationTarget; + /** Goes where the item leads; a channel is looked up by its profile id first. */ + open: (item: NotificationPayload) => void; + /** The item being opened while its channel is looked up. */ + openingId: string | null; +}; diff --git a/platforms/market/src/features/notification/models/notification-centre/use-notification-centre.ts b/platforms/market/src/features/notification/models/notification-centre/use-notification-centre.ts new file mode 100644 index 0000000..17cce21 --- /dev/null +++ b/platforms/market/src/features/notification/models/notification-centre/use-notification-centre.ts @@ -0,0 +1,101 @@ +import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'; +import { useRouter } from 'next/navigation'; +import { useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../app/navigation/navigation'; +import { showActionError } from '../../../../shared/utils'; +import { channelRepository } from '../../../channel'; +import { + notificationKeys, + notificationRepository, +} from '../../repositories/notification'; +import type { + NotificationPayload, + UnreadCountPayload, +} from '../../repositories/notification'; +import type { NotificationCentreModel, NotificationTarget } from './types'; + +const CREATOR_LINK = /^\/traders\/([^/?#]+)/; + +// The app pages a notification may open. Any other link, such as a page not built yet (the +// creator's /dashboard/subscribers) or another site, leaves the item plain rather than leading to +// not-found. +const IN_APP_PATHS: ReadonlySet = new Set([ + ROUTES.dashboard.subscriptions, + ROUTES.dashboard.transactions, + ROUTES.notifications, +]); +const CHANNEL_PATH = ROUTES.channel(''); + +function targetOf(item: NotificationPayload): NotificationTarget { + if (!item.link) return { kind: 'none' }; + const creator = CREATOR_LINK.exec(item.link); + if (creator) return { kind: 'creator', profileId: creator[1] }; + const [path] = item.link.split(/[?#]/, 1); + return IN_APP_PATHS.has(path) || path.startsWith(CHANNEL_PATH) + ? { kind: 'path', href: item.link } + : { kind: 'none' }; +} + +/** + * The notification centre (U5 §۲): the newest notifications, read in the browser with the + * member's session. Opening it clears the bell, once the list has arrived; the items keep the + * unread mark they came with, so the person sees what is new. An item leads to its section; a + * creator link is turned into their channel by looking up the profile first. + */ +export function useNotificationCentre(): NotificationCentreModel { + const { t } = useTranslation('notifications'); + const router = useRouter(); + const queryClient = useQueryClient(); + const [openingId, setOpeningId] = useState(null); + const markedRead = useRef(false); + + const inbox = useSuspenseQuery({ + queryKey: notificationKeys.inbox(), + queryFn: ({ signal }) => notificationRepository.listInbox({ signal }), + // Dropped once the centre closes (a second later, the least suspense allows), so every open + // reads the newest list behind its skeleton, and marking all read follows what this open + // shows, never an older list. + gcTime: 0, + }); + const hasUnread = inbox.data.unreadCount > 0; + + useEffect(() => { + if (markedRead.current || !hasUnread) return; + markedRead.current = true; + notificationRepository + .markAllRead() + .then((count) => + queryClient.setQueryData( + notificationKeys.unreadCount(), + count, + ), + ) + // The badge stays until the next open; nothing to tell the person. + .catch(() => undefined); + }, [hasUnread, queryClient]); + + const open = (item: NotificationPayload) => { + const target = targetOf(item); + if (target.kind === 'path') { + router.push(target.href); + return; + } + if (target.kind !== 'creator' || openingId) return; + setOpeningId(item.id); + channelRepository + .getCreator({ creatorId: target.profileId }) + .then((creator) => router.push(ROUTES.channel(creator.username))) + .catch((error: unknown) => + showActionError(error, { + t, + failedMessage: t('open-failed'), + retry: () => open(item), + }), + ) + .finally(() => setOpeningId(null)); + }; + + return { items: inbox.data.items, targetOf, open, openingId }; +} diff --git a/platforms/market/src/features/notification/models/unread-count/index.ts b/platforms/market/src/features/notification/models/unread-count/index.ts new file mode 100644 index 0000000..907e7cb --- /dev/null +++ b/platforms/market/src/features/notification/models/unread-count/index.ts @@ -0,0 +1 @@ +export { useUnreadCount } from './use-unread-count'; diff --git a/platforms/market/src/features/notification/models/unread-count/use-unread-count.ts b/platforms/market/src/features/notification/models/unread-count/use-unread-count.ts new file mode 100644 index 0000000..964053f --- /dev/null +++ b/platforms/market/src/features/notification/models/unread-count/use-unread-count.ts @@ -0,0 +1,23 @@ +import { useQuery } from '@tanstack/react-query'; + +import { useViewerStatus } from '../../../../stores/auth'; +import { + notificationKeys, + notificationRepository, +} from '../../repositories/notification'; + +/** + * The bell's unread count (U5 ۲.۲), read in the browser for a signed-in member, either role; 0 + * until it is known and for a guest. It reads again when the tab comes back into view. A failed + * read shows no badge rather than an error in the bar. + */ +export function useUnreadCount(): number { + const status = useViewerStatus(); + const unread = useQuery({ + queryKey: notificationKeys.unreadCount(), + queryFn: ({ signal }) => notificationRepository.getUnreadCount({ signal }), + enabled: status === 'member', + throwOnError: false, + }); + return unread.data?.count ?? 0; +} diff --git a/platforms/market/src/features/overview/repositories/creator-dashboard/types.ts b/platforms/market/src/features/overview/repositories/creator-dashboard/types.ts index d0923ef..202d7b7 100644 --- a/platforms/market/src/features/overview/repositories/creator-dashboard/types.ts +++ b/platforms/market/src/features/overview/repositories/creator-dashboard/types.ts @@ -1,4 +1,7 @@ -import type { BillingPeriod, CheckoutKind } from '../../../../shared/constants'; +import type { + BillingPeriod, + TransactionKind, +} from '../../../../shared/constants'; import type { PaymentEntity } from '../../../transaction'; import type { CreatorTierEntity } from '../../entities/creator-tier'; @@ -16,7 +19,7 @@ export type CreatorTierPayload = { export type RecentPaymentPayload = { id: string; subscriberId: string; - type: CheckoutKind; + type: TransactionKind; billingPeriod: BillingPeriod; amountToman: number | null; createdAt: string | null; diff --git a/platforms/market/src/features/subscription/actions/.gitkeep b/platforms/market/src/features/subscription/actions/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/subscription/actions/start-renewal/actions.ts b/platforms/market/src/features/subscription/actions/start-renewal/actions.ts new file mode 100644 index 0000000..0b8ebcd --- /dev/null +++ b/platforms/market/src/features/subscription/actions/start-renewal/actions.ts @@ -0,0 +1,52 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { useCheckoutDraftStore } from '../../../../stores/checkout-draft'; +import type { CheckoutResultPayload } from '../../../checkout'; +import { SUBSCRIPTION_EVENTS } from '../../constants'; +import { subscriptionRepository } from '../../repositories/subscription'; +import type { RenewalKind } from '../../repositories/subscription'; + +export type StartRenewalArgs = { + kind: RenewalKind; + subscriptionId: string; + tierId: string; + /** The creator's account id, for the checkout draft. */ + creatorId: string; +}; + +/** + * Pays for more time on a running subscription (`renew`, from its current expiry) or for a new + * period after it ended (`reactivate`, from now, no invite code). Once a payment exists the period + * is kept as the checkout draft, with the payment when it goes to the bank, so it can be settled if + * the investor comes back without the bank's answer (U10 ۶.۳); then `subscription.renewal-started` + * is emitted. Errors reach the caller with their checkout code. + */ +export async function startRenewal( + { kind, subscriptionId, tierId, creatorId }: StartRenewalArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = + kind === 'renew' + ? await subscriptionRepository.renew({ subscriptionId, tierId }) + : await subscriptionRepository.reactivate({ subscriptionId, tierId }); + if (result.outcome === 'granted' || result.outcome === 'redirect') { + useCheckoutDraftStore.getState().keepDraft({ + creatorId, + tierId, + referralCode: '', + // Only a payment handed to the bank can be left there. + paymentId: + result.outcome === 'redirect' && result.redirectUrl + ? result.paymentId + : null, + }); + if (emit) { + eventEmitter.emit(SUBSCRIPTION_EVENTS.renewalStarted, { + subscriptionId, + kind, + paymentId: result.paymentId, + }); + } + } + return result; +} diff --git a/platforms/market/src/features/subscription/actions/start-renewal/index.ts b/platforms/market/src/features/subscription/actions/start-renewal/index.ts new file mode 100644 index 0000000..d4b8735 --- /dev/null +++ b/platforms/market/src/features/subscription/actions/start-renewal/index.ts @@ -0,0 +1,2 @@ +export { startRenewal } from './actions'; +export type { StartRenewalArgs } from './actions'; diff --git a/platforms/market/src/features/subscription/constants.ts b/platforms/market/src/features/subscription/constants.ts new file mode 100644 index 0000000..d0f8328 --- /dev/null +++ b/platforms/market/src/features/subscription/constants.ts @@ -0,0 +1,5 @@ +/** Events subscription actions emit when they succeed. */ +export const SUBSCRIPTION_EVENTS = { + /** A renew or reactivate payment exists: the bank is next, or it was granted at once. */ + renewalStarted: 'subscription.renewal-started', +} as const; diff --git a/platforms/market/src/features/subscription/entities/subscription/types.ts b/platforms/market/src/features/subscription/entities/subscription/types.ts index 553583c..bff4798 100644 --- a/platforms/market/src/features/subscription/entities/subscription/types.ts +++ b/platforms/market/src/features/subscription/entities/subscription/types.ts @@ -15,6 +15,8 @@ export type SubscriptionCreatorEntity = { id: string; avatar: string | null; username: string | null; + /** The creator's display name; an API older than it leaves it out. */ + displayName?: string | null; /** trader-service `kycStatus` (or `verificationStatus`) is `suspended`. */ suspended: boolean; noteFa: string | null; @@ -62,6 +64,9 @@ export type InvestorSubscriptionEntity = { color: 'primary' | 'ink-mute'; hex: string; }; + /** A refund ended it (A16); `expiryDate` is then the refund date. Older APIs leave them out. */ + refunded?: boolean; + refundedAt?: string | null; /** The last completed payment to this creator differs from the tier's current price. */ priceChanged: boolean; priceChangedNoteFa: string; diff --git a/platforms/market/src/features/subscription/index.ts b/platforms/market/src/features/subscription/index.ts index a3e7ca1..a458731 100644 --- a/platforms/market/src/features/subscription/index.ts +++ b/platforms/market/src/features/subscription/index.ts @@ -1,3 +1,16 @@ +import './types'; + +export { startRenewal } from './actions/start-renewal'; +export type { StartRenewalArgs } from './actions/start-renewal'; +export { SUBSCRIPTION_EVENTS } from './constants'; +export { useRenewalSheet } from './models/renewal'; +export type { + RenewalPhase, + RenewalSheetModel, + UseRenewalSheetOptions, +} from './models/renewal'; +export { useSubscriptionsPart } from './models/subscriptions'; +export type { SubscriptionsPartModel } from './models/subscriptions'; export { subscriptionKeys, subscriptionRepository, diff --git a/platforms/market/src/features/subscription/models/.gitkeep b/platforms/market/src/features/subscription/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/subscription/models/renewal/index.ts b/platforms/market/src/features/subscription/models/renewal/index.ts new file mode 100644 index 0000000..978d0cd --- /dev/null +++ b/platforms/market/src/features/subscription/models/renewal/index.ts @@ -0,0 +1,6 @@ +export { useRenewalSheet } from './use-renewal-sheet'; +export type { + RenewalPhase, + RenewalSheetModel, + UseRenewalSheetOptions, +} from './types'; diff --git a/platforms/market/src/features/subscription/models/renewal/types.ts b/platforms/market/src/features/subscription/models/renewal/types.ts new file mode 100644 index 0000000..d2d9149 --- /dev/null +++ b/platforms/market/src/features/subscription/models/renewal/types.ts @@ -0,0 +1,26 @@ +import type { + RenewalKind, + RenewalPreviewPayload, + RenewalTierPayload, +} from '../../repositories/subscription'; + +export type UseRenewalSheetOptions = { subscriptionId: string }; + +/** idle → paying → leaving, for the bank or the result page; a failure returns to idle. */ +export type RenewalPhase = 'idle' | 'paying' | 'leaving'; + +export type RenewalSheetModel = { + /** Follows the subscription: `renew` while it runs, `reactivate` once it ended. */ + kind: RenewalKind; + preview: RenewalPreviewPayload; + /** The periods with a price, in the creator's order. */ + tiers: RenewalTierPayload[]; + selectedTier: RenewalTierPayload | null; + /** The monthly period's standing price, for every longer one's «n٪ کمتر از ماهانه». */ + monthlyPrice: number | undefined; + selectTier: (tierId: string) => void; + pay: () => void; + phase: RenewalPhase; + /** The last tap never reached the server: the banner and its retry. */ + isOffline: boolean; +}; diff --git a/platforms/market/src/features/subscription/models/renewal/use-renewal-sheet.ts b/platforms/market/src/features/subscription/models/renewal/use-renewal-sheet.ts new file mode 100644 index 0000000..8a04614 --- /dev/null +++ b/platforms/market/src/features/subscription/models/renewal/use-renewal-sheet.ts @@ -0,0 +1,118 @@ +import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'; +import { useRouter } from 'next/navigation'; +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { ROUTES } from '../../../../app/navigation/navigation'; +import { isConnectionError, showActionError } from '../../../../shared/utils'; +import { startRenewal } from '../../actions/start-renewal'; +import { + subscriptionKeys, + subscriptionRepository, +} from '../../repositories/subscription'; +import type { + RenewalPhase, + RenewalSheetModel, + UseRenewalSheetOptions, +} from './types'; + +/** + * The renew and reactivate sheet (U3): the creator's periods with the exact dates each would buy + * and its price, a live promotion applied as for new subscribers (terms §۵). Renew + * starts on the current period and extends from the current expiry; reactivate starts with none + * picked, from today, with no invite code. Paying goes to the bank, and every payment ends on its + * result page (U10 §۹). A tap that never reached the server keeps the choice and says so. A + * suspended creator or a payment already in flight is refused with a toast that reloads the list. + */ +export function useRenewalSheet({ + subscriptionId, +}: UseRenewalSheetOptions): RenewalSheetModel { + const { t } = useTranslation('dashboard'); + const router = useRouter(); + const queryClient = useQueryClient(); + const [tierId, setTierId] = useState(null); + const [phase, setPhase] = useState('idle'); + const [isOffline, setIsOffline] = useState(false); + + const { data: preview } = useSuspenseQuery({ + queryKey: subscriptionKeys.preview(subscriptionId), + queryFn: ({ signal }) => + subscriptionRepository.getPreview({ subscriptionId }, { signal }), + }); + + const tiers = preview.tiers.filter((tier) => tier.amountToman !== null); + const selectedId = tierId ?? preview.selectedTierId; + const selectedTier = tiers.find((tier) => tier.id === selectedId) ?? null; + const monthly = tiers.find((tier) => tier.billingPeriod === 'monthly'); + + // Back from the bank restores the page as it was left, spinner and all: start over from it. + useEffect(() => { + const onPageShow = (event: PageTransitionEvent) => { + if (event.persisted) setPhase('idle'); + }; + window.addEventListener('pageshow', onPageShow); + return () => window.removeEventListener('pageshow', onPageShow); + }, []); + + const reload = () => { + void queryClient.invalidateQueries({ + queryKey: subscriptionKeys.detail(subscriptionId), + }); + void queryClient.invalidateQueries({ + queryKey: subscriptionKeys.dashboard(), + }); + }; + + const pay = async () => { + if (!selectedTier || phase !== 'idle') return; + setPhase('paying'); + setIsOffline(false); + try { + const result = await startRenewal({ + kind: preview.kind, + subscriptionId, + tierId: selectedTier.id, + creatorId: preview.creator.id, + }); + if (result.outcome === 'redirect' || result.outcome === 'granted') { + setPhase('leaving'); + if (result.outcome === 'redirect' && result.redirectUrl) { + window.location.assign(result.redirectUrl); + } else { + router.push(ROUTES.paymentResult(result.paymentId)); + } + return; + } + // Renew and reactivate send no expected price and never meet the waitlist; read it again. + setPhase('idle'); + reload(); + } catch (error) { + setPhase('idle'); + if (isConnectionError(error)) setIsOffline(true); + showActionError(error, { + t, + failedMessage: + preview.kind === 'renew' + ? t('subscriptions.renewal.renew-failed', { + username: preview.creator.username, + }) + : t('subscriptions.renewal.reactivate-failed', { + username: preview.creator.username, + }), + reload, + }); + } + }; + + return { + kind: preview.kind, + preview, + tiers, + selectedTier, + monthlyPrice: monthly?.standingToman ?? monthly?.amountToman ?? undefined, + selectTier: setTierId, + pay: () => void pay(), + phase, + isOffline, + }; +} diff --git a/platforms/market/src/features/subscription/models/subscriptions/index.ts b/platforms/market/src/features/subscription/models/subscriptions/index.ts new file mode 100644 index 0000000..1aaf81b --- /dev/null +++ b/platforms/market/src/features/subscription/models/subscriptions/index.ts @@ -0,0 +1,2 @@ +export { useSubscriptionsPart } from './use-subscriptions-part'; +export type { SubscriptionsPartModel } from './types'; diff --git a/platforms/market/src/features/subscription/models/subscriptions/types.ts b/platforms/market/src/features/subscription/models/subscriptions/types.ts new file mode 100644 index 0000000..938d34b --- /dev/null +++ b/platforms/market/src/features/subscription/models/subscriptions/types.ts @@ -0,0 +1,18 @@ +import type { + SubscriptionDashboardPayload, + SubscriptionPayload, +} from '../../repositories/subscription'; + +export type SubscriptionsPartModel = { + dashboard: SubscriptionDashboardPayload; + /** The card whose renew or reactivate sheet is open, kept while it closes. */ + renewalTarget: SubscriptionPayload | null; + isRenewalOpen: boolean; + /** «تمدید» on an active card, «فعال‌سازی مجدد» on an expired one. */ + openRenewal: (subscription: SubscriptionPayload) => void; + closeRenewal: () => void; + /** «تماس با پشتیبانی» on a suspended card, or an expired one whose creator is suspended. */ + isSupportOpen: boolean; + openSupport: () => void; + closeSupport: () => void; +}; diff --git a/platforms/market/src/features/subscription/models/subscriptions/use-subscriptions-part.ts b/platforms/market/src/features/subscription/models/subscriptions/use-subscriptions-part.ts new file mode 100644 index 0000000..401c710 --- /dev/null +++ b/platforms/market/src/features/subscription/models/subscriptions/use-subscriptions-part.ts @@ -0,0 +1,41 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { useState } from 'react'; + +import { + subscriptionKeys, + subscriptionRepository, +} from '../../repositories/subscription'; +import type { SubscriptionPayload } from '../../repositories/subscription'; +import type { SubscriptionsPartModel } from './types'; + +/** + * داشبورد › اشتراک‌ها (U2): the investor's subscriptions, read in the browser with their session. + * Active ones by nearest expiry, a suspended creator's among them, then the expired ones. A card's + * «تمدید» or «فعال‌سازی مجدد» opens the renewal sheet (U3); its «تماس با پشتیبانی» the support + * sheet (U2 ۱.۲). + */ +export function useSubscriptionsPart(): SubscriptionsPartModel { + const [renewalTarget, setRenewalTarget] = + useState(null); + const [isRenewalOpen, setIsRenewalOpen] = useState(false); + const [isSupportOpen, setIsSupportOpen] = useState(false); + + const dashboard = useSuspenseQuery({ + queryKey: subscriptionKeys.dashboard(), + queryFn: ({ signal }) => subscriptionRepository.getDashboard({ signal }), + }); + + return { + dashboard: dashboard.data, + renewalTarget, + isRenewalOpen, + openRenewal: (subscription) => { + setRenewalTarget(subscription); + setIsRenewalOpen(true); + }, + closeRenewal: () => setIsRenewalOpen(false), + isSupportOpen, + openSupport: () => setIsSupportOpen(true), + closeSupport: () => setIsSupportOpen(false), + }; +} diff --git a/platforms/market/src/features/subscription/repositories/subscription/mappers.ts b/platforms/market/src/features/subscription/repositories/subscription/mappers.ts index 21c82d9..de65a97 100644 --- a/platforms/market/src/features/subscription/repositories/subscription/mappers.ts +++ b/platforms/market/src/features/subscription/repositories/subscription/mappers.ts @@ -26,6 +26,7 @@ export function toSubscriptionCreatorPayload( return { id: dto.id, username: dto.username, + displayName: dto.displayName ?? null, avatarUrl: toApiUrl(dto.avatar), suspended: dto.suspended, }; @@ -37,11 +38,13 @@ export function toSubscriptionPayload( const expired = dto.status.value === 'expired'; return { id: dto.id, - status: expired - ? 'expired' - : dto.creator.suspended - ? 'suspended' - : 'active', + status: dto.refunded + ? 'refunded' + : expired + ? 'expired' + : dto.creator.suspended + ? 'suspended' + : 'active', creator: toSubscriptionCreatorPayload(dto.creator), tier: { id: dto.tier.id, @@ -101,6 +104,14 @@ export function toRenewalPreviewPayload( id: tier.id, billingPeriod: tier.billingPeriod, amountToman: tier.toman, + standingToman: tier.standingPriceToman, + promotion: tier.promotion + ? { + percent: tier.promotion.percent, + endsAt: tier.promotion.endsAt ?? null, + indefinite: tier.promotion.indefinite, + } + : null, selected: tier.selected, periodFrom: tier.preview.from, periodTo: tier.preview.to, diff --git a/platforms/market/src/features/subscription/repositories/subscription/subscription.ts b/platforms/market/src/features/subscription/repositories/subscription/subscription.ts index 67b07a6..5f63871 100644 --- a/platforms/market/src/features/subscription/repositories/subscription/subscription.ts +++ b/platforms/market/src/features/subscription/repositories/subscription/subscription.ts @@ -1,4 +1,5 @@ import { + toCheckoutError, toCheckoutResultPayload, toPriceChangedPayload, } from '../../../checkout'; @@ -31,7 +32,8 @@ import type { /** * A renew or reactivate request, mapped as checkout maps subscribe. The 409 of a stale price is an - * outcome; every other error is thrown. + * outcome; every other error is thrown with its checkout code (`checkoutErrorCode`): the creator + * suspended (403) or a payment to them still in flight (409). */ async function checkout( request: () => Promise, @@ -41,7 +43,7 @@ async function checkout( } catch (error) { const priceChanged = toPriceChangedPayload(error); if (priceChanged) return priceChanged; - throw error; + throw toCheckoutError(error); } } diff --git a/platforms/market/src/features/subscription/repositories/subscription/types.ts b/platforms/market/src/features/subscription/repositories/subscription/types.ts index e8c88af..524e9b0 100644 --- a/platforms/market/src/features/subscription/repositories/subscription/types.ts +++ b/platforms/market/src/features/subscription/repositories/subscription/types.ts @@ -9,15 +9,20 @@ import type { /** * 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. + * creator's channel is suspended, so it stays in the active list. `refunded`: a refund ended it + * (A16), «پایان یافته · بازگشت وجه». */ -export type SubscriptionStatus = 'active' | 'suspended' | 'expired'; +export type SubscriptionStatus = + | 'active' + | 'suspended' + | 'expired' + | 'refunded'; -/** The creator behind a subscription. `id` is their user id; there is no display name. */ +/** The creator behind a subscription. `id` is their user id. */ export type SubscriptionCreatorPayload = { id: string; username: string | null; + displayName: string | null; avatarUrl: string | null; /** The channel is blacked out: no link, and renew or reactivate answers 403. */ suspended: boolean; @@ -31,6 +36,7 @@ export type SubscriptionPayload = { /** `priceToman` is the tier's current price, not the amount paid (see `lastReceipt`). */ tier: { id: string; billingPeriod: BillingPeriod; priceToman: number | null }; startsAt: string | null; + /** The expiry; for a refunded one, the refund date. */ endsAt: string; /** While running (active or suspended): whole days left, rounded up, at least 1. */ daysLeft: number | null; @@ -106,8 +112,16 @@ export type RenewalPreviewQueryDto = { tierId?: string }; export type RenewalTierPayload = { id: string; billingPeriod: BillingPeriod; - /** What renew or reactivate charges: the standing price, as promotions apply to subscribe only. */ + /** What renew or reactivate charges: a live promotion applies, as it does to subscribe. */ amountToman: number | null; + /** The price without the promotion, shown struck while one runs. */ + standingToman: number | null; + /** A live promotion; `endsAt` is `null` when it is open-ended. */ + promotion: { + percent: number; + endsAt: string | null; + indefinite: boolean; + } | null; selected: boolean; /** Renew: from the current expiry. Reactivate: from now. */ periodFrom: string; @@ -140,7 +154,7 @@ export type RenewalPreviewResponseDto = { suspendedCreatorBlockFa: string; priceChangedNoteFa: string; currentStatementFa: string | null; - /** `toman` here is the charged (standing) price; `priceToman` may carry a subscribe-only promotion. */ + /** `toman` here is the charged price, a live promotion applied; `standingPriceToman` is without it. */ tiers: (PublicTierEntity & { selected: boolean; preview: { diff --git a/platforms/market/src/features/subscription/types.ts b/platforms/market/src/features/subscription/types.ts new file mode 100644 index 0000000..5cf08d8 --- /dev/null +++ b/platforms/market/src/features/subscription/types.ts @@ -0,0 +1,11 @@ +import type { RenewalKind } from './repositories/subscription'; + +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'subscription.renewal-started': { + subscriptionId: string; + kind: RenewalKind; + paymentId: string; + }; + } +} diff --git a/platforms/market/src/features/transaction/actions/.gitkeep b/platforms/market/src/features/transaction/actions/.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 index e01223d..808a22b 100644 --- a/platforms/market/src/features/transaction/entities/payment/index.ts +++ b/platforms/market/src/features/transaction/entities/payment/index.ts @@ -3,4 +3,5 @@ export type { PaymentCreatorEntity, PaymentDetailEntity, PaymentEntity, + PaymentRefundEntity, } from './types'; diff --git a/platforms/market/src/features/transaction/entities/payment/types.ts b/platforms/market/src/features/transaction/entities/payment/types.ts index 6db6642..02afe7a 100644 --- a/platforms/market/src/features/transaction/entities/payment/types.ts +++ b/platforms/market/src/features/transaction/entities/payment/types.ts @@ -1,10 +1,10 @@ import type { BillingPeriod, - CheckoutKind, ConfirmationLanding, ConfirmationPhase, PaymentStatus, PaymentUiStatus, + TransactionKind, } from '../../../../shared/constants'; /** @@ -32,10 +32,23 @@ export type AccessConfirmationEntity = { export type PaymentCreatorEntity = { id: string; username: string | null; + displayName: string | null; avatar: string | null; historical: boolean; }; +/** A refund paid back by bank transfer (S3): on the refund row, and on the payment it refunded. */ +export type PaymentRefundEntity = { + refundedAt: string; + /** Only on the refund row: the last four digits of the شبا it went to. */ + shebaLast4?: string | null; + currency: string; + toman: number | null; + amountUnitFa: string; + /** On the refunded payment: «پایان‌یافته با بازگشت وجه». */ + noteFa: string | null; +}; + /** * 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. @@ -52,8 +65,8 @@ export type PaymentEntity = { period: BillingPeriod; labelFa: string; }; - /** What the payment bought. */ - type: { value: CheckoutKind; labelFa: string }; + /** What the payment bought, or `refund` for a بازگشت وجه row (its id ends `-refund`). */ + type: { value: TransactionKind; labelFa: string }; amount: number; currency: string; toman: number | null; @@ -85,6 +98,10 @@ export type PaymentEntity = { to: string | null; labelFa: string | null; } | null; + /** Its refund, if an admin recorded one; an API older than refunds leaves it out. */ + refund?: PaymentRefundEntity | null; + /** A refund row only: the payment it refunded. */ + refundOf?: string; }; /** `GET /subscriptions/payments/:id`: the row plus the detail screen and the U10 confirmation. */ diff --git a/platforms/market/src/features/transaction/index.ts b/platforms/market/src/features/transaction/index.ts index 22473e9..409e542 100644 --- a/platforms/market/src/features/transaction/index.ts +++ b/platforms/market/src/features/transaction/index.ts @@ -2,8 +2,12 @@ export type { AccessConfirmationEntity, PaymentEntity, } from './entities/payment'; +export { useTransactionsPart } from './models/transactions'; +export type { TransactionsPartModel } from './models/transactions'; export { toAccessConfirmationPayload, + TRANSACTION_FILTER_PARAM, + TRANSACTION_FILTERS, transactionKeys, transactionRepository, } from './repositories/transaction'; diff --git a/platforms/market/src/features/transaction/models/.gitkeep b/platforms/market/src/features/transaction/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/platforms/market/src/features/transaction/models/transactions/index.ts b/platforms/market/src/features/transaction/models/transactions/index.ts new file mode 100644 index 0000000..4f33486 --- /dev/null +++ b/platforms/market/src/features/transaction/models/transactions/index.ts @@ -0,0 +1,2 @@ +export { useTransactionsPart } from './use-transactions-part'; +export type { TransactionsPartModel } from './types'; diff --git a/platforms/market/src/features/transaction/models/transactions/types.ts b/platforms/market/src/features/transaction/models/transactions/types.ts new file mode 100644 index 0000000..f01fb8b --- /dev/null +++ b/platforms/market/src/features/transaction/models/transactions/types.ts @@ -0,0 +1,31 @@ +import type { LoadMoreErrorKind } from '../../../../shared/utils'; +import type { + TransactionFilter, + TransactionPayload, +} from '../../repositories/transaction'; + +export type TransactionsPartModel = { + /** The filter in the URL; `all` without one. */ + filter: TransactionFilter; + /** Shows another status at once; the list keeps its rows until the new ones arrive. */ + setFilter: (filter: TransactionFilter) => void; + /** A new filter's rows are on their way. */ + isFiltering: boolean; + /** The payments for the filter, pending ones first, then newest first, each once. */ + rows: TransactionPayload[]; + /** No payment at all yet, under any filter: the chips hide (U4 ۴.۲). */ + isEmpty: boolean; + hasMore: boolean; + /** Reads the next page; nothing while any read of the list is on its way. Also its retry. */ + loadMore: () => void; + isLoadingMore: boolean; + /** The next page failed: an inline row with its retry replaces «more». */ + loadMoreError: LoadMoreErrorKind | null; + /** The row whose detail is open, kept while it closes. */ + detail: TransactionPayload | null; + isDetailOpen: boolean; + openDetail: (row: TransactionPayload) => void; + closeDetail: () => void; + /** Copies a reference and says so: «شماره پیگیری کپی شد.». */ + copyReference: (reference: string) => void; +}; diff --git a/platforms/market/src/features/transaction/models/transactions/use-transactions-part.ts b/platforms/market/src/features/transaction/models/transactions/use-transactions-part.ts new file mode 100644 index 0000000..d8f64e4 --- /dev/null +++ b/platforms/market/src/features/transaction/models/transactions/use-transactions-part.ts @@ -0,0 +1,101 @@ +import { useSuspenseInfiniteQuery } from '@tanstack/react-query'; +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; +import { useState, useTransition } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { + copyWithToast, + firstOfEach, + loadMoreErrorKind, +} from '../../../../shared/utils'; +import { + TRANSACTION_FILTER_PARAM, + TRANSACTION_FILTERS, + transactionKeys, + transactionRepository, +} from '../../repositories/transaction'; +import type { + TransactionFilter, + TransactionPayload, +} from '../../repositories/transaction'; +import type { TransactionsPartModel } from './types'; + +function toFilter(value: string | null): TransactionFilter { + return TRANSACTION_FILTERS.find((filter) => filter === value) ?? 'all'; +} + +/** + * داشبورد › تراکنش‌ها (U4): every payment the investor made or tried, read in the browser with + * their session, 20 a page, pending ones first, then newest first. The status filter lives in the + * URL and applies at once; the rows stay until the new ones arrive. A row opens its detail, whose + * reference copies with a toast (۱.۲). + */ +export function useTransactionsPart(): TransactionsPartModel { + const { t } = useTranslation('dashboard'); + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const [isFiltering, startFiltering] = useTransition(); + const [detail, setDetail] = useState(null); + const [isDetailOpen, setIsDetailOpen] = useState(false); + const filter = toFilter(searchParams.get(TRANSACTION_FILTER_PARAM)); + + const list = useSuspenseInfiniteQuery({ + queryKey: transactionKeys.list(filter), + queryFn: ({ pageParam, signal }) => + transactionRepository.list( + { status: filter, page: pageParam }, + { signal }, + ), + initialPageParam: 1, + getNextPageParam: (last) => (last.hasMore ? last.page + 1 : undefined), + }); + + const setFilter = (next: TransactionFilter) => { + const params = new URLSearchParams(searchParams.toString()); + if (next === 'all') params.delete(TRANSACTION_FILTER_PARAM); + else params.set(TRANSACTION_FILTER_PARAM, next); + const query = params.toString(); + startFiltering(() => { + router.replace(query ? `${pathname}?${query}` : pathname, { + scroll: false, + }); + }); + }; + + const rows = firstOfEach( + list.data.pages.flatMap((page) => page.items), + (row) => row.id, + ); + + return { + filter, + setFilter, + isFiltering, + rows, + // No payment at all, whatever the filter in the URL: the empty state, with no chips (U4 ۴.۲). + isEmpty: !list.data.pages[0].hasAnyPayment, + hasMore: list.hasNextPage, + loadMore: () => { + // fetchNextPage would cancel a read of every page on its way and skip or repeat rows. + if (!list.isFetching) void list.fetchNextPage(); + }, + isLoadingMore: list.isFetchingNextPage, + loadMoreError: list.isFetchNextPageError + ? loadMoreErrorKind(list.error) + : null, + detail, + isDetailOpen, + openDetail: (row) => { + setDetail(row); + setIsDetailOpen(true); + }, + closeDetail: () => setIsDetailOpen(false), + copyReference: (reference) => + copyWithToast(reference, { + copied: t('transactions.reference-copied'), + failed: t('transactions.copy-failed'), + failedDescription: t('transactions.copy-failed-description'), + }), + }; +} diff --git a/platforms/market/src/features/transaction/repositories/transaction/constants.ts b/platforms/market/src/features/transaction/repositories/transaction/constants.ts index d24ac1c..fe42bd4 100644 --- a/platforms/market/src/features/transaction/repositories/transaction/constants.ts +++ b/platforms/market/src/features/transaction/repositories/transaction/constants.ts @@ -1,5 +1,16 @@ import type { TransactionFilter } from './types'; +/** The history's status filters in display order: همه · موفق · در حال بررسی · ناموفق (U4 ۳.۱). */ +export const TRANSACTION_FILTERS = [ + 'all', + 'successful', + 'pending', + 'failed', +] as const satisfies readonly TransactionFilter[]; + +/** The URL's query parameter that holds the filter, so a view can be shared and survives a refresh. */ +export const TRANSACTION_FILTER_PARAM = 'status'; + export const TRANSACTION_ENDPOINTS = { list: '/subscriptions/transactions', detail: (id: string) => `/subscriptions/payments/${encodeURIComponent(id)}`, diff --git a/platforms/market/src/features/transaction/repositories/transaction/index.ts b/platforms/market/src/features/transaction/repositories/transaction/index.ts index 815d14c..ecfc534 100644 --- a/platforms/market/src/features/transaction/repositories/transaction/index.ts +++ b/platforms/market/src/features/transaction/repositories/transaction/index.ts @@ -1,4 +1,8 @@ -export { transactionKeys } from './constants'; +export { + TRANSACTION_FILTER_PARAM, + TRANSACTION_FILTERS, + transactionKeys, +} from './constants'; export { toAccessConfirmationPayload } from './mappers'; export { transactionRepository } from './transaction'; export type { diff --git a/platforms/market/src/features/transaction/repositories/transaction/mappers.ts b/platforms/market/src/features/transaction/repositories/transaction/mappers.ts index 74ad4e9..014c15b 100644 --- a/platforms/market/src/features/transaction/repositories/transaction/mappers.ts +++ b/platforms/market/src/features/transaction/repositories/transaction/mappers.ts @@ -26,6 +26,7 @@ export function toTransactionPayload(dto: PaymentEntity): TransactionPayload { creator: { id: dto.creator.id, username: dto.creator.username, + displayName: dto.creator.displayName ?? null, avatarUrl: toApiUrl(dto.creator.avatar), }, type: dto.type.value, @@ -38,6 +39,13 @@ export function toTransactionPayload(dto: PaymentEntity): TransactionPayload { reference: dto.reference.value, subscriptionId: dto.subscriptionId, period: dto.period ? { from: dto.period.from, to: dto.period.to } : null, + refund: dto.refund + ? { + refundedAt: dto.refund.refundedAt, + amountToman: dto.refund.toman, + shebaLast4: dto.refund.shebaLast4 ?? null, + } + : null, }; } @@ -50,6 +58,7 @@ export function toTransactionPagePayload( pageSize: dto.pageSize, total: dto.total, hasMore: dto.hasMore, + hasAnyPayment: dto.summary.hasAny, items: dto.items.map(toTransactionPayload), }; } diff --git a/platforms/market/src/features/transaction/repositories/transaction/types.ts b/platforms/market/src/features/transaction/repositories/transaction/types.ts index 184915d..1fc2672 100644 --- a/platforms/market/src/features/transaction/repositories/transaction/types.ts +++ b/platforms/market/src/features/transaction/repositories/transaction/types.ts @@ -1,10 +1,10 @@ import type { BillingPeriod, - CheckoutKind, ConfirmationLanding, ConfirmationPhase, PaymentStatus, PaymentUiStatus, + TransactionKind, } from '../../../../shared/constants'; import type { PaymentDetailEntity, @@ -29,9 +29,14 @@ export type ListTransactionsQueryDto = { 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; + creator: { + id: string; + username: string | null; + displayName: string | null; + avatarUrl: string | null; + }; + /** What the payment bought, or `refund`: money an admin paid back (S3). */ + type: TransactionKind; billingPeriod: BillingPeriod; tierId: string; amountToman: number | null; @@ -42,8 +47,17 @@ export type TransactionPayload = { /** 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. */ + /** The period bought; only on a successful payment. A refunded one ends on its refund date. */ period: { from: string | null; to: string | null } | null; + /** + * A refund: on a `refund` row, what went back and to which شبا; on a payment, that it was + * refunded. `null` otherwise. + */ + refund: { + refundedAt: string; + amountToman: number | null; + shebaLast4: string | null; + } | null; }; /** One page of the history, paginated exactly as the server does. */ @@ -54,6 +68,8 @@ export type TransactionPagePayload = { pageSize: number; total: number; hasMore: boolean; + /** The investor has made or tried a payment, whatever the filter; `false` is the empty state. */ + hasAnyPayment: boolean; items: TransactionPayload[]; }; @@ -61,6 +77,8 @@ export type TransactionPageResponseDto = { labels: { tabFa: string; sectionFa: string }; summary: { empty: boolean; + /** Any payment at all, whatever the filter. */ + hasAny: boolean; emptyMessageFa: string; emptyCta: { labelFa: string; href: string }; }; diff --git a/platforms/market/src/index.ts b/platforms/market/src/index.ts index 3a7943d..de5a8b4 100644 --- a/platforms/market/src/index.ts +++ b/platforms/market/src/index.ts @@ -77,6 +77,7 @@ export { toE164Mobile, } from './shared/utils'; export { + BILLING_PERIOD_MONTHS, BILLING_PERIODS, CHECKOUT_KINDS, COMPARE_SOURCES, @@ -86,6 +87,7 @@ export { PAYMENT_STATUSES, PAYMENT_UI_STATUSES, SUBSCRIPTION_RECORD_STATUSES, + TRANSACTION_KINDS, VERIFICATION_STATUSES, } from './shared/constants'; export type { @@ -98,6 +100,7 @@ export type { PaymentStatus, PaymentUiStatus, SubscriptionRecordStatus, + TransactionKind, VerificationStatus, } from './shared/constants'; export { @@ -257,22 +260,43 @@ export type { SavePricingArgs, } from './features/pricing'; export { + CHECKOUT_ERROR_CODES, CHECKOUT_EVENTS, + checkoutErrorCode, checkoutKeys, checkoutRepository, + joinWaitlist, leaveWaitlist, + settleAbandonedPayment, + startCheckout, + useCheckoutPage, + usePaymentResultPage, + usePaymentReturnPage, } from './features/checkout'; export type { + AbandonOutcome, + AbandonPaymentPayload, CheckoutCtaState, + CheckoutErrorCode, + CheckoutHalt, + CheckoutMode, + CheckoutPageModel, CheckoutPayload, + CheckoutPhase, CheckoutResultPayload, CheckoutTierPayload, + CodeCheck, GrantedSubscriptionPayload, + PaymentResultKind, + PaymentResultPageModel, PriceChangedPayload, ReferralCodeArgs, ReferralCodeStatus, ReferralValidationPayload, SubscribeArgs, + UseCheckoutPageOptions, + UsePaymentResultPageOptions, + UsePaymentReturnPageOptions, WaitlistJoinedPayload, } from './features/checkout'; export { diff --git a/platforms/market/src/shared/constants/index.ts b/platforms/market/src/shared/constants/index.ts index 1126e5f..c0af063 100644 --- a/platforms/market/src/shared/constants/index.ts +++ b/platforms/market/src/shared/constants/index.ts @@ -10,10 +10,22 @@ export const BILLING_PERIODS = [ ] 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. */ +/** Each period's length in months, for its per-month equivalent. */ +export const BILLING_PERIOD_MONTHS: Record = { + monthly: 1, + quarterly: 3, + semi_annual: 6, + yearly: 12, +}; + +/** What a checkout buys, and so a payment's `type`: a new subscription, more time on a running one, or a restart after expiry. */ export const CHECKOUT_KINDS = ['subscribe', 'renew', 'reactivate'] as const; export type CheckoutKind = (typeof CHECKOUT_KINDS)[number]; +/** A row of the investor's تراکنش‌ها: a purchase, or a refund an admin paid back (S3). */ +export const TRANSACTION_KINDS = [...CHECKOUT_KINDS, 'refund'] as const; +export type TransactionKind = (typeof TRANSACTION_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. @@ -52,7 +64,8 @@ export type Market = (typeof MARKETS)[number]; /** * `subscription_payments.status` as stored. A pending payment turns `pending_review` after a while - * and `expired` after its 30-minute TTL. + * and `expired` after its 30-minute TTL; `abandoned` when the investor came back from the gateway + * without paying, which no list shows. */ export const PAYMENT_STATUSES = [ 'pending', @@ -61,6 +74,7 @@ export const PAYMENT_STATUSES = [ 'failed', 'cancelled', 'expired', + 'abandoned', ] as const; export type PaymentStatus = (typeof PAYMENT_STATUSES)[number]; diff --git a/platforms/market/src/shared/labels/content-labels.tsx b/platforms/market/src/shared/labels/content-labels.tsx index 276925c..a60fe2d 100644 --- a/platforms/market/src/shared/labels/content-labels.tsx +++ b/platforms/market/src/shared/labels/content-labels.tsx @@ -22,6 +22,8 @@ export function postCardLabels(t: ContentT): PostCardLabels { alt ? t('post.open-slide-alt', { n, total, alt }) : t('post.open-slide', { n, total }), + previousImage: t('post.previous-image'), + nextImage: t('post.next-image'), imageCount: (n) => t('post.image-count', { n }), share: t('post.share'), copyLink: t('post.copy-link'), diff --git a/platforms/market/src/shared/labels/index.ts b/platforms/market/src/shared/labels/index.ts index a16e440..d203acd 100644 --- a/platforms/market/src/shared/labels/index.ts +++ b/platforms/market/src/shared/labels/index.ts @@ -4,4 +4,6 @@ export { postCardLabels, predictionCardLabels, } from './content-labels'; -export type { ContentT } from './types'; +export { promotionCountdownLabels, tierOptionLabels } from './payment-labels'; +export { subscriptionCardLabels } from './subscription-labels'; +export type { CommonT, ContentT, DashboardT, PaymentT } from './types'; diff --git a/platforms/market/src/shared/labels/payment-labels.tsx b/platforms/market/src/shared/labels/payment-labels.tsx new file mode 100644 index 0000000..887667d --- /dev/null +++ b/platforms/market/src/shared/labels/payment-labels.tsx @@ -0,0 +1,36 @@ +import type { CountdownLabels } from '@lumina/island/atoms/countdown'; +import type { TierOptionLabels } from '@lumina/island/organisms/tier-option'; +import { number } from '@lumina/tools/format'; + +import type { PaymentT } from './types'; + +// Island organisms take every text as props (0005). These build them from the `payment` +// namespace once, so checkout and the renew and reactivate sheets word a period the same way. + +/** TierOption's texts: the unit, the discount tag, the per-month line and the saving. */ +export function tierOptionLabels(t: PaymentT): TierOptionLabels { + return { + currency: t('tier.currency'), + discount: (pct) => t('tier.discount', { pct }), + perMonth: (amount) => ( + <> + {t('tier.per-month-before')} {amount} {t('tier.per-month-after')} + + ), + saving: (pct) => ( + <> + {pct} {t('tier.saving-after')} + + ), + struckSr: t('tier.struck'), + }; +} + +/** A promotion's end under its tier (U9 ۳.۵): a date, then hours, then under an hour. */ +export function promotionCountdownLabels(t: PaymentT): CountdownLabels { + return { + until: (date) => t('tier.until', { date }), + hoursLeft: (hours) => t('tier.hours-left', { hours: number(hours) }), + underAnHour: t('tier.under-an-hour'), + }; +} diff --git a/platforms/market/src/shared/labels/subscription-labels.tsx b/platforms/market/src/shared/labels/subscription-labels.tsx new file mode 100644 index 0000000..42b1574 --- /dev/null +++ b/platforms/market/src/shared/labels/subscription-labels.tsx @@ -0,0 +1,53 @@ +import type { SubscriptionCardLabels } from '@lumina/island/organisms/subscription-card'; +import { number } from '@lumina/tools/format'; + +import type { CommonT, DashboardT } from './types'; + +// Island organisms take every text as props (0005). One object serves every card in a list. + +/** SubscriptionCard's texts: the badges, the rows, the time left and the actions. */ +export function subscriptionCardLabels( + t: DashboardT, + tCommon: CommonT, +): SubscriptionCardLabels { + return { + status: { + active: tCommon('status.subscription.active'), + suspended: tCommon('status.subscription.suspended'), + expired: tCommon('status.subscription.expired'), + refunded: tCommon('status.subscription.refunded'), + }, + period: t('subscriptions.card.period'), + amount: t('subscriptions.card.amount'), + currency: tCommon('currency'), + start: t('subscriptions.card.start'), + expiry: t('subscriptions.card.expiry'), + end: t('subscriptions.card.end'), + daysLeft: (days) => + t('subscriptions.card.days-left', { days: number(days) }), + underDays: (days) => + t('subscriptions.card.under-days', { days: number(days) }), + expiring: t('subscriptions.card.expiring'), + renew: t('subscriptions.card.renew'), + reactivate: t('subscriptions.card.reactivate'), + support: t('subscriptions.card.support'), + terms: t('subscriptions.card.terms'), + suspendedNote: t('subscriptions.card.suspended-note'), + refundNote: t('subscriptions.card.refund-note'), + range: (start, end) => ( + <> + {start} {t('subscriptions.card.range-to')} {end} + + ), + expiresOn: (end) => ( + <> + {t('subscriptions.card.expires-on')} {end} + + ), + endedOn: (end) => ( + <> + {t('subscriptions.card.ended-on')} {end} + + ), + }; +} diff --git a/platforms/market/src/shared/labels/types.ts b/platforms/market/src/shared/labels/types.ts index bf44bd9..ac5826b 100644 --- a/platforms/market/src/shared/labels/types.ts +++ b/platforms/market/src/shared/labels/types.ts @@ -5,3 +5,12 @@ import type { TFunction } from 'i18next'; * `i18n.getFixedT(null, 'content')` on the server. */ export type ContentT = TFunction<'content'>; + +/** `t` fixed to the `payment` namespace, as `ContentT` is to `content`. */ +export type PaymentT = TFunction<'payment'>; + +/** `t` fixed to the `dashboard` namespace. */ +export type DashboardT = TFunction<'dashboard'>; + +/** `t` fixed to the `common` namespace. */ +export type CommonT = TFunction<'common'>; diff --git a/platforms/market/src/shared/locales/fa/common.json b/platforms/market/src/shared/locales/fa/common.json index 45370c8..23f42a5 100644 --- a/platforms/market/src/shared/locales/fa/common.json +++ b/platforms/market/src/shared/locales/fa/common.json @@ -37,6 +37,17 @@ "pending": "در انتظار احراز هویت", "approved": "تأییدشده", "rejected": "رد شده" + }, + "subscription": { + "active": "فعال", + "suspended": "کانال معلق شده", + "expired": "منقضی‌شده", + "refunded": "پایان یافته · بازگشت وجه" + }, + "payment": { + "successful": "موفق", + "failed": "ناموفق", + "pending": "در حال بررسی" } }, "nav": { @@ -69,5 +80,6 @@ "title": "حساب تعلیق شده", "reason": "حساب شما تعلیق شده است. امکان انتشار پست وجود ندارد." } - } + }, + "currency": "تومان" } diff --git a/platforms/market/src/shared/locales/fa/content.json b/platforms/market/src/shared/locales/fa/content.json index 6e497e0..a531a75 100644 --- a/platforms/market/src/shared/locales/fa/content.json +++ b/platforms/market/src/shared/locales/fa/content.json @@ -8,6 +8,8 @@ "open-image-alt": "نمایش تصویر، {{alt}}", "open-slide": "نمایش تصویر {{n}} از {{total}}", "open-slide-alt": "نمایش تصویر {{n}} از {{total}}، {{alt}}", + "previous-image": "تصویر قبلی", + "next-image": "تصویر بعدی", "image-count": "{{n}} تصویر", "share": "اشتراک‌گذاری پست", "copy-link": "کپی لینک", diff --git a/platforms/market/src/shared/locales/fa/dashboard.json b/platforms/market/src/shared/locales/fa/dashboard.json index b7d663d..54480c8 100644 --- a/platforms/market/src/shared/locales/fa/dashboard.json +++ b/platforms/market/src/shared/locales/fa/dashboard.json @@ -19,5 +19,116 @@ "title": "هنوز تحلیلگری را دنبال نکرده‌اید.", "home": "رفتن به خانه" } + }, + "subscriptions": { + "meta-title": "اشتراک‌ها", + "label": "اشتراک‌های شما", + "loading": "در حال بارگذاری اشتراک‌ها…", + "error": "خطا در بارگذاری اشتراک‌ها. دوباره تلاش کنید.", + "active-count": "{{n}} اشتراک فعال", + "no-active": "اشتراک فعالی ندارید.", + "expired": "اشتراک‌های منقضی‌شده", + "empty": { + "title": "شما هنوز اشتراکی ندارید.", + "home": "رفتن به خانه" + }, + "card": { + "period": "دوره", + "amount": "مبلغ پرداختی", + "start": "تاریخ شروع", + "expiry": "تاریخ انقضا", + "end": "تاریخ پایان", + "days-left": "{{days}} روز مانده", + "under-days": "کمتر از {{days}} روز مانده", + "expiring": "اشتراک شما در حال انقضاست. همین الان تمدید کنید.", + "renew": "تمدید", + "reactivate": "فعال‌سازی مجدد", + "support": "تماس با پشتیبانی", + "terms": "شرایط اشتراک", + "suspended-note": "دسترسی به این کانال موقتاً متوقف شده است. اگر کانال پیش از پایان اشتراک شما دوباره فعال شود، مدت توقف به اشتراک شما افزوده می‌شود.", + "refund-note": "در صورت تمایل به بازگشت وجه مدت استفاده‌نشده، با پشتیبانی لومینا در ارتباط باشید.", + "expires-on": "انقضا", + "ended-on": "پایان", + "range-to": "تا" + }, + "renewal": { + "renew-title": "تمدید اشتراک", + "reactivate-title": "فعال‌سازی مجدد اشتراک", + "loading": "در حال بارگذاری دوره‌های اشتراک…", + "error": "دوره‌های اشتراک بارگذاری نشد. دوباره تلاش کنید.", + "current": "شما تا {{date}} اشتراک فعال دارید.", + "tiers": "دوره اشتراک", + "from": "تمدید از:", + "start": "شروع از:", + "today": "امروز — {{date}}", + "to": "تا:", + "price-changed": "قیمت این اشتراک توسط تحلیلگر تغییر کرده است.", + "total": "مبلغ قابل پرداخت", + "no-total": "هنوز دوره‌ای انتخاب نشده است", + "pay-renew": "پرداخت و تمدید", + "pay-reactivate": "پرداخت و فعال‌سازی", + "paying": "در حال انتقال به درگاه…", + "retry": "تلاش دوباره", + "frozen": "برای ادامه، یک دوره اشتراک انتخاب کنید.", + "offline": "خطا در اتصال. دوباره تلاش کنید.", + "renew-failed": "تمدید اشتراک ⁦@{{username}}⁩ شروع نشد", + "reactivate-failed": "فعال‌سازی مجدد اشتراک ⁦@{{username}}⁩ شروع نشد", + "close": "بستن" + } + }, + "transactions": { + "meta-title": "تراکنش‌ها", + "label": "تراکنش‌های شما", + "loading": "در حال بارگذاری تراکنش‌ها…", + "error": "خطا در بارگذاری تراکنش‌ها. دوباره تلاش کنید.", + "filter": "وضعیت", + "filters": { + "all": "همه", + "successful": "موفق", + "pending": "در حال بررسی", + "failed": "ناموفق" + }, + "kinds": { + "subscribe": "اشتراک", + "renew": "تمدید", + "reactivate": "فعال‌سازی مجدد", + "refund": "بازگشت وجه" + }, + "title": "{{kind}} {{period}} — {{name}}", + "open": "جزئیات {{title}}", + "amount": "مبلغ", + "amount-paid": "مبلغ پرداختی", + "reference": "کد پیگیری", + "zarinpal-reference": "کد پیگیری زرین‌پال", + "status": "وضعیت", + "period": "دوره", + "period-to": "تا", + "pending-note": "پرداخت شما در حال بررسی است. پس از تأیید، اشتراک شما فعال می‌شود. اگر پس از مدتی اشتراک فعال نشد، با پشتیبانی در ارتباط باشید.", + "failed-note": "اگر مبلغی از حساب شما کسر شده، بانک آن را حداکثر تا 72 ساعت به حساب شما بازمی‌گرداند.", + "failed-detail-note": "این تراکنش ناموفق بوده است. اگر مبلغی از حساب شما کسر شده، بانک آن را حداکثر تا 72 ساعت به حساب شما بازمی‌گرداند.", + "detail-title": "جزئیات تراکنش", + "support": "تماس با پشتیبانی", + "copy-reference": "کپی کد پیگیری", + "reference-copied": "شماره پیگیری کپی شد.", + "copy-failed": "کد پیگیری کپی نشد", + "copy-failed-description": "کد را نگه دارید و دستی کپی کنید.", + "more": "نمایش تراکنش‌های بیشتر", + "more-failed": "ادامه‌ی فهرست تراکنش‌ها بارگذاری نشد.", + "empty": { + "title": "هنوز هیچ تراکنشی انجام نداده‌اید.", + "home": "رفتن به خانه" + }, + "no-results": "تراکنشی با این وضعیت یافت نشد.", + "close": "بستن", + "title-label": "خرید", + "date": "تاریخ", + "handle": "⁦@{{username}}⁩", + "refund-title": "بازگشت وجه", + "refund-amount": "مبلغ بازگشت‌داده‌شده", + "transfer-reference": "شماره پیگیری انتقال", + "kind": "نوع", + "channel": "کانال", + "sheba": "شبا مقصد", + "refunded-note": "پایان‌یافته با بازگشت وجه" } } diff --git a/platforms/market/src/shared/locales/fa/errors.json b/platforms/market/src/shared/locales/fa/errors.json index 6fb524f..8538f79 100644 --- a/platforms/market/src/shared/locales/fa/errors.json +++ b/platforms/market/src/shared/locales/fa/errors.json @@ -86,5 +86,13 @@ }, "form": { "network": "اتصال اینترنت خود را بررسی کنید." + }, + "checkout": { + "tier-required": "یک دوره اشتراک انتخاب کنید.", + "code-required": "کد دعوت را وارد کنید.", + "code-invalid": "کد دعوت وارد‌شده معتبر نیست.", + "already-active": "اشتراک شما در این کانال همین حالا فعال است.", + "payment-pending": "پرداخت دیگری برای این کانال در حال بررسی است؛ تا روشن شدن نتیجه آن، پرداخت تازه‌ای شروع نمی‌شود.", + "unavailable": "این کانال در حال حاضر در دسترس نیست." } } diff --git a/platforms/market/src/shared/locales/fa/notifications.json b/platforms/market/src/shared/locales/fa/notifications.json new file mode 100644 index 0000000..6dd9785 --- /dev/null +++ b/platforms/market/src/shared/locales/fa/notifications.json @@ -0,0 +1,23 @@ +{ + "title": "اعلان‌ها", + "label": "اعلان‌های شما", + "loading": "در حال بارگذاری اعلان‌ها…", + "error": "خطا در بارگذاری اعلان‌ها. دوباره تلاش کنید.", + "empty": "اعلانی وجود ندارد.", + "bell": "اعلان‌ها", + "bell-unread": "اعلان‌ها، {{count}} خوانده‌نشده", + "close": "بستن", + "unread": "خوانده‌نشده", + "open-failed": "کانال این اعلان باز نشد", + "show-more": "نمایش کامل متن اعلان", + "cta": { + "subscription_expiry_warning": "تمدید اشتراک", + "subscription_expired": "فعال‌سازی مجدد", + "subscription_delayed_confirm": "مشاهده اشتراک", + "waitlist_capacity": "مشاهده کانال", + "payment_pending_review": "مشاهده تراکنش‌ها", + "creator_suspended": "مشاهده اشتراک", + "access_restored": "مشاهده اشتراک" + }, + "support": "تماس با پشتیبانی" +} diff --git a/platforms/market/src/shared/locales/fa/payment.json b/platforms/market/src/shared/locales/fa/payment.json new file mode 100644 index 0000000..afbeee4 --- /dev/null +++ b/platforms/market/src/shared/locales/fa/payment.json @@ -0,0 +1,111 @@ +{ + "checkout": { + "meta-title": "خرید اشتراک ⁦@{{username}}⁩", + "title": "خرید اشتراک", + "loading": "در حال بارگذاری صفحه پرداخت…", + "error": "صفحه پرداخت بارگذاری نشد. دوباره تلاش کنید.", + "leaving": "در حال بازگشت به کانال…", + "verified": "تأییدشده", + "invite-note": "اشتراک در این کانال به‌صورت دعوت‌نامه‌ای و با ظرفیت محدود است. برای دریافت کد دعوت با تحلیلگر در ارتباط باشید.", + "tiers": "دوره اشتراک", + "code": { + "label": "کد دعوت", + "placeholder": "کد دعوت را وارد کنید", + "valid": "کد دعوت معتبر است." + }, + "total": "مبلغ قابل پرداخت", + "no-total": "هنوز دوره‌ای انتخاب نشده است", + "terms-before": "با پرداخت، ", + "terms-link": "شرایط اشتراک", + "terms-after": " را می‌پذیرید.", + "pay": "پرداخت", + "paying": "در حال انتقال به درگاه…", + "retry": "تلاش دوباره", + "frozen": "برای ادامه، یک دوره اشتراک انتخاب کنید و کد دعوت را وارد کنید.", + "offline": "خطا در اتصال. دوباره تلاش کنید.", + "pay-failed": "پرداخت شروع نشد", + "price-changed": { + "title": "قیمت تغییر کرده است", + "from": "قیمت این اشتراک از", + "to": "به", + "changed": "تغییر کرده است.", + "total": "مبلغ قابل پرداخت", + "confirm": "تأیید و پرداخت", + "cancel": "انصراف" + }, + "unavailable": { + "title": "این کانال در حال حاضر در دسترس نیست و پرداخت انجام نشد.", + "home": "بازگشت به خانه" + }, + "waitlist": { + "title": "ظرفیت تکمیل است", + "body": "کد دعوت شما معتبر است، اما ظرفیت اشتراک این کانال در حال حاضر تکمیل شده. می‌توانید در لیست اطلاع‌رسانی قرار بگیرید تا به‌محض باز شدن ظرفیت به شما خبر دهیم.", + "join": "به من اطلاع بده", + "decline": "انصراف", + "already": "شما در لیست اطلاع‌رسانی هستید و به‌محض باز شدن ظرفیت به شما خبر می‌دهیم.", + "back": "بازگشت به کانال", + "joined": "در لیست اطلاع‌رسانی قرار گرفتید.", + "join-failed": "عضویت در لیست اطلاع‌رسانی انجام نشد." + }, + "reactivation-note": "دوره جدید از امروز شروع می‌شود، نه از تاریخ انقضای قبلی.", + "frozen-reactivate": "برای ادامه، یک دوره اشتراک انتخاب کنید.", + "settling": "در حال بررسی پرداخت قبلی شما با بانک…" + }, + "tier": { + "currency": "تومان", + "discount": "{{pct}} تخفیف", + "per-month-before": "معادل", + "per-month-after": "در ماه", + "saving-after": "کمتر از ماهانه", + "struck": "قیمت پیش از تخفیف", + "until": "تا {{date}}", + "hours-left": "{{hours}} ساعت باقی مانده", + "under-an-hour": "کمتر از 1 ساعت باقی مانده" + }, + "confirm": { + "meta-title": "در حال تأیید پرداخت", + "title": "در حال تأیید پرداخت...", + "description": "لطفاً برنامه را نبندید. این کار چند لحظه طول می‌کشد." + }, + "result": { + "meta-title": "نتیجه پرداخت", + "title": "نتیجه پرداخت", + "loading": "در حال بارگذاری نتیجه پرداخت…", + "error": "نتیجه پرداخت بارگذاری نشد. دوباره تلاش کنید.", + "receipt": "رسید پرداخت", + "success": { + "title": "پرداخت موفق بود", + "description": "اشتراک شما فعال شد.", + "note": "رسید این پرداخت با پیامک و اعلان هم برای شما فرستاده شد.", + "channel": "رفتن به کانال {{name}}", + "subscriptions": "مشاهده اشتراک‌ها" + }, + "failed": { + "title": "پرداخت ناموفق بود", + "description": "لطفاً دوباره تلاش کنید.", + "note": "اگر مبلغی از حساب شما کسر شده، بانک آن را حداکثر تا 72 ساعت به حساب شما بازمی‌گرداند.", + "retry": "تلاش دوباره", + "channel": "بازگشت به کانال {{name}}", + "transactions": "مشاهده تراکنش‌ها" + }, + "pending": { + "title": "پرداخت شما در حال بررسی است", + "description": "پس از تأیید، اشتراک شما فعال می‌شود.", + "note": "به محض تأیید با پیامک و اعلان خبر می‌دهیم. اگر پس از مدتی اشتراک فعال نشد، با پشتیبانی در ارتباط باشید.", + "channel": "رفتن به کانال {{name}}", + "transactions": "مشاهده تراکنش‌ها" + }, + "period": "دوره", + "amount-paid": "مبلغ پرداختی", + "amount": "مبلغ", + "paid-at": "تاریخ پرداخت", + "attempted-at": "زمان تلاش", + "expires-at": "تاریخ انقضا", + "reference": "شماره پیگیری", + "copy-reference": "کپی شماره پیگیری", + "reference-copied": "شماره پیگیری کپی شد.", + "copy-failed": "شماره پیگیری کپی نشد", + "copy-failed-description": "شماره را نگه دارید و دستی کپی کنید.", + "handle": "⁦@{{username}}⁩" + } +} diff --git a/platforms/market/src/shared/locales/fa/terms.json b/platforms/market/src/shared/locales/fa/terms.json new file mode 100644 index 0000000..7dccc23 --- /dev/null +++ b/platforms/market/src/shared/locales/fa/terms.json @@ -0,0 +1,54 @@ +{ + "meta-title": "شرایط اشتراک", + "meta-description": "شرایط خرید، تمدید و بازگشت وجه اشتراک کانال تحلیلگران در لومینا.", + "title": "شرایط اشتراک", + "s1": { + "title": "1. اشتراک چیست؟", + "p1": "با خرید اشتراک، به محتوای ویژه (پریمیوم) کانال یک تحلیلگر برای مدت انتخاب‌شده دسترسی پیدا می‌کنید. دسترسی شما بلافاصله پس از تأیید پرداخت فعال می‌شود و تا پایان دوره ادامه دارد.", + "p2": "اشتراک به‌صورت خودکار تمدید نمی‌شود. پیش از پایان دوره به شما اطلاع داده می‌شود تا در صورت تمایل، اشتراک خود را تمدید کنید." + }, + "s2": { + "title": "2. بازگشت وجه", + "p1": "اشتراک‌ها به‌دلیل ماهیت دیجیتال و دسترسی فوری به محتوا، به‌طور کلی قابل بازگشت نیستند.", + "p2": "در موارد استثنایی می‌توانید از طریق پشتیبانی لومینا درخواست بررسی دهید. هر درخواست به‌صورت جداگانه بررسی می‌شود.", + "p3": "در صورت تأیید بازگشت وجه، مبلغ از طریق انتقال بانکی به شماره شبایی که به پشتیبانی اعلام می‌کنید واریز می‌شود. مسئولیت صحت شماره شبای اعلام‌شده بر عهده شماست. بازگشت وجه به‌صورت اعتبار داخل پلتفرم انجام نمی‌شود." + }, + "s3": { + "title": "3. در صورت غیرفعال شدن کانال تحلیلگر", + "p1": "اگر دسترسی به کانال یک تحلیلگر در طول دوره اشتراک شما متوقف شود، بلافاصله از طریق پیامک و اعلان در پلتفرم به شما اطلاع داده می‌شود و دو گزینه خواهید داشت:", + "refund-lead": "درخواست بازگشت وجه:", + "refund": "با پیام به پشتیبانی لومینا، مبلغ دوره استفاده‌نشده به‌صورت نسبی محاسبه و به حساب شما واریز می‌شود.", + "wait-lead": "انتظار برای بازگشت کانال:", + "wait": "اگر کانال پیش از پایان اشتراک شما دوباره فعال شود، مدت‌زمان توقف به اشتراک شما اضافه می‌شود و تاریخ انقضای جدید به شما اعلام خواهد شد.", + "p2": "اگر هیچ اقدامی نکنید، گزینه دوم به‌طور خودکار اعمال می‌شود.", + "p3": "با دریافت بازگشت وجه، اشتراک شما پایان می‌یابد و مدت توقف به آن اضافه نمی‌شود.", + "p4": "اگر اشتراک شما در دوره توقف به پایان برسد، حق درخواست بازگشت وجه مدت استفاده‌نشده برای شما محفوظ می‌ماند." + }, + "s4": { + "title": "4. تغییر قیمت", + "p1": "قیمتی که هنگام خرید پرداخت کرده‌اید تا پایان دوره اشتراک شما ثابت می‌ماند. تغییر قیمت توسط تحلیلگر روی اشتراک فعلی شما تأثیری ندارد.", + "p2": "در زمان تمدید، قیمت جاری آن کانال اعمال می‌شود و پیش از پرداخت به شما نمایش داده خواهد شد." + }, + "s5": { + "title": "5. تخفیف‌ها", + "p1": "تخفیف‌های دوره‌ای هنگام خرید اشتراک جدید، تمدید اشتراک فعلی، و خرید مجدد پس از پایان دوره قابل استفاده هستند.", + "p2": "تخفیف روی اشتراکی که پیش‌تر خریداری کرده‌اید اعمال نمی‌شود، اما می‌توانید در زمان تمدید یا خرید مجدد از آن بهره‌مند شوید.", + "p3": "پایان یافتن یک تخفیف روی اشتراکی که با قیمت تخفیف‌خورده خریداری شده تأثیری ندارد؛ شما تا پایان دوره از همان قیمت بهره‌مند می‌شوید." + }, + "s6": { + "title": "6. محتوا و مسئولیت", + "p1": "محتوای منتشرشده در کانال‌ها، شامل تحلیل‌ها، پیش‌بینی‌ها و دیدگاه‌ها، توسط تحلیلگران تولید می‌شود و مسئولیت آن به‌عهده خود آن‌هاست.", + "p2": "لومینا بستری برای انتشار و اعتبارسنجی عملکرد تحلیلگران فراهم می‌کند و هیچ‌یک از محتوای منتشرشده را تأیید، تضمین یا به‌عنوان توصیه سرمایه‌گذاری ارائه نمی‌دهد.", + "p3": "تصمیمات سرمایه‌گذاری شما بر عهده خودتان است." + }, + "s7": { + "title": "7. مشکلات پرداخت", + "p1": "اگر مبلغی از حساب شما کسر شده اما پرداخت ناموفق اعلام شده است، این مبلغ حداکثر ظرف 72 ساعت به‌طور خودکار توسط بانک به حساب شما بازمی‌گردد.", + "p2": "اگر پرداخت موفق بوده اما اشتراک شما فعال نشده است، شماره پیگیری را از بخش تراکنش‌ها برای پشتیبانی ارسال کنید تا دسترسی شما فعال شود." + }, + "s8": { + "title": "8. ارتباط با پشتیبانی", + "p1": "برای هرگونه پرسش یا مشکل، از طریق پیام‌رسان بله یا تلگرام با پشتیبانی لومینا در ارتباط باشید.", + "hours": "زمان پاسخگویی: {{hours}}" + } +} diff --git a/platforms/market/src/shared/locales/resources.ts b/platforms/market/src/shared/locales/resources.ts index 2b02283..6279e2b 100644 --- a/platforms/market/src/shared/locales/resources.ts +++ b/platforms/market/src/shared/locales/resources.ts @@ -5,6 +5,8 @@ import faContent from './fa/content.json'; import faDashboard from './fa/dashboard.json'; import faErrors from './fa/errors.json'; import faHome from './fa/home.json'; +import faNotifications from './fa/notifications.json'; +import faPayment from './fa/payment.json'; /** * The product is Persian only; every route loads every namespace here, because any route can fail. @@ -23,6 +25,8 @@ export const resources = { channel: faChannel, home: faHome, dashboard: faDashboard, + payment: faPayment, + notifications: faNotifications, }, } as const; diff --git a/platforms/market/src/shared/locales/server-resources.ts b/platforms/market/src/shared/locales/server-resources.ts index d00b5ad..9348453 100644 --- a/platforms/market/src/shared/locales/server-resources.ts +++ b/platforms/market/src/shared/locales/server-resources.ts @@ -1,13 +1,16 @@ import 'server-only'; import faLanding from './fa/landing.json'; +import faTerms from './fa/terms.json'; /** - * Namespaces that only server components read: the prerendered landing. They stay out of every - * client bundle; each app's server bootstrap adds them to its i18n instance. + * Namespaces that only server components read: the prerendered landing and the subscription + * terms. They stay out of every client bundle; each app's server bootstrap adds them to its i18n + * instance. */ export const SERVER_RESOURCES = { fa: { landing: faLanding, + terms: faTerms, }, } as const; diff --git a/platforms/market/src/shared/utils/copy-with-toast.ts b/platforms/market/src/shared/utils/copy-with-toast.ts new file mode 100644 index 0000000..3c99c07 --- /dev/null +++ b/platforms/market/src/shared/utils/copy-with-toast.ts @@ -0,0 +1,25 @@ +import { showToast } from '@lumina/island/molecules/toast'; + +export type CopyWithToastMessages = { + copied: string; + failed: string; + /** What to do instead, such as selecting the text by hand. */ + failedDescription: string; +}; + +/** Copies text such as a bank reference, and says how it went with a toast. */ +export function copyWithToast( + text: string, + { copied, failed, failedDescription }: CopyWithToastMessages, +): void { + navigator.clipboard + .writeText(text) + .then(() => showToast({ tone: 'success', message: copied })) + .catch(() => + showToast({ + tone: 'error', + message: failed, + description: failedDescription, + }), + ); +} diff --git a/platforms/market/src/shared/utils/index.ts b/platforms/market/src/shared/utils/index.ts index b279348..f4517aa 100644 --- a/platforms/market/src/shared/utils/index.ts +++ b/platforms/market/src/shared/utils/index.ts @@ -1,7 +1,10 @@ export { applyServerErrors } from './apply-server-errors'; export { toApiUrl } from './api-url'; export { toChannelUsername } from './channel-username'; +export { copyWithToast } from './copy-with-toast'; +export type { CopyWithToastMessages } from './copy-with-toast'; export { firstOfEach } from './first-of-each'; +export { isConnectionError } from './is-connection-error'; export { loadMoreErrorKind } from './load-more-error-kind'; export type { LoadMoreErrorKind } from './load-more-error-kind'; export { toggleMarket } from './markets'; diff --git a/platforms/market/src/shared/utils/is-connection-error.ts b/platforms/market/src/shared/utils/is-connection-error.ts new file mode 100644 index 0000000..84ffec0 --- /dev/null +++ b/platforms/market/src/shared/utils/is-connection-error.ts @@ -0,0 +1,9 @@ +import { isHttpError } from '@lumina/libs/http'; + +/** The request never got an answer: the connection dropped or our time limit passed. */ +export function isConnectionError(error: unknown): boolean { + return ( + isHttpError(error) && + (error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT') + ); +} diff --git a/platforms/market/src/shared/validations/index.ts b/platforms/market/src/shared/validations/index.ts index 0d156bd..da1e654 100644 --- a/platforms/market/src/shared/validations/index.ts +++ b/platforms/market/src/shared/validations/index.ts @@ -20,6 +20,7 @@ export { SOCIAL_PLATFORMS, USERNAME_LENGTH, } from './constants'; +export { checkoutSchema } from './payment-validations'; export { avatarImage, creatorProfileSchema, @@ -30,6 +31,8 @@ export { export type { AccountTypeFormOutput, AccountTypeFormValues, + CheckoutFormOutput, + CheckoutFormValues, ClosePredictionFormOutput, ClosePredictionFormValues, PostComposerFormValues, diff --git a/platforms/market/src/shared/validations/payment-validations.ts b/platforms/market/src/shared/validations/payment-validations.ts new file mode 100644 index 0000000..b6bb019 --- /dev/null +++ b/platforms/market/src/shared/validations/payment-validations.ts @@ -0,0 +1,13 @@ +import * as v from 'valibot'; + +import { requiredString } from './base-validations'; + +/** + * Checkout's two choices (U9 §۲). Both are required, but «پرداخت» stays frozen and says so until + * they are made (۴.۱), so these messages show only if a submit gets past it. Codes are checked + * case-insensitively by the server, so the code is only trimmed. + */ +export const checkoutSchema = v.object({ + tierId: requiredString('errors:checkout.tier-required'), + referralCode: requiredString('errors:checkout.code-required'), +}); diff --git a/platforms/market/src/shared/validations/types.ts b/platforms/market/src/shared/validations/types.ts index 0044ed8..b547e04 100644 --- a/platforms/market/src/shared/validations/types.ts +++ b/platforms/market/src/shared/validations/types.ts @@ -12,6 +12,7 @@ import type { closePredictionSchema, postComposerSchema, } from './content-validations'; +import type { checkoutSchema } from './payment-validations'; import type { creatorProfileSchema, investorProfileSchema, @@ -57,3 +58,5 @@ export type ClosePredictionFormOutput = v.InferOutput< typeof closePredictionSchema >; export type PostComposerFormValues = v.InferInput; +export type CheckoutFormValues = v.InferInput; +export type CheckoutFormOutput = v.InferOutput; diff --git a/platforms/market/src/stores/checkout-draft/checkout-draft-store.ts b/platforms/market/src/stores/checkout-draft/checkout-draft-store.ts new file mode 100644 index 0000000..64da086 --- /dev/null +++ b/platforms/market/src/stores/checkout-draft/checkout-draft-store.ts @@ -0,0 +1,60 @@ +import { storage } from '@lumina/libs/local-storage'; +import { create } from 'zustand'; +import { createJSONStorage, persist } from 'zustand/middleware'; +import { immer } from 'zustand/middleware/immer'; + +import type { CheckoutDraftState } from './types'; + +/** + * The last checkout's period and invite code, kept before the browser leaves for the bank, so + * «تلاش دوباره» on the result page and back from the gateway reopen checkout as it was (U10 ۶.۳, + * ۹.۲), with the payment that left, until the bank answers. One draft at a time, under `session.` + * so logout removes it. An invite code is the creator's shared invitation, not personal data. + * Rehydrated after mount by the AppShell, so the server render and the first browser render match. + * Which payment this page load sent and how its settling went stay in memory only. + */ +export const useCheckoutDraftStore = create()( + persist( + immer((set) => ({ + draft: null, + sentHere: null, + settlement: null, + keepDraft: (draft) => + set((state) => { + state.draft = draft; + state.sentHere = draft.paymentId; + }), + forgetPayment: () => + set((state) => { + if (state.draft) state.draft.paymentId = null; + }), + setSettlement: (settlement) => + set((state) => { + state.settlement = settlement; + }), + clearDraft: () => + set((state) => { + state.draft = null; + state.settlement = null; + }), + })), + { + name: 'session.checkout-draft', + storage: createJSONStorage(() => storage), + version: 2, + // Version 1 had no payment id. + migrate: (persisted) => { + const { draft } = (persisted ?? {}) as { + draft?: CheckoutDraftState['draft']; + }; + return { + draft: draft + ? { ...draft, paymentId: draft.paymentId ?? null } + : null, + }; + }, + partialize: (state) => ({ draft: state.draft }), + skipHydration: true, + }, + ), +); diff --git a/platforms/market/src/stores/checkout-draft/index.ts b/platforms/market/src/stores/checkout-draft/index.ts new file mode 100644 index 0000000..4ab2264 --- /dev/null +++ b/platforms/market/src/stores/checkout-draft/index.ts @@ -0,0 +1,6 @@ +export { useCheckoutDraftStore } from './checkout-draft-store'; +export type { + CheckoutDraft, + CheckoutDraftState, + PaymentSettlement, +} from './types'; diff --git a/platforms/market/src/stores/checkout-draft/types.ts b/platforms/market/src/stores/checkout-draft/types.ts new file mode 100644 index 0000000..30c9adc --- /dev/null +++ b/platforms/market/src/stores/checkout-draft/types.ts @@ -0,0 +1,41 @@ +import type { AbandonOutcome } from '../../features/checkout'; + +/** What the investor chose before leaving for the bank, and the payment they left with. */ +export type CheckoutDraft = { + /** The creator's account id. */ + creatorId: string; + tierId: string; + /** The invite code as typed; empty for a renewal or reactivation. */ + referralCode: string; + /** + * The payment handed to the bank. It stays until the browser comes back through the return + * page; still here on any other page means the investor came back without the bank's callback. + */ + paymentId: string | null; +}; + +/** + * This page load's settling of a payment left at the bank (U10 ۶.۳): `outcome` is `null` while the + * bank is asked. Kept in memory only. + */ +export type PaymentSettlement = { + paymentId: string; + /** The creator's account id. */ + creatorId: string; + outcome: AbandonOutcome | null; +}; + +export type CheckoutDraftState = { + draft: CheckoutDraft | null; + /** + * The payment this page load handed to the bank. A page restored from the back cache still has + * it, which is how it knows it is the one coming back. Kept in memory only. + */ + sentHere: string | null; + settlement: PaymentSettlement | null; + keepDraft: (draft: CheckoutDraft) => void; + /** The bank answered, or the payment was settled: the choice stays for a retry. */ + forgetPayment: () => void; + setSettlement: (settlement: PaymentSettlement | null) => void; + clearDraft: () => void; +};