diff --git a/AGENTS.md b/AGENTS.md index 694a98b..9149b33 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -61,7 +61,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web 3. Sin `BILLING_ENFORCEMENT=on` todo es Pro y los guards no tocan la base (por eso los tests viejos con prisma mockeado no necesitan `billingSubscription`). 4. Los webhooks `POST /billing/webhooks/mp/:country` y `POST /billing/webhooks/stripe` son públicos (`isPublicApiRequest`): el adaptador verifica la firma (`x-signature` / `Stripe-Signature`) y solo dice qué suscripción sincronizar; se deduplica por `(source, dedupeKey)` y se le vuelve a pedir todo al proveedor. El polling (`ReconcileSubscriptions` + sync on-read en `GET /billing/status` si está `PENDING`) es el fallback. 5. `402` con `plan_limit_reached` / `plan_feature_required` / `plan_read_only`: la web abre el aviso de Pro desde el `MutationCache` de `main.tsx`. - 6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. + 6. Onboarding: paso **Plan** obligatorio (`POST /onboarding/plan`, guarda `country` y `plan_selected_at`); `first-group` da `409 plan_not_selected` sin él. Los pasos del wizard son ids (`features/onboarding/steps.ts`) y con Free se saltean Cobros y WhatsApp. El paso vive en `?step=` (el back del dispositivo retrocede un paso) y lo que pide la URL pasa por `effectiveStep`: sin plan no se pasa de Plan y con el grupo ya creado no se vuelve al formulario. Los callbacks (`?mp=`, `?wa=`, `?sub=`) navegan con `replace` al paso que corresponde. - **zod en v3.24 (pin exacto)**, no v4: `better-call` (transitiva de better-auth) pide `zod ^4` — ese peer warning es conocido y aceptado. `validator` de hono (`hono/validator`) sustituyó a `@hono/zod-validator` (sus tipos duales zod v3/v4 causaban TS2589/exhaustion no resolubles con `ZodTypeAny`); las rutas tipan `c.req.valid` vía el `ValidationInput` derivado del schema. - **PWA (`apps/web`)**: Workbox precachea todo lo que emite Vite, así que el tamaño del precache es un costo real de arranque offline. Cuatro trampas ya pisadas: (1) `globIgnores: ['**/workbox-*.js']` matchea también `workbox-window.*.js`, que es el módulo cliente de `virtual:pwa-register` — excluirlo rompe el registro del SW en cada carga; solo se excluye `**/sw.js`. (2) Importar `@fontsource-variable/inter/wght.css` arrastra los 7 subsets (~220 KB que el navegador nunca baja); por eso los `@font-face` de `latin`/`latin-ext` están escritos a mano en `src/index.css`. **No re-agregar `` a `fonts.googleapis.com`**: rompe el offline. (3) El SW necesita contexto seguro (HTTPS o `localhost`); por IP de LAN sobre `http://` no se registra y no avisa. (4) El aviso de instalación vive en `PwaProvider` (fuera del `RouterProvider`, así que sigue la ruta con `router.subscribe('onResolved')`) y **no** en `RootLayout`: `AppLayoutGuard` desmonta `RootLayout` cada vez que su query de onboarding vuelve a `pending`, y un `settled` de dwell en el hijo se perdería en cada navegación. - **Aviso de instalación (`src/features/pwa/`)**: se ofrece solo con **sesión iniciada**, fuera de `/onboarding` y tras **20 s seguidos en la misma ruta** (navegar antes reinicia la cuenta; después de armado ya no se oculta). El descarte es definitivo vía `localStorage['pwa-install-dismissed']`. Ojo: `_authenticated` **no** es un guard de sesión —`AppLayoutGuard` renderiza `RootLayout` aunque no haya `user`—, así que el gate se chequea en el provider. Safari en iOS no dispara `beforeinstallprompt`: ahí se muestra `IosInstallHint` con la instrucción de Compartir → Agregar a pantalla de inicio (excluye CriOS/FxiOS/EdgiOS, que también usan WebKit pero se instalan desde Safari). diff --git a/apps/web/src/components/ui/button.tsx b/apps/web/src/components/ui/button.tsx index 72b3d01..663deff 100644 --- a/apps/web/src/components/ui/button.tsx +++ b/apps/web/src/components/ui/button.tsx @@ -2,7 +2,7 @@ import { forwardRef, type ButtonHTMLAttributes } from 'react' import { cn } from '../../lib/utils' export type ButtonVariant = 'primary' | 'ghost' | 'outline' -export type ButtonSize = 'sm' | 'md' | 'icon' +export type ButtonSize = 'sm' | 'md' | 'lg' | 'icon' export type ButtonProps = ButtonHTMLAttributes & { variant?: ButtonVariant @@ -18,6 +18,8 @@ const variants: Record = { const sizes: Record = { sm: 'h-8 px-3 text-sm', md: 'h-10 px-4 text-sm', + // Acciones principales de un flujo en mobile: 48px, cómodo para el pulgar. + lg: 'h-12 px-5 text-sm', icon: 'size-9', } diff --git a/apps/web/src/features/billing/PlanOptionCard.tsx b/apps/web/src/features/billing/PlanOptionCard.tsx index e93aa94..b5baf26 100644 --- a/apps/web/src/features/billing/PlanOptionCard.tsx +++ b/apps/web/src/features/billing/PlanOptionCard.tsx @@ -1,5 +1,5 @@ import type { Plan, PlanLimits } from '@gruperly/shared' -import { Check } from 'lucide-react' +import { Check, Lock } from 'lucide-react' import type { ReactNode } from 'react' import { Badge } from '../../components/ui' import { cn } from '../../lib/utils' @@ -29,18 +29,32 @@ export function PlanOptionCard({ plan, limits, price, current, highlighted, chil >

{PLAN_NAMES[plan]}

- {current ? {t('option.yourPlan')} : null} + {current ? ( + {t('option.yourPlan')} + ) : highlighted ? ( + // El destacado no puede ser solo el color del borde. + {t('option.recommended')} + ) : null}

{price ?? t('option.free')}

    {planFeatureList(limits).map((feature) => (
  • - - + {feature.included ? ( +
  • ))} diff --git a/apps/web/src/features/billing/SubscribeForm.tsx b/apps/web/src/features/billing/SubscribeForm.tsx index 34515c9..2cbb38d 100644 --- a/apps/web/src/features/billing/SubscribeForm.tsx +++ b/apps/web/src/features/billing/SubscribeForm.tsx @@ -60,7 +60,7 @@ export function SubscribeForm({ ) : null} - {error ?

    {error}

    : null} + {error ?

    {error}

    : null}
    {onCancel ? ( diff --git a/apps/web/src/features/groups/GroupForm.tsx b/apps/web/src/features/groups/GroupForm.tsx index 6a12ab3..8041f85 100644 --- a/apps/web/src/features/groups/GroupForm.tsx +++ b/apps/web/src/features/groups/GroupForm.tsx @@ -1,10 +1,12 @@ import { type DefaultValues, useForm } from 'react-hook-form' import { zodResolver } from '@hookform/resolvers/zod' import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared' -import { CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared' +import { COUNTRY_CURRENCY, CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared' import { ArrowLeft, Check, Loader2 } from 'lucide-react' +import type { ReactNode } from 'react' +import { useId } from 'react' import { useTranslation } from 'react-i18next' -import { sortWeekDays } from '../../lib/format' +import { currencySymbol, sortWeekDays } from '../../lib/format' import { cn } from '../../lib/utils' import { Button, FieldError, Input, Label } from '../../components/ui' import { BILLING_TYPES, WEEK_DAYS } from '../onboarding/constants' @@ -15,6 +17,8 @@ type GroupFormProps = { submitLabel: string isSubmitting: boolean errorMessage?: string | null + /** Una acción para salir del error (p. ej. volver a elegir el plan). */ + errorAction?: ReactNode /** Solo lo usa el onboarding: ahí el país ya se eligió en el paso anterior. */ country?: CountryCode onSubmit: (values: CreateFirstGroup) => void @@ -27,7 +31,8 @@ export function GroupForm({ submitLabel, isSubmitting, errorMessage, - country = DEFAULT_COUNTRY, + errorAction, + country, onSubmit, onBack, }: GroupFormProps) { @@ -42,8 +47,13 @@ export function GroupForm({ capacity: 10, billingType: 'MONTHLY', dueDay: 1, - country, + country: country ?? DEFAULT_COUNTRY, } + // Con país (onboarding) el símbolo sale de su moneda; sin país, del navegador, + // igual que el resto de los montos de la app. + const symbol = currencySymbol(country ? COUNTRY_CURRENCY[country] : undefined) + const daysLabelId = useId() + const billingLabelId = useId() const { register, @@ -89,9 +99,13 @@ export function GroupForm({
    +
    + + {t('form.whenLegend')} +
    - -
    + +
    {WEEK_DAYS.map((value) => { const isActive = days.includes(value) return ( @@ -101,7 +115,7 @@ export function GroupForm({ aria-pressed={isActive} onClick={() => toggleDay(value)} className={cn( - 'h-9 rounded-full border px-3.5 text-sm font-medium transition-colors', + 'h-11 rounded-xl border text-sm font-medium transition-colors', isActive ? 'border-accent bg-accent text-on-accent' : 'border-border bg-surface text-primary hover:bg-primary-soft', @@ -126,7 +140,6 @@ export function GroupForm({
    -
    +
    + +
    + + {t('form.priceLegend')} +
    - $ + {symbol} 1 ? 'pl-10' : 'pl-7'} invalid={!!errors.price} {...register('price', { valueAsNumber: true })} />
    -
    - -
    + +
    {BILLING_TYPES.map((value) => { const isActive = billingType === value return ( @@ -196,6 +214,9 @@ export function GroupForm({
    + {/* El vencimiento es de la cuota mensual: cobrando por clase no aplica (el + valor por default sigue en el form para que el esquema valide). */} + {billingType === 'MONTHLY' ? (
    + ) : null} +
    {errorMessage ? ( -

    {errorMessage}

    +
    +

    {errorMessage}

    + {errorAction} +
    ) : null}
    {onBack ? ( - ) : null} - diff --git a/apps/web/src/features/home/AttentionList.tsx b/apps/web/src/features/home/AttentionList.tsx index 9dac80b..496c261 100644 --- a/apps/web/src/features/home/AttentionList.tsx +++ b/apps/web/src/features/home/AttentionList.tsx @@ -1,80 +1,69 @@ import { useQuery } from '@tanstack/react-query' import { Link } from '@tanstack/react-router' import type { PendingPreRegistrations } from '@gruperly/shared' -import { CheckCircle2, ChevronRight, Inbox, Wallet } from 'lucide-react' +import { CheckCircle2, ChevronRight, Inbox, MessageCircle } from 'lucide-react' import { useTranslation } from 'react-i18next' -import { Avatar } from '../../components/ui' -import { getGroupsRiskOverview, getPayments } from '../../lib/api' -import { absenceReason } from '../groups/card' +import { Button } from '../../components/ui' +import { AlertTag } from '../attention/AlertTag' +import { alertLabel, flaggedStudents, reminderMessage, whatsappLink } from '../attention/attention' +import { attentionQueryOptions } from '../attention/queries' +import { SeverityAvatar } from '../attention/SeverityAvatar' -/** How many at-risk people Home names; the rest is in each group's stats. */ -const MAX_AT_RISK = 4 +/** Cuántas personas nombra el Inicio; el resto está a un toque, en "Requiere atención". */ +const MAX_STUDENTS = 4 -/* "Para atender": what the teacher has to act on today, across all groups. - Nothing is computed here: the at-risk people are the high-risk `urgentes` of - `GET /groups-risk/overview` (same query key as the group list, so the cache - is shared), the overdue payments are just the total of the filtered list and - the pending pre-registrations come with the Home summary. */ +/* "Para atender": lo que el profe tiene que resolver, en todos sus grupos. + Sale de la misma query que "Requiere atención" (`['attention']`), así las dos + pantallas aplican la misma regla (`computeStudentAlerts`) y un "Resuelto" en + una se ve en la otra sin refetch. Las preinscripciones vienen con el resumen + del Inicio y van primero: del otro lado alguien espera una respuesta. */ export function AttentionList({ pendingPreRegistrations, }: { pendingPreRegistrations: PendingPreRegistrations[] }) { - const { t } = useTranslation('home') - const riskQuery = useQuery({ - queryKey: ['groups-risk-overview'], - queryFn: getGroupsRiskOverview, - }) - const overdueQuery = useQuery({ - queryKey: ['payments', { page: 1, pageSize: 1, status: 'OVERDUE' }], - queryFn: () => getPayments({ page: 1, pageSize: 1, status: 'OVERDUE' }), - }) + const { t } = useTranslation(['home', 'attention', 'common']) + const attentionQuery = useQuery(attentionQueryOptions) - if (riskQuery.isPending || overdueQuery.isPending) return null - // A failing secondary block shouldn't take Home down: it just isn't shown. - if (riskQuery.isError && overdueQuery.isError) return null - - const groups = riskQuery.data?.items ?? [] - const atRisk = groups - .flatMap((group) => - group.urgentes - .filter((member) => member.level === 'riesgo_alto') - .map((member) => ({ ...member, groupId: group.groupId, groupName: group.groupName })), - ) - .sort((a, b) => b.consecutiveAbsences - a.consecutiveAbsences) - const totalAtRisk = groups.reduce((total, group) => total + group.riesgoAlto, 0) - const overdue = overdueQuery.data?.pagination.total ?? 0 + const students = flaggedStudents(attentionQuery.data) + const shown = students.slice(0, MAX_STUDENTS) + const hidden = students.length - shown.length + const isEmpty = students.length === 0 && pendingPreRegistrations.length === 0 return ( -
    -

    {t('attention.title')}

    +
    +
    +

    + {t('attention.title')} +

    + {students.length > 0 ? ( + + {t('attention.seeAll')} + + ) : null} +
    - {atRisk.length === 0 && overdue === 0 && pendingPreRegistrations.length === 0 ? ( -

    + {attentionQuery.isPending ? ( + // Reserva el lugar de dos filas: sin esto, la sección aparecía de golpe + // y empujaba los cobros. +

    +
    ) } const ROW_CLASS_NAME = - 'flex items-center gap-3 px-4 py-3 transition-colors hover:bg-primary-soft/50 active:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent' + 'flex min-h-14 items-center gap-3 px-4 py-3 transition-colors hover:bg-primary-soft/50 active:bg-primary-soft focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent' diff --git a/apps/web/src/features/home/HomeView.tsx b/apps/web/src/features/home/HomeView.tsx index 04a826c..4215514 100644 --- a/apps/web/src/features/home/HomeView.tsx +++ b/apps/web/src/features/home/HomeView.tsx @@ -1,59 +1,59 @@ import { useQuery } from '@tanstack/react-query' -import { Link, useNavigate } from '@tanstack/react-router' +import { useNavigate } from '@tanstack/react-router' import { Loader2, Plus } from 'lucide-react' +import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import { Button } from '../../components/ui' import { useAuth } from '../../context/AuthProvider' import { useIntlLocale } from '../../i18n' import { getClassesToday, getHomeSummary } from '../../lib/api' -import { useMpStatus } from '../mp/useMpStatus' import { AttentionList } from './AttentionList' -import { SummaryStats } from './SummaryStats' -import { TodayClassCard } from './TodayClassCard' +import { classState, planDay } from './day' import { NextClassHero } from './NextClassHero' -import { UpcomingPaymentRow } from './UpcomingPaymentRow' +import { PaymentsSection } from './PaymentsSection' +import { TodayClassCard } from './TodayClassCard' +import { TodayClassRow } from './TodayClassRow' + +/** Cada cuánto se recalcula qué clase va en el hero (una clase termina de estar + * "en curso" con la app abierta). */ +const CLOCK_TICK_MS = 60_000 export function HomeView() { const navigate = useNavigate() const { t } = useTranslation(['home', 'common']) const locale = useIntlLocale() const { user } = useAuth() - const mpStatusQuery = useMpStatus() const firstName = user?.name?.trim().split(/\s+/)[0] - // "martes 27 de octubre": the date anchors "Clase de hoy" and the due dates below. - const today = new Date().toLocaleDateString(locale, { - weekday: 'long', - day: 'numeric', - month: 'long', - }) - const summaryQuery = useQuery({ - queryKey: ['home-summary'], - queryFn: getHomeSummary, - }) + const now = useNow(CLOCK_TICK_MS) + // "jueves, 5 de noviembre": ancla la clase de hoy y los vencimientos de abajo. + const today = now.toLocaleDateString(locale, { weekday: 'long', day: 'numeric', month: 'long' }) + + const summaryQuery = useQuery({ queryKey: ['home-summary'], queryFn: getHomeSummary }) const classesTodayQuery = useQuery({ queryKey: ['classes-today'], queryFn: getClassesToday, staleTime: 60_000, }) - const todayClasses = classesTodayQuery.data?.data ?? [] + const { hero, rest } = planDay(classesTodayQuery.data?.data ?? [], now) return (
    -
    -

    {today}

    +
    +

    {today}

    {firstName ? t('greetingName', { name: firstName }) : t('greeting')}

    -
    + {summaryQuery.isPending ? ( -
    - +
    +
    ) : null} {summaryQuery.isError ? ( -
    +

    {t('loadError')}

    ) : null} {summaryQuery.isSuccess && summaryQuery.data.stats.groups > 0 ? ( -
    - {todayClasses.length > 0 ? ( -
    - {todayClasses.map((classItem) => ( - - ))} -
    - ) : summaryQuery.data.nextClass ? ( - - ) : ( -
    -

    {t('noClasses.title')}

    -

    - {t('noClasses.description')} -

    -
    - )} - - - - - -
    -
    -

    {t('upcoming.title')}

    - -
    - - {summaryQuery.data.upcomingPayments.length > 0 ? ( -
      - {summaryQuery.data.upcomingPayments.map((payment) => ( - - ))} -
    - ) : ( -
    -

    {t('upcoming.empty')}

    - {/* The empty state says how to get out of it: without Mercado - Pago there is no way to create payment links. */} - {mpStatusQuery.data && mpStatusQuery.data.status !== 'active' ? ( - - {t('upcoming.linkMp')} - - ) : ( -

    {t('upcoming.hint')}

    - )} + // En desktop, dos columnas: el día a la izquierda y lo pendiente a la + // derecha. En mobile, el mismo orden de arriba abajo. +
    +
    + {classesTodayQuery.isError ? ( +
    + {t('today.loadError')} +
    - )} + ) : hero ? ( + + ) : summaryQuery.data.nextClass ? ( + + ) : classesTodayQuery.isSuccess && rest.length === 0 ? ( +
    +

    {t('noClasses.title')}

    +

    {t('noClasses.description')}

    +
    + ) : null} + + {rest.length > 0 ? ( +
    +

    + {t('today.listTitle')} +

    +
      + {rest.map((item) => ( + + ))} +
    +
    + ) : null} +
    + +
    + +
    ) : null}
    ) -} \ No newline at end of file +} + +/** La hora actual, refrescada cada `intervalMs`. */ +function useNow(intervalMs: number): Date { + const [now, setNow] = useState(() => new Date()) + useEffect(() => { + const id = window.setInterval(() => setNow(new Date()), intervalMs) + return () => window.clearInterval(id) + }, [intervalMs]) + return now +} diff --git a/apps/web/src/features/home/NextClassHero.tsx b/apps/web/src/features/home/NextClassHero.tsx index e716e41..6bcd6e3 100644 --- a/apps/web/src/features/home/NextClassHero.tsx +++ b/apps/web/src/features/home/NextClassHero.tsx @@ -1,45 +1,37 @@ -import { useNavigate } from '@tanstack/react-router' +import { Link } from '@tanstack/react-router' import type { NextClassDto } from '@gruperly/shared' -import { CalendarClock } from 'lucide-react' +import { ChevronRight } from 'lucide-react' import { useTranslation } from 'react-i18next' -import { Badge, Button } from '../../components/ui' +import { Badge } from '../../components/ui' import { formatRelativeDateTime, formatSchedule } from '../../lib/format' +/** El hero cuando hoy ya no queda ninguna clase por dar: la próxima, sea cuando sea. */ export function NextClassHero({ nextClass }: { nextClass: NextClassDto }) { - const navigate = useNavigate() const { t } = useTranslation('home') const hasSchedule = (nextClass.days?.length ?? 0) > 0 return ( -
    -
    -
    -

    - {nextClass.isNow ? t('nextClass.now') : t('nextClass.next')} -

    -

    {nextClass.name}

    - {hasSchedule ? ( -
    - - {formatSchedule(nextClass.days ?? [], nextClass.time)} -
    - ) : null} -
    -
    - - {nextClass.isNow ? t('nextClass.nowBadge') : formatRelativeDateTime(nextClass.occurrenceAt)} - -
    + +
    +

    {nextClass.name}

    +
    -
    - -
    -
    +

    + {nextClass.isNow ? t('nextClass.now') : t('nextClass.next')} + + {nextClass.isNow ? t('nextClass.nowBadge') : formatRelativeDateTime(nextClass.occurrenceAt)} + +

    + {hasSchedule ? ( +

    {formatSchedule(nextClass.days ?? [], nextClass.time)}

    + ) : null} + ) -} \ No newline at end of file +} diff --git a/apps/web/src/features/home/PaymentsSection.tsx b/apps/web/src/features/home/PaymentsSection.tsx new file mode 100644 index 0000000..76817b9 --- /dev/null +++ b/apps/web/src/features/home/PaymentsSection.tsx @@ -0,0 +1,111 @@ +import { Link } from '@tanstack/react-router' +import type { HomeSummaryDto } from '@gruperly/shared' +import { Lock, Sparkles } from 'lucide-react' +import { useTranslation } from 'react-i18next' +import { useBillingStatus } from '../billing/useBillingStatus' +import { useMpStatus } from '../mp/useMpStatus' +import { formatPrice } from '../../lib/format' +import { UpcomingPaymentRow } from './UpcomingPaymentRow' + +/* Filas de muestra de la vista previa de Free: nombres y montos de ejemplo, en + la moneda que formatea el navegador. Nunca son datos del profe. */ +const TEASER_ROWS = [ + { name: 'teaser.sample1', amount: 15000 }, + { name: 'teaser.sample2', amount: 15000 }, +] as const + +/** + * "Próximos cobros". Con un plan que cobra por Mercado Pago muestra los cobros + * y lo que queda por cobrar; sin él (Free), una vista previa bloqueada de cómo + * se vería, con el paso a Pro. Nunca ofrece vincular Mercado Pago a quien no + * puede cobrar con él. + */ +export function PaymentsSection({ summary }: { summary: HomeSummaryDto }) { + const { t } = useTranslation('home') + const billingQuery = useBillingStatus() + const mpStatusQuery = useMpStatus() + // Mientras no se sabe el plan no se decide nada: ni cobros ni vista previa. + if (billingQuery.isPending) return null + + // Sin enforcement (o si el estado del plan no cargó) todo es Pro: se muestran + // los cobros, como hasta ahora. + const billing = billingQuery.data + const canCharge = !billing || !billing.enforced || billing.limits.mpCharges + const { pendingAmount, pendingPayments } = summary.stats + + return ( +
    +
    +

    + {t('upcoming.title')} +

    + {canCharge ? ( + + {t('upcoming.seeAll')} + + ) : null} +
    + + {!canCharge ? ( +
    + +
    +

    +

    + +
    +
    + ) : ( + <> + {pendingPayments > 0 ? ( +

    + {t('upcoming.pending', { amount: formatPrice(pendingAmount), count: pendingPayments })} +

    + ) : null} + + {summary.upcomingPayments.length > 0 ? ( +
      + {summary.upcomingPayments.map((payment) => ( + + ))} +
    + ) : ( +
    +

    {t('upcoming.empty')}

    + {/* El vacío dice cómo salir de él: sin Mercado Pago vinculado no + hay cómo crear links de cobro. */} + {mpStatusQuery.data && mpStatusQuery.data.status !== 'active' ? ( + + {t('upcoming.linkMp')} + + ) : ( +

    {t('upcoming.hint')}

    + )} +
    + )} + + )} +
    + ) +} diff --git a/apps/web/src/features/home/SummaryStats.tsx b/apps/web/src/features/home/SummaryStats.tsx deleted file mode 100644 index 6dd4a35..0000000 --- a/apps/web/src/features/home/SummaryStats.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { useNavigate } from '@tanstack/react-router' -import type { HomeSummaryDto } from '@gruperly/shared' -import { UserCheck, Users, Wallet, type LucideIcon } from 'lucide-react' -import { useTranslation } from 'react-i18next' -import { cn } from '../../lib/utils' -import { formatPrice } from '../../lib/format' - -type StatTarget = '/groups' | '/payments' - -/* Three compact tiles in a row, also on mobile: they are reference numbers, not - the protagonists of the screen, and stacked they pushed "Próximos cobros" - below the fold. The value always goes with its label: the old tile swapped - the label for a sub-line and read "0 / 0 por cobrar". */ -export function SummaryStats({ summary }: { summary: HomeSummaryDto }) { - const navigate = useNavigate() - const { t } = useTranslation('home') - const { pendingAmount, pendingPayments } = summary.stats - const stats: { - label: string - value: string - icon: LucideIcon - to: StatTarget - }[] = [ - { - label: t('stats.groups', { count: summary.stats.groups }), - value: String(summary.stats.groups), - icon: Users, - to: '/groups', - }, - { - label: pendingPayments > 0 ? t('stats.toCollectCount', { count: pendingPayments }) : t('stats.toCollect'), - value: formatPrice(pendingAmount), - icon: Wallet, - to: '/payments', - }, - { - label: t('stats.students', { count: summary.stats.attendees }), - value: String(summary.stats.attendees), - icon: UserCheck, - to: '/groups', - }, - ] - - return ( -
    - {stats.map((stat) => { - const Icon = stat.icon - return ( - - ) - })} -
    - ) -} diff --git a/apps/web/src/features/home/TodayClassCard.tsx b/apps/web/src/features/home/TodayClassCard.tsx index cc25e80..a5ae0e7 100644 --- a/apps/web/src/features/home/TodayClassCard.tsx +++ b/apps/web/src/features/home/TodayClassCard.tsx @@ -1,53 +1,56 @@ -import { Link, useNavigate } from '@tanstack/react-router' +import { Link } from '@tanstack/react-router' import type { ClassTodayDto } from '@gruperly/shared' -import { CalendarClock, ChevronRight, ClipboardCheck } from 'lucide-react' +import { ChevronRight, ClipboardCheck } from 'lucide-react' import { useTranslation } from 'react-i18next' -import { Badge, Button } from '../../components/ui' +import { Badge } from '../../components/ui' import { useIntlLocale } from '../../i18n' +import { formatClockTime } from '../../lib/format' +import { cn } from '../../lib/utils' +import type { ClassState } from './day' -export function TodayClassCard({ item }: { item: ClassTodayDto }) { - const navigate = useNavigate() +/** El hero del Inicio: la clase en curso o la próxima de hoy. */ +export function TodayClassCard({ item, state }: { item: ClassTodayDto; state: ClassState }) { const { t } = useTranslation('home') const locale = useIntlLocale() - const time = new Date(item.startsAt).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' }) + const time = formatClockTime(item.startsAt, locale) + const isLive = state === 'live' return ( -
    +
    -

    - {t('today.label')} -

    - {/* Only the done state earns a badge: "Por tomar" repeated what the - button below already says. */} - {item.hasAttendance ? {t('today.attendanceTaken')} : null} + +

    {item.groupName}

    +
    - -

    {item.groupName}

    -
    ) } diff --git a/apps/web/src/features/home/TodayClassRow.tsx b/apps/web/src/features/home/TodayClassRow.tsx new file mode 100644 index 0000000..72f8b43 --- /dev/null +++ b/apps/web/src/features/home/TodayClassRow.tsx @@ -0,0 +1,41 @@ +import { Link } from '@tanstack/react-router' +import type { ClassTodayDto } from '@gruperly/shared' +import { Check, ChevronRight } from 'lucide-react' +import { useTranslation } from 'react-i18next' +import { useIntlLocale } from '../../i18n' +import { formatClockTime } from '../../lib/format' +import { cn } from '../../lib/utils' +import type { ClassState } from './day' + +/** Una clase del día fuera del hero: hora, grupo y en qué quedó la asistencia. */ +export function TodayClassRow({ item, state }: { item: ClassTodayDto; state: ClassState }) { + const { t } = useTranslation('home') + const locale = useIntlLocale() + + return ( +
  • + + + {formatClockTime(item.startsAt, locale)} + + {item.groupName} + + {state === 'taken' ? +
  • + ) +} diff --git a/apps/web/src/features/home/UpcomingPaymentRow.tsx b/apps/web/src/features/home/UpcomingPaymentRow.tsx index 8a1d36b..9b7930e 100644 --- a/apps/web/src/features/home/UpcomingPaymentRow.tsx +++ b/apps/web/src/features/home/UpcomingPaymentRow.tsx @@ -1,4 +1,6 @@ +import { Link } from '@tanstack/react-router' import type { UpcomingPaymentDto } from '@gruperly/shared' +import { ChevronRight } from 'lucide-react' import { useTranslation } from 'react-i18next' import { Badge } from '../../components/ui' import { formatPrice, formatRelativeDateTime, paymentStatusLabel } from '../../lib/format' @@ -8,19 +10,25 @@ export function UpcomingPaymentRow({ payment }: { payment: UpcomingPaymentDto }) // Re-render on language change: the labels come from lib/format. useTranslation() return ( -
  • -
    -

    {payment.attendeeName}

    -

    - {payment.groupName} · {formatRelativeDateTime(payment.dueDate)} -

    -
    -
    - {formatPrice(payment.amount)} - - {paymentStatusLabel(payment.status)} - -
    +
  • + + + {payment.attendeeName} + + {payment.groupName} · {formatRelativeDateTime(payment.dueDate)} + + + + + {formatPrice(payment.amount, payment.currency)} + + {paymentStatusLabel(payment.status)} + +
  • ) -} \ No newline at end of file +} diff --git a/apps/web/src/features/home/day.ts b/apps/web/src/features/home/day.ts new file mode 100644 index 0000000..680ff49 --- /dev/null +++ b/apps/web/src/features/home/day.ts @@ -0,0 +1,41 @@ +import type { ClassTodayDto } from '@gruperly/shared' + +/* El día del profe, como funciones puras: qué clase va en el hero y en qué + estado está cada una. `HomeView` las usa y `test/home-day.test.ts` las cubre. */ + +/** Cuánto después del inicio una clase sin asistencia sigue siendo "la de + * ahora". Pasado eso, deja el hero a la próxima y queda en la lista del día + * como pendiente. */ +export const CLASS_ACTIVE_WINDOW_MS = 2 * 60 * 60 * 1000 + +export type ClassState = + /** La asistencia ya está tomada. */ + | 'taken' + /** Empezó hace menos de `CLASS_ACTIVE_WINDOW_MS` y falta la asistencia. */ + | 'live' + /** Todavía no empezó. */ + | 'upcoming' + /** Ya pasó y nadie tomó asistencia: un olvido, se ofrece tomarla igual. */ + | 'missed' + +export function classState(item: ClassTodayDto, now: Date): ClassState { + if (item.hasAttendance) return 'taken' + const startsAt = new Date(item.startsAt).getTime() + if (startsAt > now.getTime()) return 'upcoming' + return now.getTime() - startsAt <= CLASS_ACTIVE_WINDOW_MS ? 'live' : 'missed' +} + +/** + * El hero es la clase en curso o la próxima de hoy que todavía no tiene + * asistencia. El resto del día va en filas compactas, en orden. Sin hero, el + * Inicio muestra la próxima clase (que puede ser de otro día). + */ +export function planDay(classes: readonly ClassTodayDto[], now: Date) { + const sorted = [...classes].sort((a, b) => a.startsAt.localeCompare(b.startsAt)) + const hero = + sorted.find((item) => { + const state = classState(item, now) + return state === 'live' || state === 'upcoming' + }) ?? null + return { hero, rest: sorted.filter((item) => item !== hero) } +} diff --git a/apps/web/src/features/onboarding/ConfirmationStep.tsx b/apps/web/src/features/onboarding/ConfirmationStep.tsx index ab8a6d5..4874d2e 100644 --- a/apps/web/src/features/onboarding/ConfirmationStep.tsx +++ b/apps/web/src/features/onboarding/ConfirmationStep.tsx @@ -1,121 +1,168 @@ import type { OnboardingGroupDto } from '@gruperly/shared' -import { useQueryClient } from '@tanstack/react-query' +import { COUNTRY_CURRENCY } from '@gruperly/shared' +import { useQuery, useQueryClient } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' -import { ArrowRight, CheckCircle2, CreditCard, MessageCircle, Sparkles } from 'lucide-react' -import { Badge, Button } from '../../components/ui' +import { ArrowRight, Copy, Loader2, Send } from 'lucide-react' +import { Trans, useTranslation } from 'react-i18next' +import { Button, useToast } from '../../components/ui' import { useAuth } from '../../context/AuthProvider' +import { useIntlLocale } from '../../i18n' +import { getInviteToken } from '../../lib/api' import { PLAN_NAMES } from '../billing' import { useMpStatus } from '../mp' import { useWhatsappStatus } from '../whatsapp' import { billingTypeLabel, formatPrice, formatSchedule } from './constants' +import { MessagePreview } from './MessagePreview' import { useOnboarding } from './OnboardingProvider' -import { Trans, useTranslation } from 'react-i18next' type ConfirmationStepProps = { group: OnboardingGroupDto } +/** + * El cierre del alta. El grupo ya existe, y el momento de valor es que llegue el + * primer miembro: por eso la acción principal es mandar el link de invitación + * (con el mensaje real que se comparte), y lo que queda para Ajustes se dice en + * una sola línea. + */ export function ConfirmationStep({ group }: ConfirmationStepProps) { const navigate = useNavigate() - const { t } = useTranslation(['onboarding', 'common', 'groups']) + const { t } = useTranslation(['onboarding', 'common', 'groupDetail']) + const locale = useIntlLocale() + const toast = useToast() const queryClient = useQueryClient() const { refresh } = useAuth() - const statusQuery = useMpStatus() - const isMpConnected = statusQuery.data?.status === 'active' - const whatsappQuery = useWhatsappStatus() - const isWhatsappConnected = whatsappQuery.data?.status === 'active' - const { selectedPlan } = useOnboarding() + const { selectedPlan, country } = useOnboarding() + const isMpConnected = useMpStatus().data?.status === 'active' + const isWhatsappConnected = useWhatsappStatus().data?.status === 'active' - const goToDashboard = () => { - // Revalidates the cache (onboarding state, session, groups) before redirecting. + const inviteQuery = useQuery({ + queryKey: ['invite-token', group.id], + queryFn: () => getInviteToken(group.id), + }) + const inviteUrl = inviteQuery.data?.inviteUrl + const shareMessage = inviteUrl ? t('groupDetail:invite.message', { group: group.name, url: inviteUrl }) : '' + + const copyLink = async () => { + if (!inviteUrl) return + try { + await navigator.clipboard.writeText(inviteUrl) + toast.success(t('groupDetail:invite.linkCopied')) + } catch { + toast.error(t('groupDetail:invite.copyError')) + } + } + + const goHome = () => { + // Revalida todo (estado del alta, sesión, grupos) antes de salir. void queryClient.invalidateQueries() void refresh() void navigate({ to: '/' }) } + const isMonthly = group.billingType === 'MONTHLY' + const price = formatPrice(group.price, COUNTRY_CURRENCY[country]) + const statusLine = + selectedPlan === 'FREE' + ? t('done.statusFree', { plan: PLAN_NAMES.FREE }) + : isMpConnected && isWhatsappConnected + ? t('done.statusAllSet') + : !isMpConnected && !isWhatsappConnected + ? t('done.statusPendingBoth') + : !isMpConnected + ? t('done.statusPendingMp') + : t('done.statusPendingWa') + return ( -
    -
    - - - -

    {t('done.title')}

    -

    - {t('done.description')} -

    +
    +
    +

    + {t('done.title')} +

    +

    {t('done.description')}

    -
    -
    -
    -

    {group.name}

    -

    - {formatSchedule(group.days ?? [], group.time)} -

    -
    - {t('done.active')} -
    +
    + + }} + /> + {inviteUrl ? ( + {inviteUrl} + ) : inviteQuery.isError ? null : ( + + + )} + -
    -
    -
    {t('done.price')}
    -
    - {formatPrice(group.price)} - {group.billingType ? ` · ${billingTypeLabel(group.billingType)}` : ''} -
    -
    -
    -
    {t('done.capacity')}
    -
    {group.capacity != null ? t('done.capacityValue', { count: group.capacity }) : '—'}
    -
    -
    -
    {t('done.dueDay')}
    -
    {group.dueDay != null ? t('done.dueDayValue', { day: group.dueDay }) : '—'}
    + {inviteQuery.isError ? ( +
    + {t('done.linkError')} +
    + ) : null} + + +
    + +
    +

    {group.name}

    +

    {formatSchedule(group.days ?? [], group.time)}

    +
    +
    {t('done.price')}
    +
    + {price} + {group.billingType ? ` · ${billingTypeLabel(group.billingType)}` : ''} +
    +
    {t('done.capacity')}
    +
    + {group.capacity != null ? t('done.capacityValue', { count: group.capacity }) : '—'} +
    + {isMonthly && group.dueDay != null ? ( + <> +
    {t('done.dueDay')}
    +
    + {t('done.dueDayValue', { day: group.dueDay })} +
    + + ) : null}
    - {selectedPlan ? ( -
    - -

    - }} /> - {selectedPlan === 'FREE' ? t('done.freeHint') : ''} -

    -
    - ) : null} +

    {statusLine}

    - {/* Con Free no se cobra ni se automatiza: esos avisos son solo de Pro. */} - {selectedPlan === 'FREE' ? null : ( - <> -
    - -

    - {isMpConnected ? ( - }} /> - ) : ( - }} /> - )} -

    -
    - -
    - -

    - {isWhatsappConnected ? ( - t('done.waConnected') - ) : ( - }} /> - )} -

    -
    - - )} - -
    ) -} \ No newline at end of file +} diff --git a/apps/web/src/features/onboarding/CountryStep.tsx b/apps/web/src/features/onboarding/CountryStep.tsx index 41b15a2..6488327 100644 --- a/apps/web/src/features/onboarding/CountryStep.tsx +++ b/apps/web/src/features/onboarding/CountryStep.tsx @@ -73,11 +73,11 @@ export function CountryStep({ onNext, onBack }: CountryStepProps) {
    - - diff --git a/apps/web/src/features/onboarding/FirstGroupStep.tsx b/apps/web/src/features/onboarding/FirstGroupStep.tsx index 783ba74..e9a589e 100644 --- a/apps/web/src/features/onboarding/FirstGroupStep.tsx +++ b/apps/web/src/features/onboarding/FirstGroupStep.tsx @@ -1,6 +1,8 @@ import type { CreateFirstGroup, OnboardingGroupDto } from '@gruperly/shared' import { useMutation } from '@tanstack/react-query' -import { createFirstGroup } from '../../lib/api' +import { ArrowLeft } from 'lucide-react' +import { Button } from '../../components/ui' +import { ApiError, createFirstGroup } from '../../lib/api' import { errorMessage } from '../../i18n' import { GroupForm } from '../groups/GroupForm' import { useOnboarding } from './OnboardingProvider' @@ -12,12 +14,15 @@ type FirstGroupStepProps = { } export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) { - const { country } = useOnboarding() + const { country, goTo } = useOnboarding() const { t } = useTranslation(['onboarding', 'common', 'groups']) const create = useMutation({ mutationFn: (values: CreateFirstGroup) => createFirstGroup(values), onSuccess: (result) => onCompleted(result.group), }) + // Sin plan elegido el backend no deja crear el grupo: se ofrece volver a Plan. + const needsPlan = + create.error instanceof ApiError && create.error.problem?.code === 'plan_not_selected' return ( goTo('plan')}> + + {t('group.choosePlan')} + + ) : null + } onSubmit={(values) => create.mutate(values)} onBack={onBack} /> diff --git a/apps/web/src/features/onboarding/MessagePreview.tsx b/apps/web/src/features/onboarding/MessagePreview.tsx new file mode 100644 index 0000000..34e4a6b --- /dev/null +++ b/apps/web/src/features/onboarding/MessagePreview.tsx @@ -0,0 +1,55 @@ +import { CheckCheck } from 'lucide-react' +import type { ReactNode } from 'react' +import { cn } from '../../lib/utils' + +type MessagePreviewProps = { + /** A quién le llega el mensaje (la cabecera del chat). */ + contactName: string + /** Una línea chica arriba del chat que dice qué se está viendo. */ + caption: string + /** La hora del mensaje, ya formateada. */ + time: string + children: ReactNode + className?: string +} + +/** + * Vista previa de un mensaje tal como lo recibe el miembro en su chat. + * + * Es lo que hace reconocible al onboarding: en vez de prometer "cobrá al + * instante", muestra el mensaje real que sale desde el número del profe. La + * burbuja usa los tokens de la app (no imita la marca de ningún chat) y el + * texto lo arma quien la usa, con los mismos datos que manda el backend. + */ +export function MessagePreview({ contactName, caption, time, children, className }: MessagePreviewProps) { + const initial = contactName.trim().charAt(0).toUpperCase() + + return ( +
    +
    {caption}
    +
    +
    + + {contactName} +
    + +
    +
    +
    + {children} +
    +

    + {time} +

    +
    +
    +
    +
    + ) +} diff --git a/apps/web/src/features/onboarding/OnboardingProvider.tsx b/apps/web/src/features/onboarding/OnboardingProvider.tsx index aba607f..315b3e4 100644 --- a/apps/web/src/features/onboarding/OnboardingProvider.tsx +++ b/apps/web/src/features/onboarding/OnboardingProvider.tsx @@ -1,10 +1,10 @@ import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto, Plan } from '@gruperly/shared' -import { DEFAULT_COUNTRY } from '@gruperly/shared' +import { countryCodeSchema, DEFAULT_COUNTRY } from '@gruperly/shared' import type { UseQueryResult } from '@tanstack/react-query' import { useQuery, useQueryClient } from '@tanstack/react-query' import { useNavigate, useSearch } from '@tanstack/react-router' import type { ReactNode } from 'react' -import { createContext, useContext, useEffect, useMemo, useState } from 'react' +import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' import { useAuth } from '../../context/AuthProvider' import { getOnboardingStatus } from '../../lib/api' import { billingStatusQueryKey } from '../billing' @@ -12,12 +12,12 @@ import type { MpCallbackFeedback } from '../mp' import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp' import type { WhatsappCallbackFeedback } from '../whatsapp' import { readWhatsappCallbackFeedback, whatsappStatusQueryKey } from '../whatsapp' -import { type OnboardingStepId, resumeStep, visibleSteps } from './steps' +import { effectiveStep, type OnboardingStepId, parseStep, resumeStep, visibleSteps } from './steps' type OnboardingContextValue = { step: OnboardingStepId steps: OnboardingStepId[] - goTo: (step: OnboardingStepId) => void + goTo: (step: OnboardingStepId, options?: { replace?: boolean }) => void goNext: () => void goBack: () => void /** El país del profesor; define la moneda de los links de cobro y el precio de Pro. */ @@ -39,13 +39,34 @@ type OnboardingContextValue = { const OnboardingContext = createContext(null) +/* El país elegido se guarda en el servidor recién junto con el plan. Mientras + tanto vive en sessionStorage: con el paso en la URL, recargar en "Plan" ya no + vuelve a la bienvenida y no tiene que perder el país. */ +const COUNTRY_STORAGE_KEY = 'onboarding-country' + +function readStoredCountry(): CountryCode | null { + try { + const parsed = countryCodeSchema.safeParse(sessionStorage.getItem(COUNTRY_STORAGE_KEY)) + return parsed.success ? parsed.data : null + } catch { + return null + } +} + +function storeCountry(country: CountryCode) { + try { + sessionStorage.setItem(COUNTRY_STORAGE_KEY, country) + } catch { + // Sin storage (modo privado, bloqueado): el país vive solo en memoria. + } +} + export function OnboardingProvider({ children }: { children: ReactNode }) { const { user } = useAuth() const navigate = useNavigate() const queryClient = useQueryClient() const search = useSearch({ from: '/onboarding' }) - const [step, setStep] = useState('welcome') - const [country, setCountry] = useState(DEFAULT_COUNTRY) + const [country, setCountryState] = useState(() => readStoredCountry() ?? DEFAULT_COUNTRY) const [selectedPlan, setSelectedPlan] = useState(null) const [mpFeedback, setMpFeedback] = useState(null) const [waFeedback, setWaFeedback] = useState(null) @@ -58,16 +79,50 @@ export function OnboardingProvider({ children }: { children: ReactNode }) { enabled: !!user, }) - const steps = useMemo(() => visibleSteps(selectedPlan), [selectedPlan]) + const setCountry = useCallback((next: CountryCode) => { + setCountryState(next) + storeCountry(next) + }, []) + + /* El paso vive en `?step=`: cada avance es una entrada del historial, así el + gesto de back del dispositivo retrocede un paso en vez de salir del alta. + Lo que pide la URL pasa por `effectiveStep`, que no deja saltear el plan ni + volver al formulario con el grupo ya creado. */ + const plan = selectedPlan ?? statusQuery.data?.selectedPlan ?? null + const requestedStep = parseStep(search.step) ?? 'welcome' + const step = effectiveStep(requestedStep, { plan, hasCreatedGroup: createdGroup !== null }) + const steps = useMemo(() => visibleSteps(plan), [plan]) + + const goTo = useCallback( + (target: OnboardingStepId, options?: { replace?: boolean }) => { + void navigate({ + to: '/onboarding', + search: target === 'welcome' ? {} : { step: target }, + replace: options?.replace ?? false, + }) + }, + [navigate], + ) const goNext = () => { const next = steps[steps.indexOf(step) + 1] - if (next) setStep(next) + if (next) goTo(next) } + // Reemplaza en vez de apilar: así el back del dispositivo después de "Volver" + // no rebota al paso del que se salió. const goBack = () => { const previous = steps[steps.indexOf(step) - 1] - if (previous) setStep(previous) + if (previous) goTo(previous, { replace: true }) } + // Si la URL pedía un paso que no corresponde, se corrige sin apilar historial. + // Solo con el estado del servidor ya cargado: antes no se sabe el plan. + const hasStatus = statusQuery.data !== undefined + useEffect(() => { + if (hasStatus && search.step !== undefined && requestedStep !== step) { + goTo(step, { replace: true }) + } + }, [hasStatus, search.step, requestedStep, step, goTo]) + const callbackFeedback = useMemo( () => readMpCallbackFeedback(search.mp, search.reason), [search.mp, search.reason], @@ -81,15 +136,11 @@ export function OnboardingProvider({ children }: { children: ReactNode }) { // "cambiar de cuenta" y el resumen final ya sabe que hay cuenta. void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey }) void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] }) - // Vuelve al paso de Cobros, que es de donde salió el flujo. Setearlo siempre - // (y no solo desde el primer paso) evita que un `?mp=` que llega con el - // proveedor recién montado salte al resumen sin mostrar la confirmación. - setStep('payment') - - // Se limpian los parámetros de la URL: si no, recargar la página volvería a - // mostrar el aviso de la vinculación vieja. - void navigate({ to: '/onboarding', search: {}, replace: true }) - }, [callbackFeedback, navigate, queryClient]) + // Vuelve al paso de Cobros, que es de donde salió el flujo, y limpia los + // parámetros: si no, recargar volvería a mostrar el aviso de la vinculación + // vieja. + goTo('payment', { replace: true }) + }, [callbackFeedback, goTo, queryClient]) const whatsappCallbackFeedback = useMemo( () => readWhatsappCallbackFeedback(search.wa, search.reason), @@ -104,9 +155,8 @@ export function OnboardingProvider({ children }: { children: ReactNode }) { setWaFeedback(whatsappCallbackFeedback) void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey }) void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] }) - setStep('whatsapp') - void navigate({ to: '/onboarding', search: {}, replace: true }) - }, [whatsappCallbackFeedback, navigate, queryClient]) + goTo('whatsapp', { replace: true }) + }, [whatsappCallbackFeedback, goTo, queryClient]) // Vuelta de Mercado Pago tras la suscripción a Pro: el paso Plan muestra si // quedó activa o se sigue procesando (y deja seguir igual). @@ -117,9 +167,8 @@ export function OnboardingProvider({ children }: { children: ReactNode }) { setSelectedPlan('PRO') void queryClient.invalidateQueries({ queryKey: billingStatusQueryKey }) void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] }) - setStep('plan') - void navigate({ to: '/onboarding', search: {}, replace: true }) - }, [search.sub, navigate, queryClient]) + goTo('plan', { replace: true }) + }, [search.sub, goTo, queryClient]) useEffect(() => { const status = statusQuery.data @@ -128,18 +177,24 @@ export function OnboardingProvider({ children }: { children: ReactNode }) { // país y el plan elegidos se recuperan del servidor. if (status.country) setCountry(status.country) if (status.selectedPlan) setSelectedPlan((current) => current ?? status.selectedPlan) + }, [statusQuery.data, setCountry]) - // Retomar donde quedó, solo si recién arranca (desde la bienvenida). + // Retomar donde quedó, solo si la URL no pide un paso ni vuelve de un redirect + // (esos ya llevan al paso que corresponde). + const isReturningFromRedirect = Boolean(search.mp || search.wa || search.sub) + useEffect(() => { + const status = statusQuery.data + if (!status || search.step !== undefined || isReturningFromRedirect) return const resumeAt = resumeStep(status) - if (resumeAt) setStep((current) => (current === 'welcome' ? resumeAt : current)) - }, [statusQuery.data]) + if (resumeAt) goTo(resumeAt, { replace: true }) + }, [statusQuery.data, search.step, isReturningFromRedirect, goTo]) return ( (null) + const isFirstStep = useRef(true) + useLayoutEffect(() => { + previousIndex.current = stepIndex + }, [stepIndex]) + useEffect(() => { + if (isFirstStep.current) { + isFirstStep.current = false + return + } + window.scrollTo({ top: 0 }) + const container = stepContainer.current + if (!container || container.contains(document.activeElement)) return + const heading = container.querySelector('h1, h2') + if (!heading) return + heading.tabIndex = -1 + heading.focus({ preventScroll: true }) + }, [step]) + useEffect(() => { if (statusQuery.data?.completed) { void navigate({ to: '/' }) @@ -53,7 +80,7 @@ export function OnboardingView() { -

    {t('signedOut.title')}

    +

    {t('signedOut.title')}

    {t('signedOut.description')}

    @@ -80,7 +107,7 @@ export function OnboardingView() { const firstName = user.name?.trim().split(/\s+/)[0] ?? t('fallbackName') return ( -
    +
    @@ -89,10 +116,17 @@ export function OnboardingView() { los pasos que se van a recorrer. */} ({ label: t(`steps.${id}`) }))} - current={steps.indexOf(step)} + current={stepIndex} /> -
    +
    {step === 'welcome' ? : null} {step === 'country' ? : null} {step === 'plan' ? : null} @@ -107,7 +141,9 @@ export function OnboardingView() { onBack={goBack} onCompleted={(group) => { setCreatedGroup(group) - goTo('done') + // Reemplaza: el formulario ya no tiene que quedar en el historial + // (volver a él crearía otro grupo). + goTo('done', { replace: true }) }} /> ) : null} diff --git a/apps/web/src/features/onboarding/PaymentReminderPreview.tsx b/apps/web/src/features/onboarding/PaymentReminderPreview.tsx new file mode 100644 index 0000000..271982a --- /dev/null +++ b/apps/web/src/features/onboarding/PaymentReminderPreview.tsx @@ -0,0 +1,48 @@ +import { COUNTRY_CURRENCY, PRO_PRICE_BY_COUNTRY } from '@gruperly/shared' +import { useTranslation } from 'react-i18next' +import { useIntlLocale } from '../../i18n' +import { formatPrice } from '../../lib/format' +import { MessagePreview } from './MessagePreview' +import { useOnboarding } from './OnboardingProvider' + +type PaymentReminderPreviewProps = { + caption: string + className?: string +} + +/* Día de vencimiento y hora de la muestra: valores típicos, fijos para que la + vista previa no cambie entre renders. */ +const SAMPLE_DUE_DAY = 10 +const SAMPLE_TIME = new Date(2026, 0, 5, 10, 0) + +/** + * El recordatorio de pago semanal, con el mismo texto que arma el backend + * (`whatsapp/lib/render-message.ts`) y un ejemplo en la moneda del país elegido. + */ +export function PaymentReminderPreview({ caption, className }: PaymentReminderPreviewProps) { + const { t } = useTranslation('onboarding') + const locale = useIntlLocale() + const { country } = useOnboarding() + + const now = new Date() + const dueDate = new Date(now.getFullYear(), now.getMonth() + (now.getDate() >= SAMPLE_DUE_DAY ? 1 : 0), SAMPLE_DUE_DAY) + // El precio de ejemplo es el de Pro del país: un monto realista en su moneda. + const amount = formatPrice(PRO_PRICE_BY_COUNTRY[country], COUNTRY_CURRENCY[country]) + + return ( + + {t('preview.reminder', { + name: t('preview.sampleStudent'), + group: t('preview.sampleGroup'), + amount, + date: new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'long' }).format(dueDate), + })}{' '} + {t('preview.sampleLink')} + + ) +} diff --git a/apps/web/src/features/onboarding/PaymentStep.tsx b/apps/web/src/features/onboarding/PaymentStep.tsx index 2bbbc46..d2da981 100644 --- a/apps/web/src/features/onboarding/PaymentStep.tsx +++ b/apps/web/src/features/onboarding/PaymentStep.tsx @@ -51,7 +51,7 @@ export function PaymentStep({ feedback, onNext, onBack }: PaymentStepProps) { ) : null} {feedback?.kind === 'error' ? ( -

    +

    {mpCallbackErrorMessage(feedback.reason)}

    ) : null} @@ -82,7 +82,8 @@ export function PaymentStep({ feedback, onNext, onBack }: PaymentStepProps) {
    {startAuthorization.error ? ( -

    +

    {startAuthorization.error}

    ) : null}
    - - diff --git a/apps/web/src/features/onboarding/PlanStep.tsx b/apps/web/src/features/onboarding/PlanStep.tsx index 2d6098e..c5b2bb3 100644 --- a/apps/web/src/features/onboarding/PlanStep.tsx +++ b/apps/web/src/features/onboarding/PlanStep.tsx @@ -82,6 +82,17 @@ export function PlanStep() { mutation.mutate({ plan: 'PRO', country, payerEmail }) } + // Con Mercado Pago hay que pedir el email de la cuenta que paga; con Stripe no + // hay nada que completar (lo pide su checkout), así que se va directo. + const startPro = () => { + if (provider === 'MERCADO_PAGO') { + setError(null) + setIsEnteringEmail(true) + } else { + choosePro(undefined) + } + } + const proPrice = t('billing:view.perMonth', { price: formatPrice(PRO_PRICE_BY_COUNTRY[country], COUNTRY_CURRENCY[country]), }) @@ -93,7 +104,7 @@ export function PlanStep() { {t('plan.active')}

    - @@ -123,21 +134,21 @@ export function PlanStep() {
    - {error ?

    {error}

    : null} + {error ?

    {error}

    : null}
    {returnedFromSubscription ? ( - ) : ( <> - - @@ -151,7 +162,7 @@ export function PlanStep() {
    - )}
    - {error ?

    {error}

    : null} + {/* Con el form de Pro abierto, el error se muestra adentro, junto a lo que + se acaba de enviar. */} + {error && !isEnteringEmail ? ( +

    {error}

    + ) : null}
    - diff --git a/apps/web/src/features/onboarding/Stepper.tsx b/apps/web/src/features/onboarding/Stepper.tsx index b6bbc6e..1088415 100644 --- a/apps/web/src/features/onboarding/Stepper.tsx +++ b/apps/web/src/features/onboarding/Stepper.tsx @@ -9,55 +9,70 @@ export type StepperProps = { export function Stepper({ steps, current }: StepperProps) { const { t } = useTranslation('onboarding') + const currentLabel = steps[current]?.label + return ( -
      - {steps.map((step, index) => { - const isDone = index < current - const isActive = index === current +
      +
        + {steps.map((step, index) => { + const isDone = index < current + const isActive = index === current - return ( -
      1. -
        - - {isDone ? ( - - ) : ( - {index + 1} - )} - - - {step.label} - -
        + return ( +
      2. +
        + + + {step.label} + +
        - {index < steps.length - 1 ? ( - - ) : null} -
      3. - ) - })} -
      + {index < steps.length - 1 ? ( +
    + + {/* En mobile los nombres no entran debajo de cada círculo: el paso actual + se nombra en una línea, para que al volver de una interrupción se sepa + dónde se está. */} + {currentLabel ? ( + + ) : null} +
    ) -} \ No newline at end of file +} diff --git a/apps/web/src/features/onboarding/WelcomeStep.tsx b/apps/web/src/features/onboarding/WelcomeStep.tsx index eb84f54..7457078 100644 --- a/apps/web/src/features/onboarding/WelcomeStep.tsx +++ b/apps/web/src/features/onboarding/WelcomeStep.tsx @@ -1,65 +1,52 @@ -import { ArrowRight, Rocket, Users, Wallet } from 'lucide-react' +import { ArrowRight } from 'lucide-react' import { Button } from '../../components/ui' import { useTranslation } from 'react-i18next' +import { PaymentReminderPreview } from './PaymentReminderPreview' type WelcomeStepProps = { name: string onNext: () => void } -const STEPS_TO_SETUP = [ - { - icon: Wallet, - title: 'welcome.step1Title', - description: 'welcome.step1', - }, - { - icon: Users, - title: 'welcome.step2Title', - description: 'welcome.step2', - }, - { - icon: Rocket, - title: 'welcome.step3Title', - description: 'welcome.step3', - }, -] as const +/* El recorrido real del alta, en orden. Cobros y WhatsApp van en el medio y son + opcionales (y solo de Pro): la lista lo dice en vez de prometer un "cobrá al + instante" que con Free no existe. Labels: `onboarding:welcome.arc.*`. */ +const ARC = ['setup', 'connect', 'group'] as const export function WelcomeStep({ name, onNext }: WelcomeStepProps) { const { t } = useTranslation('onboarding') return ( -
    -
    - - - -

    {t('welcome.title', { name })}

    -

    - {t('welcome.description')} -

    +
    +
    +

    + {t('welcome.title', { name })} +

    +

    {t('welcome.description')}

    + +
      - {STEPS_TO_SETUP.map(({ icon: Icon, title, description }) => ( -
    1. - - + {ARC.map((id, index) => ( +
    2. + -
      -

      {t(title)}

      -

      {t(description)}

      +
      +

      {t(`welcome.arc.${id}Title`)}

      +

      {t(`welcome.arc.${id}`)}

    3. ))}
    -
    ) -} \ No newline at end of file +} diff --git a/apps/web/src/features/onboarding/WhatsappStep.tsx b/apps/web/src/features/onboarding/WhatsappStep.tsx index 3e42564..1931946 100644 --- a/apps/web/src/features/onboarding/WhatsappStep.tsx +++ b/apps/web/src/features/onboarding/WhatsappStep.tsx @@ -13,6 +13,7 @@ import { whatsappStatusLabel, } from '../whatsapp' import { useTranslation } from 'react-i18next' +import { PaymentReminderPreview } from './PaymentReminderPreview' type WhatsappStepProps = { /** Resultado de una vinculación por redirect, leído de `?wa=` al volver. */ @@ -46,7 +47,11 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {

    - {feedback?.kind === 'success' || (isConnected && !feedback) ? ( + {!isConnected ? : null} + + {/* El banner es la confirmación de una vinculación recién hecha. Si ya + estaba vinculado, alcanza con el estado de la tarjeta. */} + {feedback?.kind === 'success' ? (

    {statusQuery.data?.displayPhoneNumber @@ -56,7 +61,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) { ) : null} {feedback?.kind === 'error' ? ( -

    +

    {whatsappCallbackErrorMessage(feedback.reason)}

    ) : null} @@ -79,6 +84,13 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) { statusQuery.error instanceof ApiError ? statusQuery.error.status : null, )}

    + ) : isConnected ? ( +

    + {statusQuery.data?.displayPhoneNumber + ? t('whatsapp.connectedWith', { phone: statusQuery.data.displayPhoneNumber }) + : t('whatsapp.connected')}{' '} + {t('whatsapp.perGroup')} +

    ) : (

    {usesQr @@ -93,6 +105,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {

    {connection.error ? ( -

    {connection.error}

    +

    {connection.error}

    ) : null}
    - - diff --git a/apps/web/src/features/onboarding/steps.ts b/apps/web/src/features/onboarding/steps.ts index 1a65f0a..b15529c 100644 --- a/apps/web/src/features/onboarding/steps.ts +++ b/apps/web/src/features/onboarding/steps.ts @@ -14,7 +14,7 @@ export type OnboardingStepId = /** Labels: `onboarding:steps.`. */ -const ALL_STEPS: readonly OnboardingStepId[] = [ +export const ALL_STEPS: readonly OnboardingStepId[] = [ 'welcome', 'country', 'plan', @@ -45,3 +45,31 @@ export function resumeStep(status: OnboardingStatusDto): OnboardingStepId | null if (status.step === 'PAYMENT_CONNECTED') return status.whatsappConnected ? 'group' : 'whatsapp' return 'payment' } + +/** Lee `?step=` de la URL: cualquier valor desconocido es "sin paso". */ +export function parseStep(value: unknown): OnboardingStepId | undefined { + return typeof value === 'string' && (ALL_STEPS as readonly string[]).includes(value) + ? (value as OnboardingStepId) + : undefined +} + +/** Pasos que necesitan el plan ya elegido (el backend da 409 `plan_not_selected`). */ +const NEEDS_PLAN: readonly OnboardingStepId[] = ['payment', 'whatsapp', 'group', 'done'] + +/** + * El paso que realmente se muestra para el que pide la URL. El paso vive en + * `?step=` (así el back del dispositivo retrocede un paso), y una URL puede + * pedir uno que hoy no corresponde: sin plan no se pasa de Plan, con Free no + * hay Cobros ni WhatsApp, "Listo" sin grupo creado vuelve al formulario, y con + * el grupo ya creado no se vuelve a mostrar el formulario (crearía otro). + */ +export function effectiveStep( + requested: OnboardingStepId, + { plan, hasCreatedGroup }: { plan: Plan | null; hasCreatedGroup: boolean }, +): OnboardingStepId { + if (hasCreatedGroup) return 'done' + if (plan === null && NEEDS_PLAN.includes(requested)) return 'plan' + if (!visibleSteps(plan).includes(requested)) return 'group' + if (requested === 'done') return 'group' + return requested +} diff --git a/apps/web/src/i18n/locales/en/billing.json b/apps/web/src/i18n/locales/en/billing.json index e9a5784..b2736e0 100644 --- a/apps/web/src/i18n/locales/en/billing.json +++ b/apps/web/src/i18n/locales/en/billing.json @@ -56,7 +56,9 @@ }, "option": { "yourPlan": "Your plan", - "free": "Free" + "free": "Free", + "inPro": "in Pro", + "recommended": "Recommended" }, "charges": { "title": "Payment history", diff --git a/apps/web/src/i18n/locales/en/groups.json b/apps/web/src/i18n/locales/en/groups.json index ddde8fc..6af5dce 100644 --- a/apps/web/src/i18n/locales/en/groups.json +++ b/apps/web/src/i18n/locales/en/groups.json @@ -63,6 +63,8 @@ "billingType": "Billing type", "dueDay": "Due day", "dueDayHint": "Payments will be due on day {{day}} of each month.", - "submitting": "Creating…" + "submitting": "Creating…", + "whenLegend": "Classes", + "priceLegend": "Billing" } } diff --git a/apps/web/src/i18n/locales/en/home.json b/apps/web/src/i18n/locales/en/home.json index 2d748c6..cccc564 100644 --- a/apps/web/src/i18n/locales/en/home.json +++ b/apps/web/src/i18n/locales/en/home.json @@ -16,41 +16,47 @@ "seeAll": "See all", "empty": "No pending payments for now.", "linkMp": "Link Mercado Pago to get paid", - "hint": "You create them from each group's page." - }, - "stats": { - "groups_one": "Group", - "groups_other": "Groups", - "toCollect": "To collect", - "toCollectCount": "To collect · {{count}}", - "students_one": "Student", - "students_other": "Students" + "hint": "You create them from each group's page.", + "pending_one": "{{amount}} to collect across {{count}} payment", + "pending_other": "{{amount}} to collect across {{count}} payments" }, "nextClass": { "now": "Class in progress", "next": "Next class", - "nowBadge": "Happening now", - "seeGroup": "View group" + "nowBadge": "Happening now" }, "today": { - "label": "Today's class", - "attendanceTaken": "Attendance taken", - "time": "Today · {{time}}", + "time": "Today, {{time}}", "enrolled_one": "{{count}} enrolled", "enrolled_other": "{{count}} enrolled", "slots_one": "{{count}} spot left", "slots_other": "{{count}} spots left", - "seeAttendance": "View attendance", - "takeAttendance": "Take attendance" + "takeAttendance": "Take attendance", + "live": "In progress", + "listTitle": "Today's classes", + "state": { + "taken": "Attendance taken", + "missed": "Take attendance", + "upcoming": "Later", + "live": "In progress" + }, + "loadError": "We couldn't load today's classes." }, "attention": { "title": "Needs attention", - "allGood": "All good: no one at risk, no overdue payments or pre-registrations.", - "overdue_one": "{{count}} overdue payment", - "overdue_other": "{{count}} overdue payments", - "overdueHint": "Review them in Payments", + "allGood": "Nothing pending: no one at risk or with overdue fees.", "preRegistrations_one": "{{count}} pre-registration to approve", "preRegistrations_other": "{{count}} pre-registrations to approve", - "moreAtRisk": "And {{count}} more at risk. Check each group's stats." + "seeAll": "See all", + "more_one": "{{count}} more person to follow up", + "more_other": "{{count}} more people to follow up", + "loadError": "We couldn't load what needs attention." + }, + "loading": "Loading your day…", + "teaser": { + "sample1": "Sofia Martinez", + "sample2": "Tom Ruiz", + "description": "With Pro, see who owes you and how much here, and collect with Mercado Pago links.", + "cta": "Explore Pro" } } diff --git a/apps/web/src/i18n/locales/en/onboarding.json b/apps/web/src/i18n/locales/en/onboarding.json index f0310e1..d61daaa 100644 --- a/apps/web/src/i18n/locales/en/onboarding.json +++ b/apps/web/src/i18n/locales/en/onboarding.json @@ -7,26 +7,30 @@ "whatsapp": "WhatsApp", "group": "Your group", "done": "Done", - "progress": "Setup progress" + "progress": "Setup progress", + "position": "Step {{current}} of {{total}}" }, "continue": "Continue", "later": "I'll do it later", "signedOut": { - "title": "Your account is ready", + "title": "Sign in to continue", "description": "Sign in to set up your payments and create your first group.", "action": "Sign in" }, "fallbackName": "there", "welcome": { "title": "Hi, {{name}}!", - "description": "Let's set up your account in 3 steps. It takes less than 5 minutes.", - "step1Title": "Connect your payment account", - "step1": "Link Mercado Pago and charge your members from the group.", - "step2Title": "Create your first group", - "step2": "Days, time, price and capacity of your class.", - "step3Title": "Start collecting", - "step3": "All set to add members and get paid right away.", - "start": "Get started" + "description": "In a few minutes your account is ready to collect payments from your members and track class attendance.", + "start": "Get started", + "previewCaption": "With Pro, Gruperly reminds your members to pay on WhatsApp, from your own number:", + "arc": { + "setupTitle": "Your country and plan", + "setup": "So you charge in your currency. You can start for free.", + "connectTitle": "Payments and WhatsApp", + "connect": "Optional, with Pro: Mercado Pago and automatic reminders.", + "groupTitle": "Your first group", + "group": "Days, time, price and capacity of your class." + } }, "country": { "title": "Which country will you charge in?", @@ -54,7 +58,7 @@ "loading": "Checking your account…", "linkedOn": "Linked on {{date}}.", "connectedHint": "Your groups' payments will go into this account.", - "connectHint": "We'll take you to Mercado Pago to authorize payments. Money goes straight into your account, no middlemen.", + "connectHint": "We'll take you to Mercado Pago to authorize Gruperly: we use it to create your members' payment links and see which ones were paid. The money goes straight to your account, no middlemen.", "opening": "Opening Mercado Pago…", "change": "Change account", "connect": "Link account" @@ -67,27 +71,42 @@ "qrHint": "Link it with your phone number or by scanning a QR code, like WhatsApp Web.", "metaHint": "We'll take you to Meta to connect your WhatsApp Business account.", "perGroup": "You turn on automatic messages later in each group.", - "opening": "Opening…", - "connect": "Link WhatsApp" + "opening": "Preparing the link…", + "connect": "Link WhatsApp", + "previewCaption": "This is what a member with a pending fee receives:", + "connected": "Messages are sent from your number.", + "connectedWith": "Messages are sent from {{phone}}." }, "group": { - "heading": "Your first group" + "heading": "Your first group", + "choosePlan": "Choose a plan" }, "done": { - "title": "All set!", - "description": "Your group was created. You can now invite members and take attendance.", - "active": "Active", + "title": "Your group is ready", + "description": "Now add your members: send them this link, they fill in their details and you approve each request.", "price": "Price", "capacity": "Capacity", "capacityValue": "{{count}} members", "dueDay": "Due date", "dueDayValue": "Day {{day}} of each month", - "plan": "You're on the {{plan}} plan.", - "freeHint": " When you want to collect with Mercado Pago or automate WhatsApp, upgrade to Pro from Settings.", - "mpConnected": "You'll collect with Mercado Pago. Payments go straight into your account.", - "mpPending": "When you're ready to collect, link Mercado Pago from Settings. Your group is already created.", - "waConnected": "Your WhatsApp is linked. Turn on payment reminders and re-engagement from the group's page.", - "waPending": "To send automatic reminders, link WhatsApp from Settings.", - "goToPanel": "Go to my dashboard" + "previewCaption": "The message you'll share:", + "previewContact": "Your members", + "linkLoading": "Generating the link…", + "linkError": "We couldn't generate the invite link.", + "share": "Share on WhatsApp", + "copyLink": "Copy link", + "statusFree": "You're on {{plan}}. Collecting with Mercado Pago and automating WhatsApp are Pro features: turn them on anytime from Settings.", + "statusAllSet": "Mercado Pago and WhatsApp are linked. Turn on reminders from the group page.", + "statusPendingBoth": "When you want to collect payments and send reminders, link Mercado Pago and WhatsApp from Settings.", + "statusPendingMp": "WhatsApp is linked. To collect payments, link Mercado Pago from Settings.", + "statusPendingWa": "Mercado Pago is linked. For automatic reminders, link WhatsApp from Settings.", + "goHome": "Go to home" + }, + "preview": { + "sampleStudent": "Sofia", + "sampleStudentFull": "Sofia Martinez", + "sampleGroup": "Yoga · Level 1", + "reminder": "Hi {{name}}! This is a reminder about your {{group}} payment of {{amount}}, due on {{date}}. You can pay from this link:", + "sampleLink": "mercadopago.com/checkout/…" } } diff --git a/apps/web/src/i18n/locales/es-419/billing.json b/apps/web/src/i18n/locales/es-419/billing.json index b3af52d..02cacdb 100644 --- a/apps/web/src/i18n/locales/es-419/billing.json +++ b/apps/web/src/i18n/locales/es-419/billing.json @@ -56,7 +56,9 @@ }, "option": { "yourPlan": "Tu plan", - "free": "Gratis" + "free": "Gratis", + "inPro": "en Pro", + "recommended": "Recomendado" }, "charges": { "title": "Historial de pagos", diff --git a/apps/web/src/i18n/locales/es-419/groups.json b/apps/web/src/i18n/locales/es-419/groups.json index a69b501..bb76d43 100644 --- a/apps/web/src/i18n/locales/es-419/groups.json +++ b/apps/web/src/i18n/locales/es-419/groups.json @@ -63,6 +63,8 @@ "billingType": "Tipo de cobro", "dueDay": "Día de vencimiento", "dueDayHint": "Los cobros vencerán el día {{day}} de cada mes.", - "submitting": "Creando…" + "submitting": "Creando…", + "whenLegend": "Las clases", + "priceLegend": "El cobro" } } diff --git a/apps/web/src/i18n/locales/es-419/home.json b/apps/web/src/i18n/locales/es-419/home.json index 8a0fe2e..6dc5489 100644 --- a/apps/web/src/i18n/locales/es-419/home.json +++ b/apps/web/src/i18n/locales/es-419/home.json @@ -16,41 +16,47 @@ "seeAll": "Ver todos", "empty": "Sin cobros pendientes por ahora.", "linkMp": "Vincula Mercado Pago para cobrar", - "hint": "Los creas desde la ficha de cada grupo." - }, - "stats": { - "groups_one": "Grupo", - "groups_other": "Grupos", - "toCollect": "Por cobrar", - "toCollectCount": "Por cobrar · {{count}}", - "students_one": "Alumno", - "students_other": "Alumnos" + "hint": "Los creas desde la ficha de cada grupo.", + "pending_one": "{{amount}} por cobrar en {{count}} cobro", + "pending_other": "{{amount}} por cobrar en {{count}} cobros" }, "nextClass": { "now": "Clase en curso", "next": "Próxima clase", - "nowBadge": "En curso ahora", - "seeGroup": "Ver grupo" + "nowBadge": "En curso ahora" }, "today": { - "label": "Clase de hoy", - "attendanceTaken": "Asistencia tomada", - "time": "Hoy · {{time}} h", + "time": "Hoy, {{time}}", "enrolled_one": "{{count}} inscrito", "enrolled_other": "{{count}} inscritos", "slots_one": "{{count}} lugar disponible", "slots_other": "{{count}} lugares disponibles", - "seeAttendance": "Ver asistencia", - "takeAttendance": "Tomar asistencia" + "takeAttendance": "Tomar asistencia", + "live": "En curso", + "listTitle": "Clases de hoy", + "state": { + "taken": "Asistencia tomada", + "missed": "Tomar asistencia", + "upcoming": "Más tarde", + "live": "En curso" + }, + "loadError": "No pudimos cargar las clases de hoy." }, "attention": { "title": "Para atender", - "allGood": "Todo en orden: nadie en riesgo, sin cobros vencidos ni preinscripciones.", - "overdue_one": "{{count}} cobro vencido", - "overdue_other": "{{count}} cobros vencidos", - "overdueHint": "Revísalos en Cobros", + "allGood": "Nada pendiente: nadie en riesgo ni con cuotas vencidas.", "preRegistrations_one": "{{count}} preinscripción por aprobar", "preRegistrations_other": "{{count}} preinscripciones por aprobar", - "moreAtRisk": "Y {{count}} más en riesgo. Revisa las estadísticas de cada grupo." + "seeAll": "Ver todo", + "more_one": "{{count}} persona más por atender", + "more_other": "{{count}} personas más por atender", + "loadError": "No pudimos cargar los pendientes." + }, + "loading": "Cargando tu día…", + "teaser": { + "sample1": "Sofía Martínez", + "sample2": "Tomás Ruiz", + "description": "Con Pro, aquí ves quién te debe y cuánto, y cobras con enlaces de Mercado Pago.", + "cta": "Conoce Pro" } } diff --git a/apps/web/src/i18n/locales/es-419/onboarding.json b/apps/web/src/i18n/locales/es-419/onboarding.json index 2a6833f..a8139dc 100644 --- a/apps/web/src/i18n/locales/es-419/onboarding.json +++ b/apps/web/src/i18n/locales/es-419/onboarding.json @@ -7,26 +7,30 @@ "whatsapp": "WhatsApp", "group": "Tu grupo", "done": "Listo", - "progress": "Progreso del alta" + "progress": "Progreso del alta", + "position": "Paso {{current}} de {{total}}" }, "continue": "Continuar", "later": "Lo haré después", "signedOut": { - "title": "Tu cuenta, lista", + "title": "Inicia sesión para continuar", "description": "Inicia sesión para configurar tus cobros y crear tu primer grupo.", "action": "Iniciar sesión" }, "fallbackName": "profe", "welcome": { "title": "¡Hola, {{name}}!", - "description": "Configuremos tu cuenta en 3 pasos. Te tomará menos de 5 minutos.", - "step1Title": "Conecta tu cuenta de cobro", - "step1": "Vincula Mercado Pago y cóbrales a tus miembros desde el grupo.", - "step2Title": "Crea tu primer grupo", - "step2": "Días, horario, precio y cupo de tu clase.", - "step3Title": "Empieza a cobrar", - "step3": "Todo listo para sumar miembros y cobrar al instante.", - "start": "Comenzar" + "description": "En unos minutos dejas tu cuenta lista para cobrarles a tus miembros y llevar la asistencia de tus clases.", + "start": "Comenzar", + "previewCaption": "Con Pro, Gruperly les recuerda los pagos a tus miembros por WhatsApp, desde tu número:", + "arc": { + "setupTitle": "Tu país y tu plan", + "setup": "Para cobrar en tu moneda. Puedes empezar gratis.", + "connectTitle": "Cobros y WhatsApp", + "connect": "Opcional, con Pro: Mercado Pago y recordatorios automáticos.", + "groupTitle": "Tu primer grupo", + "group": "Días, horario, precio y cupo de tu clase." + } }, "country": { "title": "¿En qué país vas a cobrar?", @@ -54,7 +58,7 @@ "loading": "Consultando tu cuenta…", "linkedOn": "Vinculada el {{date}}.", "connectedHint": "Los pagos de tus grupos entrarán a esta cuenta.", - "connectHint": "Te llevamos a Mercado Pago para autorizar los cobros. Los pagos entran directo en tu cuenta, sin intermediarios.", + "connectHint": "Te llevamos a Mercado Pago para autorizar a Gruperly: lo usamos para crear los enlaces de cobro de tus miembros y ver cuáles se pagaron. El dinero entra directo a tu cuenta, sin intermediarios.", "opening": "Abriendo Mercado Pago…", "change": "Cambiar de cuenta", "connect": "Vincular cuenta" @@ -67,27 +71,42 @@ "qrHint": "Lo vinculas con tu número de teléfono o escaneando un código QR, como WhatsApp Web.", "metaHint": "Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.", "perGroup": "Los envíos automáticos los activas después en cada grupo.", - "opening": "Abriendo…", - "connect": "Vincular WhatsApp" + "opening": "Preparando la vinculación…", + "connect": "Vincular WhatsApp", + "previewCaption": "Esto es lo que recibe un miembro con la cuota pendiente:", + "connected": "Los mensajes salen desde tu número.", + "connectedWith": "Los mensajes salen desde {{phone}}." }, "group": { - "heading": "Tu primer grupo" + "heading": "Tu primer grupo", + "choosePlan": "Elegir un plan" }, "done": { - "title": "¡Todo listo!", - "description": "Tu grupo se creó. Ya puedes invitar miembros y pasar lista.", - "active": "Activo", + "title": "Tu grupo está listo", + "description": "Ahora suma a tus miembros: envíales este enlace, completan sus datos y tú apruebas cada solicitud.", "price": "Precio", "capacity": "Cupo", "capacityValue": "{{count}} miembros", "dueDay": "Vencimiento", "dueDayValue": "Día {{day}} de cada mes", - "plan": "Estás en el plan {{plan}}.", - "freeHint": " Cuando quieras cobrar con Mercado Pago o automatizar WhatsApp, cámbiate a Pro desde Ajustes.", - "mpConnected": "Cobrarás con Mercado Pago. Los pagos entran directo en tu cuenta.", - "mpPending": "Cuando quieras cobrar, vincula Mercado Pago desde Ajustes. Tu grupo ya quedó creado.", - "waConnected": "Tu WhatsApp está vinculado. Activa los recordatorios de pago y el reenganche desde la ficha del grupo.", - "waPending": "Para enviar recordatorios automáticos, vincula WhatsApp desde Ajustes.", - "goToPanel": "Ir a mi Panel" + "previewCaption": "El mensaje que vas a compartir:", + "previewContact": "Tus miembros", + "linkLoading": "Generando el enlace…", + "linkError": "No pudimos generar el enlace de invitación.", + "share": "Compartir por WhatsApp", + "copyLink": "Copiar enlace", + "statusFree": "Estás en {{plan}}. Cobrar con Mercado Pago y automatizar WhatsApp es de Pro: lo activas cuando quieras desde Ajustes.", + "statusAllSet": "Mercado Pago y WhatsApp quedaron vinculados. Activa los recordatorios desde la ficha del grupo.", + "statusPendingBoth": "Cuando quieras cobrar y enviar recordatorios, vincula Mercado Pago y WhatsApp desde Ajustes.", + "statusPendingMp": "WhatsApp quedó vinculado. Para cobrar, vincula Mercado Pago desde Ajustes.", + "statusPendingWa": "Mercado Pago quedó vinculado. Para los recordatorios automáticos, vincula WhatsApp desde Ajustes.", + "goHome": "Ir al inicio" + }, + "preview": { + "sampleStudent": "Sofía", + "sampleStudentFull": "Sofía Martínez", + "sampleGroup": "Yoga · Nivel 1", + "reminder": "¡Hola, {{name}}! Te recordamos el pago de {{group}} por {{amount}}, con vencimiento el {{date}}. Puedes pagarlo desde este enlace:", + "sampleLink": "mercadopago.com/checkout/…" } } diff --git a/apps/web/src/i18n/locales/es-AR/billing.json b/apps/web/src/i18n/locales/es-AR/billing.json index 1aaf781..c28b630 100644 --- a/apps/web/src/i18n/locales/es-AR/billing.json +++ b/apps/web/src/i18n/locales/es-AR/billing.json @@ -56,7 +56,9 @@ }, "option": { "yourPlan": "Tu plan", - "free": "Gratis" + "free": "Gratis", + "inPro": "en Pro", + "recommended": "Recomendado" }, "charges": { "title": "Historial de pagos", diff --git a/apps/web/src/i18n/locales/es-AR/groups.json b/apps/web/src/i18n/locales/es-AR/groups.json index a079c7c..87ca252 100644 --- a/apps/web/src/i18n/locales/es-AR/groups.json +++ b/apps/web/src/i18n/locales/es-AR/groups.json @@ -63,6 +63,8 @@ "billingType": "Tipo de cobro", "dueDay": "Día de vencimiento", "dueDayHint": "Los cobros vencerán el día {{day}} de cada mes.", - "submitting": "Creando…" + "submitting": "Creando…", + "whenLegend": "Las clases", + "priceLegend": "El cobro" } } diff --git a/apps/web/src/i18n/locales/es-AR/home.json b/apps/web/src/i18n/locales/es-AR/home.json index 0b05580..2f394ca 100644 --- a/apps/web/src/i18n/locales/es-AR/home.json +++ b/apps/web/src/i18n/locales/es-AR/home.json @@ -16,41 +16,47 @@ "seeAll": "Ver todos", "empty": "Sin cobros pendientes por ahora.", "linkMp": "Vinculá Mercado Pago para cobrar", - "hint": "Los creás desde la ficha de cada grupo." - }, - "stats": { - "groups_one": "Grupo", - "groups_other": "Grupos", - "toCollect": "Por cobrar", - "toCollectCount": "Por cobrar · {{count}}", - "students_one": "Alumno", - "students_other": "Alumnos" + "hint": "Los creás desde la ficha de cada grupo.", + "pending_one": "{{amount}} por cobrar en {{count}} cobro", + "pending_other": "{{amount}} por cobrar en {{count}} cobros" }, "nextClass": { "now": "Clase en curso", "next": "Próxima clase", - "nowBadge": "En curso ahora", - "seeGroup": "Ver grupo" + "nowBadge": "En curso ahora" }, "today": { - "label": "Clase de hoy", - "attendanceTaken": "Asistencia tomada", - "time": "Hoy · {{time}} hs", - "enrolled_one": "{{count}} inscrito", - "enrolled_other": "{{count}} inscritos", + "time": "Hoy, {{time}} hs", + "enrolled_one": "{{count}} inscripto", + "enrolled_other": "{{count}} inscriptos", "slots_one": "{{count}} cupo disponible", "slots_other": "{{count}} cupos disponibles", - "seeAttendance": "Ver asistencia", - "takeAttendance": "Tomar asistencia" + "takeAttendance": "Tomar asistencia", + "live": "En curso", + "listTitle": "Clases de hoy", + "state": { + "taken": "Asistencia tomada", + "missed": "Tomar asistencia", + "upcoming": "Más tarde", + "live": "En curso" + }, + "loadError": "No pudimos cargar las clases de hoy." }, "attention": { "title": "Para atender", - "allGood": "Todo en orden: nadie en riesgo, sin cobros vencidos ni preinscripciones.", - "overdue_one": "{{count}} cobro vencido", - "overdue_other": "{{count}} cobros vencidos", - "overdueHint": "Revisalos en Cobros", + "allGood": "Nada pendiente: nadie en riesgo ni con cuotas vencidas.", "preRegistrations_one": "{{count}} preinscripción por aprobar", "preRegistrations_other": "{{count}} preinscripciones por aprobar", - "moreAtRisk": "Y {{count}} más en riesgo. Mirá las estadísticas de cada grupo." + "seeAll": "Ver todo", + "more_one": "{{count}} persona más para atender", + "more_other": "{{count}} personas más para atender", + "loadError": "No pudimos cargar lo pendiente." + }, + "loading": "Cargando tu día…", + "teaser": { + "sample1": "Sofía Martínez", + "sample2": "Tomás Ruiz", + "description": "Con Pro, acá ves quién te debe y cuánto, y cobrás con links de Mercado Pago.", + "cta": "Conocé Pro" } } diff --git a/apps/web/src/i18n/locales/es-AR/onboarding.json b/apps/web/src/i18n/locales/es-AR/onboarding.json index ab23662..25b7151 100644 --- a/apps/web/src/i18n/locales/es-AR/onboarding.json +++ b/apps/web/src/i18n/locales/es-AR/onboarding.json @@ -7,26 +7,30 @@ "whatsapp": "WhatsApp", "group": "Tu grupo", "done": "Listo", - "progress": "Progreso del alta" + "progress": "Progreso del alta", + "position": "Paso {{current}} de {{total}}" }, "continue": "Continuar", "later": "Lo hago después", "signedOut": { - "title": "Tu cuenta, lista", + "title": "Iniciá sesión para seguir", "description": "Iniciá sesión para configurar tus cobros y crear tu primer grupo.", "action": "Iniciar sesión" }, "fallbackName": "profe", "welcome": { "title": "¡Hola, {{name}}!", - "description": "Vamos a configurar tu cuenta en 3 pasos. Vas a tardar menos de 5 minutos.", - "step1Title": "Conectá tu cuenta de cobro", - "step1": "Vinculá Mercado Pago y cobrale a tus miembros desde el grupo.", - "step2Title": "Creá tu primer grupo", - "step2": "Días, horario, precio y cupo de tu clase.", - "step3Title": "Empezá a cobrar", - "step3": "Todo listo para sumar miembros y cobrar al instante.", - "start": "Comenzar" + "description": "En unos minutos dejás tu cuenta lista para cobrarles a tus miembros y llevar la asistencia de tus clases.", + "start": "Comenzar", + "previewCaption": "Con Pro, Gruperly les recuerda los pagos a tus miembros por WhatsApp, desde tu número:", + "arc": { + "setupTitle": "Tu país y tu plan", + "setup": "Para cobrar en tu moneda. Podés empezar gratis.", + "connectTitle": "Cobros y WhatsApp", + "connect": "Opcional, con Pro: Mercado Pago y recordatorios automáticos.", + "groupTitle": "Tu primer grupo", + "group": "Días, horario, precio y cupo de tu clase." + } }, "country": { "title": "¿En qué país vas a cobrar?", @@ -54,7 +58,7 @@ "loading": "Consultando tu cuenta…", "linkedOn": "Vinculada el {{date}}.", "connectedHint": "Los pagos de tus grupos van a entrar a esta cuenta.", - "connectHint": "Te llevamos a Mercado Pago para autorizar los cobros. Los pagos entran directo en tu cuenta, sin intermediarios.", + "connectHint": "Te llevamos a Mercado Pago para autorizar a Gruperly: lo usamos para crear los links de cobro de tus miembros y ver cuáles se pagaron. La plata entra directo en tu cuenta, sin intermediarios.", "opening": "Abriendo Mercado Pago…", "change": "Cambiar de cuenta", "connect": "Vincular cuenta" @@ -67,27 +71,42 @@ "qrHint": "Lo vinculás con tu número de teléfono o escaneando un código QR, como WhatsApp Web.", "metaHint": "Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.", "perGroup": "Los envíos automáticos los prendés después en cada grupo.", - "opening": "Abriendo…", - "connect": "Vincular WhatsApp" + "opening": "Preparando la vinculación…", + "connect": "Vincular WhatsApp", + "previewCaption": "Esto es lo que recibe un miembro con la cuota pendiente:", + "connected": "Los mensajes salen desde tu número.", + "connectedWith": "Los mensajes salen desde {{phone}}." }, "group": { - "heading": "Tu primer grupo" + "heading": "Tu primer grupo", + "choosePlan": "Elegir un plan" }, "done": { - "title": "¡Todo listo!", - "description": "Tu grupo se creó. Ya podés invitar miembros y pasar lista.", - "active": "Activo", + "title": "Tu grupo está listo", + "description": "Ahora sumá a tus miembros: mandales este link, completan sus datos y vos aprobás cada solicitud.", "price": "Precio", "capacity": "Cupo", "capacityValue": "{{count}} miembros", "dueDay": "Vencimiento", "dueDayValue": "Día {{day}} de cada mes", - "plan": "Estás en el plan {{plan}}.", - "freeHint": " Cuando quieras cobrar con Mercado Pago o automatizar WhatsApp, pasate a Pro desde Ajustes.", - "mpConnected": "Vas a cobrar con Mercado Pago. Los pagos entran directo en tu cuenta.", - "mpPending": "Cuando quieras cobrar, vinculá Mercado Pago desde Ajustes. Tu grupo ya quedó creado.", - "waConnected": "Tu WhatsApp está vinculado. Activá los recordatorios de pago y el reenganche desde la ficha del grupo.", - "waPending": "Para enviar recordatorios automáticos, vinculá WhatsApp desde Ajustes.", - "goToPanel": "Ir a mi Panel" + "previewCaption": "El mensaje que vas a compartir:", + "previewContact": "Tus miembros", + "linkLoading": "Generando el link…", + "linkError": "No pudimos generar el link de invitación.", + "share": "Compartir por WhatsApp", + "copyLink": "Copiar link", + "statusFree": "Estás en {{plan}}. Cobrar con Mercado Pago y automatizar WhatsApp es de Pro: lo activás cuando quieras desde Ajustes.", + "statusAllSet": "Mercado Pago y WhatsApp quedaron vinculados. Prendé los recordatorios desde la ficha del grupo.", + "statusPendingBoth": "Cuando quieras cobrar y mandar recordatorios, vinculá Mercado Pago y WhatsApp desde Ajustes.", + "statusPendingMp": "WhatsApp quedó vinculado. Para cobrar, vinculá Mercado Pago desde Ajustes.", + "statusPendingWa": "Mercado Pago quedó vinculado. Para los recordatorios automáticos, vinculá WhatsApp desde Ajustes.", + "goHome": "Ir al inicio" + }, + "preview": { + "sampleStudent": "Sofía", + "sampleStudentFull": "Sofía Martínez", + "sampleGroup": "Yoga · Nivel 1", + "reminder": "¡Hola {{name}}! Te recordamos el pago de {{group}} por {{amount}}, con vencimiento el {{date}}. Podés pagarlo desde este link:", + "sampleLink": "mercadopago.com/checkout/…" } } diff --git a/apps/web/src/i18n/locales/pt-BR/billing.json b/apps/web/src/i18n/locales/pt-BR/billing.json index 549bac0..3515d30 100644 --- a/apps/web/src/i18n/locales/pt-BR/billing.json +++ b/apps/web/src/i18n/locales/pt-BR/billing.json @@ -56,7 +56,9 @@ }, "option": { "yourPlan": "Seu plano", - "free": "Grátis" + "free": "Grátis", + "inPro": "no Pro", + "recommended": "Recomendado" }, "charges": { "title": "Histórico de pagamentos", diff --git a/apps/web/src/i18n/locales/pt-BR/groups.json b/apps/web/src/i18n/locales/pt-BR/groups.json index e362cf6..189a728 100644 --- a/apps/web/src/i18n/locales/pt-BR/groups.json +++ b/apps/web/src/i18n/locales/pt-BR/groups.json @@ -63,6 +63,8 @@ "billingType": "Tipo de cobrança", "dueDay": "Dia de vencimento", "dueDayHint": "As cobranças vencerão todo dia {{day}}.", - "submitting": "Criando…" + "submitting": "Criando…", + "whenLegend": "As aulas", + "priceLegend": "A cobrança" } } diff --git a/apps/web/src/i18n/locales/pt-BR/home.json b/apps/web/src/i18n/locales/pt-BR/home.json index a5b6b49..8ad906d 100644 --- a/apps/web/src/i18n/locales/pt-BR/home.json +++ b/apps/web/src/i18n/locales/pt-BR/home.json @@ -16,41 +16,47 @@ "seeAll": "Ver todas", "empty": "Nenhuma cobrança pendente por enquanto.", "linkMp": "Vincule o Mercado Pago para cobrar", - "hint": "Você cria as cobranças na página de cada grupo." - }, - "stats": { - "groups_one": "Grupo", - "groups_other": "Grupos", - "toCollect": "A receber", - "toCollectCount": "A receber · {{count}}", - "students_one": "Aluno", - "students_other": "Alunos" + "hint": "Você cria as cobranças na página de cada grupo.", + "pending_one": "{{amount}} a receber em {{count}} cobrança", + "pending_other": "{{amount}} a receber em {{count}} cobranças" }, "nextClass": { "now": "Aula em andamento", "next": "Próxima aula", - "nowBadge": "Acontecendo agora", - "seeGroup": "Ver grupo" + "nowBadge": "Acontecendo agora" }, "today": { - "label": "Aula de hoje", - "attendanceTaken": "Presença registrada", - "time": "Hoje · {{time}}", + "time": "Hoje, {{time}}", "enrolled_one": "{{count}} inscrito", "enrolled_other": "{{count}} inscritos", "slots_one": "{{count}} vaga disponível", "slots_other": "{{count}} vagas disponíveis", - "seeAttendance": "Ver presença", - "takeAttendance": "Fazer chamada" + "takeAttendance": "Fazer chamada", + "live": "Em andamento", + "listTitle": "Aulas de hoje", + "state": { + "taken": "Presença registrada", + "missed": "Registrar presença", + "upcoming": "Mais tarde", + "live": "Em andamento" + }, + "loadError": "Não conseguimos carregar as aulas de hoje." }, "attention": { "title": "Para resolver", - "allGood": "Tudo certo: ninguém em risco, sem cobranças vencidas nem pré-inscrições.", - "overdue_one": "{{count}} cobrança vencida", - "overdue_other": "{{count}} cobranças vencidas", - "overdueHint": "Confira em Cobranças", + "allGood": "Nada pendente: ninguém em risco nem com mensalidades vencidas.", "preRegistrations_one": "{{count}} pré-inscrição para aprovar", "preRegistrations_other": "{{count}} pré-inscrições para aprovar", - "moreAtRisk": "E mais {{count}} em risco. Veja as estatísticas de cada grupo." + "seeAll": "Ver tudo", + "more_one": "Mais {{count}} pessoa para atender", + "more_other": "Mais {{count}} pessoas para atender", + "loadError": "Não conseguimos carregar as pendências." + }, + "loading": "Carregando seu dia…", + "teaser": { + "sample1": "Sofia Martins", + "sample2": "Tomás Rocha", + "description": "Com o Pro, aqui você vê quem deve e quanto, e cobra com links do Mercado Pago.", + "cta": "Conheça o Pro" } } diff --git a/apps/web/src/i18n/locales/pt-BR/onboarding.json b/apps/web/src/i18n/locales/pt-BR/onboarding.json index 6aa50e6..ae17a9a 100644 --- a/apps/web/src/i18n/locales/pt-BR/onboarding.json +++ b/apps/web/src/i18n/locales/pt-BR/onboarding.json @@ -7,26 +7,30 @@ "whatsapp": "WhatsApp", "group": "Seu grupo", "done": "Pronto", - "progress": "Progresso do cadastro" + "progress": "Progresso do cadastro", + "position": "Passo {{current}} de {{total}}" }, "continue": "Continuar", "later": "Faço depois", "signedOut": { - "title": "Sua conta, pronta", + "title": "Entre para continuar", "description": "Entre para configurar suas cobranças e criar seu primeiro grupo.", "action": "Entrar" }, "fallbackName": "professor", "welcome": { "title": "Olá, {{name}}!", - "description": "Vamos configurar sua conta em 3 passos. Leva menos de 5 minutos.", - "step1Title": "Conecte sua conta de recebimento", - "step1": "Vincule o Mercado Pago e cobre seus membros pelo grupo.", - "step2Title": "Crie seu primeiro grupo", - "step2": "Dias, horário, preço e vagas da sua aula.", - "step3Title": "Comece a cobrar", - "step3": "Tudo pronto para adicionar membros e cobrar na hora.", - "start": "Começar" + "description": "Em poucos minutos sua conta fica pronta para cobrar seus membros e registrar a presença nas aulas.", + "start": "Começar", + "previewCaption": "Com o Pro, o Gruperly lembra seus membros dos pagamentos pelo WhatsApp, a partir do seu número:", + "arc": { + "setupTitle": "Seu país e seu plano", + "setup": "Para cobrar na sua moeda. Você pode começar grátis.", + "connectTitle": "Cobranças e WhatsApp", + "connect": "Opcional, com o Pro: Mercado Pago e lembretes automáticos.", + "groupTitle": "Seu primeiro grupo", + "group": "Dias, horário, preço e vagas da sua aula." + } }, "country": { "title": "Em que país você vai cobrar?", @@ -54,7 +58,7 @@ "loading": "Consultando sua conta…", "linkedOn": "Vinculada em {{date}}.", "connectedHint": "Os pagamentos dos seus grupos vão entrar nesta conta.", - "connectHint": "Vamos te levar ao Mercado Pago para autorizar as cobranças. Os pagamentos entram direto na sua conta, sem intermediários.", + "connectHint": "Levamos você ao Mercado Pago para autorizar o Gruperly: usamos isso para criar os links de cobrança dos seus membros e ver quais foram pagos. O dinheiro cai direto na sua conta, sem intermediários.", "opening": "Abrindo o Mercado Pago…", "change": "Trocar de conta", "connect": "Vincular conta" @@ -67,27 +71,42 @@ "qrHint": "Você vincula com seu número de telefone ou escaneando um QR code, como no WhatsApp Web.", "metaHint": "Vamos te levar à Meta para conectar sua conta do WhatsApp Business.", "perGroup": "Os envios automáticos você ativa depois em cada grupo.", - "opening": "Abrindo…", - "connect": "Vincular WhatsApp" + "opening": "Preparando a vinculação…", + "connect": "Vincular WhatsApp", + "previewCaption": "Isto é o que recebe um membro com a mensalidade pendente:", + "connected": "As mensagens saem do seu número.", + "connectedWith": "As mensagens saem de {{phone}}." }, "group": { - "heading": "Seu primeiro grupo" + "heading": "Seu primeiro grupo", + "choosePlan": "Escolher um plano" }, "done": { - "title": "Tudo pronto!", - "description": "Seu grupo foi criado. Agora você pode convidar membros e fazer a chamada.", - "active": "Ativo", + "title": "Seu grupo está pronto", + "description": "Agora adicione seus membros: envie este link, eles preenchem os dados e você aprova cada solicitação.", "price": "Preço", "capacity": "Vagas", "capacityValue": "{{count}} membros", "dueDay": "Vencimento", "dueDayValue": "Todo dia {{day}}", - "plan": "Você está no plano {{plan}}.", - "freeHint": " Quando quiser cobrar com Mercado Pago ou automatizar o WhatsApp, mude para o Pro em Ajustes.", - "mpConnected": "Você vai cobrar com Mercado Pago. Os pagamentos entram direto na sua conta.", - "mpPending": "Quando quiser cobrar, vincule o Mercado Pago em Ajustes. Seu grupo já foi criado.", - "waConnected": "Seu WhatsApp está vinculado. Ative os lembretes de pagamento e o reengajamento na página do grupo.", - "waPending": "Para enviar lembretes automáticos, vincule o WhatsApp em Ajustes.", - "goToPanel": "Ir para o meu painel" + "previewCaption": "A mensagem que você vai compartilhar:", + "previewContact": "Seus membros", + "linkLoading": "Gerando o link…", + "linkError": "Não conseguimos gerar o link de convite.", + "share": "Compartilhar no WhatsApp", + "copyLink": "Copiar link", + "statusFree": "Você está no {{plan}}. Cobrar com o Mercado Pago e automatizar o WhatsApp é do Pro: ative quando quiser em Ajustes.", + "statusAllSet": "Mercado Pago e WhatsApp vinculados. Ative os lembretes na página do grupo.", + "statusPendingBoth": "Quando quiser cobrar e enviar lembretes, vincule o Mercado Pago e o WhatsApp em Ajustes.", + "statusPendingMp": "O WhatsApp foi vinculado. Para cobrar, vincule o Mercado Pago em Ajustes.", + "statusPendingWa": "O Mercado Pago foi vinculado. Para os lembretes automáticos, vincule o WhatsApp em Ajustes.", + "goHome": "Ir para o início" + }, + "preview": { + "sampleStudent": "Sofia", + "sampleStudentFull": "Sofia Martins", + "sampleGroup": "Yoga · Nível 1", + "reminder": "Olá, {{name}}! Lembramos do pagamento de {{group}} no valor de {{amount}}, com vencimento em {{date}}. Você pode pagar por este link:", + "sampleLink": "mercadopago.com/checkout/…" } } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 7613b06..a667727 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -92,6 +92,7 @@ /* Animations */ --animate-fade-in: fade-in 0.2s ease-out; --animate-step-enter: step-enter 0.35s cubic-bezier(0.22, 1, 0.36, 1) both; + --animate-step-enter-back: step-enter-back 0.35s cubic-bezier(0.22, 1, 0.36, 1) both; --animate-sheet-up: sheet-up 0.25s cubic-bezier(0.22, 1, 0.36, 1) both; @keyframes fade-in { @@ -114,6 +115,18 @@ transform: translateX(0); } } + + /* Al volver un paso, el contenido entra desde la izquierda. */ + @keyframes step-enter-back { + from { + opacity: 0; + transform: translateX(-1.5rem); + } + to { + opacity: 1; + transform: translateX(0); + } + } } :root { diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts index f74b09d..9033701 100644 --- a/apps/web/src/lib/format.ts +++ b/apps/web/src/lib/format.ts @@ -111,6 +111,37 @@ export function formatPrice( return tidyCurrencySpacing(formatter.format(price)) } +/** El símbolo de la moneda tal como lo escribe `formatPrice` ("$", "R$", "S/"). + Sin moneda, la del país del navegador, igual que `formatPrice`. */ +export function currencySymbol(currency?: string): string { + const browser = browserLocale() + const country = countryOf(browser) + const resolvedCurrency = currency ?? currencyForRegion(country) + if (!resolvedCurrency) return '$' + try { + const parts = new Intl.NumberFormat(localeForRegion(country) ?? browser, { + style: 'currency', + currency: resolvedCurrency, + currencyDisplay: 'narrowSymbol', + }).formatToParts(0) + return parts.find((part) => part.type === 'currency')?.value ?? '$' + } catch { + return '$' + } +} + +/** La hora de una clase: "19:00" en español y portugués (reloj de 24 h, que + es como se anuncia una clase en la región, aunque el sistema use 12 h) y la + del idioma en el resto ("7:00 PM"). */ +export function formatClockTime(date: Date | string, locale: string): string { + const uses24h = /^(es|pt)\b/i.test(locale) + return new Intl.DateTimeFormat(locale, { + hour: 'numeric', + minute: '2-digit', + ...(uses24h ? { hourCycle: 'h23' as const } : {}), + }).format(typeof date === 'string' ? new Date(date) : date) +} + /* Intl separates the currency symbol with a hard space: "$ 50.000" reads as two loose tokens. We strip it only when it separates symbol from number; between digits and the code ("50.000 ARS") the non-breaking space prevents the diff --git a/apps/web/src/routes/onboarding.tsx b/apps/web/src/routes/onboarding.tsx index 0cda82b..db7342d 100644 --- a/apps/web/src/routes/onboarding.tsx +++ b/apps/web/src/routes/onboarding.tsx @@ -1,20 +1,23 @@ import { createFileRoute } from '@tanstack/react-router' import { OnboardingProvider } from '../features/onboarding/OnboardingProvider' import { OnboardingView } from '../features/onboarding/OnboardingView' +import { type OnboardingStepId, parseStep } from '../features/onboarding/steps' export const Route = createFileRoute('/onboarding')({ /* Los callbacks de Mercado Pago (`?mp=`) y de WhatsApp por redirect (`?wa=`) devuelven el control acá con `success` o `error&reason=…`; la suscripción a - Pro vuelve con `?sub=return`. Se validan como + Pro vuelve con `?sub=return`. El paso actual vive en `?step=` para que el + back del dispositivo retroceda un paso. Se validan como search params para que el provider tenga los valores ya tipados y no tenga que leer el `location` crudo. */ validateSearch: ( search: Record, - ): { mp?: string; wa?: string; reason?: string; sub?: string } => ({ + ): { mp?: string; wa?: string; reason?: string; sub?: string; step?: OnboardingStepId } => ({ mp: typeof search.mp === 'string' ? search.mp : undefined, wa: typeof search.wa === 'string' ? search.wa : undefined, reason: typeof search.reason === 'string' ? search.reason : undefined, sub: typeof search.sub === 'string' ? search.sub : undefined, + step: parseStep(search.step), }), component: () => ( diff --git a/apps/web/test/home-day.test.ts b/apps/web/test/home-day.test.ts new file mode 100644 index 0000000..4f1e6c6 --- /dev/null +++ b/apps/web/test/home-day.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, test } from 'bun:test' +import type { ClassTodayDto } from '@gruperly/shared' +import { classState, planDay } from '../src/features/home/day' +import { formatClockTime } from '../src/lib/format' + +function session(id: string, startsAt: string, hasAttendance = false): ClassTodayDto { + return { + sessionId: id, + groupId: `g-${id}`, + groupName: `Grupo ${id}`, + startsAt, + enrolledCount: 5, + capacity: 10, + availableSlots: 5, + hasAttendance, + } +} + +const now = new Date('2026-11-05T22:00:00.000Z') + +describe('el día del Inicio', () => { + test('estado de cada clase', () => { + expect(classState(session('a', '2026-11-05T23:00:00.000Z'), now)).toBe('upcoming') + expect(classState(session('b', '2026-11-05T21:00:00.000Z'), now)).toBe('live') + expect(classState(session('c', '2026-11-05T18:00:00.000Z'), now)).toBe('missed') + expect(classState(session('d', '2026-11-05T21:00:00.000Z', true), now)).toBe('taken') + }) + + test('el hero es la clase en curso o la próxima sin asistencia; el resto va en orden', () => { + const morning = session('m', '2026-11-05T12:00:00.000Z', true) + const live = session('l', '2026-11-05T21:30:00.000Z') + const later = session('n', '2026-11-05T23:30:00.000Z') + const { hero, rest } = planDay([later, morning, live], now) + expect(hero?.sessionId).toBe('l') + expect(rest.map((item) => item.sessionId)).toEqual(['m', 'n']) + }) + + test('terminado el día no hay hero: las clases quedan en la lista', () => { + const missed = session('x', '2026-11-05T18:00:00.000Z') + const taken = session('y', '2026-11-05T19:00:00.000Z', true) + const { hero, rest } = planDay([taken, missed], now) + expect(hero).toBeNull() + expect(rest.map((item) => item.sessionId)).toEqual(['x', 'y']) + }) +}) + +describe('hora de una clase', () => { + test('24 h en español y portugués', () => { + const date = new Date(2026, 10, 5, 19, 0) + expect(formatClockTime(date, 'es-AR')).toBe('19:00') + expect(formatClockTime(date, 'pt-BR')).toBe('19:00') + expect(formatClockTime(new Date(2026, 10, 5, 9, 5), 'es-419')).toBe('09:05') + }) +}) diff --git a/apps/web/test/onboarding-steps.test.ts b/apps/web/test/onboarding-steps.test.ts index bb2c3f1..abc9e50 100644 --- a/apps/web/test/onboarding-steps.test.ts +++ b/apps/web/test/onboarding-steps.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test' import type { OnboardingStatusDto } from '@gruperly/shared' -import { resumeStep, visibleSteps } from '../src/features/onboarding/steps' +import { effectiveStep, parseStep, resumeStep, visibleSteps } from '../src/features/onboarding/steps' function status(overrides: Partial = {}): OnboardingStatusDto { return { @@ -46,3 +46,30 @@ describe('pasos del onboarding', () => { ).toBe('group') }) }) + +describe('paso pedido por la URL', () => { + test('solo acepta ids de pasos conocidos', () => { + expect(parseStep('plan')).toBe('plan') + expect(parseStep('nope')).toBeUndefined() + expect(parseStep(undefined)).toBeUndefined() + expect(parseStep(3)).toBeUndefined() + }) + + test('sin plan elegido no se pasa del paso Plan', () => { + expect(effectiveStep('group', { plan: null, hasCreatedGroup: false })).toBe('plan') + expect(effectiveStep('payment', { plan: null, hasCreatedGroup: false })).toBe('plan') + expect(effectiveStep('country', { plan: null, hasCreatedGroup: false })).toBe('country') + }) + + test('con Free no se muestran Cobros ni WhatsApp', () => { + expect(effectiveStep('payment', { plan: 'FREE', hasCreatedGroup: false })).toBe('group') + expect(effectiveStep('whatsapp', { plan: 'FREE', hasCreatedGroup: false })).toBe('group') + expect(effectiveStep('payment', { plan: 'PRO', hasCreatedGroup: false })).toBe('payment') + }) + + test('"Listo" necesita el grupo creado, y con el grupo creado no se vuelve al formulario', () => { + expect(effectiveStep('done', { plan: 'PRO', hasCreatedGroup: false })).toBe('group') + expect(effectiveStep('group', { plan: 'PRO', hasCreatedGroup: true })).toBe('done') + expect(effectiveStep('plan', { plan: 'FREE', hasCreatedGroup: true })).toBe('done') + }) +})