diff --git a/apps/wall-street-plaza/package.json b/apps/wall-street-plaza/package.json index 73ffad2..b7ad51e 100644 --- a/apps/wall-street-plaza/package.json +++ b/apps/wall-street-plaza/package.json @@ -2,6 +2,9 @@ "name": "@lumina/wall-street-plaza", "version": "0.0.1", "private": true, + "scripts": { + "test": "vitest run --config ../../vitest.config.ts" + }, "nx": { "name": "wall-street-plaza", "sourceRoot": "apps/wall-street-plaza/src", diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/loading.tsx b/apps/wall-street-plaza/src/app/(panel)/settings/loading.tsx new file mode 100644 index 0000000..8e5b57e --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/loading.tsx @@ -0,0 +1,17 @@ +import { PageHeader } from '@lumina/island/molecules/page-header'; + +import { i18n } from '../../../i18n'; +import { PriceFloorSkeleton } from './organisms/price-floor-card'; + +/** The card before it arrives: the title and subtitle over the skeleton. */ +export default function Loading() { + return ( + <> + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/PriceFloorCard.tsx b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/PriceFloorCard.tsx new file mode 100644 index 0000000..26c5dd2 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/PriceFloorCard.tsx @@ -0,0 +1,10 @@ +'use client'; + +import { usePriceFloorPage } from '@lumina/garden-roof'; + +import { PriceFloorForm } from './components/PriceFloorForm'; + +/** «کف قیمت اشتراک» (J11-11), its model read here so the form renders from props. */ +export function PriceFloorCard() { + return ; +} diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/ConfirmPriceFloorDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/ConfirmPriceFloorDialog.tsx new file mode 100644 index 0000000..e15e7e1 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/ConfirmPriceFloorDialog.tsx @@ -0,0 +1,44 @@ +'use client'; + +import { ReasonDialog } from '@lumina/garden-roof/app/screens'; +import { Banner } from '@lumina/island/molecules/banner'; +import { number, price } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { PriceFloorPartProps } from '../types'; + +/** + * «تغییر کف قیمت به {x} تومان» (J11-11): the required reason, 10 characters at least, goes to «گزارش + * ممیزی», with the raise's warning repeated above it. + */ +export function ConfirmPriceFloorDialog({ model }: PriceFloorPartProps) { + const { t } = useTranslation('settings'); + const affected = + model.preview.status === 'ready' ? model.preview.change : null; + + return ( + + {affected && affected.affectedTiers.length > 0 && ( + + {t('price-floor.preview.warning', { + tiers: number(affected.affectedTiers.length), + analysts: number(affected.analystCount), + })} + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorForm.test.tsx b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorForm.test.tsx new file mode 100644 index 0000000..1210533 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorForm.test.tsx @@ -0,0 +1,176 @@ +import type { PriceFloorPageModel } from '@lumina/garden-roof'; +import { useReasonForm } from '@lumina/garden-roof/shared/utils'; +import { render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; + +import '../../../../../../i18n/i18n.client'; +import { PriceFloorForm } from './PriceFloorForm'; + +const change = { + monthlyMin: 250000, + analystCount: 1, + affectedTiers: [ + { + tierId: 't1', + traderId: 'u1', + username: 'reza', + billingPeriod: 'monthly' as const, + labelFa: 'ماهانه', + finalMonthlyToman: 200000, + activeSubscribers: 4, + }, + { + tierId: 't2', + traderId: 'u1', + username: null, + billingPeriod: 'yearly' as const, + labelFa: 'سالانه', + finalMonthlyToman: 210000, + activeSubscribers: 0, + }, + ], +}; + +function Harness(props: Partial) { + const reasonForm = useReasonForm(); + const model: PriceFloorPageModel = { + currentToman: 199000, + changedAt: null, + text: '250٬000', + setText: vi.fn(), + error: null, + valueToman: 250000, + change: 'raise', + preview: { status: 'ready', change }, + blockedReason: null, + isConfirming: false, + openConfirm: vi.fn(), + closeConfirm: vi.fn(), + reasonForm, + confirm: vi.fn(), + isSaving: false, + ...props, + }; + return ; +} + +describe('PriceFloorForm', () => { + it('shows the current value in the hint, and its last change once there is one', () => { + const { rerender } = render(); + expect(screen.getByText(/هنوز تغییری ثبت نشده است/)).toBeTruthy(); + rerender(); + expect(screen.getByText(/آخرین تغییر:/)).toBeTruthy(); + }); + + it('a raise warns with how many plans and analysts, and lists each', () => { + render(); + expect( + screen.getByText('2 طرح از 1 تحلیلگر زیر کف جدید می‌مانند.'), + ).toBeTruthy(); + const table = screen.getByRole('table'); + expect(within(table).getByText('@reza')).toBeTruthy(); + expect(within(table).getByText('ماهانه')).toBeTruthy(); + expect(within(table).getByText('200٬000')).toBeTruthy(); + expect(within(table).getByText('4')).toBeTruthy(); + expect(within(table).getByText('حساب نامشخص')).toBeTruthy(); + }); + + it('a raise that takes nothing says so, with no table', () => { + render( + , + ); + expect(screen.getByText('هیچ طرحی زیر کف جدید نمی‌ماند.')).toBeTruthy(); + expect(screen.queryByRole('table')).toBeNull(); + }); + + it('a lower floor says it changes nothing yet, with no preview', () => { + render(); + expect(screen.getByText(/چیزی تغییر نمی‌کند/)).toBeTruthy(); + expect(screen.queryByRole('table')).toBeNull(); + }); + + it('a failed preview offers to try again', async () => { + const retry = vi.fn(); + render(); + await userEvent.click(screen.getByRole('button', { name: 'تلاش دوباره' })); + expect(retry).toHaveBeenCalled(); + }); + + it('«ذخیره» waits and says why while blocked', async () => { + const openConfirm = vi.fn(); + render( + , + ); + const save = screen.getByText('ذخیره').closest('button')!; + expect(save.classList.contains('frozen')).toBe(true); + await userEvent.click(save); + expect(openConfirm).not.toHaveBeenCalled(); + expect( + screen.getByText( + 'پیش از ذخیره باید پیش‌نمایش طرح‌های زیر کف آماده باشد.', + ), + ).toBeTruthy(); + }); + + it('«ذخیره» opens the confirmation', async () => { + const openConfirm = vi.fn(); + render(); + await userEvent.click(screen.getByRole('button', { name: 'ذخیره' })); + expect(openConfirm).toHaveBeenCalled(); + }); +}); + +describe('ConfirmPriceFloorDialog', () => { + const dialog = () => screen.getByRole('dialog', { hidden: true }); + + it('names the new floor and asks a reason before saving', async () => { + const confirm = vi.fn(); + render(); + expect( + within(dialog()).getByText('تغییر کف قیمت به 250٬000 تومان'), + ).toBeTruthy(); + const submit = within(dialog()) + .getByText('ذخیره و اطلاع‌رسانی') + .closest('button')!; + expect(submit.classList.contains('frozen')).toBe(true); + await userEvent.click(submit); + expect(confirm).not.toHaveBeenCalled(); + }); + + it('refuses a reason under 10 characters', async () => { + const confirm = vi.fn(); + render(); + await userEvent.type( + within(dialog()).getByRole('textbox', { hidden: true }), + 'کوتاه', + ); + await userEvent.click( + within(dialog()).getByText('ذخیره و اطلاع‌رسانی').closest('button')!, + ); + await waitFor(() => expect(confirm).not.toHaveBeenCalled()); + }); + + it('saves with the trimmed reason', async () => { + const confirm = vi.fn(); + render(); + await userEvent.type( + within(dialog()).getByRole('textbox', { hidden: true }), + ' افزایش کف قیمت پس از بازبینی. ', + ); + await userEvent.click( + within(dialog()).getByText('ذخیره و اطلاع‌رسانی').closest('button')!, + ); + await waitFor(() => + expect(confirm).toHaveBeenCalledWith('افزایش کف قیمت پس از بازبینی.'), + ); + }); +}); diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorForm.tsx b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorForm.tsx new file mode 100644 index 0000000..015b015 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorForm.tsx @@ -0,0 +1,80 @@ +'use client'; + +import { translateMessage } from '@lumina/garden-roof/shared/utils'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { Card } from '@lumina/island/molecules/card'; +import { TextInput } from '@lumina/island/molecules/text-input'; +import { date, price } from '@lumina/tools/format'; +import { useId } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { PriceFloorPartProps } from '../types'; +import { ConfirmPriceFloorDialog } from './ConfirmPriceFloorDialog'; +import { PriceFloorPreview } from './PriceFloorPreview'; + +/** + * The card (J11-11): «کف ماهانه» with the current value and its last change as the hint, then what + * the typed value does: a raise previews the tiers it takes off sale, a lower floor says it changes + * nothing yet. «ذخیره» opens the confirmation once that is known, and says why it waits until then. + */ +export function PriceFloorForm({ model }: PriceFloorPartProps) { + const { t } = useTranslation('settings'); + const headingId = useId(); + const current = price(model.currentToman); + + return ( + <> + + + + + {t('price-floor.title')} + + + {t('price-floor.description')} + + + model.setText(event.target.value)} + error={translateMessage(t, model.error ?? undefined)} + hint={ + model.changedAt + ? t('price-floor.hint', { + current, + date: date(model.changedAt, { time: false }), + }) + : t('price-floor.hint-never', { current }) + } + /> + {model.change === 'lower' && ( + + {t('price-floor.lower-note')} + + )} + + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorPreview.tsx b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorPreview.tsx new file mode 100644 index 0000000..2af5322 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorPreview.tsx @@ -0,0 +1,108 @@ +'use client'; + +import type { PriceFloorPreview as PriceFloorPreviewModel } from '@lumina/garden-roof'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Spinner } from '@lumina/island/atoms/spinner'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { DataTable } from '@lumina/island/organisms/data-table'; +import { Element } from '@lumina/island/primitives/element'; +import { number, price } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +/** + * What a raise takes off sale (J11-11): the warning with how many plans of how many analysts, and + * each plan's analyst, final monthly price and active subscribers. It scrolls sideways on a narrow + * column. Nothing while the floor isn't being raised. + */ +export function PriceFloorPreview({ + preview, +}: { + preview: PriceFloorPreviewModel; +}) { + const { t } = useTranslation('settings'); + + if (preview.status === 'idle') return null; + if (preview.status === 'loading') { + return ( + + + + {t('price-floor.preview.loading')} + + + ); + } + if (preview.status === 'error') { + return ( + + {t('price-floor.preview.retry')} + + } + > + {t('price-floor.preview.error')} + + ); + } + + const { affectedTiers, analystCount } = preview.change; + if (affectedTiers.length === 0) { + return ( + + {t('price-floor.preview.none')} + + ); + } + return ( + + + {t('price-floor.preview.warning', { + tiers: number(affectedTiers.length), + analysts: number(analystCount), + })} + + + + + + {t('price-floor.preview.columns.analyst')} + + + {t('price-floor.preview.columns.plan')} + + + {t('price-floor.preview.columns.price')} + + + {t('price-floor.preview.columns.subscribers')} + + + + {affectedTiers.map((tier) => ( + + + {tier.username ? ( + + @{tier.username} + + ) : ( + t('price-floor.preview.unknown') + )} + + {tier.labelFa} + {price(tier.finalMonthlyToman)} + + {number(tier.activeSubscribers)} + + + ))} + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorSkeleton.tsx new file mode 100644 index 0000000..dcc7d87 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/components/PriceFloorSkeleton.tsx @@ -0,0 +1,11 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import type { PriceFloorSkeletonProps } from '../types'; + +/** The card before it arrives. */ +export function PriceFloorSkeleton({ + label, + delayed, +}: PriceFloorSkeletonProps) { + return ; +} diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/index.ts b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/index.ts new file mode 100644 index 0000000..63b685b --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/index.ts @@ -0,0 +1,3 @@ +export { PriceFloorSkeleton } from './components/PriceFloorSkeleton'; +export { PriceFloorCard } from './PriceFloorCard'; +export type { PriceFloorPartProps, PriceFloorSkeletonProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/types.ts b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/types.ts new file mode 100644 index 0000000..3edd52a --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/organisms/price-floor-card/types.ts @@ -0,0 +1,10 @@ +import type { PriceFloorPageModel } from '@lumina/garden-roof'; + +export type PriceFloorPartProps = { model: PriceFloorPageModel }; + +export type PriceFloorSkeletonProps = { + /** Hidden status text. */ + label: string; + /** Fades in after 300ms: loading.tsx only. */ + delayed?: boolean; +}; diff --git a/apps/wall-street-plaza/src/app/(panel)/settings/page.tsx b/apps/wall-street-plaza/src/app/(panel)/settings/page.tsx new file mode 100644 index 0000000..0611a1b --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/settings/page.tsx @@ -0,0 +1,39 @@ +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { AdminGuard } from '@lumina/garden-roof/app/guards'; +import { PageHeader } from '@lumina/island/molecules/page-header'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { i18n } from '../../../i18n'; +import { PriceFloorCard, PriceFloorSkeleton } from './organisms/price-floor-card'; + +export const metadata: Metadata = { title: i18n.t('settings:page.meta-title') }; + +/** + * تنظیمات (J11-11): the title on the server; «کف قیمت اشتراک» in the browser once the admin is known + * (0062). + */ +export default function SettingsPage() { + const skeleton = ( + + ); + + return ( + <> + + + + + + + + + + ); +} diff --git a/docs/pages/README.md b/docs/pages/README.md index 6e83bf2..77289b6 100644 --- a/docs/pages/README.md +++ b/docs/pages/README.md @@ -85,6 +85,7 @@ Every page renders in the browser behind `AdminGuard` or `GuestGuard` (0062). - `/invite-codes/requests` · [invite-codes-requests.md](wall-street-plaza/invite-codes-requests.md) · noindex · none · browser: request rows, code dialogs - `/payouts` · [payouts.md](wall-street-plaza/payouts.md) · noindex · none · browser: tabs, payout rows, payout detail sheet, create, mark-paid and cancel dialogs - `/predictions` · [predictions.md](wall-street-plaza/predictions.md) · noindex · none · browser: quote health, queue tabs, queue rows, prediction sheet, prediction dialogs +- `/settings` · [settings.md](wall-street-plaza/settings.md) · noindex · none · browser: price floor card, raise preview, confirm dialog - `/subscriptions` · [subscriptions.md](wall-street-plaza/subscriptions.md) · noindex · none · browser: filter chips, subscription rows, detail sheet, grant dialog - `/verifications` · [verifications.md](wall-street-plaza/verifications.md) · noindex · none · browser: status tabs, search and sort, verification rows - `/verifications/[id]` · [verifications-id.md](wall-street-plaza/verifications-id.md) · noindex · none · browser: queue nav, banner, facts, decisions, past submissions, ID image, audit log, decision dialogs diff --git a/docs/pages/market/dashboard-plans.md b/docs/pages/market/dashboard-plans.md index 86d5e46..63798c0 100644 --- a/docs/pages/market/dashboard-plans.md +++ b/docs/pages/market/dashboard-plans.md @@ -28,3 +28,7 @@ In bull's document order. Everything sits in `AuthGuard role="creator"`, whose f - bull: cards 12px apart; bear: 16px apart, desktop card layouts. Same sections in both apps. - The cards' queries run only in the browser: `AuthGuard` returns its fallback on the server, so no `useSuspenseQuery` sends a request from the server. + +## Price floor + +A plan the price floor took off sale gets a «خارج از فروش» badge on its row, and a banner above the card, «طرح {tier} شما از فروش خارج شد», with «اصلاح قیمت» to `/dashboard/pricing`. Both read `offSale` from the pricing form, so they load with the card. diff --git a/docs/pages/market/dashboard-pricing.md b/docs/pages/market/dashboard-pricing.md index 5cff442..405f6f9 100644 --- a/docs/pages/market/dashboard-pricing.md +++ b/docs/pages/market/dashboard-pricing.md @@ -29,3 +29,8 @@ In bull's document order. `dashboard/pricing/layout.tsx` is only `OnboardingGuar - bull: the form pads itself and pins save to the bottom; bear: the form in the 560 column. - Debt: different H1 per app. bull has no `h1`; add a screen-reader `h1` to `PricingEditor`'s mobile branch (`platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-editor/PricingEditor.tsx`, the `MobileTopBar` return). + +## Price floor + +- The floor comes from `GET /subscriptions/pricing` (`floorTomanPerMonth`), on the final price after any discount; the browser compares exact totals as the API does. +- During the 7-day lock a tier the floor took off sale (`offSale`) stays editable and shows «خارج از فروش»; the other tiers stay read-only, and the save reads «ذخیره قیمت‌گذاری» instead of «ذخیره تخفیف». diff --git a/docs/pages/wall-street-plaza/settings.md b/docs/pages/wall-street-plaza/settings.md new file mode 100644 index 0000000..f679367 --- /dev/null +++ b/docs/pages/wall-street-plaza/settings.md @@ -0,0 +1,26 @@ +# Settings + +`/settings` · `apps/wall-street-plaza/src/app/(panel)/settings/page.tsx` · Type: account (back office) · Layout: [layout-panel.md](layout-panel.md) + +| Field | Value | +| ----------- | -------------------------------------------------------- | +| Robots | `noindex` (root layout `metadata`, `src/configs/seo.ts`) | +| Status | `200` | +| loading.tsx | `(panel)/settings/loading.tsx` | +| First flush | none | +| Canonical | none | +| H1 | `settings:page.title` from i18n, in `PageHeader` | +| JSON-LD | none | +| Scripts | none | + +## Sections + +| Section | Data | HTML | JS | Index | Notes | +| -------------- | ------ | ----------- | ------- | ----- | ------------------------------------------------------------------------------------------------- | +| PageHeader | config | first flush | none | no | title and subtitle | +| PriceFloorCard | viewer | skeleton | hydrate | no | `AdminGuard`, `PartBoundary`, `Suspense`; `GET /admin/settings/price-floor` in the browser (0062) | +| Raise preview | viewer | none | hydrate | no | on a raise, a dry run `PUT` once the value stands still 400 ms; warning and table | +| Confirm dialog | viewer | none | hydrate | no | `ReasonDialog`, reason of 10 characters at least, audited as `settings.price_floor_changed` | + +- A lower floor shows no preview, since nothing changes until analysts edit. +- «ذخیره» stays frozen, with its reason, on an invalid or unchanged value, or until a raise's preview is in. diff --git a/platforms/garden-roof/package.json b/platforms/garden-roof/package.json index b497393..3a326b8 100644 --- a/platforms/garden-roof/package.json +++ b/platforms/garden-roof/package.json @@ -2,6 +2,9 @@ "name": "@lumina/garden-roof", "version": "0.0.1", "private": true, + "scripts": { + "test": "vitest run --config ../../vitest.config.ts" + }, "type": "module", "sideEffects": false, "exports": { diff --git a/platforms/garden-roof/src/app/navigation/constants.ts b/platforms/garden-roof/src/app/navigation/constants.ts index 1c98289..6c8bccc 100644 --- a/platforms/garden-roof/src/app/navigation/constants.ts +++ b/platforms/garden-roof/src/app/navigation/constants.ts @@ -10,6 +10,7 @@ export const NAV_ITEMS: readonly NavItem[] = [ { section: 'preds', icon: 'target' }, { section: 'payouts', icon: 'wallet' }, { section: 'featured', icon: 'star' }, + { section: 'settings', icon: 'settings' }, ]; export const SOON_ITEMS: readonly SoonItem[] = [ diff --git a/platforms/garden-roof/src/app/navigation/navigation.ts b/platforms/garden-roof/src/app/navigation/navigation.ts index 93fa451..a75b8e2 100644 --- a/platforms/garden-roof/src/app/navigation/navigation.ts +++ b/platforms/garden-roof/src/app/navigation/navigation.ts @@ -15,6 +15,7 @@ export const ROUTES = { predictions: '/predictions', payouts: '/payouts', featured: '/featured', + settings: '/settings', } as const; /** Where a signed-in admin lands, and where «بازگشت» goes when nothing else fits. */ @@ -47,6 +48,7 @@ export const SECTION_ROUTES: Record = { preds: ROUTES.predictions, payouts: ROUTES.payouts, featured: ROUTES.featured, + settings: ROUTES.settings, }; export function sectionOf(pathname: string): AdminSection | null { diff --git a/platforms/garden-roof/src/app/navigation/types.ts b/platforms/garden-roof/src/app/navigation/types.ts index fe1cbcc..b9f1f01 100644 --- a/platforms/garden-roof/src/app/navigation/types.ts +++ b/platforms/garden-roof/src/app/navigation/types.ts @@ -9,7 +9,8 @@ export type AdminSection = | 'subs' | 'preds' | 'payouts' - | 'featured'; + | 'featured' + | 'settings'; /** Sections whose sidebar link shows what waits there. */ export type CountedSection = 'verify' | 'codes' | 'preds' | 'payouts'; diff --git a/platforms/garden-roof/src/features/settings/actions/save-price-floor/actions.ts b/platforms/garden-roof/src/features/settings/actions/save-price-floor/actions.ts new file mode 100644 index 0000000..c8409f6 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/actions/save-price-floor/actions.ts @@ -0,0 +1,25 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { SETTINGS_EVENTS } from '../../constants'; +import { settingsRepository } from '../../repositories/settings'; +import type { + PriceFloorChangePayload, + SavePriceFloorArgs, +} from '../../repositories/settings'; + +/** + * «ذخیره و اطلاع‌رسانی» (J11-11): saves the floor with its audited reason. Emits + * `settings.price-floor-changed`. + */ +export async function savePriceFloor( + args: SavePriceFloorArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await settingsRepository.savePriceFloor(args); + if (emit) { + eventEmitter.emit(SETTINGS_EVENTS.priceFloorChanged, { + monthlyMin: result.monthlyMin, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/settings/actions/save-price-floor/index.ts b/platforms/garden-roof/src/features/settings/actions/save-price-floor/index.ts new file mode 100644 index 0000000..f503a6e --- /dev/null +++ b/platforms/garden-roof/src/features/settings/actions/save-price-floor/index.ts @@ -0,0 +1 @@ +export { savePriceFloor } from './actions'; diff --git a/platforms/garden-roof/src/features/settings/constants.ts b/platforms/garden-roof/src/features/settings/constants.ts new file mode 100644 index 0000000..118fed4 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/constants.ts @@ -0,0 +1,7 @@ +/** Events settings actions emit when they succeed. */ +export const SETTINGS_EVENTS = { + priceFloorChanged: 'settings.price-floor-changed', +} as const; + +/** How long the typed floor must stand still before its preview is asked. */ +export const PREVIEW_DEBOUNCE_MS = 400; diff --git a/platforms/garden-roof/src/features/settings/entities/price-floor/index.ts b/platforms/garden-roof/src/features/settings/entities/price-floor/index.ts new file mode 100644 index 0000000..65ef958 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/entities/price-floor/index.ts @@ -0,0 +1 @@ +export type { AffectedTierEntity } from './types'; diff --git a/platforms/garden-roof/src/features/settings/entities/price-floor/types.ts b/platforms/garden-roof/src/features/settings/entities/price-floor/types.ts new file mode 100644 index 0000000..3fa1d29 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/entities/price-floor/types.ts @@ -0,0 +1,12 @@ +/** One tier a floor would take off sale (admin-api `PUT /admin/settings/price-floor`). */ +export type AffectedTierEntity = { + tierId: string; + traderId: string; + /** `null` when the account can no longer be found. */ + username: string | null; + billingPeriod: 'monthly' | 'quarterly' | 'semi_annual' | 'yearly'; + labelFa: string; + /** The lowest price it is committed to, as a month's worth, in Toman. */ + finalMonthlyToman: number; + activeSubscribers: number; +}; diff --git a/platforms/garden-roof/src/features/settings/http.ts b/platforms/garden-roof/src/features/settings/http.ts new file mode 100644 index 0000000..179cffd --- /dev/null +++ b/platforms/garden-roof/src/features/settings/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const settingsHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/settings/index.ts b/platforms/garden-roof/src/features/settings/index.ts new file mode 100644 index 0000000..3b6cacc --- /dev/null +++ b/platforms/garden-roof/src/features/settings/index.ts @@ -0,0 +1,23 @@ +import './types'; + +export { savePriceFloor } from './actions/save-price-floor'; +export { PREVIEW_DEBOUNCE_MS, SETTINGS_EVENTS } from './constants'; +export type { AffectedTierEntity } from './entities/price-floor'; +export { usePriceFloorPage } from './models/price-floor'; +export type { + PriceFloorChange, + PriceFloorPageModel, + PriceFloorPreview, +} from './models/price-floor'; +export { + SETTINGS_ENDPOINTS, + settingsKeys, + settingsRepository, +} from './repositories/settings'; +export type { + AffectedTierPayload, + PreviewPriceFloorArgs, + PriceFloorChangePayload, + PriceFloorPayload, + SavePriceFloorArgs, +} from './repositories/settings'; diff --git a/platforms/garden-roof/src/features/settings/models/price-floor/index.ts b/platforms/garden-roof/src/features/settings/models/price-floor/index.ts new file mode 100644 index 0000000..e54492f --- /dev/null +++ b/platforms/garden-roof/src/features/settings/models/price-floor/index.ts @@ -0,0 +1,11 @@ +export { usePriceFloorPage } from './use-price-floor-page'; +export { + floorBlockedReason, + floorChange, + readMonthlyFloor, +} from './price-floor-rules'; +export type { + PriceFloorChange, + PriceFloorPageModel, + PriceFloorPreview, +} from './types'; diff --git a/platforms/garden-roof/src/features/settings/models/price-floor/price-floor-rules.test.ts b/platforms/garden-roof/src/features/settings/models/price-floor/price-floor-rules.test.ts new file mode 100644 index 0000000..6af3c75 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/models/price-floor/price-floor-rules.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; + +import { + floorBlockedReason, + floorChange, + readMonthlyFloor, +} from './price-floor-rules'; + +describe('readMonthlyFloor', () => { + it.each([ + ['199000', 199000], + ['199٬000', 199000], + ['۱۹۹٬۰۰۰', 199000], + ['1000', 1000], + ])('reads %s', (text, value) => { + expect(readMonthlyFloor(text)).toEqual({ value, error: null }); + }); + + it.each([ + ['', 'settings:price-floor.errors.required'], + ['12.5', 'settings:price-floor.errors.integer'], + ['abc', 'settings:price-floor.errors.integer'], + ['999', 'settings:price-floor.errors.below-min'], + ])('refuses %j', (text, error) => { + expect(readMonthlyFloor(text)).toEqual({ value: null, error }); + }); +}); + +describe('floorChange', () => { + it('tells a raise, a lower floor and no change apart', () => { + expect(floorChange(250000, 199000)).toBe('raise'); + expect(floorChange(150000, 199000)).toBe('lower'); + expect(floorChange(199000, 199000)).toBe('none'); + expect(floorChange(null, 199000)).toBe('none'); + }); +}); + +describe('floorBlockedReason', () => { + const blocked = (over: Partial[0]>) => + floorBlockedReason({ + error: null, + change: 'raise', + previewStatus: 'ready', + ...over, + }); + + it('lets a raise through only once its preview is in', () => { + expect(blocked({})).toBeNull(); + expect(blocked({ previewStatus: 'loading' })).toBe( + 'settings:price-floor.blocked.preview', + ); + expect(blocked({ previewStatus: 'error' })).toBe( + 'settings:price-floor.blocked.preview', + ); + }); + + it('lets a lower floor through with no preview', () => { + expect(blocked({ change: 'lower', previewStatus: 'idle' })).toBeNull(); + }); + + it('waits on an unchanged or a bad value', () => { + expect(blocked({ change: 'none', previewStatus: 'idle' })).toBe( + 'settings:price-floor.blocked.unchanged', + ); + expect(blocked({ error: 'x', change: 'none' })).toBe( + 'settings:price-floor.blocked.invalid', + ); + }); +}); diff --git a/platforms/garden-roof/src/features/settings/models/price-floor/price-floor-rules.ts b/platforms/garden-roof/src/features/settings/models/price-floor/price-floor-rules.ts new file mode 100644 index 0000000..4767ca9 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/models/price-floor/price-floor-rules.ts @@ -0,0 +1,40 @@ +import * as v from 'valibot'; + +import { monthlyFloorSchema } from '../../../../shared/validations'; +import type { PriceFloorChange } from './types'; + +/** The typed floor: its value, or the `settings:` key of why it isn't one. */ +export function readMonthlyFloor( + text: string, +): { value: number; error: null } | { value: null; error: string } { + const parsed = v.safeParse(monthlyFloorSchema, text); + return parsed.success + ? { value: parsed.output, error: null } + : { value: null, error: parsed.issues[0].message }; +} + +export function floorChange( + value: number | null, + current: number, +): PriceFloorChange { + if (value === null || value === current) return 'none'; + return value > current ? 'raise' : 'lower'; +} + +/** Why «ذخیره» waits: nothing to save, a bad value, or a raise whose effect isn't known yet. */ +export function floorBlockedReason({ + error, + change, + previewStatus, +}: { + error: string | null; + change: PriceFloorChange; + previewStatus: 'idle' | 'loading' | 'error' | 'ready'; +}): string | null { + if (error) return 'settings:price-floor.blocked.invalid'; + if (change === 'none') return 'settings:price-floor.blocked.unchanged'; + if (change === 'raise' && previewStatus !== 'ready') { + return 'settings:price-floor.blocked.preview'; + } + return null; +} diff --git a/platforms/garden-roof/src/features/settings/models/price-floor/types.ts b/platforms/garden-roof/src/features/settings/models/price-floor/types.ts new file mode 100644 index 0000000..6c313ba --- /dev/null +++ b/platforms/garden-roof/src/features/settings/models/price-floor/types.ts @@ -0,0 +1,36 @@ +import type { ReasonForm } from '../../../../shared/utils'; +import type { PriceFloorChangePayload } from '../../repositories/settings'; + +/** What the typed floor does against the current one. */ +export type PriceFloorChange = 'none' | 'raise' | 'lower'; + +/** The raise's preview: asked once the value stands still, and only for a raise. */ +export type PriceFloorPreview = + | { status: 'idle' } + | { status: 'loading' } + | { status: 'error'; retry: () => void } + | { status: 'ready'; change: PriceFloorChangePayload }; + +export type PriceFloorPageModel = { + currentToman: number; + /** When an admin last changed it; `null` while it is still the default. */ + changedAt: string | null; + /** «کف ماهانه» as typed, grouped. */ + text: string; + setText: (text: string) => void; + /** A `settings:` key while the typed value is not a floor; `null` otherwise. */ + error: string | null; + /** The typed floor, once valid. */ + valueToman: number | null; + change: PriceFloorChange; + preview: PriceFloorPreview; + /** Why «ذخیره» waits: a `settings:` key; `null` when it can open the confirmation. */ + blockedReason: string | null; + isConfirming: boolean; + openConfirm: () => void; + closeConfirm: () => void; + reasonForm: ReasonForm; + /** «ذخیره و اطلاع‌رسانی», with the trimmed reason. */ + confirm: (reason: string) => void; + isSaving: boolean; +}; diff --git a/platforms/garden-roof/src/features/settings/models/price-floor/use-price-floor-page.ts b/platforms/garden-roof/src/features/settings/models/price-floor/use-price-floor-page.ts new file mode 100644 index 0000000..bab3a94 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/models/price-floor/use-price-floor-page.ts @@ -0,0 +1,116 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { latinDigits, number, price } from '@lumina/tools/format'; +import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { + showActionError, + useDebouncedValue, + useReasonForm, +} from '../../../../shared/utils'; +import { savePriceFloor } from '../../actions/save-price-floor'; +import { PREVIEW_DEBOUNCE_MS } from '../../constants'; +import { settingsKeys, settingsRepository } from '../../repositories/settings'; +import { + floorBlockedReason, + floorChange, + readMonthlyFloor, +} from './price-floor-rules'; +import type { PriceFloorPageModel, PriceFloorPreview } from './types'; + +/** A typed amount as the field shows it: digits only, grouped. */ +function toAmountText(text: string): string { + const digits = latinDigits(text).replace(/\D/g, ''); + return digits === '' ? '' : number(Number(digits)); +} + +/** + * «کف قیمت اشتراک» (J11-11). A raise shows what it would take off sale before it can be saved: a + * dry run asked once the value stands still, so nothing is confirmed on a stale list. A lower floor + * changes nothing until analysts edit, so it has no preview. Saving asks a reason (audited); a + * failure keeps the dialog and its text. + */ +export function usePriceFloorPage(): PriceFloorPageModel { + const { t } = useTranslation('settings'); + const queryClient = useQueryClient(); + const { data: floor } = useSuspenseQuery({ + queryKey: settingsKeys.priceFloor(), + queryFn: ({ signal }) => settingsRepository.getPriceFloor({ signal }), + }); + const [text, setText] = useState(() => number(floor.monthlyMin)); + const [isConfirming, setIsConfirming] = useState(false); + const [isSaving, setIsSaving] = useState(false); + const reasonForm = useReasonForm(); + + const { value, error } = readMonthlyFloor(text); + const change = floorChange(value, floor.monthlyMin); + const settled = useDebouncedValue(value, PREVIEW_DEBOUNCE_MS); + const dryRun = useQuery({ + queryKey: settingsKeys.preview(value ?? 0), + queryFn: ({ signal }) => + settingsRepository.previewPriceFloor( + { monthlyMin: value as number }, + { signal }, + ), + enabled: change === 'raise' && settled === value, + // Each read answers for this moment: another admin or analyst may have changed the tiers. + staleTime: 0, + gcTime: 0, + throwOnError: false, + }); + + const preview: PriceFloorPreview = + change !== 'raise' + ? { status: 'idle' } + : dryRun.isError + ? { status: 'error', retry: () => void dryRun.refetch() } + : dryRun.data && settled === value + ? { status: 'ready', change: dryRun.data } + : { status: 'loading' }; + + const confirm = async (reason: string) => { + if (value === null || isSaving) return; + setIsSaving(true); + try { + const saved = await savePriceFloor({ monthlyMin: value, reason }); + await queryClient.invalidateQueries({ + queryKey: settingsKeys.priceFloor(), + }); + setIsConfirming(false); + showToast({ + tone: 'success', + message: t('price-floor.saved', { amount: price(saved.monthlyMin) }), + }); + } catch (failure) { + showActionError(failure, { + t, + failedMessage: t('price-floor.save-failed'), + }); + } finally { + setIsSaving(false); + } + }; + + return { + currentToman: floor.monthlyMin, + changedAt: floor.changedAt, + text, + setText: (next) => setText(toAmountText(next)), + error, + valueToman: value, + change, + preview, + blockedReason: floorBlockedReason({ + error, + change, + previewStatus: preview.status, + }), + isConfirming, + openConfirm: () => setIsConfirming(true), + closeConfirm: () => setIsConfirming(false), + reasonForm, + confirm: (reason) => void confirm(reason), + isSaving, + }; +} diff --git a/platforms/garden-roof/src/features/settings/repositories/settings/constants.ts b/platforms/garden-roof/src/features/settings/repositories/settings/constants.ts new file mode 100644 index 0000000..348f722 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/repositories/settings/constants.ts @@ -0,0 +1,10 @@ +export const SETTINGS_ENDPOINTS = { + priceFloor: '/admin/settings/price-floor', +} as const; + +export const settingsKeys = { + all: ['settings'] as const, + priceFloor: () => [...settingsKeys.all, 'price-floor'] as const, + preview: (monthlyMin: number) => + [...settingsKeys.priceFloor(), 'preview', monthlyMin] as const, +}; diff --git a/platforms/garden-roof/src/features/settings/repositories/settings/index.ts b/platforms/garden-roof/src/features/settings/repositories/settings/index.ts new file mode 100644 index 0000000..b0eb83c --- /dev/null +++ b/platforms/garden-roof/src/features/settings/repositories/settings/index.ts @@ -0,0 +1,9 @@ +export { SETTINGS_ENDPOINTS, settingsKeys } from './constants'; +export { settingsRepository } from './settings'; +export type { + AffectedTierPayload, + PreviewPriceFloorArgs, + PriceFloorChangePayload, + PriceFloorPayload, + SavePriceFloorArgs, +} from './types'; diff --git a/platforms/garden-roof/src/features/settings/repositories/settings/mappers.ts b/platforms/garden-roof/src/features/settings/repositories/settings/mappers.ts new file mode 100644 index 0000000..85ff443 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/repositories/settings/mappers.ts @@ -0,0 +1,37 @@ +import type { + PreviewPriceFloorArgs, + PriceFloorChangePayload, + PriceFloorChangeResponseDto, + PriceFloorPayload, + PriceFloorResponseDto, + SavePriceFloorArgs, + SavePriceFloorDto, +} from './types'; + +export function toPriceFloorPayload( + dto: PriceFloorResponseDto, +): PriceFloorPayload { + return { monthlyMin: dto.monthlyMin, changedAt: dto.changedAt }; +} + +export function toPriceFloorChangePayload( + dto: PriceFloorChangeResponseDto, +): PriceFloorChangePayload { + return { + monthlyMin: dto.monthlyMin, + analystCount: dto.analystCount, + affectedTiers: dto.affectedTiers, + }; +} + +export function toPreviewPriceFloorDto( + args: PreviewPriceFloorArgs, +): SavePriceFloorDto { + return { monthlyMin: args.monthlyMin, dryRun: true }; +} + +export function toSavePriceFloorDto( + args: SavePriceFloorArgs, +): SavePriceFloorDto { + return { monthlyMin: args.monthlyMin, reason: args.reason }; +} diff --git a/platforms/garden-roof/src/features/settings/repositories/settings/settings.ts b/platforms/garden-roof/src/features/settings/repositories/settings/settings.ts new file mode 100644 index 0000000..18e08e7 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/repositories/settings/settings.ts @@ -0,0 +1,53 @@ +import { settingsHttp } from '../../http'; +import { SETTINGS_ENDPOINTS } from './constants'; +import { + toPreviewPriceFloorDto, + toPriceFloorChangePayload, + toPriceFloorPayload, + toSavePriceFloorDto, +} from './mappers'; +import type { + PreviewPriceFloorArgs, + PriceFloorChangePayload, + PriceFloorChangeResponseDto, + PriceFloorPayload, + PriceFloorResponseDto, + SavePriceFloorArgs, +} from './types'; + +/** «تنظیمات» (J11-11): «کف قیمت اشتراک». */ +export const settingsRepository = { + async getPriceFloor({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await settingsHttp.get( + SETTINGS_ENDPOINTS.priceFloor, + { signal }, + ); + return toPriceFloorPayload(response); + }, + + /** The tiers this floor would take off sale; a dry run changes nothing. */ + async previewPriceFloor( + args: PreviewPriceFloorArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await settingsHttp.put( + SETTINGS_ENDPOINTS.priceFloor, + toPreviewPriceFloorDto(args), + { signal }, + ); + return toPriceFloorChangePayload(response); + }, + + /** Saves the floor; raising it takes the tiers below it off sale and notifies their analysts. */ + async savePriceFloor( + args: SavePriceFloorArgs, + ): Promise { + const response = await settingsHttp.put( + SETTINGS_ENDPOINTS.priceFloor, + toSavePriceFloorDto(args), + ); + return toPriceFloorChangePayload(response); + }, +}; diff --git a/platforms/garden-roof/src/features/settings/repositories/settings/types.ts b/platforms/garden-roof/src/features/settings/repositories/settings/types.ts new file mode 100644 index 0000000..d6e0ec4 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/repositories/settings/types.ts @@ -0,0 +1,47 @@ +import type { AffectedTierEntity } from '../../entities/price-floor'; + +// Money is whole Toman; dates are ISO strings. + +// GET /admin/settings/price-floor + +export type PriceFloorResponseDto = { + monthlyMin: number; + previousValue: number | null; + changedAt: string | null; + changedBy: string | null; +}; + +/** The floor per month-equivalent, on the final price after any discount, and its last change. */ +export type PriceFloorPayload = { + monthlyMin: number; + /** `null` until an admin first changes it. */ + changedAt: string | null; +}; + +// PUT /admin/settings/price-floor + +export type PreviewPriceFloorArgs = { monthlyMin: number }; + +export type SavePriceFloorArgs = { monthlyMin: number; reason: string }; + +export type SavePriceFloorDto = { + monthlyMin: number; + reason?: string; + dryRun?: boolean; +}; + +export type PriceFloorChangeResponseDto = { + monthlyMin: number; + previousValue: number; + analystCount: number; + affectedTiers: AffectedTierEntity[]; +}; + +export type AffectedTierPayload = AffectedTierEntity; + +/** What a floor takes, or would take, off sale. */ +export type PriceFloorChangePayload = { + monthlyMin: number; + analystCount: number; + affectedTiers: AffectedTierPayload[]; +}; diff --git a/platforms/garden-roof/src/features/settings/types.ts b/platforms/garden-roof/src/features/settings/types.ts new file mode 100644 index 0000000..50eaaa0 --- /dev/null +++ b/platforms/garden-roof/src/features/settings/types.ts @@ -0,0 +1,7 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'settings.price-floor-changed': { monthlyMin: number }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/index.ts b/platforms/garden-roof/src/index.ts index cf48a9f..5bfee09 100644 --- a/platforms/garden-roof/src/index.ts +++ b/platforms/garden-roof/src/index.ts @@ -350,6 +350,26 @@ export type { ReadyPayoutPayload, ReadyPayoutsPartModel, } from './features/payouts'; +export { + PREVIEW_DEBOUNCE_MS, + savePriceFloor, + SETTINGS_ENDPOINTS, + SETTINGS_EVENTS, + settingsKeys, + settingsRepository, + usePriceFloorPage, +} from './features/settings'; +export type { + AffectedTierEntity, + AffectedTierPayload, + PreviewPriceFloorArgs, + PriceFloorChange, + PriceFloorChangePayload, + PriceFloorPageModel, + PriceFloorPayload, + PriceFloorPreview, + SavePriceFloorArgs, +} from './features/settings'; export { addFeatured, FEATURED_ENDPOINTS, diff --git a/platforms/garden-roof/src/shared/locales/fa/common.json b/platforms/garden-roof/src/shared/locales/fa/common.json index bfc7dec..4ef97d7 100644 --- a/platforms/garden-roof/src/shared/locales/fa/common.json +++ b/platforms/garden-roof/src/shared/locales/fa/common.json @@ -16,6 +16,7 @@ "preds": "سیگنال‌ها", "payouts": "تسویه تحلیلگران", "featured": "تحلیلگران منتخب", + "settings": "تنظیمات", "soon": "به‌زودی", "soon-items": { "users": "کاربران", @@ -132,7 +133,9 @@ "ledger.corrected": "اصلاح موجودی", "featured.added": "به منتخب اضافه شد", "featured.removed": "از منتخب حذف شد", - "featured.reordered": "ترتیب تغییر کرد" + "featured.reordered": "ترتیب تغییر کرد", + "legal.published": "نسخه تازه سند منتشر شد", + "settings.price_floor_changed": "کف قیمت تغییر کرد" }, "capacity-up": "افزایش ظرفیت از {{from}} به {{to}}", "capacity-down": "کاهش ظرفیت از {{from}} به {{to}}", diff --git a/platforms/garden-roof/src/shared/locales/fa/settings.json b/platforms/garden-roof/src/shared/locales/fa/settings.json new file mode 100644 index 0000000..5d6bf4f --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/settings.json @@ -0,0 +1,52 @@ +{ + "page": { + "meta-title": "تنظیمات", + "title": "تنظیمات", + "subtitle": "مقادیری که بدون انتشار نسخه تازه تغییر می‌کنند.", + "loading": "در حال بارگذاری تنظیمات…", + "error": "تنظیمات بارگذاری نشد. دوباره تلاش کنید." + }, + "price-floor": { + "title": "کف قیمت اشتراک", + "description": "کمترین قیمت نهایی هر طرح به ازای هر ماه، بعد از هر تخفیف.", + "field": "کف ماهانه", + "currency": "تومان", + "hint": "کف فعلی: {{current}} تومان در ماه · آخرین تغییر: {{date}}", + "hint-never": "کف فعلی: {{current}} تومان در ماه · هنوز تغییری ثبت نشده است", + "errors": { + "required": "کف ماهانه را وارد کنید.", + "integer": "کف ماهانه باید یک عدد صحیح به تومان باشد.", + "below-min": "کف ماهانه نمی‌تواند کمتر از ۱٬۰۰۰ تومان باشد." + }, + "blocked": { + "invalid": "ابتدا مقدار کف ماهانه را اصلاح کنید.", + "unchanged": "برای ذخیره، مقدار تازه‌ای وارد کنید.", + "preview": "پیش از ذخیره باید پیش‌نمایش طرح‌های زیر کف آماده باشد." + }, + "save": "ذخیره", + "lower-note": "با کاهش کف، تا زمانی که تحلیلگران قیمت‌هایشان را ویرایش نکنند چیزی تغییر نمی‌کند.", + "preview": { + "warning": "{{tiers}} طرح از {{analysts}} تحلیلگر زیر کف جدید می‌مانند.", + "none": "هیچ طرحی زیر کف جدید نمی‌ماند.", + "loading": "در حال بررسی طرح‌های زیر کف جدید…", + "error": "پیش‌نمایش طرح‌های زیر کف بارگذاری نشد.", + "retry": "تلاش دوباره", + "table": "طرح‌هایی که زیر کف جدید می‌مانند", + "columns": { + "analyst": "تحلیلگر", + "plan": "طرح", + "price": "قیمت نهایی ماهانه", + "subscribers": "مشترکان فعال" + }, + "unknown": "حساب نامشخص" + }, + "confirm": { + "title": "تغییر کف قیمت به {{amount}} تومان", + "submit": "ذخیره و اطلاع‌رسانی", + "placeholder": "چرا کف قیمت تغییر می‌کند؟", + "empty": "ابتدا دلیل تغییر کف قیمت را بنویسید." + }, + "saved": "کف قیمت به {{amount}} تومان تغییر کرد.", + "save-failed": "کف قیمت ذخیره نشد" + } +} diff --git a/platforms/garden-roof/src/shared/locales/resources.ts b/platforms/garden-roof/src/shared/locales/resources.ts index 99d33f1..efc64dc 100644 --- a/platforms/garden-roof/src/shared/locales/resources.ts +++ b/platforms/garden-roof/src/shared/locales/resources.ts @@ -7,6 +7,7 @@ import faFeatured from './fa/featured.json'; import faHealth from './fa/health.json'; import faPayouts from './fa/payouts.json'; import faPredictions from './fa/predictions.json'; +import faSettings from './fa/settings.json'; import faSubscriptions from './fa/subscriptions.json'; import faVerification from './fa/verification.json'; @@ -28,6 +29,7 @@ export const resources = { predictions: faPredictions, payouts: faPayouts, featured: faFeatured, + settings: faSettings, }, } as const; diff --git a/platforms/garden-roof/src/shared/validations/index.ts b/platforms/garden-roof/src/shared/validations/index.ts index 673be05..9013774 100644 --- a/platforms/garden-roof/src/shared/validations/index.ts +++ b/platforms/garden-roof/src/shared/validations/index.ts @@ -57,3 +57,7 @@ export type { MarkPaidFormOutput, MarkPaidFormValues, } from './payout-validations'; +export { + monthlyFloorSchema, + PRICE_FLOOR_MIN_TOMAN, +} from './settings-validations'; diff --git a/platforms/garden-roof/src/shared/validations/settings-validations.ts b/platforms/garden-roof/src/shared/validations/settings-validations.ts new file mode 100644 index 0000000..488c159 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/settings-validations.ts @@ -0,0 +1,15 @@ +import { latinDigits } from '@lumina/tools/format'; +import * as v from 'valibot'; + +/** The least a price floor can be, as admin-api takes it. */ +export const PRICE_FLOOR_MIN_TOMAN = 1000; + +/** «کف ماهانه», typed in any digits, grouped or not: a whole Toman amount of at least 1,000. */ +export const monthlyFloorSchema = v.pipe( + v.string(), + v.transform((value) => latinDigits(value).replace(/[٬,\s]/g, '')), + v.nonEmpty('settings:price-floor.errors.required'), + v.regex(/^\d+$/, 'settings:price-floor.errors.integer'), + v.transform(Number), + v.minValue(PRICE_FLOOR_MIN_TOMAN, 'settings:price-floor.errors.below-min'), +); diff --git a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/PricingForm.tsx b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/PricingForm.tsx index 9eb754b..9de3db3 100644 --- a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/PricingForm.tsx +++ b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/PricingForm.tsx @@ -29,7 +29,7 @@ import type { DatePick, PricingFormProps } from './types'; * once something is saved, the note on existing subscribers. Save is pinned to the bottom on * mobile and sits under the form on desktop; while a broken rule shows it freezes with the line * above it (۳), and offline it freezes and says why. During the lock it reads «ذخیره تخفیف» (J10-4m, - * 0036). The confirmation and the date picker are sheets on mobile and modals on desktop. It + * 0036), unless a tier is off sale, whose price can be fixed through the lock. The confirmation and the date picker are sheets on mobile and modals on desktop. It * reports unsaved changes to the frame and answers its leave sheet (J10-4n): «ذخیره و خروج» closes * it and saves as the save button does, leaving once «تأیید و ذخیره» went through; a broken rule * or «انصراف» keeps the page. @@ -78,7 +78,7 @@ export function PricingForm({ ? { frozen: true, pressableWhenFrozen: true } : offline)} > - {t(locked ? 'form.save-promotion' : 'form.save')} + {t(locked && !model.hasOffSale ? 'form.save-promotion' : 'form.save')} ); diff --git a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/PromotionBlock.tsx b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/PromotionBlock.tsx index 69925f1..dccf272 100644 --- a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/PromotionBlock.tsx +++ b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/PromotionBlock.tsx @@ -77,6 +77,9 @@ export function PromotionBlock({ onChange={(event) => model.setPromotionPercent(period, event.target.value) } + hint={t('promotion.floor-hint', { + floor: price(tier.floorTomanPerMonth), + })} error={percentError} /> ); diff --git a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/TierCard.test.tsx b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/TierCard.test.tsx new file mode 100644 index 0000000..657d856 --- /dev/null +++ b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/TierCard.test.tsx @@ -0,0 +1,101 @@ +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; + +import type { + PricingPageModel, + PricingTierView, +} from '../../../../../../../../features/pricing'; +import { TierCard } from './TierCard'; + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string, options?: Record) => + options ? `${key}:${JSON.stringify(options)}` : key, + }), +})); + +const tier = (over: Partial = {}): PricingTierView => ({ + billingPeriod: 'quarterly', + mandatory: false, + enabled: true, + priceId: 'price', + priceText: '', + priceMessage: null, + perMonthToman: null, + floorTotalToman: 597000, + floorTomanPerMonth: 199000, + offSale: false, + locked: false, + disableNoteCount: null, + promotion: { + enabled: false, + percent: '', + startsAt: null, + endsAt: null, + indefinite: true, + percentId: 'percent', + startsAtId: 'start', + endsAtId: 'end', + percentMessage: null, + startsAtMessage: null, + endsAtMessage: null, + priceToman: null, + perMonthToman: null, + percentValue: null, + saved: false, + running: false, + }, + ...over, +}); + +const model = (over: Partial = {}) => + ({ + firstTimeSetup: false, + lockedUntil: '2026-11-09T00:00:00.000Z', + setPrice: vi.fn(), + setEnabled: vi.fn(), + blurPrice: vi.fn(), + ...over, + }) as unknown as PricingPageModel; + +const renderCard = (view: PricingTierView, page = model()) => + render( + , + ); + +describe('TierCard during the lock', () => { + it('keeps a plain tier read-only', () => { + renderCard(tier({ locked: true, priceText: '700٬000' })); + expect(screen.getByRole('textbox').hasAttribute('readonly')).toBe(true); + expect(screen.queryByText('off-sale.badge')).toBeNull(); + }); + + it('lets a tier the floor took off sale be edited, and says it is off sale', async () => { + const page = model(); + renderCard(tier({ offSale: true, locked: false }), page); + expect(screen.getByText('off-sale.badge')).toBeTruthy(); + await userEvent.type(screen.getByRole('textbox'), '6'); + expect(page.setPrice).toHaveBeenCalledWith('quarterly', '6'); + }); +}); + +describe('TierCard floor hint', () => { + it('names the total and the month on a long period', () => { + renderCard(tier(), model({ lockedUntil: null })); + expect(screen.getByText(/form\.floor:/).textContent).toContain('597٬000'); + expect(screen.getByText(/form\.floor:/).textContent).toContain('199٬000'); + }); + + it('names only the month on the monthly one', () => { + renderCard( + tier({ + billingPeriod: 'monthly', + mandatory: true, + floorTotalToman: 199000, + }), + model({ lockedUntil: null }), + ); + expect(screen.getByText(/form\.floor-monthly:/)).toBeTruthy(); + }); +}); diff --git a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/TierCard.tsx b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/TierCard.tsx index 27f9cd0..bf64bc6 100644 --- a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/TierCard.tsx +++ b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/TierCard.tsx @@ -1,4 +1,5 @@ import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; import { Switch } from '@lumina/island/atoms/switch'; import { Tag } from '@lumina/island/atoms/tag'; import { Typography } from '@lumina/island/atoms/typography'; @@ -18,7 +19,8 @@ import { useFieldMessage } from './use-field-message'; * after (۲.۱), the rule it breaks in place of either (۳). Switched off, it collapses to its muted * switch row, with a note when subscribers run on it (۲.۲). A priced period carries its promotion * once the first save is done. During the lock the whole card is read-only at 50%, the total's - * note is its per-month figure, and the promotion moves to its own live card (۶.۲). + * note is its per-month figure, and the promotion moves to its own live card (۶.۲). A tier the floor + * took off sale says so and stays editable through the lock, since a valid price puts it back. */ export function TierCard({ tier, model, layout, onPickDate }: TierCardProps) { const { t } = useTranslation(['pricing', 'common']); @@ -26,7 +28,8 @@ export function TierCard({ tier, model, layout, onPickDate }: TierCardProps) { const headingId = useId(); const period = tier.billingPeriod; const periodLabel = t(`common:billing-periods.${period}`); - const locked = model.lockedUntil !== null; + const locked = tier.locked; + const lockRuns = model.lockedUntil !== null; const priceError = message(tier.priceMessage); const belowFloor = tier.priceMessage?.kind === 'issue' && @@ -34,7 +37,14 @@ export function TierCard({ tier, model, layout, onPickDate }: TierCardProps) { const promo = tier.promotion; // No promotion before the first save, nor on a period without a total (۴.۱). const showsPromotion = - !locked && !model.firstTimeSetup && tier.perMonthToman !== null; + !lockRuns && !model.firstTimeSetup && tier.perMonthToman !== null; + const floorHint = + period === 'monthly' + ? t('form.floor-monthly', { floor: price(tier.floorTomanPerMonth) }) + : t('form.floor', { + floor: price(tier.floorTomanPerMonth), + total: price(tier.floorTotalToman), + }); const showsDiscount = showsPromotion && promo.enabled && @@ -69,6 +79,11 @@ export function TierCard({ tier, model, layout, onPickDate }: TierCardProps) { {t('form.required-tag')} )} + {tier.offSale && ( + + {t('off-sale.badge')} + + )} {showsDiscount && promo.percentValue !== null && ( {t('card.discount', { @@ -112,7 +127,7 @@ export function TierCard({ tier, model, layout, onPickDate }: TierCardProps) { error={priceError} hint={ tier.perMonthToman === null - ? t('form.floor', { floor: price(tier.floorTomanPerMonth) }) + ? floorHint : t('form.per-month', { amount: price(tier.perMonthToman) }) } locked={locked} diff --git a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/use-field-message.ts b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/use-field-message.ts index 2ed7225..ccb0229 100644 --- a/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/use-field-message.ts +++ b/platforms/market/src/app/screens/(flow)/dashboard/pricing/organisms/pricing-form/components/use-field-message.ts @@ -15,7 +15,13 @@ export function useFieldMessage() { case 'required': return t('form.errors.required'); case 'below-floor': - return t('form.errors.below-floor', { floor: price(issue.floor) }); + return issue.period === 'monthly' + ? t('form.errors.below-floor', { floor: price(issue.floor) }) + : t('form.errors.below-floor-long', { + floor: price(issue.floor), + total: price(issue.floorTotal), + period: t(`form.total-of.${issue.period}`), + }); case 'per-month-increase': return t('form.errors.per-month-increase', { amount: price(issue.amount), diff --git a/platforms/market/src/app/screens/(main)/dashboard/plans/organisms/pricing-card/PricingCard.test.tsx b/platforms/market/src/app/screens/(main)/dashboard/plans/organisms/pricing-card/PricingCard.test.tsx new file mode 100644 index 0000000..740f1d6 --- /dev/null +++ b/platforms/market/src/app/screens/(main)/dashboard/plans/organisms/pricing-card/PricingCard.test.tsx @@ -0,0 +1,65 @@ +import { render, screen } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { PricingCardPartModel } from '../../../../../../../features/pricing'; +import { PricingCard } from './PricingCard'; + +const model = vi.hoisted(() => ({ current: null as unknown })); + +vi.mock('../../../../../../../features/pricing', () => ({ + usePricingCardPart: () => model.current, +})); + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string, options?: Record) => + options?.tier ? `${key}:${options.tier}` : key, + }), +})); + +const plan = (billingPeriod: 'monthly' | 'yearly', offSale = false) => ({ + billingPeriod, + offSale, + priceToman: 400000, + perMonthToman: 400000, + promotion: null, +}); + +const base: PricingCardPartModel = { + isEmpty: false, + plans: [plan('monthly'), plan('yearly', true)], + offSale: ['yearly'], + lockedUntil: null, + verification: 'approved', +}; + +describe('PricingCard off sale', () => { + beforeEach(() => { + model.current = base; + }); + + it('marks only the plan the floor took off sale', () => { + render(); + expect(screen.getAllByText('off-sale.badge')).toHaveLength(1); + }); + + it('shows a banner per plan, with its name and «اصلاح قیمت» to the editor', () => { + render(); + expect( + screen.getByText('off-sale.banner:common:billing-periods.yearly'), + ).toBeTruthy(); + const action = screen.getByRole('link', { name: 'off-sale.action' }); + expect(action.getAttribute('href')).toBe('/dashboard/pricing'); + }); + + it('shows neither while everything is on sale', () => { + model.current = { + ...base, + plans: [plan('monthly')], + offSale: [], + }; + render(); + expect(screen.queryByText('off-sale.badge')).toBeNull(); + expect(screen.queryByRole('link', { name: 'off-sale.action' })).toBeNull(); + }); +}); diff --git a/platforms/market/src/app/screens/(main)/dashboard/plans/organisms/pricing-card/PricingCard.tsx b/platforms/market/src/app/screens/(main)/dashboard/plans/organisms/pricing-card/PricingCard.tsx index e07d052..3c3da85 100644 --- a/platforms/market/src/app/screens/(main)/dashboard/plans/organisms/pricing-card/PricingCard.tsx +++ b/platforms/market/src/app/screens/(main)/dashboard/plans/organisms/pricing-card/PricingCard.tsx @@ -24,7 +24,8 @@ import type { PricingCardProps } from './types'; * notice «قیمت‌ها را هر ۷ روز یک‌بار می‌توانید تغییر دهید.» sits under the plans and the button * stays live, since promotions stay editable (1c). A creator not yet verified, or rejected, sees * that status above the card as a link to the identity block (1e), pending with «بررسی معمولاً تا - * ۲۴ ساعت طول می‌کشد.» beside it; prices stay editable. + * ۲۴ ساعت طول می‌کشد.» beside it; prices stay editable. A plan the price floor took off sale gets a + * banner above the card with «اصلاح قیمت» and a badge on its row (J10-1h). */ export function PricingCard({ layout }: PricingCardProps) { const { t } = useTranslation(['pricing', 'common']); @@ -60,6 +61,26 @@ export function PricingCard({ layout }: PricingCardProps) { )} + {model.offSale.map((period) => ( + + {t('off-sale.action')} + + } + > + {t('off-sale.banner', { + tier: t(`common:billing-periods.${period}`), + })} + + ))} {t(`common:billing-periods.${plan.billingPeriod}`)} + {plan.offSale && ( + + {t('off-sale.badge')} + + )} {promo && ( {t('card.discount', { percent: percent(promo.percent, 0) })} diff --git a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalForm.tsx b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalForm.tsx index 1f63553..831546a 100644 --- a/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalForm.tsx +++ b/platforms/market/src/app/screens/(main)/dashboard/subscriptions/organisms/renewal-sheet/components/RenewalForm.tsx @@ -112,6 +112,11 @@ export function RenewalForm({ {t('subscriptions.renewal.tiers')} + {tiers.length === 0 && ( + + {t('subscriptions.renewal.none-on-sale')} + + )} = { // From the admin panel (J11-7d, J11-7e). subscription_extended: { icon: 'calendar', tone: 'brand' }, rules_updated: { icon: 'file', tone: 'brand' }, + tier_off_sale: { icon: 'alert', tone: 'warning' }, subscription_refunded: { icon: 'receipt', tone: 'neutral' }, // Capacity opened, with the investor's code ready (J06-7e). waitlist_capacity: { icon: 'tag', tone: 'brand' }, diff --git a/platforms/market/src/features/checkout/models/checkout/use-checkout-page.ts b/platforms/market/src/features/checkout/models/checkout/use-checkout-page.ts index ef682f6..f76c1dc 100644 --- a/platforms/market/src/features/checkout/models/checkout/use-checkout-page.ts +++ b/platforms/market/src/features/checkout/models/checkout/use-checkout-page.ts @@ -307,6 +307,11 @@ export function useCheckoutPage({ return; } if (isConnectionError(error)) setIsOffline(true); + // The plan just left sale: the list reads again without it, and nothing stays picked. + if (code === CHECKOUT_ERROR_CODES.tierUnavailable) { + form.setValue('tierId', ''); + refreshScreen(); + } // An active subscription or a payment in flight: reloading sends the investor to the channel. const options = { t, diff --git a/platforms/market/src/features/checkout/repositories/checkout/constants.ts b/platforms/market/src/features/checkout/repositories/checkout/constants.ts index d5125ff..5741223 100644 --- a/platforms/market/src/features/checkout/repositories/checkout/constants.ts +++ b/platforms/market/src/features/checkout/repositories/checkout/constants.ts @@ -33,6 +33,8 @@ export const CHECKOUT_ERROR_CODES = { paymentPending: 'CHECKOUT_PAYMENT_PENDING', /** 403: the creator was suspended (or is no longer approved) since checkout opened. */ unavailable: 'CHECKOUT_UNAVAILABLE', + /** 409: the plan is off sale, below the price floor, on subscribe, renew and reactivate alike. */ + tierUnavailable: 'tier_unavailable', } as const; /** @@ -48,6 +50,7 @@ export const CHECKOUT_ERROR_COPY = { alreadyActive: 'errors:checkout.already-active', paymentPending: 'errors:checkout.payment-pending', unavailable: 'errors:checkout.unavailable', + tierUnavailable: 'errors:checkout.tier-unavailable', } as const; /** Each checkout code's copy, and the `*Args` field it belongs to when it has one. */ @@ -72,4 +75,7 @@ export const CHECKOUT_ERROR_RULES: Record< [CHECKOUT_ERROR_CODES.unavailable]: { message: CHECKOUT_ERROR_COPY.unavailable, }, + [CHECKOUT_ERROR_CODES.tierUnavailable]: { + message: CHECKOUT_ERROR_COPY.tierUnavailable, + }, }; diff --git a/platforms/market/src/features/checkout/repositories/checkout/errors.test.ts b/platforms/market/src/features/checkout/repositories/checkout/errors.test.ts new file mode 100644 index 0000000..a8b15b7 --- /dev/null +++ b/platforms/market/src/features/checkout/repositories/checkout/errors.test.ts @@ -0,0 +1,21 @@ +import { HttpError } from '@lumina/libs/http'; +import { describe, expect, it } from 'vitest'; + +import { CHECKOUT_ERROR_CODES } from './constants'; +import { checkoutErrorCode, toCheckoutError } from './errors'; + +const refusal = (code: string) => + new HttpError({ code, message: 'server text', status: 409 }); + +describe('tier_unavailable', () => { + it('gets its own copy and code on subscribe, renew and reactivate alike', () => { + const error = toCheckoutError(refusal('tier_unavailable')) as HttpError; + expect(error.message).toBe('errors:checkout.tier-unavailable'); + expect(checkoutErrorCode(error)).toBe(CHECKOUT_ERROR_CODES.tierUnavailable); + }); + + it('leaves any other code alone', () => { + const other = refusal('SOMETHING_ELSE'); + expect(toCheckoutError(other)).toBe(other); + }); +}); diff --git a/platforms/market/src/features/notification/constants.ts b/platforms/market/src/features/notification/constants.ts index 0b77b27..5e27e68 100644 --- a/platforms/market/src/features/notification/constants.ts +++ b/platforms/market/src/features/notification/constants.ts @@ -36,4 +36,5 @@ export const NOTIFICATION_CATEGORY: Partial< account_reinstated: 'account', capacity_request_result: 'account', invite_code_deactivated: 'account', + tier_off_sale: 'account', }; diff --git a/platforms/market/src/features/notification/entities/notification/types.ts b/platforms/market/src/features/notification/entities/notification/types.ts index 69e2615..14a793a 100644 --- a/platforms/market/src/features/notification/entities/notification/types.ts +++ b/platforms/market/src/features/notification/entities/notification/types.ts @@ -17,6 +17,7 @@ * that an admin corrected one of their predictions (with the reason as its body). * * `rules_updated` tells every user a major version of the rules is out (links to /terms). + * `tier_off_sale` tells a creator the price floor took a plan off sale (links to طرح‌های اشتراک). * * From the admin panel (J11-7): `subscription_extended` tells an investor their subscription got * extra days (with the new expiry), `subscription_refunded` that money was paid back and the @@ -32,6 +33,7 @@ export type NotificationType = | 'subscription_expired_suspended' | 'subscription_extended' | 'rules_updated' + | 'tier_off_sale' | 'subscription_refunded' | 'payment_pending_review' | 'waitlist_capacity' diff --git a/platforms/market/src/features/pricing/constants.ts b/platforms/market/src/features/pricing/constants.ts index a6892d8..df9534b 100644 --- a/platforms/market/src/features/pricing/constants.ts +++ b/platforms/market/src/features/pricing/constants.ts @@ -6,9 +6,6 @@ export const PRICING_EVENTS = { 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; diff --git a/platforms/market/src/features/pricing/entities/pricing-tier/types.ts b/platforms/market/src/features/pricing/entities/pricing-tier/types.ts index 46d05f3..6e636ab 100644 --- a/platforms/market/src/features/pricing/entities/pricing-tier/types.ts +++ b/platforms/market/src/features/pricing/entities/pricing-tier/types.ts @@ -32,6 +32,10 @@ export type PricingTierEntity = { perMonthEquivalentFa: string | null; floorTomanPerMonth: number; floorHelperFa: string; + promoFloorHintFa: string; + /** Below the price floor: hidden from buyers until a valid price is saved. */ + offSale: boolean; + offSaleBannerFa: string | null; priceFieldLabelFa: string; suggestedPriceToman: number | null; suggestionHintFa: string | null; diff --git a/platforms/market/src/features/pricing/index.ts b/platforms/market/src/features/pricing/index.ts index 3b62385..0bd9fd8 100644 --- a/platforms/market/src/features/pricing/index.ts +++ b/platforms/market/src/features/pricing/index.ts @@ -1,11 +1,7 @@ import './types'; export { savePricing } from './actions/save-pricing'; -export { - PRICE_ROUND_STEP_TOMAN, - PRICING_EVENTS, - PROMO_FLOOR_TOMAN_PER_MONTH, -} from './constants'; +export { PRICE_ROUND_STEP_TOMAN, PRICING_EVENTS } from './constants'; export { usePricingPage } from './models/pricing'; export type { PricingFieldMessage, diff --git a/platforms/market/src/features/pricing/models/pricing-card/types.ts b/platforms/market/src/features/pricing/models/pricing-card/types.ts index 5b6a6cb..3d006a8 100644 --- a/platforms/market/src/features/pricing/models/pricing-card/types.ts +++ b/platforms/market/src/features/pricing/models/pricing-card/types.ts @@ -6,6 +6,8 @@ import type { /** A priced, offered plan as the «قیمت طرح‌ها» card lists it. */ export type PricingPlanRow = { billingPeriod: BillingPeriod; + /** Below the price floor: hidden from buyers until a valid price is saved. */ + offSale: boolean; /** The standing period total. */ priceToman: number; perMonthToman: number; @@ -23,6 +25,8 @@ export type PricingCardPartModel = { /** Nothing priced yet: one line and «تعیین قیمت‌ها» (۲.۴). */ isEmpty: boolean; plans: PricingPlanRow[]; + /** The plans the price floor took off sale: each gets a banner with «اصلاح قیمت». */ + offSale: BillingPeriod[]; /** During the 7-day lock: when standing prices open again (۲.۳). */ lockedUntil: string | null; verification: VerificationStatus; diff --git a/platforms/market/src/features/pricing/models/pricing-card/use-pricing-card-part.ts b/platforms/market/src/features/pricing/models/pricing-card/use-pricing-card-part.ts index d1fa71d..03fcecc 100644 --- a/platforms/market/src/features/pricing/models/pricing-card/use-pricing-card-part.ts +++ b/platforms/market/src/features/pricing/models/pricing-card/use-pricing-card-part.ts @@ -7,7 +7,7 @@ import type { PricingCardPartModel, PricingPlanRow } from './types'; /** * طرح‌های اشتراک › «قیمت طرح‌ها» (Creator Dashboard ۲.۱–۲.۵): each offered, priced plan with its * total and per-month equivalent, a running promotion over its struck standing price, the lock's - * end, and the creator's verification for the badge above. The C7 page reads the same query, so a + * end, the tiers the price floor took off sale, and the creator's verification for the badge above. The C7 page reads the same query, so a * save there shows here at once. */ export function usePricingCardPart(): PricingCardPartModel { @@ -23,6 +23,7 @@ export function usePricingCardPart(): PricingCardPartModel { return [ { billingPeriod: tier.billingPeriod, + offSale: tier.offSale, priceToman: tier.priceToman, perMonthToman: tier.perMonthToman ?? Math.round(tier.priceToman / months), @@ -43,6 +44,9 @@ export function usePricingCardPart(): PricingCardPartModel { return { isEmpty: data.firstTimeSetup || plans.length === 0, plans, + offSale: plans + .filter((plan) => plan.offSale) + .map((plan) => plan.billingPeriod), lockedUntil: data.cooldown.locked ? data.cooldown.editableAt : null, verification: data.verification.status, }; diff --git a/platforms/market/src/features/pricing/models/pricing/pricing-rules.test.ts b/platforms/market/src/features/pricing/models/pricing/pricing-rules.test.ts new file mode 100644 index 0000000..88eb785 --- /dev/null +++ b/platforms/market/src/features/pricing/models/pricing/pricing-rules.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, it } from 'vitest'; + +import { checkPricingDraft, floorTotal, perMonth } from './pricing-rules'; +import type { PricingFormValues, PricingTierValues } from './types'; + +const FLOOR = 199000; + +const tier = (price: string, over: Partial = {}) => ({ + enabled: price !== '', + priceToman: price, + promotion: { + enabled: false, + percent: '', + startsAt: null, + endsAt: null, + indefinite: true, + }, + ...over, +}); +const values = ( + over: Partial = {}, +): PricingFormValues => ({ + tiers: { + monthly: tier('400000'), + quarterly: tier(''), + semi_annual: tier(''), + yearly: tier(''), + ...over, + }, +}); +const withPromotion = (price: string, percent: string) => + tier(price, { + promotion: { + enabled: true, + percent, + startsAt: null, + endsAt: null, + indefinite: true, + }, + }); + +describe('floorTotal', () => { + it.each([ + ['monthly', 199000], + ['quarterly', 597000], + ['semi_annual', 1194000], + ['yearly', 2388000], + ] as const)('%s needs %d at 199,000 a month', (period, total) => { + expect(floorTotal(FLOOR, period)).toBe(total); + }); +}); + +describe('checkPricingDraft floor', () => { + it('passes a price exactly at the floor', () => { + expect( + checkPricingDraft(values({ monthly: tier('199000') }), FLOOR), + ).toEqual({}); + expect( + checkPricingDraft( + values({ monthly: tier('199000'), quarterly: tier('597000') }), + FLOOR, + ), + ).toEqual({}); + }); + + it('refuses a monthly price under the floor, naming the floor', () => { + const issues = checkPricingDraft( + values({ monthly: tier('198000') }), + FLOOR, + ); + expect(issues['tiers.monthly.priceToman']).toEqual({ + code: 'below-floor', + floor: FLOOR, + floorTotal: FLOOR, + period: 'monthly', + }); + }); + + it('compares the exact total, so per-month rounding lets nothing under', () => { + expect(perMonth(596999, 'quarterly')).toBe(FLOOR); + const issues = checkPricingDraft( + values({ quarterly: tier('596999') }), + FLOOR, + ); + expect(issues['tiers.quarterly.priceToman']).toEqual({ + code: 'below-floor', + floor: FLOOR, + floorTotal: 597000, + period: 'quarterly', + }); + }); + + it('uses the same floor for every period, with no older per-tier one', () => { + const issues = checkPricingDraft( + values({ + monthly: tier('250000'), + quarterly: tier('600000'), + semi_annual: tier('1200000'), + yearly: tier('2388000'), + }), + FLOOR, + ); + expect(issues).toEqual({}); + }); + + it('follows a floor the admin raised', () => { + const issues = checkPricingDraft( + values({ monthly: tier('240000') }), + 250000, + ); + expect(issues['tiers.monthly.priceToman']).toMatchObject({ floor: 250000 }); + }); + + it('ignores a switched-off period', () => { + expect( + checkPricingDraft( + values({ quarterly: { ...tier('100000'), enabled: false } }), + FLOOR, + ), + ).toEqual({}); + }); +}); + +describe('checkPricingDraft promotion floor', () => { + it('refuses a discount that lands under the floor, with the discounted month', () => { + const issues = checkPricingDraft( + values({ monthly: withPromotion('300000', '50') }), + FLOOR, + ); + expect(issues['tiers.monthly.promotion.percent']).toEqual({ + code: 'promo-floor', + amount: 150000, + floor: FLOOR, + }); + }); + + it('passes a discount that lands exactly on the floor', () => { + const issues = checkPricingDraft( + values({ monthly: withPromotion('398000', '50') }), + FLOOR, + ); + expect(issues['tiers.monthly.promotion.percent']).toBeUndefined(); + }); + + it('has no separate, lower promotion floor', () => { + const issues = checkPricingDraft( + values({ monthly: withPromotion('200000', '10') }), + FLOOR, + ); + expect(issues['tiers.monthly.promotion.percent']).toMatchObject({ + code: 'promo-floor', + }); + }); + + it('compares the discounted total exactly on a long period', () => { + const issues = checkPricingDraft( + values({ + monthly: tier('400000'), + quarterly: withPromotion('1192000', '50'), + }), + FLOOR, + ); + expect(issues['tiers.quarterly.promotion.percent']).toMatchObject({ + code: 'promo-floor', + }); + }); +}); diff --git a/platforms/market/src/features/pricing/models/pricing/pricing-rules.ts b/platforms/market/src/features/pricing/models/pricing/pricing-rules.ts index 8d7465d..0c938be 100644 --- a/platforms/market/src/features/pricing/models/pricing/pricing-rules.ts +++ b/platforms/market/src/features/pricing/models/pricing/pricing-rules.ts @@ -4,10 +4,7 @@ import { } from '../../../../shared/constants'; import type { BillingPeriod } from '../../../../shared/constants'; import { toPriceNumber } from '../../../../shared/utils'; -import { - PRICE_ROUND_STEP_TOMAN, - PROMO_FLOOR_TOMAN_PER_MONTH, -} from '../../constants'; +import { PRICE_ROUND_STEP_TOMAN } from '../../constants'; import type { PricingFieldName, SavePricingArgs, @@ -15,7 +12,8 @@ import type { import type { PricingFormValues, PricingIssue } from './types'; // The C7 rules (§۳, §۴, §۷.۱) the API enforces, checked as the creator types so nothing waits for -// a save to say what is wrong. Same order and same first-message-per-field as the API. +// a save to say what is wrong. Same order and same first-message-per-field as the API. The floor is +// the one the API reports, compared on the exact total, so rounding per month lets nothing under it. /** A typed total as whole Toman; `null` while empty or not a number. */ export function toToman(text: string): number | null { @@ -29,6 +27,14 @@ export function perMonth(total: number, period: BillingPeriod): number { return Math.round(total / BILLING_PERIOD_MONTHS[period]); } +/** The least a total of this period may be at this monthly floor. */ +export function floorTotal( + floorPerMonth: number, + period: BillingPeriod, +): number { + return floorPerMonth * BILLING_PERIOD_MONTHS[period]; +} + /** The promotional total, rounded down to 1,000 so the investor gets at least the advertised discount. */ export function promotionalTotal(total: number, percent: number): number { const raw = (total * (100 - percent)) / 100; @@ -51,7 +57,7 @@ export type PromotionStartContext = { export function checkPricingDraft( values: PricingFormValues, - floors: Record, + floorPerMonth: number, starts?: PromotionStartContext, ): Partial> { const issues: Partial> = {}; @@ -68,10 +74,12 @@ export function checkPricingDraft( add(`tiers.${period}.priceToman`, { code: 'required' }); continue; } - if (perMonth(total, period) < floors[period]) { + if (total < floorTotal(floorPerMonth, period)) { add(`tiers.${period}.priceToman`, { code: 'below-floor', - floor: floors[period], + floor: floorPerMonth, + floorTotal: floorTotal(floorPerMonth, period), + period, }); } } @@ -103,15 +111,12 @@ export function checkPricingDraft( } else { const total = toToman(values.tiers[period].priceToman); if (total !== null) { - const promoPerMonth = perMonth( - promotionalTotal(total, percent), - period, - ); - if (promoPerMonth < PROMO_FLOOR_TOMAN_PER_MONTH) { + const promoTotal = promotionalTotal(total, percent); + if (promoTotal < floorTotal(floorPerMonth, period)) { add(`tiers.${period}.promotion.percent`, { code: 'promo-floor', - amount: promoPerMonth, - floor: PROMO_FLOOR_TOMAN_PER_MONTH, + amount: perMonth(promoTotal, period), + floor: floorPerMonth, }); } } diff --git a/platforms/market/src/features/pricing/models/pricing/types.ts b/platforms/market/src/features/pricing/models/pricing/types.ts index 288ca42..0e0069c 100644 --- a/platforms/market/src/features/pricing/models/pricing/types.ts +++ b/platforms/market/src/features/pricing/models/pricing/types.ts @@ -31,7 +31,12 @@ export type PricingFormValues = { /** A broken rule, with what its message needs. */ export type PricingIssue = | { code: 'required' } - | { code: 'below-floor'; floor: number } + | { + code: 'below-floor'; + floor: number; + floorTotal: number; + period: BillingPeriod; + } | { code: 'per-month-increase'; amount: number; @@ -81,7 +86,13 @@ export type PricingTierView = { priceMessage: PricingFieldMessage | null; /** The per-month equivalent of a valid total. */ perMonthToman: number | null; + /** The least this period's total may be, after any discount. */ + floorTotalToman: number; floorTomanPerMonth: number; + /** Below the floor: hidden from buyers until a valid price is saved («خارج از فروش»). */ + offSale: boolean; + /** Its price and switch are read-only: the lock runs, and the floor didn't take it off sale. */ + locked: boolean; /** Switched off while it carries running subscriptions: they run to their end (۲.۲). */ disableNoteCount: number | null; promotion: PricingPromotionView; @@ -102,6 +113,8 @@ export type PricingPageModel = { prePurchase: boolean; /** Standing prices and periods frozen until this date; promotions stay live (۶.۲). */ lockedUntil: string | null; + /** A tier is off sale: its price stays editable through the lock, so the save is a full one. */ + hasOffSale: boolean; tiers: PricingTierView[]; setEnabled: (period: BillingPeriod, enabled: boolean) => void; setPrice: (period: BillingPeriod, text: string) => void; diff --git a/platforms/market/src/features/pricing/models/pricing/use-pricing-page.ts b/platforms/market/src/features/pricing/models/pricing/use-pricing-page.ts index 3f01ad0..a508f45 100644 --- a/platforms/market/src/features/pricing/models/pricing/use-pricing-page.ts +++ b/platforms/market/src/features/pricing/models/pricing/use-pricing-page.ts @@ -27,6 +27,7 @@ import type { } from '../../repositories/pricing'; import { checkPricingDraft, + floorTotal, perMonth, pricingFieldId, promotionalTotal, @@ -88,7 +89,8 @@ function defaultPromotionRange(): { startsAt: string; endsAt: string } { * enabled period only once a save is tried. On first setup, leaving the monthly field fills the longer periods' suggestions. Save * asks the API to check the draft, then confirms in a dialog that lists every period; «تأیید و * ذخیره» stores it, toasts and leaves the page as saved. During the 7-day lock standing prices and - * the periods are frozen, promotions not. A save that never reached the API keeps everything and + * the periods are frozen, promotions not, and so is a tier the floor took off sale, which a valid + * price puts back on sale. A save that never reached the API keeps everything and * offers to try again from the banner. */ export function usePricingPage(): PricingPageModel { @@ -121,16 +123,12 @@ export function usePricingPage(): PricingPageModel { }); const locked = payload.cooldown.locked; - const floors = useMemo( - () => - Object.fromEntries( - payload.tiers.map((tier) => [ - tier.billingPeriod, - tier.floorTomanPerMonth, - ]), - ) as Record, - [payload.tiers], - ); + const floorPerMonth = payload.floorTomanPerMonth; + const isPriceLocked = (period: BillingPeriod) => + locked && + !payload.tiers.some( + (tier) => tier.billingPeriod === period && tier.offSale, + ); const savedStarts = useMemo( () => Object.fromEntries( @@ -143,11 +141,11 @@ export function usePricingPage(): PricingPageModel { ); const issues = useMemo( () => - checkPricingDraft(values, floors, { + checkPricingDraft(values, floorPerMonth, { saved: savedStarts, notBefore: openedAt, }), - [values, floors, savedStarts, openedAt], + [values, floorPerMonth, savedStarts, openedAt], ); // A rule about a field still empty (an enabled period's price, a promotion's percent or end) @@ -195,7 +193,10 @@ export function usePricingPage(): PricingPageModel { ? messageOf(priceField, current.priceToman !== '') : null, perMonthToman: total === null ? null : perMonth(total, period), - floorTomanPerMonth: tier.floorTomanPerMonth, + floorTotalToman: floorTotal(floorPerMonth, period), + floorTomanPerMonth: floorPerMonth, + offSale: tier.offSale, + locked: locked && !tier.offSale, disableNoteCount: !current.enabled && tier.enabled && tier.activeSubscribers > 0 ? tier.activeSubscribers @@ -301,6 +302,8 @@ export function usePricingPage(): PricingPageModel { const saved = toFormValues(fresh); for (const tier of fresh.tiers) { const period = tier.billingPeriod; + // The lock never covers a tier the floor took off sale: its edit stays. + if (tier.offSale) continue; form.resetField(`tiers.${period}.enabled`, { defaultValue: saved.tiers[period].enabled, }); @@ -377,19 +380,20 @@ export function usePricingPage(): PricingPageModel { verification: payload.verification.status, prePurchase: payload.cooldown.prePurchase, lockedUntil: locked ? payload.cooldown.editableAt : null, + hasOffSale: payload.tiers.some((tier) => tier.offSale), tiers, setEnabled: (period, enabled) => { - if (locked || period === 'monthly') return; + if (isPriceLocked(period) || period === 'monthly') return; update(`tiers.${period}.enabled`, enabled); }, setPrice: (period, text) => { - if (locked) return; + if (isPriceLocked(period)) return; update(`tiers.${period}.priceToman`, toAmountText(text)); }, blurPrice: (period) => { if (period !== 'monthly' || !payload.firstTimeSetup) return; const monthly = toToman(form.getValues('tiers.monthly.priceToman')); - if (monthly !== null && monthly >= floors.monthly) + if (monthly !== null && monthly >= floorPerMonth) fillSuggestions(monthly); }, setPromotionEnabled: (period, enabled) => { diff --git a/platforms/market/src/features/pricing/repositories/pricing/mappers.ts b/platforms/market/src/features/pricing/repositories/pricing/mappers.ts index eac2bdd..734d37c 100644 --- a/platforms/market/src/features/pricing/repositories/pricing/mappers.ts +++ b/platforms/market/src/features/pricing/repositories/pricing/mappers.ts @@ -24,7 +24,7 @@ function toPricingTierPayload(dto: PricingTierEntity): PricingTierPayload { enabled: dto.enabled, priceToman: dto.priceToman, perMonthToman: dto.perMonthToman, - floorTomanPerMonth: dto.floorTomanPerMonth, + offSale: dto.offSale, suggestedPriceToman: dto.suggestedPriceToman, prefillSuggestion: dto.prefillSuggestion, activeSubscribers: dto.activeSubscribers, @@ -46,6 +46,7 @@ export function toPricingFormPayload( ): PricingFormPayload { return { firstTimeSetup: dto.firstTimeSetup, + floorTomanPerMonth: dto.floorTomanPerMonth, verification: { status: dto.verification.status, canBeSubscribedTo: dto.verification.canBeSubscribedTo, diff --git a/platforms/market/src/features/pricing/repositories/pricing/types.ts b/platforms/market/src/features/pricing/repositories/pricing/types.ts index 31d6ca8..a43a0bb 100644 --- a/platforms/market/src/features/pricing/repositories/pricing/types.ts +++ b/platforms/market/src/features/pricing/repositories/pricing/types.ts @@ -22,6 +22,8 @@ export type PricingFormResponseDto = { monthlyMandatoryNoteFa: string; existingSubscribersNoteFa: string; firstTimeSetup: boolean; + /** «کف قیمت»: the least any tier may finally cost per month, after any discount. */ + floorTomanPerMonth: number; verification: { status: VerificationStatus; canBeSubscribedTo: boolean; @@ -66,8 +68,8 @@ export type PricingTierPayload = { enabled: boolean; priceToman: number | null; perMonthToman: number | null; - /** The lowest allowed price per month for this period. */ - floorTomanPerMonth: number; + /** Below the price floor: hidden from buyers, and editable through the 7-day lock. */ + offSale: boolean; /** Monthly × duration minus the period's discount, from the saved (or previewed) monthly price. */ suggestedPriceToman: number | null; prefillSuggestion: boolean; @@ -79,6 +81,8 @@ export type PricingTierPayload = { export type PricingFormPayload = { /** Nothing has been priced yet; the longer periods carry the suggestions as prices. */ firstTimeSetup: boolean; + /** «کف قیمت»: the least any tier may finally cost per month, after any discount. */ + floorTomanPerMonth: number; verification: { status: VerificationStatus; canBeSubscribedTo: boolean; diff --git a/platforms/market/src/features/subscription/models/renewal/use-renewal-sheet.ts b/platforms/market/src/features/subscription/models/renewal/use-renewal-sheet.ts index 8a04614..b700bf5 100644 --- a/platforms/market/src/features/subscription/models/renewal/use-renewal-sheet.ts +++ b/platforms/market/src/features/subscription/models/renewal/use-renewal-sheet.ts @@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { ROUTES } from '../../../../app/navigation/navigation'; +import { CHECKOUT_ERROR_CODES, checkoutErrorCode } from '../../../checkout'; import { isConnectionError, showActionError } from '../../../../shared/utils'; import { startRenewal } from '../../actions/start-renewal'; import { @@ -22,7 +23,8 @@ import type { * starts on the current period and extends from the current expiry; reactivate starts with none * picked, from today, with no invite code. Paying goes to the bank, and every payment ends on its * result page (U10 §۹). A tap that never reached the server keeps the choice and says so. A - * suspended creator or a payment already in flight is refused with a toast that reloads the list. + * suspended creator, a payment already in flight or a plan off sale (below the price floor) is + * refused with a toast that reloads the list; an off-sale plan isn't offered at all. */ export function useRenewalSheet({ subscriptionId, @@ -55,6 +57,9 @@ export function useRenewalSheet({ }, []); const reload = () => { + void queryClient.invalidateQueries({ + queryKey: subscriptionKeys.preview(subscriptionId), + }); void queryClient.invalidateQueries({ queryKey: subscriptionKeys.detail(subscriptionId), }); @@ -89,6 +94,11 @@ export function useRenewalSheet({ } catch (error) { setPhase('idle'); if (isConnectionError(error)) setIsOffline(true); + // The plan just left sale: the list reads again without it, and nothing stays picked. + if (checkoutErrorCode(error) === CHECKOUT_ERROR_CODES.tierUnavailable) { + setTierId(null); + reload(); + } showActionError(error, { t, failedMessage: diff --git a/platforms/market/src/index.ts b/platforms/market/src/index.ts index d968579..68614ed 100644 --- a/platforms/market/src/index.ts +++ b/platforms/market/src/index.ts @@ -246,7 +246,6 @@ export { PRICING_EVENTS, pricingKeys, pricingRepository, - PROMO_FLOOR_TOMAN_PER_MONTH, savePricing, usePricingCardPart, usePricingPage, diff --git a/platforms/market/src/shared/locales/fa/dashboard.json b/platforms/market/src/shared/locales/fa/dashboard.json index 6da550e..eddd3d7 100644 --- a/platforms/market/src/shared/locales/fa/dashboard.json +++ b/platforms/market/src/shared/locales/fa/dashboard.json @@ -58,6 +58,7 @@ "error": "دوره‌های اشتراک بارگذاری نشد. دوباره تلاش کنید.", "current": "شما تا {{date}} اشتراک فعال دارید.", "tiers": "دوره اشتراک", + "none-on-sale": "این کانال در حال حاضر طرحی برای فروش ندارد. پس از اصلاح قیمت‌ها می‌توانید اشتراک را تمدید کنید.", "from": "تمدید از:", "start": "شروع از:", "today": "امروز — {{date}}", diff --git a/platforms/market/src/shared/locales/fa/errors.json b/platforms/market/src/shared/locales/fa/errors.json index a346662..55e5488 100644 --- a/platforms/market/src/shared/locales/fa/errors.json +++ b/platforms/market/src/shared/locales/fa/errors.json @@ -102,6 +102,7 @@ "code-invalid": "کد دعوت وارد‌شده معتبر نیست.", "already-active": "اشتراک شما در این کانال همین حالا فعال است.", "payment-pending": "پرداخت دیگری برای این کانال در حال بررسی است؛ تا روشن شدن نتیجه آن، پرداخت تازه‌ای شروع نمی‌شود.", - "unavailable": "این کانال در حال حاضر در دسترس نیست." + "unavailable": "این کانال در حال حاضر در دسترس نیست.", + "tier-unavailable": "این طرح در حال حاضر در فروش نیست. طرح دیگری را انتخاب کنید." } } diff --git a/platforms/market/src/shared/locales/fa/pricing.json b/platforms/market/src/shared/locales/fa/pricing.json index f6a1f16..f464b95 100644 --- a/platforms/market/src/shared/locales/fa/pricing.json +++ b/platforms/market/src/shared/locales/fa/pricing.json @@ -18,6 +18,11 @@ "loading": "در حال بارگذاری قیمت طرح‌ها…", "error": "قیمت طرح‌ها بارگذاری نشد. دوباره تلاش کنید." }, + "off-sale": { + "badge": "خارج از فروش", + "banner": "طرح {{tier}} شما از فروش خارج شد", + "action": "اصلاح قیمت" + }, "form": { "label": "قیمت‌گذاری اشتراک", "required-tag": "الزامی", @@ -26,7 +31,13 @@ "price-label": "قیمت کل دوره", "price-label-of": "قیمت کل دوره {{period}}", "currency": "تومان", - "floor": "حداقل قیمت این دوره {{floor}} تومان در ماه است.", + "floor": "حداقل {{total}} تومان ({{floor}} در ماه)، حتی بعد از تخفیف.", + "floor-monthly": "حداقل {{floor}} تومان در ماه، حتی بعد از تخفیف.", + "total-of": { + "quarterly": "سه ماه", + "semi_annual": "شش ماه", + "yearly": "یک سال" + }, "per-month": "معادل {{amount}} تومان در ماه", "disable-note": "{{count}} مشترک فعال روی این دوره دارید. با غیرفعال کردن، اشتراک آن‌ها تا پایان دوره ادامه می‌یابد و فقط این دوره برای کاربران جدید نمایش داده نمی‌شود.", "existing-note": "تغییر قیمت روی مشترکان فعلی تأثیری ندارد. قیمت جدید از زمان تمدید اشتراک آن‌ها اعمال می‌شود.", @@ -44,9 +55,10 @@ "errors": { "required": "وارد کردن قیمت برای دوره‌های فعال الزامی است.", "below-floor": "قیمت این دوره نمی‌تواند کمتر از {{floor}} تومان در ماه باشد.", + "below-floor-long": "قیمت این دوره نمی‌تواند کمتر از {{floor}} تومان در ماه ({{total}} تومان برای {{period}}) باشد.", "per-month-increase": "قیمت ماهانه این دوره ({{amount}} تومان) نباید بیشتر از دوره {{period}} ({{shorter}} تومان) باشد.", "promo-percent": "درصد تخفیف باید بین ۱ تا ۹۹ باشد.", - "promo-floor": "قیمت با تخفیف ({{amount}} تومان در ماه) نمی‌تواند کمتر از {{floor}} تومان در ماه باشد.", + "promo-floor": "قیمت با تخفیف ({{amount}} تومان در ماه) نمی‌تواند کمتر از کف {{floor}} تومان در ماه باشد.", "promo-end-required": "تاریخ و ساعت پایان را انتخاب کنید، یا «بدون تاریخ پایان» را بزنید.", "promo-start-past": "تاریخ و ساعت شروع نمی‌تواند در گذشته باشد.", "promo-range": "تاریخ و ساعت پایان باید بعد از شروع باشد." @@ -59,6 +71,7 @@ "intro": "با فعال‌کردن، درصد تخفیف و بازه زمانی آن را تعیین می‌کنید. قیمت پایه این دوره تغییر نمی‌کند.", "percent": "درصد تخفیف", "percent-sign": "٪", + "floor-hint": "قیمت با تخفیف نباید کمتر از {{floor}} تومان در ماه شود.", "start": "تاریخ و ساعت شروع", "end": "تاریخ و ساعت پایان", "indefinite": "بدون تاریخ پایان", diff --git a/vitest.config.ts b/vitest.config.ts index eab11cd..6131e51 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -2,7 +2,6 @@ import { defineConfig } from 'vitest/config'; // Component and unit tests of every project; each project's `test` script runs its own folder. export default defineConfig({ - esbuild: { jsx: 'automatic' }, oxc: { jsx: { runtime: 'automatic' } }, resolve: { conditions: ['@lumina/source'] }, test: {