diff --git a/apps/wall-street-plaza/.env.example b/apps/wall-street-plaza/.env.example new file mode 100644 index 0000000..d2e1012 --- /dev/null +++ b/apps/wall-street-plaza/.env.example @@ -0,0 +1,11 @@ +# Copy to .env.local. Public variables are inlined into the browser bundle: never put a secret in one. +NEXT_PUBLIC_SITE_URL=http://localhost:7002 + +# Server only: the admin API's origin from inside the deployment network (0061). The browser's +# /api proxy goes there (next.config rewrite, fixed at build time). The admin app never calls the +# public gateway. +ADMIN_API_INTERNAL_ORIGIN=http://localhost:9010 + +# Only for steps that run without the real env (lint, type-check). A build still needs +# ADMIN_API_INTERNAL_ORIGIN: the /api rewrite keeps the value it was built with. +SKIP_ENV_VALIDATION=false diff --git a/apps/wall-street-plaza/.swcrc b/apps/wall-street-plaza/.swcrc new file mode 100644 index 0000000..e912f18 --- /dev/null +++ b/apps/wall-street-plaza/.swcrc @@ -0,0 +1,30 @@ +{ + "jsc": { + "target": "es2017", + "parser": { + "syntax": "typescript", + "decorators": true, + "dynamicImport": true + }, + "transform": { + "decoratorMetadata": true, + "legacyDecorator": true + }, + "keepClassNames": true, + "externalHelpers": true, + "loose": true + }, + "module": { + "type": "commonjs" + }, + "sourceMaps": true, + "exclude": [ + "jest.config.[ct]s", + ".*\\.spec.tsx?$", + ".*\\.test.tsx?$", + "./src/jest-setup.ts$", + "./**/jest-setup.ts$", + ".*.js$", + ".*.d.ts$" + ] +} diff --git a/apps/wall-street-plaza/AGENTS.md b/apps/wall-street-plaza/AGENTS.md new file mode 100644 index 0000000..643577d --- /dev/null +++ b/apps/wall-street-plaza/AGENTS.md @@ -0,0 +1,9 @@ + + +# This is NOT the Next.js you know + +This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. + +This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. + + diff --git a/apps/wall-street-plaza/CLAUDE.md b/apps/wall-street-plaza/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/apps/wall-street-plaza/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/apps/wall-street-plaza/eslint.config.mjs b/apps/wall-street-plaza/eslint.config.mjs new file mode 100644 index 0000000..71dcc08 --- /dev/null +++ b/apps/wall-street-plaza/eslint.config.mjs @@ -0,0 +1,3 @@ +import baseConfig from '../../eslint.config.mjs'; + +export default baseConfig; diff --git a/apps/wall-street-plaza/index.d.ts b/apps/wall-street-plaza/index.d.ts new file mode 100644 index 0000000..89925ef --- /dev/null +++ b/apps/wall-street-plaza/index.d.ts @@ -0,0 +1 @@ +/// diff --git a/apps/wall-street-plaza/next.config.ts b/apps/wall-street-plaza/next.config.ts new file mode 100644 index 0000000..d40a777 --- /dev/null +++ b/apps/wall-street-plaza/next.config.ts @@ -0,0 +1,66 @@ +import { withFontCopy } from '@lumina/island/tools/font-copy-plugin'; +import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin'; +import type { NextConfig } from 'next'; + +import { + API_PROXY_MAX_BODY, + API_PROXY_PATH, + API_PROXY_TIMEOUT_MS, +} from './src/constants'; +import { adminApiInternalUrl } from './src/env/env.config'; + +// Fonts and the icon sprite keep fixed names (0011, 0012); Next serves public/ with max-age=0. +const immutable = [ + { key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }, +]; + +// The panel is never framed, never indexed, and never sends full URLs to other sites. +const security = [ + { key: 'Content-Security-Policy', value: "frame-ancestors 'none'" }, + { key: 'X-Frame-Options', value: 'DENY' }, + { key: 'X-Content-Type-Options', value: 'nosniff' }, + { key: 'Referrer-Policy', value: 'same-origin' }, + { key: 'X-Robots-Tag', value: 'noindex, nofollow' }, +]; + +const nextConfig: NextConfig = { + // Metadata always in (0054). + htmlLimitedBots: /.*/, + experimental: { + proxyTimeout: API_PROXY_TIMEOUT_MS, + proxyClientMaxBodySize: API_PROXY_MAX_BODY, + }, + // Workspace packages export TypeScript source, so Next.js compiles them. + transpilePackages: [ + '@lumina/garden-roof', + '@lumina/integrations', + '@lumina/island', + '@lumina/libs', + '@lumina/tools', + ], + // The browser calls the admin API on this site's origin (`/api/v1/admin/…`), proxied to + // admin-api, so there is no CORS and the session cookies are this site's (0061). No service + // worker or manifest: the panel isn't installable (0062). + async rewrites() { + return [ + { + source: `${API_PROXY_PATH}/:path*`, + destination: `${adminApiInternalUrl()}/:path*`, + }, + ]; + }, + async headers() { + return [ + { source: '/:path*', headers: security }, + { source: '/fonts/:path*', headers: immutable }, + { source: '/icons/:path*', headers: immutable }, + ]; + }, + async redirects() { + return [{ source: '/', destination: '/health', permanent: false }]; + }, +}; + +// On next dev and next build, island's plugins write the fonts and icon sprite into public/ +// under their fixed names, with no hash (0012). +export default withIconSprite(withFontCopy(nextConfig)); diff --git a/apps/wall-street-plaza/package.json b/apps/wall-street-plaza/package.json new file mode 100644 index 0000000..73ffad2 --- /dev/null +++ b/apps/wall-street-plaza/package.json @@ -0,0 +1,43 @@ +{ + "name": "@lumina/wall-street-plaza", + "version": "0.0.1", + "private": true, + "nx": { + "name": "wall-street-plaza", + "sourceRoot": "apps/wall-street-plaza/src", + "tags": [ + "type:app", + "scope:admin" + ], + "targets": { + "build": { + "outputs": [ + "{projectRoot}/.next/!(cache)/**/*", + "{projectRoot}/.next/!(cache)", + "{projectRoot}/public/icons", + "{projectRoot}/public/fonts" + ] + }, + "dev": { + "options": { + "command": "next dev --port 7002" + } + }, + "start": { + "options": { + "command": "next start --port 7002" + } + } + } + }, + "dependencies": { + "@lumina/garden-roof": "workspace:*", + "@lumina/integrations": "workspace:*", + "@lumina/island": "workspace:*", + "@lumina/libs": "workspace:*", + "@lumina/tools": "workspace:*", + "next": "~16.3.8", + "react": "^19.0.0", + "react-dom": "^19.0.0" + } +} diff --git a/apps/wall-street-plaza/postcss.config.mjs b/apps/wall-street-plaza/postcss.config.mjs new file mode 100644 index 0000000..a34a3d5 --- /dev/null +++ b/apps/wall-street-plaza/postcss.config.mjs @@ -0,0 +1,5 @@ +export default { + plugins: { + '@tailwindcss/postcss': {}, + }, +}; diff --git a/apps/wall-street-plaza/public/favicon.ico b/apps/wall-street-plaza/public/favicon.ico new file mode 100644 index 0000000..317ebcb Binary files /dev/null and b/apps/wall-street-plaza/public/favicon.ico differ diff --git a/apps/wall-street-plaza/src/app/(auth)/error.tsx b/apps/wall-street-plaza/src/app/(auth)/error.tsx new file mode 100644 index 0000000..51346a4 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(auth)/error.tsx @@ -0,0 +1,24 @@ +'use client'; + +import { ErrorFallback } from '@lumina/garden-roof/app/error-boundaries'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; + +type GroupErrorProps = { + error: Error & { digest?: string }; + retry: () => void; +}; + +/** A failed login page: the state in the form column. */ +export default function GroupError({ error, retry }: GroupErrorProps) { + return ( + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(auth)/layout.tsx b/apps/wall-street-plaza/src/app/(auth)/layout.tsx new file mode 100644 index 0000000..84007c6 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(auth)/layout.tsx @@ -0,0 +1,9 @@ +import type { ReactNode } from 'react'; + +// Every request renders fresh: nothing in this group is prerendered or cached on the server. +export const dynamic = 'force-dynamic'; + +/** Adds nothing to the page; it holds the group's rendering mode. */ +export default function AuthLayout({ children }: { children: ReactNode }) { + return children; +} diff --git a/apps/wall-street-plaza/src/app/(auth)/login/loading.tsx b/apps/wall-street-plaza/src/app/(auth)/login/loading.tsx new file mode 100644 index 0000000..0a6e070 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(auth)/login/loading.tsx @@ -0,0 +1,26 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Card } from '@lumina/island/molecules/card'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import { i18n } from '../../../i18n'; + +/** The login frame before it arrives: the card in the form column. */ +export default function Loading() { + return ( + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(auth)/login/page.tsx b/apps/wall-street-plaza/src/app/(auth)/login/page.tsx new file mode 100644 index 0000000..3614d37 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(auth)/login/page.tsx @@ -0,0 +1,61 @@ +import { GuestGuard } from '@lumina/garden-roof/app/guards'; +import { Card } from '@lumina/island/molecules/card'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { i18n } from '../../../i18n'; +import { LoginTemplate } from './templates/login-template'; + +export const metadata: Metadata = { title: i18n.t('auth:login.title') }; + +/** + * ورود به پنل ادمین: the brand over the sign-in card in the form column. The form renders only in + * the browser, once the viewer is known to be a guest (0062, as 0013). + */ +export default function LoginPage() { + const skeleton = ( + + ); + + return ( + + + + + {i18n.t('app.brand')} + + + {i18n.t('app.panel')} + + + + + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/LoginTemplate.tsx b/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/LoginTemplate.tsx new file mode 100644 index 0000000..f95c790 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/LoginTemplate.tsx @@ -0,0 +1,131 @@ +'use client'; + +import { useLoginPage } from '@lumina/garden-roof/features/auth'; +import { + RETURN_TO_PARAM, + safeReturnPath, +} from '@lumina/garden-roof/app/navigation'; +import { + formatMobile, + 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 { OtpInput } from '@lumina/island/molecules/otp-input'; +import { TextInput } from '@lumina/island/molecules/text-input'; +import { clock } from '@lumina/tools/format'; +import { useRouter, useSearchParams } from 'next/navigation'; +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +/** Seconds left until `endsAt`, ticking once a second. */ +function useSecondsLeft(endsAt: number | null): number { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + if (endsAt === null) return; + const timer = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(timer); + }, [endsAt]); + return endsAt === null ? 0 : Math.max(0, Math.ceil((endsAt - now) / 1000)); +} + +/** + * The admin's sign-in (0061): the number, then the code, in one card. A signed-in admin goes on + * to the page they came for. + */ +export function LoginTemplate() { + const { t } = useTranslation('auth'); + const router = useRouter(); + const searchParams = useSearchParams(); + const model = useLoginPage({ + onSignedIn: () => + router.replace(safeReturnPath(searchParams.get(RETURN_TO_PARAM))), + }); + const secondsLeft = useSecondsLeft(model.resendEndsAt); + const { errors } = model.phoneForm.formState; + + return ( + + + + {model.step === 'phone' ? t('login.title') : t('login.code-title')} + + + {model.step === 'phone' + ? t('login.subtitle') + : t('login.code-subtitle', { phone: formatMobile(model.phone) })} + + + {model.step === 'phone' ? ( + { + event.preventDefault(); + model.submitPhone(); + }} + > + + + + ) : ( + + + + + + + + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/index.ts b/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/index.ts new file mode 100644 index 0000000..499ba85 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/index.ts @@ -0,0 +1,2 @@ +export { LoginTemplate } from './LoginTemplate'; +export type { LoginTemplateProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/types.ts b/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/types.ts new file mode 100644 index 0000000..7338682 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(auth)/login/templates/login-template/types.ts @@ -0,0 +1 @@ +export type LoginTemplateProps = Record; diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/loading.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/loading.tsx new file mode 100644 index 0000000..bdcf3d7 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/loading.tsx @@ -0,0 +1,14 @@ +import { i18n } from '../../../../i18n'; +import { DetailSkeleton } from './organisms/analyst-detail'; + +/** The analyst before they arrive: the way back over the skeleton. */ +export default function Loading() { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/AnalystDetail.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/AnalystDetail.tsx new file mode 100644 index 0000000..71732e8 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/AnalystDetail.tsx @@ -0,0 +1,80 @@ +'use client'; + +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { AuditLog } from '@lumina/garden-roof/app/screens'; +import { useAnalystDetailPage } from '@lumina/garden-roof/features/analysts'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { PageHeader } from '@lumina/island/molecules/page-header'; +import { Element } from '@lumina/island/primitives/element'; +import { useTranslation } from 'react-i18next'; + +import { + AccountActionButton, + AccountDialogs, +} from '../../../organisms/account-dialogs'; +import { AccountBadges } from './components/AccountBadges'; +import { AnalystFacts } from './components/AnalystFacts'; +import type { AnalystDetailProps } from './types'; + +/** + * One analyst (J11-4b): the name over @username with both states and the one account action in + * the header, the facts in the 432px column and «گزارش ممیزی» beside them. On a phone the states + * and the action sit under the title, full width. A suspension or reinstatement updates the page + * in place (J11-5d, J11-5f). + */ +export function AnalystDetail({ id }: AnalystDetailProps) { + const { t } = useTranslation('analysts'); + const { analyst, account } = useAnalystDetailPage(id); + + return ( + <> + + @{analyst.username} + + } + backHref={ROUTES.analysts} + backLabel={t('detail.back')} + actions={ + + + + + } + /> + + + + + + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/AccountBadges.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/AccountBadges.tsx new file mode 100644 index 0000000..ec54f5e --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/AccountBadges.tsx @@ -0,0 +1,22 @@ +'use client'; + +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { useTranslation } from 'react-i18next'; + +import type { AccountBadgesProps } from '../types'; + +/** Verification and account side by side: independent states (J11-4). */ +export function AccountBadges({ analyst }: AccountBadgesProps) { + const { t } = useTranslation(); + + return ( + <> + + {t(`status.verification.${analyst.verificationStatus}`)} + + + {t(`status.account.${analyst.accountStatus}`)} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/AnalystFacts.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/AnalystFacts.tsx new file mode 100644 index 0000000..5258005 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/AnalystFacts.tsx @@ -0,0 +1,42 @@ +'use client'; + +import { formatMobile } from '@lumina/garden-roof/shared/utils'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { AnalystFactsProps } from '../types'; + +/** Who the analyst is, both of their states and how many subscribe now (J11-4b). */ +export function AnalystFacts({ analyst }: AnalystFactsProps) { + const { t } = useTranslation(['analysts', 'common']); + + return ( + + + {analyst.fullName} + + + @{analyst.username} + + + {analyst.phone ? formatMobile(analyst.phone) : '—'} + + + + {t(`common:status.verification.${analyst.verificationStatus}`)} + + + + + {t(`common:status.account.${analyst.accountStatus}`)} + + + + {number(analyst.activeSubscriptions)} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/DetailSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/DetailSkeleton.tsx new file mode 100644 index 0000000..c7b354c --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/components/DetailSkeleton.tsx @@ -0,0 +1,33 @@ +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; +import { PageHeader } from '@lumina/island/molecules/page-header'; + +import type { DetailSkeletonProps } from '../types'; + +/** The analyst before they arrive: the way back, then the facts card and the audit card. */ +export function DetailSkeleton({ + label, + title, + backLabel, + delayed, +}: DetailSkeletonProps) { + return ( + <> + + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/index.ts b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/index.ts new file mode 100644 index 0000000..1651154 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/index.ts @@ -0,0 +1,3 @@ +export { AnalystDetail } from './AnalystDetail'; +export { DetailSkeleton } from './components/DetailSkeleton'; +export type { AnalystDetailProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/types.ts b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/types.ts new file mode 100644 index 0000000..565b258 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/organisms/analyst-detail/types.ts @@ -0,0 +1,15 @@ +import type { AnalystDetailPayload } from '@lumina/garden-roof/features/analysts'; + +export type AnalystDetailProps = { id: string }; + +export type AnalystFactsProps = { analyst: AnalystDetailPayload }; + +export type AccountBadgesProps = { analyst: AnalystDetailPayload }; + +export type DetailSkeletonProps = { + label: string; + /** The page's title until the analyst's name arrives. */ + title: string; + backLabel: string; + delayed?: boolean; +}; diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/page.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/page.tsx new file mode 100644 index 0000000..36111fa --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/[id]/page.tsx @@ -0,0 +1,41 @@ +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { AdminGuard } from '@lumina/garden-roof/app/guards'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { i18n } from '../../../../i18n'; +import { AnalystDetail, DetailSkeleton } from './organisms/analyst-detail'; + +export const metadata: Metadata = { + title: i18n.t('analysts:detail.meta-title'), +}; + +type AnalystPageProps = { params: Promise<{ id: string }> }; + +/** + * One analyst (J11-4b): the header carries the analyst's name, so the whole page renders in the + * browser once the admin is known (0062); until then, its way back over the skeleton. + */ +export default async function AnalystPage({ params }: AnalystPageProps) { + const { id } = await params; + const skeleton = ( + + ); + + return ( + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/loading.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/loading.tsx new file mode 100644 index 0000000..36da71d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/loading.tsx @@ -0,0 +1,14 @@ +import { PageHeader } from '@lumina/island/molecules/page-header'; + +import { i18n } from '../../../i18n'; +import { ListSkeleton } from './organisms/analysts-list'; + +/** The list before it arrives: its title over the table skeleton. */ +export default function Loading() { + return ( + <> + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/AccountDialogs.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/AccountDialogs.tsx new file mode 100644 index 0000000..5dfedad --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/AccountDialogs.tsx @@ -0,0 +1,109 @@ +'use client'; + +import { ReasonDialog } from '@lumina/garden-roof/app/screens'; +import { SUSPEND_TEMPLATES } from '@lumina/garden-roof/features/analysts'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { exactDuration, number } from '@lumina/tools/format'; +import { Trans, useTranslation } from 'react-i18next'; + +import { TargetLine } from './components/TargetLine'; +import type { AccountDialogsProps } from './types'; + +/** + * «تعلیق حساب تحلیلگر» (J11-5, J11-5b with a template) and «رفع تعلیق حساب» (J11-5e). Each says + * whom it touches: the active subscribers losing access, or the subscriptions extended and by how + * long. A suspension's reason reaches the analyst (never the subscribers); a reinstatement's stays + * in the audit log. Only a suspended channel extends; after an account-only suspension the analyst may still + * have subscribers, and the dialog says none of them is extended. Both stay mounted, so each keeps + * animating out and clears its text once it's gone. + */ +export function AccountDialogs({ account }: AccountDialogsProps) { + const { t } = useTranslation(['analysts', 'common']); + const { dialog } = account; + const target = dialog?.target; + const subscribers = target?.activeSubscriptions ?? 0; + const reinstate = dialog?.kind === 'reinstate' ? dialog : null; + const extendedCount = reinstate?.extendedCount ?? 0; + + return ( + <> + } + fieldLabel={t('suspend.field')} + placeholder={t('suspend.placeholder')} + hint={t('suspend.hint')} + templatesLabel={t('suspend.templates-label')} + templates={SUSPEND_TEMPLATES.map((id) => ({ + id, + label: t(`suspend.templates.${id}.label`), + text: t(`suspend.templates.${id}.text`), + }))} + emptyReason={t('suspend.empty')} + form={account.suspendForm} + onSubmit={account.confirmSuspend} + isSubmitting={account.isSuspending} + confirmLabel={t('suspend.confirm')} + > + {subscribers > 0 ? ( + + + ), + }} + /> + + ) : ( + + {t('suspend.impact-none')} + + )} + + } + fieldLabel={t('reinstate.field')} + placeholder={t('reinstate.placeholder')} + emptyReason={t('reinstate.empty')} + form={account.reinstateForm} + onSubmit={account.confirmReinstate} + isSubmitting={account.isReinstating} + confirmLabel={t('reinstate.confirm')} + confirmVariant="primary" + > + + {t('reinstate.description')} + + {extendedCount > 0 ? ( + + {t('reinstate.impact', { + subscriptions: number(extendedCount), + duration: exactDuration(reinstate?.extensionMinutes ?? 0), + })} + + ) : ( + + {subscribers > 0 + ? t('reinstate.impact-account-only') + : t('reinstate.impact-none')} + + )} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/components/AccountActionButton.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/components/AccountActionButton.tsx new file mode 100644 index 0000000..2a5133d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/components/AccountActionButton.tsx @@ -0,0 +1,44 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { useTranslation } from 'react-i18next'; + +import type { AccountActionButtonProps } from '../types'; + +/** + * The one account action an analyst has (J11-4): «تعلیق حساب» (danger) while فعال, «رفع تعلیق» + * (primary) while تعلیق‌شده, never both. Its accessible name says whose account. + */ +export function AccountActionButton({ + target, + account, + size = 'sm', + withIcon = false, + block, +}: AccountActionButtonProps) { + const { t } = useTranslation('analysts'); + + return target.accountStatus === 'suspended' ? ( + + ) : ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/components/TargetLine.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/components/TargetLine.tsx new file mode 100644 index 0000000..af1c0ac --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/components/TargetLine.tsx @@ -0,0 +1,17 @@ +import { Typography } from '@lumina/island/atoms/typography'; +import { Element } from '@lumina/island/primitives/element'; + +import type { TargetLineProps } from '../types'; + +/** Whom the dialog acts on, under its title: «علی محمدی · @ali_gold». */ +export function TargetLine({ target }: TargetLineProps) { + if (!target) return null; + return ( + + {target.fullName} ·{' '} + + @{target.username} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/index.ts b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/index.ts new file mode 100644 index 0000000..4adbee2 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/index.ts @@ -0,0 +1,3 @@ +export { AccountDialogs } from './AccountDialogs'; +export { AccountActionButton } from './components/AccountActionButton'; +export type { AccountActionButtonProps, AccountDialogsProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/types.ts b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/types.ts new file mode 100644 index 0000000..a62d728 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/account-dialogs/types.ts @@ -0,0 +1,18 @@ +import type { + AccountTarget, + AnalystAccountModel, +} from '@lumina/garden-roof/features/analysts'; +import type { ButtonProps } from '@lumina/island/atoms/button'; + +export type AccountDialogsProps = { account: AnalystAccountModel }; + +export type AccountActionButtonProps = { + target: AccountTarget; + account: AnalystAccountModel; + size?: ButtonProps['size']; + /** The detail header's `ban` / `check` before the label (J11-4b). */ + withIcon?: boolean; + block?: boolean; +}; + +export type TargetLineProps = { target: AccountTarget | undefined }; diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/AnalystsList.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/AnalystsList.tsx new file mode 100644 index 0000000..5c0e183 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/AnalystsList.tsx @@ -0,0 +1,47 @@ +'use client'; + +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { useAnalystsPage } from '@lumina/garden-roof/features/analysts'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SearchField } from '@lumina/island/molecules/search-field'; +import { Element } from '@lumina/island/primitives/element'; +import { Suspense } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { AccountDialogs } from '../account-dialogs'; +import { AnalystRows } from './components/AnalystRows'; +import { ListSkeleton } from './components/ListSkeleton'; + +/** + * مدیریت تحلیلگران (J11-4): the search, in the URL, over every analyst. A new search or page + * remounts the rows behind the table skeleton; a failed read errors in their place. The account + * dialogs sit outside the rows, so the rows can reload under them. + */ +export function AnalystsList() { + const { t } = useTranslation(['analysts', 'common']); + const model = useAnalystsPage(); + + return ( + + + + + + }> + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/components/AnalystRows.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/components/AnalystRows.tsx new file mode 100644 index 0000000..5d573b3 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/components/AnalystRows.tsx @@ -0,0 +1,222 @@ +'use client'; + +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { useAnalystListPart } from '@lumina/garden-roof/features/analysts'; +import { Avatar } from '@lumina/island/atoms/avatar'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { ListRow } from '@lumina/island/molecules/list-row'; +import { Pager } from '@lumina/island/molecules/pager'; +import { DataTable } from '@lumina/island/organisms/data-table'; +import { Element } from '@lumina/island/primitives/element'; +import { number } from '@lumina/tools/format'; +import { useRouter } from 'next/navigation'; +import { Trans, useTranslation } from 'react-i18next'; + +import { AccountActionButton } from '../../account-dialogs'; +import type { AnalystRowsProps } from '../types'; +import { AnalystsEmpty } from './AnalystsEmpty'; + +/** + * Every analyst for the search and page: a table from 1024px up (J11-4), a card per analyst on a + * phone (J11-4 M, 0063). A suspended account's row is tinted. The row opens the analyst; its one + * account action opens its dialog in place. + */ +export function AnalystRows({ args, account }: AnalystRowsProps) { + const { t } = useTranslation(['analysts', 'common']); + const router = useRouter(); + const part = useAnalystListPart(args); + + if (part.empty) { + return ( + router.replace(ROUTES.analysts)} + /> + ); + } + + return ( + + + + + + {t('list.columns.analyst')} + + + {t('list.columns.username')} + + + {t('list.columns.verification')} + + + {t('list.columns.account')} + + + {t('list.columns.subscribers')} + + + + + {part.rows.map((row) => ( + router.push(ROUTES.analyst(row.id))} + > + + + + + {row.fullName} + + + + + + @{row.username} + + + + + {t(`common:status.verification.${row.verificationStatus}`)} + + + + + {t(`common:status.account.${row.accountStatus}`)} + + + + {number(row.activeSubscriptions)} + + + + + + + ) : ( + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/components/ListSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/components/ListSkeleton.tsx new file mode 100644 index 0000000..85b2f2c --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/components/ListSkeleton.tsx @@ -0,0 +1,20 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +/** The list's rows before they arrive: the admin table preset (J11-4). */ +export function ListSkeleton({ + label, + delayed, +}: { + label: string; + delayed?: boolean; +}) { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/index.ts b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/index.ts new file mode 100644 index 0000000..9577cb3 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/index.ts @@ -0,0 +1,3 @@ +export { AnalystsList } from './AnalystsList'; +export { ListSkeleton } from './components/ListSkeleton'; +export type { AnalystsListProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/types.ts b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/types.ts new file mode 100644 index 0000000..b4dadfa --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/organisms/analysts-list/types.ts @@ -0,0 +1,16 @@ +import type { + AnalystAccountModel, + ListAnalystsArgs, +} from '@lumina/garden-roof/features/analysts'; + +export type AnalystsListProps = Record; + +export type AnalystRowsProps = { + args: ListAnalystsArgs; + account: AnalystAccountModel; +}; + +export type AnalystsEmptyProps = { + kind: 'list' | 'search'; + onClearSearch: () => void; +}; diff --git a/apps/wall-street-plaza/src/app/(panel)/analysts/page.tsx b/apps/wall-street-plaza/src/app/(panel)/analysts/page.tsx new file mode 100644 index 0000000..0983f62 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/analysts/page.tsx @@ -0,0 +1,28 @@ +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 { AnalystsList, ListSkeleton } from './organisms/analysts-list'; + +export const metadata: Metadata = { title: i18n.t('analysts:list.meta-title') }; + +/** + * مدیریت تحلیلگران (J11-4): the title on the server; every analyst in the browser once the admin + * is known (0062). + */ +export default function AnalystsPage() { + const skeleton = ; + + return ( + <> + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/error.tsx b/apps/wall-street-plaza/src/app/(panel)/error.tsx new file mode 100644 index 0000000..3fed3ec --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/error.tsx @@ -0,0 +1,15 @@ +'use client'; + +import { ErrorFallback } from '@lumina/garden-roof/app/error-boundaries'; + +type GroupErrorProps = { + error: Error & { digest?: string }; + retry: () => void; +}; + +/** A failed panel page: the state in the page's column; the layout keeps the sidebar. */ +export default function GroupError({ error, retry }: GroupErrorProps) { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/loading.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/loading.tsx new file mode 100644 index 0000000..7080227 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/loading.tsx @@ -0,0 +1,17 @@ +import { PageHeader } from '@lumina/island/molecules/page-header'; + +import { i18n } from '../../../i18n'; +import { FeaturedSkeleton } from './organisms/featured-list'; + +/** The list before it arrives: its title and subtitle over the skeleton. */ +export default function Loading() { + return ( + <> + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/FeaturedList.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/FeaturedList.tsx new file mode 100644 index 0000000..d41187d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/FeaturedList.tsx @@ -0,0 +1,55 @@ +'use client'; + +import { AuditLog } from '@lumina/garden-roof/app/screens'; +import { useFeaturedPage } from '@lumina/garden-roof/features/featured'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import { AddFeaturedButton } from './components/AddFeaturedButton'; +import { AddFeaturedDialog } from './components/AddFeaturedDialog'; +import { FeaturedPreview } from './components/FeaturedPreview'; +import { FeaturedTable } from './components/FeaturedTable'; +import { FewerBanner } from './components/FewerBanner'; +import { PageVisibility } from './components/PageVisibility'; +import { RemoveFeaturedDialog } from './components/RemoveFeaturedDialog'; + +/** + * تحلیلگران منتخب (J11-10): with fewer than three visible, the warning first (J11-10e); the list in + * the admin's order, reordered by drag, keyboard or the row menu and saved on drop (J11-10b, + * J11-10g); where the analysts show while fewer than three are visible; the preview of the first + * cards; and «گزارش ممیزی», folded. The add and remove dialogs (J11-10c, J11-10d) sit over it. + */ +export function FeaturedList() { + const { t } = useTranslation('featured'); + const model = useFeaturedPage(); + const { featured } = model; + + return ( + + + {model.rows.length === 0 ? ( + + + + + + ) : ( + + )} + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/AddFeaturedButton.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/AddFeaturedButton.tsx new file mode 100644 index 0000000..85270dd --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/AddFeaturedButton.tsx @@ -0,0 +1,22 @@ +'use client'; + +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { FEATURED_PARAMS } from '@lumina/garden-roof/features/featured'; +import { Button } from '@lumina/island/atoms/button'; + +/** + * «افزودن تحلیلگر» in the page header (J11-10): it opens «افزودن تحلیلگر منتخب» through `?add=1`, + * so the server renders the header and a reload keeps the dialog open. + */ +export function AddFeaturedButton({ label }: { label: string }) { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/AddFeaturedDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/AddFeaturedDialog.tsx new file mode 100644 index 0000000..6e90b96 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/AddFeaturedDialog.tsx @@ -0,0 +1,98 @@ +'use client'; + +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { useAddFeaturedDialog } from '@lumina/garden-roof/features/featured'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Modal } from '@lumina/island/molecules/modal'; +import { SearchField } from '@lumina/island/molecules/search-field'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; +import { number } from '@lumina/tools/format'; +import { Suspense } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { AddFeaturedDialogProps } from '../types'; +import { CandidateOptions } from './CandidateOptions'; + +/** + * «افزودن تحلیلگر منتخب» (J11-10c): the search, then what it finds behind its own skeleton and + * error, the note that new analysts join the end, and «افزودن به منتخب (n)», which waits for a pick. + * Picks survive a new search; the dialog forgets them once closed. + */ +export function AddFeaturedDialog({ + open, + featured, + onClose, +}: AddFeaturedDialogProps) { + const { t } = useTranslation(['featured', 'common']); + const model = useAddFeaturedDialog({ featured, onClose }); + const count = model.picked.length; + + return ( + + + + + } + > + + + + + } + > + + + + + {t('add.note')} + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/CandidateOptions.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/CandidateOptions.tsx new file mode 100644 index 0000000..a9e1e1a --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/CandidateOptions.tsx @@ -0,0 +1,104 @@ +'use client'; + +import { useFeaturedCandidatesPart } from '@lumina/garden-roof/features/featured'; +import type { FeaturedCandidatePayload } from '@lumina/garden-roof/features/featured'; +import { Avatar } from '@lumina/island/atoms/avatar'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Tag } from '@lumina/island/atoms/tag'; +import { ChoiceCard } from '@lumina/island/molecules/choice-card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { List, ListRow } from '@lumina/island/molecules/list-row'; +import { Element } from '@lumina/island/primitives/element'; +import { useTranslation } from 'react-i18next'; + +import type { CandidateOptionsProps } from '../types'; + +/** + * What a search finds (J11-10c): each eligible analyst a checkbox card, «@user · بازار»; under them + * the ones who can't be added yet, dimmed, each with the first check they fail. + */ +export function CandidateOptions({ + query, + isPicked, + onToggle, +}: CandidateOptionsProps) { + const { t } = useTranslation(['featured', 'common']); + const part = useFeaturedCandidatesPart(query); + + if (part.isEmpty) { + return ( + + ); + } + + const handle = (candidate: FeaturedCandidatePayload) => ( + + @{candidate.username} + + ); + + return ( + + {part.eligible.length > 0 && ( + + {part.eligible.map((candidate) => ( + onToggle(candidate)} + title={candidate.fullName} + description={ + <> + {handle(candidate)} ·{' '} + {candidate.markets + .map((market) => t(`common:markets.${market}`)) + .join('، ')} + + } + /> + ))} + + )} + {part.ineligible.length > 0 && ( + + {part.ineligible.map((candidate) => ( + + } + title={candidate.fullName} + subtitle={handle(candidate)} + end={ + candidate.ineligibleReason && ( + + {t(`add.reasons.${candidate.ineligibleReason}`)} + + ) + } + /> + ))} + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedPreview.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedPreview.tsx new file mode 100644 index 0000000..0b65387 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedPreview.tsx @@ -0,0 +1,100 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Tag } from '@lumina/island/atoms/tag'; +import { Typography } from '@lumina/island/atoms/typography'; +import { AnalystCard } from '@lumina/island/organisms/analyst-card'; +import type { AnalystCardLabels } from '@lumina/island/organisms/analyst-card'; +import { number } from '@lumina/tools/format'; +import { useId } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { FeaturedPartProps } from '../types'; + +/** + * «پیش‌نمایش» (J11-10): the first three visible cards in the saved order, as the public card draws + * them, so a drag shows here only once it's dropped. Hidden analysts are skipped (J11-10f); with + * fewer than three visible the landing has none, so the title names only خانه and «تحلیلگران + * منتخب» (J11-10e). + */ +export function FeaturedPreview({ model }: FeaturedPartProps) { + const { t } = useTranslation(['featured', 'common']); + const titleId = useId(); + const { featured, preview } = model; + if (preview.length === 0) return null; + + const labels: AnalystCardLabels = { + verified: t('card.verified'), + markets: t('card.markets'), + winRate: t('card.win-rate'), + predictions: t('card.predictions'), + avgRoi: t('card.avg-roi'), + noRecord: t('card.no-record'), + followers: (followers) => t('card.followers', { followers }), + view: t('card.view'), + }; + const shown = number(preview.length); + const caption = !featured.landingVisible + ? t('preview.visible', { total: number(featured.visibleCount) }) + : featured.visibleCount < featured.items.length + ? t('preview.first-visible', { + shown, + total: number(featured.visibleCount), + }) + : t('preview.first', { shown, total: number(featured.items.length) }); + + return ( + + + + + {featured.landingVisible + ? t('preview.landing-title') + : t('preview.home-title')} + + + {t('preview.tag')} + + + + {caption} + + + + {preview.map((analyst) => ( + + t(`common:markets.${market}`), + ), + bio: analyst.bio, + followers: analyst.followers, + stats: analyst.stats, + }} + labels={labels} + /> + ))} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedRow.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedRow.tsx new file mode 100644 index 0000000..c376ba8 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedRow.tsx @@ -0,0 +1,139 @@ +'use client'; + +import { Avatar } from '@lumina/island/atoms/avatar'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { Tag } from '@lumina/island/atoms/tag'; +import { Typography } from '@lumina/island/atoms/typography'; +import { PersonSummary } from '@lumina/island/molecules/person-summary'; +import { DataTable } from '@lumina/island/organisms/data-table'; +import { cn } from '@lumina/island/tools/cn'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { FeaturedRowProps } from '../types'; +import { RowMenu } from './RowMenu'; + +/** + * One analyst at their place (J11-10): the grip, the admin-only number, who, markets, public track + * record, account status, «حذف از منتخب» and «بیشتر». The moving row sits on the sunken ground and + * says where it is (J11-10b); a hidden one (suspended) is dimmed and says why (J11-10f). + */ +export function FeaturedRow({ + row, + total, + grip, + onRemove, + onMoveUp, + onMoveDown, +}: FeaturedRowProps) { + const { t } = useTranslation(['featured', 'common']); + + return ( + td]:bg-surface-sunken')} + > + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedSkeleton.tsx new file mode 100644 index 0000000..2b25f2c --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedSkeleton.tsx @@ -0,0 +1,26 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Skeleton } from '@lumina/island/atoms/skeleton'; +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import type { FeaturedSkeletonProps } from '../types'; + +/** The list before it arrives: the table preset over the preview's three cards (J11-10). */ +export function FeaturedSkeleton({ label, delayed }: FeaturedSkeletonProps) { + return ( + + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedTable.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedTable.tsx new file mode 100644 index 0000000..33c483b --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FeaturedTable.tsx @@ -0,0 +1,97 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { DataTable } from '@lumina/island/organisms/data-table'; +import { Element } from '@lumina/island/primitives/element'; +import { cn } from '@lumina/island/tools/cn'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { FeaturedPartProps } from '../types'; +import { FeaturedRow } from './FeaturedRow'; + +/** + * The list in the admin's order (J11-10), reordered in place (J11-10b, J11-10g). It scrolls + * sideways while the column is narrower than its seven columns (below 1280px); from there its + * overflow stays visible, so a row's menu isn't clipped, and the corners are rounded on the cells. Under it, the live caption that follows a moving row, and the note + * on hidden (suspended) analysts (J11-10f). + */ +export function FeaturedTable({ model }: FeaturedPartProps) { + const { t } = useTranslation('featured'); + const { reorder, rows } = model; + const { announcement } = reorder; + + return ( + + + tr:last-child>td:first-child]:rounded-es-lg [&_tbody>tr:last-child>td:last-child]:rounded-ee-lg [&_thead_th:first-child]:rounded-ss-lg [&_thead_th:last-child]:rounded-se-lg', + reorder.isDragging && 'cursor-grabbing select-none', + )} + > + + + {t('table.columns.move')} + + + {t('table.columns.position')} + + + {t('table.columns.analyst')} + + + {t('table.columns.markets')} + + + {t('table.columns.track-record')} + + + {t('table.columns.status')} + + + {t('table.columns.actions')} + + + + {rows.map((row) => ( + model.openRemove(row.id)} + onMoveUp={() => model.moveUp(row.id)} + onMoveDown={() => model.moveDown(row.id)} + /> + ))} + + + + + {announcement && + t(`reorder.${announcement.kind}`, { + name: announcement.name, + position: number(announcement.position), + total: number(announcement.total), + })} + + {model.hasSuspended && ( + + {t('table.hidden-note')} + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FewerBanner.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FewerBanner.tsx new file mode 100644 index 0000000..d02d260 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/FewerBanner.tsx @@ -0,0 +1,30 @@ +'use client'; + +import { LANDING_MIN_VISIBLE } from '@lumina/garden-roof/features/featured'; +import { Banner } from '@lumina/island/molecules/banner'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { FeaturedListPartProps } from '../types'; + +/** + * «کمتر از ۳ تحلیلگر منتخب» (J11-10e): the landing hides its analysts section; خانه and «تحلیلگران + * منتخب» show the visible ones, and the banner says how many more bring the section back. + */ +export function FewerBanner({ featured }: FeaturedListPartProps) { + const { t } = useTranslation('featured'); + if (featured.landingVisible) return null; + const visible = featured.visibleCount; + const needed = LANDING_MIN_VISIBLE - visible; + + return ( + + {visible === 0 + ? t('fewer.shown-none') + : t('fewer.shown', { total: number(visible) })}{' '} + {needed === 1 + ? t('fewer.needed-one') + : t('fewer.needed', { total: number(needed) })} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/PageVisibility.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/PageVisibility.tsx new file mode 100644 index 0000000..4ccdf40 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/PageVisibility.tsx @@ -0,0 +1,61 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { StatTile } from '@lumina/island/molecules/stat-tile'; +import { Element } from '@lumina/island/primitives/element'; +import { number } from '@lumina/tools/format'; +import { useId } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { FeaturedListPartProps } from '../types'; + +/** + * «نمایش در صفحه‌ها» (J11-10e), while fewer than three analysts are visible: the landing hides its + * section, خانه and «تحلیلگران منتخب» show what's left. + */ +export function PageVisibility({ featured }: FeaturedListPartProps) { + const { t } = useTranslation('featured'); + const titleId = useId(); + if (featured.landingVisible) return null; + const cards = t('pages.cards', { total: number(featured.visibleCount) }); + + return ( + + + {t('pages.title')} + + + + + + {t('pages.analysts-path')} + + } + /> + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/RemoveFeaturedDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/RemoveFeaturedDialog.tsx new file mode 100644 index 0000000..2850b8d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/RemoveFeaturedDialog.tsx @@ -0,0 +1,49 @@ +'use client'; + +import { ReasonDialog } from '@lumina/garden-roof/app/screens'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { Element } from '@lumina/island/primitives/element'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { FeaturedPartProps } from '../types'; + +/** + * «حذف از تحلیلگران منتخب» (J11-10d): who and at which place, what changes for them (nothing but + * the slider), and «دلیل» for «گزارش ممیزی». + */ +export function RemoveFeaturedDialog({ model }: FeaturedPartProps) { + const { t } = useTranslation('featured'); + const row = model.removing; + + return ( + + {row.fullName} ·{' '} + + @{row.username} + {' '} + · {t('remove.position', { position: number(row.position) })} + + ) + } + emptyReason={t('remove.empty')} + form={model.removeForm} + onSubmit={model.confirmRemove} + isSubmitting={model.isRemoving} + confirmLabel={t('remove.confirm')} + > + {row && ( + + {t('remove.impact', { name: row.fullName })} + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/RowMenu.tsx b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/RowMenu.tsx new file mode 100644 index 0000000..c1e9b93 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/featured/organisms/featured-list/components/RowMenu.tsx @@ -0,0 +1,66 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { ActionMenu } from '@lumina/island/molecules/action-menu'; +import type { ActionMenuItem } from '@lumina/island/molecules/action-menu'; +import { Element } from '@lumina/island/primitives/element'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { RowMenuProps } from '../types'; + +/** + * «بیشتر» on a row (J11-10g): «انتقال به بالا» and «انتقال به پایین», one place each, saved at once + * like a drop. The first row has no «بالا», the last no «پایین»; a lone row has no menu. + */ +export function RowMenu({ + name, + canMoveUp, + canMoveDown, + onMoveUp, + onMoveDown, +}: RowMenuProps) { + const { t } = useTranslation('featured'); + const [isOpen, setIsOpen] = useState(false); + const items: ActionMenuItem[] = [ + ...(canMoveUp + ? [ + { + label: t('table.move-up'), + icon: 'arrow-up' as const, + onSelect: onMoveUp, + }, + ] + : []), + ...(canMoveDown + ? [ + { + label: t('table.move-down'), + icon: 'arrow-down' as const, + onSelect: onMoveDown, + }, + ] + : []), + ]; + if (items.length === 0) return null; + + return ( + + + + + } + > + {dialog && ( + { + event.preventDefault(); + actions.submitCapacity(); + }} + > + + + {dialog.code.analyst.fullName} ·{' '} + + @{dialog.code.analyst.username} + + + + + {dialog.code.code} + + + + {dialog.code.status === 'full' && ( + + )} + {t('usage', { + used: number(dialog.code.usedCount), + max: number(dialog.code.maxUses), + })} + + + + {dialog.code.waitlistCount > 0 + ? t('people', { value: number(dialog.code.waitlistCount) }) + : t('none')} + + {dialog.request && ( + + {t('capacity.request-value', { + people: t('people', { + value: number(dialog.request.requestedMaxUses), + }), + date: date(dialog.request.createdAt, { time: false }), + })} + + )} + + + + {capacityNotice && ( + + {capacityNotice === 'notify' + ? t('capacity.notify', { + people: t('people', { + value: number(dialog.code.waitlistCount), + }), + }) + : t('capacity.held')} + + )} + + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDetail.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDetail.tsx new file mode 100644 index 0000000..c8a7f23 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDetail.tsx @@ -0,0 +1,120 @@ +'use client'; + +import { AuditLog } from '@lumina/garden-roof/app/screens'; +import { useInviteCodeDetailPart } from '@lumina/garden-roof/features/invite-codes'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { Element } from '@lumina/island/primitives/element'; +import { date, number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { CodeDetailProps } from '../types'; +import { CodeStatusBadge } from './CodeStatusBadge'; + +/** + * One code (J11-6g): the code with «کپی کد» and its status, who it belongs to, its seats, the + * list and its last SMS, when it was made and the link the analyst shares; then «گزارش ممیزی» and + * the code's actions. The dialogs open over the panel, which shows the change once it's made. + */ +export function CodeDetail({ id, actions }: CodeDetailProps) { + const { t } = useTranslation(['codes', 'common']); + const { code, copyCode } = useInviteCodeDetailPart(id); + const waitlist = + code.waitlistCount > 0 + ? t('people', { value: number(code.waitlistCount) }) + : t('none'); + + return ( + + + + + + {code.code} + + + + ) : ( + <> + + + + )} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDetailSheet.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDetailSheet.tsx new file mode 100644 index 0000000..1acb945 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDetailSheet.tsx @@ -0,0 +1,52 @@ +'use client'; + +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { Suspense } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { CodeDetailSheetProps } from '../types'; +import { CodeDetail } from './CodeDetail'; + +/** + * «جزئیات کد دعوت» (J11-6g): a side panel over the list while the URL has `?code=`; ✕, Escape or + * the scrim close it. The code loads inside, behind its skeleton; a failed read errors there. + */ +export function CodeDetailSheet({ model }: CodeDetailSheetProps) { + const { t } = useTranslation(['codes', 'common']); + const { codeId, isOpen } = model.detail; + + return ( + + {codeId && ( + + + + + + + + + } + > + + + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDialogs.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDialogs.tsx new file mode 100644 index 0000000..5f76685 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeDialogs.tsx @@ -0,0 +1,15 @@ +'use client'; + +import type { CodeDialogsProps } from '../types'; +import { CapacityDialog } from './CapacityDialog'; +import { CodeReasonDialog } from './CodeReasonDialog'; + +/** Every dialog of the section, driven by the page's actions model; one shows at a time. */ +export function CodeDialogs({ actions }: CodeDialogsProps) { + return ( + <> + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeReasonDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeReasonDialog.tsx new file mode 100644 index 0000000..9a95759 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeReasonDialog.tsx @@ -0,0 +1,113 @@ +'use client'; + +import { ReasonDialog } from '@lumina/garden-roof/app/screens'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Banner } from '@lumina/island/molecules/banner'; +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { Element } from '@lumina/island/primitives/element'; +import { iso, number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { CodeDialogsProps } from '../types'; + +/** + * The «دلیل» dialogs (J11-6e, 6f): rejecting a request shows its seats, ask and note; deactivating + * says what checkout and shared links do from now on; activating says the code works again. The + * analyst sees a rejection's or a deactivation's reason on their card; an activation's stays in the + * audit log. + */ +export function CodeReasonDialog({ actions }: CodeDialogsProps) { + const { t } = useTranslation(['codes', 'common']); + const { dialog } = actions; + if (!dialog || dialog.kind === 'capacity') return null; + + const code = dialog.kind === 'reject' ? dialog.request.code : dialog.code; + const who = ( + + {code.analyst.fullName} ·{' '} + + @{code.analyst.username} + {' '} + ·{' '} + + {code.code} + + + ); + + const shared = { + open: actions.isOpen, + onClose: actions.close, + description: who, + form: actions.reasonForm, + onSubmit: actions.confirmReason, + isSubmitting: actions.isSubmitting, + }; + + if (dialog.kind === 'reject') { + const { request } = dialog; + return ( + + + + {t('usage', { + used: number(code.usedCount), + max: number(code.maxUses), + })} + + + {t('people', { value: number(request.requestedMaxUses) })} + + + {request.note ?? t('none')} + + + + ); + } + + if (dialog.kind === 'deactivate') { + return ( + + + {t('deactivate.notice', { code: iso(code.code) })} + + + ); + } + + return ( + + + + {t('activate.notice', { code: iso(code.code) })} + + {code.analyst.isSuspended && ( + + {t('activate.suspended')} + + )} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeRows.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeRows.tsx new file mode 100644 index 0000000..ee6f9a0 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeRows.tsx @@ -0,0 +1,181 @@ +'use client'; + +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { useInviteCodeListPart } from '@lumina/garden-roof/features/invite-codes'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Link } from '@lumina/island/atoms/link'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Meter } from '@lumina/island/molecules/meter'; +import { PersonSummary } from '@lumina/island/molecules/person-summary'; +import { DataTable } from '@lumina/island/organisms/data-table'; +import { Element } from '@lumina/island/primitives/element'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { CodeRowsProps } from '../types'; +import { CodeStatusBadge } from './CodeStatusBadge'; +import { ListEmpty } from './ListEmpty'; +import { ListPager } from './ListPager'; + +/** + * «همه کدها» (J11-6): one row per analyst's code, most used first, its capacity as a meter that + * turns warning near full. The whole row (or its code) opens the details beside the table; a + * pending request links to its tab. Desktop only: on a phone the table scrolls sideways. + */ +export function CodeRows({ model }: CodeRowsProps) { + const { t } = useTranslation(['codes', 'common']); + const part = useInviteCodeListPart(model.args); + const { actions } = model; + + if (part.empty) + return ; + + return ( + + + + + + {t('list.columns.analyst')} + + + {t('list.columns.code')} + + + {t('list.columns.usage')} + + + {t('list.columns.waitlist')} + + + {t('list.columns.status')} + + + {t('list.columns.actions')} + + + + {part.rows.map((row) => { + const usage = t('usage', { + used: number(row.usedCount), + max: number(row.maxUses), + }); + return ( + model.openCode(row.id)} + selected={ + model.detail.isOpen && model.detail.codeId === row.id + } + > + + + + + + + {row.code} + + + + + + + + {row.waitlistCount > 0 + ? t('people', { value: number(row.waitlistCount) }) + : t('none')} + + + + + {row.pendingRequest && ( + + + {t('list.request', { + people: t('people', { + value: number( + row.pendingRequest.requestedMaxUses, + ), + }), + })} + + + )} + + + + + {row.status === 'inactive' ? ( + + ) : ( + <> + + + + )} + + + + ); + })} + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeStatusBadge.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeStatusBadge.tsx new file mode 100644 index 0000000..3c7ce2d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/CodeStatusBadge.tsx @@ -0,0 +1,31 @@ +'use client'; + +import type { InviteCodeStatus } from '@lumina/garden-roof/features/invite-codes'; +import type { IconName } from '@lumina/island/atoms/icon'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import type { StatusTone } from '@lumina/island/atoms/status-badge'; +import { useTranslation } from 'react-i18next'; + +import type { CodeStatusBadgeProps } from '../types'; + +/** Each code status always reads with the same tone and icon (J11-6). */ +const STATUS_STYLES: Record< + InviteCodeStatus, + { tone: StatusTone; icon: IconName } +> = { + active: { tone: 'success', icon: 'check' }, + full: { tone: 'warning', icon: 'users' }, + inactive: { tone: 'neutral', icon: 'ban' }, +}; + +/** «فعال» · «ظرفیت تکمیل» · «غیرفعال». */ +export function CodeStatusBadge({ status }: CodeStatusBadgeProps) { + const { t } = useTranslation('codes'); + const style = STATUS_STYLES[status]; + + return ( + + {t(`status.${status}`)} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/ListEmpty.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/ListEmpty.tsx new file mode 100644 index 0000000..b6e5a2b --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/ListEmpty.tsx @@ -0,0 +1,45 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import type { ListEmptyProps } from '../types'; + +/** No row: no code yet, no pending request (all decided), or nothing matched the search. */ +export function ListEmpty({ kind, onClearSearch }: ListEmptyProps) { + const { t } = useTranslation('codes'); + + if (kind === 'search') { + return ( + + + + + + ); + } + return ( + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/ListPager.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/ListPager.tsx new file mode 100644 index 0000000..b05dc9c --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/ListPager.tsx @@ -0,0 +1,41 @@ +'use client'; + +import { Pager } from '@lumina/island/molecules/pager'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { ListPagerProps } from '../types'; + +/** «نمایش ۱ تا ۸ از ۸ · ترتیب: …» with the page links under a tab's table. */ +export function ListPager({ + page, + pageCount, + from, + to, + total, + hrefFor, + summaryKey, +}: ListPagerProps) { + const { t } = useTranslation(['codes', 'common']); + + return ( + t('common:pager.page', { page: number(value) }), + }} + /> + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/RequestRows.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/RequestRows.tsx new file mode 100644 index 0000000..b9af01a --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/RequestRows.tsx @@ -0,0 +1,141 @@ +'use client'; + +import { useCapacityRequestListPart } from '@lumina/garden-roof/features/invite-codes'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { PersonSummary } from '@lumina/island/molecules/person-summary'; +import { DataTable } from '@lumina/island/organisms/data-table'; +import { Element } from '@lumina/island/primitives/element'; +import { date, number, time } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { RequestRowsProps } from '../types'; +import { ListEmpty } from './ListEmpty'; +import { ListPager } from './ListPager'; + +/** + * «درخواست‌های افزایش» (J11-6d): pending requests, oldest first, with the code's seats, the + * analyst's note and when they asked. «تأیید» opens «تغییر ظرفیت» pre-filled; «رد» asks the reason. + */ +export function RequestRows({ model }: RequestRowsProps) { + const { t } = useTranslation(['codes', 'common']); + const part = useCapacityRequestListPart(model.args); + const { actions } = model; + + if (part.empty) + return ; + + return ( + + + + + + {t('requests.columns.analyst')} + + + {t('requests.columns.current')} + + + {t('requests.columns.requested')} + + + {t('requests.columns.waitlist')} + + + {t('requests.columns.note')} + + + {t('requests.columns.date')} + + + {t('requests.columns.actions')} + + + + {part.rows.map((row) => ( + + + + + + {t('usage', { + used: number(row.code.usedCount), + max: number(row.code.maxUses), + })} + + + {t('people', { value: number(row.requestedMaxUses) })} + + + {row.code.waitlistCount > 0 + ? t('people', { value: number(row.code.waitlistCount) }) + : t('none')} + + + + {row.note ?? t('none')} + + + + + + {date(row.createdAt, { time: false })} + + + {time(row.createdAt)} + + + + + + + + + + + ))} + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/TableSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/TableSkeleton.tsx new file mode 100644 index 0000000..f7d4f2d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/components/TableSkeleton.tsx @@ -0,0 +1,16 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import type { TableSkeletonProps } from '../types'; + +/** A tab's rows before they arrive: the admin table preset with the tab's columns. */ +export function TableSkeleton({ columns, label, delayed }: TableSkeletonProps) { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/index.ts b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/index.ts new file mode 100644 index 0000000..ce35804 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/index.ts @@ -0,0 +1,8 @@ +export { CapacityRequests } from './CapacityRequests'; +export { TableSkeleton } from './components/TableSkeleton'; +export { InviteCodes } from './InviteCodes'; +export type { + CapacityRequestsProps, + InviteCodesProps, + TableSkeletonProps, +} from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/types.ts b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/types.ts new file mode 100644 index 0000000..98c309c --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/organisms/invite-codes/types.ts @@ -0,0 +1,45 @@ +import type { + CapacityRequestsPageModel, + CodeActionsModel, + InviteCodeStatus, + InviteCodesPageModel, +} from '@lumina/garden-roof/features/invite-codes'; + +export type InviteCodesProps = Record; + +export type CapacityRequestsProps = Record; + +export type TableSkeletonProps = { + columns: number; + label: string; + delayed?: boolean; +}; + +export type ListEmptyProps = { + /** No code yet, no pending request, or nothing matched the search. */ + kind: 'codes' | 'requests' | 'search'; + onClearSearch: () => void; +}; + +export type CodeStatusBadgeProps = { status: InviteCodeStatus }; + +export type CodeRowsProps = { model: InviteCodesPageModel }; + +export type RequestRowsProps = { model: CapacityRequestsPageModel }; + +export type CodeDetailSheetProps = { model: InviteCodesPageModel }; + +export type CodeDetailProps = { id: string; actions: CodeActionsModel }; + +export type CodeDialogsProps = { actions: CodeActionsModel }; + +export type ListPagerProps = { + page: number; + pageCount: number; + from: number; + to: number; + total: number; + hrefFor: (page: number) => string; + /** The order after the range: «ترتیب: بیشترین استفاده». */ + summaryKey: 'list.summary' | 'requests.summary'; +}; diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/page.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/page.tsx new file mode 100644 index 0000000..b429f30 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/page.tsx @@ -0,0 +1,23 @@ +import { AdminGuard } from '@lumina/garden-roof/app/guards'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { i18n } from '../../../i18n'; +import { InviteCodes, TableSkeleton } from './organisms/invite-codes'; + +export const metadata: Metadata = { title: i18n.t('codes:list.meta-title') }; + +/** «همه کدها» (J11-6): the codes in the browser once the admin is known (0062). */ +export default function InviteCodesPage() { + const skeleton = ( + + ); + + return ( + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/requests/loading.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/requests/loading.tsx new file mode 100644 index 0000000..1c82bfb --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/requests/loading.tsx @@ -0,0 +1,13 @@ +import { i18n } from '../../../../i18n'; +import { TableSkeleton } from '../organisms/invite-codes'; + +/** The requests before they arrive, under the section's header and tabs. */ +export default function Loading() { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/invite-codes/requests/page.tsx b/apps/wall-street-plaza/src/app/(panel)/invite-codes/requests/page.tsx new file mode 100644 index 0000000..fa67a91 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/invite-codes/requests/page.tsx @@ -0,0 +1,25 @@ +import { AdminGuard } from '@lumina/garden-roof/app/guards'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { i18n } from '../../../../i18n'; +import { CapacityRequests, TableSkeleton } from '../organisms/invite-codes'; + +export const metadata: Metadata = { + title: i18n.t('codes:requests.meta-title'), +}; + +/** «درخواست‌های افزایش» (J11-6d): the pending requests in the browser once the admin is known (0062). */ +export default function CapacityRequestsPage() { + const skeleton = ( + + ); + + return ( + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/layout.tsx b/apps/wall-street-plaza/src/app/(panel)/layout.tsx new file mode 100644 index 0000000..8a37dc9 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/layout.tsx @@ -0,0 +1,30 @@ +import { AdminSidebar, AdminTopBar } from '@lumina/garden-roof/app/navigation'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import type { ReactNode } from 'react'; + +// Every request renders fresh: nothing in the panel is prerendered or cached on the server. +export const dynamic = 'force-dynamic'; + +/** + * The panel's frame (DS AppShell role=admin): the sidebar at the inline start from 1024px up, the + * phone's top bar below it (0063), and each page's column (DS `lm-amain`: 32px 40px, 24px gaps). + * Each page guards itself with its own skeleton (0062). + */ +export default function PanelLayout({ children }: { children: ReactNode }) { + return ( + + + + + + {children} + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/loading.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/loading.tsx new file mode 100644 index 0000000..c62f43c --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/loading.tsx @@ -0,0 +1,17 @@ +import { PageHeader } from '@lumina/island/molecules/page-header'; + +import { i18n } from '../../../i18n'; +import { PayoutsSkeleton } from './organisms/payouts-board'; + +/** The payouts before they arrive: the title and the weekly rule over the table skeleton. */ +export default function Loading() { + return ( + <> + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/PayoutsBoard.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/PayoutsBoard.tsx new file mode 100644 index 0000000..5f82c35 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/PayoutsBoard.tsx @@ -0,0 +1,76 @@ +'use client'; + +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { + PAYOUT_TABS, + usePayoutsPage, +} from '@lumina/garden-roof/features/payouts'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { TabLinks } from '@lumina/island/molecules/tab-links'; +import { Suspense } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { CancelPayoutDialog } from './components/CancelPayoutDialog'; +import { CreatePayoutDialog } from './components/CreatePayoutDialog'; +import { MarkPaidDialog } from './components/MarkPaidDialog'; +import { PayoutDetailSheet } from './components/PayoutDetailSheet'; +import { PayoutRows } from './components/PayoutRows'; +import { PayoutsSkeleton } from './components/PayoutsSkeleton'; +import { ReadyRows } from './components/ReadyRows'; + +/** + * The payouts' tabs and rows (J11-9), the open payout beside them (J11-9f) and the three dialogs + * (J11-9b, 9d, 9e). The tab, search, page and open payout are in the URL; any change but the open + * payout remounts the rows behind the table skeleton, and a failed read errors in their place. + */ +export function PayoutsBoard() { + const { t } = useTranslation(['payouts', 'common']); + const model = usePayoutsPage(); + const { args, dialogs, readyCount } = model; + + return ( + + ({ + href: model.tabHref(tab), + label: t(`page.tabs.${tab}`), + isActive: tab === model.status, + ...(tab === 'ready' && readyCount + ? { + count: readyCount, + countLabel: t('page.ready-count', { count: readyCount }), + } + : {}), + }))} + /> + + }> + {args.status === 'ready' ? ( + + ) : ( + + )} + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/AccountBankRow.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/AccountBankRow.tsx new file mode 100644 index 0000000..bd9f9d1 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/AccountBankRow.tsx @@ -0,0 +1,24 @@ +'use client'; + +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { useTranslation } from 'react-i18next'; + +import type { AccountBankRowProps } from '../types'; + +/** + * The account the transfer goes to (J11-9b, 9f): «صاحب حساب» with the bank when the API knows the + * holder; it records the number only for now, so the row names the bank alone, or hides. + */ +export function AccountBankRow({ holderName, bankCode }: AccountBankRowProps) { + const { t } = useTranslation('payouts'); + const bank = t(`banks.${bankCode}`, { defaultValue: '' }); + + if (holderName) { + return ( + + {bank ? t('holder', { name: holderName, bank }) : holderName} + + ); + } + return bank ? {bank} : null; +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/AnalystName.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/AnalystName.tsx new file mode 100644 index 0000000..3e313ef --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/AnalystName.tsx @@ -0,0 +1,16 @@ +import { Typography } from '@lumina/island/atoms/typography'; +import { Element } from '@lumina/island/primitives/element'; + +import type { AnalystNameProps } from '../types'; + +/** «سارا مرادی @sara_gold», as the dialogs' «تحلیلگر» row writes it. */ +export function AnalystName({ name, username }: AnalystNameProps) { + return ( + + {name}{' '} + + @{username} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/CancelPayoutDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/CancelPayoutDialog.tsx new file mode 100644 index 0000000..293e67a --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/CancelPayoutDialog.tsx @@ -0,0 +1,43 @@ +'use client'; + +import { ReasonDialog } from '@lumina/garden-roof/app/screens'; +import { Banner } from '@lumina/island/molecules/banner'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { PayoutDialogProps } from '../types'; +import { PayoutFacts } from './PayoutFacts'; + +/** + * «لغو تسویه» (J11-9e): final. The amount goes back to the analyst's «قابل واریز» and they are + * told without the reason; the reason (10 characters at least) shows in their payout's detail. + */ +export function CancelPayoutDialog({ dialogs }: PayoutDialogProps) { + const { t } = useTranslation(['payouts', 'common']); + const payout = + dialogs.dialog?.kind === 'cancel' ? dialogs.dialog.payout : null; + + return ( + } + hint={t('cancel.shown')} + emptyReason={t('cancel.empty')} + form={dialogs.cancelForm} + onSubmit={dialogs.confirmCancel} + isSubmitting={dialogs.pending === 'cancel'} + confirmLabel={t('cancel.confirm')} + > + {payout && ( + + {t('cancel.notice', { + amount: number(payout.amount), + name: payout.fullName, + })} + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/CreatePayoutDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/CreatePayoutDialog.tsx new file mode 100644 index 0000000..bb6cdba --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/CreatePayoutDialog.tsx @@ -0,0 +1,86 @@ +'use client'; + +import { Amount } from '@lumina/island/atoms/amount'; +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 { DetailRow } from '@lumina/island/molecules/detail-row'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { Modal } from '@lumina/island/molecules/modal'; +import { useTranslation } from 'react-i18next'; + +import type { PayoutDialogProps } from '../types'; +import { periodLabel } from '../utils'; +import { AccountBankRow } from './AccountBankRow'; +import { AnalystName } from './AnalystName'; +import { ShebaText } from './ShebaText'; + +/** + * «ایجاد تسویه» (J11-9b): the amount from the ledger and the شبا to copy for the transfer, neither + * editable, and what the analyst is told. No reason is asked: making a payout is audited as is. + */ +export function CreatePayoutDialog({ dialogs }: PayoutDialogProps) { + const { t } = useTranslation(['payouts', 'common']); + const payout = + dialogs.dialog?.kind === 'create' ? dialogs.dialog.payout : null; + const isCreating = dialogs.pending === 'create'; + + return ( + + + + + } + > + {payout && ( + + + + + + + {periodLabel(payout.periodStart, payout.periodEnd)} + + + + + dialogs.copySheba(payout.sheba)} + > + + + + + + {t('create.note')} + + + {t('create.notice', { name: payout.fullName })} + + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/LedgerLineSubtitle.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/LedgerLineSubtitle.tsx new file mode 100644 index 0000000..d75029b --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/LedgerLineSubtitle.tsx @@ -0,0 +1,27 @@ +'use client'; + +import { Element } from '@lumina/island/primitives/element'; +import { useTranslation } from 'react-i18next'; + +import type { LedgerLineSubtitleProps } from '../types'; + +/** Who subscribed and for which period, or a correction's reason. */ +export function LedgerLineSubtitle({ line }: LedgerLineSubtitleProps) { + const { t } = useTranslation(['payouts', 'common']); + + if (line.kind === 'correction') return line.reason; + return ( + <> + {line.subscriberUsername && ( + + @{line.subscriberUsername} + + )} + {line.subscriberUsername && line.billingPeriod && ' · '} + {line.billingPeriod && + t('detail.lines.plan', { + period: t(`common:billing-periods.${line.billingPeriod}`), + })} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/LedgerLines.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/LedgerLines.tsx new file mode 100644 index 0000000..3624682 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/LedgerLines.tsx @@ -0,0 +1,72 @@ +'use client'; + +import { Amount } from '@lumina/island/atoms/amount'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { List, ListRow } from '@lumina/island/molecules/list-row'; +import { date } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { LedgerLinesProps } from '../types'; +import { LedgerLineSubtitle } from './LedgerLineSubtitle'; +import { PayoutAmount } from './PayoutAmount'; + +/** + * «ردیف‌های دفتر حساب» (J11-9f): the lines the payout pays, each the analyst's share after + * Lumina's fee, a refund's deduction in danger, an admin's ± correction with its reason, and their + * sum, which is the payout's amount. A payout made by amount (A15) has no lines. + */ +export function LedgerLines({ payout }: LedgerLinesProps) { + const { t } = useTranslation(['payouts', 'common']); + + return ( + + + + {t('detail.lines.title')} + + + {t('detail.lines.note')} + + + {payout.lines.length === 0 ? ( + + {t('detail.lines.empty')} + + ) : ( + + {payout.lines.map((line) => ( + } + meta={date(line.at, { time: false })} + end={} + /> + ))} + + )} + + + {t('detail.lines.total')} + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/MarkPaidDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/MarkPaidDialog.tsx new file mode 100644 index 0000000..f607624 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/payouts/organisms/payouts-board/components/MarkPaidDialog.tsx @@ -0,0 +1,150 @@ +'use client'; + +import { RECEIPT_FILE } from '@lumina/garden-roof/features/payouts'; +import { translateMessage } from '@lumina/garden-roof/shared/utils'; +import { Button } from '@lumina/island/atoms/button'; +import { FieldError } from '@lumina/island/atoms/field-error'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Select } from '@lumina/island/atoms/select'; +import { Banner } from '@lumina/island/molecules/banner'; +import { FileField } from '@lumina/island/molecules/file-field'; +import { Modal } from '@lumina/island/molecules/modal'; +import { TextInput } from '@lumina/island/molecules/text-input'; +import { date, number } from '@lumina/tools/format'; +import { useId } from 'react'; +import { Controller } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import type { PayoutDialogProps } from '../types'; +import { megabytes } from '../utils'; +import { PayoutFacts } from './PayoutFacts'; + +/** + * «ثبت پرداخت» (J11-9d): after the bank transfer, its tracking number (required), the day the + * money moved (today by default, never before the payout was made) and an optional receipt. A + * failure keeps every value, with the server's word under its field or at the top. + */ +export function MarkPaidDialog({ dialogs }: PayoutDialogProps) { + const { t } = useTranslation(['payouts', 'common']); + const dateErrorId = useId(); + const payout = + dialogs.dialog?.kind === 'mark-paid' ? dialogs.dialog.payout : null; + const isSaving = dialogs.pending === 'mark-paid'; + const form = dialogs.markPaidForm; + const { errors } = form.formState; + const formError = errors.root?.server?.message; + + return ( + + + + + } + > + {payout && ( + { + event.preventDefault(); + dialogs.confirmMarkPaid(); + }} + > + {formError && ( + + {translateMessage(t, formError)} + + )} + + + ( + + ({ + value, + label: t(`grant.reasons.${value}`), + })), + ]} + /> + {errors.reasonCode?.message && ( + + {translateMessage(t, errors.reasonCode.message)} + + )} + + + + {t('grant.notice')} + + {errors.root?.server?.message && ( + {errors.root.server.message} + )} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/grant-access/index.ts b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/grant-access/index.ts new file mode 100644 index 0000000..fe26162 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/grant-access/index.ts @@ -0,0 +1,2 @@ +export { GrantAccessDialog } from './GrantAccessDialog'; +export type { GrantAccessDialogProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/grant-access/types.ts b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/grant-access/types.ts new file mode 100644 index 0000000..2f51af2 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/grant-access/types.ts @@ -0,0 +1,5 @@ +export type GrantAccessDialogProps = { + /** From `?grant=1`. */ + open: boolean; + onClose: () => void; +}; diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/SubscriptionDetailSheet.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/SubscriptionDetailSheet.tsx new file mode 100644 index 0000000..b155bc6 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/SubscriptionDetailSheet.tsx @@ -0,0 +1,46 @@ +'use client'; + +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { Sheet } from '@lumina/island/molecules/sheet'; +import { Suspense, useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { DetailSkeleton } from './components/DetailSkeleton'; +import { SubscriptionDetail } from './components/SubscriptionDetail'; +import type { SubscriptionDetailSheetProps } from './types'; + +/** + * «جزئیات اشتراک» as a side panel over the list (J11-7b), open while the URL names a subscription. + * The panel keeps the last one while it slides out; a failed read errors inside it. + */ +export function SubscriptionDetailSheet({ + id, + onClose, +}: SubscriptionDetailSheetProps) { + const { t } = useTranslation('subscriptions'); + const [shownId, setShownId] = useState(id); + if (id !== null && id !== shownId) setShownId(id); + + return ( + setShownId(null)} + > + {shownId && ( + + }> + + + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DetailFacts.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DetailFacts.tsx new file mode 100644 index 0000000..50ef6bb --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DetailFacts.tsx @@ -0,0 +1,100 @@ +'use client'; + +import { GRANT_REASONS } from '@lumina/garden-roof/features/subscriptions'; +import { formatMobile } from '@lumina/garden-roof/shared/utils'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { Element } from '@lumina/island/primitives/element'; +import { date } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { DetailPartProps } from '../types'; + +/** + * Who, which channel, the period and its dates, and whether access is open (J11-7b). A refunded + * subscription ends at the refund, with the expiry it cut short under it (J11-7f). The phone shows + * here only, with a lock: admins only. + */ +export function DetailFacts({ model }: DetailPartProps) { + const { t } = useTranslation(['subscriptions', 'common']); + const { subscription } = model; + const grantReason = GRANT_REASONS.find( + (code) => code === subscription.grant?.reasonCode, + ); + const access = + subscription.status === 'active' + ? t('detail.access.open') + : subscription.status === 'suspended' + ? t('detail.access.suspended') + : t('detail.access.closed'); + + return ( + + + {subscription.investor.fullName}{' '} + + @{subscription.investor.username} + + + + + + {formatMobile(subscription.investorPhone) || '—'} + + + + + + {subscription.analyst.fullName}{' '} + + @{subscription.analyst.username} + + + + {t(`common:billing-periods.${subscription.period}`)} + + + {date(subscription.startedAt)} + + {subscription.refund ? ( + + + + {date(subscription.endsAt)} + + + {t('detail.previous-ends', { + date: date(subscription.refund.previousEndsAt, { time: false }), + })} + + + + ) : ( + + {date(subscription.endsAt)} + + )} + {access} + {subscription.grant && ( + <> + + {grantReason + ? t(`grant.reasons.${grantReason}`) + : subscription.grant.reasonCode} + + + {subscription.grant.note} + + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DetailSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DetailSkeleton.tsx new file mode 100644 index 0000000..dcabdd0 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DetailSkeleton.tsx @@ -0,0 +1,8 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +/** The panel before the subscription arrives: rows like its facts and payment. */ +export function DetailSkeleton({ label }: { label: string }) { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DialogSubject.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DialogSubject.tsx new file mode 100644 index 0000000..8a8971d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/DialogSubject.tsx @@ -0,0 +1,26 @@ +'use client'; + +import { Typography } from '@lumina/island/atoms/typography'; +import { Element } from '@lumina/island/primitives/element'; +import { useTranslation } from 'react-i18next'; + +import type { DialogSubjectProps } from '../types'; + +/** Whose subscription a dialog changes: «مهدی کاظمی · @mehdi_k · اشتراک ماهانه رضا احمدی». */ +export function DialogSubject({ subscription }: DialogSubjectProps) { + const { t } = useTranslation(['subscriptions', 'common']); + + return ( + + {subscription.investor.fullName} ·{' '} + + @{subscription.investor.username} + {' '} + ·{' '} + {t('dialog.plan', { + period: t(`common:billing-periods.${subscription.period}`), + analyst: subscription.analyst.fullName, + })} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/ExtendDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/ExtendDialog.tsx new file mode 100644 index 0000000..d18b0db --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/ExtendDialog.tsx @@ -0,0 +1,109 @@ +'use client'; + +import { EXTEND_DAYS } from '@lumina/garden-roof/features/subscriptions'; +import { translateMessage } from '@lumina/garden-roof/shared/utils'; +import { REASON_MAX_LENGTH } from '@lumina/garden-roof/shared/validations'; +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 { DetailRow } from '@lumina/island/molecules/detail-row'; +import { FilterChips } from '@lumina/island/molecules/filter-chips'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { Modal } from '@lumina/island/molecules/modal'; +import { TextInput } from '@lumina/island/molecules/text-input'; +import { date, number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; +import { useWatch } from 'react-hook-form'; + +import type { DetailPartProps } from '../types'; +import { DialogSubject } from './DialogSubject'; + +/** + * «تمدید دستی» (J11-7d): the current expiry, the days (۷ by default), the new expiry they lead to, + * and the «دلیل». No money moves; the subscriber is notified. Confirm waits for a reason; while it + * runs the dialog can't be closed, and a failure keeps it as it was. + */ +export function ExtendDialog({ model }: DetailPartProps) { + const { t } = useTranslation(['subscriptions', 'common']); + const { subscription, extendForm: form, isExtending } = model; + const { errors } = form.formState; + const reason = useWatch({ control: form.control, name: 'reason' }); + const days = useWatch({ control: form.control, name: 'days' }); + + return ( + + + + + } + > + + + + + {date(subscription.endsAt)} + + + + + {t('extend.days-label')} + + ({ + value, + label: t('extend.days', { days: number(Number(value)) }), + }))} + value={days} + onChange={(next) => form.setValue('days', next)} + disabled={isExtending} + /> + + + + {date(model.extendedEndsAt)} + + + + + {t('extend.notice', { days: number(model.extendDays) })} + + {errors.root?.server?.message && ( + {errors.root.server.message} + )} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/MaskedSheba.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/MaskedSheba.tsx new file mode 100644 index 0000000..48f4b2d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/MaskedSheba.tsx @@ -0,0 +1,14 @@ +import { Element } from '@lumina/island/primitives/element'; + +/** + * A شبا with only its last four digits, as the refund row prints it (J11-7f): `IR•• •••• •••• •••• + * 4567`, left to right in the Latin-digit face banks print (0011). The API keeps only those four + * (`IR` and 20 stars before them); the full number is on the transfer record. + */ +export function MaskedSheba({ value }: { value: string }) { + return ( + + {`IR•• •••• •••• •••• ${value.slice(-4)}`} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/PaymentSection.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/PaymentSection.tsx new file mode 100644 index 0000000..a7de5bb --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/PaymentSection.tsx @@ -0,0 +1,109 @@ +'use client'; + +import { Amount } from '@lumina/island/atoms/amount'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { Typography } from '@lumina/island/atoms/typography'; +import { List, ListRow } from '@lumina/island/molecules/list-row'; +import { date } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { DetailPartProps } from '../types'; +import { MaskedSheba } from './MaskedSheba'; + +/** + * «پرداخت» (J11-7b): the gateway payment; after a refund, «پرداخت و بازگشت وجه» with the refund + * row first and the payment marked unchanged (J11-7f). A grant has no payment: it says so; a paid + * one with no payment on record says that. A missing tracking number or شبا leaves its line out. + */ +export function PaymentSection({ model }: DetailPartProps) { + const { t } = useTranslation(['subscriptions', 'common']); + const { payment, refund } = model.subscription; + const successful = ( + + {t('common:status.payment.successful')} + + ); + + if (!payment) { + const isGrant = model.subscription.source === 'grant'; + return ( + + + {isGrant ? t('detail.grant.title') : t('detail.payment.title')} + + + {isGrant + ? t('detail.grant.description') + : t('detail.payment.missing')} + + + ); + } + + return ( + + + {refund + ? t('detail.payment.title-refunded') + : t('detail.payment.title')} + + + {refund && ( + + + {t('detail.payment.refund-reference', { + reference: refund.bankReference, + })} + + {refund.destinationSheba && ( + + {t('detail.payment.refund-sheba')}{' '} + + + )} + + } + end={ + <> + + {successful} + + } + /> + )} + + + {successful} + + } + /> + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/RefundDialog.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/RefundDialog.tsx new file mode 100644 index 0000000..f256621 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/RefundDialog.tsx @@ -0,0 +1,162 @@ +'use client'; + +import { translateMessage } from '@lumina/garden-roof/shared/utils'; +import { REASON_MAX_LENGTH } from '@lumina/garden-roof/shared/validations'; +import { Amount } from '@lumina/island/atoms/amount'; +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 { DetailRow } from '@lumina/island/molecules/detail-row'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { Modal } from '@lumina/island/molecules/modal'; +import { TextInput } from '@lumina/island/molecules/text-input'; +import { date, number, signed } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; +import { useWatch } from 'react-hook-form'; + +import type { DetailPartProps } from '../types'; +import { DialogSubject } from './DialogSubject'; + +/** + * «بازگشت وجه» (J11-7e): the payment, then the amount (all of it by default, never more), the + * destination شبا, the bank transfer's tracking number and the «دلیل», with what the refund does + * spelled out as the amount changes. The money is wired before this is recorded (phase 0). + */ +export function RefundDialog({ model }: DetailPartProps) { + const { t } = useTranslation(['subscriptions', 'common']); + const { subscription, refundForm: form, isRefunding } = model; + const { errors } = form.formState; + const payment = subscription.payment; + const reason = useWatch({ control: form.control, name: 'reason' }); + const amount = useWatch({ control: form.control, name: 'amount' }); + const destinationSheba = useWatch({ + control: form.control, + name: 'destinationSheba', + }); + if (!payment) return null; + + const amountField = form.register('amount', { + onChange: (event: { target: { value: string } }) => + form.setValue('amount', model.formatAmount(event.target.value)), + }); + const shebaField = form.register('destinationSheba', { + onChange: (event: { target: { value: string } }) => + form.setValue('destinationSheba', model.formatSheba(event.target.value)), + }); + + return ( + + + + + } + > + + + + + + + + {date(payment.paidAt)} + + + {payment.reference ?? '—'} + + + + + + + + + + • {t('refund.impact.access')} + + + •{' '} + {t('refund.impact.transaction', { + amount: signed(model.refundAmount), + })} + + + • {t('refund.impact.card')} + + + •{' '} + {t('refund.impact.deduction', { + amount: number(model.refundDeduction), + analyst: subscription.analyst.fullName, + })} + + + + {errors.root?.server?.message && ( + {errors.root.server.message} + )} + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/SubscriptionDetail.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/SubscriptionDetail.tsx new file mode 100644 index 0000000..0014e37 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/components/SubscriptionDetail.tsx @@ -0,0 +1,71 @@ +'use client'; + +import { AuditLog } from '@lumina/garden-roof/app/screens'; +import { useSubscriptionDetailPart } from '@lumina/garden-roof/features/subscriptions'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { Typography } from '@lumina/island/atoms/typography'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { SubscriptionDetailProps } from '../types'; +import { DetailFacts } from './DetailFacts'; +import { ExtendDialog } from './ExtendDialog'; +import { PaymentSection } from './PaymentSection'; +import { RefundDialog } from './RefundDialog'; + +/** + * One subscription in the side panel (J11-7b): its status with the days left and the source, the + * facts, the payment (and refund, J11-7f), «گزارش ممیزی», and «تمدید دستی» / «بازگشت وجه» when + * they apply, each opening its dialog over the panel. + */ +export function SubscriptionDetail({ id }: SubscriptionDetailProps) { + const { t } = useTranslation(['subscriptions', 'common']); + const model = useSubscriptionDetailPart({ id }); + const { subscription } = model; + const caption = [ + subscription.remainingDays !== null + ? t('detail.remaining', { days: number(subscription.remainingDays) }) + : null, + t('detail.source', { source: t(`list.sources.${subscription.source}`) }), + ] + .filter(Boolean) + .join(' · '); + + return ( + + + + {t(`common:status.subscription.${subscription.status}`)} + + + {caption} + + + + + + {(subscription.canExtend || subscription.canRefund) && ( + + {subscription.canExtend && ( + + )} + {subscription.canRefund && ( + + )} + + )} + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/index.ts b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/index.ts new file mode 100644 index 0000000..f32216c --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/index.ts @@ -0,0 +1,2 @@ +export { SubscriptionDetailSheet } from './SubscriptionDetailSheet'; +export type { SubscriptionDetailSheetProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/types.ts b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/types.ts new file mode 100644 index 0000000..eafff43 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-detail/types.ts @@ -0,0 +1,18 @@ +import type { + SubscriptionDetailPartModel, + SubscriptionDetailPayload, +} from '@lumina/garden-roof/features/subscriptions'; + +export type SubscriptionDetailSheetProps = { + /** The subscription to show, from `?id=`; `null` closes the panel. */ + id: string | null; + onClose: () => void; +}; + +export type SubscriptionDetailProps = { id: string }; + +export type DetailPartProps = { model: SubscriptionDetailPartModel }; + +export type DialogSubjectProps = { subscription: SubscriptionDetailPayload }; + +export type MaskedShebaProps = { value: string }; diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/SubscriptionList.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/SubscriptionList.tsx new file mode 100644 index 0000000..5c30ef1 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/SubscriptionList.tsx @@ -0,0 +1,61 @@ +'use client'; + +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { + SUBSCRIPTION_FILTERS, + useSubscriptionsPage, +} from '@lumina/garden-roof/features/subscriptions'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { ChipGroup } from '@lumina/island/molecules/chip-group'; +import { Suspense } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { GrantAccessDialog } from '../grant-access'; +import { SubscriptionDetailSheet } from '../subscription-detail'; +import { ListSkeleton } from './components/ListSkeleton'; +import { SubscriptionRows } from './components/SubscriptionRows'; + +/** + * اشتراک‌ها (J11-7): the filter chips and the rows, with the detail panel (J11-7b) and the grant + * dialog (J11-7c) over them; all of it in the URL. Any search, filter or page change remounts the + * rows behind the table skeleton; a failed read errors in their place. + */ +export function SubscriptionList() { + const { t } = useTranslation('subscriptions'); + const model = useSubscriptionsPage(); + + return ( + + ({ + value: filter, + label: t(`list.filters.${filter}`), + }))} + value={model.filters} + onToggle={model.toggleFilter} + /> + + }> + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/ListEmpty.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/ListEmpty.tsx new file mode 100644 index 0000000..5f046d0 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/ListEmpty.tsx @@ -0,0 +1,38 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import type { ListEmptyProps } from '../types'; + +/** No row: no subscription yet, or nothing matched the search and filters. */ +export function ListEmpty({ kind, clearHref }: ListEmptyProps) { + const { t } = useTranslation('subscriptions'); + + if (kind === 'search') { + return ( + + + + + + ); + } + return ( + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/ListSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/ListSkeleton.tsx new file mode 100644 index 0000000..3e1d14d --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/ListSkeleton.tsx @@ -0,0 +1,16 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +import type { ListSkeletonProps } from '../types'; + +/** The rows before they arrive: the admin table preset with the list's seven columns. */ +export function ListSkeleton({ label, delayed }: ListSkeletonProps) { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/SubscriptionRows.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/SubscriptionRows.tsx new file mode 100644 index 0000000..6fad836 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscription-list/components/SubscriptionRows.tsx @@ -0,0 +1,151 @@ +'use client'; + +import { useSubscriptionListPart } from '@lumina/garden-roof/features/subscriptions'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { Tag } from '@lumina/island/atoms/tag'; +import { Pager } from '@lumina/island/molecules/pager'; +import { PersonSummary } from '@lumina/island/molecules/person-summary'; +import { DataTable } from '@lumina/island/organisms/data-table'; +import { Element } from '@lumina/island/primitives/element'; +import { date, number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { SubscriptionRowsProps } from '../types'; +import { ListEmpty } from './ListEmpty'; + +/** + * The rows for the search, filters and page, newest start first (J11-7). Desktop only, so the + * table scrolls sideways when the window is narrow. The whole row opens its detail panel; the + * open button does the same from the keyboard. + */ +export function SubscriptionRows({ + args, + selectedId, + detailHref, + onOpen, + clearHref, +}: SubscriptionRowsProps) { + const { t } = useTranslation(['subscriptions', 'common']); + const part = useSubscriptionListPart(args); + + if (part.empty) return ; + + return ( + + + + + + {t('list.columns.investor')} + + + {t('list.columns.analyst')} + + + {t('list.columns.period')} + + + {t('list.columns.started')} + + + {t('list.columns.ends')} + + + {t('list.columns.status')} + + + {t('list.columns.source')} + + + + + {part.rows.map((row) => ( + onOpen(row.id)} + > + + + + + + + + {t(`common:billing-periods.${row.period}`)} + + + {date(row.startedAt, { time: false })} + + + {date(row.endsAt, { time: false })} + + + + {t(`common:status.subscription.${row.status}`)} + + + + {row.source === 'grant' ? ( + + {t('list.sources.grant')} + + ) : ( + t('list.sources.payment') + )} + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscriptions-toolbar/index.ts b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscriptions-toolbar/index.ts new file mode 100644 index 0000000..17c90c4 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscriptions-toolbar/index.ts @@ -0,0 +1,2 @@ +export { SubscriptionsToolbar } from './SubscriptionsToolbar'; +export type { SubscriptionsToolbarProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscriptions-toolbar/types.ts b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscriptions-toolbar/types.ts new file mode 100644 index 0000000..daba2a4 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/organisms/subscriptions-toolbar/types.ts @@ -0,0 +1 @@ +export type SubscriptionsToolbarProps = Record; diff --git a/apps/wall-street-plaza/src/app/(panel)/subscriptions/page.tsx b/apps/wall-street-plaza/src/app/(panel)/subscriptions/page.tsx new file mode 100644 index 0000000..aacc009 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/subscriptions/page.tsx @@ -0,0 +1,40 @@ +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 { ListSkeleton, SubscriptionList } from './organisms/subscription-list'; +import { SubscriptionsToolbar } from './organisms/subscriptions-toolbar'; + +export const metadata: Metadata = { + title: i18n.t('subscriptions:list.meta-title'), +}; + +/** + * اشتراک‌ها (J11-7): the title on the server with the search and «اعطای دسترسی» beside it; the + * list, its detail panel and dialogs in the browser once the admin is known (0062). + */ +export default function SubscriptionsPage() { + const skeleton = ( + + ); + + return ( + <> + + + + } + /> + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/loading.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/loading.tsx new file mode 100644 index 0000000..2ce22bd --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/loading.tsx @@ -0,0 +1,19 @@ +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { PageHeader } from '@lumina/island/molecules/page-header'; + +import { i18n } from '../../../../i18n'; +import { ReviewSkeleton } from './organisms/verification-review'; + +/** The review before it arrives: its title and back link over the skeleton. */ +export default function Loading() { + return ( + <> + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/VerificationReview.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/VerificationReview.tsx new file mode 100644 index 0000000..8c04d7b --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/VerificationReview.tsx @@ -0,0 +1,85 @@ +'use client'; + +import { AuditLog } from '@lumina/garden-roof/app/screens'; +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { useVerificationReviewPage } from '@lumina/garden-roof/features/verification'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Banner } from '@lumina/island/molecules/banner'; +import { useRouter } from 'next/navigation'; +import { useTranslation } from 'react-i18next'; + +import { DecisionDialogs } from './components/DecisionDialogs'; +import { Decisions } from './components/Decisions'; +import { IdImageCard } from './components/IdImageCard'; +import { PastSubmissions } from './components/PastSubmissions'; +import { QueueNav } from './components/QueueNav'; +import { RequestFacts } from './components/RequestFacts'; +import type { VerificationReviewProps } from './types'; + +/** + * One request under review (J11-3): the queue's place, the facts and decisions in the 432px + * column with past submissions, and the ID image with «گزارش ممیزی» beside them. On a phone the + * image comes first and the decisions pin to the bottom (J11-3 M). After a decision the next + * pending request loads in place; after the last, back to the queue. + */ +export function VerificationReview({ id }: VerificationReviewProps) { + const { t } = useTranslation('verification'); + const router = useRouter(); + const model = useVerificationReviewPage({ + id, + onDecided: (nextId, sort) => { + if (!nextId) { + router.replace(ROUTES.verifications); + return; + } + router.replace( + sort === 'asc' + ? ROUTES.verification(nextId) + : `${ROUTES.verification(nextId)}?sort=${sort}`, + ); + }, + }); + + return ( + + + {model.request.accountStatus === 'suspended' && ( + + )} + + + + + + + + + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/DecisionDialogs.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/DecisionDialogs.tsx new file mode 100644 index 0000000..171bc92 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/DecisionDialogs.tsx @@ -0,0 +1,87 @@ +'use client'; + +import { ReasonDialog } from '@lumina/garden-roof/app/screens'; +import { REJECT_TEMPLATES } from '@lumina/garden-roof/features/verification'; +import { Button } from '@lumina/island/atoms/button'; +import { Element } from '@lumina/island/primitives/element'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Modal } from '@lumina/island/molecules/modal'; +import { useTranslation } from 'react-i18next'; + +import type { ReviewPartProps } from '../types'; + +/** + * «تأیید درخواست» (J11-3g, 3h for a suspended account) and «رد درخواست احراز هویت» (J11-3k), whose + * reason the analyst gets. + */ +export function DecisionDialogs({ model }: ReviewPartProps) { + const { t } = useTranslation(['verification', 'common']); + const { request } = model; + const isSuspended = request.accountStatus === 'suspended'; + + return ( + <> + + + + + } + > + {isSuspended + ? t('approve.description-suspended') + : t('approve.description')} + + + {request.fullName} ·{' '} + + @{request.username} + + + } + fieldLabel={t('reject.field')} + placeholder={t('reject.placeholder')} + hint={t('common:reason.hint-analyst')} + templatesLabel={t('reject.templates-label')} + templates={REJECT_TEMPLATES.map((id) => ({ + id, + label: t(`reject.templates.${id}.label`), + text: t(`reject.templates.${id}.text`), + }))} + emptyReason={t('reject.empty')} + form={model.rejectForm} + onSubmit={model.confirmReject} + isSubmitting={model.isRejecting} + confirmLabel={t('reject.confirm')} + /> + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/Decisions.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/Decisions.tsx new file mode 100644 index 0000000..63ccad9 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/Decisions.tsx @@ -0,0 +1,52 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { PinnedFooter } from '@lumina/island/molecules/pinned-footer'; +import { useTranslation } from 'react-i18next'; + +import type { DecisionsProps } from '../types'; + +/** + * «تأیید» and «رد کردن»: under the facts from 1024px up (`placement="column"`), or pinned to the + * bottom of the page on a phone (`placement="footer"`, J11-3 M). They wait for the ID image; a + * failed image leaves them live. + */ +export function Decisions({ model, placement }: DecisionsProps) { + const { t } = useTranslation('verification'); + if (!model.isPending) return null; + const frozenReason = t('review.image.frozen'); + + const buttons = ( + <> + + + + ); + + return placement === 'column' ? ( + + {buttons} + + ) : ( + + {buttons} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/IdImageCard.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/IdImageCard.tsx new file mode 100644 index 0000000..0e999d9 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/IdImageCard.tsx @@ -0,0 +1,116 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton } from '@lumina/island/atoms/skeleton'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { Lightbox } from '@lumina/island/organisms/lightbox'; +import { Element } from '@lumina/island/primitives/element'; +import { cn } from '@lumina/island/tools/cn'; +import { useTranslation } from 'react-i18next'; + +import type { ReviewPartProps } from '../types'; + +/** + * «تصویر کارت ملی»: the ID image fitted in its card, opening at 100% in the zoomable lightbox. + * Until it loads, both image buttons wait; a failed load says so with its own retry. + */ +export function IdImageCard({ model }: ReviewPartProps) { + const { t } = useTranslation('verification'); + const { request } = model; + const alt = t('review.image.alt', { name: request.fullName }); + const isLoaded = model.imageState === 'loaded'; + const download = () => { + const link = document.createElement('a'); + link.href = model.imageSrc; + link.download = `id-card-${request.username}`; + link.click(); + }; + + return ( + + + + {t('review.image.title')} + + {model.imageState === 'failed' ? ( + + ) : ( + + {!isLoaded && ( + + )} + + + )} + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/PastSubmissions.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/PastSubmissions.tsx new file mode 100644 index 0000000..02ee0d7 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/PastSubmissions.tsx @@ -0,0 +1,47 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { Timeline, TimelineItem } from '@lumina/island/molecules/timeline'; +import { date } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { ReviewPartProps } from '../types'; + +/** «تاریخچه ارسال‌های قبلی»: earlier refusals of a resubmitted request; none for a first one. */ +export function PastSubmissions({ model }: ReviewPartProps) { + const { t } = useTranslation('verification'); + const submissions = model.request.pastSubmissions; + if (submissions.length === 0) return null; + + return ( + + + + {t('review.history.title')} + + + {submissions.map((submission) => ( + + ))} + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/QueueNav.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/QueueNav.tsx new file mode 100644 index 0000000..b7c86ec --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/QueueNav.tsx @@ -0,0 +1,59 @@ +'use client'; + +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { ReviewPartProps } from '../types'; + +/** «۲ از ۷» with «درخواست قبلی» / «درخواست بعدی» through the pending queue in its sort. */ +export function QueueNav({ model }: ReviewPartProps) { + const { t } = useTranslation('verification'); + const { queue } = model.request; + if (!queue) return null; + const hrefOf = (id: string) => + model.sort === 'asc' + ? ROUTES.verification(id) + : `${ROUTES.verification(id)}?sort=${model.sort}`; + + return ( + + + + {t('review.position', { + position: number(queue.position), + total: number(queue.total), + })} + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/RequestFacts.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/RequestFacts.tsx new file mode 100644 index 0000000..3517f82 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/RequestFacts.tsx @@ -0,0 +1,51 @@ +'use client'; + +import { formatMobile } from '@lumina/garden-roof/shared/utils'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { DetailRow } from '@lumina/island/molecules/detail-row'; +import { KeyValue } from '@lumina/island/molecules/key-value'; +import { date } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import type { ReviewPartProps } from '../types'; + +/** Who asked and when, with the request's status and, for a suspended account, its badge. */ +export function RequestFacts({ model }: ReviewPartProps) { + const { t } = useTranslation(['verification', 'common']); + const { request } = model; + + return ( + + + {request.fullName} + + + @{request.username} + + + {formatMobile(request.phone)} + + + {date(request.submittedAt)} + + + + + {t(`common:status.verification.${request.status}`)} + + {request.accountStatus === 'suspended' && ( + + {t('common:status.account.suspended')} + + )} + + + {request.rejectionReason && ( + + {request.rejectionReason} + + )} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/ReviewSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/ReviewSkeleton.tsx new file mode 100644 index 0000000..f0e752f --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/components/ReviewSkeleton.tsx @@ -0,0 +1,21 @@ +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { GridBox } from '@lumina/island/atoms/grid-box'; +import { Skeleton, SkeletonRegion } from '@lumina/island/atoms/skeleton'; + +/** The review before it arrives: the queue row, the facts card and the image card. */ +export function ReviewSkeleton({ label }: { label: string }) { + return ( + + + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/index.ts b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/index.ts new file mode 100644 index 0000000..c6cecb4 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/index.ts @@ -0,0 +1,3 @@ +export { ReviewSkeleton } from './components/ReviewSkeleton'; +export { VerificationReview } from './VerificationReview'; +export type { VerificationReviewProps } from './types'; diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/types.ts b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/types.ts new file mode 100644 index 0000000..8cbec26 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/organisms/verification-review/types.ts @@ -0,0 +1,9 @@ +import type { VerificationReviewPageModel } from '@lumina/garden-roof/features/verification'; + +export type VerificationReviewProps = { id: string }; + +export type ReviewPartProps = { model: VerificationReviewPageModel }; + +export type DecisionsProps = ReviewPartProps & { + placement: 'column' | 'footer'; +}; diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/page.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/page.tsx new file mode 100644 index 0000000..4d371e5 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/[id]/page.tsx @@ -0,0 +1,51 @@ +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { AdminGuard } from '@lumina/garden-roof/app/guards'; +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { PageHeader } from '@lumina/island/molecules/page-header'; +import type { Metadata } from 'next'; +import { Suspense } from 'react'; + +import { i18n } from '../../../../i18n'; +import { + ReviewSkeleton, + VerificationReview, +} from './organisms/verification-review'; + +export const metadata: Metadata = { + title: i18n.t('verification:review.meta-title'), +}; + +type ReviewPageProps = { params: Promise<{ id: string }> }; + +/** + * بررسی درخواست احراز هویت (J11-3): the title and the way back to the queue on the server; the + * request in the browser once the admin is known (0062). A failed read shows no decisions. + */ +export default async function VerificationReviewPage({ + params, +}: ReviewPageProps) { + const { id } = await params; + const skeleton = ( + + ); + + return ( + <> + + + + + + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/loading.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/loading.tsx new file mode 100644 index 0000000..072b7c8 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/loading.tsx @@ -0,0 +1,14 @@ +import { PageHeader } from '@lumina/island/molecules/page-header'; + +import { i18n } from '../../../i18n'; +import { QueueSkeleton } from './organisms/verification-queue'; + +/** The queue before it arrives: its title over the table skeleton. */ +export default function Loading() { + return ( + <> + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/VerificationQueue.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/VerificationQueue.tsx new file mode 100644 index 0000000..5367e91 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/VerificationQueue.tsx @@ -0,0 +1,68 @@ +'use client'; + +import { PartBoundary } from '@lumina/garden-roof/app/error-boundaries'; +import { + VERIFICATION_TABS, + useVerificationQueuePage, +} from '@lumina/garden-roof/features/verification'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { SearchField } from '@lumina/island/molecules/search-field'; +import { TabLinks } from '@lumina/island/molecules/tab-links'; +import { Element } from '@lumina/island/primitives/element'; +import { Suspense } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { QueueSkeleton } from './components/QueueSkeleton'; +import { SortMenu } from './components/SortMenu'; +import { VerificationRows } from './components/VerificationRows'; + +/** + * The queue's controls and rows (J11-2): the status tabs, the search and the sort, all in the URL. + * Any change remounts the rows behind the table skeleton; a failed read errors in their place. + */ +export function VerificationQueue() { + const { t } = useTranslation(['verification', 'common']); + const model = useVerificationQueuePage(); + + return ( + + + ({ + href: model.tabHref(status), + label: t(`queue.tabs.${status}`), + isActive: status === model.status, + }))} + /> + + + + + + + + + }> + + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/Highlight.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/Highlight.tsx new file mode 100644 index 0000000..99d8392 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/Highlight.tsx @@ -0,0 +1,22 @@ +import { Element } from '@lumina/island/primitives/element'; +import { latinDigits } from '@lumina/tools/format'; + +import type { HighlightProps } from '../types'; + +/** The searched text marked inside a cell (J11-2d: «match highlighted»). */ +export function Highlight({ text, query }: HighlightProps) { + const needle = latinDigits(query).trim().replace(/^@/, ''); + const index = needle + ? latinDigits(text).toLowerCase().indexOf(needle.toLowerCase()) + : -1; + if (index === -1) return text; + return ( + <> + {text.slice(0, index)} + + {text.slice(index, index + needle.length)} + + {text.slice(index + needle.length)} + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/QueueEmpty.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/QueueEmpty.tsx new file mode 100644 index 0000000..a54d4a1 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/QueueEmpty.tsx @@ -0,0 +1,39 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { Card } from '@lumina/island/molecules/card'; +import { EmptyState } from '@lumina/island/molecules/empty-state'; +import { useTranslation } from 'react-i18next'; + +import type { QueueEmptyProps } from '../types'; + +/** No row: the queue is empty (J11-2f), or nothing matched the search. */ +export function QueueEmpty({ status, kind, onClearSearch }: QueueEmptyProps) { + const { t } = useTranslation('verification'); + + if (kind === 'search') { + return ( + + + + + + ); + } + return ( + + + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/QueueSkeleton.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/QueueSkeleton.tsx new file mode 100644 index 0000000..6d5385a --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/QueueSkeleton.tsx @@ -0,0 +1,20 @@ +import { SkeletonPreset } from '@lumina/island/organisms/skeleton-preset'; + +/** The queue's rows before they arrive: the admin table preset (J11-2 States). */ +export function QueueSkeleton({ + label, + delayed, +}: { + label: string; + delayed?: boolean; +}) { + return ( + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/SortMenu.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/SortMenu.tsx new file mode 100644 index 0000000..365c17a --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/SortMenu.tsx @@ -0,0 +1,42 @@ +'use client'; + +import { VERIFICATION_SORTS } from '@lumina/garden-roof/features/verification'; +import { Button } from '@lumina/island/atoms/button'; +import { ActionMenu } from '@lumina/island/molecules/action-menu'; +import { Element } from '@lumina/island/primitives/element'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import type { SortMenuProps } from '../types'; + +/** «تاریخ ارسال: قدیمی‌ترین اول» with its menu; the current order carries the check (J11-2d). */ +export function SortMenu({ sort, onChange }: SortMenuProps) { + const { t } = useTranslation('verification'); + const [isOpen, setIsOpen] = useState(false); + + return ( + + + setIsOpen(false)} + label={t('queue.sort-label')} + items={VERIFICATION_SORTS.map((option) => ({ + label: t(`queue.sort-options.${option}`), + icon: option === sort ? 'check' : 'sort', + onSelect: () => onChange(option), + }))} + /> + + ); +} diff --git a/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/VerificationRows.tsx b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/VerificationRows.tsx new file mode 100644 index 0000000..9b154b6 --- /dev/null +++ b/apps/wall-street-plaza/src/app/(panel)/verifications/organisms/verification-queue/components/VerificationRows.tsx @@ -0,0 +1,174 @@ +'use client'; + +import { ROUTES } from '@lumina/garden-roof/app/navigation'; +import { useVerificationListPart } from '@lumina/garden-roof/features/verification'; +import type { VerificationListItemPayload } from '@lumina/garden-roof/features/verification'; +import { formatMobile } from '@lumina/garden-roof/shared/utils'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { StatusBadge } from '@lumina/island/atoms/status-badge'; +import { Typography } from '@lumina/island/atoms/typography'; +import { List, ListRow } from '@lumina/island/molecules/list-row'; +import { Pager } from '@lumina/island/molecules/pager'; +import { DataTable } from '@lumina/island/organisms/data-table'; +import { Element } from '@lumina/island/primitives/element'; +import { date, number } from '@lumina/tools/format'; +import { useRouter } from 'next/navigation'; +import { useTranslation } from 'react-i18next'; + +import type { VerificationRowsProps } from '../types'; +import { Highlight } from './Highlight'; +import { QueueEmpty } from './QueueEmpty'; + +/** + * The queue's rows for the tab, search, sort and page: a table from 1024px up, a list of rows on + * a phone (0063). The whole row opens the request, which walks the pending queue in this sort. + */ +export function VerificationRows({ args }: VerificationRowsProps) { + const { t } = useTranslation(['verification', 'common']); + const router = useRouter(); + const part = useVerificationListPart(args); + + if (part.empty) { + return ( + router.replace(ROUTES.verifications)} + /> + ); + } + + const hrefOf = (row: VerificationListItemPayload) => + args.sort === 'asc' + ? ROUTES.verification(row.id) + : `${ROUTES.verification(row.id)}?sort=${args.sort}`; + const statusLabel = (row: VerificationListItemPayload) => + t(`common:status.verification.${row.status}`); + + return ( + + + + + + {t('queue.columns.name')} + + + {t('queue.columns.username')} + + + {t('queue.columns.phone')} + + + {t('queue.columns.submitted')} + + + {t('queue.columns.status')} + + + + + {part.rows.map((row) => ( + router.push(hrefOf(row))} + > + + + + + + + + @ + + + + + + + + {date(row.submittedAt)} + + + {statusLabel(row)} + + + + + + + ); +} diff --git a/platforms/garden-roof/src/app/error-boundaries/app-crash/index.ts b/platforms/garden-roof/src/app/error-boundaries/app-crash/index.ts new file mode 100644 index 0000000..dfc85e3 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/app-crash/index.ts @@ -0,0 +1,2 @@ +export { AppCrash } from './AppCrash'; +export type { AppCrashProps } from './types'; diff --git a/platforms/garden-roof/src/app/error-boundaries/app-crash/types.ts b/platforms/garden-roof/src/app/error-boundaries/app-crash/types.ts new file mode 100644 index 0000000..4d7160e --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/app-crash/types.ts @@ -0,0 +1,4 @@ +export type AppCrashProps = { + /** What reached global-error: nothing below caught it. */ + error: Error & { digest?: string }; +}; diff --git a/platforms/garden-roof/src/app/error-boundaries/error-fallback/ErrorFallback.tsx b/platforms/garden-roof/src/app/error-boundaries/error-fallback/ErrorFallback.tsx new file mode 100644 index 0000000..2302f13 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/error-fallback/ErrorFallback.tsx @@ -0,0 +1,106 @@ +'use client'; + +import { Card } from '@lumina/island/molecules/card'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { + classifyError, + describeError, + handleError, +} from '@lumina/libs/error-handler'; +import { useEffect, useRef } from 'react'; +import type { ReactNode } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { StatusEmptyState } from '../status-empty-state'; +import type { ErrorFallbackProps } from './types'; +import { errorKind } from './utils'; + +/** + * What every boundary renders. A silent error (aborted, or a 401 already redirecting) shows + * nothing; a 404 or 403 read shows its empty state; anything else shows ErrorState with Try again + * for a network cause or Reload page for a bug, and the reference ID. It reports the error once, + * and a page or app fallback moves focus to its heading. A framed part sits in a Card, as the + * boards draw a section's error (S3-03, U8 ۴.۵). + * + * Offline it has no retry, which can't succeed: it tries again by itself when the device is back + * (G-5c). The app fallback says the app failed, with «بارگذاری دوباره» (G-4h). + */ +export function ErrorFallback({ + error, + size, + name, + onRetry, + retrying = false, + title, + description, + framed = false, + stateSize = 'section', + children, +}: ErrorFallbackProps) { + const { t } = useTranslation('errors'); + const headingRef = useRef(null); + const { read, cause } = classifyError(error); + const kind = errorKind(error); + const isOffline = read === 'boundary' && kind === 'offline'; + + useEffect(() => { + handleError(error, { where: size, name }); + if (size !== 'part') headingRef.current?.focus(); + }, [error, size, name]); + + useEffect(() => { + if (!isOffline || !onRetry) return; + window.addEventListener('online', onRetry, { once: true }); + return () => window.removeEventListener('online', onRetry); + }, [isOffline, onRetry]); + + if (read === 'silent') return null; + const frame = (state: ReactNode) => (framed ? {state} : state); + if (read !== 'boundary') { + return frame( + , + ); + } + + // Only the reference ID is read here, so no copy goes through a translator. + const { referenceId } = describeError(error, (key) => key); + const isApp = size === 'app'; + // A bug won't go away on retry, and the app has nothing left to retry: reload the page instead. + const reloads = isApp || cause === 'logic'; + // Offline keeps its own description: the page updates by itself once the device is back. The + // app's own copy would blame the app, so offline it says only that. + const own: { title?: string; description?: string } = isApp + ? isOffline + ? {} + : { title: t('app.title'), description: t('app.description') } + : { title, description: isOffline ? undefined : description }; + const retry = reloads ? () => window.location.reload() : onRetry; + + return frame( + + {children} + , + ); +} diff --git a/platforms/garden-roof/src/app/error-boundaries/error-fallback/index.ts b/platforms/garden-roof/src/app/error-boundaries/error-fallback/index.ts new file mode 100644 index 0000000..392bc0c --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/error-fallback/index.ts @@ -0,0 +1,6 @@ +export { ErrorFallback } from './ErrorFallback'; +export type { + ErrorFallbackProps, + ErrorFallbackSize, + FallbackKind, +} from './types'; diff --git a/platforms/garden-roof/src/app/error-boundaries/error-fallback/types.ts b/platforms/garden-roof/src/app/error-boundaries/error-fallback/types.ts new file mode 100644 index 0000000..7ca8be4 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/error-fallback/types.ts @@ -0,0 +1,38 @@ +import type { ErrorKind } from '@lumina/island/molecules/error-state'; +import type { ReactNode } from 'react'; + +/** The ErrorState kinds a boundary can show; each has its copy under `errors:fallback`. */ +export type FallbackKind = Exclude< + ErrorKind, + 'not-found' | 'forbidden' | 'session' +>; + +export type ErrorFallbackSize = 'app' | 'page' | 'part'; + +export type ErrorFallbackProps = { + error: unknown; + /** app: global-error. page: a route group's error.tsx. part: a PartBoundary. */ + size: ErrorFallbackSize; + /** The part or route, for the error report; never personal data. */ + name?: string; + /** Try again: resets the failed queries, then the boundary. Offline it runs on `online`. */ + onRetry?: () => void; + /** The retry is running: the button spins and blocks repeat taps. */ + retrying?: boolean; + /** + * A part's own copy for a failure it can be retried from; empty states keep theirs, and offline + * keeps its description. The app fallback has its own. + */ + title?: string; + description?: string; + /** Sits in a Card, where the board draws the part's error as a card (S3-03, U8 ۴.۵). */ + framed?: boolean; + /** + * A part whose board draws its error page-size, such as a dashboard tab's list (J07-1, J07-3): + * the ErrorState is `size="page"`, while the part still reports as a part and keeps focus where + * it is. `section` by default. + */ + stateSize?: 'section' | 'page'; + /** The way out after retry: «بازگشت به خانه», or «تماس با پشتیبانی» after a second failure. */ + children?: ReactNode; +}; diff --git a/platforms/garden-roof/src/app/error-boundaries/error-fallback/utils.ts b/platforms/garden-roof/src/app/error-boundaries/error-fallback/utils.ts new file mode 100644 index 0000000..1fca558 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/error-fallback/utils.ts @@ -0,0 +1,20 @@ +import { isHttpError } from '@lumina/libs/http'; + +import type { FallbackKind } from './types'; + +/** + * Which ErrorState a boundary shows, as the DS classifies it: offline when the device is, the + * HTTP lib's network and timeout codes, server for a 5xx or a server error's digest, else error. + * 404, 403 and 401 never get here: they are empty states or silent. + */ +export function errorKind(error: unknown): FallbackKind { + if (typeof navigator !== 'undefined' && !navigator.onLine) return 'offline'; + if (isHttpError(error)) { + if (error.code === 'NETWORK_ERROR') return 'network'; + if (error.code === 'TIMEOUT') return 'timeout'; + return error.status >= 500 ? 'server' : 'error'; + } + return typeof error === 'object' && error !== null && 'digest' in error + ? 'server' + : 'error'; +} diff --git a/platforms/garden-roof/src/app/error-boundaries/index.ts b/platforms/garden-roof/src/app/error-boundaries/index.ts new file mode 100644 index 0000000..01186c9 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/index.ts @@ -0,0 +1,15 @@ +export { AppCrash } from './app-crash'; +export type { AppCrashProps } from './app-crash'; +export { ErrorFallback } from './error-fallback'; +export type { + ErrorFallbackProps, + ErrorFallbackSize, + FallbackKind, +} from './error-fallback'; +export { PartBoundary } from './part-boundary'; +export type { PartBoundaryProps } from './part-boundary'; +export { StatusEmptyState } from './status-empty-state'; +export type { + StatusEmptyStateProps, + StatusVariant, +} from './status-empty-state'; diff --git a/platforms/garden-roof/src/app/error-boundaries/part-boundary/PartBoundary.tsx b/platforms/garden-roof/src/app/error-boundaries/part-boundary/PartBoundary.tsx new file mode 100644 index 0000000..751d1f3 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/part-boundary/PartBoundary.tsx @@ -0,0 +1,42 @@ +'use client'; + +import { useQueryErrorResetBoundary } from '@tanstack/react-query'; +import { catchError } from 'next/error'; +import type { ErrorInfo } from 'next/error'; + +import { ErrorFallback } from '../error-fallback'; +import type { PartBoundaryProps } from './types'; + +function PartFallback( + { name, title, description, framed, size }: PartBoundaryProps, + { error, retry, reset }: ErrorInfo, +) { + const queryErrors = useQueryErrorResetBoundary(); + // A digest means the part failed on the server: retry renders it there again. + const isServerError = + typeof error === 'object' && error !== null && 'digest' in error; + + return ( + { + queryErrors.reset(); + if (isServerError) retry(); + else reset(); + }} + /> + ); +} + +/** + * The part-size boundary (EB-S) around every part that loads on its own, outside its Suspense, so + * the fallback replaces the skeleton and the part together. Next.js's catchError lets notFound() + * and redirect() through and clears itself on navigation. + */ +export const PartBoundary = catchError(PartFallback); diff --git a/platforms/garden-roof/src/app/error-boundaries/part-boundary/index.ts b/platforms/garden-roof/src/app/error-boundaries/part-boundary/index.ts new file mode 100644 index 0000000..45b6f75 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/part-boundary/index.ts @@ -0,0 +1,2 @@ +export { PartBoundary } from './PartBoundary'; +export type { PartBoundaryProps } from './types'; diff --git a/platforms/garden-roof/src/app/error-boundaries/part-boundary/types.ts b/platforms/garden-roof/src/app/error-boundaries/part-boundary/types.ts new file mode 100644 index 0000000..9dadbce --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/part-boundary/types.ts @@ -0,0 +1,17 @@ +export type PartBoundaryProps = { + /** The part, for the error report: «creator-stats», «feed». Never personal data. */ + name: string; + /** + * The part's own failure copy, such as «عملکرد پیش‌بینی‌ها بارگذاری نشد» / «بقیه کانال در دسترس + * است…» (S3); without it the fallback says what every part says. + */ + title?: string; + description?: string; + /** The fallback sits in a Card, where the board draws the part's error as a card (S3-03). */ + framed?: boolean; + /** + * `page`: the board draws this part's error page-size, such as a dashboard tab's list (J07-1, + * J07-3). `section` by default. + */ + size?: 'section' | 'page'; +}; diff --git a/platforms/garden-roof/src/app/error-boundaries/status-empty-state/StatusEmptyState.tsx b/platforms/garden-roof/src/app/error-boundaries/status-empty-state/StatusEmptyState.tsx new file mode 100644 index 0000000..947f8a8 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/status-empty-state/StatusEmptyState.tsx @@ -0,0 +1,37 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { useTranslation } from 'react-i18next'; + +import { HOME_ROUTE } from '../../navigation/navigation'; +import { STATUS_KINDS } from './constants'; +import type { StatusEmptyStateProps } from './types'; + +/** + * What a read that answered 404, 410 or 403 shows: not an alarm, no retry. At page size it adds the + * way back to سلامت بتا. A client component, so server pages and parts can render it too. + */ +export function StatusEmptyState({ + variant, + size, + headingRef, +}: StatusEmptyStateProps) { + const { t } = useTranslation('errors'); + + return ( + + {size === 'page' && ( + + )} + + ); +} diff --git a/platforms/garden-roof/src/app/error-boundaries/status-empty-state/constants.ts b/platforms/garden-roof/src/app/error-boundaries/status-empty-state/constants.ts new file mode 100644 index 0000000..b376cff --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/status-empty-state/constants.ts @@ -0,0 +1,9 @@ +import type { ErrorKind } from '@lumina/island/molecules/error-state'; + +import type { StatusVariant } from './types'; + +/** The DS draws a missing or forbidden read as ErrorState's calm not-found and forbidden kinds. */ +export const STATUS_KINDS: Record = { + 'not-found': 'not-found', + 'no-access': 'forbidden', +}; diff --git a/platforms/garden-roof/src/app/error-boundaries/status-empty-state/index.ts b/platforms/garden-roof/src/app/error-boundaries/status-empty-state/index.ts new file mode 100644 index 0000000..d793732 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/status-empty-state/index.ts @@ -0,0 +1,2 @@ +export { StatusEmptyState } from './StatusEmptyState'; +export type { StatusEmptyStateProps, StatusVariant } from './types'; diff --git a/platforms/garden-roof/src/app/error-boundaries/status-empty-state/types.ts b/platforms/garden-roof/src/app/error-boundaries/status-empty-state/types.ts new file mode 100644 index 0000000..3cd9c37 --- /dev/null +++ b/platforms/garden-roof/src/app/error-boundaries/status-empty-state/types.ts @@ -0,0 +1,12 @@ +import type { Ref } from 'react'; + +export type StatusVariant = 'not-found' | 'no-access'; + +export type StatusEmptyStateProps = { + /** not-found: a 404 or 410 read. no-access: a 403 read. */ + variant: StatusVariant; + /** page: a route, with a way home. part: one part of a page. */ + size: 'page' | 'part'; + /** A page fallback focuses its heading. */ + headingRef?: Ref; +}; diff --git a/platforms/garden-roof/src/app/guards/admin-guard/AdminGuard.tsx b/platforms/garden-roof/src/app/guards/admin-guard/AdminGuard.tsx new file mode 100644 index 0000000..e923aab --- /dev/null +++ b/platforms/garden-roof/src/app/guards/admin-guard/AdminGuard.tsx @@ -0,0 +1,35 @@ +'use client'; + +import { useRouter } from 'next/navigation'; +import { useEffect } from 'react'; + +import { useCurrentAdmin, useViewerStatus } from '../../../stores/auth'; +import { loginRoute } from '../../navigation'; +import { SessionEnded } from './components/SessionEnded'; +import { useSessionEnded } from './hooks/use-session-ended'; +import type { AdminGuardProps } from './types'; + +/** + * Wraps every panel page (the `(panel)` layout renders it, 0062). The server render and the first + * browser render show the page skeleton, because the server never knows the viewer. Then a guest + * goes to login with a return path and an admin sees the page. The admin API answers only admin + * sessions, so there is no other role to turn away here. When the session runs out on the page, + * it says so in the page's place, with «ورود دوباره». + */ +export function AdminGuard({ fallback, children }: AdminGuardProps) { + const status = useViewerStatus(); + const admin = useCurrentAdmin(); + const router = useRouter(); + const endedHere = useSessionEnded(status); + const showsEnded = status === 'guest' && endedHere !== null; + + useEffect(() => { + if (status !== 'guest' || showsEnded) return; + const { pathname, search } = window.location; + router.replace(loginRoute(`${pathname}${search}`)); + }, [status, showsEnded, router]); + + if (showsEnded) return ; + if (status !== 'member' || !admin) return fallback; + return children; +} diff --git a/platforms/garden-roof/src/app/guards/admin-guard/components/SessionEnded.tsx b/platforms/garden-roof/src/app/guards/admin-guard/components/SessionEnded.tsx new file mode 100644 index 0000000..d9796e0 --- /dev/null +++ b/platforms/garden-roof/src/app/guards/admin-guard/components/SessionEnded.tsx @@ -0,0 +1,24 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { ErrorState } from '@lumina/island/molecules/error-state'; +import { useTranslation } from 'react-i18next'; + +import { loginRoute } from '../../../navigation'; +import type { SessionEndedProps } from '../types'; + +/** «نشست شما به پایان رسید» in the page's place, with «ورود دوباره» back to this page. */ +export function SessionEnded({ returnTo }: SessionEndedProps) { + const { t } = useTranslation('auth'); + + return ( + + + + ); +} diff --git a/platforms/garden-roof/src/app/guards/admin-guard/hooks/use-session-ended.ts b/platforms/garden-roof/src/app/guards/admin-guard/hooks/use-session-ended.ts new file mode 100644 index 0000000..af3f685 --- /dev/null +++ b/platforms/garden-roof/src/app/guards/admin-guard/hooks/use-session-ended.ts @@ -0,0 +1,34 @@ +'use client'; + +import { eventEmitter } from '@lumina/libs/event-emitter'; +import { useEffect, useRef, useState } from 'react'; + +import { AUTH_EVENTS } from '../../../../features/auth'; +import type { ViewerStatus } from '../../../../stores/auth'; + +/** + * Where to come back to when the admin's session ran out on this page (a refresh that failed), + * else `null`. Only a session this page showed as a member counts: an expired one found + * when the page loads, or a sign-out, still goes straight to login. + */ +export function useSessionEnded(status: ViewerStatus): string | null { + const [returnTo, setReturnTo] = useState(null); + // The status this page last showed; the logout event arrives before the guest renders. + const wasMember = useRef(false); + + useEffect(() => { + wasMember.current = status === 'member'; + }, [status]); + + useEffect( + () => + eventEmitter.on(AUTH_EVENTS.logout, ({ reason }) => { + if (reason !== 'session-ended' || !wasMember.current) return; + const { pathname, search } = window.location; + setReturnTo(`${pathname}${search}`); + }), + [], + ); + + return returnTo; +} diff --git a/platforms/garden-roof/src/app/guards/admin-guard/index.ts b/platforms/garden-roof/src/app/guards/admin-guard/index.ts new file mode 100644 index 0000000..9ffd234 --- /dev/null +++ b/platforms/garden-roof/src/app/guards/admin-guard/index.ts @@ -0,0 +1,2 @@ +export { AdminGuard } from './AdminGuard'; +export type { AdminGuardProps } from './types'; diff --git a/platforms/garden-roof/src/app/guards/admin-guard/types.ts b/platforms/garden-roof/src/app/guards/admin-guard/types.ts new file mode 100644 index 0000000..7955819 --- /dev/null +++ b/platforms/garden-roof/src/app/guards/admin-guard/types.ts @@ -0,0 +1,12 @@ +import type { ReactNode } from 'react'; + +export type AdminGuardProps = { + /** The page's same-size skeleton, shown until the browser knows the admin. */ + fallback: ReactNode; + children: ReactNode; +}; + +export type SessionEndedProps = { + /** The page to come back to after login: its path and query. */ + returnTo: string; +}; diff --git a/platforms/garden-roof/src/app/guards/guest-guard/GuestGuard.tsx b/platforms/garden-roof/src/app/guards/guest-guard/GuestGuard.tsx new file mode 100644 index 0000000..c396ea9 --- /dev/null +++ b/platforms/garden-roof/src/app/guards/guest-guard/GuestGuard.tsx @@ -0,0 +1,26 @@ +'use client'; + +import { useRouter } from 'next/navigation'; +import { useEffect } from 'react'; + +import { useViewerStatus } from '../../../stores/auth'; +import { RETURN_TO_PARAM, safeReturnPath } from '../../navigation'; +import type { GuestGuardProps } from './types'; + +/** + * Wraps the login page: a signed-in admin goes on to the page they came for (or سلامت بتا), so + * the form never shows to someone already in. + */ +export function GuestGuard({ fallback, children }: GuestGuardProps) { + const status = useViewerStatus(); + const router = useRouter(); + + useEffect(() => { + if (status !== 'member') return; + const params = new URLSearchParams(window.location.search); + router.replace(safeReturnPath(params.get(RETURN_TO_PARAM))); + }, [status, router]); + + if (status !== 'guest') return fallback; + return children; +} diff --git a/platforms/garden-roof/src/app/guards/guest-guard/index.ts b/platforms/garden-roof/src/app/guards/guest-guard/index.ts new file mode 100644 index 0000000..3686656 --- /dev/null +++ b/platforms/garden-roof/src/app/guards/guest-guard/index.ts @@ -0,0 +1,2 @@ +export { GuestGuard } from './GuestGuard'; +export type { GuestGuardProps } from './types'; diff --git a/platforms/garden-roof/src/app/guards/guest-guard/types.ts b/platforms/garden-roof/src/app/guards/guest-guard/types.ts new file mode 100644 index 0000000..c7dd7d9 --- /dev/null +++ b/platforms/garden-roof/src/app/guards/guest-guard/types.ts @@ -0,0 +1,7 @@ +import type { ReactNode } from 'react'; + +export type GuestGuardProps = { + /** The login frame's skeleton, shown until the browser knows the viewer. */ + fallback: ReactNode; + children: ReactNode; +}; diff --git a/platforms/garden-roof/src/app/guards/index.ts b/platforms/garden-roof/src/app/guards/index.ts new file mode 100644 index 0000000..ea7dbec --- /dev/null +++ b/platforms/garden-roof/src/app/guards/index.ts @@ -0,0 +1,4 @@ +export { AdminGuard } from './admin-guard'; +export type { AdminGuardProps } from './admin-guard'; +export { GuestGuard } from './guest-guard'; +export type { GuestGuardProps } from './guest-guard'; diff --git a/platforms/garden-roof/src/app/http/index.ts b/platforms/garden-roof/src/app/http/index.ts new file mode 100644 index 0000000..82647c2 --- /dev/null +++ b/platforms/garden-roof/src/app/http/index.ts @@ -0,0 +1,2 @@ +export { mapApiErrorBody } from './map-error-body'; +export type { ApiErrorEnvelope } from './types'; diff --git a/platforms/garden-roof/src/app/http/map-error-body.ts b/platforms/garden-roof/src/app/http/map-error-body.ts new file mode 100644 index 0000000..a9388b2 --- /dev/null +++ b/platforms/garden-roof/src/app/http/map-error-body.ts @@ -0,0 +1,54 @@ +import { toFieldErrors } from '@lumina/libs/http'; +import type { HttpErrorShape } from '@lumina/libs/http'; + +import type { ApiErrorEnvelope } from './types'; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** Persian letters: the back end's i18n is English, but a few services answer in Persian copy. */ +const PERSIAN = /[؀-ۿ]/; + +/** A server text the panel can show as it is; English text never reaches a Persian screen. */ +function persianOnly(text: unknown): string | undefined { + return typeof text === 'string' && PERSIAN.test(text) ? text : undefined; +} + +/** A field's own message when it is Persian, else the panel's generic «this value isn't valid». */ +const FIELD_INVALID = 'errors:form.field-invalid'; + +/** + * Adapts admin-api's error contract (the gateway's envelope, `RpcToHttpFilter`) to `HttpError`. + * - `code` is the API's stable code; screens branch on it and word it in Persian themselves. + * - `message` passes through only when it is Persian. admin-api's own messages are English, so + * without one the HTTP lib words the failure from its status (`errors:http.*`). + * - Field errors (a DTO's `{ field: [messages] }`) keep Persian messages; English ones become the + * generic field message, so the form still marks the right field. + * `details` (a changed version, a maximum amount) passes through for the action that handles it. + */ +export function mapApiErrorBody(body: unknown): Partial { + if (!isRecord(body)) return {}; + const fieldMessages = (raw: unknown) => { + const fields = toFieldErrors(raw); + if (!fields) return undefined; + return Object.fromEntries( + Object.entries(fields).map(([field, text]) => [ + field, + persianOnly(text) ?? FIELD_INVALID, + ]), + ); + }; + if (typeof body.statusCode !== 'number' && typeof body.error !== 'string') { + return { fieldErrors: fieldMessages(body) }; + } + const { code, message, details } = body as ApiErrorEnvelope; + const retryAfter = details?.retryAfterSeconds; + return { + code: typeof code === 'string' && code.length > 0 ? code : undefined, + message: persianOnly(Array.isArray(message) ? message[0] : message), + fieldErrors: fieldMessages(message), + retryAfter: typeof retryAfter === 'number' ? retryAfter : undefined, + details: isRecord(details) ? details : undefined, + }; +} diff --git a/platforms/garden-roof/src/app/http/types.ts b/platforms/garden-roof/src/app/http/types.ts new file mode 100644 index 0000000..adedcad --- /dev/null +++ b/platforms/garden-roof/src/app/http/types.ts @@ -0,0 +1,12 @@ +/** + * The admin API's error envelope, the gateway's (`RpcToHttpFilter`). `message` is a string, or a field → messages + * map for validation errors; a throttled request (429) adds `details.retryAfterSeconds`. + */ +export type ApiErrorEnvelope = { + statusCode: number; + /** The stable error code, when the API names the failure (checkout, verification, referral…). */ + code?: string; + error?: string; + message?: string | string[] | Record; + details?: { retryAfterSeconds?: number; [key: string]: unknown } | null; +}; diff --git a/platforms/garden-roof/src/app/navigation/components/admin-sidebar/AdminSidebar.tsx b/platforms/garden-roof/src/app/navigation/components/admin-sidebar/AdminSidebar.tsx new file mode 100644 index 0000000..7b15c38 --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/components/admin-sidebar/AdminSidebar.tsx @@ -0,0 +1,54 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { cn } from '@lumina/island/tools/cn'; +import NextLink from 'next/link'; +import { useTranslation } from 'react-i18next'; + +import { useSignOut } from '../../hooks/use-sign-out'; +import { HOME_ROUTE } from '../../navigation'; +import { SignOutDialog } from '../sign-out-dialog'; +import { AdminIdentity } from './components/AdminIdentity'; +import { NavList } from './components/NavList'; +import type { AdminSidebarProps } from './types'; + +/** + * The admin's sidebar (DS AdminAside), 264px at the inline start from 1024px up (0063): the brand + * with «پنل ادمین», the sections with what waits in each, «به‌زودی», and the signed-in admin. + * Counts and the admin read in the browser; the rest renders on the server. + */ +export function AdminSidebar({ className }: AdminSidebarProps) { + const { t } = useTranslation(); + const signOut = useSignOut(); + + return ( + + + + {t('app.brand')} + + + {t('app.panel')} + + + + + + + ); +} diff --git a/platforms/garden-roof/src/app/navigation/components/admin-sidebar/components/AdminIdentity.tsx b/platforms/garden-roof/src/app/navigation/components/admin-sidebar/components/AdminIdentity.tsx new file mode 100644 index 0000000..077510e --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/components/admin-sidebar/components/AdminIdentity.tsx @@ -0,0 +1,54 @@ +'use client'; + +import { Avatar } from '@lumina/island/atoms/avatar'; +import { Button } from '@lumina/island/atoms/button'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Skeleton } from '@lumina/island/atoms/skeleton'; +import { Typography } from '@lumina/island/atoms/typography'; +import { useTranslation } from 'react-i18next'; + +import { useCurrentAdmin } from '../../../../../stores/auth'; +import type { AdminIdentityProps } from '../types'; +import { Element } from '@lumina/island/primitives/element'; + +/** The signed-in admin at the sidebar's foot (DS `lm-aside__me`), with «خروج از حساب». */ +export function AdminIdentity({ onSignOut }: AdminIdentityProps) { + const { t } = useTranslation(); + const admin = useCurrentAdmin(); + + return ( + + {admin ? ( + <> + + + + {admin.displayName} + + + + @{admin.username} + + + + + } + > + setIsOpen(false)} /> + + + + ); +} diff --git a/platforms/garden-roof/src/app/navigation/components/admin-top-bar/index.ts b/platforms/garden-roof/src/app/navigation/components/admin-top-bar/index.ts new file mode 100644 index 0000000..012bf07 --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/components/admin-top-bar/index.ts @@ -0,0 +1,2 @@ +export { AdminTopBar } from './AdminTopBar'; +export type { AdminTopBarProps } from './types'; diff --git a/platforms/garden-roof/src/app/navigation/components/admin-top-bar/types.ts b/platforms/garden-roof/src/app/navigation/components/admin-top-bar/types.ts new file mode 100644 index 0000000..5b59f0a --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/components/admin-top-bar/types.ts @@ -0,0 +1 @@ +export type AdminTopBarProps = { className?: string }; diff --git a/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/SignOutDialog.tsx b/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/SignOutDialog.tsx new file mode 100644 index 0000000..be673e2 --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/SignOutDialog.tsx @@ -0,0 +1,37 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { Modal } from '@lumina/island/molecules/modal'; +import { useTranslation } from 'react-i18next'; + +import type { SignOutDialogProps } from './types'; + +/** «از پنل ادمین خارج می‌شوید؟», with the sign-out first and the cancel under it. */ +export function SignOutDialog({ signOut }: SignOutDialogProps) { + const { t } = useTranslation(); + + return ( + + + + + } + > + {t('sign-out.description')} + + ); +} diff --git a/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/index.ts b/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/index.ts new file mode 100644 index 0000000..4da7b31 --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/index.ts @@ -0,0 +1,2 @@ +export { SignOutDialog } from './SignOutDialog'; +export type { SignOutDialogProps } from './types'; diff --git a/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/types.ts b/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/types.ts new file mode 100644 index 0000000..e1b02ba --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/components/sign-out-dialog/types.ts @@ -0,0 +1,3 @@ +import type { SignOut } from '../../hooks/use-sign-out'; + +export type SignOutDialogProps = { signOut: SignOut }; diff --git a/platforms/garden-roof/src/app/navigation/constants.ts b/platforms/garden-roof/src/app/navigation/constants.ts new file mode 100644 index 0000000..1c98289 --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/constants.ts @@ -0,0 +1,20 @@ +import type { NavItem, SoonItem } from './types'; + +/** The DS AdminAside: section, icon; the label is `common:nav.
`. */ +export const NAV_ITEMS: readonly NavItem[] = [ + { section: 'health', icon: 'dashboard' }, + { section: 'verify', icon: 'shield-check' }, + { section: 'analysts', icon: 'users' }, + { section: 'codes', icon: 'tag' }, + { section: 'subs', icon: 'receipt' }, + { section: 'preds', icon: 'target' }, + { section: 'payouts', icon: 'wallet' }, + { section: 'featured', icon: 'star' }, +]; + +export const SOON_ITEMS: readonly SoonItem[] = [ + 'users', + 'transactions', + 'moderation', + 'flags', +]; diff --git a/platforms/garden-roof/src/app/navigation/hooks/use-active-section.ts b/platforms/garden-roof/src/app/navigation/hooks/use-active-section.ts new file mode 100644 index 0000000..d618dd6 --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/hooks/use-active-section.ts @@ -0,0 +1,9 @@ +import { usePathname } from 'next/navigation'; + +import { sectionOf } from '../navigation'; +import type { AdminSection } from '../types'; + +/** The sidebar section the current page belongs to. */ +export function useActiveSection(): AdminSection | null { + return sectionOf(usePathname()); +} diff --git a/platforms/garden-roof/src/app/navigation/hooks/use-sign-out.ts b/platforms/garden-roof/src/app/navigation/hooks/use-sign-out.ts new file mode 100644 index 0000000..3aa6850 --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/hooks/use-sign-out.ts @@ -0,0 +1,47 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { logout } from '../../../features/auth'; +import { showActionError } from '../../../shared/utils'; +import { ROUTES } from '../navigation'; + +export type SignOut = { + isConfirming: boolean; + ask: () => void; + cancel: () => void; + confirm: () => void; + isSigningOut: boolean; +}; + +/** + * «خروج از حساب»: asks first, then ends the session and loads the login page afresh, so nothing + * of the session stays in memory. + */ +export function useSignOut(): SignOut { + const { t } = useTranslation(); + const [isConfirming, setIsConfirming] = useState(false); + const [isSigningOut, setIsSigningOut] = useState(false); + + const confirm = async () => { + setIsSigningOut(true); + try { + await logout(); + window.location.assign(ROUTES.login); + } catch (error) { + setIsSigningOut(false); + showActionError(error, { + t, + failedMessage: t('sign-out.failed'), + retry: () => void confirm(), + }); + } + }; + + return { + isConfirming, + ask: () => setIsConfirming(true), + cancel: () => setIsConfirming(false), + confirm: () => void confirm(), + isSigningOut, + }; +} diff --git a/platforms/garden-roof/src/app/navigation/index.ts b/platforms/garden-roof/src/app/navigation/index.ts new file mode 100644 index 0000000..66feddb --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/index.ts @@ -0,0 +1,16 @@ +export { AdminSidebar } from './components/admin-sidebar'; +export type { AdminSidebarProps } from './components/admin-sidebar'; +export { AdminTopBar } from './components/admin-top-bar'; +export type { AdminTopBarProps } from './components/admin-top-bar'; +export { NAV_ITEMS, SOON_ITEMS } from './constants'; +export { useActiveSection } from './hooks/use-active-section'; +export { + HOME_ROUTE, + loginRoute, + RETURN_TO_PARAM, + ROUTES, + safeReturnPath, + SECTION_ROUTES, + sectionOf, +} from './navigation'; +export type { AdminSection, CountedSection, NavItem, SoonItem } from './types'; diff --git a/platforms/garden-roof/src/app/navigation/navigation.ts b/platforms/garden-roof/src/app/navigation/navigation.ts new file mode 100644 index 0000000..93fa451 --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/navigation.ts @@ -0,0 +1,57 @@ +import type { AdminSection } from './types'; + +/** Every admin route. Lists keep their filters, search and page in the query string. */ +export const ROUTES = { + login: '/login', + health: '/health', + healthSecondary: '/health/secondary', + verifications: '/verifications', + verification: (id: string) => `/verifications/${encodeURIComponent(id)}`, + analysts: '/analysts', + analyst: (id: string) => `/analysts/${encodeURIComponent(id)}`, + codes: '/invite-codes', + capacityRequests: '/invite-codes/requests', + subscriptions: '/subscriptions', + predictions: '/predictions', + payouts: '/payouts', + featured: '/featured', +} as const; + +/** Where a signed-in admin lands, and where «بازگشت» goes when nothing else fits. */ +export const HOME_ROUTE = ROUTES.health; + +/** The query parameter that carries the page to return to after login. */ +export const RETURN_TO_PARAM = 'returnTo'; + +/** `/login?returnTo=…`, with the page to come back to. */ +export function loginRoute(returnTo?: string): string { + if (!returnTo || returnTo === ROUTES.login) return ROUTES.login; + return `${ROUTES.login}?${RETURN_TO_PARAM}=${encodeURIComponent(returnTo)}`; +} + +/** A return path from the URL, kept on this site only. */ +export function safeReturnPath(value: string | null): string { + if (!value || !value.startsWith('/') || value.startsWith('//')) { + return HOME_ROUTE; + } + return value; +} + +/** Each sidebar section's root; a section is active on its root and every path under it. */ +export const SECTION_ROUTES: Record = { + health: ROUTES.health, + verify: ROUTES.verifications, + analysts: ROUTES.analysts, + codes: ROUTES.codes, + subs: ROUTES.subscriptions, + preds: ROUTES.predictions, + payouts: ROUTES.payouts, + featured: ROUTES.featured, +}; + +export function sectionOf(pathname: string): AdminSection | null { + const match = ( + Object.entries(SECTION_ROUTES) as [AdminSection, string][] + ).find(([, root]) => pathname === root || pathname.startsWith(`${root}/`)); + return match ? match[0] : null; +} diff --git a/platforms/garden-roof/src/app/navigation/types.ts b/platforms/garden-roof/src/app/navigation/types.ts new file mode 100644 index 0000000..fe1cbcc --- /dev/null +++ b/platforms/garden-roof/src/app/navigation/types.ts @@ -0,0 +1,23 @@ +import type { IconName } from '@lumina/island/atoms/icon'; + +/** The sidebar's sections, in the order the DS AdminAside lists them. */ +export type AdminSection = + | 'health' + | 'verify' + | 'analysts' + | 'codes' + | 'subs' + | 'preds' + | 'payouts' + | 'featured'; + +/** Sections whose sidebar link shows what waits there. */ +export type CountedSection = 'verify' | 'codes' | 'preds' | 'payouts'; + +export type NavItem = { + section: AdminSection; + icon: IconName; +}; + +/** Sections drawn under «به‌زودی», not yet links. */ +export type SoonItem = 'users' | 'transactions' | 'moderation' | 'flags'; diff --git a/platforms/garden-roof/src/app/screens/index.ts b/platforms/garden-roof/src/app/screens/index.ts new file mode 100644 index 0000000..790f28f --- /dev/null +++ b/platforms/garden-roof/src/app/screens/index.ts @@ -0,0 +1,7 @@ +export { AuditLog } from './organisms/audit-log'; +export type { AuditLogProps } from './organisms/audit-log'; +export { ReasonDialog } from './organisms/reason-dialog'; +export type { + ReasonDialogProps, + ReasonTemplate, +} from './organisms/reason-dialog'; diff --git a/platforms/garden-roof/src/app/screens/organisms/audit-log/AuditLog.tsx b/platforms/garden-roof/src/app/screens/organisms/audit-log/AuditLog.tsx new file mode 100644 index 0000000..9b0c57f --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/audit-log/AuditLog.tsx @@ -0,0 +1,86 @@ +'use client'; + +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Icon } from '@lumina/island/atoms/icon'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Card } from '@lumina/island/molecules/card'; +import { Timeline } from '@lumina/island/molecules/timeline'; +import { Element } from '@lumina/island/primitives/element'; +import { cn } from '@lumina/island/tools/cn'; +import { useId, useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { AuditEntry } from './components/AuditEntry'; +import type { AuditLogProps } from './types'; + +/** + * «گزارش ممیزی»: the permanent, read-only log of an item's admin actions (J11 §0.5), oldest first, + * with a lock that says it can't be edited. Collapsible where the board folds it. + */ +export function AuditLog({ + entries, + collapsible = false, + emptyText, + framed = true, + className, +}: AuditLogProps) { + const { t } = useTranslation(); + const [isOpen, setIsOpen] = useState(!collapsible); + const bodyId = useId(); + + const heading = ( + + + {t('audit.title')} + + + + ); + + const body = ( + + {collapsible ? ( + setIsOpen((open) => !open)} + alignItems="items-center" + justifyContent="justify-between" + className="w-full cursor-pointer rounded-md text-start focus-visible:focus-ring" + > + {heading} + + + ) : ( + heading + )} + + + ); + + return framed ? ( + + {body} + + ) : ( + body + ); +} diff --git a/platforms/garden-roof/src/app/screens/organisms/audit-log/components/AuditEntry.tsx b/platforms/garden-roof/src/app/screens/organisms/audit-log/components/AuditEntry.tsx new file mode 100644 index 0000000..c8bfc68 --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/audit-log/components/AuditEntry.tsx @@ -0,0 +1,52 @@ +'use client'; + +import { TimelineItem } from '@lumina/island/molecules/timeline'; +import { date, exactDuration, number } from '@lumina/tools/format'; +import { useTranslation } from 'react-i18next'; + +import { AUDIT_DESCRIPTIONS, AUDIT_STYLES } from '../constants'; +import type { AuditEntryProps } from '../types'; +import { auditTitle } from '../utils'; + +/** One audit row: what happened, why, and when · by whom · how many it touched. */ +export function AuditEntry({ entry }: AuditEntryProps) { + const { t } = useTranslation(); + const style = AUDIT_STYLES[entry.action]; + const extension = + entry.extensionMinutes !== null + ? t('audit.extension', { + duration: exactDuration(entry.extensionMinutes), + }) + : null; + const meta = [ + date(entry.at), + entry.actorName ?? t('audit.system'), + entry.affectedCount !== null + ? t('audit.affected', { + count: entry.affectedCount, + formatted: number(entry.affectedCount), + }) + : null, + ].filter(Boolean); + + const title = auditTitle(entry, t); + // Whom the row was about (the analysts a featured save added, moved or removed, J11-10), then why + // or, without a reason, the action's fixed line (what a new payout sent, J11-9f). + const description = + entry.action in AUDIT_DESCRIPTIONS + ? t(AUDIT_DESCRIPTIONS[entry.action]!) + : null; + const body = [entry.analystNames, entry.reason ?? description, extension] + .filter(Boolean) + .join(' · '); + + return ( + + ); +} diff --git a/platforms/garden-roof/src/app/screens/organisms/audit-log/constants.ts b/platforms/garden-roof/src/app/screens/organisms/audit-log/constants.ts new file mode 100644 index 0000000..c86e2c7 --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/audit-log/constants.ts @@ -0,0 +1,43 @@ +import type { IconName } from '@lumina/island/atoms/icon'; +import type { TimelineTone } from '@lumina/island/molecules/timeline'; + +import type { AuditAction } from '../../../../features/audit'; + +/** How each kind of audit row reads in the timeline: the dot's tone and icon. */ +export const AUDIT_STYLES: Record< + AuditAction, + { tone: TimelineTone; icon: IconName } +> = { + 'verification.approved': { tone: 'brand', icon: 'check' }, + 'verification.rejected': { tone: 'danger', icon: 'alert' }, + 'account.suspended': { tone: 'danger', icon: 'ban' }, + 'account.reinstated': { tone: 'success', icon: 'check' }, + 'code.created': { tone: 'brand', icon: 'tag' }, + 'code.capacity_changed': { tone: 'neutral', icon: 'edit' }, + 'code.deactivated': { tone: 'danger', icon: 'ban' }, + 'code.activated': { tone: 'success', icon: 'check' }, + 'capacity_request.approved': { tone: 'success', icon: 'check' }, + 'capacity_request.rejected': { tone: 'danger', icon: 'x-circle' }, + 'subscription.extended': { tone: 'brand', icon: 'calendar' }, + 'subscription.refunded': { tone: 'danger', icon: 'receipt' }, + 'subscription.granted': { tone: 'brand', icon: 'plus' }, + 'prediction.resolved': { tone: 'success', icon: 'check' }, + 'prediction.proposal_dismissed': { tone: 'neutral', icon: 'x-circle' }, + 'prediction.overridden': { tone: 'warning', icon: 'shield-check' }, + 'prediction.flagged': { tone: 'warning', icon: 'flag' }, + 'prediction.unflagged': { tone: 'neutral', icon: 'flag' }, + 'payout.created': { tone: 'brand', icon: 'wallet' }, + 'payout.paid': { tone: 'success', icon: 'check' }, + 'payout.cancelled': { tone: 'danger', icon: 'x-circle' }, + 'ledger.corrected': { tone: 'neutral', icon: 'edit' }, + 'featured.added': { tone: 'brand', icon: 'star' }, + 'featured.removed': { tone: 'danger', icon: 'trash' }, + 'featured.reordered': { tone: 'neutral', icon: 'grip' }, +}; + +/** Fixed lines some actions show when the row has no reason, under `common:audit.descriptions`. */ +export const AUDIT_DESCRIPTIONS: Partial< + Record +> = { + 'payout.created': 'audit.descriptions.payout-created', +}; diff --git a/platforms/garden-roof/src/app/screens/organisms/audit-log/index.ts b/platforms/garden-roof/src/app/screens/organisms/audit-log/index.ts new file mode 100644 index 0000000..a757209 --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/audit-log/index.ts @@ -0,0 +1,2 @@ +export { AuditLog } from './AuditLog'; +export type { AuditLogProps } from './types'; diff --git a/platforms/garden-roof/src/app/screens/organisms/audit-log/types.ts b/platforms/garden-roof/src/app/screens/organisms/audit-log/types.ts new file mode 100644 index 0000000..13c74dd --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/audit-log/types.ts @@ -0,0 +1,18 @@ +import type { AuditEntryPayload } from '../../../../features/audit'; + +export type AuditLogProps = { + /** Oldest first, as the API answers them. */ + entries: readonly AuditEntryPayload[]; + /** + * Starts folded under its title, as the featured page draws it (J11-10); open by default + * elsewhere. + */ + collapsible?: boolean; + /** What an empty log says, such as «هنوز اقدامی روی این اشتراک ثبت نشده است.»; a generic line by default. */ + emptyText?: string; + /** In its own card on a page (default); `false` inside a sheet, where the board draws a plain section. */ + framed?: boolean; + className?: string; +}; + +export type AuditEntryProps = { entry: AuditEntryPayload }; diff --git a/platforms/garden-roof/src/app/screens/organisms/audit-log/utils.ts b/platforms/garden-roof/src/app/screens/organisms/audit-log/utils.ts new file mode 100644 index 0000000..177c989 --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/audit-log/utils.ts @@ -0,0 +1,36 @@ +import { number } from '@lumina/tools/format'; +import type { TFunction } from 'i18next'; + +import type { AuditEntryPayload } from '../../../../features/audit'; + +/** + * A row's title, naming its figure where the board does: «افزایش ظرفیت از ۲۰ به ۴۰» (J11-6g), + * «بازگشت وجه ۵۴۰٬۰۰۰ تومان» (J11-7f), «تمدید ۷ روزه» (J11-7d); the action's title otherwise. + */ +export function auditTitle(entry: AuditEntryPayload, t: TFunction): string { + if (entry.fromMaxUses !== null && entry.toMaxUses !== null) { + return t( + entry.toMaxUses > entry.fromMaxUses + ? 'audit.capacity-up' + : 'audit.capacity-down', + { + from: number(entry.fromMaxUses), + to: number(entry.toMaxUses), + }, + ); + } + if (entry.action === 'subscription.refunded' && entry.amount !== null) { + return t('audit.refund-amount', { amount: number(entry.amount) }); + } + if ( + entry.action === 'prediction.overridden' && + entry.toPrice !== null && + entry.fromPrice === null + ) { + return t('audit.closed-by-admin'); + } + if (entry.action === 'subscription.extended' && entry.days !== null) { + return t('audit.extend-days', { days: number(entry.days) }); + } + return t(`audit.actions.${entry.action}`); +} diff --git a/platforms/garden-roof/src/app/screens/organisms/reason-dialog/ReasonDialog.tsx b/platforms/garden-roof/src/app/screens/organisms/reason-dialog/ReasonDialog.tsx new file mode 100644 index 0000000..09ee406 --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/reason-dialog/ReasonDialog.tsx @@ -0,0 +1,149 @@ +'use client'; + +import { Button } from '@lumina/island/atoms/button'; +import { Chip } from '@lumina/island/atoms/chip'; +import { FlexBox } from '@lumina/island/atoms/flex-box'; +import { Typography } from '@lumina/island/atoms/typography'; +import { Modal } from '@lumina/island/molecules/modal'; +import { TextInput } from '@lumina/island/molecules/text-input'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { useWatch } from 'react-hook-form'; + +import { translateMessage } from '../../../../shared/utils'; +import { REASON_MAX_LENGTH } from '../../../../shared/validations'; +import type { ReasonDialogProps } from './types'; + +const OTHER = 'other'; + +/** + * Every admin action that changes access or money asks «دلیل» here (J11 §0.5): trimmed, 10 + * characters at least, written to «گزارش ممیزی». A template chip fills editable text, another + * replaces it and «سایر» clears it. While the request runs the dialog can't be closed; when it + * fails the dialog stays with the text and the chip as they were, and confirm retries. + */ +export function ReasonDialog({ + open, + onClose, + title, + description, + children, + templates, + fieldLabel, + placeholder, + hint, + templatesLabel, + emptyReason, + form, + onSubmit, + isSubmitting, + confirmLabel, + confirmVariant = 'danger-solid', +}: ReasonDialogProps) { + const { t } = useTranslation(); + const [chip, setChip] = useState(null); + const { errors } = form.formState; + // Controlled, so a template's text shows in the field and its count at once. + const reason = useWatch({ control: form.control, name: 'reason' }); + const isEmpty = reason.trim() === ''; + + const pick = (id: string, text: string) => { + setChip(id); + form.setValue('reason', text, { + shouldValidate: errors.reason !== undefined, + }); + form.setFocus('reason'); + }; + + const submit = form.handleSubmit(({ reason }) => onSubmit(reason)); + + return ( + { + setChip(null); + form.reset(); + }} + title={title} + actions={ + <> + + + + } + > + + {description} + {children} + + {templates && templates.length > 0 && ( + + + {templatesLabel ?? t('reason.label')} + + + {templates.map((template) => ( + pick(template.id, template.text)} + > + {template.label} + + ))} + pick(OTHER, '')} + > + {t('reason.other')} + + + + )} + + + ); +} diff --git a/platforms/garden-roof/src/app/screens/organisms/reason-dialog/index.ts b/platforms/garden-roof/src/app/screens/organisms/reason-dialog/index.ts new file mode 100644 index 0000000..c8619d5 --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/reason-dialog/index.ts @@ -0,0 +1,2 @@ +export { ReasonDialog } from './ReasonDialog'; +export type { ReasonDialogProps, ReasonTemplate } from './types'; diff --git a/platforms/garden-roof/src/app/screens/organisms/reason-dialog/types.ts b/platforms/garden-roof/src/app/screens/organisms/reason-dialog/types.ts new file mode 100644 index 0000000..6cccb4b --- /dev/null +++ b/platforms/garden-roof/src/app/screens/organisms/reason-dialog/types.ts @@ -0,0 +1,41 @@ +import type { ReactNode } from 'react'; + +import type { ReasonForm } from '../../../../shared/utils'; + +/** A ready reason: its chip, and the editable text it fills in. */ +export type ReasonTemplate = { id: string; label: string; text: string }; + +export type ReasonDialogProps = { + open: boolean; + onClose: () => void; + title: ReactNode; + /** What the action does, above the field, such as the subscribers it touches. */ + description?: ReactNode; + /** Anything between the description and the field, such as an impact banner. */ + children?: ReactNode; + /** + * Chips that fill the field with editable text; another chip replaces it and «سایر» clears it + * (J11-3k). Without them, only the field shows. + */ + templates?: readonly ReasonTemplate[]; + /** The field's label; «دلیل» by default. */ + fieldLabel?: string; + placeholder?: string; + /** + * Under the field: who reads the reason. «حداقل ۱۰ نویسه؛ فقط ادمین‌ها آن را می‌بینند…» by + * default; pass `common:reason.hint-analyst` (or the section's own) when the analyst gets it. + */ + hint?: string; + /** The chips' caption, such as «انتخاب دلیل پیش‌فرض». */ + templatesLabel?: string; + /** Why confirm waits while the field is empty, such as «ابتدا دلیل رد درخواست را بنویسید.». */ + emptyReason: string; + /** The model's reason form; it keeps the text when the request fails. */ + form: ReasonForm; + /** Runs with the trimmed reason once the form is valid. */ + onSubmit: (reason: string) => void; + isSubmitting: boolean; + confirmLabel: string; + /** `danger-solid` (default) for a refusal, a suspension or a cancel; `primary` otherwise. */ + confirmVariant?: 'danger-solid' | 'primary'; +}; diff --git a/platforms/garden-roof/src/env/env.ts b/platforms/garden-roof/src/env/env.ts new file mode 100644 index 0000000..b8c78f8 --- /dev/null +++ b/platforms/garden-roof/src/env/env.ts @@ -0,0 +1,18 @@ +import type { GardenRoofEnv } from './types'; + +let gardenRoofEnv: GardenRoofEnv | undefined; + +/** Called by the app bootstrap, on the server and in the browser. Idempotent. */ +export function setEnv(env: GardenRoofEnv): void { + gardenRoofEnv = env; +} + +/** Read inside functions, never at module top level: bootstrap may not have run yet. */ +export function getEnv(): Readonly { + if (!gardenRoofEnv) { + throw new Error( + 'garden-roof env is not set. The app bootstrap must call setEnv from @lumina/garden-roof/env first.', + ); + } + return gardenRoofEnv; +} diff --git a/platforms/garden-roof/src/env/index.ts b/platforms/garden-roof/src/env/index.ts new file mode 100644 index 0000000..f4b1ad5 --- /dev/null +++ b/platforms/garden-roof/src/env/index.ts @@ -0,0 +1,2 @@ +export { getEnv, setEnv } from './env'; +export type { GardenRoofEnv } from './types'; diff --git a/platforms/garden-roof/src/env/types.ts b/platforms/garden-roof/src/env/types.ts new file mode 100644 index 0000000..fea0e36 --- /dev/null +++ b/platforms/garden-roof/src/env/types.ts @@ -0,0 +1,8 @@ +/** The platform's own settings, named for what they are, not for the variables behind them. */ +export type GardenRoofEnv = { + /** + * Where the browser loads the admin API from: a path on this site (`/api`) that the app proxies + * to `admin-api` (0061). For what the browser loads itself, such as ID card images. + */ + apiBaseUrl: string; +}; diff --git a/platforms/garden-roof/src/features/analysts/actions/reinstate-analyst/actions.ts b/platforms/garden-roof/src/features/analysts/actions/reinstate-analyst/actions.ts new file mode 100644 index 0000000..ce50a26 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/actions/reinstate-analyst/actions.ts @@ -0,0 +1,29 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { ANALYST_EVENTS } from '../../constants'; +import { analystsRepository } from '../../repositories/analysts'; +import type { + ReinstateAnalystArgs, + ReinstatePayload, +} from '../../repositories/analysts'; + +/** + * «بله، رفع تعلیق» (J11-5e): access comes back and the analyst gets an SMS; every eligible + * subscription (not refunded, not lapsed) runs longer by the suspended time, to the minute, and + * its subscriber is told the new expiry. Takes a «دلیل» like every access change (§0.5). + * Emits `analyst.reinstated`. + */ +export async function reinstateAnalyst( + args: ReinstateAnalystArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await analystsRepository.reinstate(args); + if (emit) { + eventEmitter.emit(ANALYST_EVENTS.reinstated, { + id: args.id, + extendedCount: result.extendedCount, + extensionMinutes: result.extensionMinutes, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/analysts/actions/reinstate-analyst/index.ts b/platforms/garden-roof/src/features/analysts/actions/reinstate-analyst/index.ts new file mode 100644 index 0000000..ac1c3f8 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/actions/reinstate-analyst/index.ts @@ -0,0 +1 @@ +export { reinstateAnalyst } from './actions'; diff --git a/platforms/garden-roof/src/features/analysts/actions/suspend-analyst/actions.ts b/platforms/garden-roof/src/features/analysts/actions/suspend-analyst/actions.ts new file mode 100644 index 0000000..24cfca4 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/actions/suspend-analyst/actions.ts @@ -0,0 +1,27 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { ANALYST_EVENTS } from '../../constants'; +import { analystsRepository } from '../../repositories/analysts'; +import type { + SuspendAnalystArgs, + SuspendPayload, +} from '../../repositories/analysts'; + +/** + * «تعلیق و اطلاع‌رسانی» (J11-5): the account is تعلیق‌شده at once and logged; the analyst gets the + * reason in-app and by SMS, their active subscribers are told without it, and the subscriptions + * keep running while the suspended time is tracked. Emits `analyst.suspended`. + */ +export async function suspendAnalyst( + args: SuspendAnalystArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await analystsRepository.suspend(args); + if (emit) { + eventEmitter.emit(ANALYST_EVENTS.suspended, { + id: args.id, + affectedCount: result.affectedCount, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/analysts/actions/suspend-analyst/index.ts b/platforms/garden-roof/src/features/analysts/actions/suspend-analyst/index.ts new file mode 100644 index 0000000..ed461e1 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/actions/suspend-analyst/index.ts @@ -0,0 +1 @@ +export { suspendAnalyst } from './actions'; diff --git a/platforms/garden-roof/src/features/analysts/constants.ts b/platforms/garden-roof/src/features/analysts/constants.ts new file mode 100644 index 0000000..6af468f --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/constants.ts @@ -0,0 +1,22 @@ +/** Events the account actions emit when they succeed. */ +export const ANALYST_EVENTS = { + suspended: 'analyst.suspended', + reinstated: 'analyst.reinstated', +} as const; + +/** + * The suspend dialog's ready reasons (J11-5b): each chip fills editable text from + * `analysts:suspend.templates.`; «سایر» clears the field. + */ +export const SUSPEND_TEMPLATES = [ + 'rules', + 'content', + 'report', + 'admin-error', +] as const; + +/** The URL's query parameters on the analysts list. */ +export const ANALYST_PARAMS = { + q: 'q', + page: 'page', +} as const; diff --git a/platforms/garden-roof/src/features/analysts/entities/analyst/index.ts b/platforms/garden-roof/src/features/analysts/entities/analyst/index.ts new file mode 100644 index 0000000..dfb1e84 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/entities/analyst/index.ts @@ -0,0 +1 @@ +export type { AnalystDetailEntity, AnalystListItemEntity } from './types'; diff --git a/platforms/garden-roof/src/features/analysts/entities/analyst/types.ts b/platforms/garden-roof/src/features/analysts/entities/analyst/types.ts new file mode 100644 index 0000000..afeeed2 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/entities/analyst/types.ts @@ -0,0 +1,37 @@ +import type { AuditEntryEntity } from '../../../audit'; +import type { AccountStatus, VerificationStatus } from '../../../verification'; + +/** + * A row of «مدیریت تحلیلگران» (`GET /admin/analysts`): every analyst account, whatever its + * verification. Verification and account states are independent (J11-4: @kaveh_usdt is pending + * and suspended). + */ +export type AnalystListItemEntity = { + /** The creator's user id. */ + id: string; + /** '' when the account has none. */ + firstName: string; + /** '' when the account has none; the channel's display name stands in when the account has no last name at all. */ + lastName: string; + username: string; + /** E.164; '' when the account can't be read. */ + phone: string; + /** API-relative (`/uploads/avatars/…`) or a legacy absolute address. */ + avatarUrl: string | null; + verificationStatus: VerificationStatus; + /** تعلیق‌شده when the account or the channel is suspended. */ + accountStatus: AccountStatus; + /** + * When the channel's suspension started: reinstating extends running subscriptions by the time + * since. `null` while active and for an account-only suspension (a pending or rejected analyst + * has no channel), which extends nothing. + */ + suspendedAt: string | null; + /** Active subscriptions now, paid or granted («مشترک فعال»). */ + activeSubscriptions: number; +}; + +/** One analyst (`GET /admin/analysts/:id`), with «گزارش ممیزی» oldest first. */ +export type AnalystDetailEntity = AnalystListItemEntity & { + audit: AuditEntryEntity[]; +}; diff --git a/platforms/garden-roof/src/features/analysts/http.ts b/platforms/garden-roof/src/features/analysts/http.ts new file mode 100644 index 0000000..85049e3 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const analystsHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/analysts/index.ts b/platforms/garden-roof/src/features/analysts/index.ts new file mode 100644 index 0000000..b692023 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/index.ts @@ -0,0 +1,35 @@ +import './types'; + +export { reinstateAnalyst } from './actions/reinstate-analyst'; +export { suspendAnalyst } from './actions/suspend-analyst'; +export { ANALYST_EVENTS, ANALYST_PARAMS, SUSPEND_TEMPLATES } from './constants'; +export type { + AnalystDetailEntity, + AnalystListItemEntity, +} from './entities/analyst'; +export { useAnalystAccount } from './models/account'; +export type { + AccountDialog, + AccountTarget, + AnalystAccountModel, +} from './models/account'; +export { useAnalystDetailPage } from './models/detail'; +export type { AnalystDetailPageModel } from './models/detail'; +export { useAnalystListPart, useAnalystsPage } from './models/list'; +export type { AnalystListPartModel, AnalystsPageModel } from './models/list'; +export { + ANALYST_ENDPOINTS, + ANALYST_ERROR_CODES, + analystKeys, + analystsRepository, +} from './repositories/analysts'; +export type { + AnalystDetailPayload, + AnalystListItemPayload, + AnalystPagePayload, + ListAnalystsArgs, + ReinstateAnalystArgs, + ReinstatePayload, + SuspendAnalystArgs, + SuspendPayload, +} from './repositories/analysts'; diff --git a/platforms/garden-roof/src/features/analysts/models/account/index.ts b/platforms/garden-roof/src/features/analysts/models/account/index.ts new file mode 100644 index 0000000..5c416c1 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/account/index.ts @@ -0,0 +1,6 @@ +export { useAnalystAccount } from './use-analyst-account'; +export type { + AccountDialog, + AccountTarget, + AnalystAccountModel, +} from './types'; diff --git a/platforms/garden-roof/src/features/analysts/models/account/types.ts b/platforms/garden-roof/src/features/analysts/models/account/types.ts new file mode 100644 index 0000000..6ee7214 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/account/types.ts @@ -0,0 +1,45 @@ +import type { ReasonForm } from '../../../../shared/utils'; +import type { AnalystListItemPayload } from '../../repositories/analysts'; + +/** The analyst an account action is about: a list row or the detail page's analyst. */ +export type AccountTarget = Pick< + AnalystListItemPayload, + | 'id' + | 'fullName' + | 'username' + | 'accountStatus' + | 'activeSubscriptions' + | 'suspendedAt' +>; + +/** + * Which account dialog shows, and for whom. `open` turns false while it animates out, so its text + * stays until it's gone. The reinstate dialog carries the extension it announces, as of opening it: + * only a suspended channel (`suspendedAt`) extends, its active subscriptions by the suspended time + * to the minute; an account-only suspension extends none, by 0. + */ +export type AccountDialog = + | { kind: 'suspend'; target: AccountTarget; open: boolean } + | { + kind: 'reinstate'; + target: AccountTarget; + extendedCount: number; + extensionMinutes: number; + open: boolean; + } + | null; + +export type AnalystAccountModel = { + dialog: AccountDialog; + /** «تعلیق حساب»: only for an active account. */ + openSuspend: (target: AccountTarget) => void; + /** «رفع تعلیق»: only for a suspended one. */ + openReinstate: (target: AccountTarget) => void; + closeDialog: () => void; + suspendForm: ReasonForm; + confirmSuspend: (reason: string) => void; + isSuspending: boolean; + reinstateForm: ReasonForm; + confirmReinstate: (reason: string) => void; + isReinstating: boolean; +}; diff --git a/platforms/garden-roof/src/features/analysts/models/account/use-analyst-account.ts b/platforms/garden-roof/src/features/analysts/models/account/use-analyst-account.ts new file mode 100644 index 0000000..434f3d2 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/account/use-analyst-account.ts @@ -0,0 +1,150 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { number } from '@lumina/tools/format'; +import { useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { applyServerErrors, useReasonForm } from '../../../../shared/utils'; +import { panelKeys } from '../../../panel'; +import { verificationKeys } from '../../../verification'; +import { reinstateAnalyst } from '../../actions/reinstate-analyst'; +import { suspendAnalyst } from '../../actions/suspend-analyst'; +import { ANALYST_ERROR_CODES, analystKeys } from '../../repositories/analysts'; +import type { + AccountDialog, + AccountTarget, + AnalystAccountModel, +} from './types'; + +const MINUTE_MS = 60_000; + +const CONFLICTS: readonly string[] = [ + ANALYST_ERROR_CODES.alreadySuspended, + ANALYST_ERROR_CODES.notSuspended, +]; + +/** + * «تعلیق حساب» and «رفع تعلیق» (J11-5), from a list row or the detail header: one dialog at a time, + * each asking a «دلیل». Done, it toasts with the board's count, closes, and the row or the page + * updates in place, as do the verification pages that show the account and the sidebar counts. A + * failed action keeps the dialog with its text (a refused reason under the field) and confirm + * retries; an account changed elsewhere (409) closes it and reloads. + */ +export function useAnalystAccount(): AnalystAccountModel { + const { t } = useTranslation('analysts'); + const queryClient = useQueryClient(); + const [dialog, setDialog] = useState(null); + const [isSuspending, setIsSuspending] = useState(false); + const [isReinstating, setIsReinstating] = useState(false); + const suspendForm = useReasonForm(); + const reinstateForm = useReasonForm(); + + const closeDialog = () => + setDialog((current) => (current ? { ...current, open: false } : current)); + + const refresh = () => + Promise.all([ + queryClient.invalidateQueries({ queryKey: analystKeys.all }), + queryClient.invalidateQueries({ queryKey: verificationKeys.all }), + queryClient.invalidateQueries({ queryKey: panelKeys.counts() }), + ]); + + const refused = async (error: unknown): Promise => { + if (!isHttpError(error) || !CONFLICTS.includes(error.code)) return false; + closeDialog(); + showToast({ tone: 'info', message: t('account.changed') }); + await refresh(); + return true; + }; + + const confirmSuspend = async (target: AccountTarget, reason: string) => { + if (isSuspending) return; + setIsSuspending(true); + try { + const { affectedCount } = await suspendAnalyst({ id: target.id, reason }); + showToast({ + tone: 'success', + message: + affectedCount > 0 + ? t('suspend.done', { subscribers: number(affectedCount) }) + : t('suspend.done-none'), + }); + closeDialog(); + await refresh(); + } catch (error) { + if (!(await refused(error))) { + applyServerErrors(suspendForm, error, { + t, + failedMessage: t('suspend.failed'), + retry: () => void confirmSuspend(target, reason), + }); + } + } finally { + setIsSuspending(false); + } + }; + + const confirmReinstate = async (target: AccountTarget, reason: string) => { + if (isReinstating) return; + setIsReinstating(true); + try { + const { extendedCount } = await reinstateAnalyst({ + id: target.id, + reason, + }); + showToast({ + tone: 'success', + message: + extendedCount > 0 + ? t('reinstate.done', { subscriptions: number(extendedCount) }) + : t('reinstate.done-none'), + }); + closeDialog(); + await refresh(); + } catch (error) { + if (!(await refused(error))) { + applyServerErrors(reinstateForm, error, { + t, + failedMessage: t('reinstate.failed'), + retry: () => void confirmReinstate(target, reason), + }); + } + } finally { + setIsReinstating(false); + } + }; + + return { + dialog, + openSuspend: (target) => setDialog({ kind: 'suspend', target, open: true }), + openReinstate: (target) => + setDialog({ + kind: 'reinstate', + target, + extendedCount: target.suspendedAt ? target.activeSubscriptions : 0, + extensionMinutes: target.suspendedAt + ? Math.max( + 0, + Math.round( + (Date.now() - Date.parse(target.suspendedAt)) / MINUTE_MS, + ), + ) + : 0, + open: true, + }), + closeDialog, + suspendForm, + confirmSuspend: (reason) => { + if (dialog?.kind === 'suspend') + void confirmSuspend(dialog.target, reason); + }, + isSuspending, + reinstateForm, + confirmReinstate: (reason) => { + if (dialog?.kind === 'reinstate') + void confirmReinstate(dialog.target, reason); + }, + isReinstating, + }; +} diff --git a/platforms/garden-roof/src/features/analysts/models/detail/index.ts b/platforms/garden-roof/src/features/analysts/models/detail/index.ts new file mode 100644 index 0000000..b290dac --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/detail/index.ts @@ -0,0 +1,2 @@ +export { useAnalystDetailPage } from './use-analyst-detail-page'; +export type { AnalystDetailPageModel } from './types'; diff --git a/platforms/garden-roof/src/features/analysts/models/detail/types.ts b/platforms/garden-roof/src/features/analysts/models/detail/types.ts new file mode 100644 index 0000000..8c5b0b3 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/detail/types.ts @@ -0,0 +1,8 @@ +import type { AnalystDetailPayload } from '../../repositories/analysts'; +import type { AnalystAccountModel } from '../account'; + +export type AnalystDetailPageModel = { + analyst: AnalystDetailPayload; + /** The header's one account action and its dialogs. */ + account: AnalystAccountModel; +}; diff --git a/platforms/garden-roof/src/features/analysts/models/detail/use-analyst-detail-page.ts b/platforms/garden-roof/src/features/analysts/models/detail/use-analyst-detail-page.ts new file mode 100644 index 0000000..37ffde6 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/detail/use-analyst-detail-page.ts @@ -0,0 +1,19 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { analystKeys, analystsRepository } from '../../repositories/analysts'; +import { useAnalystAccount } from '../account'; +import type { AnalystDetailPageModel } from './types'; + +/** + * One analyst (J11-4b): the facts, «گزارش ممیزی» and the header's one account action. After a + * suspension or reinstatement the page reloads in place, with the new row at the log's end. + */ +export function useAnalystDetailPage(id: string): AnalystDetailPageModel { + const { data: analyst } = useSuspenseQuery({ + queryKey: analystKeys.detail(id), + queryFn: ({ signal }) => analystsRepository.get(id, { signal }), + }); + const account = useAnalystAccount(); + + return { analyst, account }; +} diff --git a/platforms/garden-roof/src/features/analysts/models/list/index.ts b/platforms/garden-roof/src/features/analysts/models/list/index.ts new file mode 100644 index 0000000..30bc5b6 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/list/index.ts @@ -0,0 +1,3 @@ +export { useAnalystListPart } from './use-analyst-list-part'; +export { useAnalystsPage } from './use-analysts-page'; +export type { AnalystListPartModel, AnalystsPageModel } from './types'; diff --git a/platforms/garden-roof/src/features/analysts/models/list/types.ts b/platforms/garden-roof/src/features/analysts/models/list/types.ts new file mode 100644 index 0000000..d2c75eb --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/list/types.ts @@ -0,0 +1,30 @@ +import type { ListSearch } from '../../../../shared/utils'; +import type { + AnalystListItemPayload, + ListAnalystsArgs, +} from '../../repositories/analysts'; +import type { AnalystAccountModel } from '../account'; + +export type AnalystsPageModel = { + search: ListSearch; + /** What the list part reads; a change remounts it behind its skeleton. */ + args: ListAnalystsArgs; + /** Changes whenever `args` does: the list part's key. */ + argsKey: string; + /** The rows' account actions; their dialogs sit outside the list part, so a refetch keeps them. */ + account: AnalystAccountModel; +}; + +export type AnalystListPartModel = { + rows: AnalystListItemPayload[]; + page: number; + pageCount: number; + total: number; + from: number; + to: number; + pageHref: (page: number) => string; + /** No row: no analyst yet, or nothing matched the search. */ + empty: 'list' | 'search' | null; + /** The search, for highlighting it in the rows. */ + query: string; +}; diff --git a/platforms/garden-roof/src/features/analysts/models/list/use-analyst-list-part.ts b/platforms/garden-roof/src/features/analysts/models/list/use-analyst-list-part.ts new file mode 100644 index 0000000..dff1ad1 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/list/use-analyst-list-part.ts @@ -0,0 +1,33 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { ANALYST_PARAMS } from '../../constants'; +import { analystKeys, analystsRepository } from '../../repositories/analysts'; +import type { ListAnalystsArgs } from '../../repositories/analysts'; +import type { AnalystListPartModel } from './types'; + +/** The list's rows for the search and page; 20 a page. */ +export function useAnalystListPart( + args: ListAnalystsArgs, +): AnalystListPartModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data } = useSuspenseQuery({ + queryKey: analystKeys.list(args), + queryFn: ({ signal }) => analystsRepository.list(args, { signal }), + }); + + return { + rows: data.items, + page: data.page, + pageCount: data.pageCount, + total: data.total, + from: data.from, + to: data.to, + pageHref: (page) => + listHref(pathname, searchParams, { [ANALYST_PARAMS.page]: page }), + empty: data.total > 0 ? null : args.q ? 'search' : 'list', + query: args.q ?? '', + }; +} diff --git a/platforms/garden-roof/src/features/analysts/models/list/use-analysts-page.ts b/platforms/garden-roof/src/features/analysts/models/list/use-analysts-page.ts new file mode 100644 index 0000000..4961d23 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/models/list/use-analysts-page.ts @@ -0,0 +1,20 @@ +import { useSearchParams } from 'next/navigation'; + +import { pageOf, useListSearch } from '../../../../shared/utils'; +import { ANALYST_PARAMS } from '../../constants'; +import { useAnalystAccount } from '../account'; +import type { AnalystsPageModel } from './types'; + +/** + * مدیریت تحلیلگران (J11-4): every analyst, whatever their verification. The search and the page + * live in the URL, so a reload or back keeps them; a new search starts again from page 1. + */ +export function useAnalystsPage(): AnalystsPageModel { + const searchParams = useSearchParams(); + const search = useListSearch(ANALYST_PARAMS.q); + const page = pageOf(searchParams.get(ANALYST_PARAMS.page)); + const account = useAnalystAccount(); + const args = { q: search.query || undefined, page }; + + return { search, args, argsKey: JSON.stringify(args), account }; +} diff --git a/platforms/garden-roof/src/features/analysts/repositories/analysts/analysts.ts b/platforms/garden-roof/src/features/analysts/repositories/analysts/analysts.ts new file mode 100644 index 0000000..fc540ee --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/repositories/analysts/analysts.ts @@ -0,0 +1,74 @@ +import { analystsHttp } from '../../http'; +import { ANALYST_ENDPOINTS } from './constants'; +import { + toAnalystDetailPayload, + toAnalystPagePayload, + toListAnalystsQueryDto, + toReinstateAnalystDto, + toReinstatePayload, + toSuspendAnalystDto, +} from './mappers'; +import type { + AnalystDetailPayload, + AnalystDetailResponseDto, + AnalystPagePayload, + AnalystPageResponseDto, + ListAnalystsArgs, + ReinstateAnalystArgs, + ReinstatePayload, + ReinstateResponseDto, + SuspendAnalystArgs, + SuspendPayload, + SuspendResponseDto, +} from './types'; + +/** Every analyst account (J11-4) and its two account actions (J11-5). */ +export const analystsRepository = { + /** 20 a page in sign-up order, whatever their verification, searched by name, username or phone. */ + async list( + args: ListAnalystsArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await analystsHttp.get( + ANALYST_ENDPOINTS.list, + { params: toListAnalystsQueryDto(args), signal }, + ); + return toAnalystPagePayload(response); + }, + + /** One analyst, with «گزارش ممیزی»; 404 without a creator profile. */ + async get( + id: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await analystsHttp.get( + ANALYST_ENDPOINTS.detail(id), + { signal }, + ); + return toAnalystDetailPayload(response); + }, + + /** + * The analyst gets the reason by in-app notice and SMS; an approved analyst's active subscribers + * are told without it. A pending or rejected one has no channel: only the account is suspended. + */ + async suspend(args: SuspendAnalystArgs): Promise { + const response = await analystsHttp.post( + ANALYST_ENDPOINTS.suspend(args.id), + toSuspendAnalystDto(args), + ); + return { affectedCount: response.affectedCount }; + }, + + /** + * The analyst gets an SMS; when the channel was suspended, each extended subscriber is told the + * new expiry. An account-only suspension extends nothing. + */ + async reinstate(args: ReinstateAnalystArgs): Promise { + const response = await analystsHttp.post( + ANALYST_ENDPOINTS.reinstate(args.id), + toReinstateAnalystDto(args), + ); + return toReinstatePayload(response); + }, +}; diff --git a/platforms/garden-roof/src/features/analysts/repositories/analysts/constants.ts b/platforms/garden-roof/src/features/analysts/repositories/analysts/constants.ts new file mode 100644 index 0000000..de23e4c --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/repositories/analysts/constants.ts @@ -0,0 +1,25 @@ +import type { ListAnalystsArgs } from './types'; + +export const ANALYST_ENDPOINTS = { + list: '/admin/analysts', + detail: (id: string) => `/admin/analysts/${encodeURIComponent(id)}`, + suspend: (id: string) => `/admin/analysts/${encodeURIComponent(id)}/suspend`, + reinstate: (id: string) => + `/admin/analysts/${encodeURIComponent(id)}/reinstate`, +} as const; + +/** The codes the API marks account-action failures with; branch on these, never on the message. */ +export const ANALYST_ERROR_CODES = { + /** 409: someone suspended this account in the meantime. */ + alreadySuspended: 'ANALYST_ALREADY_SUSPENDED', + /** 409: someone reinstated this account in the meantime. */ + notSuspended: 'ANALYST_NOT_SUSPENDED', +} as const; + +export const analystKeys = { + all: ['analysts'] as const, + lists: () => [...analystKeys.all, 'list'] as const, + list: (args: ListAnalystsArgs) => [...analystKeys.lists(), args] as const, + details: () => [...analystKeys.all, 'detail'] as const, + detail: (id: string) => [...analystKeys.details(), id] as const, +}; diff --git a/platforms/garden-roof/src/features/analysts/repositories/analysts/index.ts b/platforms/garden-roof/src/features/analysts/repositories/analysts/index.ts new file mode 100644 index 0000000..f6875be --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/repositories/analysts/index.ts @@ -0,0 +1,16 @@ +export { + ANALYST_ENDPOINTS, + ANALYST_ERROR_CODES, + analystKeys, +} from './constants'; +export { analystsRepository } from './analysts'; +export type { + AnalystDetailPayload, + AnalystListItemPayload, + AnalystPagePayload, + ListAnalystsArgs, + ReinstateAnalystArgs, + ReinstatePayload, + SuspendAnalystArgs, + SuspendPayload, +} from './types'; diff --git a/platforms/garden-roof/src/features/analysts/repositories/analysts/mappers.ts b/platforms/garden-roof/src/features/analysts/repositories/analysts/mappers.ts new file mode 100644 index 0000000..a68bd69 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/repositories/analysts/mappers.ts @@ -0,0 +1,87 @@ +import { toApiUrl } from '../../../../shared/utils'; +import { toAuditEntryPayload } from '../../../audit'; +import type { AnalystListItemEntity } from '../../entities/analyst'; +import type { + AnalystDetailPayload, + AnalystDetailResponseDto, + AnalystListItemPayload, + AnalystPagePayload, + AnalystPageResponseDto, + ListAnalystsArgs, + ListAnalystsQueryDto, + ReinstateAnalystArgs, + ReinstateAnalystDto, + ReinstatePayload, + ReinstateResponseDto, + SuspendAnalystArgs, + SuspendAnalystDto, +} from './types'; + +export function toListAnalystsQueryDto( + args: ListAnalystsArgs, +): ListAnalystsQueryDto { + return { q: args.q?.trim() || undefined, page: args.page }; +} + +/** + * Either name part may be '' (the API falls back to the channel's display name as `lastName`); with + * neither, the username stands in, so a header or a dialog never names nobody. + */ +function fullNameOf(dto: AnalystListItemEntity): string { + return `${dto.firstName} ${dto.lastName}`.trim() || dto.username; +} + +function toListItemPayload(dto: AnalystListItemEntity): AnalystListItemPayload { + return { + id: dto.id, + fullName: fullNameOf(dto), + username: dto.username, + phone: dto.phone, + avatarUrl: toApiUrl(dto.avatarUrl), + verificationStatus: dto.verificationStatus, + accountStatus: dto.accountStatus, + suspendedAt: dto.suspendedAt, + activeSubscriptions: dto.activeSubscriptions, + }; +} + +export function toAnalystPagePayload( + dto: AnalystPageResponseDto, +): AnalystPagePayload { + const from = dto.total === 0 ? 0 : (dto.page - 1) * dto.pageSize + 1; + return { + items: dto.items.map(toListItemPayload), + page: dto.page, + pageCount: Math.max(1, Math.ceil(dto.total / dto.pageSize)), + total: dto.total, + from, + to: from === 0 ? 0 : from + dto.items.length - 1, + }; +} + +export function toAnalystDetailPayload( + dto: AnalystDetailResponseDto, +): AnalystDetailPayload { + return { + ...toListItemPayload(dto), + audit: dto.audit.map(toAuditEntryPayload), + }; +} + +export function toSuspendAnalystDto( + args: SuspendAnalystArgs, +): SuspendAnalystDto { + return { reason: args.reason.trim() }; +} + +export function toReinstateAnalystDto( + args: ReinstateAnalystArgs, +): ReinstateAnalystDto { + return { reason: args.reason.trim() }; +} + +export function toReinstatePayload( + dto: ReinstateResponseDto, +): ReinstatePayload { + return { extendedCount: dto.extendedCount, extensionMinutes: dto.extension }; +} diff --git a/platforms/garden-roof/src/features/analysts/repositories/analysts/types.ts b/platforms/garden-roof/src/features/analysts/repositories/analysts/types.ts new file mode 100644 index 0000000..0b16ea3 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/repositories/analysts/types.ts @@ -0,0 +1,83 @@ +import type { AuditEntryPayload } from '../../../audit'; +import type { AccountStatus, VerificationStatus } from '../../../verification'; +import type { + AnalystDetailEntity, + AnalystListItemEntity, +} from '../../entities/analyst'; + +// GET /admin/analysts?q=&page= + +export type ListAnalystsArgs = { + /** First, last or full name, username or phone. */ + q?: string; + page: number; +}; + +export type ListAnalystsQueryDto = { + q?: string; + page: number; +}; + +export type AnalystPageResponseDto = { + items: AnalystListItemEntity[]; + page: number; + pageSize: number; + total: number; +}; + +export type AnalystListItemPayload = { + id: string; + /** The username when the account has no name. */ + fullName: string; + username: string; + /** E.164; '' when the account can't be read. */ + phone: string; + /** Loadable through this site's API proxy. */ + avatarUrl: string | null; + verificationStatus: VerificationStatus; + accountStatus: AccountStatus; + suspendedAt: string | null; + activeSubscriptions: number; +}; + +export type AnalystPagePayload = { + items: AnalystListItemPayload[]; + page: number; + pageCount: number; + total: number; + /** The first and last row's place among all rows, for «نمایش ۱ تا ۱۴ از ۱۴». */ + from: number; + to: number; +}; + +// GET /admin/analysts/:id + +export type AnalystDetailResponseDto = AnalystDetailEntity; + +export type AnalystDetailPayload = AnalystListItemPayload & { + audit: AuditEntryPayload[]; +}; + +// POST /admin/analysts/:id/suspend { reason } + +export type SuspendAnalystArgs = { id: string; reason: string }; +export type SuspendAnalystDto = { reason: string }; + +/** The active subscribers told of the suspension (without its reason); 0 for an account-only one. */ +export type SuspendResponseDto = { affectedCount: number }; +export type SuspendPayload = { affectedCount: number }; + +// POST /admin/analysts/:id/reinstate { reason } + +export type ReinstateAnalystArgs = { id: string; reason: string }; +export type ReinstateAnalystDto = { reason: string }; + +/** + * The eligible subscriptions (not refunded, not lapsed) extended, and by how long: the channel's + * suspended time, in whole minutes. Both 0 when only the account was suspended. + */ +export type ReinstateResponseDto = { extendedCount: number; extension: number }; +export type ReinstatePayload = { + extendedCount: number; + extensionMinutes: number; +}; diff --git a/platforms/garden-roof/src/features/analysts/types.ts b/platforms/garden-roof/src/features/analysts/types.ts new file mode 100644 index 0000000..87bbef4 --- /dev/null +++ b/platforms/garden-roof/src/features/analysts/types.ts @@ -0,0 +1,12 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'analyst.suspended': { id: string; affectedCount: number }; + 'analyst.reinstated': { + id: string; + extendedCount: number; + extensionMinutes: number; + }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/features/audit/entities/audit-entry/index.ts b/platforms/garden-roof/src/features/audit/entities/audit-entry/index.ts new file mode 100644 index 0000000..3a0a076 --- /dev/null +++ b/platforms/garden-roof/src/features/audit/entities/audit-entry/index.ts @@ -0,0 +1 @@ +export type { AuditAction, AuditEntryEntity } from './types'; diff --git a/platforms/garden-roof/src/features/audit/entities/audit-entry/types.ts b/platforms/garden-roof/src/features/audit/entities/audit-entry/types.ts new file mode 100644 index 0000000..8bf7c16 --- /dev/null +++ b/platforms/garden-roof/src/features/audit/entities/audit-entry/types.ts @@ -0,0 +1,40 @@ +/** What an audit row records; each has its title under `common:audit.actions`. */ +export type AuditAction = + | 'verification.approved' + | 'verification.rejected' + | 'account.suspended' + | 'account.reinstated' + | 'code.created' + | 'code.capacity_changed' + | 'code.deactivated' + | 'code.activated' + | 'capacity_request.approved' + | 'capacity_request.rejected' + | 'subscription.extended' + | 'subscription.refunded' + | 'subscription.granted' + | 'prediction.resolved' + | 'prediction.proposal_dismissed' + | 'prediction.overridden' + | 'prediction.flagged' + | 'prediction.unflagged' + | 'payout.created' + | 'payout.paid' + | 'payout.cancelled' + | 'ledger.corrected' + | 'featured.added' + | 'featured.removed' + | 'featured.reordered'; + +/** + * One permanent row of «گزارش ممیزی», as every admin API detail answers it in `audit[]`, oldest + * first. `actorName` is `null` for the system («سیستم»). + */ +export type AuditEntryEntity = { + id: string; + action: AuditAction; + actorName: string | null; + reason: string | null; + details: Record; + at: string; +}; diff --git a/platforms/garden-roof/src/features/audit/index.ts b/platforms/garden-roof/src/features/audit/index.ts new file mode 100644 index 0000000..07001ad --- /dev/null +++ b/platforms/garden-roof/src/features/audit/index.ts @@ -0,0 +1,3 @@ +export type { AuditAction, AuditEntryEntity } from './entities/audit-entry'; +export { toAuditEntryPayload } from './repositories/audit'; +export type { AuditEntryPayload } from './repositories/audit'; diff --git a/platforms/garden-roof/src/features/audit/repositories/audit/index.ts b/platforms/garden-roof/src/features/audit/repositories/audit/index.ts new file mode 100644 index 0000000..e6c2d8d --- /dev/null +++ b/platforms/garden-roof/src/features/audit/repositories/audit/index.ts @@ -0,0 +1,2 @@ +export { toAuditEntryPayload } from './mappers'; +export type { AuditEntryPayload } from './types'; diff --git a/platforms/garden-roof/src/features/audit/repositories/audit/mappers.ts b/platforms/garden-roof/src/features/audit/repositories/audit/mappers.ts new file mode 100644 index 0000000..b20885b --- /dev/null +++ b/platforms/garden-roof/src/features/audit/repositories/audit/mappers.ts @@ -0,0 +1,30 @@ +import type { AuditEntryEntity } from '../../entities/audit-entry'; +import type { AuditEntryPayload } from './types'; + +function numberOf(value: unknown): number | null { + return typeof value === 'number' ? value : null; +} + +function textOf(value: unknown): string | null { + return typeof value === 'string' && value.trim() ? value : null; +} + +/** Every admin detail's `audit[]` row; other features map their DTOs with it. */ +export function toAuditEntryPayload(dto: AuditEntryEntity): AuditEntryPayload { + return { + id: dto.id, + action: dto.action, + actorName: dto.actorName, + reason: dto.reason, + affectedCount: numberOf(dto.details.affectedCount), + extensionMinutes: numberOf(dto.details.extensionMinutes), + fromMaxUses: numberOf(dto.details.fromMaxUses), + toMaxUses: numberOf(dto.details.toMaxUses), + amount: numberOf(dto.details.amount), + days: numberOf(dto.details.days), + fromPrice: numberOf(dto.details.fromPrice), + toPrice: numberOf(dto.details.toPrice), + analystNames: textOf(dto.details.analystNames), + at: dto.at, + }; +} diff --git a/platforms/garden-roof/src/features/audit/repositories/audit/types.ts b/platforms/garden-roof/src/features/audit/repositories/audit/types.ts new file mode 100644 index 0000000..d06168a --- /dev/null +++ b/platforms/garden-roof/src/features/audit/repositories/audit/types.ts @@ -0,0 +1,29 @@ +import type { AuditAction } from '../../entities/audit-entry'; + +/** An audit row as the log shows it. */ +export type AuditEntryPayload = { + id: string; + action: AuditAction; + actorName: string | null; + reason: string | null; + /** Affected subscribers of a suspension or reinstatement. */ + affectedCount: number | null; + /** How long a reinstatement extended the subscriptions, in minutes. */ + extensionMinutes: number | null; + /** A capacity change: the invite code's seats before and after (J11-6g). */ + fromMaxUses: number | null; + toMaxUses: number | null; + /** A refund or payout's Toman (J11-7f «بازگشت وجه ۵۴۰٬۰۰۰ تومان»). */ + amount: number | null; + /** An extension's days (J11-7d). */ + days: number | null; + /** + * A prediction override's prices: `fromPrice` is null when the admin closed a still-open + * prediction at their own price (J11-8). + */ + fromPrice: number | null; + toPrice: number | null; + /** Who the row is about, as the API named them (`details.analystNames`, e.g. a featured save). */ + analystNames: string | null; + at: string; +}; diff --git a/platforms/garden-roof/src/features/auth/actions/login/actions.ts b/platforms/garden-roof/src/features/auth/actions/login/actions.ts new file mode 100644 index 0000000..59506c6 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/actions/login/actions.ts @@ -0,0 +1,20 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { useAuthStore } from '../../../../stores/auth'; +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; +import type { AdminPayload, VerifyCodeArgs } from '../../repositories/auth'; + +/** + * Verifies the login code; the admin API sets the session cookies and the auth store learns the + * admin. Emits `auth.login`. + */ +export async function login( + args: VerifyCodeArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const admin = await authRepository.verifyCode(args); + useAuthStore.getState().setAdmin(admin); + if (emit) eventEmitter.emit(AUTH_EVENTS.login, { adminId: admin.id }); + return admin; +} diff --git a/platforms/garden-roof/src/features/auth/actions/login/index.ts b/platforms/garden-roof/src/features/auth/actions/login/index.ts new file mode 100644 index 0000000..00d9ea2 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/actions/login/index.ts @@ -0,0 +1 @@ +export { login } from './actions'; diff --git a/platforms/garden-roof/src/features/auth/actions/logout/actions.ts b/platforms/garden-roof/src/features/auth/actions/logout/actions.ts new file mode 100644 index 0000000..470e18f --- /dev/null +++ b/platforms/garden-roof/src/features/auth/actions/logout/actions.ts @@ -0,0 +1,15 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { useAuthStore } from '../../../../stores/auth'; +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; + +/** Revokes the session, clears its cookies and the auth store. Emits `auth.logout`. */ +export async function logout({ + emit = true, +}: { emit?: boolean } = {}): Promise<'ok'> { + await authRepository.logout(); + useAuthStore.getState().clearSession(); + if (emit) eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'signed-out' }); + return 'ok'; +} diff --git a/platforms/garden-roof/src/features/auth/actions/logout/index.ts b/platforms/garden-roof/src/features/auth/actions/logout/index.ts new file mode 100644 index 0000000..0284a3e --- /dev/null +++ b/platforms/garden-roof/src/features/auth/actions/logout/index.ts @@ -0,0 +1 @@ +export { logout } from './actions'; diff --git a/platforms/garden-roof/src/features/auth/actions/restore-session/actions.ts b/platforms/garden-roof/src/features/auth/actions/restore-session/actions.ts new file mode 100644 index 0000000..b8e36fc --- /dev/null +++ b/platforms/garden-roof/src/features/auth/actions/restore-session/actions.ts @@ -0,0 +1,40 @@ +import { classifyError } from '@lumina/libs/error-handler'; +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { useAuthStore } from '../../../../stores/auth'; +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; + +/** The connection or the API failed, so a later read may still succeed. */ +function isTransient(error: unknown): boolean { + const { retry } = classifyError(error); + return retry === 'again' || retry === 'wait'; +} + +/** + * Learns who the admin is, once per page load and again when the connection comes back (the + * AppShell calls it). A guest is an empty session, not an error. When the read fails for a reason + * that may pass, the viewer stays unknown, so an admin is never sent to login; any other failure + * makes the viewer a guest. Both rethrow for reporting. Emits `auth.restore`. + */ +export async function restoreSession({ + emit = true, +}: { emit?: boolean } = {}): Promise<'guest' | 'member'> { + const { setAdmin, clearSession } = useAuthStore.getState(); + let status: 'guest' | 'member'; + try { + const admin = await authRepository.getSession(); + if (admin) { + setAdmin(admin); + status = 'member'; + } else { + clearSession(); + status = 'guest'; + } + } catch (error) { + if (!isTransient(error)) clearSession(); + throw error; + } + if (emit) eventEmitter.emit(AUTH_EVENTS.restore, { status }); + return status; +} diff --git a/platforms/garden-roof/src/features/auth/actions/restore-session/index.ts b/platforms/garden-roof/src/features/auth/actions/restore-session/index.ts new file mode 100644 index 0000000..0a4bdf0 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/actions/restore-session/index.ts @@ -0,0 +1 @@ +export { restoreSession } from './actions'; diff --git a/platforms/garden-roof/src/features/auth/actions/send-code/actions.ts b/platforms/garden-roof/src/features/auth/actions/send-code/actions.ts new file mode 100644 index 0000000..092a0d2 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/actions/send-code/actions.ts @@ -0,0 +1,18 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { AUTH_EVENTS } from '../../constants'; +import { authRepository } from '../../repositories/auth'; +import type { SendCodeArgs, SendCodePayload } from '../../repositories/auth'; + +/** + * Asks for a login code. The API answers every well-formed number alike and texts a code only to + * an admin's. Emits `auth.code-sent`. + */ +export async function sendCode( + args: SendCodeArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await authRepository.sendCode(args); + if (emit) eventEmitter.emit(AUTH_EVENTS.codeSent, {}); + return result; +} diff --git a/platforms/garden-roof/src/features/auth/actions/send-code/index.ts b/platforms/garden-roof/src/features/auth/actions/send-code/index.ts new file mode 100644 index 0000000..6a43168 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/actions/send-code/index.ts @@ -0,0 +1 @@ +export { sendCode } from './actions'; diff --git a/platforms/garden-roof/src/features/auth/constants.ts b/platforms/garden-roof/src/features/auth/constants.ts new file mode 100644 index 0000000..7a59806 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/constants.ts @@ -0,0 +1,10 @@ +/** Events auth actions emit when they succeed; the AppShell reacts to them. */ +export const AUTH_EVENTS = { + restore: 'auth.restore', + codeSent: 'auth.code-sent', + login: 'auth.login', + logout: 'auth.logout', +} as const; + +/** The product's resend wait; the server's own cooldown is shorter. */ +export const RESEND_WAIT_SECONDS = 120; diff --git a/platforms/garden-roof/src/features/auth/entities/admin/index.ts b/platforms/garden-roof/src/features/auth/entities/admin/index.ts new file mode 100644 index 0000000..33def26 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/entities/admin/index.ts @@ -0,0 +1 @@ +export type { AdminEntity } from './types'; diff --git a/platforms/garden-roof/src/features/auth/entities/admin/types.ts b/platforms/garden-roof/src/features/auth/entities/admin/types.ts new file mode 100644 index 0000000..6f662f6 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/entities/admin/types.ts @@ -0,0 +1,7 @@ +/** An admin account as the admin API answers it (`GET /admin/auth/session`). */ +export type AdminEntity = { + id: string; + username: string; + displayName: string; + avatarUrl: string | null; +}; diff --git a/platforms/garden-roof/src/features/auth/http.ts b/platforms/garden-roof/src/features/auth/http.ts new file mode 100644 index 0000000..28c6d44 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const authHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/auth/index.ts b/platforms/garden-roof/src/features/auth/index.ts new file mode 100644 index 0000000..c8ecfbf --- /dev/null +++ b/platforms/garden-roof/src/features/auth/index.ts @@ -0,0 +1,21 @@ +import './types'; + +export { login } from './actions/login'; +export { logout } from './actions/logout'; +export { restoreSession } from './actions/restore-session'; +export { sendCode } from './actions/send-code'; +export { AUTH_EVENTS, RESEND_WAIT_SECONDS } from './constants'; +export type { AdminEntity } from './entities/admin'; +export { useLoginPage } from './models/login'; +export type { LoginPageModel, LoginStep } from './models/login'; +export { + AUTH_ENDPOINTS, + AUTH_ERROR_CODES, + authRepository, +} from './repositories/auth'; +export type { + AdminPayload, + SendCodeArgs, + SendCodePayload, + VerifyCodeArgs, +} from './repositories/auth'; diff --git a/platforms/garden-roof/src/features/auth/models/login/index.ts b/platforms/garden-roof/src/features/auth/models/login/index.ts new file mode 100644 index 0000000..69cb3c3 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/models/login/index.ts @@ -0,0 +1,2 @@ +export { useLoginPage } from './use-login-page'; +export type { LoginPageModel, LoginStep } from './types'; diff --git a/platforms/garden-roof/src/features/auth/models/login/types.ts b/platforms/garden-roof/src/features/auth/models/login/types.ts new file mode 100644 index 0000000..7141b16 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/models/login/types.ts @@ -0,0 +1,34 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { + PhoneFormOutput, + PhoneFormValues, +} from '../../../../shared/validations'; + +/** phone → code → signed-in; the page then leaves for the return path. */ +export type LoginStep = 'phone' | 'code'; + +export type LoginPageModel = { + step: LoginStep; + phoneForm: UseFormReturn; + submitPhone: () => void; + isSending: boolean; + /** The number the code went to, as the admin typed it. */ + phone: string; + code: string; + setCode: (code: string) => void; + submitCode: (code: string) => void; + isVerifying: boolean; + /** Why the code was refused, or how long to wait after too many requests; shown under the cells. */ + codeError: string | null; + /** + * Counts refused codes. The cells are disabled while a code is checked, which drops focus; the + * template keys them on this so each refusal remounts them focused for the retry. + */ + attempt: number; + /** When a new code may be asked for. */ + resendEndsAt: number | null; + resend: () => void; + isResending: boolean; + editPhone: () => void; +}; diff --git a/platforms/garden-roof/src/features/auth/models/login/use-login-page.ts b/platforms/garden-roof/src/features/auth/models/login/use-login-page.ts new file mode 100644 index 0000000..c0a573c --- /dev/null +++ b/platforms/garden-roof/src/features/auth/models/login/use-login-page.ts @@ -0,0 +1,188 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import type { HttpError } from '@lumina/libs/http'; +import { exactDuration } from '@lumina/tools/format'; +import { useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; +import * as v from 'valibot'; + +import { + applyServerErrors, + showActionError, + translateMessage, +} from '../../../../shared/utils'; +import { codeSchema, phoneSchema } from '../../../../shared/validations'; +import type { + PhoneFormOutput, + PhoneFormValues, +} from '../../../../shared/validations'; +import { login } from '../../actions/login'; +import { sendCode } from '../../actions/send-code'; +import { RESEND_WAIT_SECONDS } from '../../constants'; +import { AUTH_ERROR_CODES } from '../../repositories/auth'; +import type { LoginPageModel, LoginStep } from './types'; + +/** The moment `seconds` from now. */ +function secondsFromNow(seconds: number): number { + return Date.now() + seconds * 1000; +} + +/** When a new code may be asked for: the server's wait or the product's, whichever is longer. */ +function resendEndsAfter(seconds: number): number { + return secondsFromNow(Math.max(seconds, RESEND_WAIT_SECONDS)); +} + +/** Too many sign-in requests from this connection, on either step (429). */ +function isTooManyRequests(error: unknown): error is HttpError { + return isHttpError(error) && error.code === AUTH_ERROR_CODES.tooManyRequests; +} + +/** + * The admin's sign-in (0061): the number, then the 6-digit code. Every well-formed number moves on + * to the code step, since the API answers them all alike (only an admin's number gets a code), and + * a refused code gets one message whatever the reason, so the screen never tells which numbers + * belong to an admin. Too many requests from this connection show the wait, under the number or + * under the code. A code that is not 6 digits is refused here, without a request (each one counts + * against the per-connection limit). `onSignedIn` runs once the session is set. + */ +export function useLoginPage({ + onSignedIn, +}: { + onSignedIn: () => void; +}): LoginPageModel { + const { t } = useTranslation(['auth', 'errors']); + const [step, setStep] = useState('phone'); + const [phone, setPhone] = useState(''); + const [code, setCode] = useState(''); + const [codeError, setCodeError] = useState(null); + const [attempt, setAttempt] = useState(0); + const [isVerifying, setIsVerifying] = useState(false); + const [isResending, setIsResending] = useState(false); + const [resendEndsAt, setResendEndsAt] = useState(null); + + const phoneForm = useForm({ + resolver: valibotResolver(phoneSchema), + defaultValues: { phone: '' }, + }); + + const startWait = (seconds: number) => + setResendEndsAt(resendEndsAfter(seconds)); + + /** «… ۱۵ دقیقه دیگر دوباره تلاش کنید.»: the wait, rounded up to whole minutes. */ + const tooManyMessage = ({ retryAfter }: HttpError): string => + retryAfter + ? t('errors:auth.too-many', { + wait: exactDuration(Math.ceil(retryAfter / 60)), + }) + : t('errors:auth.too-many-later'); + + const submitPhone = phoneForm.handleSubmit(async (values) => { + try { + const { resendAfterSeconds } = await sendCode({ phone: values.phone }); + setPhone(values.phone); + setCode(''); + setCodeError(null); + startWait(resendAfterSeconds); + setStep('code'); + } catch (error) { + if (isTooManyRequests(error)) { + phoneForm.setError( + 'phone', + { type: 'server', message: tooManyMessage(error) }, + { shouldFocus: true }, + ); + return; + } + applyServerErrors(phoneForm, error, { + t, + failedMessage: t('login.send-failed'), + }); + } + }); + + /** Shows why the code was refused; the cells come back for the retry. */ + const refuseCode = (message: string) => { + setCodeError(message); + setAttempt((count) => count + 1); + }; + + const submitCode = async (value: string) => { + if (isVerifying) return; + const checked = v.safeParse(codeSchema, { code: value }); + if (!checked.success) { + // Missing digits: the typed ones stay so the admin only adds the rest. + refuseCode(translateMessage(t, checked.issues[0].message) ?? ''); + return; + } + setIsVerifying(true); + setCodeError(null); + try { + await login({ phone, code: value }); + onSignedIn(); + } catch (error) { + setCode(''); + if (isHttpError(error) && error.code === AUTH_ERROR_CODES.codeInvalid) { + refuseCode(t('errors:auth.code-invalid')); + } else if (isTooManyRequests(error)) { + refuseCode(tooManyMessage(error)); + } else { + setAttempt((count) => count + 1); + showActionError(error, { t, failedMessage: t('login.verify-failed') }); + } + } finally { + setIsVerifying(false); + } + }; + + const resend = async () => { + if (isResending) return; + setIsResending(true); + try { + const { resendAfterSeconds } = await sendCode({ phone }); + startWait(resendAfterSeconds); + setCode(''); + setCodeError(null); + showToast({ tone: 'success', message: t('login.code-sent') }); + } catch (error) { + if (isTooManyRequests(error)) { + // Resending waits as long as the API asks. + if (error.retryAfter) { + setResendEndsAt(secondsFromNow(error.retryAfter)); + } + setCodeError(tooManyMessage(error)); + return; + } + showActionError(error, { + t, + failedMessage: t('login.send-failed'), + retry: () => void resend(), + }); + } finally { + setIsResending(false); + } + }; + + return { + step, + phoneForm, + submitPhone: () => void submitPhone(), + isSending: phoneForm.formState.isSubmitting, + phone, + code, + setCode, + submitCode: (value) => void submitCode(value), + isVerifying, + codeError, + attempt, + resendEndsAt, + resend: () => void resend(), + isResending, + editPhone: () => { + setStep('phone'); + setCode(''); + setCodeError(null); + }, + }; +} diff --git a/platforms/garden-roof/src/features/auth/repositories/auth/auth.ts b/platforms/garden-roof/src/features/auth/repositories/auth/auth.ts new file mode 100644 index 0000000..0b37eb1 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/repositories/auth/auth.ts @@ -0,0 +1,64 @@ +import { renameFieldErrors } from '../../../../shared/utils'; +import { authHttp } from '../../http'; +import { AUTH_ENDPOINTS } from './constants'; +import { + AUTH_FIELD_NAMES, + toAdminPayload, + toSendCodeDto, + toVerifyCodeDto, +} from './mappers'; +import type { + AdminPayload, + SendCodeArgs, + SendCodePayload, + SendCodeResponseDto, + SessionResponseDto, + VerifyCodeArgs, +} from './types'; + +/** + * Admin sign-in with a code by SMS, against the admin API only (0061). The API sets the session + * in HttpOnly cookies of its own names. Only an admin account gets a code, but asking for one + * answers every number alike and a refused code always fails with `OTP_INVALID`. + */ +export const authRepository = { + async sendCode(args: SendCodeArgs): Promise { + try { + const response = await authHttp.post( + AUTH_ENDPOINTS.sendCode, + toSendCodeDto(args), + ); + return { resendAfterSeconds: response.resendAfterSeconds }; + } catch (error) { + throw renameFieldErrors(error, AUTH_FIELD_NAMES); + } + }, + + async verifyCode(args: VerifyCodeArgs): Promise { + try { + const response = await authHttp.post( + AUTH_ENDPOINTS.verifyCode, + toVerifyCodeDto(args), + ); + if (!response.admin) throw new Error('verify answered no admin'); + return toAdminPayload(response.admin); + } catch (error) { + throw renameFieldErrors(error, AUTH_FIELD_NAMES); + } + }, + + /** The signed-in admin, or `null` for a guest. */ + async getSession({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await authHttp.get( + AUTH_ENDPOINTS.session, + { signal }, + ); + return response.admin ? toAdminPayload(response.admin) : null; + }, + + async logout(): Promise { + await authHttp.post(AUTH_ENDPOINTS.logout); + }, +}; diff --git a/platforms/garden-roof/src/features/auth/repositories/auth/constants.ts b/platforms/garden-roof/src/features/auth/repositories/auth/constants.ts new file mode 100644 index 0000000..c83645b --- /dev/null +++ b/platforms/garden-roof/src/features/auth/repositories/auth/constants.ts @@ -0,0 +1,22 @@ +export const AUTH_ENDPOINTS = { + sendCode: '/admin/auth/otp', + verifyCode: '/admin/auth/otp/verify', + session: '/admin/auth/session', + refresh: '/admin/auth/refresh', + logout: '/admin/auth/logout', +} as const; + +/** + * The codes the admin API marks login failures with; branch on these, never on the message. Asking + * for a code always succeeds, whatever the number, so neither step can tell which numbers belong to + * an admin. + */ +export const AUTH_ERROR_CODES = { + /** + * 400 at verify, the same for every failure about the number or the code: a wrong or expired + * code, a number that got no code, or one blocked after too many wrong codes. + */ + codeInvalid: 'OTP_INVALID', + /** 429 on either step: too many sign-in requests from this connection (`retryAfter`). */ + tooManyRequests: 'TOO_MANY_REQUESTS', +} as const; diff --git a/platforms/garden-roof/src/features/auth/repositories/auth/index.ts b/platforms/garden-roof/src/features/auth/repositories/auth/index.ts new file mode 100644 index 0000000..89b2e6d --- /dev/null +++ b/platforms/garden-roof/src/features/auth/repositories/auth/index.ts @@ -0,0 +1,8 @@ +export { authRepository } from './auth'; +export { AUTH_ENDPOINTS, AUTH_ERROR_CODES } from './constants'; +export type { + AdminPayload, + SendCodeArgs, + SendCodePayload, + VerifyCodeArgs, +} from './types'; diff --git a/platforms/garden-roof/src/features/auth/repositories/auth/mappers.ts b/platforms/garden-roof/src/features/auth/repositories/auth/mappers.ts new file mode 100644 index 0000000..4a89eae --- /dev/null +++ b/platforms/garden-roof/src/features/auth/repositories/auth/mappers.ts @@ -0,0 +1,29 @@ +import { toE164Mobile } from '../../../../shared/utils'; +import type { AdminEntity } from '../../entities/admin'; +import type { + AdminPayload, + SendCodeArgs, + SendCodeDto, + VerifyCodeArgs, + VerifyCodeDto, +} from './types'; + +export function toSendCodeDto(args: SendCodeArgs): SendCodeDto { + return { phoneNumber: toE164Mobile(args.phone) }; +} + +export function toVerifyCodeDto(args: VerifyCodeArgs): VerifyCodeDto { + return { phoneNumber: toE164Mobile(args.phone), code: args.code }; +} + +export function toAdminPayload(dto: AdminEntity): AdminPayload { + return { + id: dto.id, + username: dto.username, + displayName: dto.displayName, + avatarUrl: dto.avatarUrl, + }; +} + +/** The server names the phone field `phoneNumber`; the form names it `phone`. */ +export const AUTH_FIELD_NAMES = { phoneNumber: 'phone' } as const; diff --git a/platforms/garden-roof/src/features/auth/repositories/auth/types.ts b/platforms/garden-roof/src/features/auth/repositories/auth/types.ts new file mode 100644 index 0000000..7db4d67 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/repositories/auth/types.ts @@ -0,0 +1,25 @@ +import type { AdminEntity } from '../../entities/admin'; + +// POST /admin/auth/otp + +export type SendCodeArgs = { phone: string }; +export type SendCodeDto = { phoneNumber: string }; +export type SendCodeResponseDto = { resendAfterSeconds: number }; +export type SendCodePayload = { resendAfterSeconds: number }; + +// POST /admin/auth/otp/verify + +export type VerifyCodeArgs = { phone: string; code: string }; +export type VerifyCodeDto = { phoneNumber: string; code: string }; + +// GET /admin/auth/session (a guest gets `{ admin: null }`) + +export type SessionResponseDto = { admin: AdminEntity | null }; + +/** The signed-in admin, as the sidebar and the audit log show them. */ +export type AdminPayload = { + id: string; + username: string; + displayName: string; + avatarUrl: string | null; +}; diff --git a/platforms/garden-roof/src/features/auth/types.ts b/platforms/garden-roof/src/features/auth/types.ts new file mode 100644 index 0000000..f62bd31 --- /dev/null +++ b/platforms/garden-roof/src/features/auth/types.ts @@ -0,0 +1,10 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'auth.restore': { status: 'guest' | 'member' }; + 'auth.code-sent': Record; + 'auth.login': { adminId: string }; + 'auth.logout': { reason: 'signed-out' | 'session-ended' }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/features/featured/actions/add-featured/actions.ts b/platforms/garden-roof/src/features/featured/actions/add-featured/actions.ts new file mode 100644 index 0000000..61944b9 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/actions/add-featured/actions.ts @@ -0,0 +1,27 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { FEATURED_EVENTS } from '../../constants'; +import { featuredRepository } from '../../repositories/featured'; +import type { FeaturedPayload } from '../../repositories/featured'; + +/** + * «افزودن به منتخب» (J11-10c): the chosen analysts join the end of the list in the order they were + * chosen; no reason is asked. The public lists show them at once (the save purges their cache). + * Emits `featured.added`. + */ +export async function addFeatured( + { + version, + current, + added, + }: { version: number; current: readonly string[]; added: readonly string[] }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await featuredRepository.save({ + version, + analystIds: [...current, ...added], + }); + if (emit) + eventEmitter.emit(FEATURED_EVENTS.added, { analystIds: [...added] }); + return result; +} diff --git a/platforms/garden-roof/src/features/featured/actions/add-featured/index.ts b/platforms/garden-roof/src/features/featured/actions/add-featured/index.ts new file mode 100644 index 0000000..5aebe9e --- /dev/null +++ b/platforms/garden-roof/src/features/featured/actions/add-featured/index.ts @@ -0,0 +1 @@ +export { addFeatured } from './actions'; diff --git a/platforms/garden-roof/src/features/featured/actions/remove-featured/actions.ts b/platforms/garden-roof/src/features/featured/actions/remove-featured/actions.ts new file mode 100644 index 0000000..edb8478 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/actions/remove-featured/actions.ts @@ -0,0 +1,33 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { FEATURED_EVENTS } from '../../constants'; +import { featuredRepository } from '../../repositories/featured'; +import type { FeaturedPayload } from '../../repositories/featured'; + +/** + * «حذف از منتخب» (J11-10d): the analyst leaves the slider on the landing, خانه and «تحلیلگران + * منتخب»; their channel, record and subscribers don't change. The reason goes to «گزارش ممیزی». + * Emits `featured.removed`. + */ +export async function removeFeatured( + { + version, + current, + analystId, + reason, + }: { + version: number; + current: readonly string[]; + analystId: string; + reason: string; + }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await featuredRepository.save({ + version, + analystIds: current.filter((id) => id !== analystId), + reason, + }); + if (emit) eventEmitter.emit(FEATURED_EVENTS.removed, { analystId }); + return result; +} diff --git a/platforms/garden-roof/src/features/featured/actions/remove-featured/index.ts b/platforms/garden-roof/src/features/featured/actions/remove-featured/index.ts new file mode 100644 index 0000000..24c7357 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/actions/remove-featured/index.ts @@ -0,0 +1 @@ +export { removeFeatured } from './actions'; diff --git a/platforms/garden-roof/src/features/featured/actions/reorder-featured/actions.ts b/platforms/garden-roof/src/features/featured/actions/reorder-featured/actions.ts new file mode 100644 index 0000000..a1c2101 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/actions/reorder-featured/actions.ts @@ -0,0 +1,22 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { FEATURED_EVENTS } from '../../constants'; +import { featuredRepository } from '../../repositories/featured'; +import type { FeaturedPayload } from '../../repositories/featured'; + +/** + * A new order, saved on drop or a row-menu move (J11-10b, J11-10g): no save button and no reason. + * The public lists take the order at once; they never get the places themselves. Emits + * `featured.reordered`. + */ +export async function reorderFeatured( + { version, analystIds }: { version: number; analystIds: readonly string[] }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await featuredRepository.save({ version, analystIds }); + if (emit) + eventEmitter.emit(FEATURED_EVENTS.reordered, { + analystIds: [...analystIds], + }); + return result; +} diff --git a/platforms/garden-roof/src/features/featured/actions/reorder-featured/index.ts b/platforms/garden-roof/src/features/featured/actions/reorder-featured/index.ts new file mode 100644 index 0000000..d235e48 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/actions/reorder-featured/index.ts @@ -0,0 +1 @@ +export { reorderFeatured } from './actions'; diff --git a/platforms/garden-roof/src/features/featured/constants.ts b/platforms/garden-roof/src/features/featured/constants.ts new file mode 100644 index 0000000..00be91f --- /dev/null +++ b/platforms/garden-roof/src/features/featured/constants.ts @@ -0,0 +1,23 @@ +/** Events featured-list actions emit when they succeed. */ +export const FEATURED_EVENTS = { + added: 'featured.added', + removed: 'featured.removed', + reordered: 'featured.reordered', +} as const; + +/** + * The landing shows its analysts section from this many visible analysts; below it, only خانه and + * «تحلیلگران منتخب» show them (J11-10e). + */ +export const LANDING_MIN_VISIBLE = 3; + +/** The most analysts the list holds (admin-api `FEATURED_MAX`); the public lists show 10. */ +export const FEATURED_MAX = 20; + +/** The preview draws the first this many visible cards, as the landing's first view does (J11-10). */ +export const PREVIEW_COUNT = 3; + +/** The URL's query parameters on the featured page: `?add=1` opens «افزودن تحلیلگر منتخب». */ +export const FEATURED_PARAMS = { + add: 'add', +} as const; diff --git a/platforms/garden-roof/src/features/featured/entities/featured/index.ts b/platforms/garden-roof/src/features/featured/entities/featured/index.ts new file mode 100644 index 0000000..d3e758e --- /dev/null +++ b/platforms/garden-roof/src/features/featured/entities/featured/index.ts @@ -0,0 +1,10 @@ +export type { + FeaturedAccountStatus, + FeaturedAnalystEntity, + FeaturedCandidateEntity, + FeaturedHiddenReason, + FeaturedIneligibility, + FeaturedListEntity, + FeaturedMarket, + FeaturedStatsEntity, +} from './types'; diff --git a/platforms/garden-roof/src/features/featured/entities/featured/types.ts b/platforms/garden-roof/src/features/featured/entities/featured/types.ts new file mode 100644 index 0000000..3d94d44 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/entities/featured/types.ts @@ -0,0 +1,88 @@ +import type { AuditEntryEntity } from '../../../audit'; + +/** The markets an analyst covers; each has its name under `common:markets`. */ +export type FeaturedMarket = + | 'crypto' + | 'gold' + | 'equities' + | 'forex' + | 'funds' + | 'real_estate' + | 'automotive' + | 'USDT'; + +export type FeaturedAccountStatus = 'active' | 'suspended'; + +/** + * Why an analyst can't show on the public lists, in the order the API checks it: verified, then an + * active account, then a public track record. Only the first failing one is sent (J11-10c). + */ +export type FeaturedIneligibility = + | 'unverified' + | 'suspended' + | 'no_track_record'; + +/** + * Why the public lists skip a listed analyst now: an ineligibility, a profile without a name or a + * market (`profile_incomplete`), or a visible one past the public lists' 10 (`over_limit`). + */ +export type FeaturedHiddenReason = + | FeaturedIneligibility + | 'profile_incomplete' + | 'over_limit'; + +/** The public track record's headline numbers, as the public card shows them. */ +export type FeaturedStatsEntity = { + winRate: number; + totalPredictions: number; + avgRoiPercent: number; +}; + +/** + * One analyst on the list, at their array index (`GET /admin/featured` → `items[]`). `firstName` + * may be `''` (`lastName` then holds the display name); `bio` is `''` without one. + */ +export type FeaturedAnalystEntity = { + analystId: string; + firstName: string; + lastName: string; + username: string; + /** API-relative (`/uploads/avatars/…`) or a legacy absolute address. */ + avatarUrl: string | null; + markets: FeaturedMarket[]; + bio: string; + followers: number; + accountStatus: FeaturedAccountStatus; + hasPublicTrackRecord: boolean; + /** `null` without a public track record: the numbers aren't public yet. */ + stats: FeaturedStatsEntity | null; + /** + * Why the public lists skip them now, or `null` when they show. A suspended analyst keeps their + * place, hidden, and shows again once reinstated (J11-10f). + */ + hiddenReason: FeaturedHiddenReason | null; +}; + +/** The whole list (`GET /admin/featured`, and the answer to every `PUT`). */ +export type FeaturedListEntity = { + /** The list's revision; a `PUT` names the one it was made on, and an older one is refused (409). */ + version: number; + /** In the admin's order: the array index is the place. Never sent to the public lists. */ + items: FeaturedAnalystEntity[]; + /** The landing shows its analysts section only with 3 or more visible analysts (J11-10e). */ + landingVisible: boolean; + audit: AuditEntryEntity[]; +}; + +/** Someone the admin may add (`GET /admin/featured/candidates?q=`), never one already listed. */ +export type FeaturedCandidateEntity = { + analystId: string; + firstName: string; + lastName: string; + username: string; + /** API-relative (`/uploads/avatars/…`) or a legacy absolute address. */ + avatarUrl: string | null; + markets: FeaturedMarket[]; + /** `null` when they can be added; else the first check they fail. */ + ineligibleReason: FeaturedIneligibility | null; +}; diff --git a/platforms/garden-roof/src/features/featured/http.ts b/platforms/garden-roof/src/features/featured/http.ts new file mode 100644 index 0000000..97dfdba --- /dev/null +++ b/platforms/garden-roof/src/features/featured/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const featuredHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/featured/index.ts b/platforms/garden-roof/src/features/featured/index.ts new file mode 100644 index 0000000..9cde8bb --- /dev/null +++ b/platforms/garden-roof/src/features/featured/index.ts @@ -0,0 +1,49 @@ +import './types'; + +export { addFeatured } from './actions/add-featured'; +export { removeFeatured } from './actions/remove-featured'; +export { reorderFeatured } from './actions/reorder-featured'; +export { + FEATURED_EVENTS, + FEATURED_MAX, + FEATURED_PARAMS, + LANDING_MIN_VISIBLE, + PREVIEW_COUNT, +} from './constants'; +export type { + FeaturedAccountStatus, + FeaturedHiddenReason, + FeaturedIneligibility, + FeaturedMarket, +} from './entities/featured'; +export { + useAddFeaturedDialog, + useFeaturedCandidatesPart, + useFeaturedPage, +} from './models/featured'; +export type { + AddFeaturedDialogModel, + AddFeaturedDialogOptions, + FeaturedCandidatesPartModel, + FeaturedPageModel, + FeaturedReorderModel, + FeaturedRemoval, + FeaturedRowModel, + GripProps, + ReorderAnnouncement, + ReorderState, +} from './models/featured'; +export { + FEATURED_ENDPOINTS, + FEATURED_ERROR_CODES, + featuredKeys, + featuredRepository, +} from './repositories/featured'; +export type { + CandidatesPayload, + FeaturedAnalystPayload, + FeaturedCandidatePayload, + FeaturedPayload, + ListCandidatesArgs, + SaveFeaturedArgs, +} from './repositories/featured'; diff --git a/platforms/garden-roof/src/features/featured/models/featured/index.ts b/platforms/garden-roof/src/features/featured/models/featured/index.ts new file mode 100644 index 0000000..eb7659a --- /dev/null +++ b/platforms/garden-roof/src/features/featured/models/featured/index.ts @@ -0,0 +1,15 @@ +export { useAddFeaturedDialog } from './use-add-featured-dialog'; +export { useFeaturedCandidatesPart } from './use-featured-candidates-part'; +export { useFeaturedPage } from './use-featured-page'; +export type { + AddFeaturedDialogModel, + AddFeaturedDialogOptions, + FeaturedCandidatesPartModel, + FeaturedPageModel, + FeaturedReorderModel, + FeaturedRemoval, + FeaturedRowModel, + GripProps, + ReorderAnnouncement, + ReorderState, +} from './types'; diff --git a/platforms/garden-roof/src/features/featured/models/featured/types.ts b/platforms/garden-roof/src/features/featured/models/featured/types.ts new file mode 100644 index 0000000..e1976c6 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/models/featured/types.ts @@ -0,0 +1,122 @@ +import type { + FocusEvent, + KeyboardEvent, + MouseEvent, + PointerEvent, + RefCallback, +} from 'react'; + +import type { ListSearch, ReasonForm } from '../../../../shared/utils'; +import type { + FeaturedAnalystPayload, + FeaturedCandidatePayload, + FeaturedPayload, +} from '../../repositories/featured'; + +/** + * Where a reorder stands (J11-10b): nothing moving; a grip pressed but not yet dragged; a row + * dragged by the pointer; or a row lifted by Space, Enter or a click, moved with ↑ ↓. `order` is + * the draft the table shows until the drop saves it or Esc drops it. + */ +export type ReorderState = + | { kind: 'idle' } + | { kind: 'pressed'; id: string; startY: number } + | { kind: 'dragging'; id: string; order: string[] } + | { kind: 'lifted'; id: string; order: string[] }; + +/** + * What the live caption under the table says: where the moving row is now (J11-10b: «امیر نوری، + * جایگاه ۲ از ۵. …»), or where the last move ended. + */ +export type ReorderAnnouncement = { + kind: 'moving' | 'dropped' | 'cancelled'; + name: string; + position: number; + total: number; +} | null; + +/** The grip's handlers and state: the pointer drags it, Space/Enter/click lift and drop it. */ +export type GripProps = { + ref: RefCallback; + onClick: (event: MouseEvent) => void; + onKeyDown: (event: KeyboardEvent) => void; + onPointerDown: (event: PointerEvent) => void; + onBlur: (event: FocusEvent) => void; + /** Lifted: a toggle that's on until the drop. */ + 'aria-pressed': boolean; +}; + +export type FeaturedReorderModel = { + /** The order the table shows: the draft while a row moves, else the saved one. */ + order: string[]; + movingId: string | null; + /** The pointer is dragging: no text selection, a grabbing cursor. */ + isDragging: boolean; + announcement: ReorderAnnouncement; + gripProps: (id: string) => GripProps; +}; + +/** One table row, at its place in the order shown. */ +export type FeaturedRowModel = FeaturedAnalystPayload & { + /** From 1, for the admin only: never a ranking (J11-10). */ + position: number; + isMoving: boolean; + canMoveUp: boolean; + canMoveDown: boolean; +}; + +/** + * «حذف از تحلیلگران منتخب» for one row, as it was when the dialog opened; kept while the dialog + * closes, so its text stays after the row has gone. + */ +export type FeaturedRemoval = { row: FeaturedRowModel; open: boolean } | null; + +export type FeaturedPageModel = { + featured: FeaturedPayload; + rows: FeaturedRowModel[]; + /** A suspended analyst keeps their place, hidden: the note under the table says so (J11-10f). */ + hasSuspended: boolean; + /** The first visible cards in order, as the landing's first view shows them. */ + preview: FeaturedAnalystPayload[]; + reorder: FeaturedReorderModel; + /** «انتقال به بالا» / «انتقال به پایین» (J11-10g): one place, saved at once. */ + moveUp: (id: string) => void; + moveDown: (id: string) => void; + /** A new order is being saved: no row can be lifted until it lands. */ + isSaving: boolean; + /** The row the remove dialog is about. */ + removing: FeaturedRowModel | null; + isRemoveOpen: boolean; + openRemove: (id: string) => void; + closeRemove: () => void; + removeForm: ReasonForm; + confirmRemove: (reason: string) => void; + isRemoving: boolean; + /** «افزودن تحلیلگر منتخب» is open (`?add=1`). */ + isAddOpen: boolean; + closeAdd: () => void; +}; + +export type AddFeaturedDialogOptions = { + featured: FeaturedPayload; + /** Closes the dialog: after the analysts are added, or on cancel. */ + onClose: () => void; +}; + +export type AddFeaturedDialogModel = { + search: ListSearch; + /** The picked analysts, in the order they were picked: they join the end in this order. */ + picked: readonly { id: string; fullName: string }[]; + isPicked: (id: string) => boolean; + toggle: (candidate: FeaturedCandidatePayload) => void; + confirm: () => void; + isAdding: boolean; + /** After the dialog has closed: a fresh search and no picks next time. */ + reset: () => void; +}; + +export type FeaturedCandidatesPartModel = { + eligible: FeaturedCandidatePayload[]; + ineligible: FeaturedCandidatePayload[]; + isEmpty: boolean; +}; diff --git a/platforms/garden-roof/src/features/featured/models/featured/use-add-featured-dialog.ts b/platforms/garden-roof/src/features/featured/models/featured/use-add-featured-dialog.ts new file mode 100644 index 0000000..efc7789 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/models/featured/use-add-featured-dialog.ts @@ -0,0 +1,127 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { number } from '@lumina/tools/format'; +import { useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { SEARCH_DELAY_MS } from '../../../../shared/constants'; +import { showActionError, useDebouncedValue } from '../../../../shared/utils'; +import { addFeatured } from '../../actions/add-featured'; +import { FEATURED_MAX } from '../../constants'; +import { + FEATURED_ERROR_CODES, + featuredKeys, +} from '../../repositories/featured'; +import type { FeaturedPayload } from '../../repositories/featured'; +import type { AddFeaturedDialogModel, AddFeaturedDialogOptions } from './types'; +import { useFeaturedRefusal } from './use-featured-refusal'; + +/** The ids a 422 FEATURED_NOT_ELIGIBLE names (`details.analystIds`). */ +function ineligibleIds(details: Record | undefined): string[] { + const ids = details?.analystIds; + return Array.isArray(ids) + ? ids.filter((id): id is string => typeof id === 'string') + : []; +} + +/** + * «افزودن تحلیلگر منتخب» (J11-10c): a search over the analysts not on the list, the eligible ones + * picked with checkboxes; the picks survive a new search, up to the list's 20. They join the end of + * the list in the order picked, with no reason asked. A list changed since it was read (409) is + * read afresh and the picks stay, so «افزودن» can be pressed again; a pick no longer eligible (422) + * is dropped, said by name, and the search refreshed. + */ +export function useAddFeaturedDialog({ + featured, + onClose, +}: AddFeaturedDialogOptions): AddFeaturedDialogModel { + const { t } = useTranslation('featured'); + const queryClient = useQueryClient(); + const refused = useFeaturedRefusal(); + const [value, setValue] = useState(''); + const query = useDebouncedValue(value.trim(), SEARCH_DELAY_MS); + const [picked, setPicked] = useState([]); + const [isAdding, setIsAdding] = useState(false); + + const confirm = async () => { + if (isAdding || picked.length === 0) return; + setIsAdding(true); + try { + const next = await addFeatured({ + version: featured.version, + current: featured.items.map((item) => item.id), + added: picked.map((item) => item.id), + }); + queryClient.setQueryData(featuredKeys.list(), next); + void queryClient.invalidateQueries({ + queryKey: featuredKeys.candidateLists(), + }); + showToast({ + tone: 'success', + message: + picked.length === 1 + ? t('add.done-one', { name: picked[0].fullName }) + : t('add.done', { total: picked.length }), + }); + onClose(); + } catch (error) { + if (await refused(error)) return; + if ( + isHttpError(error) && + error.code === FEATURED_ERROR_CODES.notEligible + ) { + const ids = ineligibleIds(error.details); + const dropped = picked.filter((item) => ids.includes(item.id)); + setPicked((current) => + current.filter((item) => !ids.includes(item.id)), + ); + void queryClient.invalidateQueries({ + queryKey: featuredKeys.candidateLists(), + }); + showToast({ + tone: 'error', + message: + dropped.length === 1 + ? t('add.not-eligible-one', { name: dropped[0].fullName }) + : t('add.not-eligible'), + }); + return; + } + showActionError(error, { + t, + failedMessage: t('add.failed'), + retry: () => void confirm(), + }); + } finally { + setIsAdding(false); + } + }; + + return { + search: { value, setValue, query }, + picked, + isPicked: (id) => picked.some((item) => item.id === id), + toggle: (candidate) => { + if (picked.some((item) => item.id === candidate.id)) { + setPicked(picked.filter((item) => item.id !== candidate.id)); + } else if (featured.items.length + picked.length >= FEATURED_MAX) { + showToast({ + tone: 'info', + message: t('add.full', { max: number(FEATURED_MAX) }), + }); + } else { + setPicked([ + ...picked, + { id: candidate.id, fullName: candidate.fullName }, + ]); + } + }, + confirm: () => void confirm(), + isAdding, + reset: () => { + setValue(''); + setPicked([]); + }, + }; +} diff --git a/platforms/garden-roof/src/features/featured/models/featured/use-featured-candidates-part.ts b/platforms/garden-roof/src/features/featured/models/featured/use-featured-candidates-part.ts new file mode 100644 index 0000000..f3dcef0 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/models/featured/use-featured-candidates-part.ts @@ -0,0 +1,20 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { featuredKeys, featuredRepository } from '../../repositories/featured'; +import type { FeaturedCandidatesPartModel } from './types'; + +/** The analysts a search finds for «افزودن تحلیلگر منتخب»: the eligible ones first (J11-10c). */ +export function useFeaturedCandidatesPart( + query: string, +): FeaturedCandidatesPartModel { + const { data } = useSuspenseQuery({ + queryKey: featuredKeys.candidates(query), + queryFn: ({ signal }) => + featuredRepository.candidates({ q: query || undefined }, { signal }), + }); + return { + eligible: data.eligible, + ineligible: data.ineligible, + isEmpty: data.eligible.length === 0 && data.ineligible.length === 0, + }; +} diff --git a/platforms/garden-roof/src/features/featured/models/featured/use-featured-page.ts b/platforms/garden-roof/src/features/featured/models/featured/use-featured-page.ts new file mode 100644 index 0000000..390e83a --- /dev/null +++ b/platforms/garden-roof/src/features/featured/models/featured/use-featured-page.ts @@ -0,0 +1,191 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { + applyServerErrors, + listHref, + showActionError, + useReasonForm, +} from '../../../../shared/utils'; +import { removeFeatured } from '../../actions/remove-featured'; +import { reorderFeatured } from '../../actions/reorder-featured'; +import { FEATURED_PARAMS, PREVIEW_COUNT } from '../../constants'; +import { featuredKeys, featuredRepository } from '../../repositories/featured'; +import type { FeaturedPayload } from '../../repositories/featured'; +import type { + FeaturedPageModel, + FeaturedRemoval, + FeaturedRowModel, +} from './types'; +import { useFeaturedRefusal } from './use-featured-refusal'; +import { moveTo, useFeaturedReorder } from './use-featured-reorder'; + +/** The list in another order: a moving row's draft, or a reorder shown before the API answers. */ +function withOrder( + list: FeaturedPayload, + order: readonly string[], +): FeaturedPayload { + const byId = new Map(list.items.map((item) => [item.id, item])); + return { + ...list, + items: order.flatMap((id) => { + const item = byId.get(id); + return item ? [item] : []; + }), + }; +} + +/** + * تحلیلگران منتخب (J11-10): the list in the admin's order, saved whole on every change. A drop or + * a row-menu move saves at once (no save button) and shows the new order meanwhile; a failed save + * puts the old order back with «ذخیره ترتیب انجام نشد.». A removal asks «دلیل»; «افزودن تحلیلگر» + * opens from `?add=1`. A list changed by someone else since it was read (409), or naming an analyst + * the API no longer knows (400), is read afresh. The list is read again on every visit, since a + * suspension elsewhere in the panel hides an analyst. + */ +export function useFeaturedPage(): FeaturedPageModel { + const { t } = useTranslation('featured'); + const queryClient = useQueryClient(); + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data: featured } = useSuspenseQuery({ + queryKey: featuredKeys.list(), + queryFn: ({ signal }) => featuredRepository.get({ signal }), + refetchOnMount: 'always', + }); + const [isSaving, setIsSaving] = useState(false); + const [removal, setRemoval] = useState(null); + const [isRemoving, setIsRemoving] = useState(false); + const removeForm = useReasonForm(); + + const refused = useFeaturedRefusal(); + + const savedOrder = featured.items.map((item) => item.id); + const nameOf = (id: string) => + featured.items.find((item) => item.id === id)?.fullName ?? ''; + + const saveOrder = async (order: string[]) => { + const previous = + queryClient.getQueryData(featuredKeys.list()) ?? + featured; + queryClient.setQueryData( + featuredKeys.list(), + withOrder(previous, order), + ); + setIsSaving(true); + try { + const next = await reorderFeatured({ + version: previous.version, + analystIds: order, + }); + queryClient.setQueryData(featuredKeys.list(), next); + showToast({ tone: 'success', message: t('reorder.done') }); + } catch (error) { + queryClient.setQueryData(featuredKeys.list(), previous); + if (!(await refused(error))) { + showActionError(error, { + t, + failedMessage: t('reorder.failed'), + retry: () => void saveOrder(order), + }); + } + } finally { + setIsSaving(false); + } + }; + + const reorder = useFeaturedReorder({ + order: savedOrder, + nameOf, + isSaving, + onDrop: (order) => void saveOrder(order), + }); + + const moveBy = (id: string, step: number) => { + const from = savedOrder.indexOf(id); + if (isSaving || from === -1) return; + const order = moveTo(savedOrder, id, from + step); + if (order.indexOf(id) !== from) void saveOrder(order); + }; + + const shown = withOrder(featured, reorder.order).items; + const rows: FeaturedRowModel[] = shown.map((item, index) => ({ + ...item, + position: index + 1, + isMoving: item.id === reorder.movingId, + canMoveUp: index > 0, + canMoveDown: index < shown.length - 1, + })); + + const confirmRemove = async (reason: string) => { + if (!removal || isRemoving) return; + const { row } = removal; + setIsRemoving(true); + try { + const next = await removeFeatured({ + version: featured.version, + current: savedOrder, + analystId: row.id, + reason, + }); + queryClient.setQueryData(featuredKeys.list(), next); + void queryClient.invalidateQueries({ + queryKey: featuredKeys.candidateLists(), + }); + showToast({ + tone: 'success', + message: t('remove.done', { name: row.fullName }), + }); + setRemoval({ row, open: false }); + } catch (error) { + if (await refused(error)) { + setRemoval({ row, open: false }); + } else { + // A reason the API refuses comes back as a field map: under «دلیل». + applyServerErrors(removeForm, error, { + t, + failedMessage: t('remove.failed'), + retry: () => void confirmRemove(reason), + }); + } + } finally { + setIsRemoving(false); + } + }; + + return { + featured, + rows, + hasSuspended: featured.items.some( + (item) => item.hiddenReason === 'suspended', + ), + preview: featured.items + .filter((item) => item.isVisible) + .slice(0, PREVIEW_COUNT), + reorder, + moveUp: (id) => moveBy(id, -1), + moveDown: (id) => moveBy(id, 1), + isSaving, + removing: removal?.row ?? null, + isRemoveOpen: removal?.open ?? false, + openRemove: (id) => { + const row = rows.find((item) => item.id === id); + if (row) setRemoval({ row, open: true }); + }, + closeRemove: () => + setRemoval((current) => current && { ...current, open: false }), + removeForm, + confirmRemove: (reason) => void confirmRemove(reason), + isRemoving, + isAddOpen: searchParams.get(FEATURED_PARAMS.add) === '1', + closeAdd: () => + router.replace( + listHref(pathname, searchParams, { [FEATURED_PARAMS.add]: null }), + { scroll: false }, + ), + }; +} diff --git a/platforms/garden-roof/src/features/featured/models/featured/use-featured-refusal.ts b/platforms/garden-roof/src/features/featured/models/featured/use-featured-refusal.ts new file mode 100644 index 0000000..2b8c95e --- /dev/null +++ b/platforms/garden-roof/src/features/featured/models/featured/use-featured-refusal.ts @@ -0,0 +1,34 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { useQueryClient } from '@tanstack/react-query'; +import { useTranslation } from 'react-i18next'; + +import { + FEATURED_ERROR_CODES, + featuredKeys, +} from '../../repositories/featured'; + +/** + * A save refused for the whole list: saved by someone else since it was read (409 + * FEATURED_VERSION_CONFLICT, `details.version`) or naming an analyst the API no longer knows (400 + * FEATURED_LIST_INVALID). Either way the list is read afresh and a toast says why; `true` when the + * error was one of these. + */ +export function useFeaturedRefusal(): (error: unknown) => Promise { + const { t } = useTranslation('featured'); + const queryClient = useQueryClient(); + + return async (error) => { + if (!isHttpError(error)) return false; + const message = + error.code === FEATURED_ERROR_CODES.versionConflict + ? t('conflict') + : error.code === FEATURED_ERROR_CODES.listInvalid + ? t('list-invalid') + : null; + if (!message) return false; + showToast({ tone: 'info', message }); + await queryClient.invalidateQueries({ queryKey: featuredKeys.all }); + return true; + }; +} diff --git a/platforms/garden-roof/src/features/featured/models/featured/use-featured-reorder.ts b/platforms/garden-roof/src/features/featured/models/featured/use-featured-reorder.ts new file mode 100644 index 0000000..1bb48cd --- /dev/null +++ b/platforms/garden-roof/src/features/featured/models/featured/use-featured-reorder.ts @@ -0,0 +1,222 @@ +import { + useEffect, + useEffectEvent, + useLayoutEffect, + useRef, + useState, +} from 'react'; +import type { FocusEvent, KeyboardEvent } from 'react'; + +import type { + FeaturedReorderModel, + ReorderAnnouncement, + ReorderState, +} from './types'; + +/** How far the pointer moves before a press on the grip becomes a drag, in px. */ +const DRAG_THRESHOLD_PX = 4; + +/** `order` with `id` taken out and put back at `to`. */ +export function moveTo( + order: readonly string[], + id: string, + to: number, +): string[] { + const rest = order.filter((item) => item !== id); + const at = Math.max(0, Math.min(to, rest.length)); + return [...rest.slice(0, at), id, ...rest.slice(at)]; +} + +export function sameOrder(a: readonly string[], b: readonly string[]): boolean { + return a.length === b.length && a.every((id, index) => b[index] === id); +} + +type FeaturedReorderOptions = { + /** The saved order. */ + order: readonly string[]; + nameOf: (id: string) => string; + /** A save is in flight: nothing can be lifted until it lands. */ + isSaving: boolean; + /** A drop that changed the order; nothing else saves. */ + onDrop: (order: string[]) => void; +}; + +/** + * Reordering without a drag-and-drop library (J11-10b). The grip drags with the pointer: the row + * takes the place of the rows whose middle the pointer passes, and the release drops it. From the + * keyboard (or a click without a drag) Space lifts the row, ↑ ↓ move it, Space or a click drops + * it and Esc puts it back; so does leaving the grip with Tab. The caption under the table follows + * the row in an `aria-live` region. Only a drop that changed the order saves. + */ +export function useFeaturedReorder({ + order: saved, + nameOf, + isSaving, + onDrop, +}: FeaturedReorderOptions): FeaturedReorderModel { + const [state, setState] = useState({ kind: 'idle' }); + const [outcome, setOutcome] = useState(null); + const grips = useRef(new Map()); + const rowsBody = useRef(null); + // The click a drag's release sends to the grip isn't a lift. + const swallowClick = useRef(false); + + const moving = + state.kind === 'dragging' || state.kind === 'lifted' ? state : null; + const order = moving ? moving.order : [...saved]; + + const lift = (id: string) => { + if (isSaving || !saved.includes(id)) return; + setOutcome(null); + setState({ kind: 'lifted', id, order: [...saved] }); + }; + + const end = (kind: 'dropped' | 'cancelled') => { + if (!moving) return; + const final = kind === 'dropped' ? moving.order : [...saved]; + setOutcome({ + kind, + name: nameOf(moving.id), + position: final.indexOf(moving.id) + 1, + total: final.length, + }); + setState({ kind: 'idle' }); + if (kind === 'dropped' && !sameOrder(moving.order, saved)) + onDrop(moving.order); + }; + + const shift = (step: number) => { + if (state.kind !== 'lifted') return; + const next = moveTo( + state.order, + state.id, + state.order.indexOf(state.id) + step, + ); + setState({ ...state, order: next }); + }; + + const onPointerMove = useEffectEvent((event: PointerEvent) => { + if (state.kind === 'pressed') { + if (Math.abs(event.clientY - state.startY) < DRAG_THRESHOLD_PX) return; + setOutcome(null); + setState({ kind: 'dragging', id: state.id, order: [...saved] }); + return; + } + if (state.kind !== 'dragging' || !rowsBody.current) return; + // The rows stand in the draft order; the row goes below every other row whose middle is above + // the pointer. + const current = state.order.indexOf(state.id); + const target = Array.from(rowsBody.current.rows).reduce( + (count, row, index) => { + if (index === current) return count; + const rect = row.getBoundingClientRect(); + return event.clientY > rect.top + rect.height / 2 ? count + 1 : count; + }, + 0, + ); + if (target !== current) { + setState({ ...state, order: moveTo(state.order, state.id, target) }); + } + }); + + const onPointerUp = useEffectEvent(() => { + if (state.kind === 'pressed') { + // A press without a drag: the click that follows lifts the row. + setState({ kind: 'idle' }); + } else if (state.kind === 'dragging') { + swallowClick.current = true; + window.setTimeout(() => { + swallowClick.current = false; + }); + end('dropped'); + } + }); + + const onPointerCancel = useEffectEvent(() => { + if (state.kind === 'pressed') setState({ kind: 'idle' }); + else end('cancelled'); + }); + + const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => { + if (event.key === 'Escape' && state.kind === 'dragging') { + event.preventDefault(); + end('cancelled'); + } + }); + + const isTracking = state.kind === 'pressed' || state.kind === 'dragging'; + useEffect(() => { + if (!isTracking) return undefined; + const move = (event: PointerEvent) => onPointerMove(event); + const up = () => onPointerUp(); + const cancel = () => onPointerCancel(); + const key = (event: globalThis.KeyboardEvent) => onWindowKeyDown(event); + window.addEventListener('pointermove', move); + window.addEventListener('pointerup', up); + window.addEventListener('pointercancel', cancel); + window.addEventListener('keydown', key); + return () => { + window.removeEventListener('pointermove', move); + window.removeEventListener('pointerup', up); + window.removeEventListener('pointercancel', cancel); + window.removeEventListener('keydown', key); + }; + }, [isTracking]); + + // A row moving down the table is put back in the DOM, which drops focus: the grip keeps it. + const liftedId = state.kind === 'lifted' ? state.id : null; + // The order as a value, so the effect runs when a row moves, not on every render. + const orderKey = order.join(','); + useLayoutEffect(() => { + if (!liftedId) return; + const grip = grips.current.get(liftedId); + if (grip && document.activeElement !== grip) grip.focus(); + }, [liftedId, orderKey]); + + return { + order, + movingId: moving?.id ?? null, + isDragging: state.kind === 'dragging', + announcement: moving + ? { + kind: 'moving', + name: nameOf(moving.id), + position: moving.order.indexOf(moving.id) + 1, + total: moving.order.length, + } + : outcome, + gripProps: (id) => ({ + ref: (element) => { + if (element) grips.current.set(id, element); + else grips.current.delete(id); + }, + onClick: () => { + if (swallowClick.current) return; + if (state.kind === 'lifted') end('dropped'); + else if (state.kind === 'idle') lift(id); + }, + onKeyDown: (event: KeyboardEvent) => { + if (state.kind !== 'lifted' || state.id !== id) return; + if (event.key === 'ArrowUp' || event.key === 'ArrowDown') { + event.preventDefault(); + shift(event.key === 'ArrowUp' ? -1 : 1); + } else if (event.key === 'Escape') { + event.preventDefault(); + end('cancelled'); + } + }, + onPointerDown: (event) => { + if (event.button !== 0 || isSaving || state.kind === 'lifted') return; + rowsBody.current = event.currentTarget.closest('tbody'); + setState({ kind: 'pressed', id, startY: event.clientY }); + }, + onBlur: (event: FocusEvent) => { + // Tab or a press elsewhere; a row put back in the DOM blurs with no next target. + if (state.kind === 'lifted' && state.id === id && event.relatedTarget) { + end('cancelled'); + } + }, + 'aria-pressed': state.kind === 'lifted' && state.id === id, + }), + }; +} diff --git a/platforms/garden-roof/src/features/featured/repositories/featured/constants.ts b/platforms/garden-roof/src/features/featured/repositories/featured/constants.ts new file mode 100644 index 0000000..f69c148 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/repositories/featured/constants.ts @@ -0,0 +1,21 @@ +export const FEATURED_ENDPOINTS = { + featured: '/admin/featured', + candidates: '/admin/featured/candidates', +} as const; + +/** The codes the API marks featured-list failures with; branch on these, never on the message. */ +export const FEATURED_ERROR_CODES = { + /** 409: the list was saved by someone else since it was read (`details.version`: the current one). */ + versionConflict: 'FEATURED_VERSION_CONFLICT', + /** 422: an added analyst is no longer eligible (`details.analystIds`, `details.reasons`). */ + notEligible: 'FEATURED_NOT_ELIGIBLE', + /** 400: an analyst on the saved list is unknown (`details.userIds`). */ + listInvalid: 'FEATURED_LIST_INVALID', +} as const; + +export const featuredKeys = { + all: ['featured'] as const, + list: () => [...featuredKeys.all, 'list'] as const, + candidateLists: () => [...featuredKeys.all, 'candidates'] as const, + candidates: (q: string) => [...featuredKeys.candidateLists(), q] as const, +}; diff --git a/platforms/garden-roof/src/features/featured/repositories/featured/featured.ts b/platforms/garden-roof/src/features/featured/repositories/featured/featured.ts new file mode 100644 index 0000000..ec25879 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/repositories/featured/featured.ts @@ -0,0 +1,57 @@ +import { featuredHttp } from '../../http'; +import { FEATURED_ENDPOINTS } from './constants'; +import { + toCandidatesPayload, + toFeaturedPayload, + toListCandidatesQueryDto, + toSaveFeaturedDto, +} from './mappers'; +import type { + CandidatesPayload, + CandidatesResponseDto, + FeaturedPayload, + FeaturedResponseDto, + ListCandidatesArgs, + SaveFeaturedArgs, +} from './types'; + +/** + * «تحلیلگران منتخب» (J11-10): the ordered list, the analysts who could join it, and the one save + * that replaces it whole: additions, removals and a new order all go through `save`. + */ +export const featuredRepository = { + /** The list in the admin's order, with each analyst's public visibility and the audit log. */ + async get({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await featuredHttp.get( + FEATURED_ENDPOINTS.featured, + { signal }, + ); + return toFeaturedPayload(response); + }, + + /** Analysts not on the list, searched by name, username or number: eligible first, at most 6. */ + async candidates( + args: ListCandidatesArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await featuredHttp.get( + FEATURED_ENDPOINTS.candidates, + { params: toListCandidatesQueryDto(args), signal }, + ); + return toCandidatesPayload(response); + }, + + /** + * Replaces the list made on `version` (the array index is the place) and answers the new one. + * Refused with 409 when the list changed since; a removal needs `reason`. + */ + async save(args: SaveFeaturedArgs): Promise { + const response = await featuredHttp.put( + FEATURED_ENDPOINTS.featured, + toSaveFeaturedDto(args), + ); + return toFeaturedPayload(response); + }, +}; diff --git a/platforms/garden-roof/src/features/featured/repositories/featured/index.ts b/platforms/garden-roof/src/features/featured/repositories/featured/index.ts new file mode 100644 index 0000000..613c164 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/repositories/featured/index.ts @@ -0,0 +1,14 @@ +export { + FEATURED_ENDPOINTS, + FEATURED_ERROR_CODES, + featuredKeys, +} from './constants'; +export { featuredRepository } from './featured'; +export type { + CandidatesPayload, + FeaturedAnalystPayload, + FeaturedCandidatePayload, + FeaturedPayload, + ListCandidatesArgs, + SaveFeaturedArgs, +} from './types'; diff --git a/platforms/garden-roof/src/features/featured/repositories/featured/mappers.ts b/platforms/garden-roof/src/features/featured/repositories/featured/mappers.ts new file mode 100644 index 0000000..baecee7 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/repositories/featured/mappers.ts @@ -0,0 +1,96 @@ +import { toApiUrl } from '../../../../shared/utils'; +import { toAuditEntryPayload } from '../../../audit'; +import type { + FeaturedAnalystEntity, + FeaturedCandidateEntity, +} from '../../entities/featured'; +import type { + CandidatesPayload, + CandidatesResponseDto, + FeaturedAnalystPayload, + FeaturedCandidatePayload, + FeaturedPayload, + FeaturedResponseDto, + ListCandidatesArgs, + ListCandidatesQueryDto, + SaveFeaturedArgs, + SaveFeaturedDto, +} from './types'; + +/** First and last name; either may be `''` (then the display name or the username stands in). */ +function fullNameOf(dto: { + firstName: string; + lastName: string; + username: string; +}): string { + return ( + [dto.firstName, dto.lastName].filter(Boolean).join(' ').trim() || + dto.username + ); +} + +function toAnalystPayload(dto: FeaturedAnalystEntity): FeaturedAnalystPayload { + return { + id: dto.analystId, + fullName: fullNameOf(dto), + username: dto.username, + avatarUrl: toApiUrl(dto.avatarUrl), + markets: [...dto.markets], + bio: dto.bio, + followers: dto.followers, + accountStatus: dto.accountStatus, + hasPublicTrackRecord: dto.hasPublicTrackRecord, + stats: dto.stats && { ...dto.stats }, + isVisible: dto.hiddenReason === null, + hiddenReason: dto.hiddenReason, + }; +} + +export function toFeaturedPayload(dto: FeaturedResponseDto): FeaturedPayload { + const items = dto.items.map(toAnalystPayload); + return { + version: dto.version, + items, + visibleCount: items.filter((item) => item.isVisible).length, + landingVisible: dto.landingVisible, + audit: dto.audit.map(toAuditEntryPayload), + }; +} + +export function toSaveFeaturedDto(args: SaveFeaturedArgs): SaveFeaturedDto { + const reason = args.reason?.trim(); + return { + version: args.version, + analystIds: [...args.analystIds], + ...(reason ? { reason } : {}), + }; +} + +export function toListCandidatesQueryDto( + args: ListCandidatesArgs, +): ListCandidatesQueryDto { + return { q: args.q?.trim() || undefined }; +} + +function toCandidatePayload( + dto: FeaturedCandidateEntity, +): FeaturedCandidatePayload { + return { + id: dto.analystId, + fullName: fullNameOf(dto), + username: dto.username, + avatarUrl: toApiUrl(dto.avatarUrl), + markets: [...dto.markets], + ineligibleReason: dto.ineligibleReason, + }; +} + +export function toCandidatesPayload( + dto: CandidatesResponseDto, +): CandidatesPayload { + const items = dto.items.map(toCandidatePayload); + return { + eligible: items.filter((item) => item.ineligibleReason === null), + ineligible: items.filter((item) => item.ineligibleReason !== null), + }; +} diff --git a/platforms/garden-roof/src/features/featured/repositories/featured/types.ts b/platforms/garden-roof/src/features/featured/repositories/featured/types.ts new file mode 100644 index 0000000..b7c599f --- /dev/null +++ b/platforms/garden-roof/src/features/featured/repositories/featured/types.ts @@ -0,0 +1,81 @@ +import type { AuditEntryPayload } from '../../../audit'; +import type { + FeaturedAccountStatus, + FeaturedCandidateEntity, + FeaturedHiddenReason, + FeaturedIneligibility, + FeaturedListEntity, + FeaturedMarket, + FeaturedStatsEntity, +} from '../../entities/featured'; + +// GET /admin/featured + +export type FeaturedResponseDto = FeaturedListEntity; + +export type FeaturedAnalystPayload = { + id: string; + fullName: string; + username: string; + avatarUrl: string | null; + markets: FeaturedMarket[]; + bio: string; + followers: number; + accountStatus: FeaturedAccountStatus; + hasPublicTrackRecord: boolean; + /** `null` without a public track record. */ + stats: FeaturedStatsEntity | null; + /** Shown on the public lists now. */ + isVisible: boolean; + hiddenReason: FeaturedHiddenReason | null; +}; + +export type FeaturedPayload = { + version: number; + /** In the admin's order. */ + items: FeaturedAnalystPayload[]; + /** The ones the public lists show, in the same order. */ + visibleCount: number; + landingVisible: boolean; + audit: AuditEntryPayload[]; +}; + +// PUT /admin/featured { version, analystIds, reason? } → the new list (FeaturedResponseDto): the +// whole list, in order, at most FEATURED_MAX. A removal needs a reason; an addition or a new order +// doesn't. + +export type SaveFeaturedArgs = { + version: number; + analystIds: readonly string[]; + reason?: string; +}; + +export type SaveFeaturedDto = { + version: number; + analystIds: string[]; + reason?: string; +}; + +// GET /admin/featured/candidates?q= + +export type ListCandidatesArgs = { q?: string }; + +export type ListCandidatesQueryDto = { q?: string }; + +export type CandidatesResponseDto = { items: FeaturedCandidateEntity[] }; + +export type FeaturedCandidatePayload = { + id: string; + fullName: string; + username: string; + avatarUrl: string | null; + markets: FeaturedMarket[]; + ineligibleReason: FeaturedIneligibility | null; +}; + +export type CandidatesPayload = { + /** Can be added: the dialog's choice cards. */ + eligible: FeaturedCandidatePayload[]; + /** Can't, each with its first failing reason: dimmed rows under them. */ + ineligible: FeaturedCandidatePayload[]; +}; diff --git a/platforms/garden-roof/src/features/featured/types.ts b/platforms/garden-roof/src/features/featured/types.ts new file mode 100644 index 0000000..53f6843 --- /dev/null +++ b/platforms/garden-roof/src/features/featured/types.ts @@ -0,0 +1,9 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'featured.added': { analystIds: string[] }; + 'featured.removed': { analystId: string }; + 'featured.reordered': { analystIds: string[] }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/features/health/constants.ts b/platforms/garden-roof/src/features/health/constants.ts new file mode 100644 index 0000000..76a9357 --- /dev/null +++ b/platforms/garden-roof/src/features/health/constants.ts @@ -0,0 +1,2 @@ +/** The page's two tabs, each its own route: «شاخص‌های اصلی» · «شاخص‌های ثانویه» (J11-1, J11-1b). */ +export const HEALTH_TABS = ['main', 'secondary'] as const; diff --git a/platforms/garden-roof/src/features/health/entities/beta-health/index.ts b/platforms/garden-roof/src/features/health/entities/beta-health/index.ts new file mode 100644 index 0000000..ebfb636 --- /dev/null +++ b/platforms/garden-roof/src/features/health/entities/beta-health/index.ts @@ -0,0 +1,15 @@ +export type { + AnalystFunnelEvent, + BetaAnalystEntity, + BetaInactiveReason, + BetaOverviewEntity, + BetaPhase, + ExitMetricEntity, + ExitMetricKey, + ExitMetricStatus, + FunnelEvent, + FunnelJourney, + FunnelStepEntity, + InvestorFunnelEvent, + SecondaryMetricsEntity, +} from './types'; diff --git a/platforms/garden-roof/src/features/health/entities/beta-health/types.ts b/platforms/garden-roof/src/features/health/entities/beta-health/types.ts new file mode 100644 index 0000000..cab4cca --- /dev/null +++ b/platforms/garden-roof/src/features/health/entities/beta-health/types.ts @@ -0,0 +1,111 @@ +/** Before the first day, during the 30 days, after the last (J11-1c: «بتا هنوز شروع نشده است»). */ +export type BetaPhase = 'upcoming' | 'running' | 'ended'; + +/** `GET /admin/beta-health`: the beta's dates and day, which the header and every part hang on. */ +export type BetaOverviewEntity = { + phase: BetaPhase; + /** The first day, 00:00 Tehran. */ + startsAt: string; + /** The last moment of the last day. */ + endsAt: string; + /** 1…totalDays from the first day on; 0 before it. */ + day: number; + totalDays: number; + /** The beta's analysts, and those active (verified, priced and a post in 7 days). */ + analysts: number; + activeAnalysts: number; + /** When the API last computed the metrics; it does every 5 minutes. */ + updatedAt: string; +}; + +/** On track or behind its target (J11-1 «در مسیر» / «عقب‌تر از هدف»). */ +export type ExitMetricStatus = 'on_track' | 'behind'; + +export type ExitMetricKey = + | 'active_analysts' + | 'avg_paid_subscribers' + | 'publishing_analysts' + | 'paid_subscribers'; + +/** + * One of phase 0's exit metrics. A cumulative metric is measured against `target × day/30` + * (`expected`); a level metric against the target itself. + */ +export type ExitMetricEntity = { + key: ExitMetricKey; + value: number; + target: number; + status: ExitMetricStatus; + /** Cumulative metrics only: where the value should be today. */ + expected: number | null; + /** A percentage's counts, such as ۳ از ۴ active analysts. */ + basis: { count: number; of: number } | null; +}; + +export type InvestorFunnelEvent = + | 'landing_cta_click' + | 'register_done' + | 'follow' + | 'checkout_view' + | 'payment_result'; + +export type AnalystFunnelEvent = + | 'kyc_submitted' + | 'verification_approved' + | 'first_prediction_published'; + +export type FunnelEvent = InvestorFunnelEvent | AnalystFunnelEvent; + +/** The investor journey (J0) or the analyst's onboarding (J2). */ +export type FunnelJourney = 'investor' | 'analyst'; + +/** + * People who reached one step of a funnel since the beta started; `count` is `null` for a step + * nothing records yet (no product events: the landing click, the checkout view). + */ +export type FunnelStepEntity = { + event: FunnelEvent; + count: number | null; + /** Those still waiting on ops to pass this step, such as identity requests under review. */ + awaitingReview: number | null; +}; + +/** Why a beta analyst isn't active, in the order the definition checks it. */ +export type BetaInactiveReason = + | 'not_verified' + | 'not_priced' + | 'no_recent_post'; + +/** One row of «تحلیلگران بتا». */ +export type BetaAnalystEntity = { + analystId: string; + /** `''` when the account has none; `lastName` then falls back to the channel's name. */ + firstName: string; + lastName: string; + username: string; + /** API-relative (`/uploads/avatars/…`): the channel's photo, else the account's. */ + avatarUrl: string | null; + /** `null` while active. */ + inactiveReason: BetaInactiveReason | null; + /** Active paid subscriptions; grants don't count. */ + paidSubscribers: number; + /** Published since the beta started. */ + publishedPredictions: number; + /** The invite code's seats; `null` before the analyst has a code. */ + code: { usedCount: number; maxUses: number } | null; + /** Gateway entries, and the payments among them that succeeded. */ + payments: { started: number; completed: number }; +}; + +/** The secondary tab's figures, from the start of the beta to today (J11-1b). */ +export type SecondaryMetricsEntity = { + /** Median days from registration to the first published prediction; `null` before any. */ + onboardingMedianDays: number | null; + /** Monthly subscriptions that came due, and those not renewed. */ + monthOneChurn: { due: number; lapsed: number }; + paymentCompletion: { started: number; completed: number }; + /** Predictions by the active analysts over the beta's days so far. */ + predictionPace: { predictions: number; activeAnalysts: number; days: number }; + /** Track-record page views in the last 7 days; `null` while page views aren't recorded. */ + trackRecordViews: number | null; +}; diff --git a/platforms/garden-roof/src/features/health/http.ts b/platforms/garden-roof/src/features/health/http.ts new file mode 100644 index 0000000..3a3da8f --- /dev/null +++ b/platforms/garden-roof/src/features/health/http.ts @@ -0,0 +1,9 @@ +import { http } from '@lumina/libs/http'; + +/** + * Without 503 among the statuses retried: the beta-health reads answer 503 BETA_NOT_SCHEDULED + * until ops set the beta's start date, which no retry a second later changes. + */ +export const healthHttp = http.extend({ + retry: { statuses: [408, 429, 502, 504] }, +}); diff --git a/platforms/garden-roof/src/features/health/index.ts b/platforms/garden-roof/src/features/health/index.ts new file mode 100644 index 0000000..09d5f98 --- /dev/null +++ b/platforms/garden-roof/src/features/health/index.ts @@ -0,0 +1,38 @@ +export { HEALTH_TABS } from './constants'; +export type { + AnalystFunnelEvent, + BetaInactiveReason, + BetaPhase, + ExitMetricKey, + ExitMetricStatus, + FunnelEvent, + FunnelJourney, + InvestorFunnelEvent, +} from './entities/beta-health'; +export { useBetaHeader, useBetaHealthPage } from './models/page'; +export type { BetaHeaderModel, BetaHealthPageModel } from './models/page'; +export { + useBetaAnalystsPart, + useExitMetricsPart, + useFunnelPart, + useSecondaryMetricsPart, +} from './models/parts'; +export { + betaHealthRepository, + HEALTH_ENDPOINTS, + HEALTH_ERROR_CODES, + HEALTH_REFRESH_MS, + healthKeys, +} from './repositories/beta-health'; +export type { + BetaAnalystPayload, + BetaAnalystsPayload, + BetaOverviewPayload, + ExitMetricPayload, + ExitMetricsPayload, + FunnelPayload, + FunnelStepPayload, + RatePayload, + SecondaryMetricsPayload, +} from './repositories/beta-health'; +export type { HealthTab } from './types'; diff --git a/platforms/garden-roof/src/features/health/models/page/index.ts b/platforms/garden-roof/src/features/health/models/page/index.ts new file mode 100644 index 0000000..a2054ac --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/page/index.ts @@ -0,0 +1,3 @@ +export { useBetaHeader } from './use-beta-header'; +export { useBetaHealthPage } from './use-beta-health-page'; +export type { BetaHeaderModel, BetaHealthPageModel } from './types'; diff --git a/platforms/garden-roof/src/features/health/models/page/types.ts b/platforms/garden-roof/src/features/health/models/page/types.ts new file mode 100644 index 0000000..ad8742f --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/page/types.ts @@ -0,0 +1,21 @@ +import type { BetaOverviewPayload } from '../../repositories/beta-health'; + +export type BetaHealthPageModel = { + /** + * `null` while ops haven't set the beta's start date: a calm configuration state in place of + * the tabs and parts, since every part would answer the same. + */ + overview: BetaOverviewPayload | null; + /** Before the first day: «هنوز داده‌ای نیست» in place of the tabs and parts (J11-1c). */ + isUpcoming: boolean; +}; + +export type BetaHeaderModel = { + /** + * `null` until the admin is known and the overview arrives, after a failed read, and while the + * beta has no start date. + */ + overview: BetaOverviewPayload | null; + /** Still waiting: the header keeps its skeleton line. */ + isLoading: boolean; +}; diff --git a/platforms/garden-roof/src/features/health/models/page/use-beta-header.ts b/platforms/garden-roof/src/features/health/models/page/use-beta-header.ts new file mode 100644 index 0000000..69e14d7 --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/page/use-beta-header.ts @@ -0,0 +1,28 @@ +import { useQuery } from '@tanstack/react-query'; + +import { useViewerStatus } from '../../../../stores/auth'; +import { + betaHealthRepository, + HEALTH_REFRESH_MS, + healthKeys, +} from '../../repositories/beta-health'; +import type { BetaHeaderModel } from './types'; + +/** + * The page header's day, dates and update time (J11-1), which the server-rendered title can't + * know. The same read as the page's, once the admin is known; a failed read leaves the line empty, + * since the page's own boundary already says what failed, as does a beta with no start date. + */ +export function useBetaHeader(): BetaHeaderModel { + const isMember = useViewerStatus() === 'member'; + const { data, isPending } = useQuery({ + queryKey: healthKeys.overview(), + queryFn: ({ signal }) => betaHealthRepository.overview({ signal }), + enabled: isMember, + refetchInterval: HEALTH_REFRESH_MS, + staleTime: HEALTH_REFRESH_MS, + throwOnError: false, + }); + + return { overview: data ?? null, isLoading: isPending }; +} diff --git a/platforms/garden-roof/src/features/health/models/page/use-beta-health-page.ts b/platforms/garden-roof/src/features/health/models/page/use-beta-health-page.ts new file mode 100644 index 0000000..a818c7d --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/page/use-beta-health-page.ts @@ -0,0 +1,24 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { + betaHealthRepository, + HEALTH_REFRESH_MS, + healthKeys, +} from '../../repositories/beta-health'; +import type { BetaHealthPageModel } from './types'; + +/** + * سلامت بتا (J11-1, J11-1b): the beta's dates and day, which decide between the tabs with their + * parts, the pre-launch state (J11-1c) and, without a start date, the configuration state. Read + * again every 5 minutes, as the API recomputes. + */ +export function useBetaHealthPage(): BetaHealthPageModel { + const { data } = useSuspenseQuery({ + queryKey: healthKeys.overview(), + queryFn: ({ signal }) => betaHealthRepository.overview({ signal }), + refetchInterval: HEALTH_REFRESH_MS, + staleTime: HEALTH_REFRESH_MS, + }); + + return { overview: data, isUpcoming: data?.phase === 'upcoming' }; +} diff --git a/platforms/garden-roof/src/features/health/models/parts/index.ts b/platforms/garden-roof/src/features/health/models/parts/index.ts new file mode 100644 index 0000000..3d18e26 --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/parts/index.ts @@ -0,0 +1,4 @@ +export { useBetaAnalystsPart } from './use-beta-analysts-part'; +export { useExitMetricsPart } from './use-exit-metrics-part'; +export { useFunnelPart } from './use-funnel-part'; +export { useSecondaryMetricsPart } from './use-secondary-metrics-part'; diff --git a/platforms/garden-roof/src/features/health/models/parts/use-beta-analysts-part.ts b/platforms/garden-roof/src/features/health/models/parts/use-beta-analysts-part.ts new file mode 100644 index 0000000..6d90d26 --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/parts/use-beta-analysts-part.ts @@ -0,0 +1,22 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { + betaHealthRepository, + HEALTH_REFRESH_MS, + healthKeys, +} from '../../repositories/beta-health'; +import type { BetaAnalystsPayload } from '../../repositories/beta-health'; +import { usePartRead } from './use-part-read'; + +/** «تحلیلگران بتا» (J11-1): the five analysts, most paid subscribers first, on its own read. */ +export function useBetaAnalystsPart(): BetaAnalystsPayload { + const partRead = usePartRead(); + const { data } = useSuspenseQuery({ + queryKey: healthKeys.analysts(), + queryFn: ({ signal }) => + partRead(() => betaHealthRepository.analysts({ signal })), + refetchInterval: HEALTH_REFRESH_MS, + staleTime: HEALTH_REFRESH_MS, + }); + return data; +} diff --git a/platforms/garden-roof/src/features/health/models/parts/use-exit-metrics-part.ts b/platforms/garden-roof/src/features/health/models/parts/use-exit-metrics-part.ts new file mode 100644 index 0000000..22a55e8 --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/parts/use-exit-metrics-part.ts @@ -0,0 +1,22 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { + betaHealthRepository, + HEALTH_REFRESH_MS, + healthKeys, +} from '../../repositories/beta-health'; +import type { ExitMetricsPayload } from '../../repositories/beta-health'; +import { usePartRead } from './use-part-read'; + +/** «شاخص‌های خروج از فاز ۰» (J11-1): loads, fails and refreshes apart from the other parts. */ +export function useExitMetricsPart(): ExitMetricsPayload { + const partRead = usePartRead(); + const { data } = useSuspenseQuery({ + queryKey: healthKeys.exit(), + queryFn: ({ signal }) => + partRead(() => betaHealthRepository.exitMetrics({ signal })), + refetchInterval: HEALTH_REFRESH_MS, + staleTime: HEALTH_REFRESH_MS, + }); + return data; +} diff --git a/platforms/garden-roof/src/features/health/models/parts/use-funnel-part.ts b/platforms/garden-roof/src/features/health/models/parts/use-funnel-part.ts new file mode 100644 index 0000000..17da9da --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/parts/use-funnel-part.ts @@ -0,0 +1,26 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import type { FunnelJourney } from '../../entities/beta-health'; +import { + betaHealthRepository, + HEALTH_REFRESH_MS, + healthKeys, +} from '../../repositories/beta-health'; +import type { FunnelPayload } from '../../repositories/beta-health'; +import { usePartRead } from './use-part-read'; + +/** + * «قیف بازدیدکننده تا سرمایه‌گذار» (J11-1) or «قیف آماده‌سازی تحلیلگر» (J11-1b): each step against + * the one before it, on its own read. + */ +export function useFunnelPart(journey: FunnelJourney): FunnelPayload { + const partRead = usePartRead(); + const { data } = useSuspenseQuery({ + queryKey: healthKeys.funnel(journey), + queryFn: ({ signal }) => + partRead(() => betaHealthRepository.funnel(journey, { signal })), + refetchInterval: HEALTH_REFRESH_MS, + staleTime: HEALTH_REFRESH_MS, + }); + return data; +} diff --git a/platforms/garden-roof/src/features/health/models/parts/use-part-read.ts b/platforms/garden-roof/src/features/health/models/parts/use-part-read.ts new file mode 100644 index 0000000..5e565ec --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/parts/use-part-read.ts @@ -0,0 +1,31 @@ +import { isHttpError } from '@lumina/libs/http'; +import { useQueryClient } from '@tanstack/react-query'; +import { useCallback } from 'react'; + +import { HEALTH_ERROR_CODES, healthKeys } from '../../repositories/beta-health'; + +/** + * Runs a part's read; when it answers 503 BETA_NOT_SCHEDULED (the start date was taken away while + * the page was open), the overview is cleared too, so the page shows its configuration state in + * place of the part's error. + */ +export function usePartRead() { + const queryClient = useQueryClient(); + + return useCallback( + async (read: () => Promise): Promise => { + try { + return await read(); + } catch (error) { + if ( + isHttpError(error) && + error.code === HEALTH_ERROR_CODES.notScheduled + ) { + queryClient.setQueryData(healthKeys.overview(), null); + } + throw error; + } + }, + [queryClient], + ); +} diff --git a/platforms/garden-roof/src/features/health/models/parts/use-secondary-metrics-part.ts b/platforms/garden-roof/src/features/health/models/parts/use-secondary-metrics-part.ts new file mode 100644 index 0000000..867796e --- /dev/null +++ b/platforms/garden-roof/src/features/health/models/parts/use-secondary-metrics-part.ts @@ -0,0 +1,22 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { + betaHealthRepository, + HEALTH_REFRESH_MS, + healthKeys, +} from '../../repositories/beta-health'; +import type { SecondaryMetricsPayload } from '../../repositories/beta-health'; +import { usePartRead } from './use-part-read'; + +/** «شاخص‌های ثانویه» (J11-1b): from the start of the beta to today, on its own read. */ +export function useSecondaryMetricsPart(): SecondaryMetricsPayload { + const partRead = usePartRead(); + const { data } = useSuspenseQuery({ + queryKey: healthKeys.secondary(), + queryFn: ({ signal }) => + partRead(() => betaHealthRepository.secondaryMetrics({ signal })), + refetchInterval: HEALTH_REFRESH_MS, + staleTime: HEALTH_REFRESH_MS, + }); + return data; +} diff --git a/platforms/garden-roof/src/features/health/repositories/beta-health/beta-health.ts b/platforms/garden-roof/src/features/health/repositories/beta-health/beta-health.ts new file mode 100644 index 0000000..58958ba --- /dev/null +++ b/platforms/garden-roof/src/features/health/repositories/beta-health/beta-health.ts @@ -0,0 +1,91 @@ +import { isHttpError } from '@lumina/libs/http'; + +import type { FunnelJourney } from '../../entities/beta-health'; +import { healthHttp } from '../../http'; +import { HEALTH_ENDPOINTS, HEALTH_ERROR_CODES } from './constants'; +import { + toBetaAnalystsPayload, + toBetaOverviewPayload, + toExitMetricsPayload, + toFunnelPayload, + toSecondaryMetricsPayload, +} from './mappers'; +import type { + BetaAnalystsPayload, + BetaAnalystsResponseDto, + BetaOverviewPayload, + BetaOverviewResponseDto, + ExitMetricsPayload, + ExitMetricsResponseDto, + FunnelPayload, + FunnelResponseDto, + SecondaryMetricsPayload, + SecondaryMetricsResponseDto, +} from './types'; + +type ReadOptions = { signal?: AbortSignal }; + +/** سلامت بتا (J11-1, J11-1b): the beta's dates and each part's figures, one read per part. */ +export const betaHealthRepository = { + /** + * The beta's dates, day and analysts, and when the metrics were last computed; `null` while + * the beta has no start date (503 BETA_NOT_SCHEDULED), which is a state of the page, not a + * failure. + */ + async overview({ + signal, + }: ReadOptions = {}): Promise { + try { + const response = await healthHttp.get( + HEALTH_ENDPOINTS.overview, + { signal }, + ); + return toBetaOverviewPayload(response); + } catch (error) { + if (isHttpError(error) && error.code === HEALTH_ERROR_CODES.notScheduled) + return null; + throw error; + } + }, + + /** Phase 0's four exit metrics, each against its target or today's share of it. */ + async exitMetrics({ signal }: ReadOptions = {}): Promise { + const response = await healthHttp.get( + HEALTH_ENDPOINTS.exit, + { signal }, + ); + return toExitMetricsPayload(response); + }, + + /** The investor journey (J0) or the analyst's onboarding (J2), step by step. */ + async funnel( + journey: FunnelJourney, + { signal }: ReadOptions = {}, + ): Promise { + const response = await healthHttp.get( + HEALTH_ENDPOINTS.funnel(journey), + { signal }, + ); + return toFunnelPayload(response); + }, + + /** The beta's analysts, most paid subscribers first. */ + async analysts({ signal }: ReadOptions = {}): Promise { + const response = await healthHttp.get( + HEALTH_ENDPOINTS.analysts, + { signal }, + ); + return toBetaAnalystsPayload(response); + }, + + /** The secondary tab's figures, from the start of the beta to today. */ + async secondaryMetrics({ + signal, + }: ReadOptions = {}): Promise { + const response = await healthHttp.get( + HEALTH_ENDPOINTS.secondary, + { signal }, + ); + return toSecondaryMetricsPayload(response); + }, +}; diff --git a/platforms/garden-roof/src/features/health/repositories/beta-health/constants.ts b/platforms/garden-roof/src/features/health/repositories/beta-health/constants.ts new file mode 100644 index 0000000..dd58e8d --- /dev/null +++ b/platforms/garden-roof/src/features/health/repositories/beta-health/constants.ts @@ -0,0 +1,37 @@ +import type { FunnelJourney } from '../../entities/beta-health'; + +/** + * One read per part rather than the single `GET /admin/beta-health` the board's note sketches: + * «A failed section errors alone», so each part loads, fails, retries and refreshes on its own, + * and a slow aggregate (the funnels scan events) never holds back or fails the others. The + * overview is the small read the header and the pre-launch state hang on. + */ +export const HEALTH_ENDPOINTS = { + overview: '/admin/beta-health', + exit: '/admin/beta-health/exit', + funnel: (journey: FunnelJourney) => `/admin/beta-health/funnels/${journey}`, + analysts: '/admin/beta-health/analysts', + secondary: '/admin/beta-health/secondary', +} as const; + +/** + * The API recomputes the metrics every 5 minutes (J11-1): the page reads them again on that beat, + * and a read is fresh until then, so a tab switch inside the window doesn't ask again. + */ +export const HEALTH_REFRESH_MS = 5 * 60_000; + +/** The codes the API marks beta-health failures with; branch on these, never on the message. */ +export const HEALTH_ERROR_CODES = { + /** 503 on every part: ops haven't set the beta's start date (`BETA_STARTS_AT`) yet. */ + notScheduled: 'BETA_NOT_SCHEDULED', +} as const; + +export const healthKeys = { + all: ['health'] as const, + overview: () => [...healthKeys.all, 'overview'] as const, + exit: () => [...healthKeys.all, 'exit'] as const, + funnel: (journey: FunnelJourney) => + [...healthKeys.all, 'funnel', journey] as const, + analysts: () => [...healthKeys.all, 'analysts'] as const, + secondary: () => [...healthKeys.all, 'secondary'] as const, +}; diff --git a/platforms/garden-roof/src/features/health/repositories/beta-health/index.ts b/platforms/garden-roof/src/features/health/repositories/beta-health/index.ts new file mode 100644 index 0000000..bc4e4e3 --- /dev/null +++ b/platforms/garden-roof/src/features/health/repositories/beta-health/index.ts @@ -0,0 +1,18 @@ +export { betaHealthRepository } from './beta-health'; +export { + HEALTH_ENDPOINTS, + HEALTH_ERROR_CODES, + HEALTH_REFRESH_MS, + healthKeys, +} from './constants'; +export type { + BetaAnalystPayload, + BetaAnalystsPayload, + BetaOverviewPayload, + ExitMetricPayload, + ExitMetricsPayload, + FunnelPayload, + FunnelStepPayload, + RatePayload, + SecondaryMetricsPayload, +} from './types'; diff --git a/platforms/garden-roof/src/features/health/repositories/beta-health/mappers.ts b/platforms/garden-roof/src/features/health/repositories/beta-health/mappers.ts new file mode 100644 index 0000000..d1ae5e4 --- /dev/null +++ b/platforms/garden-roof/src/features/health/repositories/beta-health/mappers.ts @@ -0,0 +1,147 @@ +import { toApiUrl } from '../../../../shared/utils'; +import type { BetaAnalystEntity } from '../../entities/beta-health'; +import type { + BetaAnalystPayload, + BetaAnalystsPayload, + BetaAnalystsResponseDto, + BetaOverviewPayload, + BetaOverviewResponseDto, + ExitMetricsPayload, + ExitMetricsResponseDto, + FunnelPayload, + FunnelResponseDto, + RatePayload, + SecondaryMetricsPayload, + SecondaryMetricsResponseDto, +} from './types'; + +/** `part` as a percent of `whole`; `null` when there is nothing to divide by. */ +function share(part: number, whole: number): number | null { + return whole > 0 ? (part / whole) * 100 : null; +} + +function rate(part: number, whole: number): RatePayload { + return { rate: share(part, whole), part, whole }; +} + +export function toBetaOverviewPayload( + dto: BetaOverviewResponseDto, +): BetaOverviewPayload { + return { + phase: dto.phase, + startsAt: dto.startsAt, + endsAt: dto.endsAt, + day: dto.day, + totalDays: dto.totalDays, + daysLeft: Math.max(0, dto.totalDays - dto.day), + analysts: dto.analysts, + activeAnalysts: dto.activeAnalysts, + updatedAt: dto.updatedAt, + }; +} + +export function toExitMetricsPayload( + dto: ExitMetricsResponseDto, +): ExitMetricsPayload { + return { + day: dto.day, + metrics: dto.metrics.map((metric) => ({ + key: metric.key, + value: metric.value, + target: metric.target, + status: metric.status, + expected: metric.expected, + basis: metric.basis ? { ...metric.basis } : null, + })), + }; +} + +/** + * Each step against the one before it (J11-1: «% = vs previous step»). A step nothing records yet + * (count `null`) is skipped over: the next known step is measured against the last known one. + */ +export function toFunnelPayload(dto: FunnelResponseDto): FunnelPayload { + const known = dto.steps.flatMap((step) => + step.count == null ? [] : [step.count], + ); + let previous: number | null = null; + const steps = dto.steps.map((step) => { + const conversion = + step.count == null || previous == null + ? null + : share(step.count, previous); + if (step.count != null) previous = step.count; + return { + event: step.event, + count: step.count, + conversion, + awaitingReview: step.awaitingReview, + }; + }); + return { + steps, + top: Math.max(0, ...known), + overall: known.length > 1 ? share(known.at(-1) ?? 0, known[0]) : null, + }; +} + +function toBetaAnalystPayload(dto: BetaAnalystEntity): BetaAnalystPayload { + return { + id: dto.analystId, + fullName: `${dto.firstName} ${dto.lastName}`.trim() || dto.username, + username: dto.username, + avatarUrl: toApiUrl(dto.avatarUrl), + isActive: dto.inactiveReason === null, + inactiveReason: dto.inactiveReason, + paidSubscribers: dto.paidSubscribers, + publishedPredictions: dto.publishedPredictions, + code: dto.code + ? { + used: dto.code.usedCount, + max: dto.code.maxUses, + isFull: dto.code.usedCount >= dto.code.maxUses, + } + : null, + payments: { + started: dto.payments.started, + completed: dto.payments.completed, + rate: share(dto.payments.completed, dto.payments.started), + }, + }; +} + +export function toBetaAnalystsPayload( + dto: BetaAnalystsResponseDto, +): BetaAnalystsPayload { + const rows = dto.items.map(toBetaAnalystPayload); + return { + rows, + total: rows.length, + active: rows.filter((row) => row.isActive).length, + }; +} + +export function toSecondaryMetricsPayload( + dto: SecondaryMetricsResponseDto, +): SecondaryMetricsPayload { + const { predictions, activeAnalysts, days } = dto.predictionPace; + return { + onboardingMedianDays: dto.onboardingMedianDays, + monthOneChurn: rate(dto.monthOneChurn.lapsed, dto.monthOneChurn.due), + paymentCompletion: rate( + dto.paymentCompletion.completed, + dto.paymentCompletion.started, + ), + predictionPace: { + // A month is 30 days, as the beta's own. + perAnalystMonth: + activeAnalysts > 0 && days > 0 + ? (predictions / activeAnalysts / days) * 30 + : null, + predictions, + activeAnalysts, + days, + }, + trackRecordViews: dto.trackRecordViews, + }; +} diff --git a/platforms/garden-roof/src/features/health/repositories/beta-health/types.ts b/platforms/garden-roof/src/features/health/repositories/beta-health/types.ts new file mode 100644 index 0000000..c05f42b --- /dev/null +++ b/platforms/garden-roof/src/features/health/repositories/beta-health/types.ts @@ -0,0 +1,139 @@ +import type { + BetaAnalystEntity, + BetaInactiveReason, + BetaOverviewEntity, + BetaPhase, + ExitMetricEntity, + ExitMetricKey, + ExitMetricStatus, + FunnelEvent, + FunnelJourney, + FunnelStepEntity, + SecondaryMetricsEntity, +} from '../../entities/beta-health'; + +// GET /admin/beta-health + +export type BetaOverviewResponseDto = BetaOverviewEntity; + +export type BetaOverviewPayload = { + phase: BetaPhase; + startsAt: string; + endsAt: string; + day: number; + totalDays: number; + /** «۱۲ روز مانده». */ + daysLeft: number; + analysts: number; + activeAnalysts: number; + updatedAt: string; +}; + +// GET /admin/beta-health/exit + +export type ExitMetricsResponseDto = { + day: number; + metrics: ExitMetricEntity[]; +}; + +export type ExitMetricPayload = { + key: ExitMetricKey; + value: number; + target: number; + status: ExitMetricStatus; + expected: number | null; + basis: { count: number; of: number } | null; +}; + +export type ExitMetricsPayload = { + /** The day the expected values are for: «انتظار روز ۱۸». */ + day: number; + metrics: ExitMetricPayload[]; +}; + +// GET /admin/beta-health/funnels/investor · GET /admin/beta-health/funnels/analyst + +export type FunnelResponseDto = { + journey: FunnelJourney; + steps: FunnelStepEntity[]; +}; + +export type FunnelStepPayload = { + event: FunnelEvent; + /** `null` for a step nothing records yet: «—», with an empty bar. */ + count: number | null; + /** + * Percent of the last step before it with a count; `null` on an unknown step, when no step + * before it has a count, or after one nobody reached. + */ + conversion: number | null; + awaitingReview: number | null; +}; + +export type FunnelPayload = { + steps: FunnelStepPayload[]; + /** The largest count (the first known step in a funnel): every bar's full length. */ + top: number; + /** + * The last known step as a percent of the first known one («تبدیل کل قیف»); `null` with fewer + * than two known steps, or while nobody reached the first. + */ + overall: number | null; +}; + +// GET /admin/beta-health/analysts + +export type BetaAnalystsResponseDto = { + /** Most paid subscribers first. */ + items: BetaAnalystEntity[]; +}; + +export type BetaAnalystPayload = { + id: string; + /** First and last name, or the username when the account has neither. */ + fullName: string; + username: string; + /** Loadable through the panel's API proxy (`/api/uploads/…`). */ + avatarUrl: string | null; + isActive: boolean; + inactiveReason: BetaInactiveReason | null; + paidSubscribers: number; + publishedPredictions: number; + code: { used: number; max: number; isFull: boolean } | null; + payments: { + started: number; + completed: number; + /** Percent completed; `null` before anyone reached the gateway. */ + rate: number | null; + }; +}; + +export type BetaAnalystsPayload = { + rows: BetaAnalystPayload[]; + total: number; + active: number; +}; + +// GET /admin/beta-health/secondary + +export type SecondaryMetricsResponseDto = SecondaryMetricsEntity; + +/** A rate with the counts it comes from; `rate` is `null` while the count it divides by is 0. */ +export type RatePayload = { rate: number | null; part: number; whole: number }; + +export type SecondaryMetricsPayload = { + onboardingMedianDays: number | null; + /** Lapsed of due. */ + monthOneChurn: RatePayload; + /** Completed of started. */ + paymentCompletion: RatePayload; + /** Predictions per active analyst per 30 days. */ + predictionPace: { + perAnalystMonth: number | null; + predictions: number; + activeAnalysts: number; + days: number; + }; + /** `null` while page views aren't recorded: «—». */ + trackRecordViews: number | null; +}; diff --git a/platforms/garden-roof/src/features/health/types.ts b/platforms/garden-roof/src/features/health/types.ts new file mode 100644 index 0000000..d96b6c9 --- /dev/null +++ b/platforms/garden-roof/src/features/health/types.ts @@ -0,0 +1,3 @@ +import type { HEALTH_TABS } from './constants'; + +export type HealthTab = (typeof HEALTH_TABS)[number]; diff --git a/platforms/garden-roof/src/features/invite-codes/actions/activate-invite-code/actions.ts b/platforms/garden-roof/src/features/invite-codes/actions/activate-invite-code/actions.ts new file mode 100644 index 0000000..0a867aa --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/activate-invite-code/actions.ts @@ -0,0 +1,21 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { INVITE_CODE_EVENTS } from '../../constants'; +import { inviteCodesRepository } from '../../repositories/invite-codes'; +import type { + CodeStatusPayload, + ReasonArgs, +} from '../../repositories/invite-codes'; + +/** + * «فعال‌سازی کد» (J11-6): checkout takes the code again, with the capacity it had; the audit log + * keeps the reason. Emits `invite-code.activated`. + */ +export async function activateInviteCode( + args: ReasonArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await inviteCodesRepository.activate(args); + if (emit) eventEmitter.emit(INVITE_CODE_EVENTS.activated, { id: args.id }); + return result; +} diff --git a/platforms/garden-roof/src/features/invite-codes/actions/activate-invite-code/index.ts b/platforms/garden-roof/src/features/invite-codes/actions/activate-invite-code/index.ts new file mode 100644 index 0000000..4876465 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/activate-invite-code/index.ts @@ -0,0 +1 @@ +export { activateInviteCode } from './actions'; diff --git a/platforms/garden-roof/src/features/invite-codes/actions/approve-capacity-request/actions.ts b/platforms/garden-roof/src/features/invite-codes/actions/approve-capacity-request/actions.ts new file mode 100644 index 0000000..b2e08e0 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/approve-capacity-request/actions.ts @@ -0,0 +1,29 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { INVITE_CODE_EVENTS } from '../../constants'; +import { inviteCodesRepository } from '../../repositories/invite-codes'; +import type { + ApproveCapacityRequestArgs, + CapacityPayload, +} from '../../repositories/invite-codes'; + +/** + * «تأیید» of a capacity request (J11-6d → 6b pre-filled): the request closes and the code takes + * the capacity the admin settled on; the analyst is told, and a full code's list hears seats + * opened. One audit row. Emits `capacity-request.approved`. + */ +export async function approveCapacityRequest( + args: ApproveCapacityRequestArgs & { codeId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await inviteCodesRepository.approveRequest(args); + if (emit) { + eventEmitter.emit(INVITE_CODE_EVENTS.requestApproved, { + id: args.id, + codeId: args.codeId, + maxUses: result.maxUses, + notifiedCount: result.notifiedCount, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/invite-codes/actions/approve-capacity-request/index.ts b/platforms/garden-roof/src/features/invite-codes/actions/approve-capacity-request/index.ts new file mode 100644 index 0000000..7d2e38b --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/approve-capacity-request/index.ts @@ -0,0 +1 @@ +export { approveCapacityRequest } from './actions'; diff --git a/platforms/garden-roof/src/features/invite-codes/actions/change-capacity/actions.ts b/platforms/garden-roof/src/features/invite-codes/actions/change-capacity/actions.ts new file mode 100644 index 0000000..db6860f --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/change-capacity/actions.ts @@ -0,0 +1,29 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { INVITE_CODE_EVENTS } from '../../constants'; +import { inviteCodesRepository } from '../../repositories/invite-codes'; +import type { + CapacityPayload, + ChangeCapacityArgs, +} from '../../repositories/invite-codes'; + +/** + * «ذخیره» in «تغییر ظرفیت کد دعوت» (J11-6b) on a code with no pending request: the capacity + * changes at once and the audit log keeps the reason. When it opens seats on a full code, the + * whole «لیست اطلاع‌رسانی» gets «ظرفیت باز شد» by SMS and in-app. Emits + * `invite-code.capacity-changed`. + */ +export async function changeCapacity( + args: ChangeCapacityArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await inviteCodesRepository.changeCapacity(args); + if (emit) { + eventEmitter.emit(INVITE_CODE_EVENTS.capacityChanged, { + id: args.id, + maxUses: result.maxUses, + notifiedCount: result.notifiedCount, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/invite-codes/actions/change-capacity/index.ts b/platforms/garden-roof/src/features/invite-codes/actions/change-capacity/index.ts new file mode 100644 index 0000000..6b16df2 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/change-capacity/index.ts @@ -0,0 +1 @@ +export { changeCapacity } from './actions'; diff --git a/platforms/garden-roof/src/features/invite-codes/actions/deactivate-invite-code/actions.ts b/platforms/garden-roof/src/features/invite-codes/actions/deactivate-invite-code/actions.ts new file mode 100644 index 0000000..586811e --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/deactivate-invite-code/actions.ts @@ -0,0 +1,22 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { INVITE_CODE_EVENTS } from '../../constants'; +import { inviteCodesRepository } from '../../repositories/invite-codes'; +import type { + CodeStatusPayload, + ReasonArgs, +} from '../../repositories/invite-codes'; + +/** + * «غیرفعال‌سازی کد» (J11-6f): checkout refuses the code with the CodeInput's invalid message, + * links already shared still open the channel, and subscriptions bought with it stay. The analyst + * gets the reason; the audit log keeps it. Emits `invite-code.deactivated`. + */ +export async function deactivateInviteCode( + args: ReasonArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await inviteCodesRepository.deactivate(args); + if (emit) eventEmitter.emit(INVITE_CODE_EVENTS.deactivated, { id: args.id }); + return result; +} diff --git a/platforms/garden-roof/src/features/invite-codes/actions/deactivate-invite-code/index.ts b/platforms/garden-roof/src/features/invite-codes/actions/deactivate-invite-code/index.ts new file mode 100644 index 0000000..997ca04 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/deactivate-invite-code/index.ts @@ -0,0 +1 @@ +export { deactivateInviteCode } from './actions'; diff --git a/platforms/garden-roof/src/features/invite-codes/actions/reject-capacity-request/actions.ts b/platforms/garden-roof/src/features/invite-codes/actions/reject-capacity-request/actions.ts new file mode 100644 index 0000000..abad2d4 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/reject-capacity-request/actions.ts @@ -0,0 +1,22 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { INVITE_CODE_EVENTS } from '../../constants'; +import { inviteCodesRepository } from '../../repositories/invite-codes'; +import type { ReasonArgs } from '../../repositories/invite-codes'; + +/** + * «رد کردن و اطلاع‌رسانی» (J11-6e): the request closes, the capacity stays, and the analyst gets + * the reason by in-app notice and SMS; the audit log keeps it. Emits `capacity-request.rejected`. + */ +export async function rejectCapacityRequest( + args: ReasonArgs & { codeId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + await inviteCodesRepository.rejectRequest(args); + if (emit) { + eventEmitter.emit(INVITE_CODE_EVENTS.requestRejected, { + id: args.id, + codeId: args.codeId, + }); + } +} diff --git a/platforms/garden-roof/src/features/invite-codes/actions/reject-capacity-request/index.ts b/platforms/garden-roof/src/features/invite-codes/actions/reject-capacity-request/index.ts new file mode 100644 index 0000000..405e109 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/actions/reject-capacity-request/index.ts @@ -0,0 +1 @@ +export { rejectCapacityRequest } from './actions'; diff --git a/platforms/garden-roof/src/features/invite-codes/constants.ts b/platforms/garden-roof/src/features/invite-codes/constants.ts new file mode 100644 index 0000000..b74d657 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/constants.ts @@ -0,0 +1,15 @@ +/** Events invite-code actions emit when they succeed. */ +export const INVITE_CODE_EVENTS = { + capacityChanged: 'invite-code.capacity-changed', + deactivated: 'invite-code.deactivated', + activated: 'invite-code.activated', + requestApproved: 'capacity-request.approved', + requestRejected: 'capacity-request.rejected', +} as const; + +/** The URL's query parameters on both tabs; `code` opens a code's details beside the list (J11-6g). */ +export const INVITE_CODE_PARAMS = { + q: 'q', + page: 'page', + code: 'code', +} as const; diff --git a/platforms/garden-roof/src/features/invite-codes/entities/invite-code/index.ts b/platforms/garden-roof/src/features/invite-codes/entities/invite-code/index.ts new file mode 100644 index 0000000..d7ee8a4 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/entities/invite-code/index.ts @@ -0,0 +1,9 @@ +export type { + CapacityRequestEntity, + CapacityRequestStatus, + InviteCodeAnalystEntity, + InviteCodeDetailEntity, + InviteCodeListItemEntity, + InviteCodeStatus, + PendingCapacityRequestEntity, +} from './types'; diff --git a/platforms/garden-roof/src/features/invite-codes/entities/invite-code/types.ts b/platforms/garden-roof/src/features/invite-codes/entities/invite-code/types.ts new file mode 100644 index 0000000..a0959b2 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/entities/invite-code/types.ts @@ -0,0 +1,60 @@ +import type { AuditEntryEntity } from '../../../audit'; + +/** `full` is computed by the API (used = capacity on an active code), never stored (J11-6). */ +export type InviteCodeStatus = 'active' | 'full' | 'inactive'; + +export type CapacityRequestStatus = 'pending' | 'approved' | 'rejected'; + +/** The analyst a code belongs to: one code each, made when they're verified. */ +export type InviteCodeAnalystEntity = { + id: string; + firstName: string; + lastName: string; + username: string; + /** API-relative (`/uploads/avatars/…`); the mapper makes it loadable. */ + avatarUrl: string | null; + /** A suspended account's code stays listed with «حساب معلق» (J11-6). */ + accountStatus: 'active' | 'suspended'; +}; + +/** The analyst's ask for more seats; one pending at most per code. */ +export type PendingCapacityRequestEntity = { + id: string; + requestedMaxUses: number; + /** '' when the analyst wrote none. */ + note: string; + createdAt: string; +}; + +/** A row of «همه کدها» (`GET /admin/invite-codes`). */ +export type InviteCodeListItemEntity = { + id: string; + code: string; + analyst: InviteCodeAnalystEntity; + usedCount: number; + /** usedCount ≤ maxUses ≤ 1000. */ + maxUses: number; + status: InviteCodeStatus; + /** People on «لیست اطلاع‌رسانی», told by SMS and in-app when seats open. */ + waitlistCount: number; + pendingRequest: PendingCapacityRequestEntity | null; +}; + +/** One code (`GET /admin/invite-codes/:id`, J11-6g). */ +export type InviteCodeDetailEntity = InviteCodeListItemEntity & { + /** + * The analyst's channel with the code filled in, as they share it; root-relative + * (`/@user?code=X`) when the API has no public site address. + */ + inviteUrl: string; + /** The last «ظرفیت باز شد» SMS to the list. */ + lastNotifiedAt: string | null; + createdAt: string; + audit: AuditEntryEntity[]; +}; + +/** A row of «درخواست‌های افزایش» (`GET /admin/capacity-requests`, J11-6d). */ +export type CapacityRequestEntity = PendingCapacityRequestEntity & { + status: CapacityRequestStatus; + code: Omit; +}; diff --git a/platforms/garden-roof/src/features/invite-codes/http.ts b/platforms/garden-roof/src/features/invite-codes/http.ts new file mode 100644 index 0000000..17f4bb5 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const inviteCodesHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/invite-codes/index.ts b/platforms/garden-roof/src/features/invite-codes/index.ts new file mode 100644 index 0000000..a3613ea --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/index.ts @@ -0,0 +1,66 @@ +import './types'; + +export { activateInviteCode } from './actions/activate-invite-code'; +export { approveCapacityRequest } from './actions/approve-capacity-request'; +export { changeCapacity } from './actions/change-capacity'; +export { deactivateInviteCode } from './actions/deactivate-invite-code'; +export { rejectCapacityRequest } from './actions/reject-capacity-request'; +export { INVITE_CODE_EVENTS, INVITE_CODE_PARAMS } from './constants'; +export type { + CapacityRequestStatus, + InviteCodeStatus, +} from './entities/invite-code'; +export { useCodeActions } from './models/actions'; +export type { + CapacityForm, + CapacityNotice, + CodeActionsModel, + CodeDialog, +} from './models/actions'; +export { + useInviteCodeDetailPart, + useInviteCodeListPart, + useInviteCodesPage, +} from './models/codes'; +export type { + InviteCodeDetailPartModel, + InviteCodeListPartModel, + InviteCodesPageModel, +} from './models/codes'; +export { useInviteCodesSearch, useInviteCodesTabs } from './models/header'; +export type { + InviteCodesTab, + InviteCodesTabsModel, + InviteCodesTabsOptions, +} from './models/header'; +export { + useCapacityRequestListPart, + useCapacityRequestsPage, +} from './models/requests'; +export type { + CapacityRequestListPartModel, + CapacityRequestsPageModel, +} from './models/requests'; +export { + INVITE_CODE_ENDPOINTS, + INVITE_CODE_ERROR_CODES, + inviteCodeKeys, + inviteCodesRepository, +} from './repositories/invite-codes'; +export type { + ApproveCapacityRequestArgs, + CapacityPayload, + CapacityRequestPagePayload, + CapacityRequestPayload, + ChangeCapacityArgs, + CodeStatusPayload, + InviteCodeDetailPayload, + InviteCodeListItemPayload, + InviteCodePagePayload, + InviteCodeSummaryPayload, + ListCapacityRequestsArgs, + ListInviteCodesArgs, + PendingCapacityRequestPayload, + ReasonArgs, +} from './repositories/invite-codes'; +export { CODE_MAX_USES } from '../../shared/validations/codes-validations'; diff --git a/platforms/garden-roof/src/features/invite-codes/models/actions/index.ts b/platforms/garden-roof/src/features/invite-codes/models/actions/index.ts new file mode 100644 index 0000000..9f36fdb --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/actions/index.ts @@ -0,0 +1,7 @@ +export { useCodeActions } from './use-code-actions'; +export type { + CapacityForm, + CapacityNotice, + CodeActionsModel, + CodeDialog, +} from './types'; diff --git a/platforms/garden-roof/src/features/invite-codes/models/actions/types.ts b/platforms/garden-roof/src/features/invite-codes/models/actions/types.ts new file mode 100644 index 0000000..c68727d --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/actions/types.ts @@ -0,0 +1,61 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { ReasonForm } from '../../../../shared/utils'; +import type { + CapacityFormOutput, + CapacityFormValues, +} from '../../../../shared/validations/codes-validations'; +import type { + CapacityRequestPayload, + InviteCodeListItemPayload, + InviteCodeSummaryPayload, + PendingCapacityRequestPayload, +} from '../../repositories/invite-codes'; + +export type CapacityForm = UseFormReturn< + CapacityFormValues, + unknown, + CapacityFormOutput +>; + +/** + * The dialog on screen. «تغییر ظرفیت کد دعوت» (J11-6b) answers the code's pending request when it + * has one, so «تأیید» on a request and «تغییر ظرفیت» on its code are the same dialog. + */ +export type CodeDialog = + | { + kind: 'capacity'; + code: InviteCodeSummaryPayload; + request: PendingCapacityRequestPayload | null; + } + | { kind: 'reject'; request: CapacityRequestPayload } + | { kind: 'deactivate'; code: InviteCodeSummaryPayload } + | { kind: 'activate'; code: InviteCodeSummaryPayload }; + +/** + * What saving the typed capacity does for «لیست اطلاع‌رسانی»: `notify` when it opens seats on a + * full code, `held` when it would but the code is inactive or the analyst suspended. + */ +export type CapacityNotice = 'notify' | 'held' | null; + +export type CodeActionsModel = { + /** Kept while the dialog closes, so its content stays put. */ + dialog: CodeDialog | null; + isOpen: boolean; + /** The dialog's request is running: it can't be closed and confirm waits. */ + isSubmitting: boolean; + close: () => void; + /** «تغییر ظرفیت» on a code, pre-filled with its request's capacity when it has one. */ + openCapacity: (code: InviteCodeListItemPayload) => void; + /** «تأیید» on a request: the same dialog, pre-filled with the capacity asked. */ + openApprove: (request: CapacityRequestPayload) => void; + openReject: (request: CapacityRequestPayload) => void; + openDeactivate: (code: InviteCodeSummaryPayload) => void; + openActivate: (code: InviteCodeSummaryPayload) => void; + capacityForm: CapacityForm; + capacityNotice: CapacityNotice; + submitCapacity: () => void; + /** Reject, deactivate and activate: one at a time, so one form. */ + reasonForm: ReasonForm; + confirmReason: (reason: string) => void; +}; diff --git a/platforms/garden-roof/src/features/invite-codes/models/actions/use-code-actions.ts b/platforms/garden-roof/src/features/invite-codes/models/actions/use-code-actions.ts new file mode 100644 index 0000000..1986b5f --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/actions/use-code-actions.ts @@ -0,0 +1,253 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { iso, latinDigits, number } from '@lumina/tools/format'; +import { useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useForm, useWatch } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { showActionError, useReasonForm } from '../../../../shared/utils'; +import { + CODE_MAX_USES, + capacitySchema, +} from '../../../../shared/validations/codes-validations'; +import type { + CapacityFormOutput, + CapacityFormValues, +} from '../../../../shared/validations/codes-validations'; +import { panelKeys } from '../../../panel'; +import { activateInviteCode } from '../../actions/activate-invite-code'; +import { approveCapacityRequest } from '../../actions/approve-capacity-request'; +import { changeCapacity } from '../../actions/change-capacity'; +import { deactivateInviteCode } from '../../actions/deactivate-invite-code'; +import { rejectCapacityRequest } from '../../actions/reject-capacity-request'; +import { + INVITE_CODE_ERROR_CODES, + inviteCodeKeys, +} from '../../repositories/invite-codes'; +import type { CapacityPayload } from '../../repositories/invite-codes'; +import type { CapacityNotice, CodeActionsModel, CodeDialog } from './types'; + +type DialogState = { dialog: CodeDialog | null; isOpen: boolean }; + +/** + * The section's dialogs, on both tabs and the code's details (J11-6b/6e/6f): change or approve a + * capacity, reject a request, deactivate or activate a code, each with its «دلیل». A success + * toasts, closes the dialog and refreshes the codes, the requests and the sidebar count. A failed + * request keeps the dialog with its text, and confirm retries; one decided or changed elsewhere + * (409) closes it and reloads. + */ +export function useCodeActions(): CodeActionsModel { + const { t } = useTranslation('codes'); + const queryClient = useQueryClient(); + const [state, setState] = useState({ + dialog: null, + isOpen: false, + }); + const [isSubmitting, setIsSubmitting] = useState(false); + const reasonForm = useReasonForm(); + const { dialog } = state; + const bounds = + dialog?.kind === 'capacity' ? dialog.code : { usedCount: 0, maxUses: -1 }; + const capacityForm = useForm( + { + resolver: valibotResolver( + capacitySchema({ + usedCount: bounds.usedCount, + maxUses: bounds.maxUses, + }), + ), + defaultValues: { maxUses: '', reason: '' }, + }, + ); + const typedMaxUses = Number( + latinDigits( + useWatch({ control: capacityForm.control, name: 'maxUses' }), + ).trim() || NaN, + ); + + let capacityNotice: CapacityNotice = null; + if (dialog?.kind === 'capacity') { + const { code } = dialog; + const opensSeats = + code.usedCount >= code.maxUses && + Number.isInteger(typedMaxUses) && + typedMaxUses > code.usedCount && + typedMaxUses <= CODE_MAX_USES; + if (opensSeats && code.waitlistCount > 0) { + capacityNotice = + code.status === 'inactive' || code.analyst.isSuspended + ? 'held' + : 'notify'; + } + } + + const open = (next: CodeDialog) => setState({ dialog: next, isOpen: true }); + const close = () => setState((current) => ({ ...current, isOpen: false })); + + const refresh = () => + Promise.all([ + queryClient.invalidateQueries({ queryKey: inviteCodeKeys.all }), + queryClient.invalidateQueries({ queryKey: panelKeys.counts() }), + ]); + + const settle = async (message: string, description?: string) => { + showToast({ tone: 'success', message, description }); + close(); + await refresh(); + }; + + /** Decided or changed by someone else in the meantime (409): say so and show the news. */ + const refused = async (error: unknown): Promise => { + if (!isHttpError(error)) return false; + const message = + error.code === INVITE_CODE_ERROR_CODES.requestAlreadyDecided + ? t('already-decided') + : error.code === INVITE_CODE_ERROR_CODES.statusChanged + ? t('status-changed') + : null; + if (!message) return false; + close(); + showToast({ tone: 'info', message }); + await refresh(); + return true; + }; + + const run = async ( + task: () => Promise, + { + done, + failed, + retry, + }: { done: () => string; failed: string; retry: () => void }, + ) => { + if (isSubmitting) return; + setIsSubmitting(true); + try { + await task(); + await settle(done()); + } catch (error) { + if (!(await refused(error))) + showActionError(error, { t, failedMessage: failed, retry }); + } finally { + setIsSubmitting(false); + } + }; + + const confirmCapacity = async ({ maxUses, reason }: CapacityFormOutput) => { + if (dialog?.kind !== 'capacity' || isSubmitting) return; + const { code, request } = dialog; + setIsSubmitting(true); + try { + const result: CapacityPayload = request + ? await approveCapacityRequest({ + id: request.id, + codeId: code.id, + maxUses, + reason, + }) + : await changeCapacity({ id: code.id, maxUses, reason }); + const values = { code: iso(code.code), max: number(result.maxUses) }; + await settle( + request + ? t('capacity.approved', values) + : t('capacity.changed', values), + result.notifiedCount > 0 + ? t('capacity.notified', { + people: t('people', { value: number(result.notifiedCount) }), + }) + : undefined, + ); + } catch (error) { + if (await refused(error)) return; + if ( + isHttpError(error) && + error.code === INVITE_CODE_ERROR_CODES.capacityInvalid + ) { + // The seats used grew while the dialog was open: say so under the field. + capacityForm.setError( + 'maxUses', + { type: 'server', message: 'codes:capacity.errors.below-used' }, + { shouldFocus: true }, + ); + void queryClient.invalidateQueries({ queryKey: inviteCodeKeys.all }); + return; + } + showActionError(error, { + t, + failedMessage: request + ? t('capacity.approve-failed') + : t('capacity.change-failed'), + retry: () => void confirmCapacity({ maxUses, reason }), + }); + } finally { + setIsSubmitting(false); + } + }; + + const confirmReason = (reason: string) => { + if (dialog?.kind === 'reject') { + const { request } = dialog; + void run( + () => + rejectCapacityRequest({ + id: request.id, + codeId: request.code.id, + reason, + }), + { + done: () => t('reject.done'), + failed: t('reject.failed'), + retry: () => confirmReason(reason), + }, + ); + } else if (dialog?.kind === 'deactivate' || dialog?.kind === 'activate') { + const { code, kind } = dialog; + void run( + () => + kind === 'deactivate' + ? deactivateInviteCode({ id: code.id, reason }) + : activateInviteCode({ id: code.id, reason }), + { + done: () => t(`${kind}.done`, { code: iso(code.code) }), + failed: t(`${kind}.failed`), + retry: () => confirmReason(reason), + }, + ); + } + }; + + // A dialog closed and another opened before its exit ended: start from an empty reason. + const openReason = (next: Exclude) => { + reasonForm.reset(); + open(next); + }; + + const openCapacityFor = (next: Extract) => { + capacityForm.reset({ + maxUses: String(next.request?.requestedMaxUses ?? next.code.maxUses), + reason: '', + }); + open(next); + }; + + return { + dialog, + isOpen: state.isOpen, + isSubmitting, + close, + openCapacity: ({ pendingRequest, ...code }) => + openCapacityFor({ kind: 'capacity', code, request: pendingRequest }), + openApprove: ({ code, ...request }) => + openCapacityFor({ kind: 'capacity', code, request }), + openReject: (request) => openReason({ kind: 'reject', request }), + openDeactivate: (code) => openReason({ kind: 'deactivate', code }), + openActivate: (code) => openReason({ kind: 'activate', code }), + capacityForm, + capacityNotice, + submitCapacity: () => void capacityForm.handleSubmit(confirmCapacity)(), + reasonForm, + confirmReason, + }; +} diff --git a/platforms/garden-roof/src/features/invite-codes/models/codes/index.ts b/platforms/garden-roof/src/features/invite-codes/models/codes/index.ts new file mode 100644 index 0000000..e00168f --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/codes/index.ts @@ -0,0 +1,8 @@ +export { useInviteCodeDetailPart } from './use-invite-code-detail-part'; +export { useInviteCodeListPart } from './use-invite-code-list-part'; +export { useInviteCodesPage } from './use-invite-codes-page'; +export type { + InviteCodeDetailPartModel, + InviteCodeListPartModel, + InviteCodesPageModel, +} from './types'; diff --git a/platforms/garden-roof/src/features/invite-codes/models/codes/types.ts b/platforms/garden-roof/src/features/invite-codes/models/codes/types.ts new file mode 100644 index 0000000..a45eb70 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/codes/types.ts @@ -0,0 +1,42 @@ +import type { + InviteCodeDetailPayload, + InviteCodeListItemPayload, + ListInviteCodesArgs, +} from '../../repositories/invite-codes'; +import type { CodeActionsModel } from '../actions'; + +export type InviteCodesPageModel = { + /** What the rows read; a change remounts them behind their skeleton. */ + args: ListInviteCodesArgs; + /** Changes whenever `args` does: the rows' key. */ + argsKey: string; + /** + * «جزئیات کد دعوت» beside the list (J11-6g), open while the URL has `?code=`. `codeId` stays + * while the panel closes, so its content doesn't vanish mid-animation. + */ + detail: { isOpen: boolean; codeId: string | null }; + /** The address that opens a code's details, keeping the search and page. */ + codeHref: (id: string) => string; + openCode: (id: string) => void; + closeCode: () => void; + clearSearch: () => void; + actions: CodeActionsModel; +}; + +export type InviteCodeListPartModel = { + rows: InviteCodeListItemPayload[]; + page: number; + pageCount: number; + total: number; + from: number; + to: number; + pageHref: (page: number) => string; + /** No row: no code yet, or nothing matched the search. */ + empty: 'codes' | 'search' | null; +}; + +export type InviteCodeDetailPartModel = { + code: InviteCodeDetailPayload; + /** «کپی کد», with a toast either way. */ + copyCode: () => void; +}; diff --git a/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-code-detail-part.ts b/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-code-detail-part.ts new file mode 100644 index 0000000..27c79a8 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-code-detail-part.ts @@ -0,0 +1,33 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { useSuspenseQuery } from '@tanstack/react-query'; +import { useTranslation } from 'react-i18next'; + +import { + inviteCodeKeys, + inviteCodesRepository, +} from '../../repositories/invite-codes'; +import type { InviteCodeDetailPartModel } from './types'; + +/** One code's details (J11-6g): its facts, invite link and «گزارش ممیزی». */ +export function useInviteCodeDetailPart(id: string): InviteCodeDetailPartModel { + const { t } = useTranslation('codes'); + const { data: code } = useSuspenseQuery({ + queryKey: inviteCodeKeys.detail(id), + queryFn: ({ signal }) => inviteCodesRepository.get(id, { signal }), + }); + + const copyCode = () => { + navigator.clipboard + .writeText(code.code) + .then(() => showToast({ tone: 'success', message: t('detail.copied') })) + .catch(() => + showToast({ + tone: 'error', + message: t('detail.copy-failed'), + description: t('detail.copy-failed-description'), + }), + ); + }; + + return { code, copyCode }; +} diff --git a/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-code-list-part.ts b/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-code-list-part.ts new file mode 100644 index 0000000..055a43d --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-code-list-part.ts @@ -0,0 +1,38 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { INVITE_CODE_PARAMS } from '../../constants'; +import { + inviteCodeKeys, + inviteCodesRepository, +} from '../../repositories/invite-codes'; +import type { ListInviteCodesArgs } from '../../repositories/invite-codes'; +import type { InviteCodeListPartModel } from './types'; + +/** «همه کدها» rows for the search and page; 20 a page, most used first. */ +export function useInviteCodeListPart( + args: ListInviteCodesArgs, +): InviteCodeListPartModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data } = useSuspenseQuery({ + queryKey: inviteCodeKeys.list(args), + queryFn: ({ signal }) => inviteCodesRepository.list(args, { signal }), + }); + + return { + rows: data.items, + page: data.page, + pageCount: data.pageCount, + total: data.total, + from: data.from, + to: data.to, + pageHref: (page) => + listHref(pathname, searchParams, { + [INVITE_CODE_PARAMS.page]: page, + [INVITE_CODE_PARAMS.code]: null, + }), + empty: data.total > 0 ? null : args.q ? 'search' : 'codes', + }; +} diff --git a/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-codes-page.ts b/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-codes-page.ts new file mode 100644 index 0000000..f500d76 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/codes/use-invite-codes-page.ts @@ -0,0 +1,45 @@ +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; +import { useState } from 'react'; + +import { listHref, pageOf } from '../../../../shared/utils'; +import { INVITE_CODE_PARAMS } from '../../constants'; +import { useCodeActions } from '../actions'; +import type { InviteCodesPageModel } from './types'; + +/** + * «همه کدها» (J11-6): the search, the page and the open code live in the URL, so a reload or a + * shared link keeps them. Opening or closing a code's details keeps the list where it was. + */ +export function useInviteCodesPage(): InviteCodesPageModel { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const q = (searchParams.get(INVITE_CODE_PARAMS.q) ?? '').trim(); + const page = pageOf(searchParams.get(INVITE_CODE_PARAMS.page)); + const openCodeId = searchParams.get(INVITE_CODE_PARAMS.code); + const [shownCodeId, setShownCodeId] = useState(openCodeId); + if (openCodeId !== null && openCodeId !== shownCodeId) + setShownCodeId(openCodeId); + const actions = useCodeActions(); + + const withCode = (id: string | null) => + listHref(pathname, searchParams, { + [INVITE_CODE_PARAMS.code]: id, + [INVITE_CODE_PARAMS.page]: page, + }); + const args = { q: q || undefined, page }; + + return { + args, + argsKey: JSON.stringify(args), + detail: { isOpen: openCodeId !== null, codeId: shownCodeId }, + codeHref: withCode, + openCode: (id) => router.replace(withCode(id), { scroll: false }), + closeCode: () => router.replace(withCode(null), { scroll: false }), + clearSearch: () => + router.replace( + listHref(pathname, searchParams, { [INVITE_CODE_PARAMS.q]: null }), + ), + actions, + }; +} diff --git a/platforms/garden-roof/src/features/invite-codes/models/header/index.ts b/platforms/garden-roof/src/features/invite-codes/models/header/index.ts new file mode 100644 index 0000000..3cb050c --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/header/index.ts @@ -0,0 +1,7 @@ +export { useInviteCodesSearch } from './use-invite-codes-search'; +export { useInviteCodesTabs } from './use-invite-codes-tabs'; +export type { + InviteCodesTab, + InviteCodesTabsModel, + InviteCodesTabsOptions, +} from './types'; diff --git a/platforms/garden-roof/src/features/invite-codes/models/header/types.ts b/platforms/garden-roof/src/features/invite-codes/models/header/types.ts new file mode 100644 index 0000000..b324331 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/header/types.ts @@ -0,0 +1,15 @@ +/** The section's two tabs: each its own route. */ +export type InviteCodesTab = 'codes' | 'requests'; + +export type InviteCodesTabsOptions = { + /** The routes of «همه کدها» and «درخواست‌های افزایش», from the app's navigation. */ + routes: Record; +}; + +export type InviteCodesTabsModel = { + active: InviteCodesTab; + /** Each tab's address; a tab keeps the search and starts from page 1. */ + hrefs: Record; + /** Requests waiting for a decision, as the sidebar counts them; 0 hides the count. */ + pendingRequests: number; +}; diff --git a/platforms/garden-roof/src/features/invite-codes/models/header/use-invite-codes-search.ts b/platforms/garden-roof/src/features/invite-codes/models/header/use-invite-codes-search.ts new file mode 100644 index 0000000..b4c022e --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/header/use-invite-codes-search.ts @@ -0,0 +1,11 @@ +import { useListSearch } from '../../../../shared/utils'; +import type { ListSearch } from '../../../../shared/utils'; +import { INVITE_CODE_PARAMS } from '../../constants'; + +/** + * «جستجوی تحلیلگر یا کد» in the page header (J11-6), shared by both tabs: kept in the URL as `q` + * once typing pauses, so each tab's rows read it from there. + */ +export function useInviteCodesSearch(): ListSearch { + return useListSearch(INVITE_CODE_PARAMS.q); +} diff --git a/platforms/garden-roof/src/features/invite-codes/models/header/use-invite-codes-tabs.ts b/platforms/garden-roof/src/features/invite-codes/models/header/use-invite-codes-tabs.ts new file mode 100644 index 0000000..d4d4d66 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/header/use-invite-codes-tabs.ts @@ -0,0 +1,27 @@ +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { usePanelCounts } from '../../../panel'; +import { INVITE_CODE_PARAMS } from '../../constants'; +import type { InviteCodesTabsModel, InviteCodesTabsOptions } from './types'; + +/** + * «همه کدها» · «درخواست‌های افزایش ۲» (J11-6, 6d): the pending count is the sidebar's, so an + * approval or a rejection lowers both at once. + */ +export function useInviteCodesTabs({ + routes, +}: InviteCodesTabsOptions): InviteCodesTabsModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const counts = usePanelCounts(); + const q = searchParams.get(INVITE_CODE_PARAMS.q); + const hrefOf = (route: string) => + listHref(route, new URLSearchParams(), { [INVITE_CODE_PARAMS.q]: q }); + + return { + active: pathname === routes.requests ? 'requests' : 'codes', + hrefs: { codes: hrefOf(routes.codes), requests: hrefOf(routes.requests) }, + pendingRequests: counts?.codes ?? 0, + }; +} diff --git a/platforms/garden-roof/src/features/invite-codes/models/requests/index.ts b/platforms/garden-roof/src/features/invite-codes/models/requests/index.ts new file mode 100644 index 0000000..5f7d091 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/requests/index.ts @@ -0,0 +1,6 @@ +export { useCapacityRequestListPart } from './use-capacity-request-list-part'; +export { useCapacityRequestsPage } from './use-capacity-requests-page'; +export type { + CapacityRequestListPartModel, + CapacityRequestsPageModel, +} from './types'; diff --git a/platforms/garden-roof/src/features/invite-codes/models/requests/types.ts b/platforms/garden-roof/src/features/invite-codes/models/requests/types.ts new file mode 100644 index 0000000..763d0c0 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/requests/types.ts @@ -0,0 +1,25 @@ +import type { + CapacityRequestPayload, + ListCapacityRequestsArgs, +} from '../../repositories/invite-codes'; +import type { CodeActionsModel } from '../actions'; + +export type CapacityRequestsPageModel = { + /** What the rows read; a change remounts them behind their skeleton. */ + args: ListCapacityRequestsArgs; + argsKey: string; + clearSearch: () => void; + actions: CodeActionsModel; +}; + +export type CapacityRequestListPartModel = { + rows: CapacityRequestPayload[]; + page: number; + pageCount: number; + total: number; + from: number; + to: number; + pageHref: (page: number) => string; + /** No row: nothing waits, or nothing matched the search. */ + empty: 'requests' | 'search' | null; +}; diff --git a/platforms/garden-roof/src/features/invite-codes/models/requests/use-capacity-request-list-part.ts b/platforms/garden-roof/src/features/invite-codes/models/requests/use-capacity-request-list-part.ts new file mode 100644 index 0000000..f6b75ce --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/requests/use-capacity-request-list-part.ts @@ -0,0 +1,36 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { INVITE_CODE_PARAMS } from '../../constants'; +import { + inviteCodeKeys, + inviteCodesRepository, +} from '../../repositories/invite-codes'; +import type { ListCapacityRequestsArgs } from '../../repositories/invite-codes'; +import type { CapacityRequestListPartModel } from './types'; + +/** «درخواست‌های افزایش» rows for the search and page; 20 a page, oldest first. */ +export function useCapacityRequestListPart( + args: ListCapacityRequestsArgs, +): CapacityRequestListPartModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data } = useSuspenseQuery({ + queryKey: inviteCodeKeys.requestList(args), + queryFn: ({ signal }) => + inviteCodesRepository.listRequests(args, { signal }), + }); + + return { + rows: data.items, + page: data.page, + pageCount: data.pageCount, + total: data.total, + from: data.from, + to: data.to, + pageHref: (page) => + listHref(pathname, searchParams, { [INVITE_CODE_PARAMS.page]: page }), + empty: data.total > 0 ? null : args.q ? 'search' : 'requests', + }; +} diff --git a/platforms/garden-roof/src/features/invite-codes/models/requests/use-capacity-requests-page.ts b/platforms/garden-roof/src/features/invite-codes/models/requests/use-capacity-requests-page.ts new file mode 100644 index 0000000..09d0a83 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/models/requests/use-capacity-requests-page.ts @@ -0,0 +1,30 @@ +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; + +import { listHref, pageOf } from '../../../../shared/utils'; +import { INVITE_CODE_PARAMS } from '../../constants'; +import { useCodeActions } from '../actions'; +import type { CapacityRequestsPageModel } from './types'; + +/** + * «درخواست‌های افزایش» (J11-6d): the pending requests, oldest first, with the header's search and + * the page in the URL. «تأیید» opens «تغییر ظرفیت» pre-filled; «رد» asks the reason (J11-6e). + */ +export function useCapacityRequestsPage(): CapacityRequestsPageModel { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const q = (searchParams.get(INVITE_CODE_PARAMS.q) ?? '').trim(); + const page = pageOf(searchParams.get(INVITE_CODE_PARAMS.page)); + const actions = useCodeActions(); + const args = { q: q || undefined, page }; + + return { + args, + argsKey: JSON.stringify(args), + clearSearch: () => + router.replace( + listHref(pathname, searchParams, { [INVITE_CODE_PARAMS.q]: null }), + ), + actions, + }; +} diff --git a/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/constants.ts b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/constants.ts new file mode 100644 index 0000000..0b54c46 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/constants.ts @@ -0,0 +1,40 @@ +import type { ListCapacityRequestsArgs, ListInviteCodesArgs } from './types'; + +export const INVITE_CODE_ENDPOINTS = { + list: '/admin/invite-codes', + detail: (id: string) => `/admin/invite-codes/${encodeURIComponent(id)}`, + deactivate: (id: string) => + `/admin/invite-codes/${encodeURIComponent(id)}/deactivate`, + activate: (id: string) => + `/admin/invite-codes/${encodeURIComponent(id)}/activate`, + requests: '/admin/capacity-requests', + approveRequest: (id: string) => + `/admin/capacity-requests/${encodeURIComponent(id)}/approve`, + rejectRequest: (id: string) => + `/admin/capacity-requests/${encodeURIComponent(id)}/reject`, +} as const; + +/** The codes the API marks invite-code failures with; branch on these, never on the message. */ +export const INVITE_CODE_ERROR_CODES = { + /** 409: someone approved or rejected this request in the meantime. */ + requestAlreadyDecided: 'CAPACITY_REQUEST_ALREADY_DECIDED', + /** 409: the code was activated or deactivated in the meantime. */ + statusChanged: 'INVITE_CODE_STATUS_CHANGED', + /** + * 422: the capacity is under the seats used (they grew meanwhile, or under 1 on an unused code) + * or over 1000; `details: { usedCount, min, max }`. + */ + capacityInvalid: 'INVITE_CODE_CAPACITY_INVALID', +} as const; + +export const inviteCodeKeys = { + all: ['invite-codes'] as const, + lists: () => [...inviteCodeKeys.all, 'list'] as const, + list: (args: ListInviteCodesArgs) => + [...inviteCodeKeys.lists(), args] as const, + details: () => [...inviteCodeKeys.all, 'detail'] as const, + detail: (id: string) => [...inviteCodeKeys.details(), id] as const, + requests: () => [...inviteCodeKeys.all, 'requests'] as const, + requestList: (args: ListCapacityRequestsArgs) => + [...inviteCodeKeys.requests(), args] as const, +}; diff --git a/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/index.ts b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/index.ts new file mode 100644 index 0000000..15835f9 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/index.ts @@ -0,0 +1,22 @@ +export { + INVITE_CODE_ENDPOINTS, + INVITE_CODE_ERROR_CODES, + inviteCodeKeys, +} from './constants'; +export { inviteCodesRepository } from './invite-codes'; +export type { + ApproveCapacityRequestArgs, + CapacityPayload, + CapacityRequestPagePayload, + CapacityRequestPayload, + ChangeCapacityArgs, + CodeStatusPayload, + InviteCodeDetailPayload, + InviteCodeListItemPayload, + InviteCodePagePayload, + InviteCodeSummaryPayload, + ListCapacityRequestsArgs, + ListInviteCodesArgs, + PendingCapacityRequestPayload, + ReasonArgs, +} from './types'; diff --git a/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/invite-codes.ts b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/invite-codes.ts new file mode 100644 index 0000000..c386dde --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/invite-codes.ts @@ -0,0 +1,111 @@ +import { inviteCodesHttp } from '../../http'; +import { INVITE_CODE_ENDPOINTS } from './constants'; +import { + toCapacityDto, + toCapacityRequestPagePayload, + toCapacityRequestsQueryDto, + toInviteCodeDetailPayload, + toInviteCodePagePayload, + toInviteCodesQueryDto, + toReasonDto, +} from './mappers'; +import type { + ApproveCapacityRequestArgs, + CapacityPayload, + CapacityRequestPagePayload, + CapacityRequestPageResponseDto, + CapacityResponseDto, + ChangeCapacityArgs, + CodeStatusPayload, + CodeStatusResponseDto, + InviteCodeDetailPayload, + InviteCodeDetailResponseDto, + InviteCodePagePayload, + InviteCodePageResponseDto, + ListCapacityRequestsArgs, + ListInviteCodesArgs, + ReasonArgs, +} from './types'; + +/** + * Analysts' invite codes and their capacity requests (J11-6): the two lists, one code, and the + * changes an admin makes, each with a «دلیل» that the audit log keeps. + */ +export const inviteCodesRepository = { + /** «همه کدها», 20 a page, most used first, searched by analyst or code. */ + async list( + args: ListInviteCodesArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await inviteCodesHttp.get( + INVITE_CODE_ENDPOINTS.list, + { params: toInviteCodesQueryDto(args), signal }, + ); + return toInviteCodePagePayload(response); + }, + + /** One code with its invite link and «گزارش ممیزی» (J11-6g). */ + async get( + id: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await inviteCodesHttp.get( + INVITE_CODE_ENDPOINTS.detail(id), + { signal }, + ); + return toInviteCodeDetailPayload(response); + }, + + /** A new capacity from the seats used up to 1000; a full code's list hears seats opened. */ + async changeCapacity(args: ChangeCapacityArgs): Promise { + return inviteCodesHttp.patch( + INVITE_CODE_ENDPOINTS.detail(args.id), + toCapacityDto(args), + ); + }, + + /** Checkout refuses the code from now on; shared links still open the channel. */ + async deactivate(args: ReasonArgs): Promise { + return inviteCodesHttp.post( + INVITE_CODE_ENDPOINTS.deactivate(args.id), + toReasonDto(args), + ); + }, + + async activate(args: ReasonArgs): Promise { + return inviteCodesHttp.post( + INVITE_CODE_ENDPOINTS.activate(args.id), + toReasonDto(args), + ); + }, + + /** «درخواست‌های افزایش»: pending only, oldest first. */ + async listRequests( + args: ListCapacityRequestsArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await inviteCodesHttp.get( + INVITE_CODE_ENDPOINTS.requests, + { params: toCapacityRequestsQueryDto(args), signal }, + ); + return toCapacityRequestPagePayload(response); + }, + + /** Grants the request with the capacity the admin settled on, not always the one asked. */ + async approveRequest( + args: ApproveCapacityRequestArgs, + ): Promise { + return inviteCodesHttp.post( + INVITE_CODE_ENDPOINTS.approveRequest(args.id), + toCapacityDto(args), + ); + }, + + /** Refuses the request (204); the analyst gets the reason by in-app notice and SMS. */ + async rejectRequest(args: ReasonArgs): Promise { + await inviteCodesHttp.post( + INVITE_CODE_ENDPOINTS.rejectRequest(args.id), + toReasonDto(args), + ); + }, +}; diff --git a/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/mappers.ts b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/mappers.ts new file mode 100644 index 0000000..65d6fc8 --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/mappers.ts @@ -0,0 +1,143 @@ +import { toApiUrl } from '../../../../shared/utils'; +import { toAuditEntryPayload } from '../../../audit'; +import type { + CapacityRequestEntity, + InviteCodeListItemEntity, + PendingCapacityRequestEntity, +} from '../../entities/invite-code'; +import type { + CapacityDto, + CapacityRequestPagePayload, + CapacityRequestPageResponseDto, + CapacityRequestPayload, + CapacityRequestsQueryDto, + ChangeCapacityArgs, + InviteCodeDetailPayload, + InviteCodeDetailResponseDto, + InviteCodeListItemPayload, + InviteCodePagePayload, + InviteCodePageResponseDto, + InviteCodeSummaryPayload, + InviteCodesQueryDto, + ListCapacityRequestsArgs, + ListInviteCodesArgs, + PendingCapacityRequestPayload, + ReasonArgs, + ReasonDto, +} from './types'; + +/** The share of its capacity at which a code's meter turns warning (J11-6: ۱۸ از ۲۰). */ +const NEARLY_FULL_RATIO = 0.9; + +export function toCapacityRequestsQueryDto( + args: ListCapacityRequestsArgs, +): CapacityRequestsQueryDto { + return { query: args.q?.trim() || undefined, page: args.page }; +} + +export function toInviteCodesQueryDto( + args: ListInviteCodesArgs, +): InviteCodesQueryDto { + return { ...toCapacityRequestsQueryDto(args), status: args.status }; +} + +function toSummaryPayload( + dto: Omit, +): InviteCodeSummaryPayload { + return { + id: dto.id, + code: dto.code, + analyst: { + id: dto.analyst.id, + // Either name may be '' (an account without a profile name): the username stands in. + fullName: + [dto.analyst.firstName, dto.analyst.lastName] + .filter(Boolean) + .join(' ') || dto.analyst.username, + username: dto.analyst.username, + avatarUrl: toApiUrl(dto.analyst.avatarUrl), + isSuspended: dto.analyst.accountStatus === 'suspended', + }, + usedCount: dto.usedCount, + maxUses: dto.maxUses, + status: dto.status, + isNearlyFull: dto.usedCount >= dto.maxUses * NEARLY_FULL_RATIO, + waitlistCount: dto.waitlistCount, + }; +} + +function toPendingRequestPayload( + dto: PendingCapacityRequestEntity, +): PendingCapacityRequestPayload { + return { + id: dto.id, + requestedMaxUses: dto.requestedMaxUses, + note: dto.note.trim() || null, + createdAt: dto.createdAt, + }; +} + +function toListItemPayload( + dto: InviteCodeListItemEntity, +): InviteCodeListItemPayload { + return { + ...toSummaryPayload(dto), + pendingRequest: dto.pendingRequest + ? toPendingRequestPayload(dto.pendingRequest) + : null, + }; +} + +function toPagePayload( + dto: { items: T[]; page: number; pageSize: number; total: number }, + map: (item: T) => U, +) { + const from = dto.total === 0 ? 0 : (dto.page - 1) * dto.pageSize + 1; + return { + items: dto.items.map(map), + page: dto.page, + pageCount: Math.max(1, Math.ceil(dto.total / dto.pageSize)), + total: dto.total, + from, + to: from === 0 ? 0 : from + dto.items.length - 1, + }; +} + +export function toInviteCodePagePayload( + dto: InviteCodePageResponseDto, +): InviteCodePagePayload { + return toPagePayload(dto, toListItemPayload); +} + +function toCapacityRequestPayload( + dto: CapacityRequestEntity, +): CapacityRequestPayload { + return { ...toPendingRequestPayload(dto), code: toSummaryPayload(dto.code) }; +} + +export function toCapacityRequestPagePayload( + dto: CapacityRequestPageResponseDto, +): CapacityRequestPagePayload { + return toPagePayload(dto, toCapacityRequestPayload); +} + +export function toInviteCodeDetailPayload( + dto: InviteCodeDetailResponseDto, +): InviteCodeDetailPayload { + return { + ...toListItemPayload(dto), + inviteUrl: dto.inviteUrl, + inviteUrlLabel: dto.inviteUrl.replace(/^https?:\/\//, ''), + lastNotifiedAt: dto.lastNotifiedAt, + createdAt: dto.createdAt, + audit: dto.audit.map(toAuditEntryPayload), + }; +} + +export function toCapacityDto(args: ChangeCapacityArgs): CapacityDto { + return { maxUses: args.maxUses, reason: args.reason.trim() }; +} + +export function toReasonDto(args: ReasonArgs): ReasonDto { + return { reason: args.reason.trim() }; +} diff --git a/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/types.ts b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/types.ts new file mode 100644 index 0000000..d8bcacf --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/repositories/invite-codes/types.ts @@ -0,0 +1,130 @@ +import type { AuditEntryPayload } from '../../../audit'; +import type { + CapacityRequestEntity, + InviteCodeDetailEntity, + InviteCodeListItemEntity, + InviteCodeStatus, +} from '../../entities/invite-code'; + +// GET /admin/capacity-requests?query=&page= · GET /admin/invite-codes?query=&status=&page= + +/** «همه کدها» and «درخواست‌های افزایش» take the same search and page. */ +export type ListCapacityRequestsArgs = { + /** The analyst's name or username, or the code. */ + q?: string; + page: number; +}; + +export type ListInviteCodesArgs = ListCapacityRequestsArgs & { + /** Only codes in this status; the board lists them all. */ + status?: InviteCodeStatus; +}; + +export type CapacityRequestsQueryDto = { query?: string; page: number }; +export type InviteCodesQueryDto = CapacityRequestsQueryDto & { + status?: InviteCodeStatus; +}; + +type PageResponseDto = { + items: T[]; + page: number; + pageSize: number; + total: number; +}; + +/** Most used first, inactive codes last («ترتیب: بیشترین استفاده»). */ +export type InviteCodePageResponseDto = + PageResponseDto; + +/** Pending only, oldest first («ترتیب: قدیمی‌ترین اول»). */ +export type CapacityRequestPageResponseDto = + PageResponseDto; + +export type PendingCapacityRequestPayload = { + id: string; + requestedMaxUses: number; + /** The analyst's note; `null` when they left none. */ + note: string | null; + createdAt: string; +}; + +/** What every code row, dialog and detail shows about a code. */ +export type InviteCodeSummaryPayload = { + id: string; + code: string; + analyst: { + id: string; + fullName: string; + username: string; + avatarUrl: string | null; + isSuspended: boolean; + }; + usedCount: number; + maxUses: number; + status: InviteCodeStatus; + /** At 90% or more of its capacity: the meter turns warning (J11-6). */ + isNearlyFull: boolean; + waitlistCount: number; +}; + +export type InviteCodeListItemPayload = InviteCodeSummaryPayload & { + pendingRequest: PendingCapacityRequestPayload | null; +}; + +export type CapacityRequestPayload = PendingCapacityRequestPayload & { + code: InviteCodeSummaryPayload; +}; + +type PagePayload = { + items: T[]; + page: number; + pageCount: number; + total: number; + /** The first and last row's place among all rows, for «نمایش ۱ تا ۸ از ۸». */ + from: number; + to: number; +}; + +export type InviteCodePagePayload = PagePayload; +export type CapacityRequestPagePayload = PagePayload; + +// GET /admin/invite-codes/:id + +export type InviteCodeDetailResponseDto = InviteCodeDetailEntity; + +export type InviteCodeDetailPayload = InviteCodeListItemPayload & { + inviteUrl: string; + /** The link as the board writes it, without its scheme: `lumina.ir/@reza_ahmadi?code=REZA-2024`. */ + inviteUrlLabel: string; + lastNotifiedAt: string | null; + createdAt: string; + audit: AuditEntryPayload[]; +}; + +// PATCH /admin/invite-codes/:id { maxUses, reason } +// POST /admin/capacity-requests/:id/approve { maxUses, reason } + +export type ChangeCapacityArgs = { + id: string; + maxUses: number; + reason: string; +}; +export type ApproveCapacityRequestArgs = ChangeCapacityArgs; +export type CapacityDto = { maxUses: number; reason: string }; + +/** The code's new capacity, and how many on the list got «ظرفیت باز شد» (0 when none did). */ +export type CapacityResponseDto = { + maxUses: number; + status: InviteCodeStatus; + notifiedCount: number; +}; +export type CapacityPayload = CapacityResponseDto; + +// POST /admin/capacity-requests/:id/reject { reason } +// POST /admin/invite-codes/:id/deactivate|activate { reason } + +export type ReasonArgs = { id: string; reason: string }; +export type ReasonDto = { reason: string }; + +export type CodeStatusResponseDto = { status: InviteCodeStatus }; +export type CodeStatusPayload = CodeStatusResponseDto; diff --git a/platforms/garden-roof/src/features/invite-codes/types.ts b/platforms/garden-roof/src/features/invite-codes/types.ts new file mode 100644 index 0000000..7e31f0d --- /dev/null +++ b/platforms/garden-roof/src/features/invite-codes/types.ts @@ -0,0 +1,20 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'invite-code.capacity-changed': { + id: string; + maxUses: number; + notifiedCount: number; + }; + 'invite-code.deactivated': { id: string }; + 'invite-code.activated': { id: string }; + 'capacity-request.approved': { + id: string; + codeId: string; + maxUses: number; + notifiedCount: number; + }; + 'capacity-request.rejected': { id: string; codeId: string }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/features/panel/http.ts b/platforms/garden-roof/src/features/panel/http.ts new file mode 100644 index 0000000..05824fa --- /dev/null +++ b/platforms/garden-roof/src/features/panel/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const panelHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/panel/index.ts b/platforms/garden-roof/src/features/panel/index.ts new file mode 100644 index 0000000..566b19c --- /dev/null +++ b/platforms/garden-roof/src/features/panel/index.ts @@ -0,0 +1,7 @@ +export { usePanelCounts } from './models/counts'; +export { + COUNTS_ENDPOINTS, + countsRepository, + panelKeys, +} from './repositories/counts'; +export type { PanelCountsPayload } from './repositories/counts'; diff --git a/platforms/garden-roof/src/features/panel/models/counts/index.ts b/platforms/garden-roof/src/features/panel/models/counts/index.ts new file mode 100644 index 0000000..0087497 --- /dev/null +++ b/platforms/garden-roof/src/features/panel/models/counts/index.ts @@ -0,0 +1 @@ +export { usePanelCounts } from './use-panel-counts'; diff --git a/platforms/garden-roof/src/features/panel/models/counts/use-panel-counts.ts b/platforms/garden-roof/src/features/panel/models/counts/use-panel-counts.ts new file mode 100644 index 0000000..02f2f75 --- /dev/null +++ b/platforms/garden-roof/src/features/panel/models/counts/use-panel-counts.ts @@ -0,0 +1,25 @@ +import { useQuery } from '@tanstack/react-query'; + +import { useViewerStatus } from '../../../../stores/auth'; +import { + COUNTS_REFRESH_MS, + countsRepository, + panelKeys, +} from '../../repositories/counts'; +import type { PanelCountsPayload } from '../../repositories/counts'; + +/** + * The sidebar's counts, read once the admin is known and every minute after; a failed read keeps + * the last counts (or none), since the counts only point the way. + */ +export function usePanelCounts(): PanelCountsPayload | null { + const isMember = useViewerStatus() === 'member'; + const { data } = useQuery({ + queryKey: panelKeys.counts(), + queryFn: ({ signal }) => countsRepository.getCounts({ signal }), + enabled: isMember, + refetchInterval: COUNTS_REFRESH_MS, + throwOnError: false, + }); + return data ?? null; +} diff --git a/platforms/garden-roof/src/features/panel/repositories/counts/constants.ts b/platforms/garden-roof/src/features/panel/repositories/counts/constants.ts new file mode 100644 index 0000000..b0c4da2 --- /dev/null +++ b/platforms/garden-roof/src/features/panel/repositories/counts/constants.ts @@ -0,0 +1,9 @@ +export const COUNTS_ENDPOINTS = { counts: '/admin/counts' } as const; + +export const panelKeys = { + all: ['panel'] as const, + counts: () => [...panelKeys.all, 'counts'] as const, +}; + +/** The counts stay live while the panel is open (J11-2: «live pending count»). */ +export const COUNTS_REFRESH_MS = 60_000; diff --git a/platforms/garden-roof/src/features/panel/repositories/counts/counts.ts b/platforms/garden-roof/src/features/panel/repositories/counts/counts.ts new file mode 100644 index 0000000..2d113a3 --- /dev/null +++ b/platforms/garden-roof/src/features/panel/repositories/counts/counts.ts @@ -0,0 +1,17 @@ +import { panelHttp } from '../../http'; +import { COUNTS_ENDPOINTS } from './constants'; +import { toPanelCountsPayload } from './mappers'; +import type { CountsResponseDto, PanelCountsPayload } from './types'; + +/** What waits in each section: one read for the whole sidebar. */ +export const countsRepository = { + async getCounts({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await panelHttp.get( + COUNTS_ENDPOINTS.counts, + { signal }, + ); + return toPanelCountsPayload(response); + }, +}; diff --git a/platforms/garden-roof/src/features/panel/repositories/counts/index.ts b/platforms/garden-roof/src/features/panel/repositories/counts/index.ts new file mode 100644 index 0000000..e5bc334 --- /dev/null +++ b/platforms/garden-roof/src/features/panel/repositories/counts/index.ts @@ -0,0 +1,3 @@ +export { COUNTS_ENDPOINTS, COUNTS_REFRESH_MS, panelKeys } from './constants'; +export { countsRepository } from './counts'; +export type { PanelCountsPayload } from './types'; diff --git a/platforms/garden-roof/src/features/panel/repositories/counts/mappers.ts b/platforms/garden-roof/src/features/panel/repositories/counts/mappers.ts new file mode 100644 index 0000000..efb883f --- /dev/null +++ b/platforms/garden-roof/src/features/panel/repositories/counts/mappers.ts @@ -0,0 +1,13 @@ +import type { CountsResponseDto, PanelCountsPayload } from './types'; + +export function toPanelCountsPayload( + dto: CountsResponseDto, +): PanelCountsPayload { + // A count that couldn't be read shows nothing, like a count of 0: the counts only point the way. + return { + verify: dto.pendingVerifications ?? 0, + codes: dto.pendingCapacityRequests ?? 0, + preds: dto.predictionsNeedingReview ?? 0, + payouts: dto.payoutsReady ?? 0, + }; +} diff --git a/platforms/garden-roof/src/features/panel/repositories/counts/types.ts b/platforms/garden-roof/src/features/panel/repositories/counts/types.ts new file mode 100644 index 0000000..2ec3af7 --- /dev/null +++ b/platforms/garden-roof/src/features/panel/repositories/counts/types.ts @@ -0,0 +1,17 @@ +// GET /admin/counts + +/** Each count is `null` when admin-api couldn't read it (its service was down). */ +export type CountsResponseDto = { + pendingVerifications: number | null; + pendingCapacityRequests: number | null; + predictionsNeedingReview: number | null; + payoutsReady: number | null; +}; + +/** What waits in each section, as the sidebar's counts show it; none at 0. */ +export type PanelCountsPayload = { + verify: number; + codes: number; + preds: number; + payouts: number; +}; diff --git a/platforms/garden-roof/src/features/payouts/actions/cancel-payout/actions.ts b/platforms/garden-roof/src/features/payouts/actions/cancel-payout/actions.ts new file mode 100644 index 0000000..f0b8e65 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/actions/cancel-payout/actions.ts @@ -0,0 +1,27 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { PAYOUT_EVENTS } from '../../constants'; +import { payoutsRepository } from '../../repositories/payouts'; +import type { + CancelPayoutArgs, + PayoutActionPayload, +} from '../../repositories/payouts'; + +/** + * «لغو تسویه» (J11-9e): final. The amount goes back to the analyst's «قابل واریز», they get an SMS + * and a notice without the reason, and the reason shows in their payout's detail and the audit log. + * Emits `payout.cancelled`. + */ +export async function cancelPayout( + args: CancelPayoutArgs & { analystId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await payoutsRepository.cancel(args); + if (emit) { + eventEmitter.emit(PAYOUT_EVENTS.cancelled, { + id: args.id, + analystId: args.analystId, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/payouts/actions/cancel-payout/index.ts b/platforms/garden-roof/src/features/payouts/actions/cancel-payout/index.ts new file mode 100644 index 0000000..eaf4075 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/actions/cancel-payout/index.ts @@ -0,0 +1 @@ +export { cancelPayout } from './actions'; diff --git a/platforms/garden-roof/src/features/payouts/actions/create-payout/actions.ts b/platforms/garden-roof/src/features/payouts/actions/create-payout/actions.ts new file mode 100644 index 0000000..a2aa505 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/actions/create-payout/actions.ts @@ -0,0 +1,27 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { PAYOUT_EVENTS } from '../../constants'; +import { payoutsRepository } from '../../repositories/payouts'; +import type { + CreatePayoutArgs, + PayoutActionPayload, +} from '../../repositories/payouts'; + +/** + * «ایجاد تسویه» (J11-9b): the analyst's unpaid ledger lines through the period become one payout + * «در حال انجام», to the شبا registered now, frozen from then on; the analyst gets an SMS and an + * in-app notice (C20), and the audit log a row. Emits `payout.created`. + */ +export async function createPayout( + args: CreatePayoutArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await payoutsRepository.create(args); + if (emit) { + eventEmitter.emit(PAYOUT_EVENTS.created, { + id: result.id, + analystId: args.analystId, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/payouts/actions/create-payout/index.ts b/platforms/garden-roof/src/features/payouts/actions/create-payout/index.ts new file mode 100644 index 0000000..19c120d --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/actions/create-payout/index.ts @@ -0,0 +1 @@ +export { createPayout } from './actions'; diff --git a/platforms/garden-roof/src/features/payouts/actions/mark-payout-paid/actions.ts b/platforms/garden-roof/src/features/payouts/actions/mark-payout-paid/actions.ts new file mode 100644 index 0000000..dd33542 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/actions/mark-payout-paid/actions.ts @@ -0,0 +1,27 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { PAYOUT_EVENTS } from '../../constants'; +import { payoutsRepository } from '../../repositories/payouts'; +import type { + MarkPayoutPaidArgs, + PayoutActionPayload, +} from '../../repositories/payouts'; + +/** + * «ثبت پرداخت» (J11-9d): after the bank transfer, its tracking number and day (and a receipt, if + * any) close the payout as «انجام شده»; the audit log gets a row, with no free-text reason. + * Emits `payout.paid`. + */ +export async function markPayoutPaid( + args: MarkPayoutPaidArgs & { analystId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await payoutsRepository.markPaid(args); + if (emit) { + eventEmitter.emit(PAYOUT_EVENTS.paid, { + id: args.id, + analystId: args.analystId, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/payouts/actions/mark-payout-paid/index.ts b/platforms/garden-roof/src/features/payouts/actions/mark-payout-paid/index.ts new file mode 100644 index 0000000..78bbcb8 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/actions/mark-payout-paid/index.ts @@ -0,0 +1 @@ +export { markPayoutPaid } from './actions'; diff --git a/platforms/garden-roof/src/features/payouts/constants.ts b/platforms/garden-roof/src/features/payouts/constants.ts new file mode 100644 index 0000000..8b1a1e2 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/constants.ts @@ -0,0 +1,14 @@ +/** Events payout actions emit when they succeed. */ +export const PAYOUT_EVENTS = { + created: 'payout.created', + paid: 'payout.paid', + cancelled: 'payout.cancelled', +} as const; + +/** The URL's query parameters on the payouts page: the tab, the search, the page, the open payout. */ +export const PAYOUT_PARAMS = { + status: 'status', + q: 'q', + page: 'page', + id: 'id', +} as const; diff --git a/platforms/garden-roof/src/features/payouts/entities/payout/index.ts b/platforms/garden-roof/src/features/payouts/entities/payout/index.ts new file mode 100644 index 0000000..e7ebb99 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/entities/payout/index.ts @@ -0,0 +1,9 @@ +export type { + BillingPeriod, + LedgerLineEntity, + PayoutDetailEntity, + PayoutListItemEntity, + PayoutStatus, + PayoutTab, + ReadyPayoutEntity, +} from './types'; diff --git a/platforms/garden-roof/src/features/payouts/entities/payout/types.ts b/platforms/garden-roof/src/features/payouts/entities/payout/types.ts new file mode 100644 index 0000000..7a58516 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/entities/payout/types.ts @@ -0,0 +1,89 @@ +import type { AuditEntryEntity } from '../../../audit'; +import type { BillingPeriod } from '../../../../shared/constants'; + +/** C20's payout states: در حال انجام, انجام شده (paid), لغو شده. */ +export type PayoutStatus = 'in_progress' | 'paid' | 'cancelled'; + +/** The list's tabs (J11-9): what is ready to pay, then each payout state. */ +export type PayoutTab = 'ready' | PayoutStatus; + +export type { BillingPeriod }; + +/** A row of «آماده تسویه» (`GET /admin/payouts?status=ready`): no payout exists yet. */ +export type ReadyPayoutEntity = { + analystId: string; + firstName: string; + lastName: string; + username: string; + avatarUrl: string | null; + /** Tehran days, `YYYY-MM-DD`: Thursday to the Wednesday the period closed. */ + periodStart: string; + periodEnd: string; + /** Toman, from the ledger; never edited. */ + amount: number; + /** The شبا registered now (C19), `IR` and 24 digits; a payout freezes it when made. */ + sheba: string; + /** No bank check records the account holder's name yet (C19 keeps the number only). */ + holderName: string | null; +}; + +/** A row of the other tabs (`GET /admin/payouts?status=in_progress|paid|cancelled`). */ +export type PayoutListItemEntity = { + id: string; + analystId: string; + firstName: string; + lastName: string; + username: string; + avatarUrl: string | null; + periodStart: string; + periodEnd: string; + amount: number; + /** Frozen when the payout was made. */ + sheba: string; + holderName: string | null; + status: PayoutStatus; + createdAt: string; + /** + * The Tehran day the bank moved the money, `YYYY-MM-DD`. A paid payout may have none, nor a + * reference: the 72-hour sweep (C20) and the older route complete it without them. + */ + paidAt: string | null; + bankReference: string | null; + cancelledAt: string | null; +}; + +type LedgerLineBase = { + id: string; + /** Signed whole Toman: the analyst's share, + for income, − for a refund's deduction. */ + amount: number; + at: string; + subscriberUsername: string | null; + /** `null` on a correction, and on a line whose subscription period wasn't recorded. */ + billingPeriod: BillingPeriod | null; +}; + +/** + * One ledger line a payout pays, as the analyst's «گردش حساب» shows it (C20), or a ± correction + * an admin recorded on the balance (A15), with its reason. + */ +export type LedgerLineEntity = + | (LedgerLineBase & { + kind: 'income'; + paidAmount: number; + commissionPercent: number; + }) + | (LedgerLineBase & { kind: 'refund_deduction'; refundedAmount: number }) + | (LedgerLineBase & { kind: 'correction'; reason: string }); + +/** One payout (`GET /admin/payouts/:id`), with the lines it pays and its audit log. */ +export type PayoutDetailEntity = PayoutListItemEntity & { + /** + * Optional (J11-9d): admin-api's own route, `/v1/admin/payouts/:id/receipt`, which streams it to + * admins only. + */ + receiptUrl: string | null; + /** Shown to the analyst in their payout's detail; never in the SMS. */ + cancelReason: string | null; + lines: LedgerLineEntity[]; + audit: AuditEntryEntity[]; +}; diff --git a/platforms/garden-roof/src/features/payouts/http.ts b/platforms/garden-roof/src/features/payouts/http.ts new file mode 100644 index 0000000..23bb88b --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const payoutHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/payouts/index.ts b/platforms/garden-roof/src/features/payouts/index.ts new file mode 100644 index 0000000..a7dffa9 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/index.ts @@ -0,0 +1,56 @@ +import './types'; + +export { cancelPayout } from './actions/cancel-payout'; +export { createPayout } from './actions/create-payout'; +export { markPayoutPaid } from './actions/mark-payout-paid'; +export { PAYOUT_EVENTS, PAYOUT_PARAMS } from './constants'; +export type { BillingPeriod, PayoutStatus, PayoutTab } from './entities/payout'; +export { + usePayoutDetailPart, + usePayoutListPart, + usePayoutsPage, + usePayoutsSearch, + useReadyPayoutsPart, +} from './models/payouts'; +export type { + MarkPaidForm, + PayoutDetailPartModel, + PayoutDialog, + PayoutDialogKind, + PayoutDialogsModel, + PayoutListPartModel, + PayoutsPageModel, + PayoutsSearchModel, + ReadyPayoutsPartModel, +} from './models/payouts'; +export { + PAYOUT_ENDPOINTS, + PAYOUT_ERROR_CODES, + PAYOUT_TABS, + payoutKeys, + payoutsRepository, +} from './repositories/payouts'; +export type { + CancelPayoutArgs, + CreatePayoutArgs, + LedgerLinePayload, + ListPayoutsArgs, + ListReadyPayoutsArgs, + MarkPayoutPaidArgs, + PayoutActionPayload, + PayoutDetailPayload, + PayoutListArgs, + PayoutListItemPayload, + PayoutPagePayload, + ReadyPayoutPagePayload, + ReadyPayoutPayload, +} from './repositories/payouts'; +export { + BANK_REFERENCE_PATTERN, + markPaidSchema, + RECEIPT_FILE, +} from '../../shared/validations/payout-validations'; +export type { + MarkPaidFormOutput, + MarkPaidFormValues, +} from '../../shared/validations/payout-validations'; diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/index.ts b/platforms/garden-roof/src/features/payouts/models/payouts/index.ts new file mode 100644 index 0000000..f6f1798 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/index.ts @@ -0,0 +1,16 @@ +export { usePayoutDetailPart } from './use-payout-detail-part'; +export { usePayoutListPart } from './use-payout-list-part'; +export { usePayoutsPage } from './use-payouts-page'; +export { usePayoutsSearch } from './use-payouts-search'; +export { useReadyPayoutsPart } from './use-ready-payouts-part'; +export type { + MarkPaidForm, + PayoutDetailPartModel, + PayoutDialog, + PayoutDialogKind, + PayoutDialogsModel, + PayoutListPartModel, + PayoutsPageModel, + PayoutsSearchModel, + ReadyPayoutsPartModel, +} from './types'; diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/refusals.ts b/platforms/garden-roof/src/features/payouts/models/payouts/refusals.ts new file mode 100644 index 0000000..45f2a63 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/refusals.ts @@ -0,0 +1,75 @@ +import { isHttpError } from '@lumina/libs/http'; + +import { PAYOUT_ERROR_CODES } from '../../repositories/payouts'; +import type { PayoutDialogKind } from './types'; + +// admin-api words its refusals in English, so the screen words each one it can act on itself. + +/** The «ثبت پرداخت» fields a server refusal can point at. */ +type MarkPaidField = 'bankReference' | 'paidAt' | 'receipt'; + +/** + * A refusal saying the payout or the balance changed elsewhere: the dialog closes with this note + * (a `payouts` key) and the lists reload. `null` for any other failure. + */ +export function staleRefusal( + error: unknown, + kind: PayoutDialogKind, +): + | 'stale.settled' + | 'stale.ready' + | 'stale.no-account' + | 'stale.locked' + | 'stale.period' + | null { + if (!isHttpError(error)) return null; + switch (error.code) { + case PAYOUT_ERROR_CODES.notInProgress: + return 'stale.settled'; + case PAYOUT_ERROR_CODES.nothingToPay: + return 'stale.ready'; + case PAYOUT_ERROR_CODES.noAccount: + return 'stale.no-account'; + case PAYOUT_ERROR_CODES.accountLocked: + return 'stale.locked'; + // Create's only server-checked field is the ready row's period. + case PAYOUT_ERROR_CODES.validationFailed: + return kind === 'create' ? 'stale.period' : null; + default: + return null; + } +} + +/** + * A «ثبت پرداخت» refusal that belongs under one field, with its message as an i18n key: a tracking + * number on another payout, a day out of range, a receipt of another type or over 5 MB, or a + * receipt the file store couldn't keep (502, only when one was sent). `null` for any other. + */ +export function markPaidFieldRefusal( + error: unknown, + hasReceipt: boolean, +): { field: MarkPaidField; message: string } | null { + if (!isHttpError(error)) return null; + if (error.code === PAYOUT_ERROR_CODES.referenceUsed) { + return { + field: 'bankReference', + message: 'payouts:validation.reference-used', + }; + } + if ( + error.code === PAYOUT_ERROR_CODES.validationFailed && + error.fieldErrors?.paidAt + ) { + return { field: 'paidAt', message: 'payouts:validation.date-range' }; + } + if (error.status === 413) { + return { field: 'receipt', message: 'payouts:validation.receipt-size' }; + } + if (error.status === 400 && error.fieldErrors?.receipt) { + return { field: 'receipt', message: 'payouts:validation.receipt-type' }; + } + if (error.status === 502 && hasReceipt) { + return { field: 'receipt', message: 'payouts:validation.receipt-store' }; + } + return null; +} diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/tehran-days.ts b/platforms/garden-roof/src/features/payouts/models/payouts/tehran-days.ts new file mode 100644 index 0000000..874f650 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/tehran-days.ts @@ -0,0 +1,34 @@ +import { TIME_ZONE } from '@lumina/tools/format'; + +const DAY_MS = 86_400_000; + +/** `YYYY-MM-DD` in Tehran: the API's day for a payment, whatever the browser's time zone. */ +const dayFormatter = new Intl.DateTimeFormat('en-CA', { + timeZone: TIME_ZONE, + year: 'numeric', + month: '2-digit', + day: '2-digit', +}); + +export function tehranDayOf(at: string | number | Date): string { + return dayFormatter.format(at instanceof Date ? at : new Date(at)); +} + +/** + * The days a transfer can carry (J11-9d «تاریخ پرداخت»), newest first: today back to the day the + * payout was made, at most `max` of them. + */ +export function paidDaysSince( + createdAt: string, + now: number = Date.now(), + max = 60, +): string[] { + const first = tehranDayOf(createdAt); + const days: string[] = []; + for (let day = tehranDayOf(now); day >= first && days.length < max; ) { + days.push(day); + day = new Date(Date.parse(day) - DAY_MS).toISOString().slice(0, 10); + } + // A clock behind the payout's day still offers that day. + return days.length > 0 ? days : [first]; +} diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/types.ts b/platforms/garden-roof/src/features/payouts/models/payouts/types.ts new file mode 100644 index 0000000..462a269 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/types.ts @@ -0,0 +1,95 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { ListSearch, ReasonForm } from '../../../../shared/utils'; +import type { + MarkPaidFormOutput, + MarkPaidFormValues, +} from '../../../../shared/validations/payout-validations'; +import type { PayoutTab } from '../../entities/payout'; +import type { + PayoutDetailPayload, + PayoutListArgs, + PayoutListItemPayload, + ReadyPayoutPayload, +} from '../../repositories/payouts'; + +export type MarkPaidForm = UseFormReturn< + MarkPaidFormValues, + unknown, + MarkPaidFormOutput +>; + +/** Which dialog is up and for which row (J11-9b, 9d, 9e). */ +export type PayoutDialog = + | { kind: 'create'; payout: ReadyPayoutPayload } + | { kind: 'mark-paid'; payout: PayoutListItemPayload } + | { kind: 'cancel'; payout: PayoutListItemPayload }; + +export type PayoutDialogKind = PayoutDialog['kind']; + +export type PayoutDialogsModel = { + /** Kept while the dialog closes, so its content stays until it has gone. */ + dialog: PayoutDialog | null; + isOpen: boolean; + /** The action in flight: its dialog can't be closed meanwhile. */ + pending: PayoutDialogKind | null; + openCreate: (payout: ReadyPayoutPayload) => void; + openMarkPaid: (payout: PayoutListItemPayload) => void; + openCancel: (payout: PayoutListItemPayload) => void; + close: () => void; + onExited: () => void; + confirmCreate: () => void; + markPaidForm: MarkPaidForm; + /** The days the transfer can have happened, newest first: from the payout's day to today. */ + paidDays: string[]; + /** A picked receipt is checked at once; a rejected one leaves the box empty with its error. */ + pickReceipt: (file: File | null) => void; + confirmMarkPaid: () => void; + cancelForm: ReasonForm; + confirmCancel: (reason: string) => void; + copySheba: (sheba: string) => void; +}; + +export type PayoutsPageModel = { + status: PayoutTab; + /** Each tab's address; a tab starts again from page 1, keeps the search and closes the detail. */ + tabHref: (tab: PayoutTab) => string; + /** Analysts ready to pay, as the sidebar counts them; `null` until known. */ + readyCount: number | null; + /** What the rows read; a change remounts them behind their skeleton (J11-9). */ + args: PayoutListArgs; + /** Changes whenever `args` does: the rows' key. */ + argsKey: string; + /** The payout whose detail is open (`?id=`). */ + detailId: string | null; + /** The detail's payout, kept while the panel slides out. */ + shownDetailId: string | null; + openDetail: (id: string) => void; + closeDetail: () => void; + onDetailExited: () => void; + dialogs: PayoutDialogsModel; + /** From the detail (J11-9f): the panel closes and the dialog opens over the list. */ + markPaidFromDetail: (payout: PayoutListItemPayload) => void; + cancelFromDetail: (payout: PayoutListItemPayload) => void; +}; + +type ListPartModel = { + rows: T[]; + page: number; + pageCount: number; + total: number; + from: number; + to: number; + pageHref: (page: number) => string; + /** No row: nothing in this tab, or nothing matched the search. */ + empty: 'tab' | 'search' | null; + /** The list without its search. */ + clearSearchHref: string; +}; + +export type ReadyPayoutsPartModel = ListPartModel; +export type PayoutListPartModel = ListPartModel; + +export type PayoutDetailPartModel = { payout: PayoutDetailPayload }; + +export type PayoutsSearchModel = ListSearch; diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-detail-part.ts b/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-detail-part.ts new file mode 100644 index 0000000..e381f4e --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-detail-part.ts @@ -0,0 +1,13 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { payoutKeys, payoutsRepository } from '../../repositories/payouts'; +import type { PayoutDetailPartModel } from './types'; + +/** One payout in the side panel (J11-9f): its facts, the ledger lines it pays and its audit log. */ +export function usePayoutDetailPart(id: string): PayoutDetailPartModel { + const { data } = useSuspenseQuery({ + queryKey: payoutKeys.detail(id), + queryFn: ({ signal }) => payoutsRepository.get(id, { signal }), + }); + return { payout: data }; +} diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-dialogs.ts b/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-dialogs.ts new file mode 100644 index 0000000..c97ea6e --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-dialogs.ts @@ -0,0 +1,237 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { showToast } from '@lumina/island/molecules/toast'; +import { useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; +import * as v from 'valibot'; + +import { + applyServerErrors, + showActionError, + useReasonForm, +} from '../../../../shared/utils'; +import { + markPaidSchema, + receiptFile, +} from '../../../../shared/validations/payout-validations'; +import type { + MarkPaidFormOutput, + MarkPaidFormValues, +} from '../../../../shared/validations/payout-validations'; +import { panelKeys } from '../../../panel'; +import { cancelPayout } from '../../actions/cancel-payout'; +import { createPayout } from '../../actions/create-payout'; +import { markPayoutPaid } from '../../actions/mark-payout-paid'; +import type { PayoutTab } from '../../entities/payout'; +import { payoutKeys } from '../../repositories/payouts'; +import { markPaidFieldRefusal, staleRefusal } from './refusals'; +import { paidDaysSince, tehranDayOf } from './tehran-days'; +import type { + PayoutDialog, + PayoutDialogKind, + PayoutDialogsModel, +} from './types'; + +const EMPTY_MARK_PAID: MarkPaidFormValues = { + bankReference: '', + paidAt: '', + receipt: null, +}; + +/** + * The three payout dialogs (J11-9b, 9d, 9e) and their requests. Each success toasts in the + * board's words, refreshes the payouts and the sidebar count, then shows the tab the payout moved + * to: a new one in «در حال انجام», a paid one in «پرداخت‌شده», a cancelled one's amount back in + * «آماده تسویه». A failure keeps the dialog with what was typed, and confirm retries; a payout + * settled elsewhere, or a balance or account that changed meanwhile, closes the dialog and + * reloads. «ثبت پرداخت» puts a refused tracking number, day or receipt under its field. + */ +export function usePayoutDialogs({ + onDone, +}: { + onDone: (tab: PayoutTab) => void; +}): PayoutDialogsModel { + const { t } = useTranslation('payouts'); + const queryClient = useQueryClient(); + const [dialog, setDialog] = useState(null); + const [isOpen, setIsOpen] = useState(false); + const [pending, setPending] = useState(null); + const cancelForm = useReasonForm(); + const markPaidForm = useForm( + { + resolver: valibotResolver(markPaidSchema), + defaultValues: EMPTY_MARK_PAID, + }, + ); + + const open = (next: PayoutDialog) => { + if (next.kind === 'mark-paid') { + // Paid today unless the admin picks the day the bank moved the money. + markPaidForm.reset({ + ...EMPTY_MARK_PAID, + paidAt: tehranDayOf(Date.now()), + }); + } + setDialog(next); + setIsOpen(true); + }; + + const refresh = () => + Promise.all([ + queryClient.invalidateQueries({ queryKey: payoutKeys.all }), + queryClient.invalidateQueries({ queryKey: panelKeys.counts() }), + ]); + + const settle = async (tab: PayoutTab) => { + setIsOpen(false); + await refresh(); + onDone(tab); + }; + + const refused = async ( + error: unknown, + kind: PayoutDialogKind, + ): Promise => { + const message = staleRefusal(error, kind); + if (!message) return false; + setIsOpen(false); + showToast({ tone: 'info', message: t(message) }); + await refresh(); + return true; + }; + + const confirmCreate = async () => { + if (dialog?.kind !== 'create' || pending) return; + const { payout } = dialog; + setPending('create'); + try { + await createPayout({ + analystId: payout.analystId, + periodEnd: payout.periodEnd, + }); + showToast({ + tone: 'success', + message: t('create.done', { name: payout.fullName }), + }); + await settle('in_progress'); + } catch (error) { + if (!(await refused(error, 'create'))) { + showActionError(error, { + t, + failedMessage: t('create.failed'), + retry: () => void confirmCreate(), + }); + } + } finally { + setPending(null); + } + }; + + const submitMarkPaid = markPaidForm.handleSubmit(async (values) => { + if (dialog?.kind !== 'mark-paid' || pending) return; + const { payout } = dialog; + setPending('mark-paid'); + try { + await markPayoutPaid({ + id: payout.id, + analystId: payout.analystId, + ...values, + }); + showToast({ tone: 'success', message: t('mark-paid.done') }); + await settle('paid'); + } catch (error) { + const fieldRefusal = markPaidFieldRefusal(error, values.receipt !== null); + if (fieldRefusal) { + markPaidForm.setError( + fieldRefusal.field, + { type: 'server', message: fieldRefusal.message }, + { shouldFocus: true }, + ); + } else if (!(await refused(error, 'mark-paid'))) { + applyServerErrors(markPaidForm, error, { + t, + failedMessage: t('mark-paid.failed'), + retry: () => void submitMarkPaid(), + }); + } + } finally { + setPending(null); + } + }); + + const pickReceipt = (file: File | null) => { + const checked = file ? v.safeParse(receiptFile, file) : null; + if (checked && !checked.success) { + markPaidForm.setValue('receipt', null); + markPaidForm.setError('receipt', { + type: 'pick', + message: checked.issues[0].message, + }); + return; + } + markPaidForm.setValue('receipt', file, { shouldValidate: true }); + }; + + const confirmCancel = async (reason: string) => { + if (dialog?.kind !== 'cancel' || pending) return; + const { payout } = dialog; + setPending('cancel'); + try { + await cancelPayout({ + id: payout.id, + analystId: payout.analystId, + reason, + }); + showToast({ + tone: 'success', + message: t('cancel.done', { name: payout.fullName }), + }); + await settle('ready'); + } catch (error) { + if (!(await refused(error, 'cancel'))) { + showActionError(error, { + t, + failedMessage: t('cancel.failed'), + retry: () => void confirmCancel(reason), + }); + } + } finally { + setPending(null); + } + }; + + const copySheba = (sheba: string) => { + navigator.clipboard.writeText(sheba).then( + () => showToast({ tone: 'success', message: t('create.copied') }), + () => showToast({ tone: 'error', message: t('create.copy-failed') }), + ); + }; + + return { + dialog, + isOpen, + pending, + openCreate: (payout) => open({ kind: 'create', payout }), + openMarkPaid: (payout) => open({ kind: 'mark-paid', payout }), + openCancel: (payout) => open({ kind: 'cancel', payout }), + close: () => { + if (!pending) setIsOpen(false); + }, + onExited: () => { + setDialog(null); + markPaidForm.reset(EMPTY_MARK_PAID); + }, + confirmCreate: () => void confirmCreate(), + markPaidForm, + paidDays: + dialog?.kind === 'mark-paid' + ? paidDaysSince(dialog.payout.createdAt) + : [], + pickReceipt, + confirmMarkPaid: () => void submitMarkPaid(), + cancelForm, + confirmCancel: (reason) => void confirmCancel(reason), + copySheba, + }; +} diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-list-part.ts b/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-list-part.ts new file mode 100644 index 0000000..00bd056 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/use-payout-list-part.ts @@ -0,0 +1,36 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { PAYOUT_PARAMS } from '../../constants'; +import { payoutKeys, payoutsRepository } from '../../repositories/payouts'; +import type { ListPayoutsArgs } from '../../repositories/payouts'; +import type { PayoutListPartModel } from './types'; + +/** + * One state's payouts for the search and page, 20 a page: newest made (در حال انجام), newest + * paid (پرداخت‌شده, J11-9g) or newest cancelled (لغوشده) first. + */ +export function usePayoutListPart(args: ListPayoutsArgs): PayoutListPartModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data } = useSuspenseQuery({ + queryKey: payoutKeys.list(args), + queryFn: ({ signal }) => payoutsRepository.list(args, { signal }), + }); + + return { + rows: data.items, + page: data.page, + pageCount: data.pageCount, + total: data.total, + from: data.from, + to: data.to, + pageHref: (page) => + listHref(pathname, searchParams, { [PAYOUT_PARAMS.page]: page }), + empty: data.total > 0 ? null : args.q ? 'search' : 'tab', + clearSearchHref: listHref(pathname, searchParams, { + [PAYOUT_PARAMS.q]: null, + }), + }; +} diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/use-payouts-page.ts b/platforms/garden-roof/src/features/payouts/models/payouts/use-payouts-page.ts new file mode 100644 index 0000000..3d6ebb7 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/use-payouts-page.ts @@ -0,0 +1,76 @@ +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; +import { useState } from 'react'; + +import { listHref, oneOf, pageOf } from '../../../../shared/utils'; +import { usePanelCounts } from '../../../panel'; +import { PAYOUT_PARAMS } from '../../constants'; +import type { PayoutTab } from '../../entities/payout'; +import { PAYOUT_TABS } from '../../repositories/payouts'; +import type { PayoutListArgs } from '../../repositories/payouts'; +import type { PayoutsPageModel } from './types'; +import { usePayoutDialogs } from './use-payout-dialogs'; + +/** + * تسویه تحلیلگران (J11-9): the tab («آماده تسویه» by default, with the sidebar's count), the + * search, the page and the open payout (`?id=`, a side panel) live in the URL, so a reload or a + * shared link keeps them. Every tab, search or page change starts the rows again behind their + * skeleton; opening a payout leaves them as they are. + */ +export function usePayoutsPage(): PayoutsPageModel { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const status = oneOf(searchParams.get(PAYOUT_PARAMS.status), PAYOUT_TABS); + const page = pageOf(searchParams.get(PAYOUT_PARAMS.page)); + const q = searchParams.get(PAYOUT_PARAMS.q)?.trim() ?? ''; + const detailId = searchParams.get(PAYOUT_PARAMS.id) || null; + const counts = usePanelCounts(); + // The panel keeps showing its payout while it slides out after `?id=` is gone. + const [shownDetailId, setShownDetailId] = useState(detailId); + if (detailId && detailId !== shownDetailId) setShownDetailId(detailId); + + const tabHref = (tab: PayoutTab) => + listHref(pathname, searchParams, { + [PAYOUT_PARAMS.status]: tab === 'ready' ? null : tab, + [PAYOUT_PARAMS.id]: null, + }); + + const replaceDetail = (id: string | null) => + router.replace( + listHref(pathname, searchParams, { + [PAYOUT_PARAMS.id]: id, + [PAYOUT_PARAMS.page]: page, + }), + { scroll: false }, + ); + + const dialogs = usePayoutDialogs({ + onDone: (tab) => router.replace(tabHref(tab), { scroll: false }), + }); + + const args: PayoutListArgs = { status, q: q || undefined, page }; + + return { + status, + tabHref, + readyCount: counts?.payouts ?? null, + args, + argsKey: JSON.stringify(args), + detailId, + shownDetailId, + openDetail: (id) => replaceDetail(id), + closeDetail: () => replaceDetail(null), + onDetailExited: () => { + if (!detailId) setShownDetailId(null); + }, + dialogs, + markPaidFromDetail: (payout) => { + replaceDetail(null); + dialogs.openMarkPaid(payout); + }, + cancelFromDetail: (payout) => { + replaceDetail(null); + dialogs.openCancel(payout); + }, + }; +} diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/use-payouts-search.ts b/platforms/garden-roof/src/features/payouts/models/payouts/use-payouts-search.ts new file mode 100644 index 0000000..a617204 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/use-payouts-search.ts @@ -0,0 +1,11 @@ +import { useListSearch } from '../../../../shared/utils'; +import { PAYOUT_PARAMS } from '../../constants'; +import type { PayoutsSearchModel } from './types'; + +/** + * «جستجوی تحلیلگر» in the page header (J11-9): kept in the URL as `q` once typing pauses, for + * every tab, back to page 1. + */ +export function usePayoutsSearch(): PayoutsSearchModel { + return useListSearch(PAYOUT_PARAMS.q); +} diff --git a/platforms/garden-roof/src/features/payouts/models/payouts/use-ready-payouts-part.ts b/platforms/garden-roof/src/features/payouts/models/payouts/use-ready-payouts-part.ts new file mode 100644 index 0000000..b72c64f --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/models/payouts/use-ready-payouts-part.ts @@ -0,0 +1,35 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { PAYOUT_PARAMS } from '../../constants'; +import { payoutKeys, payoutsRepository } from '../../repositories/payouts'; +import type { ListReadyPayoutsArgs } from '../../repositories/payouts'; +import type { ReadyPayoutsPartModel } from './types'; + +/** «آماده تسویه» rows for the search and page: largest balance first, 20 a page (J11-9). */ +export function useReadyPayoutsPart( + args: ListReadyPayoutsArgs, +): ReadyPayoutsPartModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data } = useSuspenseQuery({ + queryKey: payoutKeys.list(args), + queryFn: ({ signal }) => payoutsRepository.listReady(args, { signal }), + }); + + return { + rows: data.items, + page: data.page, + pageCount: data.pageCount, + total: data.total, + from: data.from, + to: data.to, + pageHref: (page) => + listHref(pathname, searchParams, { [PAYOUT_PARAMS.page]: page }), + empty: data.total > 0 ? null : args.q ? 'search' : 'tab', + clearSearchHref: listHref(pathname, searchParams, { + [PAYOUT_PARAMS.q]: null, + }), + }; +} diff --git a/platforms/garden-roof/src/features/payouts/repositories/payouts/constants.ts b/platforms/garden-roof/src/features/payouts/repositories/payouts/constants.ts new file mode 100644 index 0000000..416fe00 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/repositories/payouts/constants.ts @@ -0,0 +1,47 @@ +import type { PayoutTab } from '../../entities/payout'; +import type { PayoutListArgs } from './types'; + +export const PAYOUT_ENDPOINTS = { + list: '/admin/payouts', + create: '/admin/payouts', + detail: (id: string) => `/admin/payouts/${encodeURIComponent(id)}`, + markPaid: (id: string) => + `/admin/payouts/${encodeURIComponent(id)}/mark-paid`, + cancel: (id: string) => `/admin/payouts/${encodeURIComponent(id)}/cancel`, +} as const; + +/** The tabs in display order: آماده تسویه · در حال انجام · پرداخت‌شده · لغوشده. */ +export const PAYOUT_TABS = [ + 'ready', + 'in_progress', + 'paid', + 'cancelled', +] as const satisfies readonly PayoutTab[]; + +/** + * The codes the API marks payout failures with; branch on these, never on the message. A 404 has + * no code (check `status`), nor does a refused receipt (400 on `receipt`, 413 over 5 MB, 502 when + * the file store fails). + */ +export const PAYOUT_ERROR_CODES = { + /** 409 mark-paid / cancel: paid or cancelled in the meantime (`details.status`). */ + notInProgress: 'PAYOUT_NOT_IN_PROGRESS', + /** 409 create: the balance changed (a refund, or another admin made the payout); nothing left to pay. */ + nothingToPay: 'PAYOUT_NOTHING_TO_PAY', + /** 422 create: the analyst has no شبا registered. */ + noAccount: 'PAYOUT_ACCOUNT_MISSING', + /** 409 create: the analyst's account is suspended. */ + accountLocked: 'PAYOUT_ACCOUNT_LOCKED', + /** 409 mark-paid: the tracking number is on another payout (field map on `bankReference`). */ + referenceUsed: 'BANK_REFERENCE_USED', + /** 422: a field only the server can check (`paidAt` out of range, `periodEnd` not a period's end). */ + validationFailed: 'VALIDATION_FAILED', +} as const; + +export const payoutKeys = { + all: ['payouts'] as const, + lists: () => [...payoutKeys.all, 'list'] as const, + list: (args: PayoutListArgs) => [...payoutKeys.lists(), args] as const, + details: () => [...payoutKeys.all, 'detail'] as const, + detail: (id: string) => [...payoutKeys.details(), id] as const, +}; diff --git a/platforms/garden-roof/src/features/payouts/repositories/payouts/index.ts b/platforms/garden-roof/src/features/payouts/repositories/payouts/index.ts new file mode 100644 index 0000000..152f587 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/repositories/payouts/index.ts @@ -0,0 +1,22 @@ +export { + PAYOUT_ENDPOINTS, + PAYOUT_ERROR_CODES, + PAYOUT_TABS, + payoutKeys, +} from './constants'; +export { payoutsRepository } from './payouts'; +export type { + CancelPayoutArgs, + CreatePayoutArgs, + LedgerLinePayload, + ListPayoutsArgs, + ListReadyPayoutsArgs, + MarkPayoutPaidArgs, + PayoutActionPayload, + PayoutDetailPayload, + PayoutListArgs, + PayoutListItemPayload, + PayoutPagePayload, + ReadyPayoutPagePayload, + ReadyPayoutPayload, +} from './types'; diff --git a/platforms/garden-roof/src/features/payouts/repositories/payouts/mappers.ts b/platforms/garden-roof/src/features/payouts/repositories/payouts/mappers.ts new file mode 100644 index 0000000..feb369a --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/repositories/payouts/mappers.ts @@ -0,0 +1,156 @@ +import { toApiUrl } from '../../../../shared/utils'; +import { toAuditEntryPayload } from '../../../audit'; +import type { + LedgerLineEntity, + PayoutListItemEntity, + ReadyPayoutEntity, +} from '../../entities/payout'; +import type { + CancelPayoutArgs, + CancelPayoutDto, + CreatePayoutArgs, + CreatePayoutDto, + LedgerLinePayload, + ListPayoutsQueryDto, + MarkPayoutPaidArgs, + MarkPayoutPaidDto, + PayoutDetailPayload, + PayoutDetailResponseDto, + PayoutListArgs, + PayoutListItemPayload, + PayoutPagePayload, + PayoutPageResponseDto, + ReadyPayoutPagePayload, + ReadyPayoutPageResponseDto, + ReadyPayoutPayload, +} from './types'; + +/** `IR` + two check digits, then the bank's three digits. */ +function bankCodeOf(sheba: string): string { + return sheba.slice(4, 7); +} + +/** The API sends '' for a missing first name (the channel's name stands in as the last). */ +function fullNameOf(dto: { + firstName: string; + lastName: string; + username: string; +}): string { + return ( + [dto.firstName, dto.lastName].filter(Boolean).join(' ') || dto.username + ); +} + +function pageOf( + dto: { page: number; pageSize: number; total: number }, + items: T[], +) { + const from = dto.total === 0 ? 0 : (dto.page - 1) * dto.pageSize + 1; + return { + items, + page: dto.page, + pageCount: Math.max(1, Math.ceil(dto.total / dto.pageSize)), + total: dto.total, + from, + to: from === 0 ? 0 : from + items.length - 1, + }; +} + +export function toListPayoutsQueryDto( + args: PayoutListArgs, +): ListPayoutsQueryDto { + return { + status: args.status, + q: args.q?.trim() || undefined, + page: args.page, + }; +} + +function toReadyPayoutPayload(dto: ReadyPayoutEntity): ReadyPayoutPayload { + return { + analystId: dto.analystId, + fullName: fullNameOf(dto), + username: dto.username, + avatarUrl: toApiUrl(dto.avatarUrl), + periodStart: dto.periodStart, + periodEnd: dto.periodEnd, + amount: dto.amount, + sheba: dto.sheba, + holderName: dto.holderName, + bankCode: bankCodeOf(dto.sheba), + }; +} + +export function toReadyPayoutPagePayload( + dto: ReadyPayoutPageResponseDto, +): ReadyPayoutPagePayload { + return pageOf(dto, dto.items.map(toReadyPayoutPayload)); +} + +function toPayoutListItemPayload( + dto: PayoutListItemEntity, +): PayoutListItemPayload { + return { + id: dto.id, + analystId: dto.analystId, + fullName: fullNameOf(dto), + username: dto.username, + avatarUrl: toApiUrl(dto.avatarUrl), + periodStart: dto.periodStart, + periodEnd: dto.periodEnd, + amount: dto.amount, + sheba: dto.sheba, + holderName: dto.holderName, + bankCode: bankCodeOf(dto.sheba), + status: dto.status, + createdAt: dto.createdAt, + paidAt: dto.paidAt, + bankReference: dto.bankReference, + cancelledAt: dto.cancelledAt, + }; +} + +export function toPayoutPagePayload( + dto: PayoutPageResponseDto, +): PayoutPagePayload { + return pageOf(dto, dto.items.map(toPayoutListItemPayload)); +} + +function toLedgerLinePayload(dto: LedgerLineEntity): LedgerLinePayload { + return { + id: dto.id, + kind: dto.kind, + amount: dto.amount, + at: dto.at, + subscriberUsername: dto.subscriberUsername, + billingPeriod: dto.billingPeriod, + reason: dto.kind === 'correction' ? dto.reason || null : null, + }; +} + +export function toPayoutDetailPayload( + dto: PayoutDetailResponseDto, +): PayoutDetailPayload { + return { + ...toPayoutListItemPayload(dto), + // admin-api's route (`/v1/admin/payouts/:id/receipt`), through this site's API proxy. + receiptUrl: toApiUrl(dto.receiptUrl), + cancelReason: dto.cancelReason, + lines: dto.lines.map(toLedgerLinePayload), + audit: dto.audit.map(toAuditEntryPayload), + }; +} + +export function toCreatePayoutDto(args: CreatePayoutArgs): CreatePayoutDto { + return { analystId: args.analystId, periodEnd: args.periodEnd }; +} + +export function toMarkPayoutPaidDto( + args: MarkPayoutPaidArgs, +): MarkPayoutPaidDto { + return { bankReference: args.bankReference, paidAt: args.paidAt }; +} + +export function toCancelPayoutDto(args: CancelPayoutArgs): CancelPayoutDto { + return { reason: args.reason.trim() }; +} diff --git a/platforms/garden-roof/src/features/payouts/repositories/payouts/payouts.ts b/platforms/garden-roof/src/features/payouts/repositories/payouts/payouts.ts new file mode 100644 index 0000000..de91c90 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/repositories/payouts/payouts.ts @@ -0,0 +1,106 @@ +import { payoutHttp } from '../../http'; +import { PAYOUT_ENDPOINTS } from './constants'; +import { + toCancelPayoutDto, + toCreatePayoutDto, + toListPayoutsQueryDto, + toMarkPayoutPaidDto, + toPayoutDetailPayload, + toPayoutPagePayload, + toReadyPayoutPagePayload, +} from './mappers'; +import type { + CancelPayoutArgs, + CreatePayoutArgs, + ListPayoutsArgs, + ListReadyPayoutsArgs, + MarkPayoutPaidArgs, + PayoutActionPayload, + PayoutActionResponseDto, + PayoutDetailPayload, + PayoutDetailResponseDto, + PayoutPagePayload, + PayoutPageResponseDto, + ReadyPayoutPagePayload, + ReadyPayoutPageResponseDto, +} from './types'; + +/** The multipart field admin-api reads a receipt from. */ +const RECEIPT_FIELD = 'receipt'; + +function toActionPayload(dto: PayoutActionResponseDto): PayoutActionPayload { + return { id: dto.id, status: dto.status }; +} + +/** Analysts' weekly payouts (J11-9): what is ready, each payout state, one payout, three actions. */ +export const payoutsRepository = { + /** «آماده تسویه»: analysts with a شبا and a balance through the last closed period, 20 a page. */ + async listReady( + args: ListReadyPayoutsArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await payoutHttp.get( + PAYOUT_ENDPOINTS.list, + { params: toListPayoutsQueryDto(args), signal }, + ); + return toReadyPayoutPagePayload(response); + }, + + /** Payouts in one state, newest first, 20 a page. */ + async list( + args: ListPayoutsArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await payoutHttp.get( + PAYOUT_ENDPOINTS.list, + { params: toListPayoutsQueryDto(args), signal }, + ); + return toPayoutPagePayload(response); + }, + + /** One payout with the ledger lines it pays, its receipt link and its audit log. */ + async get( + id: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await payoutHttp.get( + PAYOUT_ENDPOINTS.detail(id), + { signal }, + ); + return toPayoutDetailPayload(response); + }, + + /** Makes the payout from the ledger with the شبا of now; the analyst gets an SMS and a notice. */ + async create(args: CreatePayoutArgs): Promise { + const response = await payoutHttp.post( + PAYOUT_ENDPOINTS.create, + toCreatePayoutDto(args), + ); + return toActionPayload(response); + }, + + /** + * Records the bank transfer: its tracking number, its day and an optional receipt. With a + * receipt the fields travel beside it as multipart; without one, as JSON. + */ + async markPaid(args: MarkPayoutPaidArgs): Promise { + const url = PAYOUT_ENDPOINTS.markPaid(args.id); + const dto = toMarkPayoutPaidDto(args); + const response = args.receipt + ? await payoutHttp.upload(url, args.receipt, { + fieldName: RECEIPT_FIELD, + fields: dto, + }) + : await payoutHttp.post(url, dto); + return toActionPayload(response); + }, + + /** Cancels for good: the amount goes back to «قابل واریز»; the analyst sees the reason. */ + async cancel(args: CancelPayoutArgs): Promise { + const response = await payoutHttp.post( + PAYOUT_ENDPOINTS.cancel(args.id), + toCancelPayoutDto(args), + ); + return toActionPayload(response); + }, +}; diff --git a/platforms/garden-roof/src/features/payouts/repositories/payouts/types.ts b/platforms/garden-roof/src/features/payouts/repositories/payouts/types.ts new file mode 100644 index 0000000..9554269 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/repositories/payouts/types.ts @@ -0,0 +1,151 @@ +import type { AuditEntryPayload } from '../../../audit'; +import type { + BillingPeriod, + PayoutDetailEntity, + PayoutListItemEntity, + PayoutStatus, + ReadyPayoutEntity, +} from '../../entities/payout'; + +// GET /admin/payouts?status=ready|in_progress|paid|cancelled&q=&page= + +export type ListReadyPayoutsArgs = { + status: 'ready'; + /** The analyst's first, last or full name, or username. */ + q?: string; + page: number; +}; + +export type ListPayoutsArgs = { + status: PayoutStatus; + q?: string; + page: number; +}; + +/** What a tab's rows read; a change remounts them behind their skeleton. */ +export type PayoutListArgs = ListReadyPayoutsArgs | ListPayoutsArgs; + +export type ListPayoutsQueryDto = { + status: PayoutListArgs['status']; + q?: string; + page: number; +}; + +export type ReadyPayoutPageResponseDto = { + items: ReadyPayoutEntity[]; + page: number; + pageSize: number; + total: number; +}; + +export type PayoutPageResponseDto = { + items: PayoutListItemEntity[]; + page: number; + pageSize: number; + total: number; +}; + +/** An analyst's balance to pay, as «آماده تسویه» and «ایجاد تسویه» show it. */ +export type ReadyPayoutPayload = { + analystId: string; + fullName: string; + username: string; + avatarUrl: string | null; + periodStart: string; + periodEnd: string; + amount: number; + sheba: string; + /** Not recorded by the API yet: the screens show the bank alone. */ + holderName: string | null; + /** The three digits after the check digits, for the bank's name. */ + bankCode: string; +}; + +export type PayoutListItemPayload = { + id: string; + analystId: string; + fullName: string; + username: string; + avatarUrl: string | null; + periodStart: string; + periodEnd: string; + amount: number; + sheba: string; + holderName: string | null; + bankCode: string; + status: PayoutStatus; + createdAt: string; + paidAt: string | null; + bankReference: string | null; + cancelledAt: string | null; +}; + +type PagePayload = { + items: T[]; + page: number; + pageCount: number; + total: number; + /** The first and last row's place among all rows, for «نمایش ۱ تا ۲۰ از ۴۷». */ + from: number; + to: number; +}; + +export type ReadyPayoutPagePayload = PagePayload; +export type PayoutPagePayload = PagePayload; + +// GET /admin/payouts/:id + +export type PayoutDetailResponseDto = PayoutDetailEntity; + +export type LedgerLinePayload = { + id: string; + kind: 'income' | 'refund_deduction' | 'correction'; + /** Signed: the analyst's share, the share a refund took back, or an admin's correction. */ + amount: number; + at: string; + subscriberUsername: string | null; + billingPeriod: BillingPeriod | null; + /** A correction's reason; `null` on the other lines. */ + reason: string | null; +}; + +export type PayoutDetailPayload = PayoutListItemPayload & { + receiptUrl: string | null; + cancelReason: string | null; + lines: LedgerLinePayload[]; + audit: AuditEntryPayload[]; +}; + +// POST /admin/payouts { analystId, periodEnd } → 201 + +export type CreatePayoutArgs = { + analystId: string; + /** The Wednesday the period closed, `YYYY-MM-DD`, from the ready row. */ + periodEnd: string; +}; +export type CreatePayoutDto = { analystId: string; periodEnd: string }; + +// POST /admin/payouts/:id/mark-paid { bankReference, paidAt }: JSON, or multipart with `receipt` + +export type MarkPayoutPaidArgs = { + id: string; + bankReference: string; + /** The Tehran day the bank moved the money, `YYYY-MM-DD`. */ + paidAt: string; + receipt: File | null; +}; + +/** The form fields; a receipt goes beside them as the multipart `receipt` file. */ +export type MarkPayoutPaidDto = { + bankReference: string; + paidAt: string; +}; + +// POST /admin/payouts/:id/cancel { reason } + +export type CancelPayoutArgs = { id: string; reason: string }; +export type CancelPayoutDto = { reason: string }; + +/** Every payout action answers with the payout's id and its state after it. */ +export type PayoutActionResponseDto = { id: string; status: PayoutStatus }; +export type PayoutActionPayload = { id: string; status: PayoutStatus }; diff --git a/platforms/garden-roof/src/features/payouts/types.ts b/platforms/garden-roof/src/features/payouts/types.ts new file mode 100644 index 0000000..90886c5 --- /dev/null +++ b/platforms/garden-roof/src/features/payouts/types.ts @@ -0,0 +1,9 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'payout.created': { id: string; analystId: string }; + 'payout.paid': { id: string; analystId: string }; + 'payout.cancelled': { id: string; analystId: string }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/features/predictions/actions/dismiss-proposal/actions.ts b/platforms/garden-roof/src/features/predictions/actions/dismiss-proposal/actions.ts new file mode 100644 index 0000000..00d4a01 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/dismiss-proposal/actions.ts @@ -0,0 +1,18 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { PREDICTION_EVENTS } from '../../constants'; +import { predictionsRepository } from '../../repositories/predictions'; +import type { DismissProposalArgs } from '../../repositories/predictions'; + +/** + * «رد پیشنهاد» (J11-8h): the prediction stays open and the checks go on; the recorded price stays + * in the audit log with the reason. Emits `prediction.proposal_dismissed`. + */ +export async function dismissProposal( + args: DismissProposalArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + await predictionsRepository.dismissProposal(args); + if (emit) + eventEmitter.emit(PREDICTION_EVENTS.proposalDismissed, { id: args.id }); +} diff --git a/platforms/garden-roof/src/features/predictions/actions/dismiss-proposal/index.ts b/platforms/garden-roof/src/features/predictions/actions/dismiss-proposal/index.ts new file mode 100644 index 0000000..13049bf --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/dismiss-proposal/index.ts @@ -0,0 +1 @@ +export { dismissProposal } from './actions'; diff --git a/platforms/garden-roof/src/features/predictions/actions/flag-prediction/actions.ts b/platforms/garden-roof/src/features/predictions/actions/flag-prediction/actions.ts new file mode 100644 index 0000000..7061a28 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/flag-prediction/actions.ts @@ -0,0 +1,22 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { PREDICTION_EVENTS } from '../../constants'; +import { predictionsRepository } from '../../repositories/predictions'; +import type { FlagPredictionArgs } from '../../repositories/predictions'; + +/** + * «ثبت پرچم» (J11-8e): an internal flag only admins see; the card, the track record and the + * outcome don't change. A new flag replaces the prediction's earlier one. Emits + * `prediction.flagged`. + */ +export async function flagPrediction( + args: FlagPredictionArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + await predictionsRepository.flag(args); + if (emit) + eventEmitter.emit(PREDICTION_EVENTS.flagged, { + id: args.id, + reason: args.reason, + }); +} diff --git a/platforms/garden-roof/src/features/predictions/actions/flag-prediction/index.ts b/platforms/garden-roof/src/features/predictions/actions/flag-prediction/index.ts new file mode 100644 index 0000000..9768f76 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/flag-prediction/index.ts @@ -0,0 +1 @@ +export { flagPrediction } from './actions'; diff --git a/platforms/garden-roof/src/features/predictions/actions/override-prediction/actions.ts b/platforms/garden-roof/src/features/predictions/actions/override-prediction/actions.ts new file mode 100644 index 0000000..f1f84eb --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/override-prediction/actions.ts @@ -0,0 +1,19 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { PREDICTION_EVENTS } from '../../constants'; +import { predictionsRepository } from '../../repositories/predictions'; +import type { OverridePredictionArgs } from '../../repositories/predictions'; + +/** + * «ثبت اصلاح» (J11-8d): a closed prediction's close price changes from the same source. On an open + * prediction, «بستن پیش‌بینی» closes it now at the admin's price (a symbol with no quote is never + * proposed). Either way investors see «علت: اصلاح توسط ادمین» (J09-5d) and the analyst's track + * record follows the outcome. Emits `prediction.overridden`. + */ +export async function overridePrediction( + args: OverridePredictionArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + await predictionsRepository.override(args); + if (emit) eventEmitter.emit(PREDICTION_EVENTS.overridden, { id: args.id }); +} diff --git a/platforms/garden-roof/src/features/predictions/actions/override-prediction/index.ts b/platforms/garden-roof/src/features/predictions/actions/override-prediction/index.ts new file mode 100644 index 0000000..b2f3d6e --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/override-prediction/index.ts @@ -0,0 +1 @@ +export { overridePrediction } from './actions'; diff --git a/platforms/garden-roof/src/features/predictions/actions/resolve-prediction/actions.ts b/platforms/garden-roof/src/features/predictions/actions/resolve-prediction/actions.ts new file mode 100644 index 0000000..d7bd236 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/resolve-prediction/actions.ts @@ -0,0 +1,23 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { PREDICTION_EVENTS } from '../../constants'; +import { predictionsRepository } from '../../repositories/predictions'; +import type { ResolvePredictionArgs } from '../../repositories/predictions'; + +/** + * «تأیید و بستن» (J11-8b, 8g): the prediction closes at the trigger time, at the proposal's price or + * at a corrected one (`corrected`, then a reason is required and the card reads «اصلاح توسط ادمین»). + * The outcome goes on the card and into the track record. Emits `prediction.resolved`. + */ +export async function resolvePrediction( + args: ResolvePredictionArgs & { corrected: boolean }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + await predictionsRepository.resolve(args); + if (emit) { + eventEmitter.emit(PREDICTION_EVENTS.resolved, { + id: args.id, + corrected: args.corrected, + }); + } +} diff --git a/platforms/garden-roof/src/features/predictions/actions/resolve-prediction/index.ts b/platforms/garden-roof/src/features/predictions/actions/resolve-prediction/index.ts new file mode 100644 index 0000000..e4c1ca2 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/resolve-prediction/index.ts @@ -0,0 +1 @@ +export { resolvePrediction } from './actions'; diff --git a/platforms/garden-roof/src/features/predictions/actions/unflag-prediction/actions.ts b/platforms/garden-roof/src/features/predictions/actions/unflag-prediction/actions.ts new file mode 100644 index 0000000..5fa1555 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/unflag-prediction/actions.ts @@ -0,0 +1,15 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { PREDICTION_EVENTS } from '../../constants'; +import { predictionsRepository } from '../../repositories/predictions'; + +/** + * «برداشتن پرچم» (J11-8f): the prediction leaves «پرچم‌خورده». Emits `prediction.unflagged`. + */ +export async function unflagPrediction( + { id }: { id: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + await predictionsRepository.unflag(id); + if (emit) eventEmitter.emit(PREDICTION_EVENTS.unflagged, { id }); +} diff --git a/platforms/garden-roof/src/features/predictions/actions/unflag-prediction/index.ts b/platforms/garden-roof/src/features/predictions/actions/unflag-prediction/index.ts new file mode 100644 index 0000000..7b234dd --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/actions/unflag-prediction/index.ts @@ -0,0 +1 @@ +export { unflagPrediction } from './actions'; diff --git a/platforms/garden-roof/src/features/predictions/constants.ts b/platforms/garden-roof/src/features/predictions/constants.ts new file mode 100644 index 0000000..b38a357 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/constants.ts @@ -0,0 +1,25 @@ +import type { FlagReason } from './entities/prediction'; + +/** Events prediction actions emit when they succeed. */ +export const PREDICTION_EVENTS = { + resolved: 'prediction.resolved', + proposalDismissed: 'prediction.proposal_dismissed', + overridden: 'prediction.overridden', + flagged: 'prediction.flagged', + unflagged: 'prediction.unflagged', +} as const; + +/** The flag dialog's chips in display order (J11-8e); «سایر» needs a note. */ +export const FLAG_REASONS = [ + 'ambiguous', + 'unrealistic_target', + 'duplicate', + 'other', +] as const satisfies readonly FlagReason[]; + +/** The URL's query parameters: the queue, its page and the prediction open beside it. */ +export const PREDICTION_PARAMS = { + queue: 'queue', + page: 'page', + id: 'id', +} as const; diff --git a/platforms/garden-roof/src/features/predictions/entities/prediction/index.ts b/platforms/garden-roof/src/features/predictions/entities/prediction/index.ts new file mode 100644 index 0000000..73c590e --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/entities/prediction/index.ts @@ -0,0 +1,15 @@ +export type { + CloseReason, + CloseTrigger, + FlagReason, + PendingCloseEntity, + PredictionAnalystEntity, + PredictionDetailEntity, + PredictionDirection, + PredictionEventEntity, + PredictionFlagEntity, + PredictionListItemEntity, + PredictionMarket, + PredictionOutcome, + PredictionStatus, +} from './types'; diff --git a/platforms/garden-roof/src/features/predictions/entities/prediction/types.ts b/platforms/garden-roof/src/features/predictions/entities/prediction/types.ts new file mode 100644 index 0000000..7c46f6f --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/entities/prediction/types.ts @@ -0,0 +1,152 @@ +import type { AuditEntryEntity } from '../../../audit'; +import type { QuoteSourceId } from '../quote-source'; + +/** The markets predictions are published in; each reads one quote source. */ +export type PredictionMarket = + | 'crypto' + | 'gold' + | 'forex' + | 'equities' + | 'USDT'; + +export type PredictionDirection = 'long' | 'short'; +export type PredictionStatus = 'open' | 'closed'; +export type PredictionOutcome = 'win' | 'loss' | 'breakeven'; + +/** What the system detects: the final target, the stop loss, or the horizon's end. */ +export type CloseTrigger = 'target' | 'stop' | 'horizon'; + +/** + * Why a prediction closed, as its card says it: a trigger ops confirmed, the analyst's early close, + * or `admin` for a corrected price or an override (J11-8: «closeReason admin, source fixed»). + */ +export type CloseReason = CloseTrigger | 'early' | 'admin'; + +/** An internal flag's reason (J11-8e): مبهم · هدف غیرواقعی · تکراری · سایر. */ +export type FlagReason = + | 'ambiguous' + | 'unrealistic_target' + | 'duplicate' + | 'other'; + +/** Names are `''` when the profile has none (then the username stands in). */ +export type PredictionAnalystEntity = { + id: string; + firstName: string; + lastName: string; + username: string; + /** API-relative (`/uploads/avatars/…`). */ + avatarUrl: string | null; +}; + +/** + * `pendingClose`: a close the system detected, waiting for ops; the card stays «فعال» until it is + * confirmed. `held` while its source has no fresh price: then it is neither listed nor counted. + */ +export type PendingCloseEntity = { + proposalId: string; + reason: CloseTrigger; + price: number; + source: QuoteSourceId; + /** When the source quoted the price: the trigger time, as the watcher stores one time. */ + quotedAt: string; + /** The trigger time: `closedAt` once confirmed. */ + at: string; + held: boolean; +}; + +export type PredictionFlagEntity = { + reason: FlagReason; + note: string | null; + flaggedBy: string; + flaggedAt: string; +}; + +/** A row of any queue (`GET /admin/predictions?queue=`). */ +export type PredictionListItemEntity = { + id: string; + analyst: PredictionAnalystEntity; + /** Uppercased: `XAUUSD`, `TEDPIX`. */ + symbol: string; + market: PredictionMarket; + direction: PredictionDirection; + entryPrice: number; + /** Nearest first; the last is the final target. */ + targetPrices: number[]; + stopLoss: number | null; + /** `1w`, `2w`, `1m`. */ + horizon: string; + /** `null` only on a malformed old post; the queues still list it. */ + publishedAt: string | null; + expiresAt: string | null; + access: 'free' | 'premium'; + /** + * The market's quote source as stamped at publish: the entry, every check and the close read it. + * `null` on old posts stamped before sources existed. + */ + priceSource: QuoteSourceId | null; + status: PredictionStatus; + pendingClose: PendingCloseEntity | null; + closedPrice: number | null; + closedAt: string | null; + closeReason: CloseReason | null; + outcome: PredictionOutcome | null; + /** % from entry in the prediction's direction. */ + roi: number | null; + flag: PredictionFlagEntity | null; +}; + +/** One step of the prediction's life, for «خط زمانی» (J11-8c). */ +export type PredictionEventEntity = + | { + type: 'published'; + at: string | null; + entryPrice: number; + source: QuoteSourceId | null; + } + | { + type: 'monitored'; + until: string; + /** Estimated from the check period: no per-check log is kept. */ + checks: number; + /** Can be a fraction (`0.5`) in development. */ + intervalMinutes: number; + /** Not tracked yet: always `null` for now. */ + nearestToTarget: number | null; + nearestToStop: number | null; + } + | { + type: 'close_detected'; + at: string; + reason: CloseTrigger; + price: number; + source: QuoteSourceId; + quotedAt: string; + } + | { + type: 'closed'; + at: string; + price: number; + /** + * Confirmed at a price other than the proposal's (J11-8g), or an open prediction ops closed + * at their own price. + */ + corrected: boolean; + actorName: string | null; + } + | { type: 'proposal_dismissed'; at: string; actorName: string | null } + | { + type: 'overridden'; + at: string; + fromPrice: number; + toPrice: number; + actorName: string | null; + }; + +/** One prediction (`GET /admin/predictions/:id`). */ +export type PredictionDetailEntity = PredictionListItemEntity & { + events: PredictionEventEntity[]; + audit: AuditEntryEntity[]; + /** The analyst's closed predictions and wins: what an override changes (J11-8d). */ + trackRecord: { wins: number; closed: number }; +}; diff --git a/platforms/garden-roof/src/features/predictions/entities/quote-source/index.ts b/platforms/garden-roof/src/features/predictions/entities/quote-source/index.ts new file mode 100644 index 0000000..c6883b7 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/entities/quote-source/index.ts @@ -0,0 +1,5 @@ +export type { + QuoteHealthEntity, + QuoteSourceHealthEntity, + QuoteSourceId, +} from './types'; diff --git a/platforms/garden-roof/src/features/predictions/entities/quote-source/types.ts b/platforms/garden-roof/src/features/predictions/entities/quote-source/types.ts new file mode 100644 index 0000000..4bc2aa5 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/entities/quote-source/types.ts @@ -0,0 +1,25 @@ +import type { PredictionMarket } from '../prediction'; + +/** + * A quote source's name as the API stamps it: `TGJU`, `Binance`, `Nobitex`, `TSETMC`, or `mock` from + * the development provider. Shown as is, left to right. + */ +export type QuoteSourceId = string; + +/** One source's health (`GET /admin/quote-sources/health`). */ +export type QuoteSourceHealthEntity = { + id: QuoteSourceId; + /** The markets it prices: «طلا و سکه، فارکس» for TGJU. */ + markets: PredictionMarket[]; + /** `null` until the source has answered once since the service started. */ + lastPriceAt: string | null; + /** No price for 15 minutes in trading hours: its close proposals wait. */ + stale: boolean; + /** Close proposals waiting for its next price («۱ پیشنهاد در انتظار»). */ + heldProposals: number; +}; + +export type QuoteHealthEntity = { + checkedAt: string; + sources: QuoteSourceHealthEntity[]; +}; diff --git a/platforms/garden-roof/src/features/predictions/http.ts b/platforms/garden-roof/src/features/predictions/http.ts new file mode 100644 index 0000000..2f43663 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const predictionsHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/predictions/index.ts b/platforms/garden-roof/src/features/predictions/index.ts new file mode 100644 index 0000000..5d11d37 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/index.ts @@ -0,0 +1,86 @@ +import './types'; + +export { dismissProposal } from './actions/dismiss-proposal'; +export { flagPrediction } from './actions/flag-prediction'; +export { overridePrediction } from './actions/override-prediction'; +export { resolvePrediction } from './actions/resolve-prediction'; +export { unflagPrediction } from './actions/unflag-prediction'; +export { + FLAG_REASONS, + PREDICTION_EVENTS, + PREDICTION_PARAMS, +} from './constants'; +export type { + CloseReason, + CloseTrigger, + FlagReason, + PredictionDirection, + PredictionMarket, + PredictionOutcome, + PredictionStatus, +} from './entities/prediction'; +export type { QuoteSourceId } from './entities/quote-source'; +export { + usePredictionActions, + usePredictionDetailPart, + usePredictionListPart, + usePredictionsPage, + useQuoteHealthPart, +} from './models/queues'; +export type { + CorrectPriceForm, + FlagForm, + OverrideForm, + OverrideSubject, + PredictionActionsModel, + PredictionDetailPartModel, + PredictionDialog, + PredictionListPartModel, + PredictionsPageModel, + QuoteHealthPartModel, +} from './models/queues'; +export { + PREDICTION_ENDPOINTS, + PREDICTION_ERROR_CODES, + PREDICTION_QUEUES, + predictionKeys, + predictionsRepository, +} from './repositories/predictions'; +export type { + DismissProposalArgs, + FlagPredictionArgs, + ListPredictionsArgs, + OverridePredictionArgs, + PendingClosePayload, + PredictionDetailPayload, + PredictionEventPayload, + PredictionPagePayload, + PredictionPayload, + PredictionQueue, + ResolvePredictionArgs, +} from './repositories/predictions'; +export { + QUOTE_HEALTH_REFRESH_MS, + QUOTE_SOURCE_ENDPOINTS, + quoteSourceKeys, + quoteSourcesRepository, +} from './repositories/quote-sources'; +export type { + QuoteHealthPayload, + QuoteSourcePayload, +} from './repositories/quote-sources'; +export { outcomeOf, roiOf, winRateAfter } from './utils'; +export { + correctPriceSchema, + flagSchema, + overrideSchema, + parsePriceInput, +} from '../../shared/validations/prediction-validations'; +export type { + CorrectPriceFormOutput, + CorrectPriceFormValues, + FlagFormOutput, + FlagFormValues, + OverrideFormOutput, + OverrideFormValues, +} from '../../shared/validations/prediction-validations'; diff --git a/platforms/garden-roof/src/features/predictions/models/queues/index.ts b/platforms/garden-roof/src/features/predictions/models/queues/index.ts new file mode 100644 index 0000000..b7e6452 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/models/queues/index.ts @@ -0,0 +1,17 @@ +export { usePredictionActions } from './use-prediction-actions'; +export { usePredictionDetailPart } from './use-prediction-detail-part'; +export { usePredictionListPart } from './use-prediction-list-part'; +export { usePredictionsPage } from './use-predictions-page'; +export { useQuoteHealthPart } from './use-quote-health-part'; +export type { + CorrectPriceForm, + FlagForm, + OverrideForm, + OverrideSubject, + PredictionActionsModel, + PredictionDetailPartModel, + PredictionDialog, + PredictionListPartModel, + PredictionsPageModel, + QuoteHealthPartModel, +} from './types'; diff --git a/platforms/garden-roof/src/features/predictions/models/queues/types.ts b/platforms/garden-roof/src/features/predictions/models/queues/types.ts new file mode 100644 index 0000000..cb6acbf --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/models/queues/types.ts @@ -0,0 +1,126 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { ReasonForm } from '../../../../shared/utils'; +import type { + CorrectPriceFormOutput, + CorrectPriceFormValues, + FlagFormOutput, + FlagFormValues, + OverrideFormOutput, + OverrideFormValues, +} from '../../../../shared/validations/prediction-validations'; +import type { + ListPredictionsArgs, + PredictionDetailPayload, + PredictionPayload, + PredictionQueue, +} from '../../repositories/predictions'; +import type { QuoteHealthPayload } from '../../repositories/quote-sources'; + +export type CorrectPriceForm = UseFormReturn< + CorrectPriceFormValues, + unknown, + CorrectPriceFormOutput +>; +export type OverrideForm = UseFormReturn< + OverrideFormValues, + unknown, + OverrideFormOutput +>; +export type FlagForm = UseFormReturn; + +/** + * What «اصلاح نتیجه» / «بستن با قیمت ادمین» acts on: the detail knows the analyst's track record, + * a «باز» row doesn't (then the dialog leaves out the win-rate change). + */ +export type OverrideSubject = PredictionPayload & + Partial>; + +/** + * The dialog on screen, with the prediction it acts on. `confirm` (J11-8b) and `correct` (8g) are + * one dialog in two modes; `reject` (8h) is reached from either and returns to `confirm`; + * `override` (8d: a closed prediction's correction, or an open one closed at the admin's price) and + * `flag` (8e) open from the detail or a row. + */ +export type PredictionDialog = + | { kind: 'confirm'; prediction: PredictionPayload } + | { kind: 'correct'; prediction: PredictionPayload } + | { kind: 'reject'; prediction: PredictionPayload } + | { kind: 'override'; prediction: OverrideSubject } + | { kind: 'flag'; prediction: PredictionPayload } + | null; + +export type PredictionActionsModel = { + dialog: PredictionDialog; + /** «بررسی و بستن»: a prediction with a close waiting for ops. */ + openConfirm: (prediction: PredictionPayload) => void; + /** «اصلاح قیمت»: the confirm dialog asks for a corrected price and a reason. */ + startCorrect: () => void; + /** «لغو اصلاح»: back to the proposal's price. */ + cancelCorrect: () => void; + /** «رد پیشنهاد» from the confirm dialog. */ + openReject: () => void; + /** «انصراف» in the reject dialog: back to the confirm dialog. */ + backToConfirm: () => void; + /** + * «اصلاح نتیجه» on a closed prediction; «بستن با قیمت ادمین» on an open one, which no proposal + * may ever close (a symbol with no quote). + */ + openOverride: (prediction: OverrideSubject) => void; + openFlag: (prediction: PredictionPayload) => void; + closeDialog: () => void; + /** «تأیید و بستن» at the proposal's price. */ + confirmClose: () => void; + correctForm: CorrectPriceForm; + /** «تأیید و بستن» at the corrected price. */ + confirmCorrected: (values: CorrectPriceFormOutput) => void; + isResolving: boolean; + rejectForm: ReasonForm; + confirmReject: (reason: string) => void; + isDismissing: boolean; + overrideForm: OverrideForm; + confirmOverride: (values: OverrideFormOutput) => void; + isOverriding: boolean; + flagForm: FlagForm; + confirmFlag: (values: FlagFormOutput) => void; + isFlagging: boolean; + /** «برداشتن پرچم» on a row of پرچم‌خورده. */ + unflag: (prediction: PredictionPayload) => void; + /** The prediction whose flag is being removed, if any. */ + unflaggingId: string | null; +}; + +export type PredictionsPageModel = { + queue: PredictionQueue; + /** Each tab's address; a tab starts again from page 1 and closes the detail. */ + tabHref: (queue: PredictionQueue) => string; + /** The sidebar's count, shown on «نیاز به تأیید»; `null` until it arrives. */ + needsReviewCount: number | null; + /** What the rows read; a change remounts them behind their skeleton. */ + args: ListPredictionsArgs; + argsKey: string; + /** The prediction open beside the table (`?id=`). */ + detailId: string | null; + /** The prediction the sheet shows: kept while it slides out after closing. */ + shownDetailId: string | null; + detailHref: (id: string) => string; + openDetail: (id: string) => void; + closeDetail: () => void; + onDetailExited: () => void; + actions: PredictionActionsModel; +}; + +export type PredictionListPartModel = { + rows: PredictionPayload[]; + page: number; + pageCount: number; + total: number; + from: number; + to: number; + pageHref: (page: number) => string; + isEmpty: boolean; +}; + +export type PredictionDetailPartModel = { prediction: PredictionDetailPayload }; + +export type QuoteHealthPartModel = { health: QuoteHealthPayload }; diff --git a/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-actions.ts b/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-actions.ts new file mode 100644 index 0000000..19cc0ac --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-actions.ts @@ -0,0 +1,315 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { showActionError, useReasonForm } from '../../../../shared/utils'; +import { + correctPriceSchema, + flagSchema, + overrideSchema, +} from '../../../../shared/validations/prediction-validations'; +import type { + CorrectPriceFormOutput, + CorrectPriceFormValues, + FlagFormOutput, + FlagFormValues, + OverrideFormOutput, + OverrideFormValues, +} from '../../../../shared/validations/prediction-validations'; +import { panelKeys } from '../../../panel'; +import { dismissProposal } from '../../actions/dismiss-proposal'; +import { flagPrediction } from '../../actions/flag-prediction'; +import { overridePrediction } from '../../actions/override-prediction'; +import { resolvePrediction } from '../../actions/resolve-prediction'; +import { unflagPrediction } from '../../actions/unflag-prediction'; +import type { FlagReason } from '../../entities/prediction'; +import { + PREDICTION_ERROR_CODES, + predictionKeys, +} from '../../repositories/predictions'; +import type { PredictionPayload } from '../../repositories/predictions'; +import type { + OverrideSubject, + PredictionActionsModel, + PredictionDialog, +} from './types'; + +const CONFLICT_CODES: readonly string[] = Object.values(PREDICTION_ERROR_CODES); + +/** + * The section's dialogs and actions (J11-8b … 8h). Each success toasts, refetches the queues and + * the open detail, and (when a close proposal is decided) the sidebar count. A failure keeps the + * dialog with what was typed, and confirm retries. When the analyst's early close (or another tab) + * got there first, the API answers 409: the dialog closes with an info toast and everything + * refetches (J11-8: «first wins»). + */ +export function usePredictionActions({ + onFlagged, +}: { + /** After «ثبت پرچم»: the page shows پرچم‌خورده (J11-8f). */ + onFlagged: () => void; +}): PredictionActionsModel { + const { t } = useTranslation('predictions'); + const queryClient = useQueryClient(); + const [dialog, setDialog] = useState(null); + const [isResolving, setIsResolving] = useState(false); + const [isDismissing, setIsDismissing] = useState(false); + const [isOverriding, setIsOverriding] = useState(false); + const [isFlagging, setIsFlagging] = useState(false); + const [unflaggingId, setUnflaggingId] = useState(null); + const rejectForm = useReasonForm(); + const correctForm = useForm< + CorrectPriceFormValues, + unknown, + CorrectPriceFormOutput + >({ + resolver: valibotResolver(correctPriceSchema), + defaultValues: { price: '', reason: '' }, + }); + const overrideForm = useForm( + { + resolver: valibotResolver(overrideSchema), + defaultValues: { closedPrice: '', reason: '' }, + }, + ); + const flagForm = useForm({ + resolver: valibotResolver(flagSchema), + defaultValues: { reason: '', note: '' }, + }); + + const refetch = ({ counts }: { counts: boolean }) => + Promise.all([ + queryClient.invalidateQueries({ queryKey: predictionKeys.all }), + counts + ? queryClient.invalidateQueries({ queryKey: panelKeys.counts() }) + : null, + ]); + + const refused = async (error: unknown): Promise => { + if (!isHttpError(error) || !CONFLICT_CODES.includes(error.code)) + return false; + setDialog(null); + showToast({ tone: 'info', message: t('conflict') }); + await refetch({ counts: true }); + return true; + }; + + const resolve = async ( + prediction: PredictionPayload, + corrected?: CorrectPriceFormOutput, + ) => { + const pending = prediction.pendingClose; + if (isResolving || !pending) return; + if (corrected && corrected.price === pending.price) { + correctForm.setError( + 'price', + { type: 'validate', message: 'predictions:correct.price-same' }, + { shouldFocus: true }, + ); + return; + } + setIsResolving(true); + try { + await resolvePrediction({ + id: prediction.id, + proposalId: pending.proposalId, + price: corrected?.price ?? pending.price, + source: pending.source, + at: pending.at, + reason: corrected?.reason, + corrected: corrected !== undefined, + }); + showToast({ + tone: 'success', + message: t(corrected ? 'correct.done' : 'confirm.done'), + }); + setDialog(null); + await refetch({ counts: true }); + } catch (error) { + if (!(await refused(error))) { + showActionError(error, { + t, + failedMessage: t('confirm.failed'), + retry: () => void resolve(prediction, corrected), + }); + } + } finally { + setIsResolving(false); + } + }; + + const reject = async (prediction: PredictionPayload, reason: string) => { + if (isDismissing) return; + setIsDismissing(true); + try { + await dismissProposal({ id: prediction.id, reason }); + showToast({ tone: 'success', message: t('reject.done') }); + setDialog(null); + await refetch({ counts: true }); + } catch (error) { + if (!(await refused(error))) { + showActionError(error, { + t, + failedMessage: t('reject.failed'), + retry: () => void reject(prediction, reason), + }); + } + } finally { + setIsDismissing(false); + } + }; + + // An open prediction closes at the admin's price; a closed one is corrected. Closing one with a + // waiting proposal settles that proposal too, so the sidebar count refetches. + const override = async ( + prediction: OverrideSubject, + values: OverrideFormOutput, + ) => { + if (isOverriding) return; + // As the dialog decides it: no close price yet means this sets the first one. + const isClosing = prediction.closedPrice === null; + if (!isClosing && values.closedPrice === prediction.closedPrice) { + overrideForm.setError( + 'closedPrice', + { type: 'validate', message: 'predictions:override.price-same' }, + { shouldFocus: true }, + ); + return; + } + setIsOverriding(true); + try { + await overridePrediction({ id: prediction.id, ...values }); + showToast({ + tone: 'success', + message: t(isClosing ? 'close-admin.done' : 'override.done'), + }); + setDialog(null); + await refetch({ counts: isClosing }); + } catch (error) { + if (!(await refused(error))) { + showActionError(error, { + t, + failedMessage: t( + isClosing ? 'close-admin.failed' : 'override.failed', + ), + retry: () => void override(prediction, values), + }); + } + } finally { + setIsOverriding(false); + } + }; + + const flag = async ( + prediction: PredictionPayload, + values: FlagFormOutput, + ) => { + if (isFlagging) return; + setIsFlagging(true); + try { + await flagPrediction({ + id: prediction.id, + reason: values.reason satisfies FlagReason, + note: values.note || undefined, + }); + showToast({ tone: 'success', message: t('flag.done') }); + setDialog(null); + await refetch({ counts: false }); + onFlagged(); + } catch (error) { + showActionError(error, { + t, + failedMessage: t('flag.failed'), + retry: () => void flag(prediction, values), + }); + } finally { + setIsFlagging(false); + } + }; + + const unflag = async (prediction: PredictionPayload) => { + if (unflaggingId) return; + setUnflaggingId(prediction.id); + try { + await unflagPrediction({ id: prediction.id }); + showToast({ tone: 'success', message: t('unflag.done') }); + await refetch({ counts: false }); + } catch (error) { + showActionError(error, { + t, + failedMessage: t('unflag.failed'), + retry: () => void unflag(prediction), + }); + } finally { + setUnflaggingId(null); + } + }; + + /** The prediction the confirm, correct and reject dialogs share. */ + const reviewed = + dialog && + (dialog.kind === 'confirm' || + dialog.kind === 'correct' || + dialog.kind === 'reject') + ? dialog.prediction + : null; + + return { + dialog, + openConfirm: (prediction) => setDialog({ kind: 'confirm', prediction }), + startCorrect: () => { + if (!reviewed) return; + correctForm.reset(); + setDialog({ kind: 'correct', prediction: reviewed }); + }, + cancelCorrect: () => { + if (!reviewed) return; + correctForm.reset(); + setDialog({ kind: 'confirm', prediction: reviewed }); + }, + openReject: () => { + if (reviewed) setDialog({ kind: 'reject', prediction: reviewed }); + }, + backToConfirm: () => { + if (reviewed) setDialog({ kind: 'confirm', prediction: reviewed }); + }, + openOverride: (prediction) => { + overrideForm.reset(); + setDialog({ kind: 'override', prediction }); + }, + openFlag: (prediction) => { + flagForm.reset(); + setDialog({ kind: 'flag', prediction }); + }, + closeDialog: () => setDialog(null), + confirmClose: () => { + if (reviewed) void resolve(reviewed); + }, + correctForm, + confirmCorrected: (values) => { + if (reviewed) void resolve(reviewed, values); + }, + isResolving, + rejectForm, + confirmReject: (reason) => { + if (reviewed) void reject(reviewed, reason); + }, + isDismissing, + overrideForm, + confirmOverride: (values) => { + if (dialog?.kind === 'override') void override(dialog.prediction, values); + }, + isOverriding, + flagForm, + confirmFlag: (values) => { + if (dialog?.kind === 'flag') void flag(dialog.prediction, values); + }, + isFlagging, + unflag: (prediction) => void unflag(prediction), + unflaggingId, + }; +} diff --git a/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-detail-part.ts b/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-detail-part.ts new file mode 100644 index 0000000..179b313 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-detail-part.ts @@ -0,0 +1,16 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { + predictionKeys, + predictionsRepository, +} from '../../repositories/predictions'; +import type { PredictionDetailPartModel } from './types'; + +/** «جزئیات پیش‌بینی» (J11-8c): the card, «خط زمانی» and «گزارش ممیزی»; refetched after each action. */ +export function usePredictionDetailPart(id: string): PredictionDetailPartModel { + const { data } = useSuspenseQuery({ + queryKey: predictionKeys.detail(id), + queryFn: ({ signal }) => predictionsRepository.get(id, { signal }), + }); + return { prediction: data }; +} diff --git a/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-list-part.ts b/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-list-part.ts new file mode 100644 index 0000000..b3a50be --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/models/queues/use-prediction-list-part.ts @@ -0,0 +1,38 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { PREDICTION_PARAMS } from '../../constants'; +import { + predictionKeys, + predictionsRepository, +} from '../../repositories/predictions'; +import type { ListPredictionsArgs } from '../../repositories/predictions'; +import type { PredictionListPartModel } from './types'; + +/** The queue's rows for its page; 20 a page. */ +export function usePredictionListPart( + args: ListPredictionsArgs, +): PredictionListPartModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data } = useSuspenseQuery({ + queryKey: predictionKeys.list(args), + queryFn: ({ signal }) => predictionsRepository.list(args, { signal }), + }); + + return { + rows: data.items, + page: data.page, + pageCount: data.pageCount, + total: data.total, + from: data.from, + to: data.to, + pageHref: (page) => + listHref(pathname, searchParams, { + [PREDICTION_PARAMS.page]: page, + [PREDICTION_PARAMS.id]: null, + }), + isEmpty: data.total === 0, + }; +} diff --git a/platforms/garden-roof/src/features/predictions/models/queues/use-predictions-page.ts b/platforms/garden-roof/src/features/predictions/models/queues/use-predictions-page.ts new file mode 100644 index 0000000..9896d04 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/models/queues/use-predictions-page.ts @@ -0,0 +1,77 @@ +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; +import { useState } from 'react'; + +import { listHref, oneOf, pageOf } from '../../../../shared/utils'; +import { usePanelCounts } from '../../../panel'; +import { PREDICTION_PARAMS } from '../../constants'; +import { PREDICTION_QUEUES } from '../../repositories/predictions'; +import type { PredictionQueue } from '../../repositories/predictions'; +import type { PredictionsPageModel } from './types'; +import { usePredictionActions } from './use-prediction-actions'; + +/** + * پیش‌بینی‌ها (J11-8): the queue (نیاز به تأیید by default, with the sidebar's count), its page and + * the prediction open beside the table (J11-8c) live in the URL, so a reload or a shared link + * keeps them. Closing never happens without ops: a detected close waits in نیاز به تأیید while the + * card stays «فعال». + */ +export function usePredictionsPage(): PredictionsPageModel { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const counts = usePanelCounts(); + const queue = oneOf( + searchParams.get(PREDICTION_PARAMS.queue), + PREDICTION_QUEUES, + ); + const page = pageOf(searchParams.get(PREDICTION_PARAMS.page)); + const detailId = searchParams.get(PREDICTION_PARAMS.id) || null; + // The sheet keeps showing its prediction while it slides out. + const [shownDetailId, setShownDetailId] = useState(detailId); + if (detailId && detailId !== shownDetailId) setShownDetailId(detailId); + + const queueParam = (next: PredictionQueue) => + next === 'needs_review' ? null : next; + + const tabHref = (next: PredictionQueue) => + listHref(pathname, searchParams, { + [PREDICTION_PARAMS.queue]: queueParam(next), + [PREDICTION_PARAMS.id]: null, + }); + + const detailHref = (id: string) => + listHref(pathname, searchParams, { + [PREDICTION_PARAMS.id]: id, + [PREDICTION_PARAMS.page]: page, + }); + + const actions = usePredictionActions({ + onFlagged: () => router.replace(tabHref('flagged'), { scroll: false }), + }); + + const args = { queue, page }; + + return { + queue, + tabHref, + needsReviewCount: counts?.preds ?? null, + args, + argsKey: JSON.stringify(args), + detailId, + shownDetailId, + detailHref, + openDetail: (id) => router.replace(detailHref(id), { scroll: false }), + closeDetail: () => + router.replace( + listHref(pathname, searchParams, { + [PREDICTION_PARAMS.id]: null, + [PREDICTION_PARAMS.page]: page, + }), + { scroll: false }, + ), + onDetailExited: () => { + if (!detailId) setShownDetailId(null); + }, + actions, + }; +} diff --git a/platforms/garden-roof/src/features/predictions/models/queues/use-quote-health-part.ts b/platforms/garden-roof/src/features/predictions/models/queues/use-quote-health-part.ts new file mode 100644 index 0000000..5230511 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/models/queues/use-quote-health-part.ts @@ -0,0 +1,21 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; + +import { + QUOTE_HEALTH_REFRESH_MS, + quoteSourceKeys, + quoteSourcesRepository, +} from '../../repositories/quote-sources'; +import type { QuoteHealthPartModel } from './types'; + +/** + * «وضعیت منابع قیمت» (J11-8), checked again every minute while the page is open. A failed refresh + * keeps the last answer; only a failed first read shows the part's error. + */ +export function useQuoteHealthPart(): QuoteHealthPartModel { + const { data } = useSuspenseQuery({ + queryKey: quoteSourceKeys.health(), + queryFn: ({ signal }) => quoteSourcesRepository.health({ signal }), + refetchInterval: QUOTE_HEALTH_REFRESH_MS, + }); + return { health: data }; +} diff --git a/platforms/garden-roof/src/features/predictions/repositories/predictions/constants.ts b/platforms/garden-roof/src/features/predictions/repositories/predictions/constants.ts new file mode 100644 index 0000000..c9275c4 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/predictions/constants.ts @@ -0,0 +1,43 @@ +import type { PredictionQueue } from './types'; + +export const PREDICTION_ENDPOINTS = { + list: '/admin/predictions', + detail: (id: string) => `/admin/predictions/${encodeURIComponent(id)}`, + resolve: (id: string) => + `/admin/predictions/${encodeURIComponent(id)}/resolve`, + dismissProposal: (id: string) => + `/admin/predictions/${encodeURIComponent(id)}/proposal/dismiss`, + override: (id: string) => + `/admin/predictions/${encodeURIComponent(id)}/override`, + flag: (id: string) => `/admin/predictions/${encodeURIComponent(id)}/flag`, +} as const; + +/** The queue tabs in display order; نیاز به تأیید opens first (J11-8). */ +export const PREDICTION_QUEUES = [ + 'needs_review', + 'open', + 'closed', + 'flagged', +] as const satisfies readonly PredictionQueue[]; + +/** + * The 409 codes the API marks prediction refusals with; branch on these, never on the message. A + * missing prediction is a 404 without a code. + */ +export const PREDICTION_ERROR_CODES = { + /** The analyst's early close and ops' confirm race, and the first wins (J11-8). */ + alreadyClosed: 'PREDICTION_ALREADY_CLOSED', + /** The reviewed proposal was decided in another tab, or replaced by a newer one. */ + proposalNotPending: 'PROPOSAL_NOT_PENDING', + /** A correction of a prediction that isn't closed (the override now closes an open one instead). */ + notClosed: 'PREDICTION_NOT_CLOSED', +} as const; + +export const predictionKeys = { + all: ['predictions'] as const, + lists: () => [...predictionKeys.all, 'list'] as const, + list: (args: { queue: PredictionQueue; page: number }) => + [...predictionKeys.lists(), args] as const, + details: () => [...predictionKeys.all, 'detail'] as const, + detail: (id: string) => [...predictionKeys.details(), id] as const, +}; diff --git a/platforms/garden-roof/src/features/predictions/repositories/predictions/index.ts b/platforms/garden-roof/src/features/predictions/repositories/predictions/index.ts new file mode 100644 index 0000000..3e583ca --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/predictions/index.ts @@ -0,0 +1,20 @@ +export { + PREDICTION_ENDPOINTS, + PREDICTION_ERROR_CODES, + PREDICTION_QUEUES, + predictionKeys, +} from './constants'; +export { predictionsRepository } from './predictions'; +export type { + DismissProposalArgs, + FlagPredictionArgs, + ListPredictionsArgs, + OverridePredictionArgs, + PendingClosePayload, + PredictionDetailPayload, + PredictionEventPayload, + PredictionPagePayload, + PredictionPayload, + PredictionQueue, + ResolvePredictionArgs, +} from './types'; diff --git a/platforms/garden-roof/src/features/predictions/repositories/predictions/mappers.ts b/platforms/garden-roof/src/features/predictions/repositories/predictions/mappers.ts new file mode 100644 index 0000000..0552794 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/predictions/mappers.ts @@ -0,0 +1,126 @@ +import { toApiUrl } from '../../../../shared/utils'; +import { toAuditEntryPayload } from '../../../audit'; +import type { PredictionListItemEntity } from '../../entities/prediction'; +import { outcomeOf, roiOf } from '../../utils'; +import type { + DismissProposalArgs, + DismissProposalDto, + FlagPredictionArgs, + FlagPredictionDto, + ListPredictionsArgs, + ListPredictionsQueryDto, + OverridePredictionArgs, + OverridePredictionDto, + PredictionDetailPayload, + PredictionDetailResponseDto, + PredictionPagePayload, + PredictionPageResponseDto, + PredictionPayload, + ResolvePredictionArgs, + ResolvePredictionDto, +} from './types'; + +export function toListPredictionsQueryDto( + args: ListPredictionsArgs, +): ListPredictionsQueryDto { + return { queue: args.queue, page: args.page }; +} + +function toPredictionPayload( + dto: PredictionListItemEntity, + now: string, +): PredictionPayload { + const pending = dto.pendingClose; + const pendingRoi = pending ? roiOf(dto, pending.price) : null; + return { + id: dto.id, + analyst: { + id: dto.analyst.id, + fullName: + `${dto.analyst.firstName} ${dto.analyst.lastName}`.trim() || + dto.analyst.username, + username: dto.analyst.username, + avatarUrl: toApiUrl(dto.analyst.avatarUrl), + }, + symbol: dto.symbol, + market: dto.market, + direction: dto.direction, + entryPrice: dto.entryPrice, + targetPrices: [...dto.targetPrices], + stopLoss: dto.stopLoss, + horizon: dto.horizon, + publishedAt: dto.publishedAt, + expiresAt: dto.expiresAt, + premium: dto.access === 'premium', + priceSource: dto.priceSource, + status: dto.status, + pendingClose: + pending && pendingRoi !== null + ? { ...pending, roi: pendingRoi, outcome: outcomeOf(pendingRoi) } + : null, + closedPrice: dto.closedPrice, + closedAt: dto.closedAt, + closeReason: dto.closeReason, + outcome: dto.outcome, + roi: dto.roi, + flag: dto.flag ? { ...dto.flag } : null, + now, + }; +} + +export function toPredictionPagePayload( + dto: PredictionPageResponseDto, +): PredictionPagePayload { + const from = dto.total === 0 ? 0 : (dto.page - 1) * dto.pageSize + 1; + return { + items: dto.items.map((item) => toPredictionPayload(item, dto.now)), + page: dto.page, + pageCount: Math.max(1, Math.ceil(dto.total / dto.pageSize)), + total: dto.total, + from, + to: from === 0 ? 0 : from + dto.items.length - 1, + }; +} + +export function toPredictionDetailPayload( + dto: PredictionDetailResponseDto, +): PredictionDetailPayload { + return { + ...toPredictionPayload(dto, dto.now), + events: dto.events.map((event) => ({ ...event })), + audit: dto.audit.map(toAuditEntryPayload), + trackRecord: { ...dto.trackRecord }, + }; +} + +export function toResolvePredictionDto( + args: ResolvePredictionArgs, +): ResolvePredictionDto { + const reason = args.reason?.trim(); + return { + proposalId: args.proposalId, + price: args.price, + source: args.source, + at: args.at, + ...(reason ? { reason } : {}), + }; +} + +export function toDismissProposalDto( + args: DismissProposalArgs, +): DismissProposalDto { + return { reason: args.reason.trim() }; +} + +export function toOverridePredictionDto( + args: OverridePredictionArgs, +): OverridePredictionDto { + return { closedPrice: args.closedPrice, reason: args.reason.trim() }; +} + +export function toFlagPredictionDto( + args: FlagPredictionArgs, +): FlagPredictionDto { + const note = args.note?.trim(); + return { reason: args.reason, ...(note ? { note } : {}) }; +} diff --git a/platforms/garden-roof/src/features/predictions/repositories/predictions/predictions.ts b/platforms/garden-roof/src/features/predictions/repositories/predictions/predictions.ts new file mode 100644 index 0000000..d7480f2 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/predictions/predictions.ts @@ -0,0 +1,95 @@ +import { predictionsHttp } from '../../http'; +import { PREDICTION_ENDPOINTS } from './constants'; +import { + toDismissProposalDto, + toFlagPredictionDto, + toListPredictionsQueryDto, + toOverridePredictionDto, + toPredictionDetailPayload, + toPredictionPagePayload, + toResolvePredictionDto, +} from './mappers'; +import type { + DismissProposalArgs, + FlagPredictionArgs, + ListPredictionsArgs, + OverridePredictionArgs, + PredictionDetailPayload, + PredictionDetailResponseDto, + PredictionPagePayload, + PredictionPageResponseDto, + ResolvePredictionArgs, +} from './types'; + +/** + * Predictions for ops (J11-8 … 8h): the four queues, one prediction with its timeline and audit, + * and the actions on it. Closing never happens without ops: a detected close waits here. Every + * action answers 204. + */ +export const predictionsRepository = { + /** 20 a page, in the queue's own order. */ + async list( + args: ListPredictionsArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await predictionsHttp.get( + PREDICTION_ENDPOINTS.list, + { params: toListPredictionsQueryDto(args), signal }, + ); + return toPredictionPagePayload(response); + }, + + async get( + id: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await predictionsHttp.get( + PREDICTION_ENDPOINTS.detail(id), + { signal }, + ); + return toPredictionDetailPayload(response); + }, + + /** + * Closes it at the proposal's price, or at a corrected one with a reason (then «علت: اصلاح توسط + * ادمین»); the close time stays the trigger's. + */ + async resolve(args: ResolvePredictionArgs): Promise { + await predictionsHttp.post( + PREDICTION_ENDPOINTS.resolve(args.id), + toResolvePredictionDto(args), + ); + }, + + /** The prediction stays open and the checks go on; the proposal stays in the audit log. */ + async dismissProposal(args: DismissProposalArgs): Promise { + await predictionsHttp.post( + PREDICTION_ENDPOINTS.dismissProposal(args.id), + toDismissProposalDto(args), + ); + }, + + /** + * A closed prediction's new close price, or an open one closed now at the admin's price: the + * card, the outcome and the track record follow. + */ + async override(args: OverridePredictionArgs): Promise { + await predictionsHttp.post( + PREDICTION_ENDPOINTS.override(args.id), + toOverridePredictionDto(args), + ); + }, + + /** Internal: no effect on the card, the track record or the outcome. */ + async flag(args: FlagPredictionArgs): Promise { + await predictionsHttp.post( + PREDICTION_ENDPOINTS.flag(args.id), + toFlagPredictionDto(args), + ); + }, + + /** Removing a flag that is already gone is a no-op, not an error. */ + async unflag(id: string): Promise { + await predictionsHttp.delete(PREDICTION_ENDPOINTS.flag(id)); + }, +}; diff --git a/platforms/garden-roof/src/features/predictions/repositories/predictions/types.ts b/platforms/garden-roof/src/features/predictions/repositories/predictions/types.ts new file mode 100644 index 0000000..b260b8b --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/predictions/types.ts @@ -0,0 +1,153 @@ +import type { AuditEntryPayload } from '../../../audit'; +import type { + CloseReason, + CloseTrigger, + FlagReason, + PredictionDetailEntity, + PredictionDirection, + PredictionEventEntity, + PredictionListItemEntity, + PredictionMarket, + PredictionOutcome, + PredictionStatus, +} from '../../entities/prediction'; +import type { QuoteSourceId } from '../../entities/quote-source'; + +/** The queues, as the tabs show them (J11-8): نیاز به تأیید · باز · بسته‌شده · پرچم‌خورده. */ +export type PredictionQueue = 'needs_review' | 'open' | 'closed' | 'flagged'; + +// GET /admin/predictions?queue=&page= + +export type ListPredictionsArgs = { queue: PredictionQueue; page: number }; + +export type ListPredictionsQueryDto = { queue: PredictionQueue; page: number }; + +export type PredictionPageResponseDto = { + items: PredictionListItemEntity[]; + page: number; + pageSize: number; + total: number; + /** The server's time, which the cards count the time left from. */ + now: string; +}; + +export type PendingClosePayload = { + proposalId: string; + reason: CloseTrigger; + price: number; + source: QuoteSourceId; + quotedAt: string; + at: string; + held: boolean; + /** What the prediction closes at if confirmed as proposed (J11-8b «نتیجه»). */ + roi: number; + outcome: PredictionOutcome; +}; + +/** A prediction as every queue, dialog and the detail use it. */ +export type PredictionPayload = { + id: string; + analyst: { + id: string; + /** The full name, else the username. */ + fullName: string; + username: string; + avatarUrl: string | null; + }; + symbol: string; + market: PredictionMarket; + direction: PredictionDirection; + entryPrice: number; + targetPrices: number[]; + stopLoss: number | null; + horizon: string; + publishedAt: string | null; + expiresAt: string | null; + premium: boolean; + priceSource: QuoteSourceId | null; + status: PredictionStatus; + pendingClose: PendingClosePayload | null; + closedPrice: number | null; + closedAt: string | null; + closeReason: CloseReason | null; + outcome: PredictionOutcome | null; + roi: number | null; + flag: { + reason: FlagReason; + note: string | null; + flaggedBy: string; + flaggedAt: string; + } | null; + /** The server's time when it answered. */ + now: string; +}; + +export type PredictionPagePayload = { + items: PredictionPayload[]; + page: number; + pageCount: number; + total: number; + /** The first and last row's place among all rows, for «نمایش ۱ تا ۷ از ۷». */ + from: number; + to: number; +}; + +// GET /admin/predictions/:id + +export type PredictionDetailResponseDto = PredictionDetailEntity & { + /** The server's time, as in the list. */ + now: string; +}; + +export type PredictionEventPayload = PredictionEventEntity; + +export type PredictionDetailPayload = PredictionPayload & { + events: PredictionEventPayload[]; + audit: AuditEntryPayload[]; + trackRecord: { wins: number; closed: number }; +}; + +// POST /admin/predictions/:id/resolve { proposalId, price, source, at, reason? } → 204 + +export type ResolvePredictionArgs = { + id: string; + proposalId: string; + price: number; + source: QuoteSourceId; + /** The trigger time: the close time. */ + at: string; + /** Only with a corrected price (J11-8g). */ + reason?: string; +}; + +export type ResolvePredictionDto = { + proposalId: string; + price: number; + source: QuoteSourceId; + at: string; + reason?: string; +}; + +// POST /admin/predictions/:id/proposal/dismiss { reason } → 204 + +export type DismissProposalArgs = { id: string; reason: string }; +export type DismissProposalDto = { reason: string }; + +// POST /admin/predictions/:id/override { closedPrice, reason } → 204: corrects a closed prediction, +// or closes an open one now at that price. + +export type OverridePredictionArgs = { + id: string; + closedPrice: number; + reason: string; +}; +export type OverridePredictionDto = { closedPrice: number; reason: string }; + +// POST /admin/predictions/:id/flag { reason, note? } · DELETE /admin/predictions/:id/flag → 204 + +export type FlagPredictionArgs = { + id: string; + reason: FlagReason; + note?: string; +}; +export type FlagPredictionDto = { reason: FlagReason; note?: string }; diff --git a/platforms/garden-roof/src/features/predictions/repositories/quote-sources/constants.ts b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/constants.ts new file mode 100644 index 0000000..f532946 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/constants.ts @@ -0,0 +1,11 @@ +export const QUOTE_SOURCE_ENDPOINTS = { + health: '/admin/quote-sources/health', +} as const; + +/** The strip checks the sources every minute (J11-8: «بررسی خودکار هر ۱ دقیقه»). */ +export const QUOTE_HEALTH_REFRESH_MS = 60_000; + +export const quoteSourceKeys = { + all: ['quote-sources'] as const, + health: () => [...quoteSourceKeys.all, 'health'] as const, +}; diff --git a/platforms/garden-roof/src/features/predictions/repositories/quote-sources/index.ts b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/index.ts new file mode 100644 index 0000000..cafb12b --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/index.ts @@ -0,0 +1,7 @@ +export { + QUOTE_HEALTH_REFRESH_MS, + QUOTE_SOURCE_ENDPOINTS, + quoteSourceKeys, +} from './constants'; +export { quoteSourcesRepository } from './quote-sources'; +export type { QuoteHealthPayload, QuoteSourcePayload } from './types'; diff --git a/platforms/garden-roof/src/features/predictions/repositories/quote-sources/mappers.ts b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/mappers.ts new file mode 100644 index 0000000..9c05345 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/mappers.ts @@ -0,0 +1,27 @@ +import type { QuoteHealthPayload, QuoteHealthResponseDto } from './types'; + +export function toQuoteHealthPayload( + dto: QuoteHealthResponseDto, +): QuoteHealthPayload { + const checkedAt = Date.parse(dto.checkedAt); + return { + checkedAt: dto.checkedAt, + sources: dto.sources.map((source) => ({ + id: source.id, + markets: [...source.markets], + lastPriceAt: source.lastPriceAt, + isStale: source.stale, + minutesWithoutPrice: + source.lastPriceAt === null + ? null + : Math.max( + 0, + Math.floor((checkedAt - Date.parse(source.lastPriceAt)) / 60_000), + ), + heldProposals: source.heldProposals, + })), + staleMarkets: dto.sources + .filter((source) => source.stale) + .flatMap((source) => source.markets), + }; +} diff --git a/platforms/garden-roof/src/features/predictions/repositories/quote-sources/quote-sources.ts b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/quote-sources.ts new file mode 100644 index 0000000..c4d03c1 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/quote-sources.ts @@ -0,0 +1,17 @@ +import { predictionsHttp } from '../../http'; +import { QUOTE_SOURCE_ENDPOINTS } from './constants'; +import { toQuoteHealthPayload } from './mappers'; +import type { QuoteHealthPayload, QuoteHealthResponseDto } from './types'; + +/** «وضعیت منابع قیمت» (J11-8): each quote source's last price and the proposals it holds. */ +export const quoteSourcesRepository = { + async health({ + signal, + }: { signal?: AbortSignal } = {}): Promise { + const response = await predictionsHttp.get( + QUOTE_SOURCE_ENDPOINTS.health, + { signal }, + ); + return toQuoteHealthPayload(response); + }, +}; diff --git a/platforms/garden-roof/src/features/predictions/repositories/quote-sources/types.ts b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/types.ts new file mode 100644 index 0000000..4d440fa --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/repositories/quote-sources/types.ts @@ -0,0 +1,30 @@ +import type { PredictionMarket } from '../../entities/prediction'; +import type { + QuoteHealthEntity, + QuoteSourceId, +} from '../../entities/quote-source'; + +// GET /admin/quote-sources/health + +export type QuoteHealthResponseDto = QuoteHealthEntity; + +export type QuoteSourcePayload = { + id: QuoteSourceId; + markets: PredictionMarket[]; + /** `null` while the source hasn't answered since the service started. */ + lastPriceAt: string | null; + isStale: boolean; + /** + * Whole minutes since its last price at the check, for «۲۵ دقیقه بدون قیمت»; `null` with no price + * yet. + */ + minutesWithoutPrice: number | null; + heldProposals: number; +}; + +export type QuoteHealthPayload = { + checkedAt: string; + sources: QuoteSourcePayload[]; + /** The markets whose close proposals wait for a fresh price, for the banner (J11-8). */ + staleMarkets: PredictionMarket[]; +}; diff --git a/platforms/garden-roof/src/features/predictions/types.ts b/platforms/garden-roof/src/features/predictions/types.ts new file mode 100644 index 0000000..29d1db2 --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/types.ts @@ -0,0 +1,11 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'prediction.resolved': { id: string; corrected: boolean }; + 'prediction.proposal_dismissed': { id: string }; + 'prediction.overridden': { id: string }; + 'prediction.flagged': { id: string; reason: string }; + 'prediction.unflagged': { id: string }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/features/predictions/utils.ts b/platforms/garden-roof/src/features/predictions/utils.ts new file mode 100644 index 0000000..37eccea --- /dev/null +++ b/platforms/garden-roof/src/features/predictions/utils.ts @@ -0,0 +1,44 @@ +import type { + PredictionDirection, + PredictionOutcome, +} from './entities/prediction'; + +/** ±0.05% from entry is breakeven, as PredictionCard reads it. */ +const BREAKEVEN_BAND = 0.05; + +/** % from entry in the prediction's direction: a short gains when the price falls. */ +export function roiOf( + { + direction, + entryPrice, + }: { direction: PredictionDirection; entryPrice: number }, + price: number, +): number { + const change = ((price - entryPrice) / entryPrice) * 100; + return direction === 'short' ? -change : change; +} + +export function outcomeOf(roi: number): PredictionOutcome { + if (Math.abs(roi) <= BREAKEVEN_BAND) return 'breakeven'; + return roi > 0 ? 'win' : 'loss'; +} + +/** + * The win rate after one prediction's outcome changes (J11-8d: «نرخ موفقیت ۵۵٫۰٪ ← ۵۶٫۷٪»): wins + * over closed predictions. `from` is `null` for an open prediction that closes now, which adds one + * closed prediction. Which outcomes count as a win is still open (OQ). + */ +export function winRateAfter( + record: { wins: number; closed: number }, + from: PredictionOutcome | null, + to: PredictionOutcome, +): { before: number; after: number } { + const wins = record.wins - (from === 'win' ? 1 : 0) + (to === 'win' ? 1 : 0); + const closed = record.closed + (from === null ? 1 : 0); + const rate = (value: number, total: number) => + total === 0 ? 0 : (value / total) * 100; + return { + before: rate(record.wins, record.closed), + after: rate(wins, closed), + }; +} diff --git a/platforms/garden-roof/src/features/subscriptions/actions/extend-subscription/actions.ts b/platforms/garden-roof/src/features/subscriptions/actions/extend-subscription/actions.ts new file mode 100644 index 0000000..5d299e4 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/actions/extend-subscription/actions.ts @@ -0,0 +1,27 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { SUBSCRIPTION_EVENTS } from '../../constants'; +import { subscriptionsRepository } from '../../repositories/subscriptions'; +import type { + ExtendSubscriptionArgs, + SubscriptionDetailPayload, +} from '../../repositories/subscriptions'; + +/** + * «تمدید اشتراک» (J11-7d): the expiry moves by the days picked, from the current expiry, with no + * money in or out; the subscriber is notified and the audit log gets a row with the reason. + * Emits `subscription.extended`. + */ +export async function extendSubscription( + args: ExtendSubscriptionArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await subscriptionsRepository.extend(args); + if (emit) { + eventEmitter.emit(SUBSCRIPTION_EVENTS.extended, { + id: args.id, + days: args.days, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/subscriptions/actions/extend-subscription/index.ts b/platforms/garden-roof/src/features/subscriptions/actions/extend-subscription/index.ts new file mode 100644 index 0000000..2e15a0d --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/actions/extend-subscription/index.ts @@ -0,0 +1 @@ +export { extendSubscription } from './actions'; diff --git a/platforms/garden-roof/src/features/subscriptions/actions/grant-access/actions.ts b/platforms/garden-roof/src/features/subscriptions/actions/grant-access/actions.ts new file mode 100644 index 0000000..28246ef --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/actions/grant-access/actions.ts @@ -0,0 +1,29 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { SUBSCRIPTION_EVENTS } from '../../constants'; +import { subscriptionsRepository } from '../../repositories/subscriptions'; +import type { + GrantAccessArgs, + GrantPayload, +} from '../../repositories/subscriptions'; + +/** + * «اعطای دسترسی» (J11-7c): opens the channel to the investor from now for the period, with no + * payment, transaction, ledger row or invite-code seat; only the audit log keeps it. Refused (409) + * while the investor already has an active subscription to that channel. + * Emits `subscription.granted`. + */ +export async function grantAccess( + args: GrantAccessArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await subscriptionsRepository.grant(args); + if (emit) { + eventEmitter.emit(SUBSCRIPTION_EVENTS.granted, { + id: result.id, + investorId: args.investorId, + analystId: args.analystId, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/subscriptions/actions/grant-access/index.ts b/platforms/garden-roof/src/features/subscriptions/actions/grant-access/index.ts new file mode 100644 index 0000000..7e2581a --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/actions/grant-access/index.ts @@ -0,0 +1 @@ +export { grantAccess } from './actions'; diff --git a/platforms/garden-roof/src/features/subscriptions/actions/refund-subscription/actions.ts b/platforms/garden-roof/src/features/subscriptions/actions/refund-subscription/actions.ts new file mode 100644 index 0000000..c5ce9cc --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/actions/refund-subscription/actions.ts @@ -0,0 +1,28 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { SUBSCRIPTION_EVENTS } from '../../constants'; +import { subscriptionsRepository } from '../../repositories/subscriptions'; +import type { + RefundSubscriptionArgs, + SubscriptionDetailPayload, +} from '../../repositories/subscriptions'; + +/** + * «بازگشت وجه و پایان اشتراک» (J11-7e): records the bank transfer already made, in one + * transaction: the investor's «بازگشت وجه» row, access ending now, the analyst's share off their + * balance, and an SMS to both. Once per subscription, at most what was paid. + * Emits `subscription.refunded`. + */ +export async function refundSubscription( + args: RefundSubscriptionArgs, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await subscriptionsRepository.refund(args); + if (emit) { + eventEmitter.emit(SUBSCRIPTION_EVENTS.refunded, { + id: args.id, + amount: args.amount, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/subscriptions/actions/refund-subscription/index.ts b/platforms/garden-roof/src/features/subscriptions/actions/refund-subscription/index.ts new file mode 100644 index 0000000..57cecb9 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/actions/refund-subscription/index.ts @@ -0,0 +1 @@ +export { refundSubscription } from './actions'; diff --git a/platforms/garden-roof/src/features/subscriptions/constants.ts b/platforms/garden-roof/src/features/subscriptions/constants.ts new file mode 100644 index 0000000..b01ad06 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/constants.ts @@ -0,0 +1,46 @@ +/** Events subscription actions emit when they succeed. */ +export const SUBSCRIPTION_EVENTS = { + extended: 'subscription.extended', + refunded: 'subscription.refunded', + granted: 'subscription.granted', +} as const; + +/** The URL's query parameters on the subscriptions page (J11-7). */ +export const SUBSCRIPTION_PARAMS = { + q: 'q', + /** Comma-separated status filters. */ + status: 'status', + /** `grant` for «اعطای دستی». */ + source: 'source', + page: 'page', + /** The subscription open in the side panel (J11-7b). */ + id: 'id', + /** `1` while «اعطای دسترسی» is open (J11-7c). */ + grant: 'grant', +} as const; + +/** «مدت تمدید» (J11-7d): the chips, in days; the first is picked. */ +export const EXTEND_DAYS = ['7', '14', '30'] as const; + +/** + * «دلیل» of a grant (J11-7c); each has its label under `subscriptions:grant.reasons`. The API keeps + * the code; the open question of which codes stay is the designer's. + */ +export const GRANT_REASONS = [ + 'unrecorded_payment', + 'compensation', + 'beta_tester', + 'partnership', + 'other', +] as const; + +/** How long the grant dialog waits after typing before it looks a person up. */ +export const LOOKUP_DELAY_MS = 350; + +/** How many months each period runs, for the grant dialog's «دسترسی از … تا …» (J11-7c). */ +export const PERIOD_MONTHS = { + monthly: 1, + quarterly: 3, + semi_annual: 6, + yearly: 12, +} as const; diff --git a/platforms/garden-roof/src/features/subscriptions/entities/subscription/index.ts b/platforms/garden-roof/src/features/subscriptions/entities/subscription/index.ts new file mode 100644 index 0000000..0838b37 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/entities/subscription/index.ts @@ -0,0 +1,11 @@ +export type { + BillingPeriod, + PersonRefEntity, + SubscriptionDetailEntity, + SubscriptionGrantEntity, + SubscriptionListItemEntity, + SubscriptionPaymentEntity, + SubscriptionRefundEntity, + SubscriptionSource, + SubscriptionStatus, +} from './types'; diff --git a/platforms/garden-roof/src/features/subscriptions/entities/subscription/types.ts b/platforms/garden-roof/src/features/subscriptions/entities/subscription/types.ts new file mode 100644 index 0000000..081d275 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/entities/subscription/types.ts @@ -0,0 +1,81 @@ +import type { AuditEntryEntity } from '../../../audit'; +import type { BillingPeriod } from '../../../../shared/constants'; + +/** + * The investor's StatusBadge `subscription.*` (J11-7): `suspended` is an active subscription to a + * channel whose analyst is suspended («کانال معلق شده»), so the «فعال» filter includes it. + */ +export type SubscriptionStatus = + | 'active' + | 'suspended' + | 'expired' + | 'refunded'; + +/** Paid through the gateway, or given by an admin without payment (J11-7c). */ +export type SubscriptionSource = 'payment' | 'grant'; + +/** The tier's period; renewal periods are tier options (0031). */ +export type { BillingPeriod }; + +/** Who a row names: the subscriber or the analyst. */ +export type PersonRefEntity = { + id: string; + firstName: string; + lastName: string; + username: string; + avatarUrl: string | null; +}; + +/** A row of the list (`GET /admin/subscriptions`). No phone: it shows only in the detail panel. */ +export type SubscriptionListItemEntity = { + id: string; + investor: PersonRefEntity; + analyst: PersonRefEntity; + period: BillingPeriod; + startedAt: string; + endsAt: string; + status: SubscriptionStatus; + source: SubscriptionSource; +}; + +/** The gateway payment behind a paid subscription. */ +export type SubscriptionPaymentEntity = { + /** Toman. */ + amount: number; + paidAt: string; + /** The bank's tracking number («کد پیگیری»); `null` when the gateway gave none. */ + reference: string | null; + /** The platform's cut; a refund takes the rest from the analyst's balance (J11-7e). */ + commissionPercent: number; +}; + +/** The one refund a paid subscription can have (J11-7f). */ +export type SubscriptionRefundEntity = { + amount: number; + /** Masked: `IR`, 20 stars and the last 4 digits, the only ones kept; `null` when none were. */ + destinationSheba: string | null; + bankReference: string; + /** The admin's «دلیل»; `null` for a refund recorded outside the panel. */ + reason: string | null; + at: string; + /** The expiry the refund cut short. */ + previousEndsAt: string; +}; + +/** Why an admin gave access without payment, with their note (J11-7c). */ +export type SubscriptionGrantEntity = { + reasonCode: string; + note: string; +}; + +/** One subscription (`GET /admin/subscriptions/:id`). */ +export type SubscriptionDetailEntity = SubscriptionListItemEntity & { + /** E.164; admins only. Empty when the account is gone. */ + investorPhone: string; + /** The last completed gateway payment; `null` for a grant or a paid one with no payment recorded. */ + payment: SubscriptionPaymentEntity | null; + refund: SubscriptionRefundEntity | null; + /** Grants only. */ + grant: SubscriptionGrantEntity | null; + audit: AuditEntryEntity[]; +}; diff --git a/platforms/garden-roof/src/features/subscriptions/http.ts b/platforms/garden-roof/src/features/subscriptions/http.ts new file mode 100644 index 0000000..005cc2c --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const subscriptionHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/subscriptions/index.ts b/platforms/garden-roof/src/features/subscriptions/index.ts new file mode 100644 index 0000000..7ba05e6 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/index.ts @@ -0,0 +1,66 @@ +import './types'; + +export { extendSubscription } from './actions/extend-subscription'; +export { grantAccess } from './actions/grant-access'; +export { refundSubscription } from './actions/refund-subscription'; +export { + EXTEND_DAYS, + GRANT_REASONS, + LOOKUP_DELAY_MS, + PERIOD_MONTHS, + SUBSCRIPTION_EVENTS, + SUBSCRIPTION_PARAMS, +} from './constants'; +export type { + BillingPeriod, + SubscriptionSource, + SubscriptionStatus, +} from './entities/subscription'; +export { useSubscriptionDetailPart } from './models/detail'; +export type { + ExtendForm, + RefundForm, + SubscriptionDetailPartModel, + SubscriptionDialog, +} from './models/detail'; +export { useGrantAccessDialog } from './models/grant'; +export type { + GrantAccessDialogModel, + GrantAccessDialogOptions, + GrantForm, + PersonLookup, +} from './models/grant'; +export { + useSubscriptionListPart, + useSubscriptionsPage, + useSubscriptionsToolbar, +} from './models/list'; +export type { + SubscriptionListPartModel, + SubscriptionsPageModel, + SubscriptionsToolbarModel, +} from './models/list'; +export { + BILLING_PERIODS, + SUBSCRIPTION_ENDPOINTS, + SUBSCRIPTION_ERROR_CODES, + SUBSCRIPTION_FILTERS, + SUBSCRIPTION_STATUS_FILTERS, + subscriptionKeys, + subscriptionsRepository, +} from './repositories/subscriptions'; +export type { + ExtendSubscriptionArgs, + GrantAccessArgs, + GrantPayload, + ListSubscriptionsArgs, + LookupPersonArgs, + PersonRefPayload, + PersonRole, + RefundSubscriptionArgs, + SubscriptionDetailPayload, + SubscriptionFilter, + SubscriptionListItemPayload, + SubscriptionPagePayload, + SubscriptionStatusFilter, +} from './repositories/subscriptions'; diff --git a/platforms/garden-roof/src/features/subscriptions/models/detail/index.ts b/platforms/garden-roof/src/features/subscriptions/models/detail/index.ts new file mode 100644 index 0000000..daeaf58 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/detail/index.ts @@ -0,0 +1,7 @@ +export { useSubscriptionDetailPart } from './use-subscription-detail-part'; +export type { + ExtendForm, + RefundForm, + SubscriptionDetailPartModel, + SubscriptionDialog, +} from './types'; diff --git a/platforms/garden-roof/src/features/subscriptions/models/detail/types.ts b/platforms/garden-roof/src/features/subscriptions/models/detail/types.ts new file mode 100644 index 0000000..1971eb5 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/detail/types.ts @@ -0,0 +1,51 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { + ExtendSubscriptionFormOutput, + ExtendSubscriptionFormValues, + RefundSubscriptionFormOutput, + RefundSubscriptionFormValues, +} from '../../../../shared/validations/subscription-validations'; +import type { SubscriptionDetailPayload } from '../../repositories/subscriptions'; + +export type ExtendForm = UseFormReturn< + ExtendSubscriptionFormValues, + unknown, + ExtendSubscriptionFormOutput +>; + +export type RefundForm = UseFormReturn< + RefundSubscriptionFormValues, + unknown, + RefundSubscriptionFormOutput +>; + +/** Which dialog is open over the detail panel: «تمدید دستی» (J11-7d) or «بازگشت وجه» (J11-7e). */ +export type SubscriptionDialog = 'extend' | 'refund' | null; + +export type SubscriptionDetailPartModel = { + subscription: SubscriptionDetailPayload; + dialog: SubscriptionDialog; + openExtend: () => void; + openRefund: () => void; + closeDialog: () => void; + extendForm: ExtendForm; + /** The days picked, as a number. */ + extendDays: number; + /** The expiry those days lead to, from the current one. */ + extendedEndsAt: string; + /** Validates, then extends; a failure keeps the dialog and its text. */ + submitExtend: () => void; + isExtending: boolean; + refundForm: RefundForm; + /** The amount typed, in Toman; 0 while it isn't a number yet. */ + refundAmount: number; + /** The analyst's share of that amount, taken off their balance (J11-7e). */ + refundDeduction: number; + /** Digits only, grouped in thousands as they're typed (`540٬000`). */ + formatAmount: (value: string) => string; + /** The 24 digits after `IR`, grouped as banks print them (`48 0570 0300 …`). */ + formatSheba: (value: string) => string; + submitRefund: () => void; + isRefunding: boolean; +}; diff --git a/platforms/garden-roof/src/features/subscriptions/models/detail/use-subscription-detail-part.ts b/platforms/garden-roof/src/features/subscriptions/models/detail/use-subscription-detail-part.ts new file mode 100644 index 0000000..fb14c33 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/detail/use-subscription-detail-part.ts @@ -0,0 +1,222 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { latinDigits, number, sheba } from '@lumina/tools/format'; +import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'; +import { useMemo, useState } from 'react'; +import { useForm, useWatch } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { applyServerErrors } from '../../../../shared/utils'; +import { + extendSubscriptionSchema, + refundSubscriptionSchema, +} from '../../../../shared/validations/subscription-validations'; +import type { + ExtendSubscriptionFormOutput, + ExtendSubscriptionFormValues, + RefundSubscriptionFormOutput, + RefundSubscriptionFormValues, +} from '../../../../shared/validations/subscription-validations'; +import { extendSubscription } from '../../actions/extend-subscription'; +import { refundSubscription } from '../../actions/refund-subscription'; +import { EXTEND_DAYS } from '../../constants'; +import { + SUBSCRIPTION_ERROR_CODES, + subscriptionKeys, + subscriptionsRepository, +} from '../../repositories/subscriptions'; +import type { SubscriptionDetailPayload } from '../../repositories/subscriptions'; +import type { SubscriptionDetailPartModel, SubscriptionDialog } from './types'; + +const DAY_MS = 24 * 60 * 60 * 1000; +const SHEBA_DIGITS = 24; + +/** Whole Toman from what's typed; 0 while it isn't a number. */ +function amountOf(value: string): number { + const digits = latinDigits(value).replace(/\D/g, ''); + return digits ? Number(digits) : 0; +} + +/** + * جزئیات اشتراک (J11-7b) with «تمدید دستی» (J11-7d) and «بازگشت وجه» (J11-7e) over it. Extend is + * for an active or suspended subscription and moves the expiry from the current one; refund is + * for a paid one, once, at most what was paid, and ends access now. Each toasts and the panel + * shows the subscription as it is now (J11-7f). A failure keeps the dialog with its text and + * offers a retry; one already changed elsewhere (409, a refund with no payment behind it, or a + * subscription gone) closes the dialog and reloads the panel. An amount over the payment the + * server knows goes under «مبلغ بازگشت». + */ +export function useSubscriptionDetailPart({ + id, +}: { + id: string; +}): SubscriptionDetailPartModel { + const { t } = useTranslation(['subscriptions', 'common']); + const queryClient = useQueryClient(); + const { data: subscription } = useSuspenseQuery({ + queryKey: subscriptionKeys.detail(id), + queryFn: ({ signal }) => subscriptionsRepository.get(id, { signal }), + }); + const [dialog, setDialog] = useState(null); + const [isExtending, setIsExtending] = useState(false); + const [isRefunding, setIsRefunding] = useState(false); + const paidAmount = subscription.payment?.amount ?? 0; + + const extendForm = useForm< + ExtendSubscriptionFormValues, + unknown, + ExtendSubscriptionFormOutput + >({ + resolver: valibotResolver(extendSubscriptionSchema), + defaultValues: { days: EXTEND_DAYS[0], reason: '' }, + }); + const refundResolver = useMemo( + () => valibotResolver(refundSubscriptionSchema(paidAmount)), + [paidAmount], + ); + const refundDefaults = { + amount: number(paidAmount), + destinationSheba: '', + bankReference: '', + reason: '', + }; + const refundForm = useForm< + RefundSubscriptionFormValues, + unknown, + RefundSubscriptionFormOutput + >({ resolver: refundResolver, defaultValues: refundDefaults }); + + const extendDays = Number( + useWatch({ control: extendForm.control, name: 'days' }), + ); + const refundAmount = amountOf( + useWatch({ control: refundForm.control, name: 'amount' }), + ); + const commission = subscription.payment?.commissionPercent ?? 0; + + /** The panel shows the answer at once; the list refetches its rows. */ + const settle = async (next: SubscriptionDetailPayload) => { + setDialog(null); + queryClient.setQueryData(subscriptionKeys.detail(id), next); + await queryClient.invalidateQueries({ queryKey: subscriptionKeys.lists() }); + }; + + /** Changed or gone in the meantime: say so, close the dialog and reload the panel and the list. */ + const refused = async (message: string) => { + setDialog(null); + showToast({ tone: 'info', message }); + await queryClient.invalidateQueries({ queryKey: subscriptionKeys.all }); + }; + + const extend = async (values: ExtendSubscriptionFormOutput) => { + if (isExtending) return; + setIsExtending(true); + try { + const next = await extendSubscription({ id, ...values }); + showToast({ + tone: 'success', + message: t('extend.done', { days: number(values.days) }), + }); + await settle(next); + } catch (error) { + if ( + isHttpError(error) && + error.code === SUBSCRIPTION_ERROR_CODES.notRunning + ) { + await refused(t('extend.not-running')); + } else if (isHttpError(error) && error.status === 404) { + await refused(t('detail.gone')); + } else { + applyServerErrors(extendForm, error, { + t, + failedMessage: t('extend.failed'), + retry: () => void extend(values), + }); + } + } finally { + setIsExtending(false); + } + }; + + const refund = async (values: RefundSubscriptionFormOutput) => { + if (isRefunding) return; + setIsRefunding(true); + try { + const next = await refundSubscription({ id, ...values }); + showToast({ tone: 'success', message: t('refund.done') }); + await settle(next); + } catch (error) { + const code = isHttpError(error) ? error.code : undefined; + if (code === SUBSCRIPTION_ERROR_CODES.alreadyRefunded) { + await refused(t('refund.already-refunded')); + } else if (code === SUBSCRIPTION_ERROR_CODES.notPaid) { + await refused(t('refund.not-paid')); + } else if (isHttpError(error) && error.status === 404) { + await refused(t('detail.gone')); + } else if ( + isHttpError(error) && + code === SUBSCRIPTION_ERROR_CODES.refundAmountInvalid + ) { + // The payment as the server knows it, when it differs from the one the panel shows. + const max = error.details?.maxAmount; + refundForm.setError( + 'amount', + { + type: 'server', + message: + typeof max === 'number' + ? t('refund.errors.amount-over', { amount: number(max) }) + : t('refund.errors.amount-max'), + }, + { shouldFocus: true }, + ); + } else { + applyServerErrors(refundForm, error, { + t, + failedMessage: t('refund.failed'), + retry: () => void refund(values), + }); + } + } finally { + setIsRefunding(false); + } + }; + + return { + subscription, + dialog, + openExtend: () => { + extendForm.reset(); + setDialog('extend'); + }, + openRefund: () => { + refundForm.reset(refundDefaults); + setDialog('refund'); + }, + closeDialog: () => setDialog(null), + extendForm, + extendDays, + extendedEndsAt: new Date( + Date.parse(subscription.endsAt) + extendDays * DAY_MS, + ).toISOString(), + submitExtend: () => void extendForm.handleSubmit(extend)(), + isExtending, + refundForm, + refundAmount, + refundDeduction: Math.round((refundAmount * (100 - commission)) / 100), + formatAmount: (value) => { + const amount = amountOf(value); + return amount > 0 ? number(amount) : ''; + }, + formatSheba: (value) => { + const digits = latinDigits(value) + .replace(/^\s*IR/i, '') + .replace(/\D/g, '') + .slice(0, SHEBA_DIGITS); + return digits ? sheba(digits, { prefix: false }) : ''; + }, + submitRefund: () => void refundForm.handleSubmit(refund)(), + isRefunding, + }; +} diff --git a/platforms/garden-roof/src/features/subscriptions/models/grant/index.ts b/platforms/garden-roof/src/features/subscriptions/models/grant/index.ts new file mode 100644 index 0000000..91a07f6 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/grant/index.ts @@ -0,0 +1,7 @@ +export { useGrantAccessDialog } from './use-grant-access-dialog'; +export type { + GrantAccessDialogModel, + GrantAccessDialogOptions, + GrantForm, + PersonLookup, +} from './types'; diff --git a/platforms/garden-roof/src/features/subscriptions/models/grant/types.ts b/platforms/garden-roof/src/features/subscriptions/models/grant/types.ts new file mode 100644 index 0000000..dad3277 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/grant/types.ts @@ -0,0 +1,41 @@ +import type { UseFormReturn } from 'react-hook-form'; + +import type { + GrantAccessFormOutput, + GrantAccessFormValues, +} from '../../../../shared/validations/subscription-validations'; +import type { PersonRefPayload } from '../../repositories/subscriptions'; + +export type GrantForm = UseFormReturn< + GrantAccessFormValues, + unknown, + GrantAccessFormOutput +>; + +/** + * The live check under «کاربر» or «کانال» (J11-7c): nothing typed, looking, the person found (their + * name shows as the field's success), or no match. + */ +export type PersonLookup = + | { status: 'idle' } + | { status: 'searching' } + | { status: 'found'; person: PersonRefPayload } + | { status: 'missing' }; + +export type GrantAccessDialogModel = { + form: GrantForm; + investor: PersonLookup; + analyst: PersonLookup; + /** Roughly when the access would run: from now for the period picked; the API sets the expiry. */ + window: { from: string; to: string }; + /** Validates, resolves both people, then grants; a failure keeps the dialog and its text. */ + submit: () => void; + isSubmitting: boolean; + /** The dialog has closed: back to an empty form for next time. */ + reset: () => void; +}; + +export type GrantAccessDialogOptions = { + /** After the grant: close the dialog (the list already refetches). */ + onGranted: () => void; +}; diff --git a/platforms/garden-roof/src/features/subscriptions/models/grant/use-grant-access-dialog.ts b/platforms/garden-roof/src/features/subscriptions/models/grant/use-grant-access-dialog.ts new file mode 100644 index 0000000..89eb1a1 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/grant/use-grant-access-dialog.ts @@ -0,0 +1,225 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { date } from '@lumina/tools/format'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useForm, useWatch } from 'react-hook-form'; +import { useTranslation } from 'react-i18next'; + +import { applyServerErrors, useDebouncedValue } from '../../../../shared/utils'; +import { grantAccessSchema } from '../../../../shared/validations/subscription-validations'; +import type { + GrantAccessFormOutput, + GrantAccessFormValues, +} from '../../../../shared/validations/subscription-validations'; +import { grantAccess } from '../../actions/grant-access'; +import { LOOKUP_DELAY_MS, PERIOD_MONTHS } from '../../constants'; +import type { BillingPeriod } from '../../entities/subscription'; +import { + BILLING_PERIODS, + SUBSCRIPTION_ERROR_CODES, + subscriptionKeys, + subscriptionsRepository, +} from '../../repositories/subscriptions'; +import type { + PersonRefPayload, + PersonRole, +} from '../../repositories/subscriptions'; +import type { + GrantAccessDialogModel, + GrantAccessDialogOptions, + PersonLookup, +} from './types'; + +const DEFAULTS: GrantAccessFormValues = { + investor: '', + analyst: '', + period: BILLING_PERIODS[0], + reasonCode: '', + note: '', +}; + +/** What a lookup is keyed by: the text without spaces or a leading `@`. */ +function lookupText(value: string): string { + return value.trim().replace(/^@/, ''); +} + +function lookupQuery(role: PersonRole, text: string) { + return { + queryKey: subscriptionKeys.lookup(role, text), + queryFn: ({ signal }: { signal: AbortSignal }) => + subscriptionsRepository.lookup({ role, q: text }, { signal }), + }; +} + +/** The field's live check, once typing paused. */ +function usePersonLookup(role: PersonRole, value: string): PersonLookup { + const typed = lookupText(value); + const settled = useDebouncedValue(typed, LOOKUP_DELAY_MS); + const query = useQuery({ + ...lookupQuery(role, settled), + enabled: settled !== '', + }); + if (typed === '') return { status: 'idle' }; + if (typed !== settled || query.isPending) return { status: 'searching' }; + if (query.data) return { status: 'found', person: query.data }; + // A failed lookup says nothing yet; submitting looks again and says what failed. + return query.isError ? { status: 'idle' } : { status: 'missing' }; +} + +/** + * The preview's end: the API adds the period's calendar months to now (Gregorian, 10 Oct + 1 → 10 + * Nov) and its answer is the real expiry; this only shows roughly where it lands. + */ +function addMonths(at: number, months: number): string { + const end = new Date(at); + end.setMonth(end.getMonth() + months); + return end.toISOString(); +} + +/** + * «اعطای دسترسی» (J11-7c): the subscriber (username or phone) and the channel (username) are + * looked up as they're typed, the person's name showing under each; the period, a reason code and + * a note go into the audit log. No payment, transaction or code seat. Submitting looks both up + * once more; an investor already subscribed to the channel (409) is told under «کانال», a period + * the channel has no plan for (422) under «دوره», and either person gone meanwhile (404) above the + * actions; the dialog stays. The success toast names the expiry the API set. + */ +export function useGrantAccessDialog({ + onGranted, +}: GrantAccessDialogOptions): GrantAccessDialogModel { + const { t } = useTranslation(['subscriptions', 'common']); + const queryClient = useQueryClient(); + const [isSubmitting, setIsSubmitting] = useState(false); + // The preview's «from»: when the dialog was first drawn; the API decides the real start. + const [openedAt] = useState(() => Date.now()); + const form = useForm({ + resolver: valibotResolver(grantAccessSchema), + defaultValues: DEFAULTS, + }); + const investor = usePersonLookup( + 'investor', + useWatch({ control: form.control, name: 'investor' }), + ); + const analyst = usePersonLookup( + 'analyst', + useWatch({ control: form.control, name: 'analyst' }), + ); + const period = useWatch({ + control: form.control, + name: 'period', + }) as BillingPeriod; + + const resolve = ( + role: PersonRole, + value: string, + ): Promise => + queryClient.fetchQuery(lookupQuery(role, lookupText(value))); + + const grant = async (values: GrantAccessFormOutput) => { + if (isSubmitting) return; + setIsSubmitting(true); + let investorPerson: PersonRefPayload | null = null; + try { + const [foundInvestor, foundAnalyst] = await Promise.all([ + resolve('investor', values.investor), + resolve('analyst', values.analyst), + ]); + investorPerson = foundInvestor; + if (!foundInvestor || !foundAnalyst) { + if (!foundInvestor) { + form.setError( + 'investor', + { message: 'subscriptions:grant.errors.investor-not-found' }, + { shouldFocus: true }, + ); + } + if (!foundAnalyst) { + form.setError( + 'analyst', + { message: 'subscriptions:grant.errors.analyst-not-found' }, + { shouldFocus: Boolean(foundInvestor) }, + ); + } + return; + } + const granted = await grantAccess({ + investorId: foundInvestor.id, + analystId: foundAnalyst.id, + period: values.period as BillingPeriod, + reasonCode: values.reasonCode, + note: values.note, + }); + showToast({ + tone: 'success', + message: t('grant.done', { + investor: foundInvestor.fullName, + analyst: foundAnalyst.fullName, + date: date(granted.endsAt, { time: false }), + }), + }); + await queryClient.invalidateQueries({ + queryKey: subscriptionKeys.lists(), + }); + onGranted(); + } catch (error) { + const code = isHttpError(error) ? error.code : undefined; + if (code === SUBSCRIPTION_ERROR_CODES.alreadySubscribed) { + form.setError( + 'analyst', + { + type: 'server', + message: t('grant.errors.already-subscribed', { + name: investorPerson?.fullName ?? values.investor, + }), + }, + { shouldFocus: true }, + ); + return; + } + if (code === SUBSCRIPTION_ERROR_CODES.tierMissing) { + form.setError('period', { + type: 'server', + message: t('grant.errors.tier-missing', { + period: t( + `common:billing-periods.${values.period as BillingPeriod}`, + ), + }), + }); + return; + } + if (isHttpError(error) && error.status === 404) { + // Suspended or unverified since the lookup: the live checks look again. + form.setError('root.server', { + type: 'server', + message: t('grant.errors.person-gone'), + }); + await queryClient.invalidateQueries({ + queryKey: subscriptionKeys.lookups(), + }); + return; + } + applyServerErrors(form, error, { + t, + failedMessage: t('grant.failed'), + retry: () => void grant(values), + }); + } finally { + setIsSubmitting(false); + } + }; + + return { + form, + investor, + analyst, + window: { + from: new Date(openedAt).toISOString(), + to: addMonths(openedAt, PERIOD_MONTHS[period] ?? PERIOD_MONTHS.monthly), + }, + submit: () => void form.handleSubmit(grant)(), + isSubmitting, + reset: () => form.reset(DEFAULTS), + }; +} diff --git a/platforms/garden-roof/src/features/subscriptions/models/list/index.ts b/platforms/garden-roof/src/features/subscriptions/models/list/index.ts new file mode 100644 index 0000000..73b470b --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/list/index.ts @@ -0,0 +1,8 @@ +export { useSubscriptionListPart } from './use-subscription-list-part'; +export { useSubscriptionsPage } from './use-subscriptions-page'; +export { useSubscriptionsToolbar } from './use-subscriptions-toolbar'; +export type { + SubscriptionListPartModel, + SubscriptionsPageModel, + SubscriptionsToolbarModel, +} from './types'; diff --git a/platforms/garden-roof/src/features/subscriptions/models/list/types.ts b/platforms/garden-roof/src/features/subscriptions/models/list/types.ts new file mode 100644 index 0000000..4b0ec43 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/list/types.ts @@ -0,0 +1,47 @@ +import type { ListSearch } from '../../../../shared/utils'; +import type { + ListSubscriptionsArgs, + SubscriptionFilter, + SubscriptionListItemPayload, +} from '../../repositories/subscriptions'; + +export type SubscriptionsPageModel = { + /** The chips on now, any of them at once (J11-7). */ + filters: SubscriptionFilter[]; + /** Turns a chip on or off; the list starts again from page 1. */ + toggleFilter: (filter: SubscriptionFilter) => void; + /** The page with no search, filter or page: the empty state's way out. */ + clearHref: string; + /** What the list part reads; a change remounts it behind its skeleton. */ + args: ListSubscriptionsArgs; + /** Changes whenever `args` does: the list part's key. */ + argsKey: string; + /** The subscription open in the side panel (J11-7b), from `?id=`. */ + detailId: string | null; + /** The list's address with that subscription's panel open, on the same page. */ + detailHref: (id: string) => string; + openDetail: (id: string) => void; + closeDetail: () => void; + /** «اعطای دسترسی» (J11-7c) is open, from `?grant=1`. */ + isGrantOpen: boolean; + closeGrant: () => void; +}; + +/** The page header's controls, beside the title: the search and «اعطای دسترسی» (J11-7). */ +export type SubscriptionsToolbarModel = { + search: ListSearch; + /** The list's address with the grant dialog open. */ + grantHref: string; +}; + +export type SubscriptionListPartModel = { + rows: SubscriptionListItemPayload[]; + page: number; + pageCount: number; + total: number; + from: number; + to: number; + pageHref: (page: number) => string; + /** No row: no subscription at all, or nothing matched the search and filters. */ + empty: 'none' | 'search' | null; +}; diff --git a/platforms/garden-roof/src/features/subscriptions/models/list/use-subscription-list-part.ts b/platforms/garden-roof/src/features/subscriptions/models/list/use-subscription-list-part.ts new file mode 100644 index 0000000..e02ca86 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/list/use-subscription-list-part.ts @@ -0,0 +1,37 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { SUBSCRIPTION_PARAMS } from '../../constants'; +import { + subscriptionKeys, + subscriptionsRepository, +} from '../../repositories/subscriptions'; +import type { ListSubscriptionsArgs } from '../../repositories/subscriptions'; +import type { SubscriptionListPartModel } from './types'; + +/** The rows for the search, filters and page; 20 a page, newest start first. */ +export function useSubscriptionListPart( + args: ListSubscriptionsArgs, +): SubscriptionListPartModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data } = useSuspenseQuery({ + queryKey: subscriptionKeys.list(args), + queryFn: ({ signal }) => subscriptionsRepository.list(args, { signal }), + }); + const isFiltered = + Boolean(args.q) || args.statuses.length > 0 || args.grantsOnly; + + return { + rows: data.items, + page: data.page, + pageCount: data.pageCount, + total: data.total, + from: data.from, + to: data.to, + pageHref: (page) => + listHref(pathname, searchParams, { [SUBSCRIPTION_PARAMS.page]: page }), + empty: data.total > 0 ? null : isFiltered ? 'search' : 'none', + }; +} diff --git a/platforms/garden-roof/src/features/subscriptions/models/list/use-subscriptions-page.ts b/platforms/garden-roof/src/features/subscriptions/models/list/use-subscriptions-page.ts new file mode 100644 index 0000000..fffd5be --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/list/use-subscriptions-page.ts @@ -0,0 +1,83 @@ +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; + +import { listHref, pageOf } from '../../../../shared/utils'; +import { SUBSCRIPTION_PARAMS } from '../../constants'; +import { SUBSCRIPTION_STATUS_FILTERS } from '../../repositories/subscriptions'; +import type { + SubscriptionFilter, + SubscriptionStatusFilter, +} from '../../repositories/subscriptions'; +import type { SubscriptionsPageModel } from './types'; + +function statusesOf(value: string | null): SubscriptionStatusFilter[] { + const picked = value?.split(',') ?? []; + return SUBSCRIPTION_STATUS_FILTERS.filter((status) => + picked.includes(status), + ); +} + +/** + * اشتراک‌ها (J11-7): the search, the filter chips (any of فعال · منقضی‌شده · بازگشت وجه · اعطای + * دستی), the page, the open detail panel (`?id=`) and the grant dialog (`?grant=1`) all live in the + * URL, so a reload or a shared link shows the same thing. Every search or filter change starts + * again from page 1; opening or closing the panel keeps the page. + */ +export function useSubscriptionsPage(): SubscriptionsPageModel { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const statuses = statusesOf(searchParams.get(SUBSCRIPTION_PARAMS.status)); + const grantsOnly = searchParams.get(SUBSCRIPTION_PARAMS.source) === 'grant'; + const q = searchParams.get(SUBSCRIPTION_PARAMS.q)?.trim() ?? ''; + const page = pageOf(searchParams.get(SUBSCRIPTION_PARAMS.page)); + const detailId = searchParams.get(SUBSCRIPTION_PARAMS.id) || null; + const filters: SubscriptionFilter[] = grantsOnly + ? [...statuses, 'grant'] + : statuses; + + /** The same list with only the panel or dialog changed, on the same page. */ + const samePage = (changes: Record) => + listHref(pathname, searchParams, { + ...changes, + [SUBSCRIPTION_PARAMS.page]: searchParams.get(SUBSCRIPTION_PARAMS.page), + }); + const go = (href: string) => router.replace(href, { scroll: false }); + + const toggleFilter = (filter: SubscriptionFilter) => { + if (filter === 'grant') { + go( + listHref(pathname, searchParams, { + [SUBSCRIPTION_PARAMS.source]: grantsOnly ? null : 'grant', + }), + ); + return; + } + const next = statuses.includes(filter) + ? statuses.filter((status) => status !== filter) + : [...statuses, filter]; + go( + listHref(pathname, searchParams, { + [SUBSCRIPTION_PARAMS.status]: SUBSCRIPTION_STATUS_FILTERS.filter( + (status) => next.includes(status), + ).join(','), + }), + ); + }; + + const detailHref = (id: string) => samePage({ [SUBSCRIPTION_PARAMS.id]: id }); + const args = { q: q || undefined, statuses, grantsOnly, page }; + + return { + filters, + toggleFilter, + clearHref: pathname, + args, + argsKey: JSON.stringify(args), + detailId, + detailHref, + openDetail: (id) => go(detailHref(id)), + closeDetail: () => go(samePage({ [SUBSCRIPTION_PARAMS.id]: null })), + isGrantOpen: searchParams.get(SUBSCRIPTION_PARAMS.grant) === '1', + closeGrant: () => go(samePage({ [SUBSCRIPTION_PARAMS.grant]: null })), + }; +} diff --git a/platforms/garden-roof/src/features/subscriptions/models/list/use-subscriptions-toolbar.ts b/platforms/garden-roof/src/features/subscriptions/models/list/use-subscriptions-toolbar.ts new file mode 100644 index 0000000..18afd47 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/models/list/use-subscriptions-toolbar.ts @@ -0,0 +1,23 @@ +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref, useListSearch } from '../../../../shared/utils'; +import { SUBSCRIPTION_PARAMS } from '../../constants'; +import type { SubscriptionsToolbarModel } from './types'; + +/** + * The header's search (a username, a phone or a tracking number, in the URL as `q` once typing + * pauses) and the address that opens «اعطای دسترسی» over the same list (J11-7). + */ +export function useSubscriptionsToolbar(): SubscriptionsToolbarModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const search = useListSearch(SUBSCRIPTION_PARAMS.q); + + return { + search, + grantHref: listHref(pathname, searchParams, { + [SUBSCRIPTION_PARAMS.grant]: '1', + [SUBSCRIPTION_PARAMS.page]: searchParams.get(SUBSCRIPTION_PARAMS.page), + }), + }; +} diff --git a/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/constants.ts b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/constants.ts new file mode 100644 index 0000000..9173e1b --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/constants.ts @@ -0,0 +1,74 @@ +import type { BillingPeriod } from '../../entities/subscription'; +import type { + PersonRole, + SubscriptionFilter, + SubscriptionStatusFilter, +} from './types'; + +export const SUBSCRIPTION_ENDPOINTS = { + list: '/admin/subscriptions', + detail: (id: string) => `/admin/subscriptions/${encodeURIComponent(id)}`, + extend: (id: string) => + `/admin/subscriptions/${encodeURIComponent(id)}/extend`, + refund: (id: string) => + `/admin/subscriptions/${encodeURIComponent(id)}/refund`, + grants: '/admin/grants', + lookup: '/admin/people/lookup', +} as const; + +/** The filter chips in display order: فعال · منقضی‌شده · بازگشت وجه · اعطای دستی (J11-7). */ +export const SUBSCRIPTION_FILTERS = [ + 'active', + 'expired', + 'refunded', + 'grant', +] as const satisfies readonly SubscriptionFilter[]; + +export const SUBSCRIPTION_STATUS_FILTERS = [ + 'active', + 'expired', + 'refunded', +] as const satisfies readonly SubscriptionStatusFilter[]; + +/** The grant dialog's periods in display order (J11-7c). */ +export const BILLING_PERIODS = [ + 'monthly', + 'quarterly', + 'semi_annual', + 'yearly', +] as const satisfies readonly BillingPeriod[]; + +/** + * The codes the API marks subscription failures with; branch on these, never on the message (it is + * English). A missing subscription or person is a 404 with no code. + */ +export const SUBSCRIPTION_ERROR_CODES = { + /** 409 grant: the investor already has an active subscription to that channel (J11-7c). */ + alreadySubscribed: 'SUBSCRIPTION_ALREADY_ACTIVE', + /** 422 grant: the channel has no plan for that period, so nothing says what the access is. */ + tierMissing: 'SUBSCRIPTION_TIER_MISSING', + /** 409 refund: refunded in the meantime; a subscription is refunded once. */ + alreadyRefunded: 'SUBSCRIPTION_ALREADY_REFUNDED', + /** 422 refund: no completed payment behind it (a grant, or one seeded by hand). */ + notPaid: 'SUBSCRIPTION_NOT_PAID', + /** 422 refund: under 1 or more than was paid; `details.maxAmount` is the payment in Toman. */ + refundAmountInvalid: 'SUBSCRIPTION_REFUND_AMOUNT_INVALID', + /** 409 extend: expired or refunded in the meantime, so it can't be extended. */ + notRunning: 'SUBSCRIPTION_NOT_RUNNING', +} as const; + +export const subscriptionKeys = { + all: ['subscription'] as const, + lists: () => [...subscriptionKeys.all, 'list'] as const, + list: (args: { + q?: string; + statuses: SubscriptionStatusFilter[]; + grantsOnly: boolean; + page: number; + }) => [...subscriptionKeys.lists(), args] as const, + details: () => [...subscriptionKeys.all, 'detail'] as const, + detail: (id: string) => [...subscriptionKeys.details(), id] as const, + lookups: () => [...subscriptionKeys.all, 'lookup'] as const, + lookup: (role: PersonRole, q: string) => + [...subscriptionKeys.lookups(), role, q] as const, +}; diff --git a/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/index.ts b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/index.ts new file mode 100644 index 0000000..dc2a70e --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/index.ts @@ -0,0 +1,24 @@ +export { + BILLING_PERIODS, + SUBSCRIPTION_ENDPOINTS, + SUBSCRIPTION_ERROR_CODES, + SUBSCRIPTION_FILTERS, + SUBSCRIPTION_STATUS_FILTERS, + subscriptionKeys, +} from './constants'; +export { subscriptionsRepository } from './subscriptions'; +export type { + ExtendSubscriptionArgs, + GrantAccessArgs, + GrantPayload, + ListSubscriptionsArgs, + LookupPersonArgs, + PersonRefPayload, + PersonRole, + RefundSubscriptionArgs, + SubscriptionDetailPayload, + SubscriptionFilter, + SubscriptionListItemPayload, + SubscriptionPagePayload, + SubscriptionStatusFilter, +} from './types'; diff --git a/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/mappers.ts b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/mappers.ts new file mode 100644 index 0000000..f630e6f --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/mappers.ts @@ -0,0 +1,132 @@ +import { toApiUrl } from '../../../../shared/utils'; +import { toAuditEntryPayload } from '../../../audit'; +import type { + PersonRefEntity, + SubscriptionListItemEntity, +} from '../../entities/subscription'; +import type { + ExtendSubscriptionArgs, + ExtendSubscriptionDto, + GrantAccessArgs, + GrantAccessDto, + ListSubscriptionsArgs, + ListSubscriptionsQueryDto, + LookupPersonArgs, + LookupPersonQueryDto, + PersonRefPayload, + RefundSubscriptionArgs, + RefundSubscriptionDto, + SubscriptionDetailPayload, + SubscriptionDetailResponseDto, + SubscriptionListItemPayload, + SubscriptionPagePayload, + SubscriptionPageResponseDto, +} from './types'; + +const DAY_MS = 24 * 60 * 60 * 1000; + +export function toListSubscriptionsQueryDto( + args: ListSubscriptionsArgs, +): ListSubscriptionsQueryDto { + return { + query: args.q?.trim() || undefined, + status: args.statuses.length > 0 ? args.statuses.join(',') : undefined, + source: args.grantsOnly ? 'grant' : undefined, + page: args.page, + }; +} + +/** The API sends empty names for an account it can't find; the username stands in then. */ +export function toPersonRefPayload(dto: PersonRefEntity): PersonRefPayload { + return { + id: dto.id, + fullName: `${dto.firstName} ${dto.lastName}`.trim() || dto.username, + username: dto.username, + avatarUrl: toApiUrl(dto.avatarUrl), + }; +} + +function toListItemPayload( + dto: SubscriptionListItemEntity, +): SubscriptionListItemPayload { + return { + id: dto.id, + investor: toPersonRefPayload(dto.investor), + analyst: toPersonRefPayload(dto.analyst), + period: dto.period, + startedAt: dto.startedAt, + endsAt: dto.endsAt, + status: dto.status, + source: dto.source, + }; +} + +export function toSubscriptionPagePayload( + dto: SubscriptionPageResponseDto, +): SubscriptionPagePayload { + const from = dto.total === 0 ? 0 : (dto.page - 1) * dto.pageSize + 1; + return { + items: dto.items.map(toListItemPayload), + page: dto.page, + pageCount: Math.max(1, Math.ceil(dto.total / dto.pageSize)), + total: dto.total, + from, + to: from === 0 ? 0 : from + dto.items.length - 1, + }; +} + +/** Days left, counted up, as the investor's card counts them; `null` once access has ended. */ +function remainingDays(dto: SubscriptionDetailResponseDto): number | null { + if (dto.status !== 'active' && dto.status !== 'suspended') return null; + const left = Date.parse(dto.endsAt) - Date.now(); + return left > 0 ? Math.ceil(left / DAY_MS) : null; +} + +export function toSubscriptionDetailPayload( + dto: SubscriptionDetailResponseDto, +): SubscriptionDetailPayload { + return { + ...toListItemPayload(dto), + investorPhone: dto.investorPhone, + remainingDays: remainingDays(dto), + payment: dto.payment ? { ...dto.payment } : null, + refund: dto.refund ? { ...dto.refund } : null, + grant: dto.grant ? { ...dto.grant } : null, + canExtend: dto.status === 'active' || dto.status === 'suspended', + canRefund: dto.payment !== null && dto.refund === null, + audit: dto.audit.map(toAuditEntryPayload), + }; +} + +export function toExtendSubscriptionDto( + args: ExtendSubscriptionArgs, +): ExtendSubscriptionDto { + return { days: args.days, reason: args.reason.trim() }; +} + +export function toRefundSubscriptionDto( + args: RefundSubscriptionArgs, +): RefundSubscriptionDto { + return { + amount: args.amount, + destinationSheba: args.destinationSheba, + bankReference: args.bankReference.trim(), + reason: args.reason.trim(), + }; +} + +export function toGrantAccessDto(args: GrantAccessArgs): GrantAccessDto { + return { + investorId: args.investorId, + analystId: args.analystId, + tier: args.period, + reasonCode: args.reasonCode, + note: args.note.trim(), + }; +} + +export function toLookupPersonQueryDto( + args: LookupPersonArgs, +): LookupPersonQueryDto { + return { role: args.role, q: args.q.trim().replace(/^@/, '') }; +} diff --git a/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/subscriptions.ts b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/subscriptions.ts new file mode 100644 index 0000000..03c140e --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/subscriptions.ts @@ -0,0 +1,101 @@ +import { subscriptionHttp } from '../../http'; +import { SUBSCRIPTION_ENDPOINTS } from './constants'; +import { + toExtendSubscriptionDto, + toGrantAccessDto, + toListSubscriptionsQueryDto, + toLookupPersonQueryDto, + toPersonRefPayload, + toRefundSubscriptionDto, + toSubscriptionDetailPayload, + toSubscriptionPagePayload, +} from './mappers'; +import type { + ExtendSubscriptionArgs, + GrantAccessArgs, + GrantPayload, + GrantResponseDto, + ListSubscriptionsArgs, + LookupPersonArgs, + LookupPersonResponseDto, + PersonRefPayload, + RefundSubscriptionArgs, + SubscriptionChangeResponseDto, + SubscriptionDetailPayload, + SubscriptionDetailResponseDto, + SubscriptionPagePayload, + SubscriptionPageResponseDto, +} from './types'; + +/** + * Investors' subscriptions (J11-7): the list, one subscription, the manual extension and refund, + * and access given without payment. + */ +export const subscriptionsRepository = { + /** 20 a page, newest start first, searched and filtered. */ + async list( + args: ListSubscriptionsArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await subscriptionHttp.get( + SUBSCRIPTION_ENDPOINTS.list, + { params: toListSubscriptionsQueryDto(args), signal }, + ); + return toSubscriptionPagePayload(response); + }, + + /** One subscription with its payment, refund or grant, the subscriber's phone and its audit. */ + async get( + id: string, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await subscriptionHttp.get( + SUBSCRIPTION_ENDPOINTS.detail(id), + { signal }, + ); + return toSubscriptionDetailPayload(response); + }, + + /** Moves the expiry by `days` from the current one; no money moves. */ + async extend( + args: ExtendSubscriptionArgs, + ): Promise { + const response = await subscriptionHttp.post( + SUBSCRIPTION_ENDPOINTS.extend(args.id), + toExtendSubscriptionDto(args), + ); + return toSubscriptionDetailPayload(response); + }, + + /** Records the bank transfer already made and ends access now. */ + async refund( + args: RefundSubscriptionArgs, + ): Promise { + const response = await subscriptionHttp.post( + SUBSCRIPTION_ENDPOINTS.refund(args.id), + toRefundSubscriptionDto(args), + ); + return toSubscriptionDetailPayload(response); + }, + + /** Opens a channel to an investor without payment, from now for the period. */ + async grant(args: GrantAccessArgs): Promise { + const response = await subscriptionHttp.post( + SUBSCRIPTION_ENDPOINTS.grants, + toGrantAccessDto(args), + ); + return { id: response.id, endsAt: response.endsAt }; + }, + + /** The grant dialog's lookup: the one person the text names, or `null`. */ + async lookup( + args: LookupPersonArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await subscriptionHttp.get( + SUBSCRIPTION_ENDPOINTS.lookup, + { params: toLookupPersonQueryDto(args), signal }, + ); + return response.person ? toPersonRefPayload(response.person) : null; + }, +}; diff --git a/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/types.ts b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/types.ts new file mode 100644 index 0000000..e956463 --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/repositories/subscriptions/types.ts @@ -0,0 +1,146 @@ +import type { AuditEntryPayload } from '../../../audit'; +import type { + BillingPeriod, + PersonRefEntity, + SubscriptionDetailEntity, + SubscriptionListItemEntity, + SubscriptionPaymentEntity, + SubscriptionRefundEntity, + SubscriptionSource, + SubscriptionStatus, +} from '../../entities/subscription'; + +/** The statuses a filter chip asks for; «فعال» brings the suspended ones too. */ +export type SubscriptionStatusFilter = 'active' | 'expired' | 'refunded'; + +/** A filter chip (J11-7): three statuses and «اعطای دستی», any of them at once. */ +export type SubscriptionFilter = SubscriptionStatusFilter | 'grant'; + +// GET /admin/subscriptions?query=&status=&source=&page= + +export type ListSubscriptionsArgs = { + /** A username (subscriber or analyst), a phone or a tracking number. */ + q?: string; + /** Any of these; none means every status. */ + statuses: SubscriptionStatusFilter[]; + /** Only grants; otherwise both sources. */ + grantsOnly: boolean; + page: number; +}; + +export type ListSubscriptionsQueryDto = { + query?: string; + /** Comma-separated. */ + status?: string; + source?: SubscriptionSource; + page: number; +}; + +export type SubscriptionPageResponseDto = { + items: SubscriptionListItemEntity[]; + page: number; + pageSize: number; + total: number; +}; + +export type PersonRefPayload = { + id: string; + fullName: string; + username: string; + avatarUrl: string | null; +}; + +export type SubscriptionListItemPayload = { + id: string; + investor: PersonRefPayload; + analyst: PersonRefPayload; + period: BillingPeriod; + startedAt: string; + endsAt: string; + status: SubscriptionStatus; + source: SubscriptionSource; +}; + +export type SubscriptionPagePayload = { + items: SubscriptionListItemPayload[]; + page: number; + pageCount: number; + total: number; + /** The first and last row's place among all rows, for «نمایش ۱ تا ۲۰ از ۴۷». */ + from: number; + to: number; +}; + +// GET /admin/subscriptions/:id + +export type SubscriptionDetailResponseDto = SubscriptionDetailEntity; + +export type SubscriptionDetailPayload = SubscriptionListItemPayload & { + investorPhone: string; + /** Whole days until the expiry while access runs; `null` once it has ended (J11-7b «۴۲ روز مانده»). */ + remainingDays: number | null; + payment: SubscriptionPaymentEntity | null; + refund: SubscriptionRefundEntity | null; + grant: { reasonCode: string; note: string } | null; + /** Active or suspended: «تمدید دستی» (J11-7d). */ + canExtend: boolean; + /** Paid and not refunded yet: «بازگشت وجه» (J11-7e). */ + canRefund: boolean; + audit: AuditEntryPayload[]; +}; + +// POST /admin/subscriptions/:id/extend { days, reason } + +export type ExtendSubscriptionArgs = { + id: string; + days: number; + reason: string; +}; +export type ExtendSubscriptionDto = { days: number; reason: string }; + +// POST /admin/subscriptions/:id/refund { amount, destinationSheba, bankReference, reason } + +export type RefundSubscriptionArgs = { + id: string; + amount: number; + destinationSheba: string; + bankReference: string; + reason: string; +}; +export type RefundSubscriptionDto = Omit; + +/** Extend and refund answer 200 with the subscription as it is now. */ +export type SubscriptionChangeResponseDto = SubscriptionDetailEntity; + +// POST /admin/grants { investorId, analystId, tier, reasonCode, note } + +export type GrantAccessArgs = { + investorId: string; + analystId: string; + period: BillingPeriod; + reasonCode: string; + note: string; +}; + +export type GrantAccessDto = { + investorId: string; + analystId: string; + tier: BillingPeriod; + reasonCode: string; + note: string; +}; + +/** 201: the new (or reused) subscription and its expiry, from now plus the period's months. */ +export type GrantResponseDto = { id: string; endsAt: string }; +export type GrantPayload = { id: string; endsAt: string }; + +// GET /admin/people/lookup?role=&q= + +/** Who the grant dialog looks up: a subscriber by username or phone, a channel by username. */ +export type PersonRole = 'investor' | 'analyst'; + +export type LookupPersonArgs = { role: PersonRole; q: string }; +export type LookupPersonQueryDto = { role: PersonRole; q: string }; + +/** The one match, or `null`; a channel is found only while verified and not suspended. */ +export type LookupPersonResponseDto = { person: PersonRefEntity | null }; diff --git a/platforms/garden-roof/src/features/subscriptions/types.ts b/platforms/garden-roof/src/features/subscriptions/types.ts new file mode 100644 index 0000000..bdcd36c --- /dev/null +++ b/platforms/garden-roof/src/features/subscriptions/types.ts @@ -0,0 +1,13 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'subscription.extended': { id: string; days: number }; + 'subscription.refunded': { id: string; amount: number }; + 'subscription.granted': { + id: string; + investorId: string; + analystId: string; + }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/features/verification/actions/approve-verification/actions.ts b/platforms/garden-roof/src/features/verification/actions/approve-verification/actions.ts new file mode 100644 index 0000000..031cab2 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/actions/approve-verification/actions.ts @@ -0,0 +1,26 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { VERIFICATION_EVENTS } from '../../constants'; +import { verificationsRepository } from '../../repositories/verifications'; +import type { + DecisionPayload, + VerificationSort, +} from '../../repositories/verifications'; + +/** + * «بله، تأیید کن» (J11-3g): the analyst is verified at once, gets an in-app notice and an SMS, and + * their invite code is made; the audit log gets a row. Approval never lifts a suspension. + * Emits `verification.approved`. + */ +export async function approveVerification( + { + id, + analystId, + sort, + }: { id: string; analystId: string; sort: VerificationSort }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await verificationsRepository.approve(id, sort); + if (emit) eventEmitter.emit(VERIFICATION_EVENTS.approved, { id, analystId }); + return result; +} diff --git a/platforms/garden-roof/src/features/verification/actions/approve-verification/index.ts b/platforms/garden-roof/src/features/verification/actions/approve-verification/index.ts new file mode 100644 index 0000000..d1b0f97 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/actions/approve-verification/index.ts @@ -0,0 +1 @@ +export { approveVerification } from './actions'; diff --git a/platforms/garden-roof/src/features/verification/actions/reject-verification/actions.ts b/platforms/garden-roof/src/features/verification/actions/reject-verification/actions.ts new file mode 100644 index 0000000..ced76e9 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/actions/reject-verification/actions.ts @@ -0,0 +1,27 @@ +import { eventEmitter } from '@lumina/libs/event-emitter'; + +import { VERIFICATION_EVENTS } from '../../constants'; +import { verificationsRepository } from '../../repositories/verifications'; +import type { + DecisionPayload, + RejectVerificationArgs, +} from '../../repositories/verifications'; + +/** + * «رد کردن و اطلاع‌رسانی» (J11-3l): the request moves to رد شده and the analyst gets the reason by + * in-app notice and SMS; the audit log gets a row with it. A resubmission (C3) brings the request + * back to the queue. Emits `verification.rejected`. + */ +export async function rejectVerification( + args: RejectVerificationArgs & { analystId: string }, + { emit = true }: { emit?: boolean } = {}, +): Promise { + const result = await verificationsRepository.reject(args); + if (emit) { + eventEmitter.emit(VERIFICATION_EVENTS.rejected, { + id: args.id, + analystId: args.analystId, + }); + } + return result; +} diff --git a/platforms/garden-roof/src/features/verification/actions/reject-verification/index.ts b/platforms/garden-roof/src/features/verification/actions/reject-verification/index.ts new file mode 100644 index 0000000..2c1d551 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/actions/reject-verification/index.ts @@ -0,0 +1 @@ +export { rejectVerification } from './actions'; diff --git a/platforms/garden-roof/src/features/verification/constants.ts b/platforms/garden-roof/src/features/verification/constants.ts new file mode 100644 index 0000000..825e92c --- /dev/null +++ b/platforms/garden-roof/src/features/verification/constants.ts @@ -0,0 +1,23 @@ +/** Events verification actions emit when they succeed. */ +export const VERIFICATION_EVENTS = { + approved: 'verification.approved', + rejected: 'verification.rejected', +} as const; + +/** + * The reject dialog's ready reasons (J11-3k): each chip fills editable text from + * `verification:reject.templates.`; «سایر» clears the field. + */ +export const REJECT_TEMPLATES = [ + 'mismatch', + 'unreadable', + 'incomplete', +] as const; + +/** The URL's query parameters on the queue and the review page. */ +export const VERIFICATION_PARAMS = { + status: 'status', + q: 'q', + sort: 'sort', + page: 'page', +} as const; diff --git a/platforms/garden-roof/src/features/verification/entities/verification/index.ts b/platforms/garden-roof/src/features/verification/entities/verification/index.ts new file mode 100644 index 0000000..815bbd7 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/entities/verification/index.ts @@ -0,0 +1,8 @@ +export type { + AccountStatus, + PastSubmissionEntity, + QueuePositionEntity, + VerificationDetailEntity, + VerificationListItemEntity, + VerificationStatus, +} from './types'; diff --git a/platforms/garden-roof/src/features/verification/entities/verification/types.ts b/platforms/garden-roof/src/features/verification/entities/verification/types.ts new file mode 100644 index 0000000..b0ec577 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/entities/verification/types.ts @@ -0,0 +1,52 @@ +import type { AuditEntryEntity } from '../../../audit'; + +export type VerificationStatus = 'pending' | 'approved' | 'rejected'; + +/** Independent of verification: a pending request can belong to a suspended account (J11-4). */ +export type AccountStatus = 'active' | 'suspended'; + +/** A row of the queue (`GET /admin/verifications`). */ +export type VerificationListItemEntity = { + id: string; + analystId: string; + firstName: string; + lastName: string; + username: string; + /** E.164. */ + phone: string; + submittedAt: string; + status: VerificationStatus; +}; + +/** + * An earlier submission of the same request, refused before this one (C3 resubmission). The API + * keeps no refusal time for these, and very old rows may lack the submission time. + */ +export type PastSubmissionEntity = { + submittedAt: string | null; + rejectedAt: string | null; + reason: string; +}; + +/** Where a pending request sits in the queue, in the admin's sort («۲ از ۷»). */ +export type QueuePositionEntity = { + position: number; + total: number; + previousId: string | null; + nextId: string | null; +}; + +/** One request (`GET /admin/verifications/:id`). */ +export type VerificationDetailEntity = VerificationListItemEntity & { + accountStatus: AccountStatus; + /** The card's front, through admin-api only (an API path such as `/v1/admin/…/id-images/front`). */ + idImageUrl: string; + /** Both sides of the card (J02-4 asks for both), as API paths. */ + idImages: { front: string; back: string }; + decidedAt: string | null; + rejectionReason: string | null; + submissions: PastSubmissionEntity[]; + audit: AuditEntryEntity[]; + /** Only while pending. */ + queue: QueuePositionEntity | null; +}; diff --git a/platforms/garden-roof/src/features/verification/http.ts b/platforms/garden-roof/src/features/verification/http.ts new file mode 100644 index 0000000..f59030e --- /dev/null +++ b/platforms/garden-roof/src/features/verification/http.ts @@ -0,0 +1,3 @@ +import { http } from '@lumina/libs/http'; + +export const verificationHttp = http.extend({}); diff --git a/platforms/garden-roof/src/features/verification/index.ts b/platforms/garden-roof/src/features/verification/index.ts new file mode 100644 index 0000000..e2ea294 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/index.ts @@ -0,0 +1,45 @@ +import './types'; + +export { approveVerification } from './actions/approve-verification'; +export { rejectVerification } from './actions/reject-verification'; +export { + REJECT_TEMPLATES, + VERIFICATION_EVENTS, + VERIFICATION_PARAMS, +} from './constants'; +export type { + AccountStatus, + VerificationStatus, +} from './entities/verification'; +export { + useVerificationListPart, + useVerificationQueuePage, +} from './models/queue'; +export type { + VerificationListPartModel, + VerificationQueuePageModel, +} from './models/queue'; +export { useVerificationReviewPage } from './models/review'; +export type { + IdImageState, + ReviewDialog, + VerificationReviewPageModel, + VerificationReviewPageOptions, +} from './models/review'; +export { + VERIFICATION_ENDPOINTS, + VERIFICATION_ERROR_CODES, + VERIFICATION_SORTS, + VERIFICATION_TABS, + verificationKeys, + verificationsRepository, +} from './repositories/verifications'; +export type { + DecisionPayload, + ListVerificationsArgs, + RejectVerificationArgs, + VerificationDetailPayload, + VerificationListItemPayload, + VerificationPagePayload, + VerificationSort, +} from './repositories/verifications'; diff --git a/platforms/garden-roof/src/features/verification/models/queue/index.ts b/platforms/garden-roof/src/features/verification/models/queue/index.ts new file mode 100644 index 0000000..b87c11a --- /dev/null +++ b/platforms/garden-roof/src/features/verification/models/queue/index.ts @@ -0,0 +1,6 @@ +export { useVerificationListPart } from './use-verification-list-part'; +export { useVerificationQueuePage } from './use-verification-queue-page'; +export type { + VerificationListPartModel, + VerificationQueuePageModel, +} from './types'; diff --git a/platforms/garden-roof/src/features/verification/models/queue/types.ts b/platforms/garden-roof/src/features/verification/models/queue/types.ts new file mode 100644 index 0000000..656c538 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/models/queue/types.ts @@ -0,0 +1,34 @@ +import type { ListSearch } from '../../../../shared/utils'; +import type { VerificationStatus } from '../../entities/verification'; +import type { + ListVerificationsArgs, + VerificationListItemPayload, + VerificationSort, +} from '../../repositories/verifications'; + +export type VerificationQueuePageModel = { + status: VerificationStatus; + /** Each tab's address; a tab starts again from page 1 and keeps the search and sort. */ + tabHref: (status: VerificationStatus) => string; + search: ListSearch; + sort: VerificationSort; + setSort: (sort: VerificationSort) => void; + /** What the list part reads; a change remounts it behind its skeleton (J11-2). */ + args: ListVerificationsArgs; + /** Changes whenever `args` does: the list part's key. */ + argsKey: string; +}; + +export type VerificationListPartModel = { + rows: VerificationListItemPayload[]; + page: number; + pageCount: number; + total: number; + from: number; + to: number; + pageHref: (page: number) => string; + /** No row: an empty queue, or nothing matched the search. */ + empty: 'queue' | 'search' | null; + /** The search, for highlighting it in the rows. */ + query: string; +}; diff --git a/platforms/garden-roof/src/features/verification/models/queue/use-verification-list-part.ts b/platforms/garden-roof/src/features/verification/models/queue/use-verification-list-part.ts new file mode 100644 index 0000000..80b22e8 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/models/queue/use-verification-list-part.ts @@ -0,0 +1,36 @@ +import { useSuspenseQuery } from '@tanstack/react-query'; +import { usePathname, useSearchParams } from 'next/navigation'; + +import { listHref } from '../../../../shared/utils'; +import { VERIFICATION_PARAMS } from '../../constants'; +import { + verificationKeys, + verificationsRepository, +} from '../../repositories/verifications'; +import type { ListVerificationsArgs } from '../../repositories/verifications'; +import type { VerificationListPartModel } from './types'; + +/** The queue's rows for the tab, search, sort and page; 20 a page. */ +export function useVerificationListPart( + args: ListVerificationsArgs, +): VerificationListPartModel { + const pathname = usePathname(); + const searchParams = useSearchParams(); + const { data } = useSuspenseQuery({ + queryKey: verificationKeys.list(args), + queryFn: ({ signal }) => verificationsRepository.list(args, { signal }), + }); + + return { + rows: data.items, + page: data.page, + pageCount: data.pageCount, + total: data.total, + from: data.from, + to: data.to, + pageHref: (page) => + listHref(pathname, searchParams, { [VERIFICATION_PARAMS.page]: page }), + empty: data.total > 0 ? null : args.q ? 'search' : 'queue', + query: args.q ?? '', + }; +} diff --git a/platforms/garden-roof/src/features/verification/models/queue/use-verification-queue-page.ts b/platforms/garden-roof/src/features/verification/models/queue/use-verification-queue-page.ts new file mode 100644 index 0000000..4234531 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/models/queue/use-verification-queue-page.ts @@ -0,0 +1,64 @@ +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; + +import { + listHref, + oneOf, + pageOf, + useListSearch, +} from '../../../../shared/utils'; +import { VERIFICATION_PARAMS } from '../../constants'; +import type { VerificationStatus } from '../../entities/verification'; +import { + VERIFICATION_SORTS, + VERIFICATION_TABS, +} from '../../repositories/verifications'; +import type { VerificationSort } from '../../repositories/verifications'; +import type { VerificationQueuePageModel } from './types'; + +/** + * احراز هویت تحلیلگران (J11-2): the tab (در انتظار بررسی by default), the search and the sort + * (oldest first) live in the URL, so a reload or back keeps them. Search and sort work within the + * tab; every change starts again from page 1. + */ +export function useVerificationQueuePage(): VerificationQueuePageModel { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const search = useListSearch(VERIFICATION_PARAMS.q); + const status = oneOf( + searchParams.get(VERIFICATION_PARAMS.status), + VERIFICATION_TABS, + ); + const sort = oneOf( + searchParams.get(VERIFICATION_PARAMS.sort), + VERIFICATION_SORTS, + ); + const page = pageOf(searchParams.get(VERIFICATION_PARAMS.page)); + + const tabHref = (next: VerificationStatus) => + listHref(pathname, searchParams, { + [VERIFICATION_PARAMS.status]: next === 'pending' ? null : next, + }); + + const setSort = (next: VerificationSort) => { + if (next === sort) return; + router.replace( + listHref(pathname, searchParams, { + [VERIFICATION_PARAMS.sort]: next === 'asc' ? null : next, + }), + { scroll: false }, + ); + }; + + const args = { status, q: search.query || undefined, sort, page }; + + return { + status, + tabHref, + search, + sort, + setSort, + args, + argsKey: JSON.stringify(args), + }; +} diff --git a/platforms/garden-roof/src/features/verification/models/review/index.ts b/platforms/garden-roof/src/features/verification/models/review/index.ts new file mode 100644 index 0000000..3618903 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/models/review/index.ts @@ -0,0 +1,7 @@ +export { useVerificationReviewPage } from './use-verification-review-page'; +export type { + IdImageState, + ReviewDialog, + VerificationReviewPageModel, + VerificationReviewPageOptions, +} from './types'; diff --git a/platforms/garden-roof/src/features/verification/models/review/types.ts b/platforms/garden-roof/src/features/verification/models/review/types.ts new file mode 100644 index 0000000..c681494 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/models/review/types.ts @@ -0,0 +1,46 @@ +import type { ReasonForm } from '../../../../shared/utils'; +import type { + VerificationDetailPayload, + VerificationSort, +} from '../../repositories/verifications'; + +/** The ID image: loading until it shows; a failed load offers its own retry (J11-3). */ +export type IdImageState = 'loading' | 'loaded' | 'failed'; + +/** Which decision dialog is open. */ +export type ReviewDialog = 'approve' | 'reject' | null; + +export type VerificationReviewPageModel = { + request: VerificationDetailPayload; + sort: VerificationSort; + /** Only a pending request can be decided. */ + isPending: boolean; + imageState: IdImageState; + /** The card's front, shown in the page; a retry asks for it afresh. */ + imageSrc: string; + /** The card's back, shown beside the front in the lightbox. */ + backImageSrc: string; + onImageLoad: () => void; + onImageError: () => void; + retryImage: () => void; + isLightboxOpen: boolean; + openLightbox: () => void; + closeLightbox: () => void; + /** The decisions wait for the image (J11-3: «until the image loads … frozen»). */ + areActionsFrozen: boolean; + dialog: ReviewDialog; + openApprove: () => void; + openReject: () => void; + closeDialog: () => void; + confirmApprove: () => void; + isApproving: boolean; + rejectForm: ReasonForm; + confirmReject: (reason: string) => void; + isRejecting: boolean; +}; + +export type VerificationReviewPageOptions = { + id: string; + /** After a decision: the next pending request in place, or the queue when none is left. */ + onDecided: (nextId: string | null, sort: VerificationSort) => void; +}; diff --git a/platforms/garden-roof/src/features/verification/models/review/use-verification-review-page.ts b/platforms/garden-roof/src/features/verification/models/review/use-verification-review-page.ts new file mode 100644 index 0000000..f26597e --- /dev/null +++ b/platforms/garden-roof/src/features/verification/models/review/use-verification-review-page.ts @@ -0,0 +1,175 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { isHttpError } from '@lumina/libs/http'; +import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'; +import { useSearchParams } from 'next/navigation'; +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; + +import { + oneOf, + showActionError, + useReasonForm, +} from '../../../../shared/utils'; +import { panelKeys } from '../../../panel'; +import { approveVerification } from '../../actions/approve-verification'; +import { rejectVerification } from '../../actions/reject-verification'; +import { VERIFICATION_PARAMS } from '../../constants'; +import { + VERIFICATION_ERROR_CODES, + VERIFICATION_SORTS, + verificationKeys, + verificationsRepository, +} from '../../repositories/verifications'; +import type { + IdImageState, + ReviewDialog, + VerificationReviewPageModel, + VerificationReviewPageOptions, +} from './types'; + +/** + * بررسی درخواست احراز هویت (J11-3): one request, «۲ از ۷» in the queue's sort, the ID image with + * its lightbox, and the two decisions. The decisions wait for the image; a failed image offers + * its retry and leaves them live. A decision toasts, then the next pending request loads in place + * and the sidebar count drops; after the last, back to the queue. A failed decision keeps the + * dialog with its text, and confirm retries; one decided elsewhere (409) reloads the request. + */ +export function useVerificationReviewPage({ + id, + onDecided, +}: VerificationReviewPageOptions): VerificationReviewPageModel { + const { t } = useTranslation('verification'); + const queryClient = useQueryClient(); + const searchParams = useSearchParams(); + const sort = oneOf( + searchParams.get(VERIFICATION_PARAMS.sort), + VERIFICATION_SORTS, + ); + const { data: request } = useSuspenseQuery({ + queryKey: verificationKeys.detail(id, sort), + queryFn: ({ signal }) => + verificationsRepository.get({ id, sort }, { signal }), + }); + // The image belongs to the request shown: a new request starts loading again. + const [image, setImage] = useState<{ + id: string; + state: IdImageState; + attempt: number; + }>({ id, state: 'loading', attempt: 0 }); + if (image.id !== id) setImage({ id, state: 'loading', attempt: 0 }); + const [isLightboxOpen, setIsLightboxOpen] = useState(false); + const [dialog, setDialog] = useState(null); + const [isApproving, setIsApproving] = useState(false); + const [isRejecting, setIsRejecting] = useState(false); + const rejectForm = useReasonForm(); + + // A retry asks for the scans afresh, past any failed response the browser kept. + const withAttempt = (src: string) => + image.attempt === 0 + ? src + : `${src}${src.includes('?') ? '&' : '?'}retry=${image.attempt}`; + const imageSrc = withAttempt(request.idImages.front); + const backImageSrc = withAttempt(request.idImages.back); + + const settle = async (nextId: string | null) => { + setDialog(null); + await Promise.all([ + queryClient.invalidateQueries({ queryKey: verificationKeys.all }), + queryClient.invalidateQueries({ queryKey: panelKeys.counts() }), + ]); + onDecided(nextId, sort); + }; + + const refused = async (error: unknown): Promise => { + if ( + !isHttpError(error) || + error.code !== VERIFICATION_ERROR_CODES.alreadyDecided + ) { + return false; + } + setDialog(null); + showToast({ tone: 'info', message: t('review.already-decided') }); + await queryClient.invalidateQueries({ queryKey: verificationKeys.all }); + return true; + }; + + const confirmApprove = async () => { + if (isApproving) return; + setIsApproving(true); + try { + const { nextId } = await approveVerification({ + id, + analystId: request.analystId, + sort, + }); + showToast({ tone: 'success', message: t('approve.done') }); + await settle(nextId); + } catch (error) { + if (!(await refused(error))) { + showActionError(error, { + t, + failedMessage: t('approve.failed'), + retry: () => void confirmApprove(), + }); + } + } finally { + setIsApproving(false); + } + }; + + const confirmReject = async (reason: string) => { + if (isRejecting) return; + setIsRejecting(true); + try { + const { nextId } = await rejectVerification({ + id, + analystId: request.analystId, + reason, + sort, + }); + showToast({ tone: 'success', message: t('reject.done') }); + await settle(nextId); + } catch (error) { + if (!(await refused(error))) { + showActionError(error, { + t, + failedMessage: t('reject.failed'), + retry: () => void confirmReject(reason), + }); + } + } finally { + setIsRejecting(false); + } + }; + + return { + request, + sort, + isPending: request.status === 'pending', + imageState: image.state, + imageSrc, + backImageSrc, + onImageLoad: () => setImage((current) => ({ ...current, state: 'loaded' })), + onImageError: () => + setImage((current) => ({ ...current, state: 'failed' })), + retryImage: () => + setImage((current) => ({ + id, + state: 'loading', + attempt: current.attempt + 1, + })), + isLightboxOpen, + openLightbox: () => setIsLightboxOpen(true), + closeLightbox: () => setIsLightboxOpen(false), + areActionsFrozen: image.state === 'loading', + dialog, + openApprove: () => setDialog('approve'), + openReject: () => setDialog('reject'), + closeDialog: () => setDialog(null), + confirmApprove: () => void confirmApprove(), + isApproving, + rejectForm, + confirmReject: (reason) => void confirmReject(reason), + isRejecting, + }; +} diff --git a/platforms/garden-roof/src/features/verification/repositories/verifications/constants.ts b/platforms/garden-roof/src/features/verification/repositories/verifications/constants.ts new file mode 100644 index 0000000..14ffd07 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/repositories/verifications/constants.ts @@ -0,0 +1,44 @@ +import type { VerificationSort } from './types'; +import type { VerificationStatus } from '../../entities/verification'; + +export const VERIFICATION_ENDPOINTS = { + list: '/admin/verifications', + detail: (id: string) => `/admin/verifications/${encodeURIComponent(id)}`, + approve: (id: string) => + `/admin/verifications/${encodeURIComponent(id)}/approve`, + reject: (id: string) => + `/admin/verifications/${encodeURIComponent(id)}/reject`, +} as const; + +/** The queue's tabs in display order: در انتظار بررسی · تأییدشده · رد شده. */ +export const VERIFICATION_TABS = [ + 'pending', + 'approved', + 'rejected', +] as const satisfies readonly VerificationStatus[]; + +/** Oldest first by default (J11-2). */ +export const VERIFICATION_SORTS = [ + 'asc', + 'desc', +] as const satisfies readonly VerificationSort[]; + +/** The codes the API marks verification failures with; branch on these, never on the message. */ +export const VERIFICATION_ERROR_CODES = { + /** 409: someone decided this request in the meantime (`details.verificationStatus`). */ + alreadyDecided: 'VERIFICATION_NOT_PENDING', +} as const; + +export const verificationKeys = { + all: ['verification'] as const, + lists: () => [...verificationKeys.all, 'list'] as const, + list: (args: { + status: VerificationStatus; + q?: string; + sort: VerificationSort; + page: number; + }) => [...verificationKeys.lists(), args] as const, + details: () => [...verificationKeys.all, 'detail'] as const, + detail: (id: string, sort: VerificationSort) => + [...verificationKeys.details(), id, sort] as const, +}; diff --git a/platforms/garden-roof/src/features/verification/repositories/verifications/index.ts b/platforms/garden-roof/src/features/verification/repositories/verifications/index.ts new file mode 100644 index 0000000..1106a61 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/repositories/verifications/index.ts @@ -0,0 +1,18 @@ +export { + VERIFICATION_ENDPOINTS, + VERIFICATION_ERROR_CODES, + VERIFICATION_SORTS, + VERIFICATION_TABS, + verificationKeys, +} from './constants'; +export { verificationsRepository } from './verifications'; +export type { + DecisionPayload, + GetVerificationArgs, + ListVerificationsArgs, + RejectVerificationArgs, + VerificationDetailPayload, + VerificationListItemPayload, + VerificationPagePayload, + VerificationSort, +} from './types'; diff --git a/platforms/garden-roof/src/features/verification/repositories/verifications/mappers.ts b/platforms/garden-roof/src/features/verification/repositories/verifications/mappers.ts new file mode 100644 index 0000000..f2a4e45 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/repositories/verifications/mappers.ts @@ -0,0 +1,81 @@ +import { toApiUrl } from '../../../../shared/utils'; +import { toAuditEntryPayload } from '../../../audit'; +import type { VerificationListItemEntity } from '../../entities/verification'; +import type { + ListVerificationsArgs, + ListVerificationsQueryDto, + RejectVerificationArgs, + RejectVerificationDto, + VerificationDetailPayload, + VerificationDetailResponseDto, + VerificationListItemPayload, + VerificationPagePayload, + VerificationPageResponseDto, +} from './types'; + +export function toListVerificationsQueryDto( + args: ListVerificationsArgs, +): ListVerificationsQueryDto { + return { + status: args.status, + q: args.q?.trim() || undefined, + sort: `submittedAt:${args.sort}`, + page: args.page, + }; +} + +function toListItemPayload( + dto: VerificationListItemEntity, +): VerificationListItemPayload { + return { + id: dto.id, + fullName: `${dto.firstName} ${dto.lastName}`, + username: dto.username, + phone: dto.phone, + submittedAt: dto.submittedAt, + status: dto.status, + }; +} + +export function toVerificationPagePayload( + dto: VerificationPageResponseDto, +): VerificationPagePayload { + const from = dto.total === 0 ? 0 : (dto.page - 1) * dto.pageSize + 1; + return { + items: dto.items.map(toListItemPayload), + page: dto.page, + pageCount: Math.max(1, Math.ceil(dto.total / dto.pageSize)), + total: dto.total, + from, + to: from === 0 ? 0 : from + dto.items.length - 1, + }; +} + +export function toVerificationDetailPayload( + dto: VerificationDetailResponseDto, +): VerificationDetailPayload { + return { + id: dto.id, + analystId: dto.analystId, + fullName: `${dto.firstName} ${dto.lastName}`, + username: dto.username, + phone: dto.phone, + submittedAt: dto.submittedAt, + status: dto.status, + accountStatus: dto.accountStatus, + idImages: { + front: toApiUrl(dto.idImages.front) ?? '', + back: toApiUrl(dto.idImages.back) ?? '', + }, + rejectionReason: dto.rejectionReason, + pastSubmissions: dto.submissions.map((submission) => ({ ...submission })), + audit: dto.audit.map(toAuditEntryPayload), + queue: dto.queue ? { ...dto.queue } : null, + }; +} + +export function toRejectVerificationDto( + args: RejectVerificationArgs, +): RejectVerificationDto { + return { reason: args.reason.trim() }; +} diff --git a/platforms/garden-roof/src/features/verification/repositories/verifications/types.ts b/platforms/garden-roof/src/features/verification/repositories/verifications/types.ts new file mode 100644 index 0000000..944c9a3 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/repositories/verifications/types.ts @@ -0,0 +1,98 @@ +import type { AuditEntryPayload } from '../../../audit'; +import type { + AccountStatus, + VerificationDetailEntity, + VerificationListItemEntity, + VerificationStatus, +} from '../../entities/verification'; + +export type VerificationSort = 'asc' | 'desc'; + +// GET /admin/verifications?status=&q=&sort=submittedAt:asc|desc&page= + +export type ListVerificationsArgs = { + status: VerificationStatus; + /** First, last or full name, username or phone. */ + q?: string; + /** By submission time; the queue starts oldest first. */ + sort: VerificationSort; + page: number; +}; + +export type ListVerificationsQueryDto = { + status: VerificationStatus; + q?: string; + sort: `submittedAt:${VerificationSort}`; + page: number; +}; + +export type VerificationPageResponseDto = { + items: VerificationListItemEntity[]; + page: number; + pageSize: number; + total: number; +}; + +export type VerificationListItemPayload = { + id: string; + fullName: string; + username: string; + phone: string; + submittedAt: string; + status: VerificationStatus; +}; + +export type VerificationPagePayload = { + items: VerificationListItemPayload[]; + page: number; + pageCount: number; + total: number; + /** The first and last row's place among all rows, for «نمایش ۱ تا ۲۰ از ۴۷». */ + from: number; + to: number; +}; + +// GET /admin/verifications/:id?sort= + +export type GetVerificationArgs = { id: string; sort: VerificationSort }; + +export type VerificationDetailResponseDto = VerificationDetailEntity; + +export type VerificationDetailPayload = { + id: string; + analystId: string; + fullName: string; + username: string; + phone: string; + submittedAt: string; + status: VerificationStatus; + accountStatus: AccountStatus; + /** The card's sides as the browser loads them (through the panel's `/api` proxy). */ + idImages: { front: string; back: string }; + rejectionReason: string | null; + pastSubmissions: { + submittedAt: string | null; + rejectedAt: string | null; + reason: string; + }[]; + audit: AuditEntryPayload[]; + queue: { + position: number; + total: number; + previousId: string | null; + nextId: string | null; + } | null; +}; + +// POST /admin/verifications/:id/approve · POST /admin/verifications/:id/reject { reason } + +export type RejectVerificationArgs = { + id: string; + reason: string; + sort: VerificationSort; +}; +export type RejectVerificationDto = { reason: string }; + +/** The pending request to show next in the same sort, or `null` when the queue is empty. */ +export type DecisionResponseDto = { nextId: string | null }; +export type DecisionPayload = { nextId: string | null }; diff --git a/platforms/garden-roof/src/features/verification/repositories/verifications/verifications.ts b/platforms/garden-roof/src/features/verification/repositories/verifications/verifications.ts new file mode 100644 index 0000000..521130e --- /dev/null +++ b/platforms/garden-roof/src/features/verification/repositories/verifications/verifications.ts @@ -0,0 +1,70 @@ +import { verificationHttp } from '../../http'; +import { VERIFICATION_ENDPOINTS } from './constants'; +import { + toListVerificationsQueryDto, + toRejectVerificationDto, + toVerificationDetailPayload, + toVerificationPagePayload, +} from './mappers'; +import type { + DecisionPayload, + DecisionResponseDto, + GetVerificationArgs, + ListVerificationsArgs, + RejectVerificationArgs, + VerificationDetailPayload, + VerificationDetailResponseDto, + VerificationPagePayload, + VerificationPageResponseDto, + VerificationSort, +} from './types'; + +/** The queue's sort travels with a read or a decision, so «قبلی / بعدی» walk the same order. */ +const sortParam = (sort: VerificationSort) => ({ sort: `submittedAt:${sort}` }); + +/** Analysts' identity requests (J11-2, J11-3): the queue, one request, and the two decisions. */ +export const verificationsRepository = { + /** 20 a page, in the tab's status, searched and sorted by submission time. */ + async list( + args: ListVerificationsArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await verificationHttp.get( + VERIFICATION_ENDPOINTS.list, + { params: toListVerificationsQueryDto(args), signal }, + ); + return toVerificationPagePayload(response); + }, + + /** One request, with its place in the pending queue in the admin's sort. */ + async get( + { id, sort }: GetVerificationArgs, + { signal }: { signal?: AbortSignal } = {}, + ): Promise { + const response = await verificationHttp.get( + VERIFICATION_ENDPOINTS.detail(id), + { params: sortParam(sort), signal }, + ); + return toVerificationDetailPayload(response); + }, + + /** Verifies the analyst: in-app and SMS notice, and their invite code is made. */ + async approve(id: string, sort: VerificationSort): Promise { + const response = await verificationHttp.post( + VERIFICATION_ENDPOINTS.approve(id), + undefined, + { params: sortParam(sort) }, + ); + return { nextId: response.nextId }; + }, + + /** Refuses the request with a reason the analyst gets by in-app notice and SMS. */ + async reject(args: RejectVerificationArgs): Promise { + const response = await verificationHttp.post( + VERIFICATION_ENDPOINTS.reject(args.id), + toRejectVerificationDto(args), + { params: sortParam(args.sort) }, + ); + return { nextId: response.nextId }; + }, +}; diff --git a/platforms/garden-roof/src/features/verification/types.ts b/platforms/garden-roof/src/features/verification/types.ts new file mode 100644 index 0000000..e971b36 --- /dev/null +++ b/platforms/garden-roof/src/features/verification/types.ts @@ -0,0 +1,8 @@ +declare module '@lumina/libs/event-emitter' { + interface EventMap { + 'verification.approved': { id: string; analystId: string }; + 'verification.rejected': { id: string; analystId: string }; + } +} + +export {}; diff --git a/platforms/garden-roof/src/index.ts b/platforms/garden-roof/src/index.ts new file mode 100644 index 0000000..cf48a9f --- /dev/null +++ b/platforms/garden-roof/src/index.ts @@ -0,0 +1,424 @@ +// Public client-safe API. Re-export each module by name; never `export *`. Apps import by subpath +// (`@lumina/garden-roof/features/verification`); this root lists the same symbols. +export { AppShell } from './app/app-shell'; +export type { AppShellProps } from './app/app-shell'; +export { + AppCrash, + ErrorFallback, + PartBoundary, + StatusEmptyState, +} from './app/error-boundaries'; +export type { + AppCrashProps, + ErrorFallbackProps, + ErrorFallbackSize, + FallbackKind, + PartBoundaryProps, + StatusEmptyStateProps, + StatusVariant, +} from './app/error-boundaries'; +export { AdminGuard, GuestGuard } from './app/guards'; +export type { AdminGuardProps, GuestGuardProps } from './app/guards'; +export { mapApiErrorBody } from './app/http'; +export type { ApiErrorEnvelope } from './app/http'; +export { + AdminSidebar, + AdminTopBar, + HOME_ROUTE, + loginRoute, + RETURN_TO_PARAM, + ROUTES, + safeReturnPath, + SECTION_ROUTES, + sectionOf, + useActiveSection, +} from './app/navigation'; +export type { + AdminSection, + AdminSidebarProps, + AdminTopBarProps, +} from './app/navigation'; +export { AuditLog, ReasonDialog } from './app/screens'; +export type { + AuditLogProps, + ReasonDialogProps, + ReasonTemplate, +} from './app/screens'; +export { getEnv, setEnv } from './env'; +export type { GardenRoofEnv } from './env'; +export { + AUTH_ENDPOINTS, + AUTH_ERROR_CODES, + AUTH_EVENTS, + login, + logout, + restoreSession, + sendCode, + useLoginPage, +} from './features/auth'; +export type { AdminPayload, LoginPageModel } from './features/auth'; +export { toAuditEntryPayload } from './features/audit'; +export type { AuditAction, AuditEntryPayload } from './features/audit'; +export { panelKeys, usePanelCounts } from './features/panel'; +export type { PanelCountsPayload } from './features/panel'; +export { useAuthStore, useCurrentAdmin, useViewerStatus } from './stores/auth'; +export type { ViewerStatus } from './stores/auth'; +export { BILLING_PERIODS } from './shared/constants'; +export type { BillingPeriod } from './shared/constants'; +export { + approveVerification, + REJECT_TEMPLATES, + rejectVerification, + useVerificationListPart, + useVerificationQueuePage, + useVerificationReviewPage, + VERIFICATION_ENDPOINTS, + VERIFICATION_ERROR_CODES, + VERIFICATION_EVENTS, + VERIFICATION_PARAMS, + VERIFICATION_SORTS, + VERIFICATION_TABS, + verificationKeys, + verificationsRepository, +} from './features/verification'; +export type { + AccountStatus, + DecisionPayload, + IdImageState, + ListVerificationsArgs, + RejectVerificationArgs, + ReviewDialog, + VerificationDetailPayload, + VerificationListItemPayload, + VerificationListPartModel, + VerificationPagePayload, + VerificationQueuePageModel, + VerificationReviewPageModel, + VerificationReviewPageOptions, + VerificationSort, + VerificationStatus, +} from './features/verification'; +export { + ANALYST_ENDPOINTS, + ANALYST_ERROR_CODES, + ANALYST_EVENTS, + ANALYST_PARAMS, + analystKeys, + analystsRepository, + reinstateAnalyst, + SUSPEND_TEMPLATES, + suspendAnalyst, + useAnalystAccount, + useAnalystDetailPage, + useAnalystListPart, + useAnalystsPage, +} from './features/analysts'; +export type { + AccountDialog, + AccountTarget, + AnalystAccountModel, + AnalystDetailEntity, + AnalystDetailPageModel, + AnalystDetailPayload, + AnalystListItemEntity, + AnalystListItemPayload, + AnalystListPartModel, + AnalystPagePayload, + AnalystsPageModel, + ListAnalystsArgs, + ReinstateAnalystArgs, + ReinstatePayload, + SuspendAnalystArgs, + SuspendPayload, +} from './features/analysts'; +export { + activateInviteCode, + approveCapacityRequest, + changeCapacity, + CODE_MAX_USES, + deactivateInviteCode, + INVITE_CODE_ENDPOINTS, + INVITE_CODE_ERROR_CODES, + INVITE_CODE_EVENTS, + INVITE_CODE_PARAMS, + inviteCodeKeys, + inviteCodesRepository, + rejectCapacityRequest, + useCapacityRequestListPart, + useCapacityRequestsPage, + useCodeActions, + useInviteCodeDetailPart, + useInviteCodeListPart, + useInviteCodesPage, + useInviteCodesSearch, + useInviteCodesTabs, +} from './features/invite-codes'; +export type { + ApproveCapacityRequestArgs, + CapacityForm, + CapacityNotice, + CapacityPayload, + CapacityRequestListPartModel, + CapacityRequestPagePayload, + CapacityRequestPayload, + CapacityRequestsPageModel, + CapacityRequestStatus, + ChangeCapacityArgs, + CodeActionsModel, + CodeDialog, + CodeStatusPayload, + InviteCodeDetailPartModel, + InviteCodeDetailPayload, + InviteCodeListItemPayload, + InviteCodeListPartModel, + InviteCodePagePayload, + InviteCodesPageModel, + InviteCodesTab, + InviteCodesTabsModel, + InviteCodesTabsOptions, + InviteCodeStatus, + InviteCodeSummaryPayload, + ListCapacityRequestsArgs, + ListInviteCodesArgs, + PendingCapacityRequestPayload, + ReasonArgs, +} from './features/invite-codes'; +export { + EXTEND_DAYS, + extendSubscription, + GRANT_REASONS, + grantAccess, + LOOKUP_DELAY_MS, + PERIOD_MONTHS, + refundSubscription, + SUBSCRIPTION_ENDPOINTS, + SUBSCRIPTION_ERROR_CODES, + SUBSCRIPTION_EVENTS, + SUBSCRIPTION_FILTERS, + SUBSCRIPTION_PARAMS, + SUBSCRIPTION_STATUS_FILTERS, + subscriptionKeys, + subscriptionsRepository, + useGrantAccessDialog, + useSubscriptionDetailPart, + useSubscriptionListPart, + useSubscriptionsPage, + useSubscriptionsToolbar, +} from './features/subscriptions'; +export type { + ExtendForm, + ExtendSubscriptionArgs, + GrantAccessArgs, + GrantAccessDialogModel, + GrantAccessDialogOptions, + GrantForm, + GrantPayload, + ListSubscriptionsArgs, + LookupPersonArgs, + PersonLookup, + PersonRefPayload, + PersonRole, + RefundForm, + RefundSubscriptionArgs, + SubscriptionDetailPartModel, + SubscriptionDetailPayload, + SubscriptionDialog, + SubscriptionFilter, + SubscriptionListItemPayload, + SubscriptionListPartModel, + SubscriptionPagePayload, + SubscriptionSource, + SubscriptionsPageModel, + SubscriptionStatus, + SubscriptionStatusFilter, + SubscriptionsToolbarModel, +} from './features/subscriptions'; +export { + correctPriceSchema, + dismissProposal, + FLAG_REASONS, + flagPrediction, + flagSchema, + outcomeOf, + overridePrediction, + overrideSchema, + parsePriceInput, + PREDICTION_ENDPOINTS, + PREDICTION_ERROR_CODES, + PREDICTION_EVENTS, + PREDICTION_PARAMS, + PREDICTION_QUEUES, + predictionKeys, + predictionsRepository, + QUOTE_HEALTH_REFRESH_MS, + QUOTE_SOURCE_ENDPOINTS, + quoteSourceKeys, + quoteSourcesRepository, + resolvePrediction, + roiOf, + unflagPrediction, + usePredictionActions, + usePredictionDetailPart, + usePredictionListPart, + usePredictionsPage, + useQuoteHealthPart, + winRateAfter, +} from './features/predictions'; +export type { + CloseReason, + CloseTrigger, + CorrectPriceForm, + CorrectPriceFormOutput, + CorrectPriceFormValues, + DismissProposalArgs, + FlagForm, + FlagFormOutput, + FlagFormValues, + FlagPredictionArgs, + FlagReason, + ListPredictionsArgs, + OverrideForm, + OverrideFormOutput, + OverrideFormValues, + OverridePredictionArgs, + PendingClosePayload, + PredictionActionsModel, + PredictionDetailPartModel, + PredictionDetailPayload, + PredictionDialog, + PredictionDirection, + PredictionEventPayload, + PredictionListPartModel, + PredictionMarket, + PredictionOutcome, + PredictionPagePayload, + PredictionPayload, + PredictionQueue, + PredictionsPageModel, + PredictionStatus, + QuoteHealthPartModel, + QuoteHealthPayload, + QuoteSourceId, + QuoteSourcePayload, + ResolvePredictionArgs, +} from './features/predictions'; +export { + BANK_REFERENCE_PATTERN, + cancelPayout, + createPayout, + markPaidSchema, + markPayoutPaid, + PAYOUT_ENDPOINTS, + PAYOUT_ERROR_CODES, + PAYOUT_EVENTS, + PAYOUT_PARAMS, + PAYOUT_TABS, + payoutKeys, + payoutsRepository, + RECEIPT_FILE, + usePayoutDetailPart, + usePayoutListPart, + usePayoutsPage, + usePayoutsSearch, + useReadyPayoutsPart, +} from './features/payouts'; +export type { + CancelPayoutArgs, + CreatePayoutArgs, + LedgerLinePayload, + ListPayoutsArgs, + ListReadyPayoutsArgs, + MarkPaidForm, + MarkPaidFormOutput, + MarkPaidFormValues, + MarkPayoutPaidArgs, + PayoutActionPayload, + PayoutDetailPartModel, + PayoutDetailPayload, + PayoutDialog, + PayoutDialogKind, + PayoutDialogsModel, + PayoutListArgs, + PayoutListItemPayload, + PayoutListPartModel, + PayoutPagePayload, + PayoutsPageModel, + PayoutsSearchModel, + PayoutStatus, + PayoutTab, + ReadyPayoutPagePayload, + ReadyPayoutPayload, + ReadyPayoutsPartModel, +} from './features/payouts'; +export { + addFeatured, + FEATURED_ENDPOINTS, + FEATURED_ERROR_CODES, + FEATURED_EVENTS, + FEATURED_PARAMS, + featuredKeys, + featuredRepository, + LANDING_MIN_VISIBLE, + PREVIEW_COUNT, + removeFeatured, + reorderFeatured, + useAddFeaturedDialog, + useFeaturedCandidatesPart, + useFeaturedPage, +} from './features/featured'; +export type { + AddFeaturedDialogModel, + AddFeaturedDialogOptions, + CandidatesPayload, + FeaturedAccountStatus, + FeaturedAnalystPayload, + FeaturedCandidatePayload, + FeaturedCandidatesPartModel, + FeaturedIneligibility, + FeaturedMarket, + FeaturedPageModel, + FeaturedPayload, + FeaturedRemoval, + FeaturedReorderModel, + FeaturedRowModel, + GripProps, + ListCandidatesArgs, + ReorderAnnouncement, + ReorderState, + SaveFeaturedArgs, +} from './features/featured'; +export { + betaHealthRepository, + HEALTH_ENDPOINTS, + HEALTH_REFRESH_MS, + HEALTH_TABS, + healthKeys, + useBetaAnalystsPart, + useBetaHeader, + useBetaHealthPage, + useExitMetricsPart, + useFunnelPart, + useSecondaryMetricsPart, +} from './features/health'; +export type { + AnalystFunnelEvent, + BetaAnalystPayload, + BetaAnalystsPayload, + BetaHeaderModel, + BetaHealthPageModel, + BetaInactiveReason, + BetaOverviewPayload, + BetaPhase, + ExitMetricKey, + ExitMetricPayload, + ExitMetricsPayload, + ExitMetricStatus, + FunnelEvent, + FunnelJourney, + FunnelPayload, + FunnelStepPayload, + HealthTab, + InvestorFunnelEvent, + RatePayload, + SecondaryMetricsPayload, +} from './features/health'; diff --git a/platforms/garden-roof/src/server.ts b/platforms/garden-roof/src/server.ts new file mode 100644 index 0000000..5801611 --- /dev/null +++ b/platforms/garden-roof/src/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +// Public server-only API, exposed as the `/server` subpath. index.ts never imports this file. +// The admin app reads nothing on the server (0062), so there is nothing here yet. diff --git a/platforms/garden-roof/src/shared/constants/billing.ts b/platforms/garden-roof/src/shared/constants/billing.ts new file mode 100644 index 0000000..bacb245 --- /dev/null +++ b/platforms/garden-roof/src/shared/constants/billing.ts @@ -0,0 +1,9 @@ +/** A subscription tier's period, as every service names it. */ +export const BILLING_PERIODS = [ + 'monthly', + 'quarterly', + 'semi_annual', + 'yearly', +] as const; + +export type BillingPeriod = (typeof BILLING_PERIODS)[number]; diff --git a/platforms/garden-roof/src/shared/constants/index.ts b/platforms/garden-roof/src/shared/constants/index.ts new file mode 100644 index 0000000..e2f3c63 --- /dev/null +++ b/platforms/garden-roof/src/shared/constants/index.ts @@ -0,0 +1,3 @@ +export { BILLING_PERIODS } from './billing'; +export type { BillingPeriod } from './billing'; +export { PAGE_SIZE, SEARCH_DELAY_MS } from './list'; diff --git a/platforms/garden-roof/src/shared/constants/list.ts b/platforms/garden-roof/src/shared/constants/list.ts new file mode 100644 index 0000000..ddecd63 --- /dev/null +++ b/platforms/garden-roof/src/shared/constants/list.ts @@ -0,0 +1,5 @@ +/** Rows per page in every admin table (J11-2: 20/page). */ +export const PAGE_SIZE = 20; + +/** How long typing must pause before a list's search reaches the URL. */ +export const SEARCH_DELAY_MS = 300; diff --git a/platforms/garden-roof/src/shared/locales/fa/analysts.json b/platforms/garden-roof/src/shared/locales/fa/analysts.json new file mode 100644 index 0000000..6def9e3 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/analysts.json @@ -0,0 +1,99 @@ +{ + "list": { + "title": "مدیریت تحلیلگران", + "meta-title": "مدیریت تحلیلگران", + "search": "جستجو بر اساس نام، نام کاربری یا شماره موبایل", + "table-label": "همه تحلیلگران", + "columns": { + "analyst": "تحلیلگر", + "username": "نام کاربری", + "verification": "وضعیت احراز هویت", + "account": "وضعیت حساب", + "subscribers": "مشترک فعال", + "actions": "عملیات" + }, + "open-row": "باز کردن صفحه {{name}}", + "subscribers": "مشترک فعال: {{subscribers}}", + "loading": "در حال بارگذاری تحلیلگران…", + "error": "فهرست تحلیلگران بارگذاری نشد.", + "empty": { + "list": { + "title": "هنوز تحلیلگری ثبت‌نام نکرده است", + "description": "تحلیلگران پس از ثبت‌نام اینجا نمایش داده می‌شوند." + }, + "search": { + "title": "نتیجه‌ای پیدا نشد", + "description": "نام، نام کاربری یا شماره دیگری را جستجو کنید.", + "clear": "پاک کردن جستجو" + } + } + }, + "detail": { + "title": "جزئیات تحلیلگر", + "meta-title": "جزئیات تحلیلگر", + "back": "بازگشت به مدیریت تحلیلگران", + "loading": "در حال بارگذاری اطلاعات تحلیلگر…", + "error": "اطلاعات تحلیلگر بارگذاری نشد.", + "fields": { + "name": "نام و نام خانوادگی", + "username": "نام کاربری", + "phone": "شماره موبایل", + "verification": "وضعیت احراز هویت", + "account": "وضعیت حساب", + "subscribers": "مشترک فعال" + } + }, + "account": { + "suspend": "تعلیق حساب", + "reinstate": "رفع تعلیق", + "suspend-of": "تعلیق حساب {{name}}", + "reinstate-of": "رفع تعلیق حساب {{name}}", + "changed": "وضعیت این حساب در این فاصله تغییر کرده است؛ اطلاعات به‌روز شد." + }, + "suspend": { + "title": "تعلیق حساب تحلیلگر", + "impact": "این تحلیلگر در حال حاضر {{subscribers}} مشترک فعال دارد. با تعلیق حساب، دسترسی آن‌ها قطع می‌شود و گزینه‌های بازگشت وجه یا تمدید اشتراک به آن‌ها اطلاع داده خواهد شد.", + "impact-none": "این تحلیلگر در حال حاضر مشترک فعالی ندارد.", + "field": "دلیل تعلیق", + "placeholder": "دلیل تعلیق را بنویسید یا از پیش‌فرض‌های زیر انتخاب کنید...", + "hint": "حداقل ۱۰ نویسه؛ تحلیلگر آن را می‌بیند و در گزارش ممیزی می‌ماند. مشترکان دلیل را نمی‌بینند.", + "templates-label": "انتخاب دلیل پیش‌فرض", + "templates": { + "rules": { + "label": "نقض قوانین پلتفرم", + "text": "حساب شما به دلیل نقض قوانین پلتفرم تعلیق شده است." + }, + "content": { + "label": "محتوای نامناسب", + "text": "حساب شما به دلیل انتشار محتوای نامناسب تعلیق شده است." + }, + "report": { + "label": "گزارش تخلف", + "text": "حساب شما به دلیل دریافت گزارش تخلف در حال بررسی است." + }, + "admin-error": { + "label": "خطای اداری", + "text": "این تعلیق به دلیل خطای اداری بوده و به زودی رفع خواهد شد." + } + }, + "empty": "ابتدا دلیل تعلیق را بنویسید.", + "confirm": "تعلیق و اطلاع‌رسانی", + "done": "حساب تحلیلگر تعلیق شد و {{subscribers}} مشترک فعال مطلع شدند.", + "done-none": "حساب تحلیلگر تعلیق شد.", + "failed": "تعلیق حساب انجام نشد" + }, + "reinstate": { + "title": "رفع تعلیق حساب", + "description": "با رفع تعلیق، دسترسی تحلیلگر و مشترکان بازیابی می‌شود.", + "impact": "{{subscriptions}} اشتراک فعال به مدت {{duration}} تمدید خواهد شد.", + "impact-none": "اشتراک فعالی برای تمدید وجود ندارد.", + "impact-account-only": "این تعلیق فقط حساب کاربری را شامل می‌شد؛ اشتراکی تمدید نمی‌شود.", + "field": "دلیل رفع تعلیق", + "placeholder": "دلیل رفع تعلیق را بنویسید...", + "empty": "ابتدا دلیل رفع تعلیق را بنویسید.", + "confirm": "بله، رفع تعلیق", + "done": "تعلیق رفع شد و {{subscriptions}} اشتراک تمدید گردید.", + "done-none": "تعلیق رفع شد.", + "failed": "رفع تعلیق انجام نشد" + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/auth.json b/platforms/garden-roof/src/shared/locales/fa/auth.json new file mode 100644 index 0000000..09743b6 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/auth.json @@ -0,0 +1,29 @@ +{ + "login": { + "title": "ورود به پنل ادمین", + "subtitle": "شماره موبایل حساب ادمین را وارد کنید.", + "phone-label": "شماره موبایل", + "phone-placeholder": "۰۹۱۲ ۳۴۵ ۶۷۸۹", + "send": "دریافت کد تأیید", + "send-failed": "کد تأیید ارسال نشد", + "code-title": "کد تأیید را وارد کنید", + "code-subtitle": "کد ۶ رقمی به ‎{{phone}}‎ پیامک شد.", + "code-label": "کد تأیید", + "verify": "ورود", + "verify-failed": "ورود انجام نشد", + "edit-phone": "ویرایش شماره", + "resend": "ارسال دوباره کد", + "resend-in": "ارسال دوباره تا {{time}}", + "code-sent": "کد تأیید دوباره ارسال شد." + }, + "validation": { + "phone-invalid": "شماره موبایل معتبر نیست؛ مثل ۰۹۱۲۳۴۵۶۷۸۹.", + "code-required": "کد تأیید را وارد کنید.", + "code-invalid": "کد تأیید ۶ رقم است." + }, + "session-ended": { + "title": "نشست شما به پایان رسید", + "description": "برای امنیت حساب، دوباره وارد شوید.", + "action": "ورود دوباره" + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/codes.json b/platforms/garden-roof/src/shared/locales/fa/codes.json new file mode 100644 index 0000000..f654e32 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/codes.json @@ -0,0 +1,158 @@ +{ + "header": { + "title": "کدهای دعوت", + "subtitle": "یک کد برای هر تحلیلگر؛ ظرفیت را فقط ادمین تغییر می‌دهد.", + "search": "جستجوی تحلیلگر یا کد", + "tabs-label": "کدهای دعوت", + "tabs": { + "codes": "همه کدها", + "requests": "درخواست‌های افزایش" + }, + "pending": "{{value}} درخواست در انتظار" + }, + "status": { + "active": "فعال", + "full": "ظرفیت تکمیل", + "inactive": "غیرفعال" + }, + "people": "{{value}} نفر", + "usage": "{{used}} از {{max}}", + "none": "—", + "suspended": "حساب معلق", + "list": { + "meta-title": "کدهای دعوت", + "table-label": "همه کدها", + "columns": { + "analyst": "تحلیلگر", + "code": "کد", + "usage": "استفاده / ظرفیت", + "waitlist": "لیست اطلاع‌رسانی", + "status": "وضعیت", + "actions": "عملیات" + }, + "request": "درخواست {{people}}", + "change-capacity": "تغییر ظرفیت", + "deactivate": "غیرفعال‌سازی", + "activate": "فعال‌سازی", + "change-capacity-label": "تغییر ظرفیت کد {{code}}", + "deactivate-label": "غیرفعال‌سازی کد {{code}}", + "activate-label": "فعال‌سازی کد {{code}}", + "summary": "{{range}} · ترتیب: بیشترین استفاده", + "loading": "در حال بارگذاری کدهای دعوت…", + "error": "فهرست کدهای دعوت بارگذاری نشد.", + "empty": { + "title": "هنوز کدی ساخته نشده است", + "description": "کد دعوت هر تحلیلگر پس از تأیید احراز هویت ساخته می‌شود." + } + }, + "empty-search": { + "title": "نتیجه‌ای پیدا نشد", + "description": "نام تحلیلگر، نام کاربری یا کد دیگری را جستجو کنید.", + "clear": "پاک کردن جستجو" + }, + "requests": { + "meta-title": "درخواست‌های افزایش ظرفیت", + "table-label": "درخواست‌های افزایش ظرفیت", + "columns": { + "analyst": "تحلیلگر", + "current": "ظرفیت فعلی", + "requested": "درخواست", + "waitlist": "لیست اطلاع‌رسانی", + "note": "یادداشت تحلیلگر", + "date": "تاریخ", + "actions": "عملیات" + }, + "approve": "تأیید", + "reject": "رد", + "approve-label": "تأیید درخواست {{name}}", + "reject-label": "رد درخواست {{name}}", + "summary": "{{range}} · ترتیب: قدیمی‌ترین اول", + "loading": "در حال بارگذاری درخواست‌ها…", + "error": "فهرست درخواست‌ها بارگذاری نشد.", + "empty": { + "title": "درخواستی در انتظار نیست", + "description": "درخواست‌های تازه افزایش ظرفیت اینجا نمایش داده می‌شوند." + } + }, + "detail": { + "title": "جزئیات کد دعوت", + "copy": "کپی کد", + "copied": "کد کپی شد.", + "copy-failed": "کپی کد انجام نشد", + "copy-failed-description": "کد را انتخاب کنید و دستی کپی کنید.", + "fields": { + "analyst": "تحلیلگر", + "used": "استفاده‌شده", + "waitlist": "لیست اطلاع‌رسانی", + "request": "درخواست تحلیلگر", + "created": "ایجاد", + "link": "لینک دعوت" + }, + "last-sms": "{{people}} · آخرین پیامک: {{time}}", + "loading": "در حال بارگذاری جزئیات کد…", + "error": "جزئیات کد بارگذاری نشد.", + "change-capacity": "تغییر ظرفیت", + "deactivate": "غیرفعال‌سازی کد", + "activate": "فعال‌سازی کد" + }, + "capacity": { + "title": "تغییر ظرفیت کد دعوت", + "fields": { + "code": "کد", + "used": "استفاده‌شده", + "waitlist": "لیست اطلاع‌رسانی", + "request": "درخواست تحلیلگر" + }, + "request-value": "{{people}} · {{date}}", + "field": "ظرفیت جدید", + "hint": "عدد صحیح، دست‌کم {{min}} (تعداد استفاده‌شده) و حداکثر {{max}}", + "notify": "با ذخیره، به {{people}} در لیست اطلاع‌رسانی پیامک «ظرفیت باز شد» ارسال می‌شود.", + "held": "تا وقتی کد غیرفعال یا حساب تحلیلگر معلق است، به لیست اطلاع‌رسانی پیامک «ظرفیت باز شد» ارسال نمی‌شود.", + "save": "ذخیره", + "save-notify": "ذخیره و اطلاع‌رسانی", + "changed": "ظرفیت کد {{code}} به {{max}} نفر تغییر کرد.", + "approved": "درخواست تأیید شد؛ ظرفیت کد {{code}} به {{max}} نفر رسید.", + "notified": "پیامک «ظرفیت باز شد» برای {{people}} در لیست اطلاع‌رسانی ارسال شد.", + "change-failed": "تغییر ظرفیت انجام نشد", + "approve-failed": "تأیید درخواست انجام نشد", + "errors": { + "required": "ظرفیت جدید را بنویسید.", + "integer": "ظرفیت باید یک عدد صحیح باشد.", + "below-one": "ظرفیت باید دست‌کم ۱ نفر باشد.", + "below-used": "ظرفیت نمی‌تواند کمتر از تعداد استفاده‌شده باشد.", + "above-max": "ظرفیت نمی‌تواند بیشتر از ۱۰۰۰ نفر باشد.", + "unchanged": "ظرفیت جدید با ظرفیت فعلی یکی است." + } + }, + "reject": { + "title": "رد درخواست افزایش ظرفیت", + "fields": { + "current": "ظرفیت فعلی", + "requested": "درخواست", + "note": "یادداشت تحلیلگر" + }, + "empty": "ابتدا دلیل رد درخواست را بنویسید.", + "confirm": "رد کردن و اطلاع‌رسانی", + "done": "درخواست رد شد و تحلیلگر مطلع گردید.", + "failed": "رد درخواست انجام نشد" + }, + "deactivate": { + "title": "غیرفعال‌سازی کد دعوت", + "notice": "کد {{code}} دیگر در خرید اشتراک پذیرفته نمی‌شود. لینک‌هایی که پیش‌تر به اشتراک گذاشته شده‌اند باز می‌شوند، اما صفحه خرید پیام «کد دعوت وارد‌شده معتبر نیست.» را نشان می‌دهد. اشتراک‌هایی که با این کد خریده شده‌اند تغییری نمی‌کنند.", + "empty": "ابتدا دلیل غیرفعال‌سازی کد را بنویسید.", + "confirm": "غیرفعال‌سازی کد", + "done": "کد {{code}} غیرفعال شد.", + "failed": "غیرفعال‌سازی کد انجام نشد" + }, + "activate": { + "title": "فعال‌سازی کد دعوت", + "notice": "کد {{code}} دوباره در خرید اشتراک پذیرفته می‌شود و ظرفیت قبلی خود را دارد.", + "suspended": "حساب این تحلیلگر معلق است؛ تا رفع تعلیق، کسی با این کد اشتراک نمی‌خرد.", + "empty": "ابتدا دلیل فعال‌سازی کد را بنویسید.", + "confirm": "فعال‌سازی کد", + "done": "کد {{code}} فعال شد.", + "failed": "فعال‌سازی کد انجام نشد" + }, + "already-decided": "این درخواست در این فاصله بررسی شده است؛ اطلاعات به‌روز شد.", + "status-changed": "وضعیت این کد در این فاصله تغییر کرده است؛ اطلاعات به‌روز شد." +} diff --git a/platforms/garden-roof/src/shared/locales/fa/common.json b/platforms/garden-roof/src/shared/locales/fa/common.json new file mode 100644 index 0000000..cec21cf --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/common.json @@ -0,0 +1,174 @@ +{ + "app": { + "name": "پنل ادمین لومینا", + "brand": "لومینا", + "panel": "پنل ادمین" + }, + "toaster": "اعلان‌ها", + "toast-close": "بستن اعلان", + "nav": { + "label": "ناوبری پنل ادمین", + "health": "سلامت بتا", + "verify": "احراز هویت تحلیلگران", + "analysts": "مدیریت تحلیلگران", + "codes": "کدهای دعوت", + "subs": "اشتراک‌ها", + "preds": "پیش‌بینی‌ها", + "payouts": "تسویه تحلیلگران", + "featured": "تحلیلگران منتخب", + "soon": "به‌زودی", + "soon-items": { + "users": "کاربران", + "transactions": "تراکنش‌ها", + "moderation": "نظارت بر محتوا", + "flags": "پرچم‌های ویژگی" + }, + "count": "{{count}} مورد در انتظار", + "open-menu": "باز کردن منوی پنل", + "close-menu": "بستن منوی پنل", + "sign-out": "خروج از حساب", + "back": "بازگشت" + }, + "sign-out": { + "title": "از پنل ادمین خارج می‌شوید؟", + "description": "برای ادامه کار باید دوباره وارد شوید.", + "confirm": "خروج از حساب", + "cancel": "انصراف", + "failed": "خروج از حساب انجام نشد" + }, + "status": { + "verification": { + "pending": "در انتظار بررسی", + "approved": "تأییدشده", + "rejected": "رد شده" + }, + "account": { + "active": "فعال", + "suspended": "تعلیق‌شده" + }, + "subscription": { + "active": "فعال", + "suspended": "کانال معلق شده", + "expired": "منقضی‌شده", + "refunded": "بازگشت وجه" + }, + "payment": { + "successful": "موفق", + "failed": "ناموفق", + "pending": "در حال بررسی" + }, + "payout": { + "ready": "قابل واریز", + "in_progress": "در حال انجام", + "paid": "انجام شده", + "cancelled": "لغو شده" + }, + "prediction": { + "open": "فعال", + "closed": "بسته‌شده" + }, + "outcome": { + "win": "موفق", + "loss": "ناموفق", + "breakeven": "سر به سر" + } + }, + "markets": { + "crypto": "کریپتو", + "gold": "طلا و سکه", + "equities": "بورس", + "forex": "فارکس", + "funds": "صندوق‌های سرمایه‌گذاری", + "real_estate": "مسکن", + "automotive": "خودرو", + "USDT": "تتر (دلار و ارز)" + }, + "billing-periods": { + "monthly": "ماهانه", + "quarterly": "سه‌ماهه", + "semi_annual": "شش‌ماهه", + "yearly": "سالانه" + }, + "reason": { + "label": "دلیل", + "hint": "حداقل ۱۰ نویسه؛ فقط ادمین‌ها آن را می‌بینند و در گزارش ممیزی ثبت می‌شود.", + "hint-analyst": "حداقل ۱۰ نویسه؛ تحلیلگر آن را می‌بیند و در گزارش ممیزی می‌ماند.", + "required": "دلیل را بنویسید.", + "short": "دلیل باید دست‌کم ۱۰ نویسه باشد.", + "long": "دلیل نباید بیشتر از ۵۰۰ نویسه باشد.", + "other": "سایر" + }, + "audit": { + "title": "گزارش ممیزی", + "empty": "هنوز رویدادی ثبت نشده است.", + "system": "سیستم", + "toggle": "نمایش گزارش ممیزی", + "locked": "ثبت دائمی، غیرقابل ویرایش", + "affected": "{{formatted}} مشترک متأثر", + "extension": "{{duration}} تمدید", + "meta": "{{time}} · {{actor}}", + "actions": { + "verification.approved": "تأیید شد", + "verification.rejected": "رد شد", + "account.suspended": "تعلیق شد", + "account.reinstated": "رفع تعلیق شد", + "code.created": "کد دعوت ساخته شد", + "code.capacity_changed": "ظرفیت تغییر کرد", + "code.deactivated": "کد غیرفعال شد", + "code.activated": "کد فعال شد", + "capacity_request.approved": "درخواست ظرفیت تأیید شد", + "capacity_request.rejected": "درخواست ظرفیت رد شد", + "subscription.extended": "اشتراک تمدید شد", + "subscription.refunded": "بازگشت وجه انجام شد", + "subscription.granted": "دسترسی اعطا شد", + "prediction.resolved": "بسته شدن تأیید شد", + "prediction.proposal_dismissed": "پیشنهاد بسته شدن رد شد", + "prediction.overridden": "نتیجه اصلاح شد", + "prediction.flagged": "پرچم‌گذاری شد", + "prediction.unflagged": "پرچم برداشته شد", + "payout.created": "ایجاد تسویه", + "payout.paid": "ثبت پرداخت", + "payout.cancelled": "لغو تسویه", + "ledger.corrected": "اصلاح موجودی", + "featured.added": "به منتخب اضافه شد", + "featured.removed": "از منتخب حذف شد", + "featured.reordered": "ترتیب تغییر کرد" + }, + "capacity-up": "افزایش ظرفیت از {{from}} به {{to}}", + "capacity-down": "کاهش ظرفیت از {{from}} به {{to}}", + "refund-amount": "بازگشت وجه {{amount}} تومان", + "extend-days": "تمدید {{days}} روزه", + "descriptions": { + "payout-created": "مبلغ از دفتر حساب؛ پیامک و اعلان برای تحلیلگر ارسال شد." + }, + "closed-by-admin": "بستن با قیمت ادمین" + }, + "table": { + "open": "باز کردن", + "more": "بیشتر", + "sort-ascending": "مرتب‌شده: صعودی", + "sort-descending": "مرتب‌شده: نزولی" + }, + "pager": { + "label": "صفحه‌بندی", + "summary": "نمایش {{from}} تا {{to}} از {{total}}", + "previous": "صفحه قبل", + "next": "صفحه بعد", + "page": "صفحه {{page}}" + }, + "search": { + "clear": "پاک کردن جستجو" + }, + "actions": { + "cancel": "انصراف", + "close": "بستن", + "confirm": "تأیید", + "retry": "تلاش مجدد", + "save": "ذخیره" + }, + "network": { + "offline": "اینترنت قطع است", + "offline-description": "آخرین اطلاعات ذخیره‌شده را می‌بینید.", + "frozen": "برای این کار به اینترنت نیاز دارید." + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/errors.json b/platforms/garden-roof/src/shared/locales/fa/errors.json new file mode 100644 index 0000000..9490553 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/errors.json @@ -0,0 +1,91 @@ +{ + "http": { + "network": "پاسخی از سرور نرسید.", + "network-hint": "اتصال اینترنت را بررسی کنید و دوباره تلاش کنید.", + "timeout": "سرور دیرتر از همیشه پاسخ داد.", + "timeout-hint": "چند لحظه بعد دوباره تلاش کنید.", + "aborted": "درخواست لغو شد.", + "aborted-hint": "دوباره تلاش کنید.", + "parse": "پاسخ سرور قابل خواندن نبود.", + "parse-hint": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید.", + "interceptor": "درخواست ارسال نشد.", + "interceptor-hint": "صفحه را دوباره بارگذاری کنید.", + "unknown": "مشکلی پیش آمد.", + "unknown-hint": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید.", + "validation": "برخی از اطلاعات واردشده درست نیست.", + "bad-request": "درخواست قابل انجام نبود.", + "unauthorized": "برای ادامه وارد حساب خود شوید.", + "forbidden": "اجازه انجام این کار را ندارید.", + "not-found": "موردی که دنبالش بودید پیدا نشد.", + "conflict": "این اطلاعات در این فاصله تغییر کرده است.", + "rate-limited": "تعداد درخواست‌ها زیاد بود.", + "server": "سرور نتوانست درخواست را انجام دهد.", + "retry-after": "{{seconds}} ثانیه دیگر دوباره تلاش کنید." + }, + "fallback": { + "error": { + "title": "مشکلی پیش آمد", + "description": "این بخش بارگذاری نشد. دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید." + }, + "server": { + "title": "سرور پاسخ نمی‌دهد", + "description": "مشکل از سمت لومیناست و در حال رفع آن هستیم. چند دقیقه دیگر دوباره تلاش کنید." + }, + "network": { + "title": "اتصال برقرار نشد", + "description": "پاسخی از سرور نرسید. اتصال اینترنت را بررسی کنید و دوباره تلاش کنید." + }, + "offline": { + "title": "اینترنت شما قطع است", + "description": "به محض وصل شدن، این صفحه خودکار به‌روز می‌شود." + }, + "timeout": { + "title": "پاسخ طول کشید", + "description": "سرور دیرتر از همیشه پاسخ داد. دوباره تلاش کنید." + }, + "retry": "تلاش مجدد", + "retrying": "در حال تلاش…", + "reload": "بارگذاری دوباره صفحه", + "reference": "کد پیگیری:" + }, + "empty": { + "not-found": { + "title": "صفحه پیدا نشد", + "description": "ممکن است نشانی اشتباه باشد یا این مورد حذف شده باشد." + }, + "no-access": { + "title": "به پنل ادمین دسترسی ندارید", + "description": "این بخش فقط برای حساب‌های ادمین است. اگر فکر می‌کنید اشتباهی رخ داده است، به تیم فنی خبر دهید." + }, + "session": { + "title": "نشست شما به پایان رسید", + "description": "برای امنیت حساب، دوباره وارد شوید." + }, + "home": "بازگشت به سلامت بتا", + "login-again": "ورود دوباره" + }, + "app": { + "title": "پنل ادمین با مشکل روبه‌رو شد", + "description": "این خطا ثبت شد. صفحه را دوباره بارگذاری کنید؛ اگر ادامه داشت، به تیم فنی خبر دهید." + }, + "action": { + "try-again": "تلاش مجدد", + "reload": "بارگذاری دوباره" + }, + "support": { + "with-reference": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، کد پیگیری {{referenceId}} را به تیم فنی بگویید.", + "without-reference": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، به تیم فنی خبر دهید." + }, + "auth": { + "code-invalid": "کد درست نیست یا دیگر اعتبار ندارد. اگر پیامکی به دستتان نرسیده است، شماره را بررسی کنید و کد تازه بگیرید.", + "too-many": "تعداد تلاش‌های ورود زیاد بوده است. {{wait}} دیگر دوباره تلاش کنید.", + "too-many-later": "تعداد تلاش‌های ورود زیاد بوده است. چند دقیقه دیگر دوباره تلاش کنید." + }, + "form": { + "network": "اتصال اینترنت خود را بررسی کنید.", + "field-invalid": "مقدار واردشده معتبر نیست." + }, + "conflict": { + "stale": "این مورد در این فاصله تغییر کرده است؛ فهرست دوباره بارگذاری شد." + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/featured.json b/platforms/garden-roof/src/shared/locales/fa/featured.json new file mode 100644 index 0000000..ec46390 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/featured.json @@ -0,0 +1,128 @@ +{ + "page": { + "title": "تحلیلگران منتخب", + "meta-title": "تحلیلگران منتخب", + "subtitle": "همین ترتیب در اسلایدر صفحه اصلی، خانه و «تحلیلگران منتخب» نمایش داده می‌شود. شماره‌ها فقط برای ادمین است و رتبه‌بندی نیست.", + "add": "افزودن تحلیلگر", + "loading": "در حال بارگذاری تحلیلگران منتخب…", + "error": "فهرست تحلیلگران منتخب بارگذاری نشد." + }, + "empty": { + "title": "هنوز تحلیلگر منتخبی نیست", + "description": "تحلیلگرانی که اضافه کنید به همین ترتیب در اسلایدر صفحه اصلی، خانه و «تحلیلگران منتخب» نمایش داده می‌شوند." + }, + "table": { + "label": "تحلیلگران منتخب به ترتیب ادمین", + "columns": { + "move": "جابه‌جایی", + "position": "ترتیب", + "analyst": "تحلیلگر", + "markets": "بازارها", + "track-record": "کارنامه عمومی", + "status": "وضعیت", + "actions": "عملیات" + }, + "track-record": { + "yes": "دارد", + "no": "ندارد" + }, + "hidden": "پنهان — {{reason}}", + "hidden-reasons": { + "suspended": "حساب معلق", + "unverified": "احراز هویت نشده", + "no_track_record": "بدون کارنامه عمومی", + "profile_incomplete": "پروفایل ناقص", + "over_limit": "بیرون از 10 کارت عمومی" + }, + "hidden-note": "تحلیلگر معلق همان لحظه از فهرست‌های عمومی پنهان می‌شود و جایش در این فهرست می‌ماند؛ با رفع تعلیق دوباره نمایش داده می‌شود.", + "remove": "حذف از منتخب", + "more": "گزینه‌های بیشتر برای {{name}}", + "menu-label": "جابه‌جایی {{name}}", + "move-up": "انتقال به بالا", + "move-down": "انتقال به پایین" + }, + "reorder": { + "grip": "جابه‌جایی {{name}}؛ Space برای برداشتن، ↑ ↓ برای جابه‌جایی", + "moving-row": "در حال جابه‌جایی · جایگاه {{position}} از {{total}}", + "moving": "{{name}}، جایگاه {{position}} از {{total}}. برای رها کردن Space یا کلیک، برای لغو Esc.", + "dropped": "{{name}} در جایگاه {{position}} از {{total}} رها شد.", + "cancelled": "جابه‌جایی لغو شد؛ {{name}} در جایگاه {{position}} از {{total}} ماند.", + "done": "ترتیب تحلیلگران منتخب ذخیره شد.", + "failed": "ذخیره ترتیب انجام نشد." + }, + "conflict": "فهرست منتخب در این فاصله تغییر کرده بود؛ فهرست تازه نمایش داده شد.", + "list-invalid": "یکی از تحلیلگران فهرست دیگر پیدا نشد؛ فهرست تازه نمایش داده شد.", + "fewer": { + "title": "کمتر از ۳ تحلیلگر منتخب: بخش تحلیلگران صفحه اصلی پنهان می‌شود.", + "shown": "خانه و «تحلیلگران منتخب» همین {{total}} تحلیلگر را نشان می‌دهند.", + "shown-none": "خانه و «تحلیلگران منتخب» هیچ تحلیلگری را نشان نمی‌دهند.", + "needed-one": "با افزودن یک تحلیلگر دیگر، بخش صفحه اصلی دوباره نمایش داده می‌شود.", + "needed": "با افزودن {{total}} تحلیلگر دیگر، بخش صفحه اصلی دوباره نمایش داده می‌شود." + }, + "pages": { + "title": "نمایش در صفحه‌ها", + "landing": "صفحه اصلی", + "landing-hidden": "پنهان", + "landing-hint": "بخش تحلیلگران نمایش داده نمی‌شود.", + "home": "خانه", + "home-hint": "با پیوند «همه تحلیلگران منتخب».", + "analysts": "تحلیلگران منتخب", + "analysts-path": "/analysts", + "cards": "{{total}} کارت" + }, + "preview": { + "label": "پیش‌نمایش", + "tag": "پیش‌نمایش", + "landing-title": "صفحه اصلی و خانه", + "home-title": "خانه و «تحلیلگران منتخب»", + "first": "{{shown}} کارت اول از {{total}}؛ بقیه در اسلایدر", + "first-visible": "{{shown}} کارت اول از {{total}} تحلیلگر قابل نمایش", + "visible": "{{total}} کارت قابل نمایش" + }, + "card": { + "verified": "تأییدشده", + "markets": "بازارهای تخصصی", + "win-rate": "نرخ موفقیت", + "predictions": "پیش‌بینی", + "avg-roi": "میانگین بازده", + "no-record": "کارنامه عمومی هنوز فعال نشده است.", + "followers": "{{followers}} دنبال‌کننده", + "view": "مشاهده کانال" + }, + "add": { + "title": "افزودن تحلیلگر منتخب", + "search": "جستجوی نام یا نام کاربری", + "eligible-label": "تحلیلگرانی که می‌توان افزود", + "ineligible-label": "تحلیلگرانی که نمی‌توان افزود", + "reasons": { + "unverified": "احراز هویت نشده", + "suspended": "حساب معلق است", + "no_track_record": "کارنامه عمومی ندارد" + }, + "note": "تحلیلگران جدید به انتهای فهرست اضافه می‌شوند.", + "confirm": "افزودن به منتخب", + "confirm-count": "افزودن به منتخب ({{total}})", + "nothing-picked": "ابتدا دست‌کم یک تحلیلگر را انتخاب کنید.", + "full": "فهرست منتخب حداکثر {{max}} تحلیلگر دارد.", + "loading": "در حال جستجوی تحلیلگران…", + "error": "فهرست تحلیلگران بارگذاری نشد.", + "empty": { + "title": "تحلیلگری پیدا نشد", + "description": "نام یا نام کاربری دیگری را جستجو کنید." + }, + "done-one": "{{name}} به منتخب اضافه شد.", + "done": "{{total}} تحلیلگر به منتخب اضافه شد.", + "failed": "افزودن به منتخب انجام نشد.", + "not-eligible-one": "{{name}} دیگر شرایط افزودن را ندارد و از انتخاب‌ها برداشته شد.", + "not-eligible": "تحلیلگران انتخاب‌شده دیگر شرایط افزودن را ندارند و از انتخاب‌ها برداشته شدند." + }, + "remove": { + "title": "حذف از تحلیلگران منتخب", + "position": "ترتیب {{position}}", + "impact": "{{name}} از اسلایدر صفحه اصلی، خانه و «تحلیلگران منتخب» حذف می‌شود. کانال، کارنامه و مشترکانش تغییری نمی‌کنند.", + "empty": "ابتدا دلیل حذف را بنویسید.", + "confirm": "حذف از منتخب", + "done": "{{name}} از منتخب حذف شد.", + "failed": "حذف از منتخب انجام نشد." + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/health.json b/platforms/garden-roof/src/shared/locales/fa/health.json new file mode 100644 index 0000000..8bdbae2 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/health.json @@ -0,0 +1,132 @@ +{ + "title": "سلامت بتا", + "meta-title": "سلامت بتا", + "meta-title-secondary": "شاخص‌های ثانویه · سلامت بتا", + "loading": "در حال بارگذاری شاخص‌های سلامت بتا…", + "error": "شاخص‌های سلامت بتا بارگذاری نشد.", + "subtitle": "روز {{day}} از {{total}} · بتای بسته از {{start}} تا {{end}}", + "subtitle-upcoming": "بتا هنوز شروع نشده است · شروع: {{start}}", + "updated": "به‌روزرسانی: {{date}}، {{time}}", + "none": "—", + "tabs-label": "شاخص‌های سلامت بتا", + "tabs": { + "main": "شاخص‌های اصلی", + "secondary": "شاخص‌های ثانویه" + }, + "upcoming": { + "title": "هنوز داده‌ای نیست", + "description": "شاخص‌ها از روز اول بتا و با اولین رویدادها (ثبت‌نام، دنبال کردن و پرداخت) اینجا نمایش داده می‌شوند." + }, + "not-scheduled": { + "title": "تاریخ شروع بتا هنوز تعیین نشده است", + "description": "شاخص‌های سلامت بتا پس از ثبت تاریخ شروع بتا در پیکربندی سرور اینجا نمایش داده می‌شوند. برای تعیین آن با تیم فنی هماهنگ کنید." + }, + "exit": { + "title": "شاخص‌های خروج از فاز 0", + "caption": "مقدار فعلی / هدف پایان بتا", + "loading": "در حال بارگذاری شاخص‌های خروج…", + "error": "شاخص‌های خروج از فاز 0 بارگذاری نشد.", + "labels": { + "active_analysts": "تحلیلگران فعال", + "avg_paid_subscribers": "میانگین مشترک پرداختی هر تحلیلگر", + "publishing_analysts": "تحلیلگرانی که پیش‌بینی منتشر کرده‌اند", + "paid_subscribers": "کل مشترکان پرداختی" + }, + "value": "{{value}} / {{target}}", + "status": { + "on_track": "در مسیر", + "behind": "عقب‌تر از هدف" + }, + "target-analysts": "هدف پایان بتا: {{target}} تحلیلگر فعال", + "expected": "انتظار روز {{day}}: {{expected}}", + "basis": "{{part}} از {{whole}} تحلیلگر فعال" + }, + "funnel": { + "title": "قیف بازدیدکننده تا سرمایه‌گذار", + "caption": "تبدیل هر مرحله نسبت به مرحلهٔ قبل", + "loading": "در حال بارگذاری قیف و زمان‌بندی بتا…", + "error": "قیف بازدیدکننده تا سرمایه‌گذار بارگذاری نشد.", + "people": "{{people}} نفر", + "people-rate": "{{people}} نفر · {{rate}}", + "awaiting": "{{waiting}} در انتظار بررسی", + "not-recorded": "هنوز ثبت نمی‌شود", + "events": { + "landing_cta_click": "کلیک دکمهٔ صفحهٔ اصلی", + "register_done": "ثبت‌نام", + "follow": "اولین دنبال کردن", + "checkout_view": "ورود به خرید اشتراک", + "payment_result": "پرداخت موفق", + "kyc_submitted": "ارسال مدارک احراز هویت", + "verification_approved": "تأیید احراز هویت", + "first_prediction_published": "اولین پیش‌بینی منتشرشده" + } + }, + "timeline": { + "title": "زمان‌بندی بتا", + "day": "روز {{day}} از {{total}}", + "days-left": "{{days}} روز مانده", + "start": "شروع", + "end": "پایان", + "analysts": "تحلیلگران بتا", + "analysts-value": "{{total}} نفر · {{active}} فعال", + "investors": "سرمایه‌گذاران ثبت‌نام‌شده", + "investors-value": "{{people}} نفر", + "conversion": "تبدیل کل قیف" + }, + "analysts": { + "title": "تحلیلگران بتا", + "caption": "{{total}} تحلیلگر · {{active}} فعال · ترتیب: مشترک پرداختی", + "loading": "در حال بارگذاری تحلیلگران بتا…", + "error": "فهرست تحلیلگران بتا بارگذاری نشد.", + "table-label": "تحلیلگران بتا", + "columns": { + "analyst": "تحلیلگر", + "paid": "مشترک پرداختی", + "predictions": "پیش‌بینی منتشرشده", + "capacity": "ظرفیت کد", + "completion": "نرخ تکمیل پرداخت" + }, + "capacity": "{{used}} از {{max}}", + "no-code": "بدون کد دعوت", + "completion-basis": "({{completed}} از {{started}})", + "inactive": { + "not_verified": "احراز هویت نشده", + "not_priced": "بدون قیمت اشتراک", + "no_recent_post": "بدون پست در 7 روز اخیر" + } + }, + "secondary": { + "title": "شاخص‌های ثانویه", + "caption": "از شروع بتا تا امروز", + "loading": "در حال بارگذاری شاخص‌های ثانویه…", + "error": "شاخص‌های ثانویه بارگذاری نشد.", + "onboarding": { + "label": "زمان آماده‌سازی تحلیلگر", + "value": "{{days}} روز", + "hint": "میانه، از ثبت‌نام تا اولین پیش‌بینی منتشرشده" + }, + "churn": { + "label": "ریزش ماه اول", + "hint": "{{lapsed}} از {{due}} اشتراک ماهانهٔ سررسیدشده تمدید نشد" + }, + "completion": { + "label": "نرخ تکمیل پرداخت", + "hint": "{{completed}} پرداخت موفق از {{started}} ورود به درگاه" + }, + "pace": { + "label": "پیش‌بینی هر تحلیلگر در ماه", + "hint": "{{predictions}} پیش‌بینی در {{days}} روز، {{analysts}} تحلیلگر فعال" + }, + "views": { + "label": "بازدید کارنامه", + "hint": "بازدید صفحهٔ کارنامهٔ تحلیلگران در 7 روز اخیر", + "hint-none": "بازدید صفحهٔ کارنامه هنوز ثبت نمی‌شود" + } + }, + "analyst-funnel": { + "title": "قیف آماده‌سازی تحلیلگر", + "caption": "تبدیل هر مرحله نسبت به مرحلهٔ قبل", + "loading": "در حال بارگذاری قیف آماده‌سازی تحلیلگر…", + "error": "قیف آماده‌سازی تحلیلگر بارگذاری نشد." + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/payouts.json b/platforms/garden-roof/src/shared/locales/fa/payouts.json new file mode 100644 index 0000000..1287ee8 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/payouts.json @@ -0,0 +1,197 @@ +{ + "page": { + "title": "تسویه تحلیلگران", + "meta-title": "تسویه تحلیلگران", + "subtitle": "تسویه هفتگی، روزهای پنجشنبه؛ هر دوره از پنجشنبه تا چهارشنبهٔ پیش از آن است.", + "search": "جستجوی تحلیلگر", + "tabs-label": "وضعیت تسویه‌ها", + "tabs": { + "ready": "آماده تسویه", + "in_progress": "در حال انجام", + "paid": "پرداخت‌شده", + "cancelled": "لغوشده" + }, + "ready-count": "{{count}} تحلیلگر آماده تسویه", + "loading": "در حال بارگذاری تسویه‌ها…", + "error": "فهرست تسویه‌ها بارگذاری نشد." + }, + "columns": { + "analyst": "تحلیلگر", + "period": "دوره", + "ready-amount": "مبلغ قابل تسویه", + "amount": "مبلغ", + "sheba": "شبا", + "created": "تاریخ ثبت", + "actions": "عملیات", + "reference": "شماره پیگیری بانک", + "paid": "تاریخ پرداخت", + "cancelled": "تاریخ لغو", + "status": "وضعیت", + "open": "باز کردن" + }, + "notes": { + "ready": "مبلغ هر ردیف از دفتر حساب تحلیلگر محاسبه می‌شود و قابل ویرایش نیست.", + "in_progress": "وضعیت برای تحلیلگر: «در حال انجام». پس از انتقال بانکی، شماره پیگیری را با «ثبت پرداخت» وارد کنید." + }, + "sorted": { + "paid": "{{summary}} · جدیدترین پرداخت اول", + "cancelled": "{{summary}} · جدیدترین لغو اول" + }, + "open-row": "جزئیات تسویه {{name}}", + "toman": "تومان", + "actions": { + "create": "ایجاد تسویه", + "mark-paid": "ثبت پرداخت", + "cancel": "لغو" + }, + "empty": { + "ready": { + "title": "تسویه‌ای آماده نیست", + "description": "پس از بسته شدن هر دوره در چهارشنبه، تحلیلگرانی که موجودی و شبای ثبت‌شده دارند اینجا نمایش داده می‌شوند." + }, + "in_progress": { + "title": "تسویه‌ای در حال انجام نیست", + "description": "تسویه‌هایی که ایجاد می‌کنید تا ثبت پرداخت اینجا می‌مانند." + }, + "paid": { + "title": "هنوز پرداختی ثبت نشده است", + "description": "تسویه‌های پرداخت‌شده اینجا نمایش داده می‌شوند." + }, + "cancelled": { + "title": "تسویهٔ لغوشده‌ای نیست", + "description": "تسویه‌های لغوشده اینجا نمایش داده می‌شوند." + }, + "search": { + "title": "نتیجه‌ای پیدا نشد", + "description": "نام یا نام کاربری دیگری را جستجو کنید.", + "clear": "پاک کردن جستجو" + } + }, + "fields": { + "analyst": "تحلیلگر", + "period": "دوره", + "ready-amount": "مبلغ قابل تسویه", + "amount": "مبلغ", + "sheba": "شبا", + "holder": "صاحب حساب", + "created": "تاریخ ثبت", + "paid": "تاریخ پرداخت", + "reference": "شماره پیگیری بانک", + "receipt": "رسید", + "cancelled": "تاریخ لغو", + "reason": "دلیل لغو", + "bank": "بانک" + }, + "holder": "{{name}} · {{bank}}", + "none": "—", + "copy-sheba": "کپی شبا", + "create": { + "title": "ایجاد تسویه", + "note": "مبلغ از دفتر حساب خوانده می‌شود و قابل تغییر نیست. شبا همان شبای ثبت‌شده در لحظهٔ ایجاد می‌ماند.", + "notice": "با ایجاد تسویه، وضعیت «در حال انجام» می‌شود و پیامک و اعلان درون‌برنامه برای {{name}} ارسال می‌شود. پس از انتقال بانکی، «ثبت پرداخت» را بزنید.", + "confirm": "ایجاد تسویه", + "done": "تسویه ایجاد شد؛ پیامک و اعلان برای {{name}} ارسال شد.", + "failed": "تسویه ایجاد نشد", + "copied": "شبا کپی شد.", + "copy-failed": "شبا کپی نشد؛ آن را از روی صفحه بخوانید." + }, + "mark-paid": { + "title": "ثبت پرداخت", + "reference": "شماره پیگیری بانک", + "reference-hint": "الزامی؛ همان شماره‌ای که بانک برای انتقال داده است.", + "date": "تاریخ پرداخت", + "receipt": "رسید (اختیاری)", + "receipt-pick": "انتخاب تصویر یا PDF", + "receipt-rules": "JPG، PNG یا PDF، حداکثر 5 مگابایت", + "receipt-remove": "حذف رسید", + "receipt-change": "تغییر فایل", + "receipt-size": "{{size}} مگابایت", + "confirm": "ثبت پرداخت", + "done": "پرداخت ثبت شد.", + "failed": "پرداخت ثبت نشد" + }, + "cancel": { + "title": "لغو تسویه", + "notice": "مبلغ {{amount}} تومان به موجودی قابل واریز {{name}} بازمی‌گردد و پیامک و اعلان لغو برای او ارسال می‌شود. لغو نهایی است.", + "shown": "حداقل ۱۰ نویسه؛ در جزئیات واریز به تحلیلگر نمایش داده می‌شود.", + "empty": "ابتدا دلیل لغو تسویه را بنویسید.", + "confirm": "لغو تسویه", + "done": "تسویه لغو شد؛ مبلغ به موجودی قابل واریز {{name}} بازگشت.", + "failed": "تسویه لغو نشد" + }, + "detail": { + "title": "جزئیات تسویه", + "period": "دوره {{period}}", + "receipt-view": "مشاهده رسید", + "no-receipt": "بارگذاری نشده", + "lines": { + "title": "ردیف‌های دفتر حساب", + "note": "سهم تحلیلگر پس از کارمزد لومینا؛ نرخ کارمزد بتا هنوز قطعی نیست.", + "income": "درآمد اشتراک", + "refund_deduction": "کسر بازگشت وجه", + "correction": "اصلاح موجودی", + "plan": "اشتراک {{period}}", + "empty": "ردیفی از دفتر حساب به این تسویه وصل نیست.", + "total": "جمع" + }, + "loading": "در حال بارگذاری جزئیات تسویه…", + "error": "جزئیات تسویه بارگذاری نشد.", + "mark-paid": "ثبت پرداخت", + "cancel": "لغو تسویه" + }, + "stale": { + "settled": "این تسویه پیش‌تر پرداخت یا لغو شده است؛ فهرست به‌روز شد.", + "ready": "مبلغ قابل تسویه این تحلیلگر تغییر کرده است؛ فهرست به‌روز شد.", + "no-account": "این تحلیلگر دیگر شبای ثبت‌شده ندارد؛ فهرست به‌روز شد.", + "locked": "حساب این تحلیلگر تعلیق شده و تسویه برای او ایجاد نمی‌شود؛ فهرست به‌روز شد.", + "period": "دورهٔ این تسویه دیگر معتبر نیست؛ فهرست به‌روز شد." + }, + "validation": { + "reference-required": "شماره پیگیری بانک را وارد کنید.", + "reference-invalid": "شماره پیگیری بانک باید 6 تا 30 رقم باشد.", + "date-required": "تاریخ پرداخت را انتخاب کنید.", + "receipt-type": "فقط فایل‌های JPG، PNG یا PDF مجاز هستند.", + "receipt-size": "حجم فایل نباید بیشتر از 5 مگابایت باشد.", + "reference-used": "این شماره پیگیری پیش‌تر برای تسویهٔ دیگری ثبت شده است.", + "date-range": "تاریخ پرداخت باید بین روز ایجاد تسویه و امروز باشد.", + "receipt-store": "رسید ذخیره نشد؛ دوباره تلاش کنید یا بدون رسید ثبت کنید." + }, + "banks": { + "010": "بانک مرکزی", + "011": "بانک صنعت و معدن", + "012": "بانک ملت", + "013": "بانک رفاه کارگران", + "014": "بانک مسکن", + "015": "بانک سپه", + "016": "بانک کشاورزی", + "017": "بانک ملی ایران", + "018": "بانک تجارت", + "019": "بانک صادرات ایران", + "020": "بانک توسعه صادرات", + "021": "پست بانک ایران", + "022": "بانک توسعه تعاون", + "051": "مؤسسه اعتباری توسعه", + "053": "بانک کارآفرین", + "054": "بانک پارسیان", + "055": "بانک اقتصاد نوین", + "056": "بانک سامان", + "057": "بانک پاسارگاد", + "058": "بانک سرمایه", + "059": "بانک سینا", + "060": "بانک قرض‌الحسنه مهر ایران", + "061": "بانک شهر", + "062": "بانک آینده", + "063": "بانک انصار", + "064": "بانک گردشگری", + "065": "بانک حکمت ایرانیان", + "066": "بانک دی", + "069": "بانک ایران زمین", + "070": "بانک قرض‌الحسنه رسالت", + "073": "مؤسسه اعتباری کوثر", + "075": "مؤسسه اعتباری ملل", + "078": "بانک خاورمیانه", + "079": "بانک مهر اقتصاد", + "080": "مؤسسه اعتباری نور", + "095": "بانک ایران و ونزوئلا" + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/predictions.json b/platforms/garden-roof/src/shared/locales/fa/predictions.json new file mode 100644 index 0000000..0e65c48 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/predictions.json @@ -0,0 +1,308 @@ +{ + "page": { + "title": "پیش‌بینی‌ها", + "meta-title": "پیش‌بینی‌ها", + "subtitle": "بستن خودکار تا تأیید ادمین منتشر نمی‌شود؛ پیش‌بینی تا آن زمان «فعال» می‌ماند.", + "loading": "در حال بارگذاری پیش‌بینی‌ها…" + }, + "health": { + "title": "وضعیت منابع قیمت", + "checked": "بررسی خودکار هر ۱ دقیقه · آخرین بررسی {{time}}", + "last-price": "آخرین قیمت {{time}}", + "last-price-held": "آخرین قیمت {{time}} · {{held}} پیشنهاد در انتظار", + "no-price": "هنوز قیمتی نرسیده", + "no-price-held": "هنوز قیمتی نرسیده · {{held}} پیشنهاد در انتظار", + "fresh": "به‌روز", + "stale": "{{minutes}} دقیقه بدون قیمت", + "stale-no-price": "بدون قیمت", + "banner": "پیشنهاد بستن پیش‌بینی‌های {{markets}} تا رسیدن قیمت تازه منتظر می‌ماند و در این صف نمایش داده نمی‌شود. این پیش‌بینی‌ها تا آن زمان باز می‌مانند.", + "loading": "در حال بررسی منابع قیمت…", + "error": "وضعیت منابع قیمت بارگذاری نشد." + }, + "markets": { + "crypto": "کریپتو", + "gold": "طلا و سکه", + "forex": "فارکس", + "equities": "بورس", + "USDT": "تتر" + }, + "direction": { + "long": "خرید", + "short": "فروش" + }, + "events": { + "target": "رسیدن به هدف نهایی", + "stop": "فعال‌شدن حد ضرر", + "horizon": "پایان افق" + }, + "close-reasons": { + "target": "رسیدن به هدف نهایی", + "stop": "فعال‌شدن حد ضرر", + "horizon": "پایان افق", + "early": "بستن زودهنگام تحلیلگر", + "admin": "اصلاح توسط ادمین" + }, + "flag-reasons": { + "ambiguous": "مبهم", + "unrealistic_target": "هدف غیرواقعی", + "duplicate": "تکراری", + "other": "سایر" + }, + "queues": { + "label": "صف‌های پیش‌بینی", + "tabs": { + "needs_review": "نیاز به تأیید", + "open": "باز", + "closed": "بسته‌شده", + "flagged": "پرچم‌خورده" + }, + "count": "{{count}} پیشنهاد در انتظار تأیید", + "loading": "در حال بارگذاری پیش‌بینی‌ها…", + "error": "فهرست پیش‌بینی‌ها بارگذاری نشد.", + "columns": { + "symbol": "نماد", + "analyst": "تحلیلگر", + "direction": "جهت", + "event": "رویداد", + "proposed": "قیمت پیشنهادی", + "actions": "عملیات", + "entry": "ورود", + "final-target": "هدف نهایی", + "stop": "حد ضرر", + "published": "انتشار", + "outcome": "نتیجه", + "roi": "بازدهی", + "reason": "علت", + "closed-price": "قیمت بسته‌شدن", + "closed-at": "تاریخ بسته‌شدن", + "flag-reason": "دلیل", + "note": "توضیح", + "flagged": "ثبت", + "status": "وضعیت", + "flag": "پرچم‌گذاری", + "open": "جزئیات" + }, + "open-row": "جزئیات پیش‌بینی {{symbol}} از {{name}}", + "pending": "پیشنهاد بستن در انتظار تأیید", + "held": "در انتظار قیمت {{source}}", + "review": "بررسی و بستن", + "close-admin": "بستن با قیمت ادمین", + "flag": "پرچم‌گذاری", + "flag-row": "پرچم‌گذاری پیش‌بینی {{symbol}} از {{name}}", + "unflag": "برداشتن پرچم", + "order": { + "needs_review": "ترتیب: قدیمی‌ترین رویداد اول. پیش‌بینی تا تأیید ادمین باز می‌ماند.", + "open": "جدیدترین انتشار اول", + "closed": "ترتیب: جدیدترین بسته‌شدن اول.", + "flagged": "ترتیب: جدیدترین پرچم اول." + }, + "summary-order": "{{summary}} · {{order}}", + "flags-note": "پرچم‌ها داخلی‌اند و در فاز ۰ روی کارت، کارنامه و نتیجه اثری ندارند.", + "empty": { + "needs_review": { + "title": "پیشنهادی در انتظار تأیید نیست", + "description": "بستن‌های خودکار تازه پیش از انتشار اینجا منتظر تأیید می‌مانند." + }, + "open": { + "title": "پیش‌بینی بازی نیست", + "description": "پیش‌بینی‌های منتشرشده تا بسته شدن اینجا نمایش داده می‌شوند." + }, + "closed": { + "title": "هنوز پیش‌بینی‌ای بسته نشده است", + "description": "پیش‌بینی‌های بسته‌شده با نتیجه‌شان اینجا نمایش داده می‌شوند." + }, + "flagged": { + "title": "پیش‌بینی پرچم‌خورده‌ای نیست", + "description": "پیش‌بینی‌هایی که پرچم بخورند اینجا نمایش داده می‌شوند." + } + } + }, + "detail": { + "title": "جزئیات پیش‌بینی", + "channel": "کانال", + "loading": "در حال بارگذاری پیش‌بینی…", + "error": "پیش‌بینی بارگذاری نشد.", + "review": "بررسی و بستن", + "override": "اصلاح نتیجه", + "close-admin": "بستن با قیمت ادمین", + "flag": "پرچم‌گذاری", + "timeline": { + "title": "خط زمانی", + "published": "انتشار", + "published-body": "قیمت ورود ثبت‌شده {{price}} · منبع {{source}}", + "published-body-no-source": "قیمت ورود ثبت‌شده {{price}}", + "monitored": "بررسی قیمت", + "monitored-checks": "{{checks}} بررسی، هر {{interval}} دقیقه", + "monitored-target": "{{checks}} · نزدیک‌ترین به هدف {{target}}", + "monitored-nearest": "{{checks}} · نزدیک‌ترین به هدف {{target}}؛ نزدیک‌ترین به حد ضرر {{stop}}", + "until": "تا {{date}}", + "detected": "پیشنهاد بستن: {{reason}}", + "detected-body": "{{price}} · {{source}} · قیمت ساعت {{time}}", + "closed": "تأیید بستن", + "closed-corrected": "تأیید بستن با قیمت اصلاح‌شده", + "closed-admin": "بستن با قیمت ادمین", + "closed-corrected-body": "{{price}} · {{actor}}", + "dismissed": "رد پیشنهاد بستن", + "overridden": "اصلاح نتیجه", + "overridden-body": "{{from}} ← {{to}} · {{actor}}" + } + }, + "confirm": { + "title": "تأیید بستن پیش‌بینی", + "fields": { + "event": "رویداد", + "proposed": "قیمت پیشنهادی", + "recorded": "قیمت ثبت‌شده", + "source": "منبع", + "time": "زمان", + "outcome": "نتیجه", + "on-card": "روی کارت" + }, + "correct": "اصلاح قیمت", + "reject": "رد پیشنهاد", + "lock": "پس از تأیید، نتیجه روی کارت و در کارنامه تحلیلگر ثبت می‌شود و فقط با «اصلاح نتیجه» تغییر می‌کند.", + "confirm": "تأیید و بستن", + "done": "پیش‌بینی بسته شد.", + "failed": "بستن پیش‌بینی انجام نشد" + }, + "correct": { + "price": "قیمت اصلاح‌شده", + "source-fixed": "منبع ثابت است: {{source}}", + "on-card": "علت: اصلاح توسط ادمین · منبع قیمت: {{source}}", + "cancel": "لغو اصلاح", + "price-required": "قیمت اصلاح‌شده را بنویسید.", + "price-invalid": "قیمت را به‌صورت یک عدد مثبت بنویسید.", + "price-same": "قیمت اصلاح‌شده با قیمت ثبت‌شده یکی است؛ برای همین قیمت «لغو اصلاح» را بزنید.", + "done": "پیش‌بینی با قیمت اصلاح‌شده بسته شد." + }, + "reject": { + "title": "رد پیشنهاد بستن", + "banner": "پیش‌بینی باز می‌ماند و بررسی قیمت ادامه پیدا می‌کند. قیمت ثبت‌شده حذف نمی‌شود و در گزارش ممیزی می‌ماند.", + "empty": "ابتدا دلیل رد پیشنهاد را بنویسید.", + "confirm": "رد پیشنهاد", + "done": "پیشنهاد بستن رد شد.", + "failed": "رد پیشنهاد انجام نشد" + }, + "override": { + "title": "اصلاح نتیجه پیش‌بینی", + "compare": "فعلی ← پس از اصلاح", + "fields": { + "closed-price": "قیمت بسته‌شدن", + "outcome": "نتیجه", + "roi": "بازدهی" + }, + "price": "قیمت بسته‌شدن جدید", + "source-fixed": "منبع ثابت است: {{source}}", + "source-fixed-horizon": "منبع ثابت است: {{source}}، قیمت پایان افق ({{time}})", + "impact": "سرمایه‌گذاران روی کارت این پیش‌بینی می‌بینند: «علت: اصلاح توسط ادمین».", + "impact-record": "کارنامه {{name}} تغییر می‌کند: نرخ موفقیت {{before}} ← {{after}}.", + "confirm": "ثبت اصلاح", + "price-required": "قیمت بسته‌شدن را بنویسید.", + "price-invalid": "قیمت را به‌صورت یک عدد مثبت بنویسید.", + "price-same": "قیمت جدید با قیمت بسته‌شدن فعلی یکی است.", + "done": "نتیجه اصلاح شد.", + "failed": "اصلاح نتیجه انجام نشد" + }, + "close-admin": { + "title": "بستن پیش‌بینی با قیمت ادمین", + "compare": "پس از بستن", + "fields": { + "entry": "قیمت ورود" + }, + "price": "قیمت بسته‌شدن", + "hint": "زمان بسته‌شدن همین لحظه ثبت می‌شود.", + "impact": "پیش‌بینی با این قیمت بسته می‌شود و دوباره باز نمی‌شود. سرمایه‌گذاران روی کارت می‌بینند: «علت: اصلاح توسط ادمین» و تحلیلگر و دنبال‌کنندگان اعلان بسته‌شدن می‌گیرند.", + "impact-pending": "پیشنهاد بستن در انتظار این پیش‌بینی هم کنار گذاشته می‌شود.", + "confirm": "بستن پیش‌بینی", + "done": "پیش‌بینی با قیمت ادمین بسته شد.", + "failed": "بستن پیش‌بینی انجام نشد" + }, + "flag": { + "title": "پرچم‌گذاری پیش‌بینی", + "banner": "پرچم‌ها داخلی‌اند: روی کارت، کارنامه و نتیجهٔ این پیش‌بینی اثری ندارند و فقط ادمین‌ها آن‌ها را می‌بینند.", + "reason": "دلیل", + "reason-label": "دلیل پرچم", + "note": "توضیح", + "note-hint": "اختیاری؛ با «سایر» الزامی است (حداقل ۱۰ نویسه). فقط ادمین‌ها آن را می‌بینند.", + "empty": "ابتدا دلیل پرچم را انتخاب کنید.", + "confirm": "ثبت پرچم", + "reason-required": "دلیل پرچم را انتخاب کنید.", + "note-required": "با «سایر»، توضیح را بنویسید.", + "note-short": "توضیح باید دست‌کم ۱۰ نویسه باشد.", + "done": "پرچم ثبت شد.", + "failed": "ثبت پرچم انجام نشد" + }, + "unflag": { + "done": "پرچم برداشته شد.", + "failed": "برداشتن پرچم انجام نشد" + }, + "conflict": "این پیش‌بینی پیش‌تر بسته یا بررسی شده است؛ اطلاعات به‌روز شد.", + "card": { + "status": { + "open": "فعال", + "win": "موفق", + "loss": "ناموفق", + "breakeven": "سربه‌سر" + }, + "premium": "پریمیوم", + "horizon": "افق {{horizon}}", + "days-left": "{{days}} روز مانده", + "under-days": "کمتر از {{days}} روز مانده", + "roi": "بازدهی", + "closed-price": "بسته‌شدن", + "held-for": "پس از {{duration}}", + "to-target": "تا هدف", + "to-final-target": "تا هدف نهایی", + "to-stop": "تا حد ضرر", + "risk-reward": "ریسک به ریوارد", + "levels": { + "stop": "حد ضرر", + "entry": "ورود", + "base": "مبنا", + "target": "هدف", + "target-n": "هدف {{n}}", + "final-target": "هدف نهایی", + "close": "بسته‌شدن", + "horizon": "افق" + }, + "ladder": { + "level": "سطح", + "price": "قیمت", + "change": "تغییر از ورود", + "state": "وضعیت", + "reached": "رسید", + "missed": "نرسید", + "triggered": "فعال شد", + "not-triggered": "فعال نشد" + }, + "range": { + "label": "محدوده پیش‌بینی: {{values}}", + "stop": "حد ضرر {{price}}", + "entry": "ورود {{price}}", + "target": "هدف {{price}}", + "target-n": "هدف {{n}} {{price}}", + "close": "بسته‌شدن {{price}}" + }, + "horizon-elapsed": "گذشته از افق: {{duration}}", + "horizon-end": "پایان افق: {{date}}", + "horizon-progress": "زمان سپری‌شده از افق", + "seal": "ثبت‌شده در", + "immutable": "غیرقابل ویرایش", + "close-reason": { + "label": "علت:", + "target": "رسیدن به هدف", + "final-target": "رسیدن به هدف نهایی", + "stop": "فعال‌شدن حد ضرر", + "horizon": "پایان افق", + "early": "بستن زودهنگام تحلیلگر", + "admin": "اصلاح توسط ادمین", + "price-source": "منبع قیمت:" + }, + "locked": { + "title": "پیش‌بینی پریمیوم", + "description": "دارایی، جهت، ورود، اهداف و حد ضرر پنهان است.", + "hidden": "پنهان", + "content": "محتوای پریمیوم" + } + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/subscriptions.json b/platforms/garden-roof/src/shared/locales/fa/subscriptions.json new file mode 100644 index 0000000..36e32f4 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/subscriptions.json @@ -0,0 +1,183 @@ +{ + "currency": "تومان", + "list": { + "title": "اشتراک‌ها", + "meta-title": "اشتراک‌ها", + "search": "نام کاربری، شماره موبایل یا شماره پیگیری", + "grant": "اعطای دسترسی", + "filters-label": "فیلتر اشتراک‌ها", + "filters": { + "active": "فعال", + "expired": "منقضی‌شده", + "refunded": "بازگشت وجه", + "grant": "اعطای دستی" + }, + "table-label": "اشتراک‌ها", + "columns": { + "investor": "مشترک", + "analyst": "تحلیلگر", + "period": "دوره", + "started": "شروع", + "ends": "انقضا", + "status": "وضعیت", + "source": "منبع", + "open": "باز کردن" + }, + "sources": { + "payment": "پرداخت", + "grant": "اعطای دستی" + }, + "open-row": "جزئیات اشتراک {{investor}} در کانال {{analyst}}", + "summary": "{{range}} · جدیدترین شروع اول", + "loading": "در حال بارگذاری اشتراک‌ها…", + "error": "فهرست اشتراک‌ها بارگذاری نشد.", + "empty": { + "none": { + "title": "هنوز اشتراکی ثبت نشده است", + "description": "اشتراک‌های پرداخت‌شده و دسترسی‌های اعطاشده اینجا نمایش داده می‌شوند." + }, + "search": { + "title": "نتیجه‌ای پیدا نشد", + "description": "نام کاربری، شماره موبایل یا شماره پیگیری دیگری را جستجو کنید یا فیلترها را تغییر دهید.", + "clear": "پاک کردن جستجو و فیلترها" + } + } + }, + "detail": { + "title": "جزئیات اشتراک", + "close": "بستن جزئیات اشتراک", + "loading": "در حال بارگذاری جزئیات اشتراک…", + "error": "جزئیات اشتراک بارگذاری نشد.", + "gone": "این اشتراک دیگر پیدا نمی‌شود.", + "remaining": "{{days}} روز مانده", + "source": "منبع: {{source}}", + "fields": { + "investor": "مشترک", + "phone": "شماره موبایل", + "analyst": "تحلیلگر", + "period": "دوره", + "started": "شروع", + "ends": "انقضا", + "ended": "پایان", + "access": "دسترسی", + "grant-reason": "دلیل اعطا", + "grant-note": "توضیح" + }, + "previous-ends": "انقضای قبلی: {{date}}", + "phone-private": "فقط برای ادمین", + "access": { + "open": "باز", + "closed": "بسته", + "suspended": "بسته تا رفع تعلیق کانال" + }, + "payment": { + "title": "پرداخت", + "title-refunded": "پرداخت و بازگشت وجه", + "missing": "پرداختی برای این اشتراک ثبت نشده است.", + "new": "اشتراک جدید", + "unchanged": "{{date}} · بدون تغییر", + "reference": "کد پیگیری {{reference}}", + "refund": "بازگشت وجه", + "refund-reference": "شماره پیگیری انتقال {{reference}}", + "refund-sheba": "شبای مقصد" + }, + "grant": { + "title": "اعطای دستی", + "description": "بدون پرداخت؛ در تراکنش‌های کاربر ثبت نمی‌شود و در گزارش ممیزی می‌ماند." + }, + "extend": "تمدید دستی", + "refund": "بازگشت وجه", + "audit-empty": "هنوز اقدامی روی این اشتراک ثبت نشده است." + }, + "dialog": { + "plan": "اشتراک {{period}} {{analyst}}" + }, + "extend": { + "title": "تمدید دستی", + "current": "انقضای فعلی", + "days-label": "مدت تمدید", + "days": "{{days}} روز", + "new": "انقضای جدید", + "notice": "مشترک اعلان «اشتراک شما به مدت {{days}} روز تمدید شد» را می‌بیند. مبلغی دریافت یا بازگردانده نمی‌شود.", + "confirm": "تمدید اشتراک", + "empty": "ابتدا دلیل تمدید را بنویسید.", + "done": "اشتراک {{days}} روز تمدید شد.", + "failed": "اشتراک تمدید نشد", + "not-running": "این اشتراک دیگر فعال نیست و تمدید نمی‌شود." + }, + "refund": { + "title": "بازگشت وجه", + "paid": "پرداخت", + "paid-at": "تاریخ پرداخت", + "reference": "کد پیگیری", + "amount": "مبلغ بازگشت", + "amount-hint": "پیش‌فرض: کل مبلغ پرداخت ({{amount}} تومان)؛ بیشتر از آن مجاز نیست.", + "currency": "تومان", + "sheba": "شبای مقصد", + "bank-reference": "شماره پیگیری بانک", + "bank-reference-hint": "در فاز ۰ مبلغ پیش از ثبت، با انتقال بانکی واریز می‌شود.", + "impact": { + "title": "با ثبت بازگشت وجه:", + "access": "دسترسی سرمایه‌گذار همین حالا قطع می‌شود.", + "transaction": "ردیف «بازگشت وجه» ({{amount}} تومان) در تراکنش‌های او ثبت می‌شود.", + "card": "کارت اشتراک «پایان یافته · بازگشت وجه» می‌شود و پیامک ارسال می‌شود.", + "deduction": "{{amount}} تومان (سهم تحلیلگر) از موجودی {{analyst}} کسر می‌شود." + }, + "confirm": "بازگشت وجه و پایان اشتراک", + "empty": "ابتدا دلیل بازگشت وجه را بنویسید.", + "done": "بازگشت وجه ثبت شد و اشتراک پایان یافت.", + "failed": "بازگشت وجه ثبت نشد", + "already-refunded": "وجه این اشتراک پیش‌تر بازگردانده شده است.", + "not-paid": "این اشتراک پرداخت ثبت‌شده‌ای ندارد و وجهی برای بازگشت نیست.", + "errors": { + "amount-required": "مبلغ بازگشت را بنویسید.", + "amount-invalid": "مبلغ را فقط با رقم و به تومان بنویسید.", + "amount-min": "مبلغ بازگشت باید بیشتر از صفر باشد.", + "amount-max": "مبلغ بازگشت نمی‌تواند بیشتر از مبلغ پرداخت باشد.", + "amount-over": "مبلغ بازگشت نمی‌تواند بیشتر از مبلغ پرداخت ({{amount}} تومان) باشد.", + "sheba-required": "شبای مقصد را بنویسید.", + "sheba-length": "شبا بعد از IR باید ۲۴ رقم داشته باشد.", + "sheba-invalid": "این شبا معتبر نیست؛ رقم‌ها را دوباره بررسی کنید.", + "bank-reference-required": "شماره پیگیری بانک را بنویسید.", + "bank-reference-invalid": "شماره پیگیری فقط رقم و حرف لاتین دارد." + } + }, + "grant": { + "title": "اعطای دسترسی", + "investor": "کاربر", + "investor-placeholder": "نام کاربری یا شماره موبایل", + "analyst": "کانال", + "analyst-placeholder": "نام کاربری تحلیلگر", + "searching": "در حال جستجو…", + "period": "دوره", + "window": "دسترسی از {{from}} تا {{to}}", + "reason": "دلیل", + "reason-placeholder": "انتخاب دلیل", + "reasons": { + "unrecorded_payment": "پرداخت تأییدنشده", + "compensation": "جبران قطعی سرویس", + "beta_tester": "آزمایش‌کننده بتا", + "partnership": "همکاری و معرفی", + "other": "سایر" + }, + "note": "توضیح", + "notice": "بدون پرداخت؛ در تراکنش‌های کاربر ثبت نمی‌شود و در گزارش ممیزی می‌ماند.", + "confirm": "اعطای دسترسی", + "done": "دسترسی {{investor}} به کانال {{analyst}} تا {{date}} اعطا شد.", + "failed": "دسترسی اعطا نشد", + "errors": { + "investor-required": "نام کاربری یا شماره موبایل سرمایه‌گذار را بنویسید.", + "investor-not-found": "سرمایه‌گذاری با این نام کاربری یا شماره پیدا نشد.", + "analyst-required": "نام کاربری کانال را بنویسید.", + "analyst-not-found": "تحلیلگر تأییدشده و فعالی با این نام کاربری پیدا نشد.", + "period-required": "دوره دسترسی را انتخاب کنید.", + "tier-missing": "این کانال پلن {{period}} ندارد؛ دوره دیگری انتخاب کنید.", + "reason-required": "دلیل اعطای دسترسی را انتخاب کنید.", + "note-required": "توضیح را بنویسید.", + "note-short": "توضیح باید دست‌کم ۱۰ نویسه باشد.", + "note-long": "توضیح نباید بیشتر از ۵۰۰ نویسه باشد.", + "already-subscribed": "{{name}} همین حالا اشتراک فعال این کانال را دارد.", + "person-gone": "کاربر یا کانال دیگر قابل اعطا نیست؛ هر دو را دوباره بررسی کنید." + } + } +} diff --git a/platforms/garden-roof/src/shared/locales/fa/verification.json b/platforms/garden-roof/src/shared/locales/fa/verification.json new file mode 100644 index 0000000..a2f1e72 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/fa/verification.json @@ -0,0 +1,137 @@ +{ + "queue": { + "title": "احراز هویت تحلیلگران", + "meta-title": "احراز هویت تحلیلگران", + "tabs-label": "فیلتر وضعیت درخواست‌ها", + "tabs": { + "pending": "در انتظار بررسی", + "approved": "تأییدشده", + "rejected": "رد شده" + }, + "search": "جستجو بر اساس نام، نام کاربری یا شماره موبایل", + "sort-label": "ترتیب درخواست‌ها", + "sort": { + "asc": "تاریخ ارسال: قدیمی‌ترین اول", + "desc": "تاریخ ارسال: جدیدترین اول" + }, + "sort-options": { + "asc": "قدیمی‌ترین اول", + "desc": "جدیدترین اول" + }, + "table-label": "درخواست‌های احراز هویت", + "columns": { + "name": "نام و نام خانوادگی", + "username": "نام کاربری", + "phone": "شماره موبایل", + "submitted": "تاریخ ارسال", + "status": "وضعیت", + "open": "باز کردن" + }, + "open-row": "باز کردن درخواست {{name}}", + "loading": "در حال بارگذاری درخواست‌ها…", + "error": "فهرست درخواست‌ها بارگذاری نشد.", + "empty": { + "pending": { + "title": "درخواستی در صف بررسی نیست", + "description": "درخواست‌های تازه احراز هویت اینجا نمایش داده می‌شوند." + }, + "approved": { + "title": "هنوز درخواستی تأیید نشده است", + "description": "درخواست‌های تأییدشده اینجا نمایش داده می‌شوند." + }, + "rejected": { + "title": "درخواست رد‌شده‌ای نیست", + "description": "درخواست‌های رد‌شده اینجا نمایش داده می‌شوند." + }, + "search": { + "title": "نتیجه‌ای پیدا نشد", + "description": "نام، نام کاربری یا شماره دیگری را جستجو کنید.", + "clear": "پاک کردن جستجو" + } + } + }, + "review": { + "title": "بررسی درخواست احراز هویت", + "meta-title": "بررسی درخواست احراز هویت", + "back": "بازگشت به صف احراز هویت", + "position": "{{position}} از {{total}}", + "previous": "درخواست قبلی", + "next": "درخواست بعدی", + "first": "این اولین درخواست در صف است.", + "last": "این آخرین درخواست در صف است.", + "loading": "در حال بارگذاری درخواست…", + "error": "درخواست بارگذاری نشد.", + "fields": { + "name": "نام و نام خانوادگی", + "username": "نام کاربری", + "phone": "شماره موبایل", + "submitted": "تاریخ ارسال", + "status": "وضعیت", + "reason": "دلیل رد" + }, + "suspended": "این حساب در حال حاضر توسط ادمین تعلیق شده است. تأیید هویت، تعلیق را لغو نمی‌کند.", + "approve": "تأیید", + "reject": "رد کردن", + "image": { + "title": "تصویر کارت ملی", + "alt": "روی کارت ملی {{name}}", + "view": "مشاهده تصویر کامل", + "download": "دانلود تصویر", + "loading": "تصویر هنوز بارگذاری نشده است.", + "frozen": "برای تأیید یا رد درخواست، ابتدا باید تصویر کارت ملی بارگذاری شود.", + "failed": "بارگذاری تصویر ناموفق بود", + "failed-description": "تصویر کارت ملی دریافت نشد. دوباره تلاش کنید.", + "retry": "تلاش مجدد", + "alt-back": "پشت کارت ملی {{name}}" + }, + "history": { + "title": "تاریخچه ارسال‌های قبلی", + "rejected": "رد شد", + "reason": "دلیل رد درخواست: {{reason}}", + "submitted": "ارسال‌شده در {{date}}" + }, + "already-decided": "این درخواست در این فاصله بررسی شده است؛ اطلاعات به‌روز شد.", + "lightbox": { + "dialog": "تصویر کارت ملی", + "close": "بستن", + "back": "بازگشت", + "previous": "تصویر قبلی", + "next": "تصویر بعدی", + "zoom-in": "بزرگ‌نمایی", + "zoom-out": "کوچک‌نمایی", + "download": "دانلود" + } + }, + "approve": { + "title": "تأیید درخواست", + "description": "آیا از تأیید هویت این تحلیلگر اطمینان دارید؟", + "description-suspended": "این حساب در حال حاضر تعلیق شده است. تأیید هویت، تعلیق را لغو نمی‌کند و حساب تا رفع تعلیق غیرفعال می‌ماند. آیا ادامه می‌دهید؟", + "confirm": "بله، تأیید کن", + "done": "حساب تحلیلگر با موفقیت تأیید شد.", + "failed": "تأیید درخواست انجام نشد" + }, + "reject": { + "title": "رد درخواست احراز هویت", + "field": "دلیل رد درخواست", + "placeholder": "دلیل رد را بنویسید یا از پیش‌فرض‌های زیر انتخاب کنید...", + "templates-label": "انتخاب دلیل پیش‌فرض", + "templates": { + "mismatch": { + "label": "عدم تطابق اطلاعات", + "text": "اطلاعات وارد‌شده با مدارک ارسالی مطابقت ندارد." + }, + "unreadable": { + "label": "تصویر ناخوانا", + "text": "تصویر کارت ملی ارسال‌شده واضح نیست. لطفاً تصویر با کیفیت بالاتر ارسال کنید." + }, + "incomplete": { + "label": "مدرک ناقص", + "text": "مدارک ارسال‌شده کامل نیست. لطفاً تصویر کامل کارت ملی را ارسال کنید." + } + }, + "empty": "ابتدا دلیل رد درخواست را بنویسید.", + "confirm": "رد کردن و اطلاع‌رسانی", + "done": "درخواست رد شد و تحلیلگر مطلع گردید.", + "failed": "رد درخواست انجام نشد" + } +} diff --git a/platforms/garden-roof/src/shared/locales/index.ts b/platforms/garden-roof/src/shared/locales/index.ts new file mode 100644 index 0000000..6e4fc78 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/index.ts @@ -0,0 +1,8 @@ +import './types'; + +export { + DEFAULT_LOCALE, + DEFAULT_NAMESPACE, + NAMESPACES, + resources, +} from './resources'; diff --git a/platforms/garden-roof/src/shared/locales/resources.ts b/platforms/garden-roof/src/shared/locales/resources.ts new file mode 100644 index 0000000..99d33f1 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/resources.ts @@ -0,0 +1,36 @@ +import faAnalysts from './fa/analysts.json'; +import faAuth from './fa/auth.json'; +import faCodes from './fa/codes.json'; +import faCommon from './fa/common.json'; +import faErrors from './fa/errors.json'; +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 faSubscriptions from './fa/subscriptions.json'; +import faVerification from './fa/verification.json'; + +/** The admin panel is Persian only; every route loads every namespace, because any route can fail. */ +export const DEFAULT_LOCALE = 'fa'; + +export const DEFAULT_NAMESPACE = 'common'; + +export const resources = { + fa: { + common: faCommon, + errors: faErrors, + auth: faAuth, + health: faHealth, + verification: faVerification, + analysts: faAnalysts, + codes: faCodes, + subscriptions: faSubscriptions, + predictions: faPredictions, + payouts: faPayouts, + featured: faFeatured, + }, +} as const; + +export const NAMESPACES = Object.keys( + resources.fa, +) as (keyof typeof resources.fa)[]; diff --git a/platforms/garden-roof/src/shared/locales/types.ts b/platforms/garden-roof/src/shared/locales/types.ts new file mode 100644 index 0000000..ae0ad72 --- /dev/null +++ b/platforms/garden-roof/src/shared/locales/types.ts @@ -0,0 +1,9 @@ +import type { DEFAULT_NAMESPACE, resources } from './resources'; + +// Types every `t` call against the Persian resources, so a missing key fails type-check. +declare module 'i18next' { + interface CustomTypeOptions { + defaultNS: typeof DEFAULT_NAMESPACE; + resources: (typeof resources)['fa']; + } +} diff --git a/platforms/garden-roof/src/shared/utils/api-url.ts b/platforms/garden-roof/src/shared/utils/api-url.ts new file mode 100644 index 0000000..cf1bcde --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/api-url.ts @@ -0,0 +1,37 @@ +import { getEnv } from '../../env'; + +/** + * Uploads the gateway stored with a host before it stored paths (`/uploads/…`). That host is the + * gateway's or, behind the proxy, an app's, so the path is what counts. Remove once the back + * end's `scripts/migrate-upload-urls-to-relative.js --apply` has run everywhere. + */ +const LEGACY_UPLOAD_PATH = /^\/uploads\//; + +/** An absolute address's path and query when it is a legacy upload, else `null`. */ +function legacyUploadPath(address: string): string | null { + try { + const url = new URL(address); + return LEGACY_UPLOAD_PATH.test(url.pathname) + ? `${url.pathname}${url.search}` + : null; + } catch { + return null; + } +} + +/** + * A path the admin API returns (`/v1/admin/verifications/…/id-images/front`, `/uploads/avatars/…`) → the URL the browser + * loads it from, through this site's API proxy (0061), so private files get the session cookie: + * `/api/v1/admin/…`. Other absolute addresses (another site's, a CDN's) pass through, as does one + * that isn't a valid URL; empty stays `null`. Reads env inside the call, so bootstrap has always + * run. + */ +export function toApiUrl(path: string | null | undefined): string | null { + if (!path) return null; + const { apiBaseUrl } = getEnv(); + if (/^[a-z][a-z\d+\-.]*:/i.test(path)) { + const legacy = legacyUploadPath(path); + return legacy ? `${apiBaseUrl}${legacy}` : path; + } + return `${apiBaseUrl}${path.startsWith('/') ? '' : '/'}${path}`; +} diff --git a/platforms/garden-roof/src/shared/utils/apply-server-errors.ts b/platforms/garden-roof/src/shared/utils/apply-server-errors.ts new file mode 100644 index 0000000..508c08e --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/apply-server-errors.ts @@ -0,0 +1,55 @@ +import { classifyError, describeError } from '@lumina/libs/error-handler'; +import { isHttpError } from '@lumina/libs/http'; +import type { FieldValues, Path, UseFormReturn } from 'react-hook-form'; + +import { showActionError } from './show-action-error'; +import { asTranslateFn } from './translate-message'; +import type { ShowActionErrorOptions } from './show-action-error'; + +/** + * A failed form submission: each server field error goes under its field (the first one gets + * focus), field errors for fields the form doesn't render and errors about the whole submission go + * to the form alert (`root.server`), then the action-error toast. A field counts as rendered when + * it has a value, so every form sets `defaultValues` for every field. The form keeps every value. + */ +export function applyServerErrors( + form: UseFormReturn, + error: unknown, + options: ShowActionErrorOptions, +): void { + if (classifyError(error).action === 'silent') return; + + const unmatched: string[] = []; + let hasFieldError = false; + const fieldErrors = isHttpError(error) ? (error.fieldErrors ?? {}) : {}; + for (const [field, message] of Object.entries(fieldErrors)) { + if (form.getValues(field as Path) === undefined) { + unmatched.push(message); + continue; + } + form.setError( + field as Path, + { type: 'server', message }, + { shouldFocus: !hasFieldError }, + ); + hasFieldError = true; + } + + if (!hasFieldError && unmatched.length === 0) { + const t = asTranslateFn(options.t); + // The form alert says what to do; the toast keeps the technical message. + unmatched.push( + isHttpError(error) && error.code === 'NETWORK_ERROR' + ? t('errors:form.network') + : (describeError(error, t).message ?? options.failedMessage), + ); + } + if (unmatched.length > 0) { + form.setError('root.server', { + type: 'server', + message: unmatched.join(' '), + }); + } + + showActionError(error, options); +} diff --git a/platforms/garden-roof/src/shared/utils/first-of-each.ts b/platforms/garden-roof/src/shared/utils/first-of-each.ts new file mode 100644 index 0000000..a67e666 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/first-of-each.ts @@ -0,0 +1,16 @@ +/** + * Each item of a paged list once, where it first shows. Pages are read by offset at different + * times, so an item added or moved between two reads comes back on the next page. + */ +export function firstOfEach( + items: readonly T[], + keyOf: (item: T) => string, +): T[] { + const seen = new Set(); + return items.filter((item) => { + const key = keyOf(item); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} diff --git a/platforms/garden-roof/src/shared/utils/index.ts b/platforms/garden-roof/src/shared/utils/index.ts new file mode 100644 index 0000000..964b946 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/index.ts @@ -0,0 +1,18 @@ +export { applyServerErrors } from './apply-server-errors'; +export { toApiUrl } from './api-url'; +export { firstOfEach } from './first-of-each'; +export { isConnectionError } from './is-connection-error'; +export { listHref, oneOf, pageOf } from './list-params'; +export { loadMoreErrorKind } from './load-more-error-kind'; +export type { LoadMoreErrorKind } from './load-more-error-kind'; +export { formatMobile, toE164Mobile, toLocalMobile } from './mobile'; +export { renameFieldErrors } from './rename-field-errors'; +export { showActionError } from './show-action-error'; +export type { ShowActionErrorOptions } from './show-action-error'; +export { asTranslateFn, translateMessage } from './translate-message'; +export type { AnyTranslate } from './translate-message'; +export { useDebouncedValue } from './use-debounced-value'; +export { useListSearch } from './use-list-search'; +export type { ListSearch } from './use-list-search'; +export { useReasonForm } from './use-reason-form'; +export type { ReasonForm } from './use-reason-form'; diff --git a/platforms/garden-roof/src/shared/utils/is-connection-error.ts b/platforms/garden-roof/src/shared/utils/is-connection-error.ts new file mode 100644 index 0000000..84ffec0 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/is-connection-error.ts @@ -0,0 +1,9 @@ +import { isHttpError } from '@lumina/libs/http'; + +/** The request never got an answer: the connection dropped or our time limit passed. */ +export function isConnectionError(error: unknown): boolean { + return ( + isHttpError(error) && + (error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT') + ); +} diff --git a/platforms/garden-roof/src/shared/utils/list-params.ts b/platforms/garden-roof/src/shared/utils/list-params.ts new file mode 100644 index 0000000..684e57f --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/list-params.ts @@ -0,0 +1,34 @@ +/** + * A list's address with some query parameters changed: `null` or '' removes one. Any change but + * the page itself starts again from page 1, as a new tab, search or sort does (J11-2). + */ +export function listHref( + pathname: string, + current: URLSearchParams, + changes: Record, + { pageParam = 'page' }: { pageParam?: string } = {}, +): string { + const params = new URLSearchParams(current.toString()); + for (const [key, value] of Object.entries(changes)) { + if (value === null || value === '') params.delete(key); + else params.set(key, String(value)); + } + if (!(pageParam in changes)) params.delete(pageParam); + if (params.get(pageParam) === '1') params.delete(pageParam); + const query = params.toString(); + return query ? `${pathname}?${query}` : pathname; +} + +/** A page number from the URL: a whole number from 1, else 1. */ +export function pageOf(value: string | null): number { + const page = Number(value); + return Number.isInteger(page) && page >= 1 ? page : 1; +} + +/** One of `allowed` from the URL, else the first. */ +export function oneOf( + value: string | null, + allowed: readonly T[], +): T { + return allowed.find((item) => item === value) ?? allowed[0]; +} diff --git a/platforms/garden-roof/src/shared/utils/load-more-error-kind.ts b/platforms/garden-roof/src/shared/utils/load-more-error-kind.ts new file mode 100644 index 0000000..291b402 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/load-more-error-kind.ts @@ -0,0 +1,15 @@ +import type { ErrorKind } from '@lumina/island/molecules/error-state'; +import { isHttpError } from '@lumina/libs/http'; + +/** Why an older page failed, as its inline row says: our time limit, the connection, or else. */ +export type LoadMoreErrorKind = Extract< + ErrorKind, + 'timeout' | 'network' | 'error' +>; + +/** How a failed page read is told: our time limit, the connection, or anything else. */ +export function loadMoreErrorKind(error: unknown): LoadMoreErrorKind { + if (isHttpError(error) && error.code === 'TIMEOUT') return 'timeout'; + if (isHttpError(error) && error.code === 'NETWORK_ERROR') return 'network'; + return 'error'; +} diff --git a/platforms/garden-roof/src/shared/utils/mobile.ts b/platforms/garden-roof/src/shared/utils/mobile.ts new file mode 100644 index 0000000..a2e0437 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/mobile.ts @@ -0,0 +1,34 @@ +import { latinDigits } from '@lumina/tools/format'; + +const MOBILE_PATTERN = /^(?:\+98|0098|98|0)?(9\d{9})$/; + +/** Latin digits without spaces, dashes or brackets. */ +function bareDigits(value: string): string { + return latinDigits(value).replace(/[\s()-]/g, ''); +} + +/** + * An Iranian mobile number as typed (`۰۹۱۲ ۳۴۵ ۶۷۸۹`, `0912…`, `+98912…`, `98912…`) → E.164 + * (`+989123456789`), the one form the API stores. Anything else is returned trimmed, so the + * server can reject it with its own message. + */ +export function toE164Mobile(value: string): string { + const digits = bareDigits(value); + const match = MOBILE_PATTERN.exec(digits); + return match ? `+98${match[1]}` : digits; +} + +/** The same number in its local form (`09123456789`), the one the pages keep. Anything else: its bare digits. */ +export function toLocalMobile(value: string): string { + const digits = bareDigits(value); + const match = MOBILE_PATTERN.exec(digits); + return match ? `0${match[1]}` : digits; +} + +/** `09123456789` → `0912 345 6789`, shown left to right; the font draws the digits in Persian. */ +export function formatMobile(value: string): string { + const local = toLocalMobile(value); + return /^09\d{9}$/.test(local) + ? `${local.slice(0, 4)} ${local.slice(4, 7)} ${local.slice(7)}` + : value; +} diff --git a/platforms/garden-roof/src/shared/utils/rename-field-errors.ts b/platforms/garden-roof/src/shared/utils/rename-field-errors.ts new file mode 100644 index 0000000..7a27316 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/rename-field-errors.ts @@ -0,0 +1,19 @@ +import { HttpError, isHttpError } from '@lumina/libs/http'; + +/** + * Renames an error's server field names to the caller's `*Args` names (`phone_number` → `phone`), + * so a form can put each message under its own field. Anything else passes through unchanged. + */ +export function renameFieldErrors( + error: unknown, + names: Readonly>, +): unknown { + if (!isHttpError(error) || !error.fieldErrors) return error; + const fieldErrors = Object.fromEntries( + Object.entries(error.fieldErrors).map(([field, message]) => [ + names[field] ?? field, + message, + ]), + ); + return new HttpError({ ...error.toJSON(), fieldErrors, cause: error }); +} diff --git a/platforms/garden-roof/src/shared/utils/show-action-error.ts b/platforms/garden-roof/src/shared/utils/show-action-error.ts new file mode 100644 index 0000000..688f71d --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/show-action-error.ts @@ -0,0 +1,50 @@ +import { showToast } from '@lumina/island/molecules/toast'; +import { describeError, handleError } from '@lumina/libs/error-handler'; + +import { asTranslateFn } from './translate-message'; +import type { AnyTranslate } from './translate-message'; + +export type ShowActionErrorOptions = { + t: AnyTranslate; + /** What failed, naming the object: «کد تأیید ارسال نشد». */ + failedMessage: string; + /** Only when running the action again is safe. */ + retry?: () => void; + /** Refetches the data the action changed, for 409 and 404. */ + reload?: () => void; +}; + +/** + * The one error toast for a failed action. It handles the error once, says what failed, adds the + * server's message and hint (or a support sentence with the reference code), and offers the button + * the error's retry kind allows. It closes after 8 seconds (10 with its button), paused while + * hovered or focused (0019); a repeated failure replaces it, as every new toast does. + */ +export function showActionError( + error: unknown, + { t: anyT, failedMessage, retry, reload }: ShowActionErrorOptions, +): void { + const t = asTranslateFn(anyT); + const errorClass = handleError(error, { where: 'action' }); + if (errorClass.action === 'silent') return; + + const { message, hint, referenceId } = describeError(error, t); + const details = [message, hint].filter(Boolean).join(' '); + const action = + errorClass.retry === 'again' && retry + ? { label: t('errors:action.try-again'), onClick: retry } + : errorClass.retry === 'reload' && reload + ? { label: t('errors:action.reload'), onClick: reload } + : undefined; + + showToast({ + tone: 'error', + message: failedMessage, + description: + details || + (referenceId + ? t('errors:support.with-reference', { referenceId }) + : t('errors:support.without-reference')), + action, + }); +} diff --git a/platforms/garden-roof/src/shared/utils/translate-message.ts b/platforms/garden-roof/src/shared/utils/translate-message.ts new file mode 100644 index 0000000..36081c4 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/translate-message.ts @@ -0,0 +1,27 @@ +import type { TranslateFn } from '@lumina/libs/error-handler'; + +/** + * i18next's `t` from `useTranslation`, for any namespace. Its key types reject the keys the error + * handler passes (`errors:http.network`), so the helpers here take it untyped. + */ +export type AnyTranslate = (...args: never[]) => unknown; + +export function asTranslateFn(t: AnyTranslate): TranslateFn { + return t as unknown as TranslateFn; +} + +/** `auth:validation.phone-invalid`, `errors:auth.code-invalid`: a namespace, a colon and a dotted key. */ +const KEY_PATTERN = /^[a-z]+:[\w.-]+$/; + +/** + * A form message as the field shows it. Validation messages and mapped server errors are i18n + * keys and get translated; any other server text is already the user's language and passes + * through. + */ +export function translateMessage( + t: AnyTranslate, + message: string | undefined, +): string | undefined { + if (!message) return undefined; + return KEY_PATTERN.test(message) ? asTranslateFn(t)(message) : message; +} diff --git a/platforms/garden-roof/src/shared/utils/use-debounced-value.ts b/platforms/garden-roof/src/shared/utils/use-debounced-value.ts new file mode 100644 index 0000000..f8b1038 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/use-debounced-value.ts @@ -0,0 +1,11 @@ +import { useEffect, useState } from 'react'; + +/** `value` once it stopped changing for `delayMs`, such as a search typed into a list. */ +export function useDebouncedValue(value: T, delayMs: number): T { + const [settled, setSettled] = useState(value); + useEffect(() => { + const timer = window.setTimeout(() => setSettled(value), delayMs); + return () => window.clearTimeout(timer); + }, [value, delayMs]); + return settled; +} diff --git a/platforms/garden-roof/src/shared/utils/use-list-search.ts b/platforms/garden-roof/src/shared/utils/use-list-search.ts new file mode 100644 index 0000000..59e56e3 --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/use-list-search.ts @@ -0,0 +1,51 @@ +import { usePathname, useRouter, useSearchParams } from 'next/navigation'; +import { useEffect, useRef, useState } from 'react'; + +import { SEARCH_DELAY_MS } from '../constants'; +import { listHref } from './list-params'; + +export type ListSearch = { + /** What the field shows now. */ + value: string; + setValue: (value: string) => void; + /** What the list is filtered by: the URL's `q`, once typing paused. */ + query: string; +}; + +/** + * A list's search field, kept in the URL as `q` (and back to page 1) once typing pauses, so a + * search survives a reload and the back button. The field shows what was typed at once. + */ +export function useListSearch(param = 'q'): ListSearch { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const query = searchParams.get(param) ?? ''; + const [value, setValue] = useState(query); + const lastPushed = useRef(query); + + // Back or a tab link changed the URL: the field follows it. + useEffect(() => { + if (query !== lastPushed.current) { + lastPushed.current = query; + setValue(query); + } + }, [query]); + + useEffect(() => { + const next = value.trim(); + if (next === lastPushed.current) return; + const timer = window.setTimeout(() => { + lastPushed.current = next; + router.replace( + listHref(pathname, new URLSearchParams(window.location.search), { + [param]: next, + }), + { scroll: false }, + ); + }, SEARCH_DELAY_MS); + return () => window.clearTimeout(timer); + }, [value, param, pathname, router]); + + return { value, setValue, query }; +} diff --git a/platforms/garden-roof/src/shared/utils/use-reason-form.ts b/platforms/garden-roof/src/shared/utils/use-reason-form.ts new file mode 100644 index 0000000..08b284a --- /dev/null +++ b/platforms/garden-roof/src/shared/utils/use-reason-form.ts @@ -0,0 +1,20 @@ +import { valibotResolver } from '@hookform/resolvers/valibot'; +import { useForm } from 'react-hook-form'; +import type { UseFormReturn } from 'react-hook-form'; + +import { reasonSchema } from '../validations/reason-validations'; +import type { ReasonFormOutput, ReasonFormValues } from '../validations/types'; + +export type ReasonForm = UseFormReturn< + ReasonFormValues, + unknown, + ReasonFormOutput +>; + +/** The «دلیل» form every access or money change asks for (J11 §0.5): trimmed, 10 characters at least. */ +export function useReasonForm(): ReasonForm { + return useForm({ + resolver: valibotResolver(reasonSchema), + defaultValues: { reason: '' }, + }); +} diff --git a/platforms/garden-roof/src/shared/validations/auth-validations.ts b/platforms/garden-roof/src/shared/validations/auth-validations.ts new file mode 100644 index 0000000..0b4d359 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/auth-validations.ts @@ -0,0 +1,16 @@ +import * as v from 'valibot'; + +import { mobileNumber } from './base-validations'; +import { CODE_PATTERN } from './constants'; + +export const phoneSchema = v.object({ + phone: mobileNumber('auth:validation.phone-invalid'), +}); + +export const codeSchema = v.object({ + code: v.pipe( + v.string(), + v.nonEmpty('auth:validation.code-required'), + v.regex(CODE_PATTERN, 'auth:validation.code-invalid'), + ), +}); diff --git a/platforms/garden-roof/src/shared/validations/base-validations.ts b/platforms/garden-roof/src/shared/validations/base-validations.ts new file mode 100644 index 0000000..db33998 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/base-validations.ts @@ -0,0 +1,23 @@ +import * as v from 'valibot'; + +import { toLocalMobile } from '../utils/mobile'; +import { REASON_MAX_LENGTH, REASON_MIN_LENGTH } from './constants'; + +// Every message is an i18n key; the field translates it. + +export const requiredString = (message: string) => + v.pipe(v.string(), v.trim(), v.nonEmpty(message)); + +/** Any way a mobile number is typed (Persian digits, +98, spaces) → `09XXXXXXXXX`. */ +export const mobileNumber = (message: string) => + v.pipe(v.string(), v.transform(toLocalMobile), v.regex(/^09\d{9}$/, message)); + +/** A «دلیل» for the audit log: trimmed, 10 characters at least (J11 §0.5). */ +export const auditReason = (required: string, short: string, long: string) => + v.pipe( + v.string(), + v.trim(), + v.nonEmpty(required), + v.minLength(REASON_MIN_LENGTH, short), + v.maxLength(REASON_MAX_LENGTH, long), + ); diff --git a/platforms/garden-roof/src/shared/validations/codes-validations.ts b/platforms/garden-roof/src/shared/validations/codes-validations.ts new file mode 100644 index 0000000..ef0a132 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/codes-validations.ts @@ -0,0 +1,43 @@ +import { latinDigits } from '@lumina/tools/format'; +import * as v from 'valibot'; + +import { auditReason } from './base-validations'; + +/** No invite code takes more seats than this (J11-6: usedCount ≤ maxUses ≤ 1000). */ +export const CODE_MAX_USES = 1000; + +/** The code being changed: its capacity can't drop below the seats already used. */ +export type CapacityBounds = { usedCount: number; maxUses: number }; + +/** + * «ظرفیت جدید» and «دلیل» (J11-6b): a whole number, typed in any digits, from the seats used (and + * at least 1) up to 1000 and not the capacity it already has; the reason as every audited change + * asks it. + */ +export function capacitySchema({ usedCount, maxUses }: CapacityBounds) { + return v.object({ + maxUses: v.pipe( + v.string(), + v.transform((value) => latinDigits(value).trim()), + v.nonEmpty('codes:capacity.errors.required'), + v.regex(/^\d+$/, 'codes:capacity.errors.integer'), + v.transform(Number), + v.minValue(1, 'codes:capacity.errors.below-one'), + v.minValue(usedCount, 'codes:capacity.errors.below-used'), + v.maxValue(CODE_MAX_USES, 'codes:capacity.errors.above-max'), + v.check((value) => value !== maxUses, 'codes:capacity.errors.unchanged'), + ), + reason: auditReason( + 'common:reason.required', + 'common:reason.short', + 'common:reason.long', + ), + }); +} + +export type CapacityFormValues = v.InferInput< + ReturnType +>; +export type CapacityFormOutput = v.InferOutput< + ReturnType +>; diff --git a/platforms/garden-roof/src/shared/validations/constants.ts b/platforms/garden-roof/src/shared/validations/constants.ts new file mode 100644 index 0000000..7d107c3 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/constants.ts @@ -0,0 +1,10 @@ +export const CODE_PATTERN = /^\d{6}$/; + +/** + * Every admin action that changes someone's access or money asks for a «دلیل» of at least this + * many characters after trimming (J11 §0.5); it goes into the audit log. + */ +export const REASON_MIN_LENGTH = 10; + +/** The longest «دلیل» the API keeps. */ +export const REASON_MAX_LENGTH = 500; diff --git a/platforms/garden-roof/src/shared/validations/index.ts b/platforms/garden-roof/src/shared/validations/index.ts new file mode 100644 index 0000000..673be05 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/index.ts @@ -0,0 +1,59 @@ +export { codeSchema, phoneSchema } from './auth-validations'; +export { auditReason, mobileNumber, requiredString } from './base-validations'; +export { + CODE_PATTERN, + REASON_MAX_LENGTH, + REASON_MIN_LENGTH, +} from './constants'; +export { reasonSchema } from './reason-validations'; +export type { + CodeFormValues, + PhoneFormOutput, + PhoneFormValues, + ReasonFormOutput, + ReasonFormValues, +} from './types'; +export { capacitySchema, CODE_MAX_USES } from './codes-validations'; +export type { + CapacityBounds, + CapacityFormOutput, + CapacityFormValues, +} from './codes-validations'; +export { + extendSubscriptionSchema, + grantAccessSchema, + refundSubscriptionSchema, +} from './subscription-validations'; +export type { + ExtendSubscriptionFormOutput, + ExtendSubscriptionFormValues, + GrantAccessFormOutput, + GrantAccessFormValues, + RefundSubscriptionFormOutput, + RefundSubscriptionFormValues, +} from './subscription-validations'; +export { + correctPriceSchema, + flagSchema, + overrideSchema, + parsePriceInput, + priceInput, +} from './prediction-validations'; +export type { + CorrectPriceFormOutput, + CorrectPriceFormValues, + FlagFormOutput, + FlagFormValues, + OverrideFormOutput, + OverrideFormValues, +} from './prediction-validations'; +export { + BANK_REFERENCE_PATTERN, + markPaidSchema, + RECEIPT_FILE, + receiptFile, +} from './payout-validations'; +export type { + MarkPaidFormOutput, + MarkPaidFormValues, +} from './payout-validations'; diff --git a/platforms/garden-roof/src/shared/validations/payout-validations.ts b/platforms/garden-roof/src/shared/validations/payout-validations.ts new file mode 100644 index 0000000..a187205 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/payout-validations.ts @@ -0,0 +1,38 @@ +import { latinDigits } from '@lumina/tools/format'; +import * as v from 'valibot'; + +// The payouts section's forms (J11-9). Every message is an i18n key; the field translates it. + +/** A receipt the admin may attach to «ثبت پرداخت» (J11-9d): JPG, PNG or PDF up to 5 MB. */ +export const RECEIPT_FILE = { + types: ['image/jpeg', 'image/png', 'application/pdf'], + maxBytes: 5 * 1024 * 1024, +} as const; + +/** A bank's tracking number for a transfer: digits only, as banks print it. */ +export const BANK_REFERENCE_PATTERN = /^\d{6,30}$/; + +/** A picked receipt's checks, run when it is picked and again on submit. */ +export const receiptFile = v.pipe( + v.file(), + v.mimeType(RECEIPT_FILE.types, 'payouts:validation.receipt-type'), + v.maxSize(RECEIPT_FILE.maxBytes, 'payouts:validation.receipt-size'), +); + +/** + * «ثبت پرداخت»: the bank's tracking number (any digits, spaces and dashes dropped), the day the + * bank moved the money, and an optional receipt. No free-text reason: the action is audited as is. + */ +export const markPaidSchema = v.object({ + bankReference: v.pipe( + v.string(), + v.transform((value) => latinDigits(value).replace(/[\s-]/g, '')), + v.nonEmpty('payouts:validation.reference-required'), + v.regex(BANK_REFERENCE_PATTERN, 'payouts:validation.reference-invalid'), + ), + paidAt: v.pipe(v.string(), v.nonEmpty('payouts:validation.date-required')), + receipt: v.nullable(receiptFile), +}); + +export type MarkPaidFormValues = v.InferInput; +export type MarkPaidFormOutput = v.InferOutput; diff --git a/platforms/garden-roof/src/shared/validations/prediction-validations.ts b/platforms/garden-roof/src/shared/validations/prediction-validations.ts new file mode 100644 index 0000000..a23a752 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/prediction-validations.ts @@ -0,0 +1,101 @@ +import { latinDigits } from '@lumina/tools/format'; +import * as v from 'valibot'; + +import { auditReason } from './base-validations'; +import { REASON_MAX_LENGTH, REASON_MIN_LENGTH } from './constants'; + +// Every message is an i18n key; the field translates it. + +/** `۱۰۳٬۹۵۰`, `1,092.5`, `۱٫۰۸۹۵`: any digits and separators an admin types → a plain number string. */ +function plainNumber(value: string): string { + return latinDigits(value) + .replace(/[٬,\s]/g, '') + .replace('٫', '.'); +} + +/** A price as typed, in any digits, → a positive number (J11-8d, 8g). */ +export const priceInput = (required: string, invalid: string) => + v.pipe( + v.string(), + v.transform(plainNumber), + v.nonEmpty(required), + v.regex(/^\d+(\.\d+)?$/, invalid), + v.transform(Number), + v.check((price) => price > 0, invalid), + ); + +const anyPrice = priceInput('', ''); + +/** The typed price as a number, or `null` while it isn't one: the dialogs' live preview. */ +export function parsePriceInput(value: string): number | null { + const result = v.safeParse(anyPrice, value); + return result.success ? result.output : null; +} + +const reason = auditReason( + 'common:reason.required', + 'common:reason.short', + 'common:reason.long', +); + +/** «قیمت اصلاح‌شده» and its «دلیل» (J11-8g): a corrected price always says why. */ +export const correctPriceSchema = v.object({ + price: priceInput( + 'predictions:correct.price-required', + 'predictions:correct.price-invalid', + ), + reason, +}); + +/** «قیمت بسته‌شدن جدید» and its «دلیل» (J11-8d). */ +export const overrideSchema = v.object({ + closedPrice: priceInput( + 'predictions:override.price-required', + 'predictions:override.price-invalid', + ), + reason, +}); + +/** + * «دلیل» chip and «توضیح» (J11-8e): the note is optional, except with «سایر», where it needs 10 + * characters at least. + */ +export const flagSchema = v.pipe( + v.object({ + reason: v.pipe( + v.string(), + v.nonEmpty('predictions:flag.reason-required'), + v.picklist( + ['ambiguous', 'unrealistic_target', 'duplicate', 'other'], + 'predictions:flag.reason-required', + ), + ), + note: v.pipe( + v.string(), + v.trim(), + v.maxLength(REASON_MAX_LENGTH, 'common:reason.long'), + ), + }), + v.forward( + v.check( + ({ reason, note }) => reason !== 'other' || note !== '', + 'predictions:flag.note-required', + ), + ['note'], + ), + v.forward( + v.check( + ({ reason, note }) => + reason !== 'other' || note === '' || note.length >= REASON_MIN_LENGTH, + 'predictions:flag.note-short', + ), + ['note'], + ), +); + +export type CorrectPriceFormValues = v.InferInput; +export type CorrectPriceFormOutput = v.InferOutput; +export type OverrideFormValues = v.InferInput; +export type OverrideFormOutput = v.InferOutput; +export type FlagFormValues = v.InferInput; +export type FlagFormOutput = v.InferOutput; diff --git a/platforms/garden-roof/src/shared/validations/reason-validations.ts b/platforms/garden-roof/src/shared/validations/reason-validations.ts new file mode 100644 index 0000000..36f23f4 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/reason-validations.ts @@ -0,0 +1,12 @@ +import * as v from 'valibot'; + +import { auditReason } from './base-validations'; + +/** A dialog that only asks for a «دلیل»: reject, suspend, reinstate, deactivate, cancel. */ +export const reasonSchema = v.object({ + reason: auditReason( + 'common:reason.required', + 'common:reason.short', + 'common:reason.long', + ), +}); diff --git a/platforms/garden-roof/src/shared/validations/subscription-validations.ts b/platforms/garden-roof/src/shared/validations/subscription-validations.ts new file mode 100644 index 0000000..f42d0e8 --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/subscription-validations.ts @@ -0,0 +1,113 @@ +import { latinDigits } from '@lumina/tools/format'; +import * as v from 'valibot'; + +import { auditReason, requiredString } from './base-validations'; + +// The subscriptions section's forms (J11-7c, 7d, 7e). Every message is an i18n key; the field +// translates it. + +const reason = () => + auditReason( + 'common:reason.required', + 'common:reason.short', + 'common:reason.long', + ); + +/** `IR` and 24 digits pass the ISO 13616 check (mod 97 = 1), so a mistyped digit is caught here. */ +function isShebaChecksumValid(digits: string): boolean { + // IR → 18 27; the country code and check digits move to the end. + const rearranged = `${digits.slice(2)}1827${digits.slice(0, 2)}`; + let remainder = 0; + for (const char of rearranged) + remainder = (remainder * 10 + Number(char)) % 97; + return remainder === 1; +} + +/** «تمدید دستی» (J11-7d): the days picked and the «دلیل». */ +export const extendSubscriptionSchema = v.object({ + days: v.pipe( + v.string(), + v.transform(Number), + v.number(), + v.integer(), + v.minValue(1), + ), + reason: reason(), +}); + +/** + * «بازگشت وجه» (J11-7e): the amount in Toman, from 1 to what was paid; the destination شبا as + * typed (Persian digits, spaces, with or without `IR`) → `IR` and 24 digits; the bank transfer's + * tracking number; the «دلیل». + */ +export function refundSubscriptionSchema(paidAmount: number) { + return v.object({ + amount: v.pipe( + v.string(), + v.transform((value) => latinDigits(value).replace(/[\s,٬]/g, '')), + v.nonEmpty('subscriptions:refund.errors.amount-required'), + v.regex(/^\d+$/, 'subscriptions:refund.errors.amount-invalid'), + v.transform(Number), + v.minValue(1, 'subscriptions:refund.errors.amount-min'), + v.maxValue(paidAmount, 'subscriptions:refund.errors.amount-max'), + ), + destinationSheba: v.pipe( + v.string(), + v.transform((value) => + latinDigits(value) + .toUpperCase() + .replace(/[\s-]/g, '') + .replace(/^IR/, ''), + ), + v.nonEmpty('subscriptions:refund.errors.sheba-required'), + v.regex(/^\d{24}$/, 'subscriptions:refund.errors.sheba-length'), + v.check( + isShebaChecksumValid, + 'subscriptions:refund.errors.sheba-invalid', + ), + v.transform((digits) => `IR${digits}`), + ), + bankReference: v.pipe( + v.string(), + v.transform((value) => latinDigits(value).trim()), + v.nonEmpty('subscriptions:refund.errors.bank-reference-required'), + v.regex( + /^[A-Za-z0-9-]{4,40}$/, + 'subscriptions:refund.errors.bank-reference-invalid', + ), + ), + reason: reason(), + }); +} + +/** + * «اعطای دسترسی» (J11-7c): who and which channel as typed (the dialog resolves them), the period, + * the reason code and a note of 10 characters at least for the audit log. + */ +export const grantAccessSchema = v.object({ + investor: requiredString('subscriptions:grant.errors.investor-required'), + analyst: requiredString('subscriptions:grant.errors.analyst-required'), + period: requiredString('subscriptions:grant.errors.period-required'), + reasonCode: requiredString('subscriptions:grant.errors.reason-required'), + note: auditReason( + 'subscriptions:grant.errors.note-required', + 'subscriptions:grant.errors.note-short', + 'subscriptions:grant.errors.note-long', + ), +}); + +/** What each form holds while typing (`useForm`'s values) and what its schema hands the submit. */ +export type ExtendSubscriptionFormValues = v.InferInput< + typeof extendSubscriptionSchema +>; +export type ExtendSubscriptionFormOutput = v.InferOutput< + typeof extendSubscriptionSchema +>; +export type RefundSubscriptionFormValues = v.InferInput< + ReturnType +>; +export type RefundSubscriptionFormOutput = v.InferOutput< + ReturnType +>; +export type GrantAccessFormValues = v.InferInput; +export type GrantAccessFormOutput = v.InferOutput; diff --git a/platforms/garden-roof/src/shared/validations/types.ts b/platforms/garden-roof/src/shared/validations/types.ts new file mode 100644 index 0000000..9c508aa --- /dev/null +++ b/platforms/garden-roof/src/shared/validations/types.ts @@ -0,0 +1,11 @@ +import type * as v from 'valibot'; + +import type { codeSchema, phoneSchema } from './auth-validations'; +import type { reasonSchema } from './reason-validations'; + +/** What each form holds while typing (`useForm`'s values) and what its schema hands the submit. */ +export type PhoneFormValues = v.InferInput; +export type PhoneFormOutput = v.InferOutput; +export type CodeFormValues = v.InferInput; +export type ReasonFormValues = v.InferInput; +export type ReasonFormOutput = v.InferOutput; diff --git a/platforms/garden-roof/src/stores/auth/auth-store.ts b/platforms/garden-roof/src/stores/auth/auth-store.ts new file mode 100644 index 0000000..ee847f5 --- /dev/null +++ b/platforms/garden-roof/src/stores/auth/auth-store.ts @@ -0,0 +1,29 @@ +import { create } from 'zustand'; +import { immer } from 'zustand/middleware/immer'; + +import type { AuthState } from './types'; + +/** + * Who the admin is, in the browser only. It starts `unknown` on the server and in the first + * browser render, so every panel page shows its skeleton until `restoreSession` has read the + * session (0062); `unknown` never reads as a guest. + */ +export const useAuthStore = create()( + immer((set) => ({ + status: 'unknown', + admin: null, + setAdmin: (admin) => + set((state) => { + state.status = 'member'; + state.admin = admin; + }), + clearSession: () => + set((state) => { + state.status = 'guest'; + state.admin = null; + }), + })), +); + +export const useViewerStatus = () => useAuthStore((state) => state.status); +export const useCurrentAdmin = () => useAuthStore((state) => state.admin); diff --git a/platforms/garden-roof/src/stores/auth/index.ts b/platforms/garden-roof/src/stores/auth/index.ts new file mode 100644 index 0000000..147e303 --- /dev/null +++ b/platforms/garden-roof/src/stores/auth/index.ts @@ -0,0 +1,2 @@ +export { useAuthStore, useCurrentAdmin, useViewerStatus } from './auth-store'; +export type { AuthState, ViewerStatus } from './types'; diff --git a/platforms/garden-roof/src/stores/auth/types.ts b/platforms/garden-roof/src/stores/auth/types.ts new file mode 100644 index 0000000..f67bcf2 --- /dev/null +++ b/platforms/garden-roof/src/stores/auth/types.ts @@ -0,0 +1,11 @@ +import type { AdminPayload } from '../../features/auth'; + +/** unknown: not read yet (the server render and the first browser render). */ +export type ViewerStatus = 'unknown' | 'guest' | 'member'; + +export type AuthState = { + status: ViewerStatus; + admin: AdminPayload | null; + setAdmin: (admin: AdminPayload) => void; + clearSession: () => void; +}; diff --git a/platforms/garden-roof/tsconfig.json b/platforms/garden-roof/tsconfig.json new file mode 100644 index 0000000..b9bb0c2 --- /dev/null +++ b/platforms/garden-roof/tsconfig.json @@ -0,0 +1,10 @@ +{ + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.lib.json" + } + ], + "extends": "../../tsconfig.base.json" +} diff --git a/platforms/garden-roof/tsconfig.lib.json b/platforms/garden-roof/tsconfig.lib.json new file mode 100644 index 0000000..032c2b0 --- /dev/null +++ b/platforms/garden-roof/tsconfig.lib.json @@ -0,0 +1,54 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "types": [ + "node", + "@nx/react/typings/cssmodule.d.ts", + "@nx/react/typings/image.d.ts" + ], + "rootDir": "src", + "jsx": "react-jsx", + "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", + "lib": ["es2022", "dom", "dom.iterable"], + "resolveJsonModule": true + }, + "exclude": [ + "out-tsc", + "dist", + "jest.config.ts", + "jest.config.cts", + "src/**/*.spec.ts", + "src/**/*.test.ts", + "src/**/*.spec.tsx", + "src/**/*.test.tsx", + "src/**/*.spec.js", + "src/**/*.test.js", + "src/**/*.spec.jsx", + "src/**/*.test.jsx", + "eslint.config.js", + "eslint.config.cjs", + "eslint.config.mjs" + ], + "include": [ + "src/**/*.js", + "src/**/*.jsx", + "src/**/*.ts", + "src/**/*.tsx", + "src/**/*.json" + ], + "references": [ + { + "path": "../../packages/tools/tsconfig.lib.json" + }, + { + "path": "../../packages/libs/tsconfig.lib.json" + }, + { + "path": "../../packages/island/tsconfig.lib.json" + }, + { + "path": "../../packages/integrations/tsconfig.lib.json" + } + ] +} diff --git a/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/constants.ts b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/constants.ts index 80f0b33..549a48e 100644 --- a/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/constants.ts +++ b/platforms/market/src/app/screens/(main)/notifications/organisms/notification-centre/constants.ts @@ -24,6 +24,9 @@ export const NOTIFICATION_ART: Record = { payment_pending_review: { icon: 'clock', tone: 'neutral' }, payment_not_confirmed: { icon: 'x-circle', tone: 'danger' }, subscription_expired_suspended: { icon: 'ban', tone: 'warning' }, + // From the admin panel (J11-7d, J11-7e). + subscription_extended: { icon: 'calendar', tone: 'brand' }, + subscription_refunded: { icon: 'receipt', tone: 'neutral' }, // Capacity opened, with the investor's code ready (J06-7e). waitlist_capacity: { icon: 'tag', tone: 'brand' }, sale_opened: { icon: 'bell', tone: 'brand' }, diff --git a/platforms/market/src/features/notification/entities/notification/types.ts b/platforms/market/src/features/notification/entities/notification/types.ts index f0d653f..90efa78 100644 --- a/platforms/market/src/features/notification/entities/notification/types.ts +++ b/platforms/market/src/features/notification/entities/notification/types.ts @@ -15,6 +15,10 @@ * `verification_approved` and `verification_rejected` tell a creator how their identity review * went, `invite_code_deactivated` that their invite code was turned off, and `prediction_corrected` * that an admin corrected one of their predictions (with the reason as its body). + * + * 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 + * subscription ended. */ export type NotificationType = | 'subscription_subscribe' @@ -24,6 +28,8 @@ export type NotificationType = | 'subscription_expiry_warning' | 'subscription_expired' | 'subscription_expired_suspended' + | 'subscription_extended' + | 'subscription_refunded' | 'payment_pending_review' | 'waitlist_capacity' | 'new_subscriber' diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e0a14d4..3c20d56 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -196,6 +196,33 @@ importers: specifier: ^19.0.0 version: 19.3.0(react@19.3.0) + apps/wall-street-plaza: + dependencies: + '@lumina/garden-roof': + specifier: workspace:* + version: link:../../platforms/garden-roof + '@lumina/integrations': + specifier: workspace:* + version: link:../../packages/integrations + '@lumina/island': + specifier: workspace:* + version: link:../../packages/island + '@lumina/libs': + specifier: workspace:* + version: link:../../packages/libs + '@lumina/tools': + specifier: workspace:* + version: link:../../packages/tools + next: + specifier: ~16.3.8 + version: 16.3.8(@babel/core@7.29.7(supports-color@8.1.1))(@types/node@22.20.4)(babel-plugin-macros@3.1.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + react: + specifier: ^19.0.0 + version: 19.3.0 + react-dom: + specifier: ^19.0.0 + version: 19.3.0(react@19.3.0) + packages/integrations: dependencies: '@lumina/island': @@ -225,6 +252,21 @@ importers: packages/tools: {} + platforms/garden-roof: + dependencies: + '@lumina/integrations': + specifier: workspace:* + version: link:../../packages/integrations + '@lumina/island': + specifier: workspace:* + version: link:../../packages/island + '@lumina/libs': + specifier: workspace:* + version: link:../../packages/libs + '@lumina/tools': + specifier: workspace:* + version: link:../../packages/tools + platforms/market: dependencies: '@lumina/integrations': diff --git a/tsconfig.json b/tsconfig.json index 11f2993..6b73051 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,6 +12,12 @@ { "path": "./platforms/market" }, + { + "path": "./apps/wall-street-plaza" + }, + { + "path": "./platforms/garden-roof" + }, { "path": "./packages/island" },