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 <noreply@anthropic.com>
This commit is contained in:
parent
a668b17590
commit
49372bc77e
|
|
@ -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 (
|
||||
|
|
|
|||
|
|
@ -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 () => {
|
||||
|
|
|
|||
|
|
@ -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]);
|
||||
}
|
||||
|
|
@ -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() {
|
|||
<FlexBox alignItems="items-center" gap="gap-2" className="ms-auto">
|
||||
{isCreator && <PublishMenu placement="header" />}
|
||||
<SupportEntry trigger="icon" placement="popover" />
|
||||
{status === 'member' && <NotificationBell placement="panel" />}
|
||||
{status === 'unknown' && (
|
||||
// The account link's size, so the end doesn't move when the session arrives.
|
||||
<GridBox
|
||||
justifyItems="justify-items-center"
|
||||
alignItems="items-center"
|
||||
className="size-touch-target"
|
||||
>
|
||||
<Skeleton shape="circle" width="2rem" height="2rem" />
|
||||
</GridBox>
|
||||
// Most visitors are guests: their «ورود/ثبتنام» holds the end's place, unseen, so it
|
||||
// doesn't move when the session arrives.
|
||||
<Element tag="span" aria-hidden className="invisible flex-none">
|
||||
<Button variant="primary" tabIndex={-1}>
|
||||
{t('nav.login')}
|
||||
</Button>
|
||||
</Element>
|
||||
)}
|
||||
{status === 'guest' && (
|
||||
<Button variant="primary" href={loginRoute(pathname)}>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
'use client';
|
||||
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { BackButton } from '../mobile-top-bar/components/BackButton';
|
||||
import type { DesktopPageTitleProps } from './types';
|
||||
|
||||
/**
|
||||
* A pushed page's heading on desktop, at the top of its column: back, then the page's name (U9
|
||||
* ۹.۱, S5 ۲.۱). Back returns where the person came from, or home for a page opened on its own.
|
||||
*/
|
||||
export function DesktopPageTitle({ title, onBack }: DesktopPageTitleProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<FlexBox alignItems="items-center" gap="gap-1" className="-ms-2">
|
||||
<BackButton label={t('nav.back')} onBack={onBack} />
|
||||
<Typography tag="h1" variant="heading-md">
|
||||
{title}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { DesktopPageTitle } from './DesktopPageTitle';
|
||||
export type { DesktopPageTitleProps } from './types';
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
export type DesktopPageTitleProps = {
|
||||
/** The page's name: «خرید اشتراک». */
|
||||
title: string;
|
||||
/** Back asks first; without it back goes back. */
|
||||
onBack?: () => void;
|
||||
};
|
||||
|
|
@ -6,6 +6,8 @@ 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 { cn } from '@lumina/island/tools/cn';
|
||||
import NextLink from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
|
@ -15,6 +17,7 @@ import { SupportEntry } from '../../../screens/organisms/support-entry';
|
|||
import { useHomeHref } from '../../hooks/use-home-href';
|
||||
import { useIsOwnPreview } from '../../hooks/use-is-own-preview';
|
||||
import { loginRoute, ROUTES } from '../../navigation';
|
||||
import { NotificationBell } from '../notification-bell';
|
||||
import { BackButton } from './components/BackButton';
|
||||
import { Brand } from './components/Brand';
|
||||
import type { MobileTopBarProps } from './types';
|
||||
|
|
@ -25,15 +28,17 @@ import type { MobileTopBarProps } from './types';
|
|||
* main screen, and a creator on their own tab, get the tab bar: the brand, the tab's name centred
|
||||
* when it has one («داشبورد»; خانه has none), support and the member's account (Main A, U8 ۴.۱).
|
||||
* Who is looking is known only in the browser, so the server and the first browser render show a
|
||||
* tab's bar with its brand and name and a placeholder where the account goes, and a pushed page's
|
||||
* bar without its start. A creator's brand goes to their own channel, their home tab, and a
|
||||
* guest's to the landing.
|
||||
* tab's bar with its brand and name, and a pushed page's bar without its start; both hold the
|
||||
* guest's «ورود/ثبتنام» unseen at the end, since most visitors are guests. A creator's brand goes to their own channel, their home tab, and a
|
||||
* guest's to the landing. A pushed page with nothing behind it drops back (`back={false}`). The tab
|
||||
* bar carries the bell between support and the account (U5 ۲.۲); a pushed bar has neither.
|
||||
*/
|
||||
export function MobileTopBar({
|
||||
title,
|
||||
isTab = false,
|
||||
tabOwnerId,
|
||||
onBack,
|
||||
back = true,
|
||||
previewTitle,
|
||||
}: MobileTopBarProps) {
|
||||
const { t } = useTranslation();
|
||||
|
|
@ -75,30 +80,31 @@ export function MobileTopBar({
|
|||
)}
|
||||
{status === 'member' && !isTabBar && (
|
||||
<>
|
||||
<BackButton label={t('nav.back')} onBack={onBack} />
|
||||
{back && <BackButton label={t('nav.back')} onBack={onBack} />}
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="heading-sm"
|
||||
className="flex-1 truncate"
|
||||
className={cn('flex-1 truncate', !back && 'ps-2')}
|
||||
>
|
||||
{isPreview && previewTitle ? previewTitle : title}
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
<SupportEntry trigger="icon" placement="bottom" />
|
||||
{status === 'member' && isTabBar && <NotificationBell placement="link" />}
|
||||
{status === 'guest' && (
|
||||
<Button variant="ghost" size="sm" href={loginRoute(pathname)}>
|
||||
{t('nav.login')}
|
||||
</Button>
|
||||
)}
|
||||
{status === 'unknown' && isTabBar && (
|
||||
<GridBox
|
||||
justifyItems="justify-items-center"
|
||||
alignItems="items-center"
|
||||
className="size-touch-target"
|
||||
>
|
||||
<Skeleton shape="circle" width="2rem" height="2rem" />
|
||||
</GridBox>
|
||||
{status === 'unknown' && (
|
||||
// Most visitors are guests: their «ورود/ثبتنام» holds the end's place, unseen, so the bar
|
||||
// doesn't move when the session arrives.
|
||||
<Element tag="span" aria-hidden className="invisible flex-none">
|
||||
<Button variant="ghost" size="sm" tabIndex={-1}>
|
||||
{t('nav.login')}
|
||||
</Button>
|
||||
</Element>
|
||||
)}
|
||||
{status === 'member' && isTabBar && account && (
|
||||
<GridBox
|
||||
|
|
|
|||
|
|
@ -10,6 +10,11 @@ type PushedBarProps = {
|
|||
tabOwnerId?: string;
|
||||
/** Back asks first (a composer with unsaved text); without it back goes back. */
|
||||
onBack?: () => 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;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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<string | null>(null);
|
||||
const [hasOpened, setHasOpened] = useState(false);
|
||||
const isOpen = openedOn === pathname;
|
||||
const label = count > 0 ? t('bell-unread', { count }) : t('bell');
|
||||
|
||||
const badge = (
|
||||
<CountBadge
|
||||
count={count}
|
||||
cap={UNREAD_BADGE_CAP}
|
||||
className="pointer-events-none absolute end-1 top-1"
|
||||
/>
|
||||
);
|
||||
|
||||
if (placement === 'link') {
|
||||
return (
|
||||
<FlexBox className="relative">
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon="bell"
|
||||
label={label}
|
||||
href={ROUTES.notifications}
|
||||
/>
|
||||
{badge}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<FlexBox className="relative">
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon="bell"
|
||||
label={label}
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={isOpen}
|
||||
onClick={() => {
|
||||
setHasOpened(true);
|
||||
setOpenedOn(pathname);
|
||||
}}
|
||||
/>
|
||||
{badge}
|
||||
{hasOpened && (
|
||||
<NotificationPanel open={isOpen} onClose={() => setOpenedOn(null)} />
|
||||
)}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { NotificationBell } from './NotificationBell';
|
||||
export type { NotificationBellProps } from './types';
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
export type NotificationBellProps = {
|
||||
/** link: mobile, to the centre's page. panel: desktop, opens the centre as a side panel. */
|
||||
placement: 'link' | 'panel';
|
||||
};
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
export { BottomNav } from './components/bottom-nav';
|
||||
export { DesktopHeader } from './components/desktop-header';
|
||||
export { DesktopPageTitle } from './components/desktop-page-title';
|
||||
export { MobileTopBar } from './components/mobile-top-bar';
|
||||
export type { DesktopPageTitleProps } from './components/desktop-page-title';
|
||||
export type { MobileTopBarProps } from './components/mobile-top-bar';
|
||||
export { CHANNEL_PREFIX, PREVIEW_PARAM, ROLE_PARAM } from './constants';
|
||||
export { useAuthRoutes } from './hooks/use-auth-routes';
|
||||
|
|
|
|||
|
|
@ -26,7 +26,13 @@ export const ROUTES = {
|
|||
`${channel(username)}/posts/${encodeURIComponent(id)}`,
|
||||
trackRecord: (username: string) => `${channel(username)}/track-record`,
|
||||
checkout: (username: string) => `/checkout/${encodeURIComponent(username)}`,
|
||||
/** Where the API's bank callback sends the browser (its `CHECKOUT_*_URL`s), with `?paymentId=`. */
|
||||
paymentReturn: '/payment/return',
|
||||
/** The end of every payment (U10 §۹): success, failed or in review. */
|
||||
paymentResult: (paymentId: string) =>
|
||||
`/payment/result/${encodeURIComponent(paymentId)}`,
|
||||
/** The notification centre on mobile; desktop opens it as a panel from the header's bell. */
|
||||
notifications: '/notifications',
|
||||
composePost: '/compose/post',
|
||||
/** The composer on a published post of the creator's own, for its first 15 minutes. */
|
||||
editPost: (id: string) => `/compose/post/${encodeURIComponent(id)}`,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,49 @@
|
|||
import { Avatar } from '@lumina/island/atoms/avatar';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
|
||||
import type { CheckoutCreatorProps } from './types';
|
||||
|
||||
/**
|
||||
* Who is being paid, checkout's first block (U9 §۲): the avatar, the name with the verified mark
|
||||
* and the @username. The same for every visitor, so it renders on the server. Every creator with
|
||||
* a checkout is approved, so every one is verified.
|
||||
*/
|
||||
export function CheckoutCreator({ creator, labels }: CheckoutCreatorProps) {
|
||||
const handle = (
|
||||
<Element tag="bdi" dir="ltr">
|
||||
@{creator.username}
|
||||
</Element>
|
||||
);
|
||||
|
||||
return (
|
||||
<FlexBox alignItems="items-center" gap="gap-3">
|
||||
<Avatar name={creator.username} src={creator.avatarUrl} />
|
||||
<FlexBox direction="flex-col" className="min-w-0 flex-1">
|
||||
<FlexBox alignItems="items-center" className="gap-1.5">
|
||||
<Typography tag="span" variant="heading-sm" className="truncate">
|
||||
{creator.displayName ?? handle}
|
||||
</Typography>
|
||||
<Icon
|
||||
name="check-circle"
|
||||
size={20}
|
||||
label={labels.verified}
|
||||
className="flex-none text-action-primary-text"
|
||||
/>
|
||||
</FlexBox>
|
||||
{creator.displayName && (
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="caption"
|
||||
color="secondary"
|
||||
className="truncate"
|
||||
>
|
||||
{handle}
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Skeleton } from '@lumina/island/atoms/skeleton';
|
||||
|
||||
/** The creator row before the page knows who it is, at the row's size. */
|
||||
export function CheckoutCreatorSkeleton() {
|
||||
return (
|
||||
<FlexBox alignItems="items-center" gap="gap-3">
|
||||
<Skeleton shape="circle" width="2.5rem" height="2.5rem" />
|
||||
<FlexBox direction="flex-col" gap="gap-2" className="flex-1">
|
||||
<Skeleton width="8rem" height="1rem" />
|
||||
<Skeleton width="6rem" />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export { CheckoutCreator } from './CheckoutCreator';
|
||||
export { CheckoutCreatorSkeleton } from './CheckoutCreatorSkeleton';
|
||||
export type { CheckoutCreatorLabels, CheckoutCreatorProps } from './types';
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import type { PublicCreatorPayload } from '../../../../../../../features/channel';
|
||||
|
||||
export type CheckoutCreatorLabels = {
|
||||
/** The verified mark's accessible name, «تأییدشده». */
|
||||
verified: string;
|
||||
};
|
||||
|
||||
export type CheckoutCreatorProps = {
|
||||
creator: Pick<PublicCreatorPayload, 'username' | 'displayName' | 'avatarUrl'>;
|
||||
labels: CheckoutCreatorLabels;
|
||||
};
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
'use client';
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { AuthGuard } from '../../../../../../guards/auth-guard';
|
||||
import { CheckoutForm } from './components/CheckoutForm';
|
||||
import { CheckoutSkeleton } from './CheckoutSkeleton';
|
||||
import type { CheckoutPanelProps } from './types';
|
||||
|
||||
/**
|
||||
* Checkout below the page's bar (U9). The creator row comes from the server; the rest is the
|
||||
* investor's own (their standing, the code, the payment), so it renders in the browser behind a
|
||||
* same-size skeleton. A guest goes to login and comes back here; a creator gets no access.
|
||||
*/
|
||||
export function CheckoutPanel(props: CheckoutPanelProps) {
|
||||
const { t } = useTranslation('payment');
|
||||
|
||||
return (
|
||||
<AuthGuard
|
||||
role="investor"
|
||||
fallback={
|
||||
<CheckoutSkeleton
|
||||
layout={props.layout}
|
||||
creator={props.creator}
|
||||
label={t('checkout.loading')}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<CheckoutForm {...props} />
|
||||
</AuthGuard>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
|
||||
import { CheckoutFrame } from './components/CheckoutFrame';
|
||||
import type { CheckoutSkeletonProps } from './types';
|
||||
|
||||
const TIER_ROWS = ['monthly', 'quarterly', 'semi-annual', 'yearly'];
|
||||
|
||||
/**
|
||||
* Checkout before the investor's screen arrives, block for block: the server-rendered creator row
|
||||
* stays, the note, four tier cards, the code field and the pay block keep their sizes.
|
||||
*/
|
||||
export function CheckoutSkeleton({
|
||||
layout,
|
||||
creator,
|
||||
label,
|
||||
}: CheckoutSkeletonProps) {
|
||||
const padding = layout === 'desktop' ? 'lg' : 'md';
|
||||
|
||||
return (
|
||||
<SkeletonRegion label={label} className="flex flex-1 flex-col">
|
||||
<CheckoutFrame
|
||||
layout={layout}
|
||||
creator={creator}
|
||||
body={
|
||||
<>
|
||||
<Skeleton lines={2} height="0.875rem" />
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<Skeleton width="7rem" height="1.25rem" />
|
||||
{TIER_ROWS.map((row) => (
|
||||
<Card key={row} padding={padding}>
|
||||
<FlexBox alignItems="items-center" gap="gap-3">
|
||||
<Skeleton shape="circle" width="1.25rem" height="1.25rem" />
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
gap="gap-2"
|
||||
className="flex-1"
|
||||
>
|
||||
<Skeleton width="40%" height="1rem" />
|
||||
<Skeleton width="55%" />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
</Card>
|
||||
))}
|
||||
</FlexBox>
|
||||
<FlexBox direction="flex-col" gap="gap-2">
|
||||
<Skeleton width="4rem" />
|
||||
<Skeleton shape="rect" width="100%" height="3rem" />
|
||||
</FlexBox>
|
||||
</>
|
||||
}
|
||||
footer={
|
||||
<>
|
||||
<FlexBox justifyContent="justify-between">
|
||||
<Skeleton width="6rem" height="1rem" />
|
||||
<Skeleton width="5rem" height="1.25rem" />
|
||||
</FlexBox>
|
||||
<Skeleton width="60%" className="self-center" />
|
||||
<Skeleton shape="pill" width="100%" height="3.25rem" />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import { Controller } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { translateMessage } from '../../../../../../../../shared/utils';
|
||||
import type { CheckoutPartProps } from '../types';
|
||||
|
||||
/**
|
||||
* «کد دعوت», left to right. Leaving the field checks the code quietly: valid in green, invalid in
|
||||
* red with the code kept, and nothing at all when the check can't reach the server (U9 ۴.۲–۴.۴).
|
||||
* The message only reassures or warns; «پرداخت» decides. Any edit drops it.
|
||||
*/
|
||||
export function CheckoutCode({ model }: Pick<CheckoutPartProps, 'model'>) {
|
||||
const { t } = useTranslation(['payment', 'errors']);
|
||||
|
||||
return (
|
||||
<Controller
|
||||
name="referralCode"
|
||||
control={model.form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
onChange={(event) => {
|
||||
field.onChange(event);
|
||||
model.codeEdited();
|
||||
}}
|
||||
onBlur={() => {
|
||||
field.onBlur();
|
||||
model.checkCode();
|
||||
}}
|
||||
dir="ltr"
|
||||
autoComplete="off"
|
||||
autoCapitalize="characters"
|
||||
spellCheck={false}
|
||||
enterKeyHint="go"
|
||||
label={t('checkout.code.label')}
|
||||
placeholder={t('checkout.code.placeholder')}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
success={
|
||||
model.codeCheck === 'valid' && !fieldState.error
|
||||
? t('checkout.code.valid')
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
import { Amount } from '@lumina/island/atoms/amount';
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Link } from '@lumina/island/atoms/link';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { ROUTES } from '../../../../../../../navigation/navigation';
|
||||
import type { CheckoutPartProps } from '../types';
|
||||
|
||||
/**
|
||||
* The pay block: «مبلغ قابل پرداخت» with the chosen period's total (a dash until one is chosen),
|
||||
* the terms line with no checkbox (S4), and «پرداخت». Frozen until a period and a code are there,
|
||||
* and a tap on it names both (U9 ۴.۱). Paying shows the spinner and «در حال انتقال به درگاه…»;
|
||||
* after a tap that never reached the server it offers «تلاش دوباره» (۵.۳).
|
||||
*/
|
||||
export function CheckoutFooter({ model }: Pick<CheckoutPartProps, 'model'>) {
|
||||
const { t } = useTranslation('payment');
|
||||
const { selectedTier, canPay, phase, isOffline } = model;
|
||||
const isBusy = phase === 'paying' || phase === 'leaving';
|
||||
const label = isBusy
|
||||
? t('checkout.paying')
|
||||
: isOffline
|
||||
? t('checkout.retry')
|
||||
: t('checkout.pay');
|
||||
|
||||
return (
|
||||
<>
|
||||
<FlexBox
|
||||
alignItems="items-baseline"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
>
|
||||
<Typography tag="span" color="secondary">
|
||||
{t('checkout.total')}
|
||||
</Typography>
|
||||
{selectedTier?.priceToman != null ? (
|
||||
<Amount
|
||||
value={selectedTier.priceToman}
|
||||
size="title"
|
||||
currency={t('tier.currency')}
|
||||
/>
|
||||
) : (
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="heading-sm"
|
||||
color="tertiary"
|
||||
aria-label={t('checkout.no-total')}
|
||||
>
|
||||
—
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
<Typography variant="caption" color="secondary" className="text-center">
|
||||
{t('checkout.terms-before')}
|
||||
<Link href={ROUTES.terms}>{t('checkout.terms-link')}</Link>
|
||||
{t('checkout.terms-after')}
|
||||
</Typography>
|
||||
{canPay ? (
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
block
|
||||
isLoading={isBusy}
|
||||
disabled={phase === 'joining'}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="lg"
|
||||
block
|
||||
frozen
|
||||
frozenReason={
|
||||
model.mode === 'reactivate'
|
||||
? t('checkout.frozen-reactivate')
|
||||
: t('checkout.frozen')
|
||||
}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<CheckoutSkeleton
|
||||
layout={layout}
|
||||
creator={creator}
|
||||
label={t(SKELETON_LABELS[model.status])}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<CheckoutFrame
|
||||
layout={layout}
|
||||
creator={creator}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
model.pay();
|
||||
}}
|
||||
banner={
|
||||
model.isOffline && (
|
||||
<Banner tone="danger" title={t('checkout.offline')} />
|
||||
)
|
||||
}
|
||||
body={
|
||||
model.mode === 'reactivate' ? (
|
||||
<>
|
||||
<Banner tone="info" icon="clock">
|
||||
{t('checkout.reactivation-note')}
|
||||
</Banner>
|
||||
<CheckoutTiers model={model} layout={layout} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Typography color="secondary">
|
||||
{t('checkout.invite-note')}
|
||||
</Typography>
|
||||
<CheckoutTiers model={model} layout={layout} />
|
||||
<CheckoutCode model={model} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
footer={<CheckoutFooter model={model} />}
|
||||
/>
|
||||
<CheckoutHalts model={model} layout={layout} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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}
|
||||
<Element tag="hr" className="m-0 border-border-subtle" />
|
||||
{body}
|
||||
</>
|
||||
);
|
||||
|
||||
if (layout === 'mobile') {
|
||||
return (
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
onSubmit={onSubmit}
|
||||
direction="flex-col"
|
||||
className="flex-1"
|
||||
>
|
||||
<FlexBox direction="flex-col" gap="gap-4" className="flex-1 p-4">
|
||||
{top}
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
tag="footer"
|
||||
direction="flex-col"
|
||||
gap="gap-2"
|
||||
className="sticky bottom-0 z-sticky border-t border-border-subtle bg-surface px-4 pt-3 pb-4"
|
||||
>
|
||||
{footer}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
onSubmit={onSubmit}
|
||||
direction="flex-col"
|
||||
gap="gap-4"
|
||||
>
|
||||
<Card tag={FlexBox} direction="flex-col" gap="gap-5" padding="lg">
|
||||
{top}
|
||||
</Card>
|
||||
<Card
|
||||
tag={FlexBox}
|
||||
direction="flex-col"
|
||||
gap="gap-2"
|
||||
padding="none"
|
||||
className="sticky bottom-6 z-sticky px-6 py-5 shadow-2"
|
||||
>
|
||||
{footer}
|
||||
</Card>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<>
|
||||
<HaltDialog
|
||||
layout={layout}
|
||||
open={priceChange !== null}
|
||||
alert
|
||||
title={t('checkout.price-changed.title')}
|
||||
buttons={
|
||||
<>
|
||||
<Button
|
||||
variant="primary"
|
||||
size={size}
|
||||
block
|
||||
onClick={model.confirmPriceChange}
|
||||
>
|
||||
{t('checkout.price-changed.confirm')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size={size}
|
||||
block
|
||||
onClick={model.cancelPriceChange}
|
||||
>
|
||||
{t('checkout.price-changed.cancel')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{priceChange && (
|
||||
<FlexBox direction="flex-col" gap="gap-4">
|
||||
<Typography>
|
||||
{t('checkout.price-changed.from')}{' '}
|
||||
<Amount value={priceChange.oldAmountToman} currency={currency} />{' '}
|
||||
{t('checkout.price-changed.to')}{' '}
|
||||
<Amount value={priceChange.newAmountToman} currency={currency} />{' '}
|
||||
{t('checkout.price-changed.changed')}
|
||||
</Typography>
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
className="rounded-md bg-surface-sunken px-4 py-3"
|
||||
>
|
||||
<Typography tag="span" className="font-semibold">
|
||||
{t('checkout.price-changed.total')}
|
||||
</Typography>
|
||||
<Amount
|
||||
value={priceChange.newAmountToman}
|
||||
size="title"
|
||||
currency={currency}
|
||||
/>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
)}
|
||||
</HaltDialog>
|
||||
|
||||
<HaltDialog
|
||||
layout={layout}
|
||||
open={halt?.kind === 'unavailable'}
|
||||
alert
|
||||
icon={<StateArt icon="ban" tone="warning" size="compact" />}
|
||||
title={t('checkout.unavailable.title')}
|
||||
buttons={
|
||||
<Button variant="primary" size={size} block href={ROUTES.home}>
|
||||
{t('checkout.unavailable.home')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<HaltDialog
|
||||
layout={layout}
|
||||
open={halt?.kind === 'waitlist-offer'}
|
||||
title={t('checkout.waitlist.title')}
|
||||
buttons={
|
||||
<>
|
||||
<Button
|
||||
variant="primary"
|
||||
size={size}
|
||||
block
|
||||
isLoading={phase === 'joining'}
|
||||
onClick={model.joinWaitlist}
|
||||
>
|
||||
{t('checkout.waitlist.join')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size={size}
|
||||
block
|
||||
disabled={phase === 'joining'}
|
||||
onClick={model.leaveToChannel}
|
||||
>
|
||||
{t('checkout.waitlist.decline')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Typography color="secondary">{t('checkout.waitlist.body')}</Typography>
|
||||
</HaltDialog>
|
||||
|
||||
<HaltDialog
|
||||
layout={layout}
|
||||
open={halt?.kind === 'waitlisted'}
|
||||
icon={<StateArt icon="clock" tone="brand" size="compact" />}
|
||||
title={t('checkout.waitlist.title')}
|
||||
buttons={
|
||||
<Button
|
||||
variant="primary"
|
||||
size={size}
|
||||
block
|
||||
onClick={model.leaveToChannel}
|
||||
>
|
||||
{t('checkout.waitlist.back')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Typography color="secondary">
|
||||
{t('checkout.waitlist.already')}
|
||||
</Typography>
|
||||
</HaltDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<FlexBox
|
||||
tag="section"
|
||||
aria-labelledby={headingId}
|
||||
direction="flex-col"
|
||||
gap="gap-3"
|
||||
>
|
||||
<Typography tag="h2" id={headingId} variant="heading-sm">
|
||||
{t('checkout.tiers')}
|
||||
</Typography>
|
||||
<Controller
|
||||
name="tierId"
|
||||
control={model.form.control}
|
||||
render={({ field }) => (
|
||||
<FlexBox
|
||||
role="radiogroup"
|
||||
aria-labelledby={headingId}
|
||||
direction="flex-col"
|
||||
gap="gap-3"
|
||||
>
|
||||
{model.tiers.map((tier) => {
|
||||
const { promotion } = tier;
|
||||
const isPromotion =
|
||||
promotion !== null &&
|
||||
tier.standingPriceToman !== null &&
|
||||
tier.priceToman !== null &&
|
||||
tier.standingPriceToman > tier.priceToman;
|
||||
return (
|
||||
<TierOption
|
||||
key={tier.id}
|
||||
name={field.name}
|
||||
value={tier.id}
|
||||
label={tCommon(`billing-periods.${tier.billingPeriod}`)}
|
||||
months={BILLING_PERIOD_MONTHS[tier.billingPeriod]}
|
||||
total={tier.priceToman ?? 0}
|
||||
monthlyPrice={model.monthlyPrice}
|
||||
standing={
|
||||
isPromotion
|
||||
? (tier.standingPriceToman ?? undefined)
|
||||
: undefined
|
||||
}
|
||||
selected={field.value === tier.id}
|
||||
onSelect={field.onChange}
|
||||
padding={layout === 'desktop' ? 'lg' : 'md'}
|
||||
labels={labels}
|
||||
>
|
||||
{isPromotion && promotion.endsAt && !promotion.indefinite && (
|
||||
<Countdown
|
||||
kind="promotion"
|
||||
endsAt={promotion.endsAt}
|
||||
labels={countdownLabels}
|
||||
/>
|
||||
)}
|
||||
</TierOption>
|
||||
);
|
||||
})}
|
||||
</FlexBox>
|
||||
)}
|
||||
/>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -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' ? (
|
||||
<Sheet
|
||||
open={open}
|
||||
title={title}
|
||||
icon={icon}
|
||||
dismissible={false}
|
||||
alert={alert}
|
||||
footer={buttons}
|
||||
>
|
||||
{children}
|
||||
</Sheet>
|
||||
) : (
|
||||
<Modal
|
||||
open={open}
|
||||
title={title}
|
||||
icon={icon}
|
||||
dismissible={false}
|
||||
alert={alert}
|
||||
actions={buttons}
|
||||
>
|
||||
{children}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export { CheckoutPanel } from './CheckoutPanel';
|
||||
export { CheckoutSkeleton } from './CheckoutSkeleton';
|
||||
export type {
|
||||
CheckoutLayout,
|
||||
CheckoutPanelProps,
|
||||
CheckoutSkeletonProps,
|
||||
} from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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 (
|
||||
<PaymentResultSkeleton layout={layout} label={t('result.loading')} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ResultFrame
|
||||
layout={layout}
|
||||
body={
|
||||
<>
|
||||
<ResultHead kind={kind} />
|
||||
<ResultReceipt
|
||||
kind={kind}
|
||||
payment={payment}
|
||||
onCopyReference={copyReference}
|
||||
/>
|
||||
<FlexBox direction="flex-col" alignItems="items-center" gap="gap-1">
|
||||
<Typography
|
||||
variant="body-sm"
|
||||
color="secondary"
|
||||
className="text-center"
|
||||
>
|
||||
{t(`result.${kind}.note`)}
|
||||
</Typography>
|
||||
{kind !== 'success' && (
|
||||
<SupportEntry
|
||||
trigger="link"
|
||||
placement={layout === 'mobile' ? 'bottom' : 'popover'}
|
||||
/>
|
||||
)}
|
||||
</FlexBox>
|
||||
</>
|
||||
}
|
||||
actions={<ResultActions kind={kind} payment={payment} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<SkeletonRegion label={label} className="flex flex-1 flex-col">
|
||||
<ResultFrame
|
||||
layout={layout}
|
||||
body={
|
||||
<>
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
alignItems="items-center"
|
||||
gap="gap-3"
|
||||
className="pt-2"
|
||||
>
|
||||
<Skeleton shape="circle" width="4.75rem" height="4.75rem" />
|
||||
<Skeleton width="10rem" height="1.25rem" />
|
||||
<Skeleton width="8rem" />
|
||||
</FlexBox>
|
||||
<Card>
|
||||
<FlexBox alignItems="items-center" gap="gap-3">
|
||||
<Skeleton shape="circle" width="2.5rem" height="2.5rem" />
|
||||
<Skeleton width="7rem" height="1rem" className="flex-1" />
|
||||
<Skeleton shape="pill" width="3.5rem" height="1.5rem" />
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
gap="gap-4"
|
||||
className="mt-3 border-t border-border-subtle pt-4"
|
||||
>
|
||||
{RECEIPT_ROWS.map((row) => (
|
||||
<FlexBox key={row} justifyContent="justify-between">
|
||||
<Skeleton width="4rem" />
|
||||
<Skeleton width="6rem" />
|
||||
</FlexBox>
|
||||
))}
|
||||
</FlexBox>
|
||||
</Card>
|
||||
</>
|
||||
}
|
||||
actions={
|
||||
<>
|
||||
<Skeleton shape="pill" width="100%" height="3.25rem" />
|
||||
<Skeleton shape="pill" width="100%" height="3.25rem" />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 ? (
|
||||
<Button
|
||||
variant={kind === 'failed' ? 'secondary' : 'primary'}
|
||||
size="lg"
|
||||
block
|
||||
href={ROUTES.channel(username)}
|
||||
>
|
||||
{t(`result.${kind}.channel`, { name })}
|
||||
</Button>
|
||||
) : null;
|
||||
|
||||
if (kind === 'failed') {
|
||||
return (
|
||||
<>
|
||||
{payment.type === 'renew' ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="lg"
|
||||
block
|
||||
href={ROUTES.dashboard.subscriptions}
|
||||
>
|
||||
{t('result.failed.retry')}
|
||||
</Button>
|
||||
) : username ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="lg"
|
||||
block
|
||||
href={ROUTES.checkout(username)}
|
||||
>
|
||||
{t('result.failed.retry')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="lg"
|
||||
block
|
||||
href={ROUTES.dashboard.transactions}
|
||||
>
|
||||
{t('result.failed.transactions')}
|
||||
</Button>
|
||||
)}
|
||||
{channel}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{channel}
|
||||
<Button
|
||||
variant={channel ? 'secondary' : 'primary'}
|
||||
size="lg"
|
||||
block
|
||||
href={
|
||||
kind === 'success'
|
||||
? ROUTES.dashboard.subscriptions
|
||||
: ROUTES.dashboard.transactions
|
||||
}
|
||||
>
|
||||
{kind === 'success'
|
||||
? t('result.success.subscriptions')
|
||||
: t('result.pending.transactions')}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<FlexBox direction="flex-col" className="flex-1 bg-surface">
|
||||
<FlexBox direction="flex-col" gap="gap-5" className="flex-1 p-4">
|
||||
{body}
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
gap="gap-2"
|
||||
className="sticky bottom-0 z-sticky border-t border-border-subtle bg-surface px-4 pt-3 pb-4"
|
||||
>
|
||||
{actions}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
tag={FlexBox}
|
||||
direction="flex-col"
|
||||
gap="gap-5"
|
||||
padding="none"
|
||||
className="px-7 py-8"
|
||||
>
|
||||
{body}
|
||||
<FlexBox direction="flex-col" gap="gap-2">
|
||||
{actions}
|
||||
</FlexBox>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<PaymentResultKind, { icon: IconName; tone: StateTone }> = {
|
||||
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 (
|
||||
<FlexBox
|
||||
tag="output"
|
||||
direction="flex-col"
|
||||
alignItems="items-center"
|
||||
gap="gap-2"
|
||||
className="pt-2 text-center"
|
||||
>
|
||||
<StateArt {...ART[kind]} size="compact" />
|
||||
<Typography tag="h2" variant="heading-md" className="mt-1">
|
||||
{t(`result.${kind}.title`)}
|
||||
</Typography>
|
||||
<Typography color="secondary">
|
||||
{t(`result.${kind}.description`)}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<Card tag="section" aria-label={t('result.receipt')}>
|
||||
<FlexBox alignItems="items-center" gap="gap-3">
|
||||
<Avatar name={creator.username ?? '?'} src={creator.avatarUrl} />
|
||||
<FlexBox direction="flex-col" className="min-w-0 flex-1">
|
||||
<Typography tag="span" className="truncate font-semibold">
|
||||
{creator.displayName ??
|
||||
(creator.username && (
|
||||
<Element tag="bdi" dir="ltr">
|
||||
@{creator.username}
|
||||
</Element>
|
||||
))}
|
||||
</Typography>
|
||||
{creator.displayName && creator.username && (
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="caption"
|
||||
color="secondary"
|
||||
className="truncate"
|
||||
>
|
||||
<Element tag="bdi" dir="ltr">
|
||||
@{creator.username}
|
||||
</Element>
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
<StatusBadge status={`payment.${payment.status}`}>
|
||||
{tCommon(`status.payment.${payment.status}`)}
|
||||
</StatusBadge>
|
||||
</FlexBox>
|
||||
<Element tag="dl" className="m-0 mt-3 border-t border-border-subtle pt-1">
|
||||
<DetailRow size="sm" label={t('result.period')}>
|
||||
{tCommon(`billing-periods.${payment.billingPeriod}`)}
|
||||
</DetailRow>
|
||||
{payment.amountToman !== null && (
|
||||
<DetailRow
|
||||
size="sm"
|
||||
label={t(
|
||||
kind === 'success' ? 'result.amount-paid' : 'result.amount',
|
||||
)}
|
||||
>
|
||||
<Amount value={payment.amountToman} currency={t('tier.currency')} />
|
||||
</DetailRow>
|
||||
)}
|
||||
{payment.createdAt && (
|
||||
<DetailRow
|
||||
size="sm"
|
||||
label={t(
|
||||
kind === 'failed' ? 'result.attempted-at' : 'result.paid-at',
|
||||
)}
|
||||
>
|
||||
<DateTime value={payment.createdAt} />
|
||||
</DetailRow>
|
||||
)}
|
||||
{kind === 'success' && payment.period?.to && (
|
||||
<DetailRow size="sm" label={t('result.expires-at')}>
|
||||
<DateTime value={payment.period.to} />
|
||||
</DetailRow>
|
||||
)}
|
||||
{payment.reference && (
|
||||
<DetailRow size="sm" label={t('result.reference')}>
|
||||
<FlexBox
|
||||
tag="span"
|
||||
display="inline-flex"
|
||||
alignItems="items-center"
|
||||
className="gap-0.5"
|
||||
>
|
||||
<Element tag="bdi" dir="ltr" className="font-latin">
|
||||
{payment.reference}
|
||||
</Element>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="copy"
|
||||
label={t('result.copy-reference')}
|
||||
onClick={onCopyReference}
|
||||
/>
|
||||
</FlexBox>
|
||||
</DetailRow>
|
||||
)}
|
||||
</Element>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export { PaymentResult } from './PaymentResult';
|
||||
export { PaymentResultSkeleton } from './PaymentResultSkeleton';
|
||||
export type {
|
||||
PaymentResultLayout,
|
||||
PaymentResultProps,
|
||||
PaymentResultSkeletonProps,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import type { ReactNode } from 'react';
|
||||
|
||||
import type {
|
||||
PaymentResultKind,
|
||||
PaymentResultPageModel,
|
||||
} from '../../../../../../../../features/checkout';
|
||||
import type { TransactionDetailPayload } from '../../../../../../../../features/transaction';
|
||||
|
||||
export type PaymentResultLayout = 'mobile' | 'desktop';
|
||||
|
||||
export type PaymentResultProps = {
|
||||
paymentId: string;
|
||||
layout: PaymentResultLayout;
|
||||
};
|
||||
|
||||
export type ResultHeadProps = { kind: PaymentResultKind };
|
||||
|
||||
export type ResultReceiptProps = {
|
||||
kind: PaymentResultKind;
|
||||
payment: TransactionDetailPayload;
|
||||
onCopyReference: PaymentResultPageModel['copyReference'];
|
||||
};
|
||||
|
||||
export type ResultActionsProps = {
|
||||
kind: PaymentResultKind;
|
||||
payment: TransactionDetailPayload;
|
||||
};
|
||||
|
||||
export type PaymentResultSkeletonProps = {
|
||||
layout: PaymentResultLayout;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export type ResultFrameProps = {
|
||||
layout: PaymentResultLayout;
|
||||
/** The head, the receipt and the note. */
|
||||
body: ReactNode;
|
||||
/** Primary then secondary. */
|
||||
actions: ReactNode;
|
||||
};
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Spinner } from '@lumina/island/atoms/spinner';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
|
||||
import type { PaymentConfirmingProps } from './types';
|
||||
|
||||
/**
|
||||
* «در حال تأیید پرداخت...» (U10 ۱.۱, ۸.۱): full screen and centred, with no bar, no navigation and
|
||||
* nothing to tap, so there is no way out but closing the app, which is safe. The spinner is the
|
||||
* only motion. If the payment settles at once it is never seen.
|
||||
*/
|
||||
export function PaymentConfirming({ layout, labels }: PaymentConfirmingProps) {
|
||||
return (
|
||||
<FlexBox
|
||||
tag="main"
|
||||
direction="flex-col"
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-center"
|
||||
className="min-h-dvh bg-bg-page px-11 text-center"
|
||||
>
|
||||
<FlexBox
|
||||
tag="output"
|
||||
aria-busy
|
||||
direction="flex-col"
|
||||
alignItems="items-center"
|
||||
gap="gap-5"
|
||||
className="max-w-105"
|
||||
>
|
||||
<Spinner size="page" />
|
||||
<FlexBox direction="flex-col" gap="gap-2">
|
||||
<Typography tag="h1" variant="heading-sm">
|
||||
{labels.title}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant={layout === 'desktop' ? 'body-md' : 'body-sm'}
|
||||
color="secondary"
|
||||
>
|
||||
{labels.description}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { PaymentConfirming } from './PaymentConfirming';
|
||||
export type { PaymentConfirmingLabels, PaymentConfirmingProps } from './types';
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
export type PaymentConfirmingLabels = {
|
||||
/** «در حال تأیید پرداخت...». */
|
||||
title: string;
|
||||
/** «لطفاً برنامه را نبندید. این کار چند لحظه طول میکشد.». */
|
||||
description: string;
|
||||
};
|
||||
|
||||
export type PaymentConfirmingProps = {
|
||||
layout: 'mobile' | 'desktop';
|
||||
labels: PaymentConfirmingLabels;
|
||||
};
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
'use client';
|
||||
|
||||
import { usePaymentReturnPage } from '../../../../../../../features/checkout';
|
||||
import type { PaymentReturnProps } from './types';
|
||||
|
||||
/**
|
||||
* Reads the payment the bank just sent back until it settles, then moves on to its result page;
|
||||
* it shows the confirming screen it is given meanwhile.
|
||||
*/
|
||||
export function PaymentReturn({ paymentId, children }: PaymentReturnProps) {
|
||||
usePaymentReturnPage({ paymentId });
|
||||
return children;
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { PaymentReturn } from './PaymentReturn';
|
||||
export type { PaymentReturnProps } from './types';
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import type { ReactNode } from 'react';
|
||||
|
||||
export type PaymentReturnProps = {
|
||||
/** From the return URL; `null` when the API's callback left it out. */
|
||||
paymentId: string | null;
|
||||
/** What shows meanwhile: PaymentConfirming. */
|
||||
children: ReactNode;
|
||||
};
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { SupportSheet } from '@lumina/island/organisms/support-sheet';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
|
||||
import type { SubscriptionTermsProps } from './types';
|
||||
|
||||
/**
|
||||
* «شرایط اشتراک» (S5): eight numbered sections, verbatim. In §۳ the two options sit as a numbered
|
||||
* list on a sunken panel with bold lead-ins, between its first paragraph and the rest; §۸ ends with
|
||||
* the support hours and the two chat rows. The same for every visitor, so it renders on the server.
|
||||
*/
|
||||
export function SubscriptionTerms({
|
||||
layout,
|
||||
chats,
|
||||
labels,
|
||||
}: SubscriptionTermsProps) {
|
||||
const last = labels.sections.length - 1;
|
||||
|
||||
return (
|
||||
<FlexBox tag="article" direction="flex-col" gap="gap-6">
|
||||
{/* Desktop's column title is the h1; the mobile bar's name is not a heading. */}
|
||||
{layout === 'mobile' && (
|
||||
<Typography tag="h1" className="sr-only">
|
||||
{labels.title}
|
||||
</Typography>
|
||||
)}
|
||||
{labels.sections.map((section, index) => {
|
||||
const [first, ...rest] = section.paragraphs;
|
||||
const titleId = `terms-${section.id}`;
|
||||
return (
|
||||
<FlexBox
|
||||
key={section.id}
|
||||
tag="section"
|
||||
aria-labelledby={titleId}
|
||||
direction="flex-col"
|
||||
gap="gap-2"
|
||||
>
|
||||
<Typography tag="h2" id={titleId} variant="heading-sm">
|
||||
{section.title}
|
||||
</Typography>
|
||||
<Typography>{first}</Typography>
|
||||
{section.options && (
|
||||
<FlexBox
|
||||
tag="ol"
|
||||
direction="flex-col"
|
||||
gap="gap-2"
|
||||
className="m-0 list-decimal rounded-md bg-surface-sunken py-3 ps-9 pe-4"
|
||||
>
|
||||
{section.options.map((option) => (
|
||||
<Element tag="li" key={option.lead}>
|
||||
<Typography tag="span">
|
||||
<Typography
|
||||
tag="b"
|
||||
variant="inherit"
|
||||
className="font-bold"
|
||||
>
|
||||
{option.lead}
|
||||
</Typography>{' '}
|
||||
{option.text}
|
||||
</Typography>
|
||||
</Element>
|
||||
))}
|
||||
</FlexBox>
|
||||
)}
|
||||
{rest.map((paragraph) => (
|
||||
<Typography key={paragraph}>{paragraph}</Typography>
|
||||
))}
|
||||
{index === last && (
|
||||
<>
|
||||
<Typography color="secondary">{labels.hours}</Typography>
|
||||
<SupportSheet
|
||||
placement="rows"
|
||||
baleHref={chats.bale}
|
||||
telegramHref={chats.telegram}
|
||||
labels={labels.support}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</FlexBox>
|
||||
);
|
||||
})}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export { subscriptionTermsLabels } from './labels';
|
||||
export { SubscriptionTerms } from './SubscriptionTerms';
|
||||
export type {
|
||||
SubscriptionTermsLabels,
|
||||
SubscriptionTermsProps,
|
||||
TermsSection,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
import type { TFunction } from 'i18next';
|
||||
|
||||
import type { SubscriptionTermsLabels, TermsSection } from './types';
|
||||
|
||||
/** The terms' text, from the server's translations (0020), verbatim from S5. */
|
||||
export function subscriptionTermsLabels(
|
||||
t: TFunction<'terms'>,
|
||||
tAuth: TFunction<'auth'>,
|
||||
hours: string,
|
||||
): SubscriptionTermsLabels {
|
||||
const sections: TermsSection[] = [
|
||||
{ id: 's1', title: t('s1.title'), paragraphs: [t('s1.p1'), t('s1.p2')] },
|
||||
{
|
||||
id: 's2',
|
||||
title: t('s2.title'),
|
||||
paragraphs: [t('s2.p1'), t('s2.p2'), t('s2.p3')],
|
||||
},
|
||||
{
|
||||
id: 's3',
|
||||
title: t('s3.title'),
|
||||
paragraphs: [t('s3.p1'), t('s3.p2'), t('s3.p3'), t('s3.p4')],
|
||||
options: [
|
||||
{ lead: t('s3.refund-lead'), text: t('s3.refund') },
|
||||
{ lead: t('s3.wait-lead'), text: t('s3.wait') },
|
||||
],
|
||||
},
|
||||
{ id: 's4', title: t('s4.title'), paragraphs: [t('s4.p1'), t('s4.p2')] },
|
||||
{
|
||||
id: 's5',
|
||||
title: t('s5.title'),
|
||||
paragraphs: [t('s5.p1'), t('s5.p2'), t('s5.p3')],
|
||||
},
|
||||
{
|
||||
id: 's6',
|
||||
title: t('s6.title'),
|
||||
paragraphs: [t('s6.p1'), t('s6.p2'), t('s6.p3')],
|
||||
},
|
||||
{ id: 's7', title: t('s7.title'), paragraphs: [t('s7.p1'), t('s7.p2')] },
|
||||
{ id: 's8', title: t('s8.title'), paragraphs: [t('s8.p1')] },
|
||||
];
|
||||
|
||||
return {
|
||||
title: t('title'),
|
||||
sections,
|
||||
hours: t('s8.hours', { hours }),
|
||||
support: {
|
||||
title: tAuth('support.title'),
|
||||
bale: tAuth('support.bale'),
|
||||
telegram: tAuth('support.telegram'),
|
||||
close: tAuth('support.close'),
|
||||
opensNewTab: tAuth('support.opens-new-tab'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import type { SupportSheetLabels } from '@lumina/island/organisms/support-sheet';
|
||||
|
||||
/** One numbered section: its paragraphs, and §۳'s two options after its first paragraph. */
|
||||
export type TermsSection = {
|
||||
id: string;
|
||||
title: string;
|
||||
paragraphs: string[];
|
||||
options?: { lead: string; text: string }[];
|
||||
};
|
||||
|
||||
export type SubscriptionTermsLabels = {
|
||||
/** The page's name: «شرایط اشتراک». */
|
||||
title: string;
|
||||
sections: TermsSection[];
|
||||
/** §۸'s line: «زمان پاسخگویی: …» with the configured hours. */
|
||||
hours: string;
|
||||
support: SupportSheetLabels;
|
||||
};
|
||||
|
||||
export type SubscriptionTermsProps = {
|
||||
/**
|
||||
* Mobile adds the page's h1 for screen readers, since its bar names the page in plain text;
|
||||
* desktop's column title (DesktopPageTitle) is the h1.
|
||||
*/
|
||||
layout: 'mobile' | 'desktop';
|
||||
/** The support chats' addresses, from config. */
|
||||
chats: { bale: string; telegram: string };
|
||||
labels: SubscriptionTermsLabels;
|
||||
};
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
'use client';
|
||||
|
||||
import { Modal } from '@lumina/island/molecules/modal';
|
||||
import { Sheet } from '@lumina/island/molecules/sheet';
|
||||
import { Suspense } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { PartBoundary } from '../../../../../../error-boundaries';
|
||||
import { RenewalForm } from './components/RenewalForm';
|
||||
import { RenewalSkeleton } from './components/RenewalSkeleton';
|
||||
import type { RenewalSheetProps } from './types';
|
||||
|
||||
/**
|
||||
* «تمدید» and «فعالسازی مجدد» (U3): a bottom sheet on mobile, a centred modal on desktop (U2
|
||||
* ۴.۳). ✕, Escape and the scrim close it. The periods load inside it, with their own skeleton and
|
||||
* error, so a failure never touches the list behind it.
|
||||
*/
|
||||
export function RenewalSheet({
|
||||
target,
|
||||
open,
|
||||
layout,
|
||||
onClose,
|
||||
}: RenewalSheetProps) {
|
||||
const { t } = useTranslation('dashboard');
|
||||
const title =
|
||||
target.status === 'expired'
|
||||
? t('subscriptions.renewal.reactivate-title')
|
||||
: t('subscriptions.renewal.renew-title');
|
||||
const body = (
|
||||
<PartBoundary
|
||||
name="renewal-sheet"
|
||||
description={t('subscriptions.renewal.error')}
|
||||
>
|
||||
<Suspense
|
||||
fallback={
|
||||
<RenewalSkeleton label={t('subscriptions.renewal.loading')} />
|
||||
}
|
||||
>
|
||||
<RenewalForm
|
||||
key={target.id}
|
||||
subscriptionId={target.id}
|
||||
layout={layout}
|
||||
/>
|
||||
</Suspense>
|
||||
</PartBoundary>
|
||||
);
|
||||
const closeLabel = t('subscriptions.renewal.close');
|
||||
|
||||
return layout === 'mobile' ? (
|
||||
<Sheet open={open} title={title} onClose={onClose} closeLabel={closeLabel}>
|
||||
{body}
|
||||
</Sheet>
|
||||
) : (
|
||||
<Modal open={open} title={title} onClose={onClose} closeLabel={closeLabel}>
|
||||
{body}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,236 @@
|
|||
import { Amount } from '@lumina/island/atoms/amount';
|
||||
import { Avatar } from '@lumina/island/atoms/avatar';
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { Countdown } from '@lumina/island/atoms/countdown';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
import { TierOption } from '@lumina/island/organisms/tier-option';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
import { date } from '@lumina/tools/format';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useRenewalSheet } from '../../../../../../../../features/subscription';
|
||||
import { BILLING_PERIOD_MONTHS } from '../../../../../../../../shared/constants';
|
||||
import {
|
||||
promotionCountdownLabels,
|
||||
tierOptionLabels,
|
||||
} from '../../../../../../../../shared/labels';
|
||||
import type { RenewalFormProps } from '../types';
|
||||
|
||||
/**
|
||||
* The renew or reactivate sheet's body (U3): the creator, then for a renewal how long the
|
||||
* subscription runs now, the periods with their prices (a live promotion struck and timed, R3 01), the exact dates the chosen one buys, a
|
||||
* note when the creator's price changed since the last purchase, the total and the payment
|
||||
* button. Renew starts on the current period; reactivate starts with none, so its button stays
|
||||
* frozen and says why until one is picked (R3 05). Dates and total follow the choice.
|
||||
*/
|
||||
export function RenewalForm({ subscriptionId, layout }: RenewalFormProps) {
|
||||
const { t } = useTranslation('dashboard');
|
||||
const { t: tPayment } = useTranslation('payment');
|
||||
const { t: tCommon } = useTranslation('common');
|
||||
const headingId = useId();
|
||||
const model = useRenewalSheet({ subscriptionId });
|
||||
const { kind, preview, tiers, selectedTier, phase } = model;
|
||||
const isRenew = kind === 'renew';
|
||||
const labels = tierOptionLabels(tPayment);
|
||||
const countdownLabels = promotionCountdownLabels(tPayment);
|
||||
const from = selectedTier?.periodFrom ?? tiers[0]?.periodFrom;
|
||||
const isBusy = phase !== 'idle';
|
||||
const payLabel = isBusy
|
||||
? t('subscriptions.renewal.paying')
|
||||
: model.isOffline
|
||||
? t('subscriptions.renewal.retry')
|
||||
: isRenew
|
||||
? t('subscriptions.renewal.pay-renew')
|
||||
: t('subscriptions.renewal.pay-reactivate');
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-4">
|
||||
{model.isOffline && (
|
||||
<Banner tone="danger" title={t('subscriptions.renewal.offline')} />
|
||||
)}
|
||||
<FlexBox alignItems="items-center" gap="gap-3">
|
||||
<Avatar
|
||||
name={preview.creator.username ?? '?'}
|
||||
src={preview.creator.avatarUrl}
|
||||
size="sm"
|
||||
/>
|
||||
<FlexBox direction="flex-col" className="min-w-0">
|
||||
<FlexBox alignItems="items-center" className="gap-1.5">
|
||||
<Typography tag="span" className="truncate font-semibold">
|
||||
{preview.creator.displayName ?? (
|
||||
<Element tag="bdi" dir="ltr">
|
||||
@{preview.creator.username}
|
||||
</Element>
|
||||
)}
|
||||
</Typography>
|
||||
<Icon
|
||||
name="check-circle"
|
||||
size={16}
|
||||
label={tPayment('checkout.verified')}
|
||||
className="flex-none text-action-primary-text"
|
||||
/>
|
||||
</FlexBox>
|
||||
{preview.creator.displayName && (
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="caption"
|
||||
color="secondary"
|
||||
className="truncate"
|
||||
>
|
||||
<Element tag="bdi" dir="ltr">
|
||||
@{preview.creator.username}
|
||||
</Element>
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
{isRenew && (
|
||||
<Typography>
|
||||
{t('subscriptions.renewal.current', {
|
||||
date: date(preview.currentEndsAt, { time: false }),
|
||||
})}
|
||||
</Typography>
|
||||
)}
|
||||
<FlexBox
|
||||
tag="section"
|
||||
aria-labelledby={headingId}
|
||||
direction="flex-col"
|
||||
gap="gap-3"
|
||||
>
|
||||
<Typography tag="h3" id={headingId} variant="label">
|
||||
{t('subscriptions.renewal.tiers')}
|
||||
</Typography>
|
||||
<FlexBox
|
||||
role="radiogroup"
|
||||
aria-labelledby={headingId}
|
||||
direction="flex-col"
|
||||
gap="gap-3"
|
||||
>
|
||||
{tiers.map((tier) => {
|
||||
const { promotion } = tier;
|
||||
// A live promotion applies to renewals and reactivations too (terms §۵).
|
||||
const isPromotion =
|
||||
promotion !== null &&
|
||||
tier.standingToman !== null &&
|
||||
tier.amountToman !== null &&
|
||||
tier.standingToman > tier.amountToman;
|
||||
return (
|
||||
<TierOption
|
||||
key={tier.id}
|
||||
name={`renewal-${subscriptionId}`}
|
||||
value={tier.id}
|
||||
label={tCommon(`billing-periods.${tier.billingPeriod}`)}
|
||||
months={BILLING_PERIOD_MONTHS[tier.billingPeriod]}
|
||||
total={tier.amountToman ?? 0}
|
||||
monthlyPrice={model.monthlyPrice}
|
||||
standing={
|
||||
isPromotion ? (tier.standingToman ?? undefined) : undefined
|
||||
}
|
||||
selected={tier.id === selectedTier?.id}
|
||||
onSelect={model.selectTier}
|
||||
padding={layout === 'desktop' ? 'lg' : 'md'}
|
||||
labels={labels}
|
||||
>
|
||||
{isPromotion && promotion.endsAt && !promotion.indefinite && (
|
||||
<Countdown
|
||||
kind="promotion"
|
||||
endsAt={promotion.endsAt}
|
||||
labels={countdownLabels}
|
||||
/>
|
||||
)}
|
||||
</TierOption>
|
||||
);
|
||||
})}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
tag="dl"
|
||||
direction="flex-col"
|
||||
className="m-0 gap-0.5 rounded-md bg-surface-sunken px-4 py-3"
|
||||
>
|
||||
<FlexBox justifyContent="justify-between" gap="gap-3">
|
||||
<Element tag="dt">
|
||||
{isRenew
|
||||
? t('subscriptions.renewal.from')
|
||||
: t('subscriptions.renewal.start')}
|
||||
</Element>
|
||||
<Element tag="dd" className="m-0 font-semibold">
|
||||
{from &&
|
||||
(isRenew
|
||||
? date(from, { time: false })
|
||||
: t('subscriptions.renewal.today', {
|
||||
date: date(from, { time: false }),
|
||||
}))}
|
||||
</Element>
|
||||
</FlexBox>
|
||||
<FlexBox justifyContent="justify-between" gap="gap-3">
|
||||
<Element tag="dt">{t('subscriptions.renewal.to')}</Element>
|
||||
<Element
|
||||
tag="dd"
|
||||
className={selectedTier ? 'm-0 font-semibold' : 'm-0'}
|
||||
>
|
||||
{selectedTier ? date(selectedTier.periodTo, { time: false }) : '—'}
|
||||
</Element>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
{selectedTier?.priceChanged && (
|
||||
<FlexBox alignItems="items-start" className="gap-1.5 text-warning-text">
|
||||
<Icon name="info" size={16} className="mt-1 flex-none" />
|
||||
<Typography variant="body-sm" color="warning">
|
||||
{t('subscriptions.renewal.price-changed')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
)}
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
>
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('subscriptions.renewal.total')}
|
||||
</Typography>
|
||||
{selectedTier?.amountToman != null ? (
|
||||
<Amount
|
||||
value={selectedTier.amountToman}
|
||||
size="figure"
|
||||
currency={tCommon('currency')}
|
||||
/>
|
||||
) : (
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="heading-sm"
|
||||
color="tertiary"
|
||||
aria-label={t('subscriptions.renewal.no-total')}
|
||||
>
|
||||
—
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
{selectedTier ? (
|
||||
<Button
|
||||
variant="primary"
|
||||
size={layout === 'mobile' ? 'lg' : 'md'}
|
||||
block
|
||||
isLoading={isBusy}
|
||||
onClick={model.pay}
|
||||
>
|
||||
{payLabel}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
size={layout === 'mobile' ? 'lg' : 'md'}
|
||||
block
|
||||
frozen
|
||||
frozenReason={t('subscriptions.renewal.frozen')}
|
||||
>
|
||||
{payLabel}
|
||||
</Button>
|
||||
)}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<SkeletonRegion label={label}>
|
||||
<FlexBox direction="flex-col" gap="gap-4">
|
||||
<FlexBox alignItems="items-center" gap="gap-3">
|
||||
<Skeleton shape="circle" width="2rem" height="2rem" />
|
||||
<Skeleton width="7rem" height="1rem" />
|
||||
</FlexBox>
|
||||
<Skeleton width="60%" />
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
{TIER_ROWS.map((row) => (
|
||||
<Card key={row}>
|
||||
<FlexBox alignItems="items-center" gap="gap-3">
|
||||
<Skeleton shape="circle" width="1.25rem" height="1.25rem" />
|
||||
<FlexBox direction="flex-col" gap="gap-2" className="flex-1">
|
||||
<Skeleton width="40%" height="1rem" />
|
||||
<Skeleton width="55%" />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
</Card>
|
||||
))}
|
||||
</FlexBox>
|
||||
<Skeleton shape="rect" width="100%" height="4rem" />
|
||||
<Skeleton shape="pill" width="100%" height="3.25rem" />
|
||||
</FlexBox>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { RenewalSheet } from './RenewalSheet';
|
||||
export type { DashboardLayout, RenewalSheetProps } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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) => (
|
||||
<FlexBox tag="ul" direction="flex-col" gap={gap}>
|
||||
{items.map((subscription) => (
|
||||
<SubscriptionItem
|
||||
key={subscription.id}
|
||||
subscription={subscription}
|
||||
onRenew={() => model.openRenewal(subscription)}
|
||||
onSupport={model.openSupport}
|
||||
/>
|
||||
))}
|
||||
</FlexBox>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<FlexBox
|
||||
tag="section"
|
||||
aria-label={t('subscriptions.label')}
|
||||
direction="flex-col"
|
||||
gap={gap}
|
||||
className="flex-1"
|
||||
>
|
||||
<Typography className="font-semibold">
|
||||
{activeCount > 0
|
||||
? t('subscriptions.active-count', { n: number(activeCount) })
|
||||
: t('subscriptions.no-active')}
|
||||
</Typography>
|
||||
{active.length > 0 ? (
|
||||
list(active)
|
||||
) : (
|
||||
<SubscriptionsEmpty layout={layout} />
|
||||
)}
|
||||
{expired.length > 0 && (
|
||||
<>
|
||||
<Typography tag="h2" variant="heading-sm" className="mt-2">
|
||||
{t('subscriptions.expired')}
|
||||
</Typography>
|
||||
{list(expired)}
|
||||
</>
|
||||
)}
|
||||
</FlexBox>
|
||||
{model.renewalTarget && (
|
||||
<RenewalSheet
|
||||
target={model.renewalTarget}
|
||||
open={model.isRenewalOpen}
|
||||
layout={layout}
|
||||
onClose={model.closeRenewal}
|
||||
/>
|
||||
)}
|
||||
<SupportDialog
|
||||
placement={layout === 'mobile' ? 'bottom' : 'modal'}
|
||||
open={model.isSupportOpen}
|
||||
onClose={model.closeSupport}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 (
|
||||
<Element tag="li">
|
||||
<SubscriptionCard
|
||||
status={status}
|
||||
analyst={{
|
||||
name: creator.displayName ?? username,
|
||||
username,
|
||||
avatarSrc: creator.avatarUrl,
|
||||
}}
|
||||
tier={tCommon(`billing-periods.${subscription.tier.billingPeriod}`)}
|
||||
startsAt={subscription.startsAt ?? undefined}
|
||||
endsAt={subscription.endsAt}
|
||||
daysLeft={subscription.daysLeft ?? undefined}
|
||||
analystSuspended={status === 'expired' && creator.suspended}
|
||||
href={
|
||||
username && !creator.suspended ? ROUTES.channel(username) : undefined
|
||||
}
|
||||
onRenew={onRenew}
|
||||
onReactivate={onRenew}
|
||||
onSupport={onSupport}
|
||||
termsHref={ROUTES.terms}
|
||||
labels={subscriptionCardLabels(t, tCommon)}
|
||||
/>
|
||||
</Element>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 = (
|
||||
<EmptyState
|
||||
title={t('subscriptions.empty.title')}
|
||||
icon="star"
|
||||
size={isDesktop ? 'section' : 'page'}
|
||||
className={isDesktop ? undefined : 'flex-1'}
|
||||
>
|
||||
<Button variant="primary" icon="home" href={ROUTES.home}>
|
||||
{t('subscriptions.empty.home')}
|
||||
</Button>
|
||||
</EmptyState>
|
||||
);
|
||||
|
||||
return isDesktop ? <Card>{state}</Card> : state;
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { SubscriptionList } from './SubscriptionList';
|
||||
export type { DashboardLayout, SubscriptionListProps } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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 <TransactionsEmpty layout={layout} />;
|
||||
|
||||
return (
|
||||
<>
|
||||
<FlexBox
|
||||
tag="section"
|
||||
aria-label={t('transactions.label')}
|
||||
aria-busy={model.isFiltering}
|
||||
direction="flex-col"
|
||||
gap={gap}
|
||||
className="flex-1"
|
||||
>
|
||||
<FilterChips
|
||||
label={t('transactions.filter')}
|
||||
options={TRANSACTION_FILTERS.map((value) => ({
|
||||
value,
|
||||
label: t(`transactions.filters.${value}`),
|
||||
}))}
|
||||
value={model.filter}
|
||||
onChange={model.setFilter}
|
||||
/>
|
||||
{model.rows.length === 0 ? (
|
||||
<EmptyState
|
||||
title={t('transactions.no-results')}
|
||||
icon="filter"
|
||||
tone="neutral"
|
||||
size="section"
|
||||
/>
|
||||
) : (
|
||||
<FlexBox tag="ul" direction="flex-col" gap={gap}>
|
||||
{model.rows.map((row) => (
|
||||
<TransactionRow
|
||||
key={row.id}
|
||||
row={row}
|
||||
layout={layout}
|
||||
onOpen={() => model.openDetail(row)}
|
||||
/>
|
||||
))}
|
||||
</FlexBox>
|
||||
)}
|
||||
{model.loadMoreError ? (
|
||||
<ErrorState
|
||||
kind={model.loadMoreError}
|
||||
size="inline"
|
||||
title={t(`errors:fallback.${model.loadMoreError}.title`)}
|
||||
description={t('transactions.more-failed')}
|
||||
onRetry={model.loadMore}
|
||||
retryLabel={t('errors:fallback.retry')}
|
||||
retryingLabel={t('errors:fallback.retrying')}
|
||||
retrying={model.isLoadingMore}
|
||||
/>
|
||||
) : (
|
||||
model.hasMore && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
block
|
||||
onClick={model.loadMore}
|
||||
isLoading={model.isLoadingMore}
|
||||
>
|
||||
{t('transactions.more')}
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</FlexBox>
|
||||
<TransactionDetail model={model} layout={layout} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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.
|
||||
<FlexBox direction="flex-col" className="relative">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size={isDesktop ? 'md' : 'lg'}
|
||||
icon="headset"
|
||||
block
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={isSupportOpen}
|
||||
onClick={() => setIsSupportOpen((open) => !open)}
|
||||
>
|
||||
{t('transactions.support')}
|
||||
</Button>
|
||||
<SupportDialog
|
||||
placement={isDesktop ? 'popover' : 'bottom'}
|
||||
open={isSupportOpen}
|
||||
onClose={() => setIsSupportOpen(false)}
|
||||
/>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="copy"
|
||||
label={t('transactions.copy-reference')}
|
||||
onClick={() => model.copyReference(row.reference ?? '')}
|
||||
/>
|
||||
);
|
||||
const reference = row.reference && (
|
||||
<FlexBox
|
||||
tag="span"
|
||||
display="inline-flex"
|
||||
alignItems="items-center"
|
||||
className="gap-0.5"
|
||||
>
|
||||
<Element tag="bdi" dir="ltr" className="font-latin">
|
||||
{row.reference}
|
||||
</Element>
|
||||
{copy}
|
||||
</FlexBox>
|
||||
);
|
||||
const currency = tCommon('currency');
|
||||
const needsSupport = row.status !== 'successful';
|
||||
const isRefund = row.type === 'refund';
|
||||
const handle = row.creator.username && (
|
||||
<Element tag="bdi" dir="ltr">
|
||||
@{row.creator.username}
|
||||
</Element>
|
||||
);
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
placement={isDesktop ? 'side' : 'bottom'}
|
||||
open={model.isDetailOpen}
|
||||
title={t('transactions.detail-title')}
|
||||
onClose={model.closeDetail}
|
||||
closeLabel={t('transactions.close')}
|
||||
>
|
||||
<FlexBox direction="flex-col" gap="gap-4">
|
||||
{row.status === 'pending' && row.reference && (
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
alignItems="items-center"
|
||||
gap="gap-1"
|
||||
className="rounded-md bg-surface-sunken px-4 py-4"
|
||||
>
|
||||
<Typography variant="caption" color="secondary">
|
||||
{t('transactions.zarinpal-reference')}
|
||||
</Typography>
|
||||
<FlexBox alignItems="items-center" className="gap-0.5">
|
||||
<Typography tag="span" variant="heading-md">
|
||||
<Element tag="bdi" dir="ltr" className="font-latin">
|
||||
{row.reference}
|
||||
</Element>
|
||||
</Typography>
|
||||
{copy}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
)}
|
||||
{row.status === 'successful' && row.amountToman !== null && (
|
||||
<FlexBox direction="flex-col" alignItems="items-center" gap="gap-1">
|
||||
<Typography variant="caption" color="secondary">
|
||||
{isRefund
|
||||
? t('transactions.refund-amount')
|
||||
: t('transactions.amount-paid')}
|
||||
</Typography>
|
||||
<Amount
|
||||
value={row.amountToman}
|
||||
size="figure"
|
||||
currency={currency}
|
||||
signed={isRefund}
|
||||
tone={isRefund ? 'positive' : undefined}
|
||||
/>
|
||||
</FlexBox>
|
||||
)}
|
||||
{isRefund ? (
|
||||
<Element tag="dl" className="m-0 divide-y divide-border-subtle">
|
||||
<DetailRow label={t('transactions.kind')}>
|
||||
{t('transactions.kinds.refund')}
|
||||
</DetailRow>
|
||||
<DetailRow label={t('transactions.channel')}>{handle}</DetailRow>
|
||||
{row.createdAt && (
|
||||
<DetailRow label={t('transactions.date')}>
|
||||
{date(row.createdAt, { time: false })}
|
||||
</DetailRow>
|
||||
)}
|
||||
{reference && (
|
||||
<DetailRow label={t('transactions.transfer-reference')}>
|
||||
{reference}
|
||||
</DetailRow>
|
||||
)}
|
||||
{row.refund?.shebaLast4 && (
|
||||
<DetailRow label={t('transactions.sheba')}>
|
||||
{/* Banks print شبا in Latin digits; only its last four are kept. */}
|
||||
<Element tag="bdi" dir="ltr" className="font-latin">
|
||||
{`IR•• •••• •••• •••• ${row.refund.shebaLast4}`}
|
||||
</Element>
|
||||
</DetailRow>
|
||||
)}
|
||||
</Element>
|
||||
) : (
|
||||
<Element tag="dl" className="m-0 divide-y divide-border-subtle">
|
||||
<DetailRow label={t('transactions.title-label')}>
|
||||
{titleOf(row)}
|
||||
</DetailRow>
|
||||
{row.createdAt && (
|
||||
<DetailRow label={t('transactions.date')}>
|
||||
<DateTime value={row.createdAt} />
|
||||
</DetailRow>
|
||||
)}
|
||||
{row.status !== 'successful' && row.amountToman !== null && (
|
||||
<DetailRow label={t('transactions.amount')}>
|
||||
<Amount value={row.amountToman} currency={currency} />
|
||||
</DetailRow>
|
||||
)}
|
||||
<DetailRow label={t('transactions.status')}>
|
||||
<StatusBadge status={`payment.${row.status}`}>
|
||||
{tCommon(`status.payment.${row.status}`)}
|
||||
</StatusBadge>
|
||||
</DetailRow>
|
||||
{row.period?.from && row.period.to && (
|
||||
<DetailRow label={t('transactions.period')}>
|
||||
{date(row.period.from, { time: false })}{' '}
|
||||
{t('transactions.period-to')}{' '}
|
||||
{date(row.period.to, { time: false })}
|
||||
</DetailRow>
|
||||
)}
|
||||
{row.status !== 'pending' && reference && (
|
||||
<DetailRow label={t('transactions.reference')}>
|
||||
{reference}
|
||||
</DetailRow>
|
||||
)}
|
||||
</Element>
|
||||
)}
|
||||
{!isRefund && row.refund && (
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{t('transactions.refunded-note')}
|
||||
</Typography>
|
||||
)}
|
||||
{needsSupport && (
|
||||
<>
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{row.status === 'failed'
|
||||
? t('transactions.failed-detail-note')
|
||||
: t('transactions.pending-note')}
|
||||
</Typography>
|
||||
<DetailSupport key={row.id} isDesktop={isDesktop} />
|
||||
</>
|
||||
)}
|
||||
</FlexBox>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
import { Amount } from '@lumina/island/atoms/amount';
|
||||
import { Avatar } from '@lumina/island/atoms/avatar';
|
||||
import { DateTime } from '@lumina/island/atoms/date-time';
|
||||
import { Separator } from '@lumina/island/atoms/separator';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { StatusBadge } from '@lumina/island/atoms/status-badge';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { TransactionRowProps } from '../types';
|
||||
import { useTransactionTitle } from './use-transaction-title';
|
||||
|
||||
/**
|
||||
* One payment (U4 ۱.۱, ۲.۲; U10 ۳.۲, ۵.۲, ۶.۲): what it bought and from whom, when, its status,
|
||||
* the amount and the bank's reference. A failed one has the danger start border and says the bank
|
||||
* returns a debited amount within 72 hours; a pending one the warning border and why it waits.
|
||||
* The title is a button stretched over the card, so a tap anywhere opens the detail. A refund row
|
||||
* (S3 ۱.۱) reads «بازگشت وجه» with the channel and date under it, its amount a green «+», and the
|
||||
* bank transfer's tracking number.
|
||||
*/
|
||||
export function TransactionRow({ row, layout, onOpen }: TransactionRowProps) {
|
||||
const { t } = useTranslation('dashboard');
|
||||
const { t: tCommon } = useTranslation('common');
|
||||
const title = useTransactionTitle()(row);
|
||||
const isRefund = row.type === 'refund';
|
||||
const accent =
|
||||
row.status === 'failed'
|
||||
? 'danger'
|
||||
: row.status === 'pending'
|
||||
? 'warning'
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<Element tag="li">
|
||||
<Card
|
||||
tag="article"
|
||||
interactive
|
||||
accent={accent}
|
||||
padding={layout === 'desktop' ? 'lg' : 'md'}
|
||||
className="has-[[data-transaction-open]:focus-visible]:focus-ring"
|
||||
>
|
||||
<FlexBox alignItems="items-start" gap="gap-3">
|
||||
{isRefund && (
|
||||
<Avatar
|
||||
name={row.creator.username ?? '?'}
|
||||
src={row.creator.avatarUrl}
|
||||
size="sm"
|
||||
/>
|
||||
)}
|
||||
<FlexBox direction="flex-col" className="min-w-0 flex-1">
|
||||
<Element
|
||||
tag="button"
|
||||
type="button"
|
||||
data-transaction-open
|
||||
aria-haspopup="dialog"
|
||||
aria-label={t('transactions.open', { title })}
|
||||
onClick={onOpen}
|
||||
className="cursor-pointer text-start outline-none after:absolute after:inset-0 after:rounded-lg"
|
||||
>
|
||||
<Typography tag="span" className="font-semibold">
|
||||
{title}
|
||||
</Typography>
|
||||
</Element>
|
||||
{isRefund ? (
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
<Element tag="bdi" dir="ltr">
|
||||
@{row.creator.username}
|
||||
</Element>
|
||||
{row.createdAt && (
|
||||
<>
|
||||
<Separator />
|
||||
<DateTime value={row.createdAt} />
|
||||
</>
|
||||
)}
|
||||
</Typography>
|
||||
) : (
|
||||
row.createdAt && (
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
<DateTime value={row.createdAt} />
|
||||
</Typography>
|
||||
)
|
||||
)}
|
||||
</FlexBox>
|
||||
<StatusBadge status={`payment.${row.status}`} className="flex-none">
|
||||
{tCommon(`status.payment.${row.status}`)}
|
||||
</StatusBadge>
|
||||
</FlexBox>
|
||||
<Element
|
||||
tag="dl"
|
||||
className="m-0 mt-2.5 border-t border-border-subtle pt-1.5"
|
||||
>
|
||||
{row.amountToman !== null && (
|
||||
<FlexBox
|
||||
alignItems="items-baseline"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
className="py-1.5"
|
||||
>
|
||||
<Typography tag="dt" variant="caption" color="secondary">
|
||||
{t('transactions.amount')}
|
||||
</Typography>
|
||||
<Element tag="dd" className="m-0">
|
||||
<Amount
|
||||
value={row.amountToman}
|
||||
currency={tCommon('currency')}
|
||||
signed={isRefund}
|
||||
tone={isRefund ? 'positive' : undefined}
|
||||
/>
|
||||
</Element>
|
||||
</FlexBox>
|
||||
)}
|
||||
{row.reference && (
|
||||
<FlexBox
|
||||
alignItems="items-baseline"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
className="py-1.5"
|
||||
>
|
||||
<Typography tag="dt" variant="caption" color="secondary">
|
||||
{isRefund
|
||||
? t('transactions.transfer-reference')
|
||||
: t('transactions.reference')}
|
||||
</Typography>
|
||||
<Element tag="dd" className="m-0 font-semibold">
|
||||
<Element tag="bdi" dir="ltr" className="font-latin">
|
||||
{row.reference}
|
||||
</Element>
|
||||
</Element>
|
||||
</FlexBox>
|
||||
)}
|
||||
</Element>
|
||||
{row.status === 'pending' && (
|
||||
<FlexBox
|
||||
alignItems="items-start"
|
||||
className="mt-2 gap-1.5 rounded-md bg-warning-subtle px-3 py-2 text-warning-text"
|
||||
>
|
||||
<Icon name="clock" size={16} className="mt-1 flex-none" />
|
||||
<Typography variant="caption" color="warning">
|
||||
{t('transactions.pending-note')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
)}
|
||||
{row.status === 'failed' && (
|
||||
<Typography variant="caption" color="secondary" className="mt-1.5">
|
||||
{t('transactions.failed-note')}
|
||||
</Typography>
|
||||
)}
|
||||
</Card>
|
||||
</Element>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 { TransactionsEmptyProps } from '../types';
|
||||
|
||||
/**
|
||||
* No payment yet (U4 ۴.۲): no chips, and one way on, to خانه. Mobile centres it at page size;
|
||||
* desktop puts it in a card in the column at section size.
|
||||
*/
|
||||
export function TransactionsEmpty({ layout }: TransactionsEmptyProps) {
|
||||
const { t } = useTranslation('dashboard');
|
||||
const isDesktop = layout === 'desktop';
|
||||
const state = (
|
||||
<EmptyState
|
||||
title={t('transactions.empty.title')}
|
||||
icon="receipt"
|
||||
size={isDesktop ? 'section' : 'page'}
|
||||
className={isDesktop ? undefined : 'flex-1'}
|
||||
>
|
||||
<Button variant="primary" icon="home" href={ROUTES.home}>
|
||||
{t('transactions.empty.home')}
|
||||
</Button>
|
||||
</EmptyState>
|
||||
);
|
||||
|
||||
return isDesktop ? <Card>{state}</Card> : state;
|
||||
}
|
||||
|
|
@ -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 ?? '' }),
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { TransactionList } from './TransactionList';
|
||||
export type { DashboardLayout, TransactionListProps } from './types';
|
||||
|
|
@ -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 };
|
||||
|
|
@ -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 (
|
||||
<EmptyState
|
||||
title={t('empty')}
|
||||
icon="bell"
|
||||
tone="neutral"
|
||||
size={layout === 'page' ? 'page' : 'section'}
|
||||
className={layout === 'page' ? 'flex-1' : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<FlexBox tag="ul" aria-label={t('label')} direction="flex-col" gap="gap-3">
|
||||
{model.items.map((item) => (
|
||||
<NotificationItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
target={model.targetOf(item)}
|
||||
onOpen={() => model.open(item)}
|
||||
isOpening={model.openingId === item.id}
|
||||
supportPlacement={supportPlacement}
|
||||
/>
|
||||
))}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 = (
|
||||
<SkeletonPreset preset="list" avatar={false} label={t('loading')} />
|
||||
);
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
placement="side"
|
||||
open={open}
|
||||
title={t('title')}
|
||||
onClose={onClose}
|
||||
closeLabel={t('close')}
|
||||
>
|
||||
<PartBoundary name="notification-centre" description={t('error')}>
|
||||
<Suspense fallback={skeleton}>
|
||||
<NotificationCentre layout="panel" supportPlacement="popover" />
|
||||
</Suspense>
|
||||
</PartBoundary>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<string> = new Set(NOTIFICATION_CTA_TYPES);
|
||||
|
||||
const isCtaType = (type: string): type is CtaType => CTA_TYPES.has(type);
|
||||
|
||||
const SUPPORT_TYPES: ReadonlySet<string> = 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 = (
|
||||
<Typography tag="span" className="font-semibold">
|
||||
{item.serverTitle}
|
||||
</Typography>
|
||||
);
|
||||
const unread = !item.read && (
|
||||
<Typography tag="span" className="sr-only">
|
||||
{` (${t('unread')})`}
|
||||
</Typography>
|
||||
);
|
||||
const stretched =
|
||||
'cursor-pointer text-start text-text-primary no-underline outline-none after:absolute after:inset-0 after:rounded-lg';
|
||||
|
||||
return (
|
||||
<Element tag="li">
|
||||
<Card
|
||||
tag="article"
|
||||
interactive
|
||||
accent={item.read ? undefined : 'unread'}
|
||||
className="has-[[data-notification-open]:focus-visible]:focus-ring"
|
||||
>
|
||||
<FlexBox alignItems="items-start" gap="gap-3">
|
||||
<GridBox
|
||||
justifyItems="justify-items-center"
|
||||
alignItems="items-center"
|
||||
className={cn(
|
||||
'size-9 flex-none rounded-md',
|
||||
NOTIFICATION_TONE_CLASS[art.tone],
|
||||
)}
|
||||
>
|
||||
<Icon name={art.icon} size={20} />
|
||||
</GridBox>
|
||||
<FlexBox direction="flex-col" gap="gap-1" className="min-w-0 flex-1">
|
||||
<Typography tag="h3" variant="body-md">
|
||||
{target.kind === 'path' ? (
|
||||
<Element
|
||||
tag={NextLink}
|
||||
href={target.href}
|
||||
data-notification-open
|
||||
className={stretched}
|
||||
>
|
||||
{title}
|
||||
{unread}
|
||||
</Element>
|
||||
) : target.kind === 'creator' ? (
|
||||
<Element
|
||||
tag="button"
|
||||
type="button"
|
||||
data-notification-open
|
||||
onClick={onOpen}
|
||||
aria-busy={isOpening}
|
||||
className={stretched}
|
||||
>
|
||||
{title}
|
||||
{unread}
|
||||
</Element>
|
||||
) : (
|
||||
<>
|
||||
{title}
|
||||
{unread}
|
||||
</>
|
||||
)}
|
||||
</Typography>
|
||||
{leads ? (
|
||||
<Typography variant="body-sm" className="line-clamp-2">
|
||||
{item.serverMessage}
|
||||
</Typography>
|
||||
) : (
|
||||
<Element
|
||||
tag="button"
|
||||
type="button"
|
||||
data-notification-open
|
||||
aria-expanded={isExpanded}
|
||||
aria-label={t('show-more')}
|
||||
onClick={() => setIsExpanded((expanded) => !expanded)}
|
||||
className={stretched}
|
||||
>
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="body-sm"
|
||||
className={isExpanded ? undefined : 'line-clamp-2'}
|
||||
>
|
||||
{item.serverMessage}
|
||||
</Typography>
|
||||
</Element>
|
||||
)}
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
className="min-h-touch-target -mb-2"
|
||||
>
|
||||
{item.createdAt && (
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="caption"
|
||||
color="secondary"
|
||||
className="whitespace-nowrap"
|
||||
>
|
||||
{relative(item.createdAt)}
|
||||
</Typography>
|
||||
)}
|
||||
{/* Above the stretched link, so it keeps its own tap and focus. */}
|
||||
{cta && target.kind === 'path' && (
|
||||
<Link
|
||||
href={target.href}
|
||||
standalone
|
||||
className="relative flex-none"
|
||||
>
|
||||
{t(`cta.${cta}`)}
|
||||
</Link>
|
||||
)}
|
||||
{cta && target.kind === 'creator' && (
|
||||
<LinkButton
|
||||
standalone
|
||||
onClick={onOpen}
|
||||
className="relative flex-none"
|
||||
>
|
||||
{t(`cta.${cta}`)}
|
||||
</LinkButton>
|
||||
)}
|
||||
{opensSupport && (
|
||||
// A popover hangs from a positioned parent that also holds its trigger.
|
||||
<FlexBox className="relative flex-none">
|
||||
<SupportLink
|
||||
standalone
|
||||
aria-haspopup="dialog"
|
||||
aria-expanded={isSupportOpen}
|
||||
onClick={() => setIsSupportOpen((open) => !open)}
|
||||
>
|
||||
{t('support')}
|
||||
</SupportLink>
|
||||
<SupportDialog
|
||||
placement={supportPlacement}
|
||||
open={isSupportOpen}
|
||||
onClose={() => setIsSupportOpen(false)}
|
||||
/>
|
||||
</FlexBox>
|
||||
)}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
</Card>
|
||||
</Element>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<NotificationTone, string> = {
|
||||
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[];
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
export { NOTIFICATION_ART } from './constants';
|
||||
export { NotificationCentre } from './NotificationCentre';
|
||||
export { NotificationPanel } from './NotificationPanel';
|
||||
export type {
|
||||
NotificationCentreLayout,
|
||||
NotificationCentreProps,
|
||||
NotificationPanelProps,
|
||||
} from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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 (
|
||||
<SupportSheet
|
||||
placement={placement}
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
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'),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 = (
|
||||
<SupportSheet
|
||||
<SupportDialog
|
||||
placement={placement}
|
||||
open={isOpen}
|
||||
onClose={() => 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'),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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<SupportPlacement, 'bottom' | 'popover' | 'modal'>;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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<WaitlistJoinedPayload> {
|
||||
const result = await checkoutRepository.joinWaitlist(args);
|
||||
if (emit) {
|
||||
eventEmitter.emit(CHECKOUT_EVENTS.waitlistJoined, {
|
||||
creatorId: args.creatorId,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { joinWaitlist } from './actions';
|
||||
|
|
@ -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<AbandonPaymentPayload | null> | 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<AbandonPaymentPayload | null> {
|
||||
inFlight ??= settle(emit).finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
async function settle(emit: boolean): Promise<AbandonPaymentPayload | null> {
|
||||
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;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { settleAbandonedPayment } from './actions';
|
||||
|
|
@ -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<CheckoutResultPayload> {
|
||||
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;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { startCheckout } from './actions';
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
export { useCheckoutPage } from './use-checkout-page';
|
||||
export type {
|
||||
CheckoutHalt,
|
||||
CheckoutMode,
|
||||
CheckoutPageModel,
|
||||
CheckoutPhase,
|
||||
CodeCheck,
|
||||
UseCheckoutPageOptions,
|
||||
} from './types';
|
||||
|
|
@ -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<CheckoutFormValues, unknown, CheckoutFormOutput>;
|
||||
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;
|
||||
};
|
||||
|
|
@ -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<CheckoutPhase>('idle');
|
||||
const [halt, setHalt] = useState<CheckoutHalt | null>(null);
|
||||
const [isOffline, setIsOffline] = useState(false);
|
||||
const [codeCheck, setCodeCheck] = useState<CodeCheck>('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<CheckoutFormValues, unknown, CheckoutFormOutput>({
|
||||
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<CheckoutPayload>(
|
||||
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);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
export { usePaymentResultPage } from './use-payment-result-page';
|
||||
export type {
|
||||
PaymentResultKind,
|
||||
PaymentResultPageModel,
|
||||
UsePaymentResultPageOptions,
|
||||
} from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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<PaymentUiStatus, PaymentResultKind> = {
|
||||
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 };
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { usePaymentReturnPage } from './use-payment-return-page';
|
||||
export type { UsePaymentReturnPageOptions } from './types';
|
||||
|
|
@ -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;
|
||||
};
|
||||
|
|
@ -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]);
|
||||
}
|
||||
|
|
@ -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<AbandonPaymentPayload> {
|
||||
return checkoutHttp.post<AbandonPaymentResponseDto>(
|
||||
CHECKOUT_ENDPOINTS.abandon(paymentId),
|
||||
);
|
||||
},
|
||||
|
||||
/** Stops capacity notifications for this creator; succeeds when not on the list too. */
|
||||
async leaveWaitlist(creatorId: string): Promise<void> {
|
||||
await checkoutHttp.delete<WaitlistLeftResponseDto>(
|
||||
|
|
@ -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<CheckoutResultPayload> {
|
||||
try {
|
||||
|
|
@ -84,7 +98,7 @@ export const checkoutRepository = {
|
|||
} catch (error) {
|
||||
const priceChanged = toPriceChangedPayload(error);
|
||||
if (priceChanged) return priceChanged;
|
||||
throw error;
|
||||
throw toCheckoutError(error);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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<string> = 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;
|
||||
}
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
|
|
|
|||
|
|
@ -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 {};
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue