feat(market): creator dashboard plans and finance, pricing form with promotions, payout account and ledger
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
db0fa7c86e
commit
163005429d
|
|
@ -12,7 +12,8 @@ import type { OnboardingGuardProps } from './types';
|
|||
* then: publishing and prices (R2-CompleteProfile 4.2). It changes nothing in the render, so the
|
||||
* server HTML stays the same for every visitor; once the browser knows the viewer, such a creator
|
||||
* goes to step 5, which returns here when done. The layouts of those routes render it
|
||||
* (`compose`, `dashboard/pricing`); everything else, such as the terms, stays open.
|
||||
* (`compose`, `dashboard/pricing`, the creator's داشبورد); everything else, such as the terms, stays
|
||||
* open.
|
||||
*/
|
||||
export function OnboardingGuard({ children }: OnboardingGuardProps) {
|
||||
const status = useViewerStatus();
|
||||
|
|
|
|||
|
|
@ -61,9 +61,7 @@ export function BottomNav() {
|
|||
)}
|
||||
<NavTab
|
||||
href={
|
||||
isCreator
|
||||
? ROUTES.dashboard.pricing
|
||||
: ROUTES.dashboard.subscriptions
|
||||
isCreator ? ROUTES.dashboard.plans : ROUTES.dashboard.subscriptions
|
||||
}
|
||||
icon="dashboard"
|
||||
label={t('nav.dashboard')}
|
||||
|
|
|
|||
|
|
@ -77,7 +77,7 @@ export function DesktopHeader() {
|
|||
<HeaderNavLink
|
||||
href={
|
||||
isCreator
|
||||
? ROUTES.dashboard.pricing
|
||||
? ROUTES.dashboard.plans
|
||||
: ROUTES.dashboard.subscriptions
|
||||
}
|
||||
label={t('nav.dashboard')}
|
||||
|
|
|
|||
|
|
@ -41,9 +41,11 @@ export const ROUTES = {
|
|||
subscriptions: '/dashboard/subscriptions',
|
||||
transactions: '/dashboard/transactions',
|
||||
following: '/dashboard/following',
|
||||
/** The creator's داشبورد: «طرحهای اشتراک» (the default tab) and «مالی». */
|
||||
plans: '/dashboard/plans',
|
||||
finance: '/dashboard/finance',
|
||||
/** C7, pushed from the «قیمت طرحها» card. */
|
||||
pricing: '/dashboard/pricing',
|
||||
ledger: '/dashboard/finance/ledger',
|
||||
sheba: '/dashboard/finance/sheba',
|
||||
},
|
||||
onboarding: {
|
||||
creatorProfile: '/onboarding/creator-profile',
|
||||
|
|
|
|||
|
|
@ -0,0 +1,140 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FieldError } from '@lumina/island/atoms/field-error';
|
||||
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 { date } from '@lumina/tools/format';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { usePricingPage } from '../../../../../../../features/pricing';
|
||||
import { ConfirmDialog } from './components/ConfirmDialog';
|
||||
import { DateTimeDialog } from './components/DateTimeDialog';
|
||||
import { TierCard } from './components/TierCard';
|
||||
import type { DatePick, PricingFormProps } from './types';
|
||||
|
||||
/**
|
||||
* C7, ویرایش قیمتها: the four period cards and «ذخیره قیمتگذاری» under them. Above the cards,
|
||||
* in order: a failed save with «تلاش دوباره» (۵.۴), the pending-verification note (۱.۳), the lock
|
||||
* notice (۶.۲) or the free-to-edit note (۶.۱). With broken rules a tap on save says so above it
|
||||
* (۳). The confirmation and the date picker are sheets on mobile and modals on desktop.
|
||||
*/
|
||||
export function PricingForm({ layout }: PricingFormProps) {
|
||||
const { t } = useTranslation('pricing');
|
||||
const model = usePricingPage();
|
||||
const [pick, setPick] = useState<DatePick | null>(null);
|
||||
const picked = pick
|
||||
? model.tiers.find((tier) => tier.billingPeriod === pick.period)?.promotion
|
||||
: null;
|
||||
|
||||
return (
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
aria-label={t('form.label')}
|
||||
direction="flex-col"
|
||||
gap="gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
model.save();
|
||||
}}
|
||||
>
|
||||
{model.saveFailed && (
|
||||
<Banner
|
||||
tone="danger"
|
||||
action={
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
icon="refresh"
|
||||
onClick={model.save}
|
||||
>
|
||||
{t('form.retry')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{t('form.network')}
|
||||
</Banner>
|
||||
)}
|
||||
{model.verification !== 'approved' && (
|
||||
<Banner tone="warning" icon="alert">
|
||||
{t('form.pending-note')}
|
||||
</Banner>
|
||||
)}
|
||||
{model.lockedUntil ? (
|
||||
<Banner tone="info" icon="lock">
|
||||
{t('form.locked-note', {
|
||||
date: date(model.lockedUntil, { time: false }),
|
||||
})}
|
||||
</Banner>
|
||||
) : (
|
||||
model.prePurchase && (
|
||||
<FlexBox
|
||||
alignItems="items-start"
|
||||
gap="gap-2"
|
||||
className="rounded-md bg-success-subtle px-3 py-2.5 text-success-text"
|
||||
>
|
||||
<Icon name="check-circle" size={18} className="mt-0.5 flex-none" />
|
||||
<Typography variant="body-sm" color="success">
|
||||
{t('form.pre-purchase-note')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
)
|
||||
)}
|
||||
{model.tiers.map((tier) => (
|
||||
<TierCard
|
||||
key={tier.billingPeriod}
|
||||
tier={tier}
|
||||
model={model}
|
||||
layout={layout}
|
||||
onPickDate={(period, edge) => setPick({ period, edge })}
|
||||
/>
|
||||
))}
|
||||
{model.lockedUntil && (
|
||||
<Typography variant="caption" color="secondary">
|
||||
{t('promotion.locked-live')}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{t('form.existing-note')}
|
||||
</Typography>
|
||||
<FlexBox direction="flex-col" gap="gap-2">
|
||||
{model.isBlocked && <FieldError>{t('form.blocked')}</FieldError>}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
block={layout === 'mobile'}
|
||||
isLoading={model.phase === 'checking'}
|
||||
frozen={model.isBlocked}
|
||||
pressableWhenFrozen
|
||||
>
|
||||
{t('form.save')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
<ConfirmDialog model={model} layout={layout} />
|
||||
<DateTimeDialog
|
||||
layout={layout}
|
||||
pick={pick}
|
||||
value={
|
||||
pick?.edge === 'end'
|
||||
? (picked?.endsAt ?? null)
|
||||
: (picked?.startsAt ?? null)
|
||||
}
|
||||
indefinite={pick?.edge === 'end' ? Boolean(picked?.indefinite) : false}
|
||||
onClose={() => setPick(null)}
|
||||
onConfirm={(iso, indefinite) => {
|
||||
if (!pick) return;
|
||||
if (pick.edge === 'start' && iso)
|
||||
model.setPromotionStart(pick.period, iso);
|
||||
if (pick.edge === 'end')
|
||||
model.setPromotionEnd(pick.period, iso, indefinite);
|
||||
setPick(null);
|
||||
}}
|
||||
/>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
|
||||
import type { PricingFormSkeletonProps } from './types';
|
||||
|
||||
/** C7 before it arrives: four period cards, each a title row, the total field and the promotion row. */
|
||||
export function PricingFormSkeleton({
|
||||
layout,
|
||||
label,
|
||||
delayed,
|
||||
}: PricingFormSkeletonProps) {
|
||||
return (
|
||||
<SkeletonRegion label={label} delayed={delayed}>
|
||||
<FlexBox direction="flex-col" gap="gap-4">
|
||||
{[0, 1, 2, 3].map((card) => (
|
||||
<Card key={card} padding={layout === 'desktop' ? 'lg' : 'md'}>
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<FlexBox
|
||||
justifyContent="justify-between"
|
||||
alignItems="items-center"
|
||||
>
|
||||
<Skeleton width="28%" height={18} />
|
||||
<Skeleton shape="pill" width={44} height={24} />
|
||||
</FlexBox>
|
||||
<Skeleton shape="rect" height={48} />
|
||||
<Skeleton width="45%" />
|
||||
<Skeleton shape="rect" height={44} />
|
||||
</FlexBox>
|
||||
</Card>
|
||||
))}
|
||||
<Skeleton shape="pill" height={52} />
|
||||
</FlexBox>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,155 @@
|
|||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Tag } from '@lumina/island/atoms/tag';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Modal } from '@lumina/island/molecules/modal';
|
||||
import { Sheet } from '@lumina/island/molecules/sheet';
|
||||
import { cn } from '@lumina/island/tools/cn';
|
||||
import { date, percent, price } from '@lumina/tools/format';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { BILLING_PERIOD_MONTHS } from '../../../../../../../../shared/constants';
|
||||
import type { ConfirmDialogProps } from '../types';
|
||||
|
||||
/**
|
||||
* The confirmation on every save (C7 §۵): each offered period, total and per month, in the order
|
||||
* investors see them; a promoted one adds its discount, end and promotional price (۵.۲). Then the
|
||||
* lock warning and the safety valve. «تأیید و ذخیره» saves; «انصراف» or the scrim go back with
|
||||
* everything kept. A bottom sheet on mobile, a modal of 420 on desktop (۸.۲); no ✕.
|
||||
*/
|
||||
export function ConfirmDialog({ model, layout }: ConfirmDialogProps) {
|
||||
const { t } = useTranslation(['pricing', 'common']);
|
||||
const confirmation = model.confirmation;
|
||||
const open = confirmation !== null;
|
||||
const saving = model.phase === 'saving';
|
||||
|
||||
const buttons = (
|
||||
<>
|
||||
<Button
|
||||
variant="primary"
|
||||
size={layout === 'mobile' ? 'lg' : undefined}
|
||||
block
|
||||
isLoading={saving}
|
||||
onClick={model.confirm}
|
||||
>
|
||||
{t('confirm.submit')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size={layout === 'mobile' ? 'lg' : undefined}
|
||||
block
|
||||
disabled={saving}
|
||||
onClick={model.closeConfirmation}
|
||||
>
|
||||
{t('confirm.cancel')}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
const body = confirmation && (
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<FlexBox
|
||||
tag="ul"
|
||||
direction="flex-col"
|
||||
className="rounded-md bg-surface-sunken px-3"
|
||||
>
|
||||
{confirmation.tiers.map((tier, index) => {
|
||||
const months = BILLING_PERIOD_MONTHS[tier.billingPeriod];
|
||||
const view = model.tiers.find(
|
||||
(item) => item.billingPeriod === tier.billingPeriod,
|
||||
);
|
||||
const promo =
|
||||
tier.promotion && view?.promotion.enabled ? view.promotion : null;
|
||||
return (
|
||||
<FlexBox
|
||||
key={tier.billingPeriod}
|
||||
tag="li"
|
||||
direction="flex-col"
|
||||
className={cn(
|
||||
'gap-0.5 py-2.5',
|
||||
index > 0 && 'border-t border-border-subtle',
|
||||
)}
|
||||
>
|
||||
<FlexBox
|
||||
alignItems="items-baseline"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
>
|
||||
<Typography tag="span" className="font-semibold">
|
||||
{t(`common:billing-periods.${tier.billingPeriod}`)}
|
||||
</Typography>
|
||||
<Typography tag="span" variant="body-sm">
|
||||
{t('confirm.row', {
|
||||
total: price(tier.priceToman),
|
||||
perMonth: price(Math.round(tier.priceToman / months)),
|
||||
})}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
{promo && promo.percentValue !== null && (
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
alignItems="items-end"
|
||||
className="gap-0.5"
|
||||
>
|
||||
<FlexBox alignItems="items-center" gap="gap-2">
|
||||
<Tag variant="discount" icon={null}>
|
||||
{promo.indefinite || !promo.endsAt
|
||||
? t('confirm.promotion-open', {
|
||||
percent: percent(promo.percentValue, 0),
|
||||
})
|
||||
: t('confirm.promotion', {
|
||||
percent: percent(promo.percentValue, 0),
|
||||
date: date(promo.endsAt, { time: false }),
|
||||
})}
|
||||
</Tag>
|
||||
</FlexBox>
|
||||
{promo.priceToman !== null &&
|
||||
promo.perMonthToman !== null && (
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="body-sm"
|
||||
className="font-semibold"
|
||||
>
|
||||
{t('confirm.promotion-price', {
|
||||
total: price(promo.priceToman),
|
||||
perMonth: price(promo.perMonthToman),
|
||||
})}
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
)}
|
||||
</FlexBox>
|
||||
);
|
||||
})}
|
||||
</FlexBox>
|
||||
<Typography variant="body-sm" className="font-semibold">
|
||||
{t('confirm.cooldown')}
|
||||
</Typography>
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{t('confirm.safety')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
);
|
||||
|
||||
const onClose = saving ? undefined : model.closeConfirmation;
|
||||
|
||||
return layout === 'mobile' ? (
|
||||
<Sheet
|
||||
open={open}
|
||||
title={t('confirm.title')}
|
||||
footer={buttons}
|
||||
onClose={onClose}
|
||||
>
|
||||
{body}
|
||||
</Sheet>
|
||||
) : (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('confirm.title')}
|
||||
actions={buttons}
|
||||
onClose={onClose}
|
||||
>
|
||||
{body}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
import { DateTime } from '@lumina/island/atoms/date-time';
|
||||
import { FieldError } from '@lumina/island/atoms/field-error';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { cn } from '@lumina/island/tools/cn';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { DateFieldProps } from './types';
|
||||
|
||||
/**
|
||||
* A promotion's start or end (C7 ۴.۲): a button that shows the Shamsi date and time and opens the
|
||||
* picker. Its error sits under it, as a text field's does.
|
||||
*/
|
||||
export function DateField({ id, label, value, error, onOpen }: DateFieldProps) {
|
||||
const { t } = useTranslation('pricing');
|
||||
const errorId = useId();
|
||||
const labelId = useId();
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-1" className="min-w-0 flex-1">
|
||||
<Typography tag="span" id={labelId} variant="caption" color="secondary">
|
||||
{label}
|
||||
</Typography>
|
||||
<FlexBox
|
||||
tag="button"
|
||||
type="button"
|
||||
id={id}
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-2"
|
||||
aria-haspopup="dialog"
|
||||
aria-invalid={error ? true : undefined}
|
||||
aria-describedby={error ? errorId : undefined}
|
||||
aria-labelledby={`${labelId} ${id}`}
|
||||
onClick={onOpen}
|
||||
className={cn(
|
||||
'h-input-height w-full cursor-pointer rounded-md border bg-surface px-3 text-start text-body-md outline-none transition-colors duration-120 ease-standard hover:border-border-strong focus-visible:focus-ring',
|
||||
error ? 'border-danger' : 'border-border-default',
|
||||
)}
|
||||
>
|
||||
<Typography
|
||||
tag="span"
|
||||
color={value ? 'primary' : 'tertiary'}
|
||||
className="truncate"
|
||||
>
|
||||
{value ? <DateTime value={value} /> : t('promotion.not-set')}
|
||||
</Typography>
|
||||
<Icon
|
||||
name="calendar"
|
||||
size={18}
|
||||
className="flex-none text-text-secondary"
|
||||
/>
|
||||
</FlexBox>
|
||||
{error && <FieldError id={errorId}>{error}</FieldError>}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,202 @@
|
|||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { Checkbox } from '@lumina/island/atoms/checkbox';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { GridBox } from '@lumina/island/atoms/grid-box';
|
||||
import { Select } from '@lumina/island/atoms/select';
|
||||
import { Modal } from '@lumina/island/molecules/modal';
|
||||
import { Sheet } from '@lumina/island/molecules/sheet';
|
||||
import { number } from '@lumina/tools/format';
|
||||
import { fromJalali, jalaliMonthLength, toJalali } from '@lumina/tools/jalali';
|
||||
import type { JalaliDateTime } from '@lumina/tools/jalali';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { DateTimeDialogProps } from '../types';
|
||||
|
||||
const MONTHS = Array.from({ length: 12 }, (_, index) => index + 1);
|
||||
const HOURS = Array.from({ length: 24 }, (_, index) => index);
|
||||
const MINUTES = Array.from({ length: 12 }, (_, index) => index * 5).concat(59);
|
||||
/** This year and the next two: a promotion is never set further out. */
|
||||
const YEARS_AHEAD = 2;
|
||||
|
||||
const pad = (value: number) => number(value).padStart(2, '0');
|
||||
|
||||
function nearestMinute(minute: number): number {
|
||||
return MINUTES.reduce((best, option) =>
|
||||
Math.abs(option - minute) < Math.abs(best - minute) ? option : best,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Shamsi date and time picker (C7 ۴.۳): day, month, year, hour and minute, each a native select
|
||||
* (a wheel on phones), and for an end «بدون تاریخ پایان», so ending is one decision in one place.
|
||||
* A bottom sheet on mobile, a centred modal on desktop (۸.۱). «تأیید» sets the field.
|
||||
*/
|
||||
export function DateTimeDialog({
|
||||
layout,
|
||||
pick,
|
||||
value,
|
||||
indefinite,
|
||||
onConfirm,
|
||||
onClose,
|
||||
}: DateTimeDialogProps) {
|
||||
const { t } = useTranslation('pricing');
|
||||
const title =
|
||||
pick?.edge === 'end' ? t('promotion.end') : t('promotion.start');
|
||||
|
||||
return layout === 'mobile' ? (
|
||||
<Sheet
|
||||
open={pick !== null}
|
||||
title={title}
|
||||
closeLabel={t('picker.close')}
|
||||
onClose={onClose}
|
||||
>
|
||||
{pick && (
|
||||
<PickerBody
|
||||
key={`${pick.period}-${pick.edge}`}
|
||||
isEnd={pick.edge === 'end'}
|
||||
value={value}
|
||||
indefinite={indefinite}
|
||||
onConfirm={onConfirm}
|
||||
size="lg"
|
||||
/>
|
||||
)}
|
||||
</Sheet>
|
||||
) : (
|
||||
<Modal
|
||||
open={pick !== null}
|
||||
title={title}
|
||||
closeLabel={t('picker.close')}
|
||||
onClose={onClose}
|
||||
>
|
||||
{pick && (
|
||||
<PickerBody
|
||||
key={`${pick.period}-${pick.edge}`}
|
||||
isEnd={pick.edge === 'end'}
|
||||
value={value}
|
||||
indefinite={indefinite}
|
||||
onConfirm={onConfirm}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
type PickerBodyProps = {
|
||||
isEnd: boolean;
|
||||
value: string | null;
|
||||
indefinite: boolean;
|
||||
onConfirm: (iso: string | null, indefinite: boolean) => void;
|
||||
size?: 'lg';
|
||||
};
|
||||
|
||||
function PickerBody({
|
||||
isEnd,
|
||||
value,
|
||||
indefinite,
|
||||
onConfirm,
|
||||
size,
|
||||
}: PickerBodyProps) {
|
||||
const { t } = useTranslation('pricing');
|
||||
const [parts, setParts] = useState<JalaliDateTime>(() => {
|
||||
const start = toJalali(value ?? new Date());
|
||||
return { ...start, minute: nearestMinute(start.minute) };
|
||||
});
|
||||
const [open, setOpen] = useState(indefinite);
|
||||
const [thisYear] = useState(() => toJalali(new Date()).year);
|
||||
const years = Array.from(
|
||||
{ length: YEARS_AHEAD + 1 },
|
||||
(_, index) => thisYear + index,
|
||||
);
|
||||
if (!years.includes(parts.year)) years.unshift(parts.year);
|
||||
const days = Array.from(
|
||||
{ length: jalaliMonthLength(parts.year, parts.month) },
|
||||
(_, index) => index + 1,
|
||||
);
|
||||
|
||||
const set = (key: keyof JalaliDateTime, next: number) =>
|
||||
setParts((current) => {
|
||||
const updated = { ...current, [key]: next };
|
||||
// 31 اردیبهشت → مهر has 30 days: keep the last one.
|
||||
updated.day = Math.min(
|
||||
updated.day,
|
||||
jalaliMonthLength(updated.year, updated.month),
|
||||
);
|
||||
return updated;
|
||||
});
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-4">
|
||||
<GridBox cols="grid-cols-3" gap="gap-2">
|
||||
<Select
|
||||
label={t('picker.day')}
|
||||
value={String(parts.day)}
|
||||
disabled={open}
|
||||
onChange={(event) => set('day', Number(event.target.value))}
|
||||
options={days.map((day) => ({
|
||||
value: String(day),
|
||||
label: number(day),
|
||||
}))}
|
||||
/>
|
||||
<Select
|
||||
label={t('picker.month')}
|
||||
value={String(parts.month)}
|
||||
disabled={open}
|
||||
onChange={(event) => set('month', Number(event.target.value))}
|
||||
options={MONTHS.map((month) => ({
|
||||
value: String(month),
|
||||
label: t(`picker.months.${month}` as 'picker.months.1'),
|
||||
}))}
|
||||
/>
|
||||
<Select
|
||||
label={t('picker.year')}
|
||||
value={String(parts.year)}
|
||||
disabled={open}
|
||||
onChange={(event) => set('year', Number(event.target.value))}
|
||||
options={years.map((year) => ({
|
||||
value: String(year),
|
||||
label: String(year),
|
||||
}))}
|
||||
/>
|
||||
</GridBox>
|
||||
<GridBox cols="grid-cols-2" gap="gap-2">
|
||||
<Select
|
||||
label={t('picker.hour')}
|
||||
value={String(parts.hour)}
|
||||
disabled={open}
|
||||
onChange={(event) => set('hour', Number(event.target.value))}
|
||||
options={HOURS.map((hour) => ({
|
||||
value: String(hour),
|
||||
label: pad(hour),
|
||||
}))}
|
||||
/>
|
||||
<Select
|
||||
label={t('picker.minute')}
|
||||
value={String(parts.minute)}
|
||||
disabled={open}
|
||||
onChange={(event) => set('minute', Number(event.target.value))}
|
||||
options={MINUTES.map((minute) => ({
|
||||
value: String(minute),
|
||||
label: pad(minute),
|
||||
}))}
|
||||
/>
|
||||
</GridBox>
|
||||
{isEnd && (
|
||||
<Checkbox
|
||||
checked={open}
|
||||
onChange={(event) => setOpen(event.target.checked)}
|
||||
>
|
||||
{t('picker.indefinite')}
|
||||
</Checkbox>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
size={size}
|
||||
block
|
||||
onClick={() => onConfirm(open ? null : fromJalali(parts), open)}
|
||||
>
|
||||
{t('picker.confirm')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
import { Checkbox } from '@lumina/island/atoms/checkbox';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Switch } from '@lumina/island/atoms/switch';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import { price } from '@lumina/tools/format';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { PromotionBlockProps } from '../types';
|
||||
import { DateField } from './DateField';
|
||||
import { useFieldMessage } from './use-field-message';
|
||||
|
||||
/**
|
||||
* A period's تخفیف دورهای (C7 §۴), on the sunken ground inside its card, so it reads as a
|
||||
* different mechanic. Off, it is one switch and a line on what it does (۴.۱). On: the percent,
|
||||
* start and end side by side, «بدون تاریخ پایان», the promotional price and who it applies to
|
||||
* (۴.۲, ۴.۷). The same switch ends it, from the next save (۴.۴, ۴.۵). It stays live during the
|
||||
* 7-day lock (۶.۲).
|
||||
*/
|
||||
export function PromotionBlock({
|
||||
tier,
|
||||
model,
|
||||
onPickDate,
|
||||
}: PromotionBlockProps) {
|
||||
const { t } = useTranslation(['pricing', 'common']);
|
||||
const message = useFieldMessage();
|
||||
const promo = tier.promotion;
|
||||
const period = tier.billingPeriod;
|
||||
const periodLabel = t(`common:billing-periods.${period}`);
|
||||
|
||||
return (
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
gap="gap-3"
|
||||
className="rounded-md bg-surface-sunken p-3"
|
||||
>
|
||||
<Switch
|
||||
checked={promo.enabled}
|
||||
onCheckedChange={(enabled) =>
|
||||
model.setPromotionEnabled(period, enabled)
|
||||
}
|
||||
aria-label={t('promotion.switch', { period: periodLabel })}
|
||||
className="-my-2 w-full"
|
||||
>
|
||||
{t('promotion.title')}
|
||||
</Switch>
|
||||
{!promo.enabled ? (
|
||||
<Typography variant="caption" color="secondary">
|
||||
{t('promotion.intro')}
|
||||
</Typography>
|
||||
) : (
|
||||
<>
|
||||
<TextInput
|
||||
id={promo.percentId}
|
||||
label={t('promotion.percent')}
|
||||
inputMode="numeric"
|
||||
dir="ltr"
|
||||
suffix={t('promotion.percent-sign')}
|
||||
value={promo.percent}
|
||||
onChange={(event) =>
|
||||
model.setPromotionPercent(period, event.target.value)
|
||||
}
|
||||
error={message(promo.percentMessage)}
|
||||
className="max-w-40"
|
||||
/>
|
||||
<FlexBox gap="gap-3" wrap="flex-wrap">
|
||||
<DateField
|
||||
id={`${promo.endsAtId}-start`}
|
||||
label={t('promotion.start')}
|
||||
value={promo.startsAt}
|
||||
onOpen={() => onPickDate(period, 'start')}
|
||||
/>
|
||||
{!promo.indefinite && (
|
||||
<DateField
|
||||
id={promo.endsAtId}
|
||||
label={t('promotion.end')}
|
||||
value={promo.endsAt}
|
||||
error={message(promo.endsAtMessage)}
|
||||
onOpen={() => onPickDate(period, 'end')}
|
||||
/>
|
||||
)}
|
||||
</FlexBox>
|
||||
<Checkbox
|
||||
checked={promo.indefinite}
|
||||
onChange={(event) =>
|
||||
model.setPromotionEnd(period, promo.endsAt, event.target.checked)
|
||||
}
|
||||
>
|
||||
{t('promotion.indefinite')}
|
||||
</Checkbox>
|
||||
{promo.priceToman !== null && promo.perMonthToman !== null && (
|
||||
<Typography variant="body-sm" className="font-semibold">
|
||||
{t('promotion.price', {
|
||||
total: price(promo.priceToman),
|
||||
perMonth: price(promo.perMonthToman),
|
||||
})}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="caption" color="secondary">
|
||||
{t('promotion.scope-note')}
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Switch } from '@lumina/island/atoms/switch';
|
||||
import { Tag } from '@lumina/island/atoms/tag';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import { date, number, percent, price } from '@lumina/tools/format';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { TierCardProps } from '../types';
|
||||
import { PromotionBlock } from './PromotionBlock';
|
||||
import { WarnNote } from './WarnNote';
|
||||
import { useFieldMessage } from './use-field-message';
|
||||
|
||||
/**
|
||||
* One period (C7 §۲): its name and switch (monthly has «الزامی» and no switch, ۱.۱), the period
|
||||
* total with its floor before typing and its per-month equivalent after (۲.۱), the rule it
|
||||
* breaks in place of either (۳). Switched off, it collapses to its switch row, with a note when
|
||||
* subscribers run on it (۲.۲). During the lock the total and the switch are read-only at 50%; the
|
||||
* promotion stays live (۶.۲).
|
||||
*/
|
||||
export function TierCard({ tier, model, layout, onPickDate }: TierCardProps) {
|
||||
const { t } = useTranslation(['pricing', 'common']);
|
||||
const message = useFieldMessage();
|
||||
const headingId = useId();
|
||||
const period = tier.billingPeriod;
|
||||
const periodLabel = t(`common:billing-periods.${period}`);
|
||||
const locked = model.lockedUntil !== null;
|
||||
const priceError = message(tier.priceMessage);
|
||||
const promoPercent = tier.promotion.enabled
|
||||
? tier.promotion.percentValue
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Card
|
||||
tag="section"
|
||||
aria-labelledby={headingId}
|
||||
padding={layout === 'desktop' ? 'lg' : 'md'}
|
||||
>
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
>
|
||||
<FlexBox alignItems="items-center" gap="gap-2">
|
||||
<Typography tag="h3" id={headingId} variant="heading-sm">
|
||||
{periodLabel}
|
||||
</Typography>
|
||||
{tier.mandatory && (
|
||||
<Tag variant="soft" icon={null}>
|
||||
{t('form.required-tag')}
|
||||
</Tag>
|
||||
)}
|
||||
{promoPercent !== null && tier.enabled && (
|
||||
<Tag variant="discount" icon={null}>
|
||||
{t('card.discount', { percent: percent(promoPercent, 0) })}
|
||||
</Tag>
|
||||
)}
|
||||
</FlexBox>
|
||||
{!tier.mandatory && (
|
||||
<Switch
|
||||
checked={tier.enabled}
|
||||
locked={locked}
|
||||
onCheckedChange={(enabled) => model.setEnabled(period, enabled)}
|
||||
aria-label={t('form.offer', { period: periodLabel })}
|
||||
className="-my-2"
|
||||
/>
|
||||
)}
|
||||
</FlexBox>
|
||||
{tier.mandatory && (
|
||||
<Typography variant="caption" color="secondary" className="-mt-2">
|
||||
{t('form.monthly-note')}
|
||||
</Typography>
|
||||
)}
|
||||
{tier.disableNoteCount !== null && (
|
||||
<WarnNote>
|
||||
{t('form.disable-note', { count: number(tier.disableNoteCount) })}
|
||||
</WarnNote>
|
||||
)}
|
||||
{tier.enabled && (
|
||||
<>
|
||||
<FlexBox direction="flex-col" gap="gap-1">
|
||||
<TextInput
|
||||
id={tier.priceId}
|
||||
label={t('form.price-label')}
|
||||
aria-label={t('form.price-label-of', { period: periodLabel })}
|
||||
inputMode="numeric"
|
||||
suffix={t('form.currency')}
|
||||
value={tier.priceText}
|
||||
onChange={(event) => model.setPrice(period, event.target.value)}
|
||||
onBlur={() => model.blurPrice(period)}
|
||||
error={priceError}
|
||||
hint={
|
||||
tier.perMonthToman === null
|
||||
? t('form.floor', { floor: price(tier.floorTomanPerMonth) })
|
||||
: t('form.per-month', { amount: price(tier.perMonthToman) })
|
||||
}
|
||||
locked={locked}
|
||||
lockedNote={
|
||||
locked && model.lockedUntil
|
||||
? t('form.locked-field', {
|
||||
date: date(model.lockedUntil, { time: false }),
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
className={locked ? 'opacity-(--opacity-dimmed)' : undefined}
|
||||
/>
|
||||
{priceError && tier.perMonthToman !== null && (
|
||||
<Typography variant="caption" color="secondary">
|
||||
{t('form.per-month', { amount: price(tier.perMonthToman) })}
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
<PromotionBlock
|
||||
tier={tier}
|
||||
model={model}
|
||||
layout={layout}
|
||||
onPickDate={onPickDate}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</FlexBox>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
/** An amber note on the amber tint, readable on white: a period switched off with subscribers. */
|
||||
export function WarnNote({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<FlexBox
|
||||
alignItems="items-start"
|
||||
gap="gap-2"
|
||||
className="rounded-md bg-warning-subtle px-3 py-2 text-warning-text"
|
||||
>
|
||||
<Icon name="alert" size={16} className="mt-1 flex-none" />
|
||||
<Typography variant="caption" color="warning">
|
||||
{children}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export type DateFieldProps = {
|
||||
id: string;
|
||||
label: string;
|
||||
value: string | null;
|
||||
error?: string;
|
||||
onOpen: () => void;
|
||||
};
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import { price } from '@lumina/tools/format';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { PricingFieldMessage } from '../../../../../../../../features/pricing';
|
||||
|
||||
/** A field's message as shown: a broken rule worded with its figures, or the API's own text. */
|
||||
export function useFieldMessage() {
|
||||
const { t } = useTranslation(['pricing', 'common']);
|
||||
|
||||
return (message: PricingFieldMessage | null): string | undefined => {
|
||||
if (!message) return undefined;
|
||||
if (message.kind === 'server') return message.message;
|
||||
const { issue } = message;
|
||||
switch (issue.code) {
|
||||
case 'required':
|
||||
return t('form.errors.required');
|
||||
case 'below-floor':
|
||||
return t('form.errors.below-floor', { floor: price(issue.floor) });
|
||||
case 'per-month-increase':
|
||||
return t('form.errors.per-month-increase', {
|
||||
amount: price(issue.amount),
|
||||
period: t(`common:billing-periods.${issue.shorter}`),
|
||||
shorter: price(issue.shorterAmount),
|
||||
});
|
||||
case 'promo-percent':
|
||||
return t('form.errors.promo-percent');
|
||||
case 'promo-floor':
|
||||
return t('form.errors.promo-floor', {
|
||||
amount: price(issue.amount),
|
||||
floor: price(issue.floor),
|
||||
});
|
||||
case 'promo-end-required':
|
||||
return t('form.errors.promo-end-required');
|
||||
case 'promo-range':
|
||||
return t('form.errors.promo-range');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export { PricingForm } from './PricingForm';
|
||||
export { PricingFormSkeleton } from './PricingFormSkeleton';
|
||||
export type { PricingFormProps, PricingFormSkeletonProps } from './types';
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
import type { BillingPeriod } from '../../../../../../../shared/constants';
|
||||
import type {
|
||||
PricingPageModel,
|
||||
PricingTierView,
|
||||
} from '../../../../../../../features/pricing';
|
||||
|
||||
export type PricingFormProps = {
|
||||
/** mobile: bottom sheets. desktop: centred modals, cards padded lg (۸). */
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
||||
export type PricingFormSkeletonProps = PricingFormProps & {
|
||||
/** Hidden status text: «در حال بارگذاری قیمتگذاری…». */
|
||||
label: string;
|
||||
/** Fades in after 300ms, so a fast route never flashes grey. loading.tsx only. */
|
||||
delayed?: boolean;
|
||||
};
|
||||
|
||||
export type TierCardProps = {
|
||||
tier: PricingTierView;
|
||||
model: PricingPageModel;
|
||||
layout: 'mobile' | 'desktop';
|
||||
/** Opens the date picker for this period's promotion. */
|
||||
onPickDate: (period: BillingPeriod, edge: 'start' | 'end') => void;
|
||||
};
|
||||
|
||||
export type PromotionBlockProps = TierCardProps;
|
||||
|
||||
/** Which date the picker is choosing, and for which period. */
|
||||
export type DatePick = { period: BillingPeriod; edge: 'start' | 'end' };
|
||||
|
||||
export type DateTimeDialogProps = {
|
||||
layout: 'mobile' | 'desktop';
|
||||
pick: DatePick | null;
|
||||
/** The value it opens at: the field's, else now. */
|
||||
value: string | null;
|
||||
/** End only: «بدون تاریخ پایان» ticked. */
|
||||
indefinite: boolean;
|
||||
onConfirm: (iso: string | null, indefinite: boolean) => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export type ConfirmDialogProps = {
|
||||
model: PricingPageModel;
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
'use client';
|
||||
|
||||
import { Amount } from '@lumina/island/atoms/amount';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Link } from '@lumina/island/atoms/link';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
import { InfoTip } from '@lumina/island/molecules/info-tip';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
import { date } from '@lumina/tools/format';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import {
|
||||
PAYOUT_ACCOUNT_ANCHOR,
|
||||
useBalancePart,
|
||||
} from '../../../../../../../features/finance';
|
||||
import { PAYOUT_WEEKDAY } from '../../../../../../../shared/constants';
|
||||
import type { BalanceSummaryProps } from './types';
|
||||
|
||||
/**
|
||||
* مالی › the balance (C20 §۱): قابل واریز, the one large figure on the page, red with its minus and
|
||||
* the reason when a refund took it below zero (۱.۲); در حال واریز under it only while a payout is
|
||||
* in progress; مجموع واریزشده under a hairline. Each has its ⓘ. Under the card, the next-payout
|
||||
* line (Appendix B §۳): the day, a link to register a شبا, nothing to pay, or the suspension.
|
||||
*/
|
||||
export function BalanceSummary({ layout }: BalanceSummaryProps) {
|
||||
const { t } = useTranslation(['finance', 'common']);
|
||||
const { balance } = useBalancePart();
|
||||
const headingId = useId();
|
||||
const negative = balance.availableToman < 0;
|
||||
const next = balance.nextPayout;
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<Card
|
||||
tag="section"
|
||||
aria-labelledby={headingId}
|
||||
padding={layout === 'desktop' ? 'lg' : 'md'}
|
||||
>
|
||||
<FlexBox direction="flex-col" className="gap-0.5">
|
||||
<FlexBox alignItems="items-center">
|
||||
<Typography
|
||||
tag="h2"
|
||||
id={headingId}
|
||||
variant="caption"
|
||||
color="secondary"
|
||||
>
|
||||
{t('balance.available')}
|
||||
</Typography>
|
||||
<InfoTip label={t('balance.available-info')}>
|
||||
{t('balance.available-tip')}
|
||||
</InfoTip>
|
||||
</FlexBox>
|
||||
<Amount
|
||||
value={balance.availableToman}
|
||||
size="figure"
|
||||
tone={negative ? 'negative' : 'figure'}
|
||||
signed={negative}
|
||||
currency={t('common:currency')}
|
||||
/>
|
||||
{negative ? (
|
||||
<Typography variant="caption" color="secondary">
|
||||
{t('balance.negative-note')}
|
||||
</Typography>
|
||||
) : (
|
||||
balance.inTransitToman > 0 && (
|
||||
<Typography variant="caption" color="secondary">
|
||||
{t('balance.in-transit')}{' '}
|
||||
<Amount
|
||||
value={balance.inTransitToman}
|
||||
size="caption"
|
||||
tone="mute"
|
||||
currency={t('common:currency')}
|
||||
/>
|
||||
</Typography>
|
||||
)
|
||||
)}
|
||||
</FlexBox>
|
||||
<Element
|
||||
tag="hr"
|
||||
className="mt-3 mb-2 border-0 border-t border-border-subtle"
|
||||
/>
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
>
|
||||
<FlexBox alignItems="items-center">
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('balance.paid-total')}
|
||||
</Typography>
|
||||
<InfoTip label={t('balance.paid-total-info')}>
|
||||
{t('balance.paid-total-tip')}
|
||||
</InfoTip>
|
||||
</FlexBox>
|
||||
<Amount
|
||||
value={balance.paidTotalToman}
|
||||
currency={t('common:currency')}
|
||||
/>
|
||||
</FlexBox>
|
||||
</Card>
|
||||
{next.state !== 'hidden' && (
|
||||
<FlexBox alignItems="items-center" gap="gap-2" className="px-1">
|
||||
<Icon
|
||||
name="clock"
|
||||
size={16}
|
||||
className="flex-none text-text-secondary"
|
||||
/>
|
||||
{next.state === 'no_account' ? (
|
||||
<Link href={`#${PAYOUT_ACCOUNT_ANCHOR}`} className="text-caption">
|
||||
{t('balance.next.no_account')}
|
||||
</Link>
|
||||
) : (
|
||||
<Typography
|
||||
variant="caption"
|
||||
color={next.state === 'scheduled' ? 'primary' : 'secondary'}
|
||||
>
|
||||
{next.state === 'scheduled' && next.date
|
||||
? t('balance.next.scheduled', {
|
||||
day: t(`weekdays.${PAYOUT_WEEKDAY}`),
|
||||
date: date(next.date, { time: false }),
|
||||
})
|
||||
: t(
|
||||
`balance.next.${next.state === 'scheduled' ? 'nothing' : next.state}`,
|
||||
)}
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
)}
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
|
||||
import type { BalanceSummarySkeletonProps } from './types';
|
||||
|
||||
/** The balance before it arrives: the label, the figure, a line, the total row and the next-payout line. */
|
||||
export function BalanceSummarySkeleton({
|
||||
layout,
|
||||
label,
|
||||
delayed,
|
||||
}: BalanceSummarySkeletonProps) {
|
||||
return (
|
||||
<SkeletonRegion label={label} delayed={delayed}>
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<Card padding={layout === 'desktop' ? 'lg' : 'md'}>
|
||||
<FlexBox direction="flex-col" gap="gap-2">
|
||||
<Skeleton width="22%" />
|
||||
<Skeleton width="55%" height={36} />
|
||||
<Skeleton width="40%" />
|
||||
</FlexBox>
|
||||
<FlexBox justifyContent="justify-between" className="mt-5">
|
||||
<Skeleton width="30%" />
|
||||
<Skeleton width="25%" />
|
||||
</FlexBox>
|
||||
</Card>
|
||||
<Skeleton width="45%" className="mx-1" />
|
||||
</FlexBox>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export { BalanceSummary } from './BalanceSummary';
|
||||
export { BalanceSummarySkeleton } from './BalanceSummarySkeleton';
|
||||
export type { BalanceSummaryProps, BalanceSummarySkeletonProps } from './types';
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
export type BalanceSummaryProps = {
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
||||
export type BalanceSummarySkeletonProps = BalanceSummaryProps & {
|
||||
/** Hidden status text: «در حال بارگذاری موجودی…». */
|
||||
label: string;
|
||||
/** Fades in after 300ms, so a fast route never flashes grey. loading.tsx only. */
|
||||
delayed?: boolean;
|
||||
};
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
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 { Lightbox } from '@lumina/island/organisms/lightbox';
|
||||
import { price } from '@lumina/tools/format';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import {
|
||||
LEDGER_FILTERS,
|
||||
useLedgerPart,
|
||||
} from '../../../../../../../features/finance';
|
||||
import { LedgerDetail } from './components/LedgerDetail';
|
||||
import { LedgerRow } from './components/LedgerRow';
|
||||
import type { LedgerProps } from './types';
|
||||
|
||||
/**
|
||||
* مالی › گردش حساب (C20 §۲): «همه» or «واریزها», newest first, 20 at a time; the rows stay while a
|
||||
* tab or the next page loads, and a failed page says so in place of «نمایش بیشتر» (۲.۵). Each tab
|
||||
* has its own empty line (۱.۳, ۲.۳). A row opens its details; an image receipt opens in the
|
||||
* lightbox (۳.۷).
|
||||
*/
|
||||
export function Ledger({ layout }: LedgerProps) {
|
||||
const { t } = useTranslation(['finance', 'errors']);
|
||||
const model = useLedgerPart();
|
||||
const headingId = useId();
|
||||
const receipt = model.lightboxReceipt;
|
||||
const receiptRow = model.detail?.kind === 'payout' ? model.detail : null;
|
||||
|
||||
return (
|
||||
<Card
|
||||
tag="section"
|
||||
aria-labelledby={headingId}
|
||||
aria-busy={model.isFiltering}
|
||||
padding="none"
|
||||
>
|
||||
<FlexBox direction="flex-col" gap="gap-2" className="px-4 pt-3.5 pb-2">
|
||||
<Typography tag="h2" id={headingId} variant="heading-sm">
|
||||
{t('ledger.title')}
|
||||
</Typography>
|
||||
<FilterChips
|
||||
label={t('ledger.filter')}
|
||||
size="sm"
|
||||
options={LEDGER_FILTERS.map((value) => ({
|
||||
value,
|
||||
label: t(`ledger.filters.${value}`),
|
||||
}))}
|
||||
value={model.filter}
|
||||
onChange={model.setFilter}
|
||||
/>
|
||||
</FlexBox>
|
||||
{model.isEmpty ? (
|
||||
<EmptyState
|
||||
title={t(`ledger.empty.${model.filter}`)}
|
||||
icon={model.filter === 'payouts' ? 'wallet' : 'receipt'}
|
||||
size="compact"
|
||||
className="px-4 pb-6"
|
||||
/>
|
||||
) : (
|
||||
<FlexBox
|
||||
tag="ul"
|
||||
direction="flex-col"
|
||||
className="border-t border-border-subtle"
|
||||
>
|
||||
{model.rows.map((row) => (
|
||||
<LedgerRow
|
||||
key={row.id}
|
||||
row={row}
|
||||
isOpen={
|
||||
layout === 'desktop' &&
|
||||
model.isDetailOpen &&
|
||||
model.detail?.id === row.id
|
||||
}
|
||||
onOpen={() => model.openDetail(row)}
|
||||
/>
|
||||
))}
|
||||
</FlexBox>
|
||||
)}
|
||||
{model.loadMoreError ? (
|
||||
<FlexBox className="border-t border-border-subtle p-3">
|
||||
<ErrorState
|
||||
kind={model.loadMoreError}
|
||||
size="inline"
|
||||
title={t(`errors:fallback.${model.loadMoreError}.title`)}
|
||||
description={t('ledger.more-failed')}
|
||||
onRetry={model.loadMore}
|
||||
retryLabel={t('errors:fallback.retry')}
|
||||
retryingLabel={t('errors:fallback.retrying')}
|
||||
retrying={model.isLoadingMore}
|
||||
/>
|
||||
</FlexBox>
|
||||
) : (
|
||||
model.hasMore && (
|
||||
<FlexBox className="border-t border-border-subtle p-3">
|
||||
<Button
|
||||
variant="secondary"
|
||||
block
|
||||
onClick={model.loadMore}
|
||||
isLoading={model.isLoadingMore}
|
||||
>
|
||||
{t('ledger.more')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
)
|
||||
)}
|
||||
<LedgerDetail model={model} layout={layout} />
|
||||
{receipt && (
|
||||
<Lightbox
|
||||
open
|
||||
images={[
|
||||
{
|
||||
src: receipt.url,
|
||||
alt: t('ledger.lightbox.alt', {
|
||||
amount: price(Math.abs(receiptRow?.amountToman ?? 0)),
|
||||
}),
|
||||
},
|
||||
]}
|
||||
onClose={model.closeLightbox}
|
||||
zoomable
|
||||
onDownload={() => window.location.assign(receipt.downloadUrl)}
|
||||
labels={{
|
||||
dialog: t('ledger.lightbox.dialog'),
|
||||
close: t('ledger.lightbox.close'),
|
||||
back: t('ledger.lightbox.back'),
|
||||
previous: t('ledger.lightbox.previous'),
|
||||
next: t('ledger.lightbox.next'),
|
||||
zoomIn: t('ledger.lightbox.zoom-in'),
|
||||
zoomOut: t('ledger.lightbox.zoom-out'),
|
||||
download: t('ledger.lightbox.download'),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
|
||||
import type { LedgerSkeletonProps } from './types';
|
||||
|
||||
/** گردش حساب before it arrives: its title, the two tabs and four 60px rows. */
|
||||
export function LedgerSkeleton({ label, delayed }: LedgerSkeletonProps) {
|
||||
return (
|
||||
<SkeletonRegion label={label} delayed={delayed}>
|
||||
<Card padding="none">
|
||||
<FlexBox direction="flex-col" gap="gap-3" className="px-4 pt-4 pb-3">
|
||||
<Skeleton width="30%" height={16} />
|
||||
<FlexBox gap="gap-2">
|
||||
<Skeleton shape="pill" width={56} height={36} />
|
||||
<Skeleton shape="pill" width={72} height={36} />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
{[0, 1, 2, 3].map((row) => (
|
||||
<FlexBox
|
||||
key={row}
|
||||
direction="flex-col"
|
||||
justifyContent="justify-center"
|
||||
gap="gap-2"
|
||||
className="min-h-15 border-t border-border-subtle px-4 py-2"
|
||||
>
|
||||
<FlexBox justifyContent="justify-between">
|
||||
<Skeleton width="30%" />
|
||||
<Skeleton width="22%" />
|
||||
</FlexBox>
|
||||
<Skeleton width="55%" />
|
||||
</FlexBox>
|
||||
))}
|
||||
</Card>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,263 @@
|
|||
import { Amount } from '@lumina/island/atoms/amount';
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FieldError } from '@lumina/island/atoms/field-error';
|
||||
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, percent } from '@lumina/tools/format';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { LedgerItemPayload } from '../../../../../../../../features/finance';
|
||||
import { maskIban } from '../../../../../../../../shared/utils';
|
||||
import type { LedgerDetailProps } from '../types';
|
||||
|
||||
function Divider() {
|
||||
return (
|
||||
<Element
|
||||
tag="div"
|
||||
aria-hidden
|
||||
className="my-2 border-t border-border-subtle"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A row's details (C20 §۳): a bottom sheet on mobile, a side panel on desktop (۶.۲), closed with
|
||||
* ✕, Escape or the scrim. Every figure is the one stored with the entry, never today's. A payout
|
||||
* always carries its receipt buttons, «مشاهده رسید» first; a receipt that won't show says so under
|
||||
* them, and they stay as the retry (۳.۸).
|
||||
*/
|
||||
export function LedgerDetail({ model, layout }: LedgerDetailProps) {
|
||||
const { t } = useTranslation(['finance', 'common']);
|
||||
const row = model.detail;
|
||||
const currency = t('common:currency');
|
||||
const username = (name: string | null) => (
|
||||
<Element tag="bdi" dir="ltr">
|
||||
@{name ?? t('ledger.unknown-subscriber')}
|
||||
</Element>
|
||||
);
|
||||
const period = (value: string | null) =>
|
||||
value ? t(`common:billing-periods.${value as 'monthly'}`) : '—';
|
||||
|
||||
const body = (item: LedgerItemPayload): ReactNode => {
|
||||
switch (item.kind) {
|
||||
case 'income':
|
||||
return (
|
||||
<>
|
||||
<DetailRow label={t('ledger.detail.plan-price')}>
|
||||
<Amount value={item.planPriceToman} currency={currency} />
|
||||
</DetailRow>
|
||||
{item.discountPercent !== null && (
|
||||
<DetailRow label={t('ledger.detail.discount')}>
|
||||
{percent(item.discountPercent, 0)}
|
||||
</DetailRow>
|
||||
)}
|
||||
<DetailRow label={t('ledger.detail.paid')}>
|
||||
<Amount value={item.paidToman} currency={currency} />
|
||||
</DetailRow>
|
||||
<DetailRow
|
||||
label={t('ledger.detail.commission', {
|
||||
percent: percent(item.commissionPercent, 0),
|
||||
})}
|
||||
>
|
||||
<Amount
|
||||
value={-item.commissionToman}
|
||||
signed
|
||||
currency={currency}
|
||||
/>
|
||||
</DetailRow>
|
||||
<Divider />
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
>
|
||||
<Typography tag="dt" variant="body-md" className="font-semibold">
|
||||
{t('ledger.detail.share')}
|
||||
</Typography>
|
||||
<Element tag="dd" className="m-0">
|
||||
<Amount
|
||||
value={item.shareToman}
|
||||
size="title"
|
||||
currency={currency}
|
||||
/>
|
||||
</Element>
|
||||
</FlexBox>
|
||||
<Divider />
|
||||
<DetailRow label={t('ledger.detail.subscriber')}>
|
||||
{username(item.subscriberUsername)}
|
||||
</DetailRow>
|
||||
<DetailRow label={t('ledger.detail.plan')}>
|
||||
{period(item.billingPeriod)}
|
||||
</DetailRow>
|
||||
<DetailRow label={t('ledger.detail.paid-at')}>
|
||||
{date(item.occurredAt)}
|
||||
</DetailRow>
|
||||
</>
|
||||
);
|
||||
case 'refund_deduction':
|
||||
return (
|
||||
<>
|
||||
<DetailRow label={t('ledger.detail.subscriber')}>
|
||||
{username(item.subscriberUsername)}
|
||||
</DetailRow>
|
||||
<DetailRow label={t('ledger.detail.plan')}>
|
||||
{period(item.billingPeriod)}
|
||||
</DetailRow>
|
||||
{item.originalPaidAt && (
|
||||
<DetailRow label={t('ledger.detail.original-paid-at')}>
|
||||
{date(item.originalPaidAt, { time: false })}
|
||||
</DetailRow>
|
||||
)}
|
||||
<DetailRow label={t('ledger.detail.refunded')}>
|
||||
<Amount value={item.refundedToman} currency={currency} />
|
||||
</DetailRow>
|
||||
<DetailRow label={t('ledger.detail.deducted')}>
|
||||
<Amount value={-item.deductedToman} signed currency={currency} />
|
||||
</DetailRow>
|
||||
<DetailRow label={t('ledger.detail.date')}>
|
||||
{date(item.occurredAt, { time: false })}
|
||||
</DetailRow>
|
||||
</>
|
||||
);
|
||||
case 'correction':
|
||||
return (
|
||||
<>
|
||||
<DetailRow label={t('ledger.detail.amount')}>
|
||||
<Amount value={item.amountToman} signed currency={currency} />
|
||||
</DetailRow>
|
||||
<FlexBox direction="flex-col" gap="gap-1" className="py-2">
|
||||
<Typography tag="dt" variant="body-sm" color="secondary">
|
||||
{t('ledger.detail.reason')}
|
||||
</Typography>
|
||||
<Typography tag="dd" variant="body-md" className="m-0">
|
||||
{item.reason}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
<DetailRow label={t('ledger.detail.date')}>
|
||||
{date(item.occurredAt, { time: false })}
|
||||
</DetailRow>
|
||||
</>
|
||||
);
|
||||
case 'payout':
|
||||
return (
|
||||
<>
|
||||
<DetailRow label={t('ledger.detail.amount')}>
|
||||
<Amount
|
||||
value={Math.abs(item.amountToman)}
|
||||
currency={currency}
|
||||
struck={item.status === 'cancelled'}
|
||||
/>
|
||||
</DetailRow>
|
||||
<DetailRow label={t('ledger.detail.status')}>
|
||||
{item.status === 'completed' ? (
|
||||
t('ledger.status.completed')
|
||||
) : (
|
||||
<StatusBadge status={`payout.${item.status}`}>
|
||||
{t(`ledger.status.${item.status}`)}
|
||||
</StatusBadge>
|
||||
)}
|
||||
</DetailRow>
|
||||
<DetailRow label={t('ledger.detail.created')}>
|
||||
{date(item.occurredAt)}
|
||||
</DetailRow>
|
||||
{item.status === 'completed' && item.completedAt && (
|
||||
<DetailRow label={t('ledger.detail.completed')}>
|
||||
{date(item.completedAt, { time: false })}
|
||||
</DetailRow>
|
||||
)}
|
||||
<DetailRow label={t('ledger.detail.destination')}>
|
||||
<Element
|
||||
tag="bdi"
|
||||
dir="ltr"
|
||||
className="font-latin whitespace-nowrap tabular-nums"
|
||||
>
|
||||
{maskIban(item.ibanCheckDigits, item.ibanTail)}
|
||||
</Element>
|
||||
</DetailRow>
|
||||
{item.status === 'cancelled' && (
|
||||
<>
|
||||
{item.cancelledAt && (
|
||||
<DetailRow label={t('ledger.detail.cancelled')}>
|
||||
{date(item.cancelledAt, { time: false })}
|
||||
</DetailRow>
|
||||
)}
|
||||
{item.cancelReason && (
|
||||
<DetailRow label={t('ledger.detail.reason')}>
|
||||
{item.cancelReason}
|
||||
</DetailRow>
|
||||
)}
|
||||
<Typography
|
||||
tag="div"
|
||||
variant="body-sm"
|
||||
color="secondary"
|
||||
className="pt-2"
|
||||
>
|
||||
{t('ledger.detail.returned')}
|
||||
</Typography>
|
||||
</>
|
||||
)}
|
||||
{item.status === 'in_progress' && (
|
||||
<Typography
|
||||
tag="div"
|
||||
variant="body-sm"
|
||||
color="secondary"
|
||||
className="pt-2"
|
||||
>
|
||||
{t('ledger.detail.timing')}
|
||||
</Typography>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const receipt = row?.kind === 'payout' ? row.receipt : null;
|
||||
const footer = receipt ? (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size={layout === 'mobile' ? 'lg' : undefined}
|
||||
block
|
||||
icon="eye"
|
||||
isLoading={model.isReceiptLoading}
|
||||
onClick={() => model.viewReceipt(receipt)}
|
||||
>
|
||||
{t('ledger.detail.view-receipt')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size={layout === 'mobile' ? 'lg' : undefined}
|
||||
block
|
||||
icon="download"
|
||||
onClick={() => window.location.assign(receipt.downloadUrl)}
|
||||
>
|
||||
{t('ledger.detail.download-receipt')}
|
||||
</Button>
|
||||
{model.receiptFailed && (
|
||||
<FieldError>{t('ledger.detail.receipt-failed')}</FieldError>
|
||||
)}
|
||||
</>
|
||||
) : undefined;
|
||||
|
||||
return (
|
||||
<Sheet
|
||||
placement={layout === 'mobile' ? 'bottom' : 'side'}
|
||||
open={model.isDetailOpen}
|
||||
title={row ? t(`ledger.detail.titles.${row.kind}`) : ''}
|
||||
closeLabel={t('ledger.detail.close')}
|
||||
onClose={model.closeDetail}
|
||||
footer={footer}
|
||||
>
|
||||
{row && (
|
||||
<Element tag="dl" className="m-0">
|
||||
{body(row)}
|
||||
</Element>
|
||||
)}
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
import { Amount } from '@lumina/island/atoms/amount';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Separator } from '@lumina/island/atoms/separator';
|
||||
import { StatusBadge } from '@lumina/island/atoms/status-badge';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
import { cn } from '@lumina/island/tools/cn';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { LedgerRowProps } from '../types';
|
||||
import { useLedgerRowText } from './use-ledger-row-text';
|
||||
|
||||
/**
|
||||
* One line of گردش حساب (C20 ۲.۱): what it is and its signed amount, then who or where, what, and
|
||||
* the date. The whole row is one button (at least 60px) that opens its details. Only an in-progress
|
||||
* or cancelled payout has a pill; a cancelled one's amount is struck, since it never left.
|
||||
*/
|
||||
export function LedgerRow({ row, isOpen, onOpen }: LedgerRowProps) {
|
||||
const { t } = useTranslation('finance');
|
||||
const text = useLedgerRowText()(row);
|
||||
const cancelled = row.kind === 'payout' && row.status === 'cancelled';
|
||||
const pill =
|
||||
row.kind === 'payout' && row.status !== 'completed' ? row.status : null;
|
||||
const meta = [
|
||||
text.who && (
|
||||
<Element key="who" tag="bdi" dir="ltr">
|
||||
@{text.who}
|
||||
</Element>
|
||||
),
|
||||
text.what && (
|
||||
<Typography
|
||||
key="what"
|
||||
tag="span"
|
||||
variant="inherit"
|
||||
color="inherit"
|
||||
className="truncate"
|
||||
>
|
||||
{text.what}
|
||||
</Typography>
|
||||
),
|
||||
<Typography
|
||||
key="when"
|
||||
tag="span"
|
||||
variant="inherit"
|
||||
color="inherit"
|
||||
className="flex-none"
|
||||
>
|
||||
{text.when}
|
||||
</Typography>,
|
||||
].filter(Boolean);
|
||||
|
||||
return (
|
||||
<Element
|
||||
tag="li"
|
||||
className="border-t border-border-subtle first:border-t-0"
|
||||
>
|
||||
<FlexBox
|
||||
tag="button"
|
||||
type="button"
|
||||
direction="flex-col"
|
||||
justifyContent="justify-center"
|
||||
aria-haspopup="dialog"
|
||||
aria-label={t('ledger.open', { title: text.title, date: text.when })}
|
||||
onClick={onOpen}
|
||||
className={cn(
|
||||
'min-h-15 w-full cursor-pointer gap-0.5 px-4 py-2 text-start outline-none transition-colors duration-120 ease-standard hover:bg-surface-hover focus-visible:focus-ring',
|
||||
isOpen && 'bg-action-primary-subtle hover:bg-action-primary-subtle',
|
||||
)}
|
||||
>
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
>
|
||||
<FlexBox alignItems="items-center" gap="gap-2" className="min-w-0">
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="label"
|
||||
className="whitespace-nowrap"
|
||||
>
|
||||
{text.title}
|
||||
</Typography>
|
||||
{pill && (
|
||||
<StatusBadge status={`payout.${pill}`}>
|
||||
{t(`ledger.status.${pill}`)}
|
||||
</StatusBadge>
|
||||
)}
|
||||
</FlexBox>
|
||||
<Amount
|
||||
value={row.amountToman}
|
||||
size="caption"
|
||||
signed
|
||||
struck={cancelled}
|
||||
srLabel={cancelled ? t('ledger.cancelled') : undefined}
|
||||
/>
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
tag="span"
|
||||
alignItems="items-center"
|
||||
className="min-w-0 text-caption text-text-secondary"
|
||||
>
|
||||
{meta.flatMap((part, index) =>
|
||||
index === 0 ? [part] : [<Separator key={`sep-${index}`} />, part],
|
||||
)}
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
</Element>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import { date } from '@lumina/tools/format';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import type { LedgerItemPayload } from '../../../../../../../../features/finance';
|
||||
|
||||
/** A row's title and the parts of its second line: who or where, what, then the Shamsi date. */
|
||||
export function useLedgerRowText() {
|
||||
const { t } = useTranslation(['finance', 'common']);
|
||||
|
||||
return (row: LedgerItemPayload) => {
|
||||
const title = t(`ledger.rows.${row.kind}`);
|
||||
const when = date(row.occurredAt, { time: false });
|
||||
switch (row.kind) {
|
||||
case 'income':
|
||||
return {
|
||||
title,
|
||||
who: row.subscriberUsername,
|
||||
what: row.billingPeriod
|
||||
? t('ledger.plan', {
|
||||
period: t(`common:billing-periods.${row.billingPeriod}`),
|
||||
})
|
||||
: null,
|
||||
when,
|
||||
};
|
||||
case 'refund_deduction':
|
||||
return {
|
||||
title,
|
||||
who: row.subscriberUsername,
|
||||
what: row.billingPeriod
|
||||
? t('ledger.refund-plan', {
|
||||
period: t(`common:billing-periods.${row.billingPeriod}`),
|
||||
})
|
||||
: null,
|
||||
when,
|
||||
};
|
||||
case 'correction':
|
||||
return { title, who: null, what: row.reason, when };
|
||||
case 'payout':
|
||||
return {
|
||||
title,
|
||||
who: null,
|
||||
what: t('ledger.payout-line', { tail: `…${row.ibanTail}` }),
|
||||
when,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export { Ledger } from './Ledger';
|
||||
export { LedgerSkeleton } from './LedgerSkeleton';
|
||||
export type { LedgerProps, LedgerSkeletonProps } from './types';
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import type {
|
||||
LedgerItemPayload,
|
||||
LedgerPartModel,
|
||||
} from '../../../../../../../features/finance';
|
||||
|
||||
export type LedgerProps = {
|
||||
/** mobile: details in a bottom sheet. desktop: in a side panel, the row highlighted (۶.۲). */
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
||||
export type LedgerSkeletonProps = LedgerProps & {
|
||||
/** Hidden status text: «در حال بارگذاری گردش حساب…». */
|
||||
label: string;
|
||||
/** Fades in after 300ms, so a fast route never flashes grey. loading.tsx only. */
|
||||
delayed?: boolean;
|
||||
};
|
||||
|
||||
export type LedgerRowProps = {
|
||||
row: LedgerItemPayload;
|
||||
/** Its details are open in the side panel. */
|
||||
isOpen: boolean;
|
||||
onOpen: () => void;
|
||||
};
|
||||
|
||||
export type LedgerDetailProps = {
|
||||
model: LedgerPartModel;
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import {
|
||||
PAYOUT_ACCOUNT_ANCHOR,
|
||||
usePayoutAccountPart,
|
||||
} from '../../../../../../../features/finance';
|
||||
import { AccountForm } from './components/AccountForm';
|
||||
import { ReadBackDialog } from './components/ReadBackDialog';
|
||||
import { SavedAccount } from './components/SavedAccount';
|
||||
import { WarnLine } from './components/WarnLine';
|
||||
import type { PayoutAccountProps } from './types';
|
||||
|
||||
/**
|
||||
* مالی › اطلاعات تسویهحساب (C19). Saved: the number, its bank and date, «ویرایش» in the header
|
||||
* (۴.۳). None: the empty line, the amber reassurance when money is waiting (۱.۲) and «ثبت شماره
|
||||
* شبا». Unverified or rejected: a lock and one line, no button (۱.۳). Suspended: the saved card
|
||||
* read-only, a lock where «ویرایش» was and the amber reason (۵.۳). The form expands in place, with
|
||||
* «انصراف» in the header when a number is already saved (۵.۱).
|
||||
*/
|
||||
export function PayoutAccount({ layout }: PayoutAccountProps) {
|
||||
const { t } = useTranslation('finance');
|
||||
const model = usePayoutAccountPart();
|
||||
const headingId = useId();
|
||||
const { state, account } = model;
|
||||
const canEdit = state === 'open';
|
||||
|
||||
let headerAction = null;
|
||||
if (model.isEditing && account) {
|
||||
headerAction = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
aria-label={t('account.cancel-label')}
|
||||
onClick={model.cancelEditing}
|
||||
disabled={model.isSaving}
|
||||
>
|
||||
{t('account.cancel')}
|
||||
</Button>
|
||||
);
|
||||
} else if (!model.isEditing && account && canEdit) {
|
||||
headerAction = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon="edit"
|
||||
aria-label={t('account.edit-label')}
|
||||
onClick={model.startEditing}
|
||||
>
|
||||
{t('account.edit')}
|
||||
</Button>
|
||||
);
|
||||
} else if (account && state === 'suspended') {
|
||||
headerAction = (
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-center"
|
||||
className="size-touch-target text-text-secondary"
|
||||
>
|
||||
<Icon name="lock" size={20} label={t('account.read-only')} />
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
tag="section"
|
||||
id={PAYOUT_ACCOUNT_ANCHOR}
|
||||
aria-labelledby={headingId}
|
||||
padding={layout === 'desktop' ? 'lg' : 'md'}
|
||||
className="scroll-mt-20"
|
||||
>
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
className="-my-2"
|
||||
>
|
||||
<Typography tag="h2" id={headingId} variant="heading-sm">
|
||||
{t('account.title')}
|
||||
</Typography>
|
||||
{headerAction}
|
||||
</FlexBox>
|
||||
{model.isEditing ? (
|
||||
<AccountForm model={model} layout={layout} />
|
||||
) : account ? (
|
||||
<>
|
||||
<SavedAccount
|
||||
iban={account.iban}
|
||||
bankCode={account.bankCode}
|
||||
savedAt={account.savedAt}
|
||||
/>
|
||||
{state === 'suspended' && (
|
||||
<WarnLine>{t('account.suspended')}</WarnLine>
|
||||
)}
|
||||
</>
|
||||
) : state === 'open' ? (
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{t('account.empty')}
|
||||
</Typography>
|
||||
{model.showHeldNote && (
|
||||
<WarnLine>{t('account.held-note')}</WarnLine>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
size="lg"
|
||||
block={layout === 'mobile'}
|
||||
onClick={model.startEditing}
|
||||
>
|
||||
{t('account.register')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
) : (
|
||||
<FlexBox alignItems="items-start" gap="gap-2">
|
||||
<Icon
|
||||
name="lock"
|
||||
size={20}
|
||||
className="mt-0.5 flex-none text-text-secondary"
|
||||
/>
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{state === 'suspended'
|
||||
? t('account.suspended')
|
||||
: t('account.locked')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
)}
|
||||
</FlexBox>
|
||||
<ReadBackDialog model={model} layout={layout} />
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
|
||||
import type { PayoutAccountSkeletonProps } from './types';
|
||||
|
||||
/** اطلاعات تسویهحساب before it arrives: the header, the number panel and its meta line. */
|
||||
export function PayoutAccountSkeleton({
|
||||
layout,
|
||||
label,
|
||||
delayed,
|
||||
}: PayoutAccountSkeletonProps) {
|
||||
return (
|
||||
<SkeletonRegion label={label} delayed={delayed}>
|
||||
<Card padding={layout === 'desktop' ? 'lg' : 'md'}>
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<Skeleton width="40%" height={16} />
|
||||
<Skeleton shape="rect" height={56} />
|
||||
<FlexBox justifyContent="justify-between">
|
||||
<Skeleton width="30%" />
|
||||
<Skeleton width="35%" />
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
</Card>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,118 @@
|
|||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { Checkbox } from '@lumina/island/atoms/checkbox';
|
||||
import { FieldError } from '@lumina/island/atoms/field-error';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
import { TextInput } from '@lumina/island/molecules/text-input';
|
||||
import { useId } from 'react';
|
||||
import { Controller } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { translateMessage } from '../../../../../../../../shared/utils';
|
||||
import type { PayoutAccountPartProps } from '../types';
|
||||
import { WarnLine } from './WarnLine';
|
||||
|
||||
/**
|
||||
* The شبا form, in place of the card's body (C19 §۲–۳). The field is the page's only LTR one: `IR`
|
||||
* fixed before it, digits grouped as typed. Under it, in order: the error, the bank, the duplicate
|
||||
* warning, the helper. The box is ticked on every save. «ثبت شماره شبا» is pressable at any time,
|
||||
* so a tap shows what is missing (۳.۴); the save's failure shows at the top (۵.۲).
|
||||
*/
|
||||
export function AccountForm({ model, layout }: PayoutAccountPartProps) {
|
||||
const { t } = useTranslation('finance');
|
||||
const hintId = useId();
|
||||
const { form } = model;
|
||||
const rootError = form.formState.errors.root?.server?.message;
|
||||
const bank = model.bankCode
|
||||
? t(`banks.${model.bankCode}`, { defaultValue: '' })
|
||||
: '';
|
||||
|
||||
return (
|
||||
<FlexBox
|
||||
tag="form"
|
||||
noValidate
|
||||
direction="flex-col"
|
||||
gap="gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
model.submit();
|
||||
}}
|
||||
>
|
||||
{rootError && (
|
||||
<Banner tone="danger" role="alert">
|
||||
{translateMessage(t, rootError)}
|
||||
</Banner>
|
||||
)}
|
||||
<FlexBox direction="flex-col" gap="gap-1">
|
||||
<Controller
|
||||
name="iban"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<TextInput
|
||||
ref={field.ref}
|
||||
name={field.name}
|
||||
label={t('account.iban')}
|
||||
dir="ltr"
|
||||
prefix="IR"
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
placeholder="00 0000 0000 0000 0000 0000 00"
|
||||
value={model.ibanText}
|
||||
onChange={(event) => model.changeIban(event.target.value)}
|
||||
onBlur={() => {
|
||||
field.onBlur();
|
||||
model.checkDuplicate();
|
||||
}}
|
||||
error={translateMessage(t, fieldState.error?.message)}
|
||||
aria-describedby={hintId}
|
||||
inputClassName="font-latin tabular-nums"
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
{bank && (
|
||||
<Typography variant="caption" color="secondary">
|
||||
{t('account.bank', { name: bank })}
|
||||
</Typography>
|
||||
)}
|
||||
{model.duplicate && <WarnLine>{t('account.duplicate')}</WarnLine>}
|
||||
<Typography id={hintId} variant="caption" color="secondary">
|
||||
{t('account.hint')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
<Controller
|
||||
name="confirmed"
|
||||
control={form.control}
|
||||
render={({ field, fieldState }) => (
|
||||
<FlexBox direction="flex-col">
|
||||
<Checkbox
|
||||
ref={field.ref}
|
||||
name={field.name}
|
||||
checked={field.value}
|
||||
onChange={(event) => field.onChange(event.target.checked)}
|
||||
onBlur={field.onBlur}
|
||||
invalid={fieldState.error != null}
|
||||
>
|
||||
{t('account.confirm')}
|
||||
</Checkbox>
|
||||
{fieldState.error?.message && (
|
||||
<FieldError className="ps-8.5">
|
||||
{translateMessage(t, fieldState.error.message)}
|
||||
</FieldError>
|
||||
)}
|
||||
</FlexBox>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
block={layout === 'mobile'}
|
||||
isLoading={model.isSaving}
|
||||
>
|
||||
{t('account.register')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Modal } from '@lumina/island/molecules/modal';
|
||||
import { Sheet } from '@lumina/island/molecules/sheet';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import {
|
||||
groupIbanDigits,
|
||||
ibanBankCode,
|
||||
} from '../../../../../../../../shared/utils';
|
||||
import type { PayoutAccountPartProps } from '../types';
|
||||
|
||||
/**
|
||||
* The read-back before saving (C19 §۷): the شبا is the largest thing on it, LTR and grouped, with
|
||||
* its bank when known (۴.۲ drops the row otherwise). «ثبت نهایی» saves; «ویرایش», Escape or the
|
||||
* scrim return to the form with the number and the tick kept. A bottom sheet on mobile, a centred
|
||||
* modal on desktop (۸.۲); no ✕, since «ویرایش» is the way back.
|
||||
*/
|
||||
export function ReadBackDialog({ model, layout }: PayoutAccountPartProps) {
|
||||
const { t } = useTranslation('finance');
|
||||
const open = model.phase === 'confirming' || model.phase === 'saving';
|
||||
const code = ibanBankCode(model.readBackIban);
|
||||
const bank = code ? t(`banks.${code}`, { defaultValue: '' }) : '';
|
||||
|
||||
const buttons = (
|
||||
<>
|
||||
<Button
|
||||
variant="primary"
|
||||
size={layout === 'mobile' ? 'lg' : undefined}
|
||||
block
|
||||
isLoading={model.isSaving}
|
||||
onClick={model.confirm}
|
||||
>
|
||||
{t('account.read-back.submit')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size={layout === 'mobile' ? 'lg' : undefined}
|
||||
block
|
||||
disabled={model.isSaving}
|
||||
onClick={model.closeReadBack}
|
||||
>
|
||||
{t('account.read-back.edit')}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
const body = (
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
<Typography variant="body-md">{t('account.read-back.intro')}</Typography>
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
gap="gap-2"
|
||||
className="rounded-md bg-surface-sunken p-3"
|
||||
>
|
||||
<FlexBox direction="flex-col" className="gap-0.5">
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('account.read-back.iban')}
|
||||
</Typography>
|
||||
<Element
|
||||
tag="bdi"
|
||||
dir="ltr"
|
||||
className="block text-start font-latin text-body-lg font-bold whitespace-nowrap tabular-nums"
|
||||
>
|
||||
IR{groupIbanDigits(model.readBackIban)}
|
||||
</Element>
|
||||
</FlexBox>
|
||||
{bank && (
|
||||
<FlexBox
|
||||
alignItems="items-baseline"
|
||||
gap="gap-2"
|
||||
className="border-t border-border-subtle pt-2"
|
||||
>
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('account.read-back.bank')}
|
||||
</Typography>
|
||||
<Typography tag="span" variant="body-sm" className="font-semibold">
|
||||
{bank}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
)}
|
||||
</FlexBox>
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{t('account.read-back.warning')}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
);
|
||||
|
||||
const onClose = model.isSaving ? undefined : model.closeReadBack;
|
||||
|
||||
return layout === 'mobile' ? (
|
||||
<Sheet
|
||||
open={open}
|
||||
title={t('account.read-back.title')}
|
||||
footer={buttons}
|
||||
onClose={onClose}
|
||||
>
|
||||
{body}
|
||||
</Sheet>
|
||||
) : (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('account.read-back.title')}
|
||||
actions={buttons}
|
||||
onClose={onClose}
|
||||
>
|
||||
{body}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
import { date } from '@lumina/tools/format';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { groupIbanDigits } from '../../../../../../../../shared/utils';
|
||||
import type { SavedAccountProps } from '../types';
|
||||
|
||||
/**
|
||||
* The saved شبا (C19 ۴.۳): the whole number, LTR and grouped, in Latin digits as banks print it,
|
||||
* then its bank when the code is known and when it was last saved.
|
||||
*/
|
||||
export function SavedAccount({ iban, bankCode, savedAt }: SavedAccountProps) {
|
||||
const { t } = useTranslation('finance');
|
||||
const bank = bankCode ? t(`banks.${bankCode}`, { defaultValue: '' }) : '';
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-2">
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
className="gap-0.5 rounded-md bg-surface-sunken px-3 py-2"
|
||||
>
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('account.iban')}
|
||||
</Typography>
|
||||
<Element
|
||||
tag="bdi"
|
||||
dir="ltr"
|
||||
className="block text-start font-latin text-body-lg font-bold whitespace-nowrap tabular-nums"
|
||||
>
|
||||
IR{groupIbanDigits(iban)}
|
||||
</Element>
|
||||
</FlexBox>
|
||||
<FlexBox justifyContent="justify-between" gap="gap-3" wrap="flex-wrap">
|
||||
{bank && (
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('account.bank', { name: bank })}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('account.updated', { date: date(savedAt, { time: false }) })}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Icon } from '@lumina/island/atoms/icon';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
|
||||
import type { WarnLineProps } from '../types';
|
||||
|
||||
/**
|
||||
* An amber note that warns without blocking (C19 ۱.۲, ۳.۳, ۵.۳): ink-dark amber text on the amber
|
||||
* tint, so it passes contrast on white, with the warning icon.
|
||||
*/
|
||||
export function WarnLine({ children }: WarnLineProps) {
|
||||
return (
|
||||
<FlexBox
|
||||
alignItems="items-start"
|
||||
gap="gap-2"
|
||||
className="rounded-md bg-warning-subtle px-3 py-2 text-warning-text"
|
||||
>
|
||||
<Icon name="alert" size={16} className="mt-1 flex-none" />
|
||||
<Typography variant="caption" color="warning">
|
||||
{children}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export { PayoutAccount } from './PayoutAccount';
|
||||
export { PayoutAccountSkeleton } from './PayoutAccountSkeleton';
|
||||
export type { PayoutAccountProps, PayoutAccountSkeletonProps } from './types';
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import type { ReactNode } from 'react';
|
||||
|
||||
import type { PayoutAccountPartModel } from '../../../../../../../features/finance';
|
||||
|
||||
export type PayoutAccountProps = {
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
||||
export type PayoutAccountSkeletonProps = PayoutAccountProps & {
|
||||
/** Hidden status text: «در حال بارگذاری اطلاعات تسویهحساب…». */
|
||||
label: string;
|
||||
/** Fades in after 300ms, so a fast route never flashes grey. loading.tsx only. */
|
||||
delayed?: boolean;
|
||||
};
|
||||
|
||||
export type PayoutAccountPartProps = {
|
||||
model: PayoutAccountPartModel;
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
||||
export type SavedAccountProps = {
|
||||
iban: string;
|
||||
bankCode: string | null;
|
||||
savedAt: string;
|
||||
};
|
||||
|
||||
export type WarnLineProps = {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
|
||||
import type { PayoutScheduleNoticeProps } from './types';
|
||||
|
||||
/**
|
||||
* مالی's first block, always (C19 §۱; brief §4): when payouts are made. The same for every creator,
|
||||
* so the server renders it with the page, and it never waits for the creator's own figures.
|
||||
*/
|
||||
export function PayoutScheduleNotice({ labels }: PayoutScheduleNoticeProps) {
|
||||
return (
|
||||
<Banner tone="info" icon="clock">
|
||||
{labels.before}{' '}
|
||||
<Typography
|
||||
tag="strong"
|
||||
variant="inherit"
|
||||
color="inherit"
|
||||
className="font-bold"
|
||||
>
|
||||
{labels.day}
|
||||
</Typography>{' '}
|
||||
{labels.after}
|
||||
</Banner>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
export { PayoutScheduleNotice } from './PayoutScheduleNotice';
|
||||
export type {
|
||||
PayoutScheduleNoticeLabels,
|
||||
PayoutScheduleNoticeProps,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
/** Every text, from the app's server i18n (0020). */
|
||||
export type PayoutScheduleNoticeLabels = {
|
||||
/** «واریز درآمد هر هفته، روزهای». */
|
||||
before: string;
|
||||
/** `{payout_day}`: «پنجشنبه». */
|
||||
day: string;
|
||||
/** «انجام میشود. …». */
|
||||
after: string;
|
||||
};
|
||||
|
||||
export type PayoutScheduleNoticeProps = {
|
||||
labels: PayoutScheduleNoticeLabels;
|
||||
};
|
||||
|
|
@ -4,26 +4,31 @@ import { TabLinks } from '@lumina/island/molecules/tab-links';
|
|||
import { usePathname } from 'next/navigation';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { INVESTOR_TABS } from './constants';
|
||||
import { CREATOR_TABS, INVESTOR_TABS } from './constants';
|
||||
import type { DashboardTabsProps } from './types';
|
||||
|
||||
/**
|
||||
* The investor داشبورد's section row: «اشتراکها» · «تراکنشها» · «دنبالشدهها», full width, the
|
||||
* current section underlined (U8 ۴.۱, ۶.۱; U8 ۵.۲). The dashboard layout renders it once, so it
|
||||
* stays put while a section loads; the current one comes from the URL, which the server render
|
||||
* already knows.
|
||||
* The داشبورد's section row, full width, the current one underlined: the investor's «اشتراکها» ·
|
||||
* «تراکنشها» · «دنبالشدهها» (U8 ۴.۱, ۶.۱; U8 ۵.۲), or the creator's «طرحهای اشتراک» · «مالی»
|
||||
* (Creator Dashboard ۱.۱). The dashboard layout renders it once, so it stays put while a section
|
||||
* loads; the current one comes from the URL, which the server render already knows.
|
||||
*/
|
||||
export function DashboardTabs({ layout }: DashboardTabsProps) {
|
||||
export function DashboardTabs({
|
||||
layout,
|
||||
role = 'investor',
|
||||
}: DashboardTabsProps) {
|
||||
const { t } = useTranslation('dashboard');
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<TabLinks
|
||||
items={INVESTOR_TABS.map(({ href, label }) => ({
|
||||
href,
|
||||
label: t(label),
|
||||
isActive: pathname === href || pathname.startsWith(`${href}/`),
|
||||
}))}
|
||||
items={(role === 'creator' ? CREATOR_TABS : INVESTOR_TABS).map(
|
||||
({ href, label }) => ({
|
||||
href,
|
||||
label: t(label),
|
||||
isActive: pathname === href || pathname.startsWith(`${href}/`),
|
||||
}),
|
||||
)}
|
||||
label={t('tabs.label')}
|
||||
fill
|
||||
band={layout === 'mobile'}
|
||||
|
|
|
|||
|
|
@ -6,3 +6,9 @@ export const INVESTOR_TABS = [
|
|||
{ href: ROUTES.dashboard.transactions, label: 'tabs.transactions' },
|
||||
{ href: ROUTES.dashboard.following, label: 'tabs.following' },
|
||||
] as const;
|
||||
|
||||
/** The creator's two tabs, «طرحهای اشتراک» first (Creator Dashboard ۱.۱). */
|
||||
export const CREATOR_TABS = [
|
||||
{ href: ROUTES.dashboard.plans, label: 'creator-tabs.plans' },
|
||||
{ href: ROUTES.dashboard.finance, label: 'creator-tabs.finance' },
|
||||
] as const;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
export type DashboardTabsProps = {
|
||||
/** mobile: the surface band under the top bar. desktop: in the 640 column, under the heading. */
|
||||
layout: 'mobile' | 'desktop';
|
||||
/** Whose داشبورد: the investor's three sections, or the creator's two tabs. Default investor. */
|
||||
role?: 'investor' | 'creator';
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,101 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { StatusBadge } from '@lumina/island/atoms/status-badge';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Banner } from '@lumina/island/molecules/banner';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
import { date } from '@lumina/tools/format';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { usePricingCardPart } from '../../../../../../../features/pricing';
|
||||
import { ROUTES } from '../../../../../../navigation/navigation';
|
||||
import { PlanRow } from './components/PlanRow';
|
||||
import type { PricingCardProps } from './types';
|
||||
|
||||
/**
|
||||
* طرحهای اشتراک › «قیمت طرحها» (Creator Dashboard ۲.۱–۲.۵): each offered plan with its total and
|
||||
* per-month equivalent, then «ویرایش قیمتها», which opens C7 as a page. With nothing priced it is
|
||||
* one line and «تعیین قیمتها» (۲.۴); during the 7-day lock the notice sits under the plans and
|
||||
* the button stays live, since promotions stay editable (۲.۳). A creator not yet verified, or
|
||||
* rejected, sees that status above the card (۲.۵); prices stay editable.
|
||||
*/
|
||||
export function PricingCard({ layout }: PricingCardProps) {
|
||||
const { t } = useTranslation(['pricing', 'common']);
|
||||
const model = usePricingCardPart();
|
||||
const headingId = useId();
|
||||
|
||||
return (
|
||||
<FlexBox direction="flex-col" gap="gap-3">
|
||||
{model.verification !== 'approved' && (
|
||||
<FlexBox>
|
||||
<StatusBadge
|
||||
status={`verification.${model.verification}`}
|
||||
aria-label={t('card.verification', {
|
||||
status: t(`common:status.verification.${model.verification}`),
|
||||
})}
|
||||
>
|
||||
{t(`common:status.verification.${model.verification}`)}
|
||||
</StatusBadge>
|
||||
</FlexBox>
|
||||
)}
|
||||
<Card
|
||||
tag="section"
|
||||
aria-labelledby={headingId}
|
||||
padding={layout === 'desktop' ? 'lg' : 'md'}
|
||||
>
|
||||
<FlexBox direction="flex-col">
|
||||
<Typography
|
||||
tag="h2"
|
||||
id={headingId}
|
||||
variant="heading-sm"
|
||||
className="mb-1"
|
||||
>
|
||||
{t('card.title')}
|
||||
</Typography>
|
||||
{model.isEmpty ? (
|
||||
<FlexBox direction="flex-col" gap="gap-3" className="pt-1">
|
||||
<Typography variant="body-sm" color="secondary">
|
||||
{t('card.empty')}
|
||||
</Typography>
|
||||
<Button href={ROUTES.dashboard.pricing} variant="primary" block>
|
||||
{t('card.set')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
) : (
|
||||
<>
|
||||
<FlexBox tag="ul" direction="flex-col">
|
||||
{model.plans.map((plan, index) => (
|
||||
<PlanRow
|
||||
key={plan.billingPeriod}
|
||||
plan={plan}
|
||||
divided={index > 0}
|
||||
/>
|
||||
))}
|
||||
</FlexBox>
|
||||
{model.lockedUntil && (
|
||||
<Banner tone="info" icon="lock" className="mt-2">
|
||||
{t('card.locked', {
|
||||
date: date(model.lockedUntil, { time: false }),
|
||||
})}
|
||||
</Banner>
|
||||
)}
|
||||
<FlexBox className="pt-2">
|
||||
<Button
|
||||
href={ROUTES.dashboard.pricing}
|
||||
variant="secondary"
|
||||
icon="edit"
|
||||
block
|
||||
>
|
||||
{t('card.edit')}
|
||||
</Button>
|
||||
</FlexBox>
|
||||
</>
|
||||
)}
|
||||
</FlexBox>
|
||||
</Card>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
|
||||
import type { PricingCardSkeletonProps } from './types';
|
||||
|
||||
/** «قیمت طرحها» before it arrives, row for row: its title, four plans and the button. */
|
||||
export function PricingCardSkeleton({
|
||||
layout,
|
||||
label,
|
||||
delayed,
|
||||
}: PricingCardSkeletonProps) {
|
||||
return (
|
||||
<SkeletonRegion label={label} delayed={delayed}>
|
||||
<Card padding={layout === 'desktop' ? 'lg' : 'md'}>
|
||||
<FlexBox direction="flex-col">
|
||||
<Skeleton width="35%" className="mb-2" />
|
||||
{[0, 1, 2, 3].map((row) => (
|
||||
<FlexBox
|
||||
key={row}
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
className="py-2.5"
|
||||
>
|
||||
<FlexBox direction="flex-col" gap="gap-1" className="w-1/2">
|
||||
<Skeleton width="40%" />
|
||||
<Skeleton width="80%" />
|
||||
</FlexBox>
|
||||
<Skeleton width="28%" height={24} />
|
||||
</FlexBox>
|
||||
))}
|
||||
<Skeleton shape="pill" height={44} className="mt-2" />
|
||||
</FlexBox>
|
||||
</Card>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
import { Amount } from '@lumina/island/atoms/amount';
|
||||
import { Countdown } from '@lumina/island/atoms/countdown';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Tag } from '@lumina/island/atoms/tag';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { cn } from '@lumina/island/tools/cn';
|
||||
import { percent, price } from '@lumina/tools/format';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { promotionCountdownLabels } from '../../../../../../../../shared/labels';
|
||||
import type { PlanRowProps } from '../types';
|
||||
|
||||
/**
|
||||
* One offered plan (Creator Dashboard ۲.۱, ۲.۲): its period and per-month equivalent, the period
|
||||
* total at the end. A running promotion adds the red «تخفیف n٪» tag and its countdown, and shows
|
||||
* the struck standing total over the promotional one.
|
||||
*/
|
||||
export function PlanRow({ plan, divided }: PlanRowProps) {
|
||||
const { t } = useTranslation(['pricing', 'common']);
|
||||
const { t: tPayment } = useTranslation('payment');
|
||||
const promo = plan.promotion;
|
||||
|
||||
return (
|
||||
<FlexBox
|
||||
tag="li"
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
className={cn('py-2.5', divided && 'border-t border-border-subtle')}
|
||||
>
|
||||
<FlexBox direction="flex-col" className="min-w-0 gap-0.5">
|
||||
<FlexBox alignItems="items-center" gap="gap-2" wrap="flex-wrap">
|
||||
<Typography tag="span" className="font-semibold">
|
||||
{t(`common:billing-periods.${plan.billingPeriod}`)}
|
||||
</Typography>
|
||||
{promo && (
|
||||
<Tag variant="discount" icon={null}>
|
||||
{t('card.discount', { percent: percent(promo.percent, 0) })}
|
||||
</Tag>
|
||||
)}
|
||||
</FlexBox>
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('card.per-month', {
|
||||
amount: price(promo ? promo.perMonthToman : plan.perMonthToman),
|
||||
})}
|
||||
</Typography>
|
||||
{promo?.endsAt && (
|
||||
<Typography tag="span" variant="caption">
|
||||
<Countdown
|
||||
kind="promotion"
|
||||
endsAt={promo.endsAt}
|
||||
labels={promotionCountdownLabels(tPayment)}
|
||||
/>
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
<FlexBox
|
||||
direction="flex-col"
|
||||
alignItems="items-end"
|
||||
className="flex-none gap-0.5"
|
||||
>
|
||||
{promo && (
|
||||
<Amount
|
||||
value={plan.priceToman}
|
||||
size="caption"
|
||||
struck
|
||||
srLabel={t('card.struck')}
|
||||
/>
|
||||
)}
|
||||
<Amount
|
||||
value={promo ? promo.priceToman : plan.priceToman}
|
||||
size="title"
|
||||
currency={t('common:currency')}
|
||||
/>
|
||||
</FlexBox>
|
||||
</FlexBox>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export { PricingCard } from './PricingCard';
|
||||
export { PricingCardSkeleton } from './PricingCardSkeleton';
|
||||
export type { PricingCardProps, PricingCardSkeletonProps } from './types';
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import type { PricingPlanRow } from '../../../../../../../features/pricing';
|
||||
|
||||
export type PricingCardProps = {
|
||||
/** mobile: card padding md. desktop: lg, in the 640 column. */
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
||||
export type PlanRowProps = {
|
||||
plan: PricingPlanRow;
|
||||
/** Every row after the first has a hairline above it. */
|
||||
divided: boolean;
|
||||
};
|
||||
|
||||
export type PricingCardSkeletonProps = PricingCardProps & {
|
||||
/** Hidden status text: «در حال بارگذاری قیمت طرحها…». */
|
||||
label: string;
|
||||
/** Fades in after 300ms, so a fast route never flashes grey. loading.tsx only. */
|
||||
delayed?: boolean;
|
||||
};
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
'use client';
|
||||
|
||||
import { Button } from '@lumina/island/atoms/button';
|
||||
import { Element } from '@lumina/island/primitives/element';
|
||||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Separator } from '@lumina/island/atoms/separator';
|
||||
import { Typography } from '@lumina/island/atoms/typography';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
import { EmptyState } from '@lumina/island/molecules/empty-state';
|
||||
import { ErrorState } from '@lumina/island/molecules/error-state';
|
||||
import { cn } from '@lumina/island/tools/cn';
|
||||
import { date, number } from '@lumina/tools/format';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSubscribersPart } from '../../../../../../../features/overview';
|
||||
import type { SubscriberListProps } from './types';
|
||||
|
||||
/**
|
||||
* طرحهای اشتراک › مشترکان (Creator Dashboard ۲.۱): the active count in the header, then each
|
||||
* running subscription by @username only, with its plan, start and end; newest start first, 20 at
|
||||
* a time. Rows aren't tappable, and there is no filter, search or action, until Epic 6. With none,
|
||||
* one quiet line (۲.۴).
|
||||
*/
|
||||
export function SubscriberList({ layout }: SubscriberListProps) {
|
||||
const { t } = useTranslation(['dashboard', 'common', 'errors']);
|
||||
const model = useSubscribersPart();
|
||||
const headingId = useId();
|
||||
|
||||
return (
|
||||
<Card
|
||||
tag="section"
|
||||
aria-labelledby={headingId}
|
||||
padding={layout === 'desktop' ? 'lg' : 'md'}
|
||||
>
|
||||
<FlexBox direction="flex-col">
|
||||
<FlexBox
|
||||
alignItems="items-baseline"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
className="pb-0.5"
|
||||
>
|
||||
<Typography tag="h2" id={headingId} variant="heading-sm">
|
||||
{t('subscribers.title')}
|
||||
</Typography>
|
||||
<Typography tag="span" variant="caption" color="secondary">
|
||||
{t('subscribers.active')}{' '}
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="body-lg"
|
||||
className="font-semibold tabular-nums"
|
||||
>
|
||||
{number(model.activeCount)}
|
||||
</Typography>
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
{model.rows.length === 0 ? (
|
||||
<EmptyState
|
||||
title={t('subscribers.empty')}
|
||||
icon="users"
|
||||
size="inline"
|
||||
className="pt-2"
|
||||
/>
|
||||
) : (
|
||||
<FlexBox tag="ul" direction="flex-col">
|
||||
{model.rows.map((row, index) => (
|
||||
<FlexBox
|
||||
key={row.id}
|
||||
tag="li"
|
||||
direction="flex-col"
|
||||
className={cn(
|
||||
'gap-0.5 py-2.5',
|
||||
index > 0 && 'border-t border-border-subtle',
|
||||
)}
|
||||
>
|
||||
<FlexBox
|
||||
alignItems="items-center"
|
||||
justifyContent="justify-between"
|
||||
gap="gap-3"
|
||||
>
|
||||
<Element
|
||||
tag="bdi"
|
||||
dir="ltr"
|
||||
className="truncate font-semibold"
|
||||
>
|
||||
@{row.username ?? '—'}
|
||||
</Element>
|
||||
{row.billingPeriod && (
|
||||
<Typography
|
||||
tag="span"
|
||||
variant="body-sm"
|
||||
className="flex-none"
|
||||
>
|
||||
{t(`common:billing-periods.${row.billingPeriod}`)}
|
||||
</Typography>
|
||||
)}
|
||||
</FlexBox>
|
||||
<Typography variant="caption" color="secondary">
|
||||
{row.startsAt &&
|
||||
t('subscribers.start', {
|
||||
date: date(row.startsAt, { time: false }),
|
||||
})}
|
||||
{row.startsAt && row.endsAt && <Separator />}
|
||||
{row.endsAt &&
|
||||
t('subscribers.end', {
|
||||
date: date(row.endsAt, { time: false }),
|
||||
})}
|
||||
</Typography>
|
||||
</FlexBox>
|
||||
))}
|
||||
</FlexBox>
|
||||
)}
|
||||
{model.loadMoreError ? (
|
||||
<ErrorState
|
||||
kind={model.loadMoreError}
|
||||
size="inline"
|
||||
title={t(`errors:fallback.${model.loadMoreError}.title`)}
|
||||
description={t('subscribers.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}
|
||||
className="mt-2"
|
||||
>
|
||||
{t('subscribers.more')}
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</FlexBox>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import { FlexBox } from '@lumina/island/atoms/flex-box';
|
||||
import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton';
|
||||
import { Card } from '@lumina/island/molecules/card';
|
||||
|
||||
import type { SubscriberListSkeletonProps } from './types';
|
||||
|
||||
/** مشترکان before it arrives: its header and three rows of two lines. */
|
||||
export function SubscriberListSkeleton({
|
||||
layout,
|
||||
label,
|
||||
delayed,
|
||||
}: SubscriberListSkeletonProps) {
|
||||
return (
|
||||
<SkeletonRegion label={label} delayed={delayed}>
|
||||
<Card padding={layout === 'desktop' ? 'lg' : 'md'}>
|
||||
<FlexBox direction="flex-col">
|
||||
<FlexBox justifyContent="justify-between" className="pb-1">
|
||||
<Skeleton width="25%" />
|
||||
<Skeleton width="30%" />
|
||||
</FlexBox>
|
||||
{[0, 1, 2].map((row) => (
|
||||
<FlexBox
|
||||
key={row}
|
||||
direction="flex-col"
|
||||
gap="gap-2"
|
||||
className="py-3"
|
||||
>
|
||||
<FlexBox justifyContent="justify-between">
|
||||
<Skeleton width="35%" />
|
||||
<Skeleton width="18%" />
|
||||
</FlexBox>
|
||||
<Skeleton width="60%" />
|
||||
</FlexBox>
|
||||
))}
|
||||
</FlexBox>
|
||||
</Card>
|
||||
</SkeletonRegion>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export { SubscriberList } from './SubscriberList';
|
||||
export { SubscriberListSkeleton } from './SubscriberListSkeleton';
|
||||
export type { SubscriberListProps, SubscriberListSkeletonProps } from './types';
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
export type SubscriberListProps = {
|
||||
layout: 'mobile' | 'desktop';
|
||||
};
|
||||
|
||||
export type SubscriberListSkeletonProps = SubscriberListProps & {
|
||||
/** Hidden status text: «در حال بارگذاری مشترکان…». */
|
||||
label: string;
|
||||
/** Fades in after 300ms, so a fast route never flashes grey. loading.tsx only. */
|
||||
delayed?: boolean;
|
||||
};
|
||||
|
|
@ -24,6 +24,11 @@ export const NOTIFICATION_ART: Record<
|
|||
access_restored: { icon: 'check', tone: 'brand' },
|
||||
account_suspended: { icon: 'ban', tone: 'warning' },
|
||||
account_reinstated: { icon: 'check', tone: 'brand' },
|
||||
payout_account_changed: { icon: 'shield-check', tone: 'warning' },
|
||||
payout_created: { icon: 'wallet', tone: 'brand' },
|
||||
payout_cancelled: { icon: 'x-circle', tone: 'warning' },
|
||||
refund_deducted: { icon: 'receipt', tone: 'neutral' },
|
||||
ledger_correction: { icon: 'edit', tone: 'neutral' },
|
||||
};
|
||||
|
||||
/** A type this front end doesn't know yet (a newer service, an old row): a plain bell. */
|
||||
|
|
@ -49,6 +54,11 @@ export const NOTIFICATION_CTA_TYPES = [
|
|||
'payment_pending_review',
|
||||
'creator_suspended',
|
||||
'access_restored',
|
||||
'payout_account_changed',
|
||||
'payout_created',
|
||||
'payout_cancelled',
|
||||
'refund_deducted',
|
||||
'ledger_correction',
|
||||
] as const satisfies readonly NotificationType[];
|
||||
|
||||
/** Types whose call to action is support itself, opened in place (U5 ۳.۱, ۳.۲). */
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
import { eventEmitter } from '@lumina/libs/event-emitter';
|
||||
|
||||
import { FINANCE_EVENTS } from '../../constants';
|
||||
import { payoutAccountRepository } from '../../repositories/payout-account';
|
||||
import type {
|
||||
PayoutAccountPayload,
|
||||
SavePayoutAccountArgs,
|
||||
} from '../../repositories/payout-account';
|
||||
|
||||
/**
|
||||
* Registers or changes the creator's شبا after the read-back (C19 §۷). The API tells the creator
|
||||
* by SMS and in-app when the number changed. Emits `finance.payout-account-saved`.
|
||||
*/
|
||||
export async function savePayoutAccount(
|
||||
args: SavePayoutAccountArgs,
|
||||
{ emit = true }: { emit?: boolean } = {},
|
||||
): Promise<PayoutAccountPayload> {
|
||||
const saved = await payoutAccountRepository.save(args);
|
||||
if (emit) eventEmitter.emit(FINANCE_EVENTS.payoutAccountSaved, {});
|
||||
return saved;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { savePayoutAccount } from './actions';
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
/** Events finance actions emit when they succeed. */
|
||||
export const FINANCE_EVENTS = {
|
||||
/** The شبا was registered or changed (C19). */
|
||||
payoutAccountSaved: 'finance.payout-account-saved',
|
||||
} as const;
|
||||
|
||||
/** The شبا block's element id: the next-payout line links to it when no شبا is registered. */
|
||||
export const PAYOUT_ACCOUNT_ANCHOR = 'payout-account';
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export type {
|
||||
LedgerItemEntity,
|
||||
NextPayoutState,
|
||||
PayoutAccountEntity,
|
||||
PayoutAccountState,
|
||||
PayoutStatus,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import type { BillingPeriod } from '../../../../shared/constants';
|
||||
|
||||
/** C19's lock: verified and not suspended may register or change the شبا. */
|
||||
export type PayoutAccountState = 'open' | 'unverified' | 'suspended';
|
||||
|
||||
/** `EarningsService.toAccount`: the 24 digits after `IR` and when they were last saved. */
|
||||
export type PayoutAccountEntity = { iban: string; savedAt: string };
|
||||
|
||||
/** What the next-payout line says (Appendix B §3). */
|
||||
export type NextPayoutState =
|
||||
| 'scheduled'
|
||||
| 'no_account'
|
||||
| 'nothing'
|
||||
| 'hidden'
|
||||
| 'suspended';
|
||||
|
||||
/** Appendix B §6.5: در حال انجام, انجام شده, لغو شده. */
|
||||
export type PayoutStatus = 'in_progress' | 'completed' | 'cancelled';
|
||||
|
||||
type LedgerItemBase = {
|
||||
id: string;
|
||||
/** Signed whole Toman: + adds to the balance, − takes from it. */
|
||||
amountToman: number;
|
||||
occurredAt: string;
|
||||
};
|
||||
|
||||
/** `EarningsService.toEntryItem` and `toPayoutItem`: one row of گردش حساب. */
|
||||
export type LedgerItemEntity =
|
||||
| (LedgerItemBase & {
|
||||
kind: 'income';
|
||||
income: {
|
||||
subscriberUsername: string | null;
|
||||
billingPeriod: BillingPeriod | null;
|
||||
planPriceToman: number;
|
||||
discountPercent: number | null;
|
||||
paidToman: number;
|
||||
commissionPercent: number;
|
||||
commissionToman: number;
|
||||
shareToman: number;
|
||||
};
|
||||
})
|
||||
| (LedgerItemBase & {
|
||||
kind: 'refund_deduction';
|
||||
refund: {
|
||||
subscriberUsername: string | null;
|
||||
billingPeriod: BillingPeriod | null;
|
||||
originalPaidAt: string | null;
|
||||
refundedToman: number;
|
||||
deductedToman: number;
|
||||
};
|
||||
})
|
||||
| (LedgerItemBase & { kind: 'correction'; correction: { reason: string } })
|
||||
| (LedgerItemBase & {
|
||||
kind: 'payout';
|
||||
payout: {
|
||||
status: PayoutStatus;
|
||||
ibanCheckDigits: string;
|
||||
ibanTail: string;
|
||||
completedAt: string | null;
|
||||
cancelledAt: string | null;
|
||||
cancelReason: string | null;
|
||||
hasReceipt: boolean;
|
||||
receiptMimeType: string | null;
|
||||
};
|
||||
});
|
||||
|
|
@ -1,5 +1,47 @@
|
|||
import './types';
|
||||
|
||||
export { savePayoutAccount } from './actions/save-payout-account';
|
||||
export { FINANCE_EVENTS, PAYOUT_ACCOUNT_ANCHOR } from './constants';
|
||||
export type {
|
||||
NextPayoutState,
|
||||
PayoutAccountState,
|
||||
PayoutStatus,
|
||||
} from './entities/earnings';
|
||||
export { useBalancePart } from './models/balance';
|
||||
export type { BalancePartModel } from './models/balance';
|
||||
export { useLedgerPart } from './models/ledger';
|
||||
export type { LedgerPartModel } from './models/ledger';
|
||||
export { usePayoutAccountPart } from './models/payout-account';
|
||||
export type {
|
||||
PayoutAccountPartModel,
|
||||
PayoutAccountPhase,
|
||||
} from './models/payout-account';
|
||||
export {
|
||||
creatorPaymentRepository,
|
||||
financeKeys,
|
||||
} from './repositories/creator-payment';
|
||||
export type { CreatorPaymentPayload } from './repositories/creator-payment';
|
||||
earningsKeys,
|
||||
earningsRepository,
|
||||
LEDGER_FILTER_PARAM,
|
||||
LEDGER_FILTERS,
|
||||
} from './repositories/earnings';
|
||||
export type {
|
||||
BalancePayload,
|
||||
CorrectionLedgerItemPayload,
|
||||
IncomeLedgerItemPayload,
|
||||
LedgerFilter,
|
||||
LedgerItemPayload,
|
||||
LedgerPagePayload,
|
||||
ListLedgerArgs,
|
||||
PayoutLedgerItemPayload,
|
||||
PayoutReceiptPayload,
|
||||
RefundLedgerItemPayload,
|
||||
} from './repositories/earnings';
|
||||
export {
|
||||
PAYOUT_ACCOUNT_ERROR_CODES,
|
||||
payoutAccountKeys,
|
||||
payoutAccountRepository,
|
||||
} from './repositories/payout-account';
|
||||
export type {
|
||||
CheckPayoutAccountArgs,
|
||||
CheckPayoutAccountPayload,
|
||||
PayoutAccountPayload,
|
||||
SavePayoutAccountArgs,
|
||||
} from './repositories/payout-account';
|
||||
|
|
|
|||
|
|
@ -0,0 +1,2 @@
|
|||
export { useBalancePart } from './use-balance-part';
|
||||
export type { BalancePartModel } from './types';
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import type { BalancePayload } from '../../repositories/earnings';
|
||||
|
||||
export type BalancePartModel = {
|
||||
balance: BalancePayload;
|
||||
};
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
import { useSuspenseQuery } from '@tanstack/react-query';
|
||||
|
||||
import { earningsKeys, earningsRepository } from '../../repositories/earnings';
|
||||
import type { BalancePartModel } from './types';
|
||||
|
||||
/**
|
||||
* مالی › the balance (C20 §۱), read in the browser with the creator's session. A failed first read
|
||||
* throws to the part's own boundary, so the ledger below still loads (۲.۴).
|
||||
*/
|
||||
export function useBalancePart(): BalancePartModel {
|
||||
const query = useSuspenseQuery({
|
||||
queryKey: earningsKeys.balance(),
|
||||
queryFn: ({ signal }) => earningsRepository.getBalance({ signal }),
|
||||
});
|
||||
return { balance: query.data };
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { useLedgerPart } from './use-ledger-part';
|
||||
export type { LedgerPartModel } from './types';
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import type { LoadMoreErrorKind } from '../../../../shared/utils';
|
||||
import type {
|
||||
LedgerFilter,
|
||||
LedgerItemPayload,
|
||||
PayoutReceiptPayload,
|
||||
} from '../../repositories/earnings';
|
||||
|
||||
export type LedgerPartModel = {
|
||||
filter: LedgerFilter;
|
||||
setFilter: (filter: LedgerFilter) => void;
|
||||
/** The tab is changing: the rows stay until the new ones arrive. */
|
||||
isFiltering: boolean;
|
||||
rows: LedgerItemPayload[];
|
||||
/** This tab has no row at all. */
|
||||
isEmpty: boolean;
|
||||
hasMore: boolean;
|
||||
loadMore: () => void;
|
||||
isLoadingMore: boolean;
|
||||
loadMoreError: LoadMoreErrorKind | null;
|
||||
/** The row whose details are open; it stays set while the sheet closes. */
|
||||
detail: LedgerItemPayload | null;
|
||||
isDetailOpen: boolean;
|
||||
openDetail: (row: LedgerItemPayload) => void;
|
||||
closeDetail: () => void;
|
||||
/** مشاهده رسید: an image opens in the lightbox once it has loaded, a PDF in a new tab. */
|
||||
viewReceipt: (receipt: PayoutReceiptPayload) => void;
|
||||
isReceiptLoading: boolean;
|
||||
/** The receipt could not be shown (C20 ۳.۸); the buttons stay as the retry. */
|
||||
receiptFailed: boolean;
|
||||
/** The image receipt in the lightbox, if open. */
|
||||
lightboxReceipt: PayoutReceiptPayload | null;
|
||||
closeLightbox: () => void;
|
||||
};
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
import { useSuspenseInfiniteQuery } from '@tanstack/react-query';
|
||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useState, useTransition } from 'react';
|
||||
|
||||
import { firstOfEach, loadMoreErrorKind } from '../../../../shared/utils';
|
||||
import {
|
||||
earningsKeys,
|
||||
earningsRepository,
|
||||
LEDGER_FILTER_PARAM,
|
||||
LEDGER_FILTERS,
|
||||
} from '../../repositories/earnings';
|
||||
import type {
|
||||
LedgerFilter,
|
||||
LedgerItemPayload,
|
||||
PayoutReceiptPayload,
|
||||
} from '../../repositories/earnings';
|
||||
import type { LedgerPartModel } from './types';
|
||||
|
||||
function toFilter(value: string | null): LedgerFilter {
|
||||
return LEDGER_FILTERS.find((filter) => filter === value) ?? 'all';
|
||||
}
|
||||
|
||||
/**
|
||||
* مالی › گردش حساب (C20 §۲–۳): همه or واریزها, newest first, 20 a page, the tab in the URL. Rows
|
||||
* stay while a tab or the next page loads. A row opens its details; a payout's receipt opens in
|
||||
* the lightbox (an image, once loaded) or a new tab (a PDF). An image that won't load says so
|
||||
* under the buttons, which stay as the retry.
|
||||
*/
|
||||
export function useLedgerPart(): LedgerPartModel {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
const [isFiltering, startFiltering] = useTransition();
|
||||
const [detail, setDetail] = useState<LedgerItemPayload | null>(null);
|
||||
const [isDetailOpen, setIsDetailOpen] = useState(false);
|
||||
const [isReceiptLoading, setIsReceiptLoading] = useState(false);
|
||||
const [receiptFailed, setReceiptFailed] = useState(false);
|
||||
const [lightboxReceipt, setLightboxReceipt] =
|
||||
useState<PayoutReceiptPayload | null>(null);
|
||||
const filter = toFilter(searchParams.get(LEDGER_FILTER_PARAM));
|
||||
|
||||
const list = useSuspenseInfiniteQuery({
|
||||
queryKey: earningsKeys.ledger(filter),
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
earningsRepository.listLedger({ filter, page: pageParam }, { signal }),
|
||||
initialPageParam: 1,
|
||||
getNextPageParam: (last) => (last.hasMore ? last.page + 1 : undefined),
|
||||
});
|
||||
|
||||
const setFilter = (next: LedgerFilter) => {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (next === 'all') params.delete(LEDGER_FILTER_PARAM);
|
||||
else params.set(LEDGER_FILTER_PARAM, next);
|
||||
const query = params.toString();
|
||||
startFiltering(() => {
|
||||
router.replace(query ? `${pathname}?${query}` : pathname, {
|
||||
scroll: false,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const viewReceipt = (receipt: PayoutReceiptPayload) => {
|
||||
setReceiptFailed(false);
|
||||
if (!receipt.isImage) {
|
||||
window.open(receipt.url, '_blank', 'noopener');
|
||||
return;
|
||||
}
|
||||
setIsReceiptLoading(true);
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
setIsReceiptLoading(false);
|
||||
setLightboxReceipt(receipt);
|
||||
};
|
||||
image.onerror = () => {
|
||||
setIsReceiptLoading(false);
|
||||
setReceiptFailed(true);
|
||||
};
|
||||
image.src = receipt.url;
|
||||
};
|
||||
|
||||
return {
|
||||
filter,
|
||||
setFilter,
|
||||
isFiltering,
|
||||
rows: firstOfEach(
|
||||
list.data.pages.flatMap((page) => page.items),
|
||||
(row) => row.id,
|
||||
),
|
||||
isEmpty: !list.data.pages[0].hasAny,
|
||||
hasMore: list.hasNextPage,
|
||||
loadMore: () => {
|
||||
// fetchNextPage would cancel a read of every page on its way and skip or repeat rows.
|
||||
if (!list.isFetching) void list.fetchNextPage();
|
||||
},
|
||||
isLoadingMore: list.isFetchingNextPage,
|
||||
loadMoreError: list.isFetchNextPageError
|
||||
? loadMoreErrorKind(list.error)
|
||||
: null,
|
||||
detail,
|
||||
isDetailOpen,
|
||||
openDetail: (row) => {
|
||||
setDetail(row);
|
||||
setReceiptFailed(false);
|
||||
setIsDetailOpen(true);
|
||||
},
|
||||
closeDetail: () => setIsDetailOpen(false),
|
||||
viewReceipt,
|
||||
isReceiptLoading,
|
||||
receiptFailed,
|
||||
lightboxReceipt,
|
||||
closeLightbox: () => setLightboxReceipt(null),
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { usePayoutAccountPart } from './use-payout-account-part';
|
||||
export type { PayoutAccountPartModel, PayoutAccountPhase } from './types';
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
import type { UseFormReturn } from 'react-hook-form';
|
||||
|
||||
import type {
|
||||
PayoutAccountFormOutput,
|
||||
PayoutAccountFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import type { PayoutAccountState } from '../../entities/earnings';
|
||||
import type { PayoutAccountPayload } from '../../repositories/payout-account';
|
||||
|
||||
/**
|
||||
* view: the saved card, or the empty line. editing: the form, in place. confirming: the read-back
|
||||
* is open. saving: «ثبت نهایی» is on its way.
|
||||
*/
|
||||
export type PayoutAccountPhase = 'view' | 'editing' | 'confirming' | 'saving';
|
||||
|
||||
export type PayoutAccountPartModel = {
|
||||
state: PayoutAccountState;
|
||||
account: PayoutAccountPayload['account'];
|
||||
phase: PayoutAccountPhase;
|
||||
isEditing: boolean;
|
||||
/** No شبا and money waiting: «درآمد شما … محفوظ است» above the CTA (C19 ۱.۲). */
|
||||
showHeldNote: boolean;
|
||||
/** «ثبت شماره شبا» or «ویرایش»: the form, pre-filled with the saved number, the box cleared. */
|
||||
startEditing: () => void;
|
||||
/** «انصراف»: back to the saved card, nothing saved. */
|
||||
cancelEditing: () => void;
|
||||
form: UseFormReturn<
|
||||
PayoutAccountFormValues,
|
||||
unknown,
|
||||
PayoutAccountFormOutput
|
||||
>;
|
||||
/** The field's text after `IR`, grouped in fours. */
|
||||
ibanText: string;
|
||||
/** Every keystroke and paste: normalized silently, then grouped. */
|
||||
changeIban: (text: string) => void;
|
||||
/** On blur: whether another account registered this valid number. */
|
||||
checkDuplicate: () => void;
|
||||
/** The bank's code while it can be named; its name comes from the translations. */
|
||||
bankCode: string | null;
|
||||
duplicate: boolean;
|
||||
/** The 24 digits the read-back shows and «ثبت نهایی» saves. */
|
||||
readBackIban: string;
|
||||
/** «ثبت شماره شبا»: both checks, then the read-back. */
|
||||
submit: () => void;
|
||||
/** «ویرایش» in the read-back: the form, with the number and the tick kept. */
|
||||
closeReadBack: () => void;
|
||||
/** «ثبت نهایی». */
|
||||
confirm: () => void;
|
||||
isSaving: boolean;
|
||||
};
|
||||
|
|
@ -0,0 +1,212 @@
|
|||
import { valibotResolver } from '@hookform/resolvers/valibot';
|
||||
import { showToast } from '@lumina/island/molecules/toast';
|
||||
import { handleError } from '@lumina/libs/error-handler';
|
||||
import { isHttpError } from '@lumina/libs/http';
|
||||
import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
useSuspenseQuery,
|
||||
} from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useForm, useWatch } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import {
|
||||
groupIbanDigits,
|
||||
ibanBankCode,
|
||||
ibanProblem,
|
||||
isConnectionError,
|
||||
normalizeIban,
|
||||
showActionError,
|
||||
} from '../../../../shared/utils';
|
||||
import { payoutAccountSchema } from '../../../../shared/validations';
|
||||
import type {
|
||||
PayoutAccountFormOutput,
|
||||
PayoutAccountFormValues,
|
||||
} from '../../../../shared/validations';
|
||||
import { savePayoutAccount } from '../../actions/save-payout-account';
|
||||
import { earningsKeys, earningsRepository } from '../../repositories/earnings';
|
||||
import {
|
||||
PAYOUT_ACCOUNT_ERROR_CODES,
|
||||
payoutAccountKeys,
|
||||
payoutAccountRepository,
|
||||
} from '../../repositories/payout-account';
|
||||
import type { PayoutAccountPayload } from '../../repositories/payout-account';
|
||||
import type { PayoutAccountPartModel, PayoutAccountPhase } from './types';
|
||||
|
||||
const EMPTY_FORM: PayoutAccountFormValues = { iban: '', confirmed: false };
|
||||
|
||||
/** The field's text: the digits grouped as banks print them, or as typed while it holds other characters. */
|
||||
function toFieldText(input: string): string {
|
||||
const iban = normalizeIban(input);
|
||||
return /^\d*$/.test(iban) ? groupIbanDigits(iban) : iban;
|
||||
}
|
||||
|
||||
/**
|
||||
* مالی › اطلاعات تسویهحساب (C19). The block is the saved card, the empty line with its CTA, or
|
||||
* the form, expanded in place (no pushed page). The شبا is normalized as typed and checked on blur
|
||||
* and on submit; its bank shows from the fifth digit while the number isn't known to be wrong.
|
||||
* A valid number is checked for another account's use on blur, as a warning only. Submit opens the
|
||||
* read-back; «ثبت نهایی» saves, collapses the block and toasts. A failed save keeps the number and
|
||||
* the tick and says why at the top of the card. Unverified and suspended creators can't edit (۱.۳,
|
||||
* ۵.۳). Every edit clears the box: it is ticked again each time.
|
||||
*/
|
||||
export function usePayoutAccountPart(): PayoutAccountPartModel {
|
||||
const { t } = useTranslation('finance');
|
||||
const queryClient = useQueryClient();
|
||||
const [phase, setPhase] = useState<PayoutAccountPhase>('view');
|
||||
const [duplicate, setDuplicate] = useState(false);
|
||||
const [checked, setChecked] = useState<string | null>(null);
|
||||
|
||||
const query = useSuspenseQuery({
|
||||
queryKey: payoutAccountKeys.detail(),
|
||||
queryFn: ({ signal }) => payoutAccountRepository.get({ signal }),
|
||||
});
|
||||
// The balance part reads it too; here it only decides the reassuring note (۱.۲).
|
||||
const balance = useQuery({
|
||||
queryKey: earningsKeys.balance(),
|
||||
queryFn: ({ signal }) => earningsRepository.getBalance({ signal }),
|
||||
throwOnError: false,
|
||||
});
|
||||
|
||||
const form = useForm<
|
||||
PayoutAccountFormValues,
|
||||
unknown,
|
||||
PayoutAccountFormOutput
|
||||
>({
|
||||
resolver: valibotResolver(payoutAccountSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: EMPTY_FORM,
|
||||
});
|
||||
const [ibanText] = useWatch({ control: form.control, name: ['iban'] });
|
||||
const iban = normalizeIban(ibanText);
|
||||
const ibanError = form.formState.errors.iban?.message;
|
||||
const problem = ibanError ? ibanProblem(iban) : null;
|
||||
// A confident bank name beside a number known to be wrong reads as a confirmation (۳.۲, ۳.۵).
|
||||
const bankCode =
|
||||
problem === 'checksum' || problem === 'non_digit'
|
||||
? null
|
||||
: ibanBankCode(iban);
|
||||
|
||||
const { state, account } = query.data;
|
||||
const isEditing = phase !== 'view';
|
||||
|
||||
const startEditing = () => {
|
||||
form.reset(
|
||||
account
|
||||
? { iban: groupIbanDigits(account.iban), confirmed: false }
|
||||
: EMPTY_FORM,
|
||||
);
|
||||
setDuplicate(false);
|
||||
setChecked(null);
|
||||
setPhase('editing');
|
||||
};
|
||||
|
||||
const cancelEditing = () => {
|
||||
form.reset(EMPTY_FORM);
|
||||
setPhase('view');
|
||||
};
|
||||
|
||||
const changeIban = (text: string) => {
|
||||
form.setValue('iban', toFieldText(text), {
|
||||
shouldDirty: true,
|
||||
shouldValidate: form.formState.touchedFields.iban === true,
|
||||
});
|
||||
if (duplicate) setDuplicate(false);
|
||||
};
|
||||
|
||||
// Advisory only: no message on failure, and the save never waits for it (§۶).
|
||||
const checkDuplicate = () => {
|
||||
if (ibanProblem(iban) !== null || checked === iban) return;
|
||||
setChecked(iban);
|
||||
payoutAccountRepository
|
||||
.check({ iban })
|
||||
.then((result) => {
|
||||
if (normalizeIban(form.getValues('iban')) === iban) {
|
||||
setDuplicate(result.duplicate);
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
handleError(error, { where: 'action', name: 'payout-account-check' });
|
||||
setChecked(null);
|
||||
});
|
||||
};
|
||||
|
||||
const failed = (error: unknown) => {
|
||||
setPhase('editing');
|
||||
if (
|
||||
isHttpError(error) &&
|
||||
error.code === PAYOUT_ACCOUNT_ERROR_CODES.invalid
|
||||
) {
|
||||
form.setError(
|
||||
'iban',
|
||||
{ type: 'server', message: 'finance:account.errors.checksum' },
|
||||
{ shouldFocus: true },
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
isHttpError(error) &&
|
||||
error.code === PAYOUT_ACCOUNT_ERROR_CODES.locked
|
||||
) {
|
||||
// Suspended or no longer verified since the page loaded: show the block as it is now.
|
||||
void queryClient.invalidateQueries({ queryKey: payoutAccountKeys.all });
|
||||
setPhase('view');
|
||||
} else {
|
||||
const message = isConnectionError(error)
|
||||
? 'finance:account.save-errors.network'
|
||||
: isHttpError(error) && error.status === 401
|
||||
? 'finance:account.save-errors.session'
|
||||
: 'finance:account.save-errors.server';
|
||||
form.setError('root.server', { type: 'server', message });
|
||||
}
|
||||
showActionError(error, { t, failedMessage: t('account.save-failed') });
|
||||
};
|
||||
|
||||
const confirm = async () => {
|
||||
const values = form.getValues();
|
||||
setPhase('saving');
|
||||
try {
|
||||
const saved = await savePayoutAccount({
|
||||
iban: normalizeIban(values.iban),
|
||||
confirmed: true,
|
||||
});
|
||||
queryClient.setQueryData<PayoutAccountPayload>(
|
||||
payoutAccountKeys.detail(),
|
||||
saved,
|
||||
);
|
||||
// The next-payout line depends on whether a شبا is registered.
|
||||
void queryClient.invalidateQueries({ queryKey: earningsKeys.balance() });
|
||||
form.reset(EMPTY_FORM);
|
||||
setPhase('view');
|
||||
showToast({ tone: 'success', message: t('account.saved') });
|
||||
} catch (error) {
|
||||
failed(error);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
account,
|
||||
phase,
|
||||
isEditing,
|
||||
// A zero or negative balance needs no reassurance: nothing is waiting (۱.۱).
|
||||
showHeldNote: !account && (balance.data?.availableToman ?? 0) > 0,
|
||||
startEditing,
|
||||
cancelEditing,
|
||||
form,
|
||||
ibanText,
|
||||
changeIban,
|
||||
checkDuplicate,
|
||||
bankCode,
|
||||
duplicate,
|
||||
readBackIban: iban,
|
||||
submit: () => {
|
||||
form.clearErrors('root.server');
|
||||
void form.handleSubmit(() => setPhase('confirming'))();
|
||||
},
|
||||
closeReadBack: () => setPhase('editing'),
|
||||
confirm: () => void confirm(),
|
||||
isSaving: phase === 'saving',
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
export const CREATOR_PAYMENTS_ENDPOINT = '/subscriptions/me/transactions';
|
||||
|
||||
export const financeKeys = {
|
||||
all: ['finance'] as const,
|
||||
payments: () => [...financeKeys.all, 'payments'] as const,
|
||||
};
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
import { financeHttp } from '../../http';
|
||||
import { CREATOR_PAYMENTS_ENDPOINT } from './constants';
|
||||
import { toCreatorPaymentPayload } from './mappers';
|
||||
import type {
|
||||
CreatorPaymentPayload,
|
||||
CreatorPaymentsResponseDto,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* Payments the signed-in creator received (the latest 100, newest first, every status). Creator
|
||||
* session only: an investor gets 403. Payouts, balances and شبا have no API yet.
|
||||
*/
|
||||
export const creatorPaymentRepository = {
|
||||
async list({ signal }: { signal?: AbortSignal } = {}): Promise<
|
||||
CreatorPaymentPayload[]
|
||||
> {
|
||||
const response = await financeHttp.get<CreatorPaymentsResponseDto>(
|
||||
CREATOR_PAYMENTS_ENDPOINT,
|
||||
{ signal },
|
||||
);
|
||||
return response.items.map(toCreatorPaymentPayload);
|
||||
},
|
||||
};
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
export { financeKeys } from './constants';
|
||||
export { creatorPaymentRepository } from './creator-payment';
|
||||
export type { CreatorPaymentPayload } from './types';
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
import type { PaymentEntity } from '../../../transaction';
|
||||
import type { CreatorPaymentPayload } from './types';
|
||||
|
||||
export function toCreatorPaymentPayload(
|
||||
dto: PaymentEntity,
|
||||
): CreatorPaymentPayload {
|
||||
return {
|
||||
id: dto.id,
|
||||
subscriberId: dto.userId,
|
||||
subscriptionId: dto.subscriptionId,
|
||||
type: dto.type.value,
|
||||
billingPeriod: dto.billingPeriod,
|
||||
amountToman: dto.toman,
|
||||
createdAt: dto.createdAt,
|
||||
status: dto.status.value,
|
||||
rawStatus: dto.rawStatus,
|
||||
reference: dto.reference.value,
|
||||
period: dto.period ? { from: dto.period.from, to: dto.period.to } : null,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
import type {
|
||||
BillingPeriod,
|
||||
PaymentStatus,
|
||||
PaymentUiStatus,
|
||||
TransactionKind,
|
||||
} from '../../../../shared/constants';
|
||||
import type { PaymentEntity } from '../../../transaction';
|
||||
|
||||
/**
|
||||
* A subscription payment the creator received, any status. The subscriber is a user id only: no
|
||||
* username is sent. Amounts are what the subscriber paid; there is no commission or share yet.
|
||||
*/
|
||||
export type CreatorPaymentPayload = {
|
||||
id: string;
|
||||
subscriberId: string;
|
||||
subscriptionId: string | null;
|
||||
type: TransactionKind;
|
||||
billingPeriod: BillingPeriod;
|
||||
amountToman: number | null;
|
||||
createdAt: string | null;
|
||||
status: PaymentUiStatus;
|
||||
rawStatus: PaymentStatus;
|
||||
/** Tracking code, else bank ref, else authority; `null` for a development grant. */
|
||||
reference: string | null;
|
||||
/** The period bought; only on a successful payment. */
|
||||
period: { from: string | null; to: string | null } | null;
|
||||
};
|
||||
|
||||
/** The latest 100, newest first; the server has no pagination. */
|
||||
export type CreatorPaymentsResponseDto = { items: PaymentEntity[] };
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import type { LedgerFilter } from './types';
|
||||
|
||||
/** گردش حساب's tabs in display order: همه · واریزها (C20 §۲). */
|
||||
export const LEDGER_FILTERS = [
|
||||
'all',
|
||||
'payouts',
|
||||
] as const satisfies readonly LedgerFilter[];
|
||||
|
||||
/** The URL's query parameter that holds the ledger tab, so it survives a refresh. */
|
||||
export const LEDGER_FILTER_PARAM = 'ledger';
|
||||
|
||||
export const EARNINGS_ENDPOINTS = {
|
||||
balance: '/payouts/me/balance',
|
||||
ledger: '/payouts/me/ledger',
|
||||
receipt: (payoutId: string) =>
|
||||
`/v1/payouts/me/payouts/${encodeURIComponent(payoutId)}/receipt`,
|
||||
} as const;
|
||||
|
||||
export const earningsKeys = {
|
||||
all: ['finance', 'earnings'] as const,
|
||||
balance: () => [...earningsKeys.all, 'balance'] as const,
|
||||
ledgers: () => [...earningsKeys.all, 'ledger'] as const,
|
||||
/** One infinite list per tab; pages are its page params. */
|
||||
ledger: (filter: LedgerFilter = 'all') =>
|
||||
[...earningsKeys.ledgers(), filter] as const,
|
||||
};
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
import { financeHttp } from '../../http';
|
||||
import { EARNINGS_ENDPOINTS } from './constants';
|
||||
import {
|
||||
toBalancePayload,
|
||||
toLedgerPagePayload,
|
||||
toListLedgerQueryDto,
|
||||
} from './mappers';
|
||||
import type {
|
||||
BalancePayload,
|
||||
BalanceResponseDto,
|
||||
LedgerPagePayload,
|
||||
LedgerPageResponseDto,
|
||||
ListLedgerArgs,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The signed-in creator's earnings (C20): the balance and گردش حساب, every figure derived on the
|
||||
* server from immutable records. Creator session only. A payout's receipt is streamed from its own
|
||||
* URL with the session cookie, so it needs no call here.
|
||||
*/
|
||||
export const earningsRepository = {
|
||||
async getBalance({
|
||||
signal,
|
||||
}: { signal?: AbortSignal } = {}): Promise<BalancePayload> {
|
||||
const response = await financeHttp.get<BalanceResponseDto>(
|
||||
EARNINGS_ENDPOINTS.balance,
|
||||
{ signal },
|
||||
);
|
||||
return toBalancePayload(response);
|
||||
},
|
||||
|
||||
/** Newest first, 20 a page: every line and payout (`all`) or payouts only. */
|
||||
async listLedger(
|
||||
args: ListLedgerArgs = {},
|
||||
{ signal }: { signal?: AbortSignal } = {},
|
||||
): Promise<LedgerPagePayload> {
|
||||
const response = await financeHttp.get<LedgerPageResponseDto>(
|
||||
EARNINGS_ENDPOINTS.ledger,
|
||||
{ params: toListLedgerQueryDto(args), signal },
|
||||
);
|
||||
return toLedgerPagePayload(response);
|
||||
},
|
||||
};
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
export {
|
||||
EARNINGS_ENDPOINTS,
|
||||
earningsKeys,
|
||||
LEDGER_FILTER_PARAM,
|
||||
LEDGER_FILTERS,
|
||||
} from './constants';
|
||||
export { earningsRepository } from './earnings';
|
||||
export type {
|
||||
BalancePayload,
|
||||
CorrectionLedgerItemPayload,
|
||||
IncomeLedgerItemPayload,
|
||||
LedgerFilter,
|
||||
LedgerItemPayload,
|
||||
LedgerPagePayload,
|
||||
ListLedgerArgs,
|
||||
PayoutLedgerItemPayload,
|
||||
PayoutReceiptPayload,
|
||||
RefundLedgerItemPayload,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
import { toApiUrl } from '../../../../shared/utils';
|
||||
import type { LedgerItemEntity } from '../../entities/earnings';
|
||||
import { EARNINGS_ENDPOINTS } from './constants';
|
||||
import type {
|
||||
BalancePayload,
|
||||
BalanceResponseDto,
|
||||
LedgerItemPayload,
|
||||
LedgerPagePayload,
|
||||
LedgerPageResponseDto,
|
||||
ListLedgerArgs,
|
||||
ListLedgerQueryDto,
|
||||
PayoutReceiptPayload,
|
||||
} from './types';
|
||||
|
||||
export function toBalancePayload(dto: BalanceResponseDto): BalancePayload {
|
||||
return {
|
||||
availableToman: dto.availableToman,
|
||||
inTransitToman: dto.inTransitToman,
|
||||
paidTotalToman: dto.paidTotalToman,
|
||||
hasAccount: dto.hasAccount,
|
||||
suspended: dto.suspended,
|
||||
nextPayout: { state: dto.nextPayout.state, date: dto.nextPayout.date },
|
||||
};
|
||||
}
|
||||
|
||||
export function toListLedgerQueryDto(args: ListLedgerArgs): ListLedgerQueryDto {
|
||||
return { type: args.filter ?? 'all', page: args.page ?? 1 };
|
||||
}
|
||||
|
||||
function toReceiptPayload(
|
||||
payoutId: string,
|
||||
mimeType: string | null,
|
||||
): PayoutReceiptPayload | null {
|
||||
const url = toApiUrl(EARNINGS_ENDPOINTS.receipt(payoutId));
|
||||
if (!url) return null;
|
||||
return {
|
||||
url,
|
||||
downloadUrl: `${url}?download=1`,
|
||||
isImage: (mimeType ?? '').startsWith('image/'),
|
||||
};
|
||||
}
|
||||
|
||||
export function toLedgerItemPayload(dto: LedgerItemEntity): LedgerItemPayload {
|
||||
const base = {
|
||||
id: dto.id,
|
||||
amountToman: dto.amountToman,
|
||||
occurredAt: dto.occurredAt,
|
||||
};
|
||||
switch (dto.kind) {
|
||||
case 'income':
|
||||
return { ...base, kind: 'income', ...dto.income };
|
||||
case 'refund_deduction':
|
||||
return { ...base, kind: 'refund_deduction', ...dto.refund };
|
||||
case 'correction':
|
||||
return { ...base, kind: 'correction', reason: dto.correction.reason };
|
||||
case 'payout':
|
||||
return {
|
||||
...base,
|
||||
kind: 'payout',
|
||||
status: dto.payout.status,
|
||||
ibanCheckDigits: dto.payout.ibanCheckDigits,
|
||||
ibanTail: dto.payout.ibanTail,
|
||||
completedAt: dto.payout.completedAt,
|
||||
cancelledAt: dto.payout.cancelledAt,
|
||||
cancelReason: dto.payout.cancelReason,
|
||||
receipt: dto.payout.hasReceipt
|
||||
? toReceiptPayload(dto.id, dto.payout.receiptMimeType)
|
||||
: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function toLedgerPagePayload(
|
||||
dto: LedgerPageResponseDto,
|
||||
): LedgerPagePayload {
|
||||
return {
|
||||
items: dto.items.map(toLedgerItemPayload),
|
||||
page: dto.page,
|
||||
hasMore: dto.hasMore,
|
||||
hasAny: dto.hasAny,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
import type { BillingPeriod } from '../../../../shared/constants';
|
||||
import type {
|
||||
LedgerItemEntity,
|
||||
NextPayoutState,
|
||||
PayoutStatus,
|
||||
} from '../../entities/earnings';
|
||||
|
||||
// GET /payouts/me/balance
|
||||
|
||||
export type BalanceResponseDto = {
|
||||
availableToman: number;
|
||||
inTransitToman: number;
|
||||
paidTotalToman: number;
|
||||
hasAccount: boolean;
|
||||
suspended: boolean;
|
||||
nextPayout: { state: NextPayoutState; date: string | null };
|
||||
};
|
||||
|
||||
/**
|
||||
* The creator's balance (C20 §۱): قابل واریز (below zero after a refund), در حال واریز and
|
||||
* مجموع واریزشده, with what the next-payout line says.
|
||||
*/
|
||||
export type BalancePayload = {
|
||||
availableToman: number;
|
||||
inTransitToman: number;
|
||||
paidTotalToman: number;
|
||||
hasAccount: boolean;
|
||||
suspended: boolean;
|
||||
nextPayout: {
|
||||
state: NextPayoutState;
|
||||
/** The payout day, only when `scheduled`. */
|
||||
date: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
// GET /payouts/me/ledger
|
||||
|
||||
export type LedgerFilter = 'all' | 'payouts';
|
||||
|
||||
export type ListLedgerArgs = { filter?: LedgerFilter; page?: number };
|
||||
export type ListLedgerQueryDto = { type: LedgerFilter; page: number };
|
||||
|
||||
export type LedgerPageResponseDto = {
|
||||
items: LedgerItemEntity[];
|
||||
page: number;
|
||||
hasMore: boolean;
|
||||
hasAny: boolean;
|
||||
};
|
||||
|
||||
type LedgerItemBasePayload = {
|
||||
id: string;
|
||||
amountToman: number;
|
||||
occurredAt: string;
|
||||
};
|
||||
|
||||
/** Where a payout's receipt opens and downloads, through this site's API proxy. */
|
||||
export type PayoutReceiptPayload = {
|
||||
url: string;
|
||||
downloadUrl: string;
|
||||
/** An image opens in the lightbox; a PDF in a new tab. */
|
||||
isImage: boolean;
|
||||
};
|
||||
|
||||
export type IncomeLedgerItemPayload = LedgerItemBasePayload & {
|
||||
kind: 'income';
|
||||
subscriberUsername: string | null;
|
||||
billingPeriod: BillingPeriod | null;
|
||||
planPriceToman: number;
|
||||
discountPercent: number | null;
|
||||
paidToman: number;
|
||||
commissionPercent: number;
|
||||
commissionToman: number;
|
||||
shareToman: number;
|
||||
};
|
||||
|
||||
export type RefundLedgerItemPayload = LedgerItemBasePayload & {
|
||||
kind: 'refund_deduction';
|
||||
subscriberUsername: string | null;
|
||||
billingPeriod: BillingPeriod | null;
|
||||
originalPaidAt: string | null;
|
||||
refundedToman: number;
|
||||
deductedToman: number;
|
||||
};
|
||||
|
||||
export type CorrectionLedgerItemPayload = LedgerItemBasePayload & {
|
||||
kind: 'correction';
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export type PayoutLedgerItemPayload = LedgerItemBasePayload & {
|
||||
kind: 'payout';
|
||||
status: PayoutStatus;
|
||||
ibanCheckDigits: string;
|
||||
/** The destination's last six digits, as recorded when the payout was made. */
|
||||
ibanTail: string;
|
||||
completedAt: string | null;
|
||||
cancelledAt: string | null;
|
||||
cancelReason: string | null;
|
||||
receipt: PayoutReceiptPayload | null;
|
||||
};
|
||||
|
||||
/** One row of گردش حساب (C20 §۲), with everything its detail sheet shows (§۳). */
|
||||
export type LedgerItemPayload =
|
||||
| IncomeLedgerItemPayload
|
||||
| RefundLedgerItemPayload
|
||||
| CorrectionLedgerItemPayload
|
||||
| PayoutLedgerItemPayload;
|
||||
|
||||
export type LedgerPagePayload = {
|
||||
items: LedgerItemPayload[];
|
||||
page: number;
|
||||
hasMore: boolean;
|
||||
/** Whether this tab has any row at all: its empty state otherwise. */
|
||||
hasAny: boolean;
|
||||
};
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
export const PAYOUT_ACCOUNT_ENDPOINTS = {
|
||||
account: '/payouts/me/account',
|
||||
check: '/payouts/me/account/check',
|
||||
} as const;
|
||||
|
||||
/** The API's stable `code`s for a refused شبا (back `PAYOUT_ERROR_CODES`). */
|
||||
export const PAYOUT_ACCOUNT_ERROR_CODES = {
|
||||
locked: 'PAYOUT_ACCOUNT_LOCKED',
|
||||
invalid: 'PAYOUT_IBAN_INVALID',
|
||||
} as const;
|
||||
|
||||
export const payoutAccountKeys = {
|
||||
all: ['finance', 'payout-account'] as const,
|
||||
detail: () => [...payoutAccountKeys.all, 'detail'] as const,
|
||||
};
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
export { PAYOUT_ACCOUNT_ERROR_CODES, payoutAccountKeys } from './constants';
|
||||
export { payoutAccountRepository } from './payout-account';
|
||||
export type {
|
||||
CheckPayoutAccountArgs,
|
||||
CheckPayoutAccountPayload,
|
||||
PayoutAccountPayload,
|
||||
SavePayoutAccountArgs,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import { ibanBankCode } from '../../../../shared/utils';
|
||||
import type {
|
||||
CheckPayoutAccountArgs,
|
||||
CheckPayoutAccountDto,
|
||||
PayoutAccountPayload,
|
||||
PayoutAccountResponseDto,
|
||||
SavePayoutAccountArgs,
|
||||
SavePayoutAccountDto,
|
||||
} from './types';
|
||||
|
||||
export function toPayoutAccountPayload(
|
||||
dto: PayoutAccountResponseDto,
|
||||
): PayoutAccountPayload {
|
||||
return {
|
||||
state: dto.state,
|
||||
account: dto.account
|
||||
? {
|
||||
iban: dto.account.iban,
|
||||
bankCode: ibanBankCode(dto.account.iban),
|
||||
savedAt: dto.account.savedAt,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function toCheckPayoutAccountDto(
|
||||
args: CheckPayoutAccountArgs,
|
||||
): CheckPayoutAccountDto {
|
||||
return { iban: args.iban };
|
||||
}
|
||||
|
||||
export function toSavePayoutAccountDto(
|
||||
args: SavePayoutAccountArgs,
|
||||
): SavePayoutAccountDto {
|
||||
return { iban: args.iban, confirmed: args.confirmed };
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
import { financeHttp } from '../../http';
|
||||
import { PAYOUT_ACCOUNT_ENDPOINTS } from './constants';
|
||||
import {
|
||||
toCheckPayoutAccountDto,
|
||||
toPayoutAccountPayload,
|
||||
toSavePayoutAccountDto,
|
||||
} from './mappers';
|
||||
import type {
|
||||
CheckPayoutAccountArgs,
|
||||
CheckPayoutAccountPayload,
|
||||
CheckPayoutAccountResponseDto,
|
||||
PayoutAccountPayload,
|
||||
PayoutAccountResponseDto,
|
||||
SavePayoutAccountArgs,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The signed-in creator's شبا (C19): one number, no account-holder name, used from the next payout
|
||||
* with no admin approval. Creator session only. A save while unverified or suspended is a 403
|
||||
* `PAYOUT_ACCOUNT_LOCKED`; an invalid number a 400 `PAYOUT_IBAN_INVALID`.
|
||||
*/
|
||||
export const payoutAccountRepository = {
|
||||
async get({
|
||||
signal,
|
||||
}: { signal?: AbortSignal } = {}): Promise<PayoutAccountPayload> {
|
||||
const response = await financeHttp.get<PayoutAccountResponseDto>(
|
||||
PAYOUT_ACCOUNT_ENDPOINTS.account,
|
||||
{ signal },
|
||||
);
|
||||
return toPayoutAccountPayload(response);
|
||||
},
|
||||
|
||||
/** Advisory, on blur: whether another account registered this valid number. */
|
||||
async check(
|
||||
args: CheckPayoutAccountArgs,
|
||||
{ signal }: { signal?: AbortSignal } = {},
|
||||
): Promise<CheckPayoutAccountPayload> {
|
||||
const response = await financeHttp.post<CheckPayoutAccountResponseDto>(
|
||||
PAYOUT_ACCOUNT_ENDPOINTS.check,
|
||||
toCheckPayoutAccountDto(args),
|
||||
{ signal },
|
||||
);
|
||||
return { duplicate: response.duplicate };
|
||||
},
|
||||
|
||||
/** Registers or changes the number; a change sends the creator an SMS and a notice. */
|
||||
async save(args: SavePayoutAccountArgs): Promise<PayoutAccountPayload> {
|
||||
const response = await financeHttp.put<PayoutAccountResponseDto>(
|
||||
PAYOUT_ACCOUNT_ENDPOINTS.account,
|
||||
toSavePayoutAccountDto(args),
|
||||
);
|
||||
return toPayoutAccountPayload(response);
|
||||
},
|
||||
};
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import type {
|
||||
PayoutAccountEntity,
|
||||
PayoutAccountState,
|
||||
} from '../../entities/earnings';
|
||||
|
||||
export type PayoutAccountResponseDto = {
|
||||
state: PayoutAccountState;
|
||||
account: PayoutAccountEntity | null;
|
||||
};
|
||||
|
||||
/** The creator's شبا (C19), if registered, and whether they may change it now. */
|
||||
export type PayoutAccountPayload = {
|
||||
state: PayoutAccountState;
|
||||
account: {
|
||||
/** The 24 digits after `IR`. */
|
||||
iban: string;
|
||||
/** Digits 3–5, for the bank's name; `null` never happens for a saved number. */
|
||||
bankCode: string | null;
|
||||
savedAt: string;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type CheckPayoutAccountArgs = { iban: string };
|
||||
export type CheckPayoutAccountDto = { iban: string };
|
||||
export type CheckPayoutAccountResponseDto = { duplicate: boolean };
|
||||
/** Another account already registered this number: a warning, never a block (C19 §6). */
|
||||
export type CheckPayoutAccountPayload = { duplicate: boolean };
|
||||
|
||||
export type SavePayoutAccountArgs = {
|
||||
/** As normalized by `normalizeIban`: 24 digits, no `IR`. */
|
||||
iban: string;
|
||||
/** The responsibility box, ticked on every save. */
|
||||
confirmed: true;
|
||||
};
|
||||
export type SavePayoutAccountDto = SavePayoutAccountArgs;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
declare module '@lumina/libs/event-emitter' {
|
||||
interface EventMap {
|
||||
'finance.payout-account-saved': Record<string, never>;
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
|
|
@ -3,7 +3,9 @@
|
|||
* `waitlist_capacity` is sticky and replaced in place; the others expire after 30 days. The S7
|
||||
* ones follow an admin's suspension of a creator: `creator_suspended` and `access_restored` to its
|
||||
* subscribers, `account_suspended` and `account_reinstated` to the creator, and
|
||||
* `subscription_expired_suspended`, the expiry notice that points to support instead.
|
||||
* `subscription_expired_suspended`, the expiry notice that points to support instead. A creator's
|
||||
* money (C19 §۶, C20 §۴) brings `payout_account_changed`, `payout_created`, `payout_cancelled`,
|
||||
* `refund_deducted` and `ledger_correction`, each linking to مالی.
|
||||
*/
|
||||
export type NotificationType =
|
||||
| 'subscription_subscribe'
|
||||
|
|
@ -19,7 +21,12 @@ export type NotificationType =
|
|||
| 'creator_suspended'
|
||||
| 'access_restored'
|
||||
| 'account_suspended'
|
||||
| 'account_reinstated';
|
||||
| 'account_reinstated'
|
||||
| 'payout_account_changed'
|
||||
| 'payout_created'
|
||||
| 'payout_cancelled'
|
||||
| 'refund_deducted'
|
||||
| 'ledger_correction';
|
||||
|
||||
/** notification-service's inbox item (`toInboxItem`). `title` and `body` are composed Persian text. */
|
||||
export type NotificationEntity = {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
export { useOwnSubscriberCount } from './models/own-subscriber-count';
|
||||
export type { UseOwnSubscriberCountOptions } from './models/own-subscriber-count';
|
||||
export { useSubscribersPart } from './models/subscribers';
|
||||
export type { SubscribersPartModel } from './models/subscribers';
|
||||
export {
|
||||
creatorDashboardRepository,
|
||||
overviewKeys,
|
||||
|
|
@ -9,3 +11,12 @@ export type {
|
|||
CreatorTierPayload,
|
||||
RecentPaymentPayload,
|
||||
} from './repositories/creator-dashboard';
|
||||
export {
|
||||
creatorSubscribersRepository,
|
||||
subscriberKeys,
|
||||
} from './repositories/creator-subscribers';
|
||||
export type {
|
||||
ListSubscribersArgs,
|
||||
SubscriberPayload,
|
||||
SubscribersPagePayload,
|
||||
} from './repositories/creator-subscribers';
|
||||
|
|
|
|||
|
|
@ -0,0 +1,2 @@
|
|||
export { useSubscribersPart } from './use-subscribers-part';
|
||||
export type { SubscribersPartModel } from './types';
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import type { LoadMoreErrorKind } from '../../../../shared/utils';
|
||||
import type { SubscriberPayload } from '../../repositories/creator-subscribers';
|
||||
|
||||
export type SubscribersPartModel = {
|
||||
activeCount: number;
|
||||
rows: SubscriberPayload[];
|
||||
hasMore: boolean;
|
||||
loadMore: () => void;
|
||||
isLoadingMore: boolean;
|
||||
loadMoreError: LoadMoreErrorKind | null;
|
||||
};
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import { useSuspenseInfiniteQuery } from '@tanstack/react-query';
|
||||
|
||||
import { firstOfEach, loadMoreErrorKind } from '../../../../shared/utils';
|
||||
import {
|
||||
creatorSubscribersRepository,
|
||||
subscriberKeys,
|
||||
} from '../../repositories/creator-subscribers';
|
||||
import type { SubscribersPartModel } from './types';
|
||||
|
||||
/**
|
||||
* طرحهای اشتراک › مشترکان (Creator Dashboard ۲.۱): the active count and the running
|
||||
* subscriptions, newest start first, 20 at a time. No filters, search or actions until Epic 6.
|
||||
*/
|
||||
export function useSubscribersPart(): SubscribersPartModel {
|
||||
const list = useSuspenseInfiniteQuery({
|
||||
queryKey: subscriberKeys.list(),
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
creatorSubscribersRepository.list({ page: pageParam }, { signal }),
|
||||
initialPageParam: 1,
|
||||
getNextPageParam: (last) => (last.hasMore ? last.page + 1 : undefined),
|
||||
});
|
||||
|
||||
return {
|
||||
activeCount: list.data.pages[0].activeCount,
|
||||
rows: firstOfEach(
|
||||
list.data.pages.flatMap((page) => page.items),
|
||||
(row) => row.id,
|
||||
),
|
||||
hasMore: list.hasNextPage,
|
||||
loadMore: () => {
|
||||
if (!list.isFetching) void list.fetchNextPage();
|
||||
},
|
||||
isLoadingMore: list.isFetchingNextPage,
|
||||
loadMoreError: list.isFetchNextPageError
|
||||
? loadMoreErrorKind(list.error)
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
export const CREATOR_SUBSCRIBERS_ENDPOINT = '/subscriptions/me/subscribers';
|
||||
|
||||
export const subscriberKeys = {
|
||||
all: ['overview', 'subscribers'] as const,
|
||||
list: () => [...subscriberKeys.all, 'list'] as const,
|
||||
};
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { overviewHttp } from '../../http';
|
||||
import { CREATOR_SUBSCRIBERS_ENDPOINT } from './constants';
|
||||
import { toListSubscribersQueryDto, toSubscribersPagePayload } from './mappers';
|
||||
import type {
|
||||
ListSubscribersArgs,
|
||||
SubscribersPagePayload,
|
||||
SubscribersPageResponseDto,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The signed-in creator's running subscriptions, newest start first, 20 a page (Creator Dashboard
|
||||
* ۲.۱). Creator session only: an investor gets 403.
|
||||
*/
|
||||
export const creatorSubscribersRepository = {
|
||||
async list(
|
||||
args: ListSubscribersArgs = {},
|
||||
{ signal }: { signal?: AbortSignal } = {},
|
||||
): Promise<SubscribersPagePayload> {
|
||||
const response = await overviewHttp.get<SubscribersPageResponseDto>(
|
||||
CREATOR_SUBSCRIBERS_ENDPOINT,
|
||||
{ params: toListSubscribersQueryDto(args), signal },
|
||||
);
|
||||
return toSubscribersPagePayload(response);
|
||||
},
|
||||
};
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export { subscriberKeys } from './constants';
|
||||
export { creatorSubscribersRepository } from './creator-subscribers';
|
||||
export type {
|
||||
ListSubscribersArgs,
|
||||
SubscriberPayload,
|
||||
SubscribersPagePayload,
|
||||
} from './types';
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import type {
|
||||
ListSubscribersArgs,
|
||||
ListSubscribersQueryDto,
|
||||
SubscribersPagePayload,
|
||||
SubscribersPageResponseDto,
|
||||
} from './types';
|
||||
|
||||
export function toListSubscribersQueryDto(
|
||||
args: ListSubscribersArgs,
|
||||
): ListSubscribersQueryDto {
|
||||
return { page: args.page ?? 1 };
|
||||
}
|
||||
|
||||
export function toSubscribersPagePayload(
|
||||
dto: SubscribersPageResponseDto,
|
||||
): SubscribersPagePayload {
|
||||
return {
|
||||
activeCount: dto.activeCount,
|
||||
items: dto.items.map((item) => ({
|
||||
id: item.id,
|
||||
username: item.username,
|
||||
billingPeriod: item.billingPeriod,
|
||||
startsAt: item.startsAt,
|
||||
endsAt: item.endsAt,
|
||||
})),
|
||||
page: dto.page,
|
||||
hasMore: dto.hasMore,
|
||||
};
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import type { BillingPeriod } from '../../../../shared/constants';
|
||||
|
||||
export type ListSubscribersArgs = { page?: number };
|
||||
export type ListSubscribersQueryDto = { page: number };
|
||||
|
||||
/** `SubscriptionService.listSubscribers`'s row. */
|
||||
export type SubscriberResponseDto = {
|
||||
id: string;
|
||||
username: string | null;
|
||||
billingPeriod: BillingPeriod | null;
|
||||
startsAt: string | null;
|
||||
endsAt: string | null;
|
||||
};
|
||||
|
||||
export type SubscribersPageResponseDto = {
|
||||
activeCount: number;
|
||||
items: SubscriberResponseDto[];
|
||||
page: number;
|
||||
hasMore: boolean;
|
||||
};
|
||||
|
||||
/** A running subscription to the creator: the investor by @username only, never a phone or name. */
|
||||
export type SubscriberPayload = {
|
||||
id: string;
|
||||
username: string | null;
|
||||
billingPeriod: BillingPeriod | null;
|
||||
/** The current period. */
|
||||
startsAt: string | null;
|
||||
endsAt: string | null;
|
||||
};
|
||||
|
||||
export type SubscribersPagePayload = {
|
||||
/** مشترکان فعال: every running subscription, not this page's. */
|
||||
activeCount: number;
|
||||
items: SubscriberPayload[];
|
||||
page: number;
|
||||
hasMore: boolean;
|
||||
};
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import { eventEmitter } from '@lumina/libs/event-emitter';
|
||||
|
||||
import { PRICING_EVENTS } from '../../constants';
|
||||
import { pricingRepository } from '../../repositories/pricing';
|
||||
import type {
|
||||
PricingFormPayload,
|
||||
SavePricingArgs,
|
||||
} from '../../repositories/pricing';
|
||||
|
||||
/**
|
||||
* Saves the confirmed C7 form (۵.۱) and returns it as stored. Rules the API rejects come back as
|
||||
* `tiers.<period>.<field>` field errors; a standing change during the 7-day lock is a 409.
|
||||
* Emits `pricing.saved`.
|
||||
*/
|
||||
export async function savePricing(
|
||||
args: SavePricingArgs,
|
||||
{ emit = true }: { emit?: boolean } = {},
|
||||
): Promise<PricingFormPayload> {
|
||||
const saved = await pricingRepository.save(args);
|
||||
if (emit) eventEmitter.emit(PRICING_EVENTS.saved, {});
|
||||
return saved;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { savePricing } from './actions';
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import type { BillingPeriod } from '../../shared/constants';
|
||||
|
||||
/** Events pricing actions emit when they succeed. */
|
||||
export const PRICING_EVENTS = {
|
||||
/** The C7 form was saved: prices, periods or promotions. */
|
||||
saved: 'pricing.saved',
|
||||
} as const;
|
||||
|
||||
/** A promotion's lowest price per month, for every period (C7 ۷.۱). Mirrors the API's floor. */
|
||||
export const PROMO_FLOOR_TOMAN_PER_MONTH = 99_000;
|
||||
|
||||
/** Suggested and promotional prices round down to this step (C7 ۷.۱). */
|
||||
export const PRICE_ROUND_STEP_TOMAN = 1_000;
|
||||
|
||||
/** A new promotion's defaults: from now to the end of the seventh day. */
|
||||
export const PROMO_DEFAULT_DAYS = 7;
|
||||
|
||||
/** The periods longer than a month, which can be switched off; monthly never can. */
|
||||
export const TOGGLEABLE_PERIODS: readonly BillingPeriod[] = [
|
||||
'quarterly',
|
||||
'semi_annual',
|
||||
'yearly',
|
||||
];
|
||||
|
|
@ -1,3 +1,25 @@
|
|||
import './types';
|
||||
|
||||
export { savePricing } from './actions/save-pricing';
|
||||
export {
|
||||
PRICE_ROUND_STEP_TOMAN,
|
||||
PRICING_EVENTS,
|
||||
PROMO_FLOOR_TOMAN_PER_MONTH,
|
||||
} from './constants';
|
||||
export { usePricingPage } from './models/pricing';
|
||||
export type {
|
||||
PricingFieldMessage,
|
||||
PricingIssue,
|
||||
PricingPageModel,
|
||||
PricingPhase,
|
||||
PricingPromotionView,
|
||||
PricingTierView,
|
||||
} from './models/pricing';
|
||||
export { usePricingCardPart } from './models/pricing-card';
|
||||
export type {
|
||||
PricingCardPartModel,
|
||||
PricingPlanRow,
|
||||
} from './models/pricing-card';
|
||||
export { pricingKeys, pricingRepository } from './repositories/pricing';
|
||||
export type {
|
||||
GetPricingFormArgs,
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue