feat: add country selection during onboarding and implement payment management features
- Introduced CountryStep component for selecting the country during onboarding, affecting payment currency. - Updated FirstGroupStep to include country information. - Enhanced PaymentsProvider to manage payment states and renewals. - Created PaymentRow component for displaying individual payment details. - Implemented PaymentsView for listing and filtering payments by group and status. - Added API endpoints for fetching and creating payments, including batch processing. - Defined payment schemas for validation and data handling. - Updated GroupHeader and GroupDetailView to include charging functionality for group members.
This commit is contained in:
@@ -1,28 +1,20 @@
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import type { BillingType, CreateFirstGroup, WeekDay } from '@gruperly/shared'
|
||||
import { CreateFirstGroupSchema } from '@gruperly/shared'
|
||||
import type { BillingType, CountryCode, CreateFirstGroup, WeekDay } from '@gruperly/shared'
|
||||
import { CreateFirstGroupSchema, DEFAULT_COUNTRY } from '@gruperly/shared'
|
||||
import { ArrowLeft, Check, Loader2 } from 'lucide-react'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { Button, Input, Label } from '../../components/ui'
|
||||
import { BILLING_TYPES, WEEK_DAY_CHIPS } from '../onboarding/constants'
|
||||
|
||||
const defaultValues: CreateFirstGroup = {
|
||||
name: '',
|
||||
days: [],
|
||||
time: '09:00',
|
||||
capacity: 1,
|
||||
price: 0,
|
||||
billingType: 'MONTHLY',
|
||||
dueDay: 1,
|
||||
}
|
||||
|
||||
type GroupFormProps = {
|
||||
heading: string
|
||||
description: string
|
||||
submitLabel: string
|
||||
isSubmitting: boolean
|
||||
errorMessage?: string | null
|
||||
/** Solo lo usa el onboarding: ahí el país ya se eligió en el paso anterior. */
|
||||
country?: CountryCode
|
||||
onSubmit: (values: CreateFirstGroup) => void
|
||||
onBack?: () => void
|
||||
}
|
||||
@@ -33,9 +25,21 @@ export function GroupForm({
|
||||
submitLabel,
|
||||
isSubmitting,
|
||||
errorMessage,
|
||||
country = DEFAULT_COUNTRY,
|
||||
onSubmit,
|
||||
onBack,
|
||||
}: GroupFormProps) {
|
||||
const defaultValues: CreateFirstGroup = {
|
||||
name: '',
|
||||
days: [],
|
||||
time: '09:00',
|
||||
capacity: 1,
|
||||
price: 0,
|
||||
billingType: 'MONTHLY',
|
||||
dueDay: 1,
|
||||
country,
|
||||
}
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
|
||||
264
apps/web/src/features/groups/detail/ChargeMembersModal.tsx
Normal file
264
apps/web/src/features/groups/detail/ChargeMembersModal.tsx
Normal file
@@ -0,0 +1,264 @@
|
||||
import type { CreatePaymentsBatchResult, PaymentBatchItem } from '@gruperly/shared'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Check, Copy, Loader2, TriangleAlert, Wallet } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Badge, Button, Input, Label, Modal } from '../../../components/ui'
|
||||
import { ApiError, createPaymentsBatch } from '../../../lib/api'
|
||||
import { formatPrice } from '../../../lib/format'
|
||||
import { mpStatusBadgeVariant, mpStatusLabel, useMpStatus } from '../../mp'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
type ChargeMembersModalProps = {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
/** El payload viaja en el día local del profesor, no en la UTC del servidor. */
|
||||
function localDateValue(date: Date): string {
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
function monthLabel(date: Date): string {
|
||||
return date.toLocaleDateString('es-MX', { month: 'long', year: 'numeric' })
|
||||
}
|
||||
|
||||
function defaultDueDate(): Date {
|
||||
const now = new Date()
|
||||
return new Date(now.getFullYear(), now.getMonth() + 1, 1)
|
||||
}
|
||||
|
||||
type LinkRowProps = {
|
||||
item: PaymentBatchItem
|
||||
copiedId: string | null
|
||||
onCopy: (id: string) => void
|
||||
}
|
||||
|
||||
function LinkRow({ item, copiedId, onCopy }: LinkRowProps) {
|
||||
if (item.outcome !== 'LINKED' || !item.checkoutUrl) {
|
||||
return (
|
||||
<li className="flex items-center justify-between gap-3 rounded-lg bg-primary-soft px-3 py-2.5">
|
||||
<span className="min-w-0 truncate text-sm text-primary">{item.attendeeName}</span>
|
||||
<Badge variant="danger">No se generó</Badge>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
const copied = copiedId === item.paymentId
|
||||
return (
|
||||
<li className="flex items-center justify-between gap-3 rounded-lg bg-primary-soft px-3 py-2.5">
|
||||
<span className="min-w-0 truncate text-sm text-primary">{item.attendeeName}</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => onCopy(item.paymentId!)}
|
||||
className="shrink-0 gap-1.5"
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="size-3.5 text-success" />
|
||||
) : (
|
||||
<Copy className="size-3.5 text-accent" />
|
||||
)}
|
||||
{copied ? 'Copiado' : 'Copiar link'}
|
||||
</Button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* "Cobrar" de una ficha de grupo: crea un link de pago por miembro activo para
|
||||
* un período (Checkout Pro). Crear links no cobra a nadie: el profesor los
|
||||
* reenvía y los pagos entran directo a su cuenta de Mercado Pago.
|
||||
*/
|
||||
export function ChargeMembersModal({ isOpen, onClose }: ChargeMembersModalProps) {
|
||||
const { group } = useGroupDetail()
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const statusQuery = useMpStatus()
|
||||
|
||||
const [dueDate, setDueDate] = useState(() => localDateValue(defaultDueDate()))
|
||||
const [description, setDescription] = useState(() =>
|
||||
monthLabel(defaultDueDate()).replace(/^./, (ch) => ch.toUpperCase()),
|
||||
)
|
||||
const [submissionError, setSubmissionError] = useState<string | null>(null)
|
||||
const [result, setResult] = useState<CreatePaymentsBatchResult | null>(null)
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setSubmissionError(null)
|
||||
setResult(null)
|
||||
setCopiedId(null)
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: () =>
|
||||
createPaymentsBatch(group!.id, {
|
||||
dueDate: new Date(`${dueDate}T12:00:00.000Z`).toISOString(),
|
||||
description: description.trim() || undefined,
|
||||
}),
|
||||
onSuccess: (payload) => {
|
||||
setResult(payload)
|
||||
void queryClient.invalidateQueries({ queryKey: ['payments'] })
|
||||
},
|
||||
onError: (error: unknown) => {
|
||||
if (error instanceof ApiError) {
|
||||
setSubmissionError(
|
||||
error.problem?.code === 'mp_not_connected'
|
||||
? 'Tu cuenta de Mercado Pago no está vinculada.'
|
||||
: error.problem?.code === 'group_without_price'
|
||||
? 'Este grupo todavía no tiene precio.'
|
||||
: error.problem?.code === 'no_attendees_to_bill'
|
||||
? 'No hay miembros activos para cobrar.'
|
||||
: (error.problem?.detail ?? error.problem?.title ?? 'No pudimos crear los cobros.'),
|
||||
)
|
||||
} else {
|
||||
setSubmissionError('No pudimos crear los cobros.')
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
const status = statusQuery.data?.status ?? 'none'
|
||||
const isConnected = status === 'active'
|
||||
const price = group?.price ?? null
|
||||
|
||||
const copyItemLink = (paymentId: string) => {
|
||||
const item = result?.items.find((candidate) => candidate.paymentId === paymentId)
|
||||
if (!item?.checkoutUrl) return
|
||||
void navigator.clipboard.writeText(item.checkoutUrl).then(() => {
|
||||
setCopiedId(paymentId)
|
||||
window.setTimeout(() => setCopiedId(null), 1500)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title="Cobrar período"
|
||||
description={group?.name ? `Links de pago para ${group.name}` : undefined}
|
||||
maxWidth="md"
|
||||
>
|
||||
{!isConnected ? (
|
||||
<div className="space-y-4">
|
||||
<Badge variant={mpStatusBadgeVariant(status)}>{mpStatusLabel(status)}</Badge>
|
||||
<p className="flex items-start gap-2 rounded-xl bg-warning-soft px-4 py-3 text-sm text-warning">
|
||||
<TriangleAlert className="mt-0.5 size-4 shrink-0" />
|
||||
Para crear links de pago primero vinculá tu cuenta de Mercado Pago.
|
||||
</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
className="w-full"
|
||||
onClick={() => void navigate({ to: '/settings' })}
|
||||
>
|
||||
Conectar Mercado Pago
|
||||
</Button>
|
||||
</div>
|
||||
) : result ? (
|
||||
<div className="space-y-5">
|
||||
<p className="flex items-center gap-2 text-sm text-primary">
|
||||
<Wallet className="size-4 text-accent" />
|
||||
{result.linked} de {result.total} links creados
|
||||
</p>
|
||||
|
||||
<ul className="space-y-2">
|
||||
{result.items.map((item) => (
|
||||
<LinkRow key={item.paymentId} item={item} copiedId={copiedId} onCopy={copyItemLink} />
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{result.failed > 0 ? (
|
||||
<p className="rounded-xl bg-primary-soft px-4 py-3 text-xs leading-relaxed text-foreground/70">
|
||||
Los que no se generaron quedaron guardados: vas a poder crearles el link desde
|
||||
Cobros sin cargarle nada al alumno.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button variant="primary" onClick={onClose}>
|
||||
Listo
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<form
|
||||
className="space-y-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
setSubmissionError(null)
|
||||
create.mutate()
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between rounded-xl bg-primary-soft px-4 py-3">
|
||||
<span className="text-sm text-foreground/70">Cuota del grupo</span>
|
||||
<span className="text-sm font-semibold text-primary">{formatPrice(price)}</span>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="charge-due-date" className="mb-1.5 block">
|
||||
Vencimiento
|
||||
</Label>
|
||||
<Input
|
||||
id="charge-due-date"
|
||||
type="date"
|
||||
required
|
||||
autoFocus
|
||||
value={dueDate}
|
||||
onChange={(event) => {
|
||||
setDueDate(event.target.value)
|
||||
const picked = new Date(`${event.target.value}T12:00:00`)
|
||||
if (!Number.isNaN(picked.getTime())) {
|
||||
setDescription(monthLabel(picked).replace(/^./, (ch) => ch.toUpperCase()))
|
||||
}
|
||||
}}
|
||||
className="[&::-webkit-calendar-picker-indicator]:opacity-60"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="charge-description" className="mb-1.5 block">
|
||||
Período o concepto
|
||||
</Label>
|
||||
<Input
|
||||
id="charge-description"
|
||||
type="text"
|
||||
maxLength={120}
|
||||
value={description}
|
||||
onChange={(event) => setDescription(event.target.value)}
|
||||
placeholder="Ej.: Octubre 2026"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{submissionError ? (
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||
{submissionError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
<Button type="button" variant="ghost" onClick={onClose}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" disabled={create.isPending}>
|
||||
{create.isPending ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Wallet className="size-4" />
|
||||
)}
|
||||
Crear links de pago
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Button } from '../../../components/ui'
|
||||
import { ChargeMembersModal } from './ChargeMembersModal'
|
||||
import { GroupHeader } from './GroupHeader'
|
||||
import { GroupInfoCard } from './GroupInfoCard'
|
||||
import { InviteLinkModal } from './InviteLinkModal'
|
||||
@@ -22,13 +24,14 @@ export function GroupDetailView() {
|
||||
isSubmittingRemoval,
|
||||
} = useGroupDetail()
|
||||
const navigate = useNavigate()
|
||||
const [isChargeModalOpen, setIsChargeModalOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<section className="animate-fade-in space-y-5 sm:space-y-6">
|
||||
{/* The large title always renders, even while loading: it is what gives
|
||||
the immersive bar its height and stops the layout from jumping when
|
||||
the data arrives. */}
|
||||
<GroupHeader />
|
||||
<GroupHeader onCharge={() => setIsChargeModalOpen(true)} />
|
||||
|
||||
{groupQueryPending ? (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
@@ -66,6 +69,10 @@ export function GroupDetailView() {
|
||||
/>
|
||||
<WaitlistEntryDetailModal />
|
||||
<PreRegistrationDetailModal />
|
||||
<ChargeMembersModal
|
||||
isOpen={isChargeModalOpen}
|
||||
onClose={() => setIsChargeModalOpen(false)}
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
import { Link, useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowLeft, BarChart3, Share2, UserPlus } from 'lucide-react'
|
||||
import { ArrowLeft, BarChart3, Share2, UserPlus, Wallet } from 'lucide-react'
|
||||
import { Badge, Button, Tooltip } from '../../../components/ui'
|
||||
import { LargeTitle } from '../../../components/layout/LargeTitle'
|
||||
import { cn } from '../../../lib/utils'
|
||||
import { RISK_HINT, RISK_LABELS } from '../constants'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
export function GroupHeader() {
|
||||
export function GroupHeader({ onCharge }: { onCharge?: () => void }) {
|
||||
const {
|
||||
group,
|
||||
groupTitle,
|
||||
@@ -122,6 +122,20 @@ export function GroupHeader() {
|
||||
<BarChart3 className="size-4 text-accent" />
|
||||
<span className="hidden sm:inline">Estadísticas</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onCharge}
|
||||
disabled={group?.price == null}
|
||||
aria-label="Cobrar período"
|
||||
title={group?.price == null ? 'Definí el precio del grupo para poder cobrar' : undefined}
|
||||
className={cn(
|
||||
'h-11 shrink-0 justify-center border-border',
|
||||
!isEmptyGroup && 'w-11 sm:w-auto sm:px-4',
|
||||
)}
|
||||
>
|
||||
<Wallet className="size-4 text-accent" />
|
||||
<span className="hidden sm:inline">Cobrar</span>
|
||||
</Button>
|
||||
{!isEmptyGroup ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
|
||||
82
apps/web/src/features/onboarding/CountryStep.tsx
Normal file
82
apps/web/src/features/onboarding/CountryStep.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { CountryCode } from '@gruperly/shared'
|
||||
import { COUNTRY_CURRENCY, COUNTRY_LABELS, DEFAULT_COUNTRY } from '@gruperly/shared'
|
||||
import { ArrowLeft, ArrowRight } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Button } from '../../components/ui'
|
||||
import { cn } from '../../lib/utils'
|
||||
|
||||
export const COUNTRY_OPTIONS: readonly CountryCode[] = [
|
||||
'AR',
|
||||
'BR',
|
||||
'CL',
|
||||
'CO',
|
||||
'MX',
|
||||
'PE',
|
||||
'UY',
|
||||
]
|
||||
|
||||
type CountryStepProps = {
|
||||
onNext: () => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Paso "País" del onboarding.
|
||||
*
|
||||
* El país del profesor define la moneda con la que se generan los links de
|
||||
* cobro, así que se pregunta al empezar. Por default Argentina (la moneda por
|
||||
* default es ARS); se cambia después desde Ajustes.
|
||||
*/
|
||||
export function CountryStep({ onNext, onBack }: CountryStepProps) {
|
||||
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
|
||||
|
||||
return (
|
||||
<section className="space-y-5">
|
||||
<header className="space-y-1">
|
||||
<h2 className="text-2xl font-bold text-primary">¿En qué país vas a cobrar?</h2>
|
||||
<p className="text-sm text-foreground/60">
|
||||
Tus links se generan en la moneda de ese país.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div role="radiogroup" aria-label="País" className="space-y-2">
|
||||
{COUNTRY_OPTIONS.map((code) => {
|
||||
const isSelected = code === country
|
||||
return (
|
||||
<label
|
||||
key={code}
|
||||
className={cn(
|
||||
'flex cursor-pointer items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3 transition-colors',
|
||||
isSelected && 'border-accent bg-accent-soft ring-2 ring-accent/20',
|
||||
)}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="country"
|
||||
value={code}
|
||||
checked={isSelected}
|
||||
onChange={() => setCountry(code)}
|
||||
className="size-4 accent-accent"
|
||||
/>
|
||||
<span className="flex-1 text-sm font-medium text-primary">
|
||||
{COUNTRY_LABELS[code]}
|
||||
</span>
|
||||
<span className="text-sm text-foreground/50">{COUNTRY_CURRENCY[code]}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="outline" onClick={onBack} className="hidden lg:inline-flex">
|
||||
<ArrowLeft className="size-4" />
|
||||
Volver
|
||||
</Button>
|
||||
<Button variant="primary" className="flex-1 lg:flex-none" onClick={() => onNext()}>
|
||||
Continuar
|
||||
<ArrowRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { CreateFirstGroup, OnboardingGroupDto } from '@gruperly/shared'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { createFirstGroup } from '../../lib/api'
|
||||
import { GroupForm } from '../groups/GroupForm'
|
||||
import { useOnboarding } from './OnboardingProvider'
|
||||
|
||||
type FirstGroupStepProps = {
|
||||
onBack: () => void
|
||||
@@ -9,6 +10,7 @@ type FirstGroupStepProps = {
|
||||
}
|
||||
|
||||
export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) {
|
||||
const { country } = useOnboarding()
|
||||
const create = useMutation({
|
||||
mutationFn: (values: CreateFirstGroup) => createFirstGroup(values),
|
||||
onSuccess: (result) => onCompleted(result.group),
|
||||
@@ -19,6 +21,7 @@ export function FirstGroupStep({ onBack, onCompleted }: FirstGroupStepProps) {
|
||||
heading="Tu primer grupo"
|
||||
description="Definí los datos de la clase que vas a cobrar. Después siempre podés editarlos."
|
||||
submitLabel="Crear grupo"
|
||||
country={country}
|
||||
isSubmitting={create.isPending}
|
||||
errorMessage={
|
||||
create.isError ? 'No pudimos crear el grupo. Revisá los datos e intentá de nuevo.' : null
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared'
|
||||
import type { CountryCode, OnboardingGroupDto, OnboardingStatusDto } from '@gruperly/shared'
|
||||
import { 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'
|
||||
@@ -10,12 +11,15 @@ import type { MpCallbackFeedback } from '../mp'
|
||||
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
||||
|
||||
const WELCOME_STEP = 0
|
||||
const PAYMENT_STEP = 1
|
||||
const FIRST_GROUP_STEP = 2
|
||||
const PAYMENT_STEP = 2
|
||||
const FIRST_GROUP_STEP = 3
|
||||
|
||||
type OnboardingContextValue = {
|
||||
step: number
|
||||
setStep: (step: number) => void
|
||||
/** El país del profesor; define la moneda de los links de cobro. */
|
||||
country: CountryCode
|
||||
setCountry: (country: CountryCode) => void
|
||||
/** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */
|
||||
mpFeedback: MpCallbackFeedback | null
|
||||
createdGroup: OnboardingGroupDto | null
|
||||
@@ -31,6 +35,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient()
|
||||
const search = useSearch({ from: '/onboarding' })
|
||||
const [step, setStep] = useState(WELCOME_STEP)
|
||||
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
|
||||
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
|
||||
const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null)
|
||||
|
||||
@@ -79,6 +84,8 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
||||
value={{
|
||||
step,
|
||||
setStep,
|
||||
country,
|
||||
setCountry,
|
||||
mpFeedback,
|
||||
createdGroup,
|
||||
setCreatedGroup,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Logo, LogoIcon } from '../../components/brand'
|
||||
import { Button } from '../../components/ui'
|
||||
import { useAuth } from '../../context/AuthProvider'
|
||||
import { ConfirmationStep } from './ConfirmationStep'
|
||||
import { CountryStep } from './CountryStep'
|
||||
import { FirstGroupStep } from './FirstGroupStep'
|
||||
import { useOnboarding } from './OnboardingProvider'
|
||||
import { PaymentStep } from './PaymentStep'
|
||||
@@ -13,6 +14,7 @@ import { WelcomeStep } from './WelcomeStep'
|
||||
|
||||
const STEPS = [
|
||||
{ label: 'Bienvenida' },
|
||||
{ label: 'País' },
|
||||
{ label: 'Cobros' },
|
||||
{ label: 'Tu grupo' },
|
||||
{ label: 'Listo' },
|
||||
@@ -81,18 +83,21 @@ export function OnboardingView() {
|
||||
<div key={step} className="mt-8 animate-step-enter">
|
||||
{step === 0 ? <WelcomeStep name={firstName} onNext={() => setStep(1)} /> : null}
|
||||
{step === 1 ? (
|
||||
<PaymentStep feedback={mpFeedback} onNext={() => setStep(2)} onBack={() => setStep(0)} />
|
||||
<CountryStep onNext={() => setStep(2)} onBack={() => setStep(0)} />
|
||||
) : null}
|
||||
{step === 2 ? (
|
||||
<PaymentStep feedback={mpFeedback} onNext={() => setStep(3)} onBack={() => setStep(1)} />
|
||||
) : null}
|
||||
{step === 3 ? (
|
||||
<FirstGroupStep
|
||||
onBack={() => setStep(1)}
|
||||
onBack={() => setStep(2)}
|
||||
onCompleted={(group) => {
|
||||
setCreatedGroup(group)
|
||||
setStep(3)
|
||||
setStep(4)
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{step === 3 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
|
||||
{step === 4 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
|
||||
93
apps/web/src/features/payments/PaymentRow.tsx
Normal file
93
apps/web/src/features/payments/PaymentRow.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import type { PaymentDto } from '@gruperly/shared'
|
||||
import { Check, Copy, Link2, Loader2, RefreshCw } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Badge, Button } from '../../components/ui'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { formatPrice, PAYMENT_STATUS_LABELS } from '../../lib/format'
|
||||
import { paymentDateLabel, paymentPeriodLabel, PAYMENT_STATUS_BADGE } from './copy'
|
||||
|
||||
type PaymentRowProps = {
|
||||
payment: PaymentDto
|
||||
isRenewing: boolean
|
||||
onRenew: (paymentId: string) => void
|
||||
}
|
||||
|
||||
export function PaymentRow({ payment, isRenewing, onRenew }: PaymentRowProps) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const canCopy = Boolean(payment.checkoutUrl)
|
||||
const canRenew = !payment.checkoutUrl || payment.status === 'CANCELLED'
|
||||
|
||||
const copyLink = async () => {
|
||||
if (!payment.checkoutUrl) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(payment.checkoutUrl)
|
||||
setCopied(true)
|
||||
window.setTimeout(() => setCopied(false), 1500)
|
||||
} catch {
|
||||
// No clipboard: the link is lost in silence, renew opens a new one later.
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<li className="rounded-xl border border-border bg-surface p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-semibold text-primary">
|
||||
{payment.attendeeName}
|
||||
<span className="ml-2 font-normal text-foreground/60">{payment.groupName}</span>
|
||||
</p>
|
||||
<p className="mt-1 flex flex-wrap items-center gap-x-2 text-sm">
|
||||
<span className="font-medium text-primary">
|
||||
{formatPrice(payment.amount, payment.currency)}
|
||||
</span>
|
||||
<span className="text-xs text-foreground/50">{paymentPeriodLabel(payment)}</span>
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-foreground/50">{paymentDateLabel(payment)}</p>
|
||||
</div>
|
||||
<Badge variant={PAYMENT_STATUS_BADGE[payment.status]}>
|
||||
{PAYMENT_STATUS_LABELS[payment.status]}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
{canCopy ? (
|
||||
<Button variant="outline" size="sm" onClick={() => void copyLink()}>
|
||||
{copied ? (
|
||||
<Check className="size-3.5 text-success" />
|
||||
) : (
|
||||
<Copy className="size-3.5 text-accent" />
|
||||
)}
|
||||
{copied ? 'Copiado' : 'Copiar link'}
|
||||
</Button>
|
||||
) : (
|
||||
<span
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 text-xs text-foreground/40',
|
||||
payment.status === 'CANCELLED' && 'line-through',
|
||||
)}
|
||||
>
|
||||
<Link2 className="size-3.5" />
|
||||
Sin link
|
||||
</span>
|
||||
)}
|
||||
|
||||
{canRenew ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="ml-auto"
|
||||
disabled={isRenewing}
|
||||
onClick={() => onRenew(payment.id)}
|
||||
>
|
||||
{isRenewing ? (
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="size-3.5 text-accent" />
|
||||
)}
|
||||
Generar link
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
132
apps/web/src/features/payments/PaymentsProvider.tsx
Normal file
132
apps/web/src/features/payments/PaymentsProvider.tsx
Normal file
@@ -0,0 +1,132 @@
|
||||
import type { PaymentDto, PaymentQuery, PaymentStatus } from '@gruperly/shared'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { createContext, useContext, useMemo, useState } from 'react'
|
||||
import { ApiError, getGroups, getPayments, renewPaymentLink } from '../../lib/api'
|
||||
|
||||
export type PaymentFilterStatus = PaymentStatus | 'ALL'
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
function filterLabel(status: PaymentFilterStatus): string {
|
||||
return status === 'ALL' ? '' : status
|
||||
}
|
||||
|
||||
type PaymentsContextValue = {
|
||||
payments: PaymentDto[]
|
||||
total: number
|
||||
page: number
|
||||
totalPages: number
|
||||
isPending: boolean
|
||||
isFetching: boolean
|
||||
isError: boolean
|
||||
errorMessage: string | null
|
||||
groupId: string | null
|
||||
setGroupId: (groupId: string | null) => void
|
||||
status: PaymentFilterStatus
|
||||
setStatus: (status: PaymentFilterStatus) => void
|
||||
setPage: (page: number) => void
|
||||
retry: () => void
|
||||
renew: (paymentId: string) => void
|
||||
isRenewing: (paymentId: string) => boolean
|
||||
groups: { id: string; name: string }[]
|
||||
}
|
||||
|
||||
const PaymentsContext = createContext<PaymentsContextValue | null>(null)
|
||||
|
||||
export function PaymentsProvider({ children }: { children: ReactNode }) {
|
||||
const queryClient = useQueryClient()
|
||||
const [page, setPage] = useState(1)
|
||||
const [groupId, setGroupId] = useState<string | null>(null)
|
||||
const [status, setStatus] = useState<PaymentFilterStatus>('ALL')
|
||||
|
||||
const params = useMemo<PaymentQuery>(
|
||||
() => ({
|
||||
page,
|
||||
pageSize: PAGE_SIZE,
|
||||
...(groupId ? { groupId } : {}),
|
||||
...(status !== 'ALL' ? { status: filterLabel(status) as PaymentStatus } : {}),
|
||||
}),
|
||||
[page, groupId, status],
|
||||
)
|
||||
|
||||
const paymentsQuery = useQuery({
|
||||
queryKey: ['payments', params],
|
||||
queryFn: () => getPayments(params),
|
||||
placeholderData: (previous) => previous,
|
||||
})
|
||||
|
||||
// El filtro por grupo reutiliza el query de la pestaña Grupos (misma clave).
|
||||
const groupsQuery = useQuery({ queryKey: ['groups'], queryFn: getGroups })
|
||||
|
||||
const renewMutation = useMutation({
|
||||
mutationFn: renewPaymentLink,
|
||||
onSuccess: (updated) => {
|
||||
queryClient.setQueriesData<{ data: PaymentDto[] }>(
|
||||
{ queryKey: ['payments'] },
|
||||
(current) =>
|
||||
current
|
||||
? {
|
||||
...current,
|
||||
data: current.data.map((payment) =>
|
||||
payment.id === updated.id ? updated : payment,
|
||||
),
|
||||
}
|
||||
: current,
|
||||
)
|
||||
void queryClient.invalidateQueries({ queryKey: ['payments'] })
|
||||
},
|
||||
})
|
||||
|
||||
const renew = (paymentId: string) => renewMutation.mutate(paymentId)
|
||||
const isRenewing = (paymentId: string) => renewMutation.isPending && renewMutation.variables === paymentId
|
||||
|
||||
const data = paymentsQuery.data
|
||||
const pagination = data?.pagination
|
||||
|
||||
const errorMessage = paymentsQuery.isError
|
||||
? paymentsQuery.error instanceof ApiError
|
||||
? paymentsQuery.error.problem?.detail ?? 'No pudimos cargar tus cobros.'
|
||||
: 'No pudimos cargar tus cobros.'
|
||||
: null
|
||||
|
||||
return (
|
||||
<PaymentsContext.Provider
|
||||
value={{
|
||||
payments: data?.data ?? [],
|
||||
total: pagination?.total ?? 0,
|
||||
page,
|
||||
totalPages: pagination?.totalPages ?? 1,
|
||||
isPending: paymentsQuery.isPending,
|
||||
isFetching: paymentsQuery.isFetching,
|
||||
isError: paymentsQuery.isError,
|
||||
errorMessage,
|
||||
groupId,
|
||||
setGroupId: (value) => {
|
||||
setGroupId(value)
|
||||
setPage(1)
|
||||
},
|
||||
status,
|
||||
setStatus: (value) => {
|
||||
setStatus(value)
|
||||
setPage(1)
|
||||
},
|
||||
setPage,
|
||||
retry: () => void paymentsQuery.refetch(),
|
||||
renew,
|
||||
isRenewing,
|
||||
groups: groupsQuery.data?.data ?? [],
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</PaymentsContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function usePayments() {
|
||||
const context = useContext(PaymentsContext)
|
||||
if (!context) {
|
||||
throw new Error('usePayments debe usarse dentro de <PaymentsProvider>')
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -1,8 +1,163 @@
|
||||
import type { PaymentStatus } from '@gruperly/shared'
|
||||
import { ChevronLeft, ChevronRight, Loader2, Wallet } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
import { cn } from '../../lib/utils'
|
||||
import { PaymentRow } from './PaymentRow'
|
||||
import { usePayments } from './PaymentsProvider'
|
||||
|
||||
const STATUS_FILTERS: readonly { value: 'ALL' | PaymentStatus; label: string }[] = [
|
||||
{ value: 'ALL', label: 'Todos' },
|
||||
{ value: 'PENDING', label: 'Pendientes' },
|
||||
{ value: 'PAID', label: 'Pagados' },
|
||||
{ value: 'OVERDUE', label: 'Vencidos' },
|
||||
{ value: 'CANCELLED', label: 'Anulados' },
|
||||
]
|
||||
|
||||
export function PaymentsView() {
|
||||
const {
|
||||
payments,
|
||||
total,
|
||||
page,
|
||||
totalPages,
|
||||
isPending,
|
||||
isFetching,
|
||||
isError,
|
||||
errorMessage,
|
||||
groupId,
|
||||
setGroupId,
|
||||
status,
|
||||
setStatus,
|
||||
setPage,
|
||||
retry,
|
||||
renew,
|
||||
isRenewing,
|
||||
groups,
|
||||
} = usePayments()
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h1 className="text-2xl font-bold text-primary">Cobros</h1>
|
||||
<p className="mt-2 text-sm text-foreground/60">Sigue los pagos de tus grupos.</p>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-primary">Cobros</h1>
|
||||
<p className="mt-1 text-sm text-foreground/60">Seguí los pagos de tus grupos.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filtros: el grupo primera (cada cobro cuelga de un grupo) y el estado. */}
|
||||
<div className="mt-5 space-y-3">
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-sm font-medium text-primary">Grupo</span>
|
||||
<select
|
||||
value={groupId ?? ''}
|
||||
onChange={(event) => setGroupId(event.target.value || null)}
|
||||
className="h-10 w-full rounded-xl border border-border bg-surface px-3 text-base text-primary sm:text-sm focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/30"
|
||||
>
|
||||
<option value="">Todos los grupos</option>
|
||||
{groups.map((group) => (
|
||||
<option key={group.id} value={group.id}>
|
||||
{group.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div role="tablist" aria-label="Filtrar por estado" className="flex gap-2 overflow-x-auto">
|
||||
{STATUS_FILTERS.map((filter) => {
|
||||
const isActive = status === filter.value
|
||||
return (
|
||||
<button
|
||||
key={filter.value}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={isActive}
|
||||
onClick={() => setStatus(filter.value)}
|
||||
className={cn(
|
||||
'shrink-0 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors',
|
||||
isActive
|
||||
? 'border-accent bg-accent text-on-accent'
|
||||
: 'border-border bg-surface text-foreground/70 hover:text-primary',
|
||||
)}
|
||||
>
|
||||
{filter.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isPending ? (
|
||||
<div className="mt-8 flex items-center justify-center py-16" role="status">
|
||||
<Loader2 className="size-6 animate-spin text-secondary/50" aria-hidden="true" />
|
||||
<span className="sr-only">Cargando cobros</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isError ? (
|
||||
<div className="mt-8 space-y-3 rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||
<p>{errorMessage}</p>
|
||||
<Button variant="outline" size="sm" onClick={retry}>
|
||||
Reintentar
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!isPending && !isError && payments.length === 0 ? (
|
||||
<div className="mt-8 rounded-xl bg-primary-soft px-5 py-12 text-center">
|
||||
<span className="mx-auto flex size-14 items-center justify-center rounded-2xl bg-accent-soft text-accent-fg">
|
||||
<Wallet className="size-7" aria-hidden="true" />
|
||||
</span>
|
||||
<p className="mt-4 text-base font-semibold text-primary">Todavía no hay cobros</p>
|
||||
<p className="mx-auto mt-1.5 max-w-[34ch] text-sm leading-relaxed text-secondary">
|
||||
Entrá a un grupo, abrí la ficha y creá los links de cobro del período.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!isPending && !isError && payments.length > 0 ? (
|
||||
<>
|
||||
<ul className="mt-5 space-y-3">
|
||||
{payments.map((payment) => (
|
||||
<PaymentRow
|
||||
key={payment.id}
|
||||
payment={payment}
|
||||
isRenewing={isRenewing(payment.id)}
|
||||
onRenew={renew}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<div className="mt-6 flex items-center justify-between gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage(page - 1)}
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
Anteriores
|
||||
</Button>
|
||||
<p className="text-xs text-foreground/50">
|
||||
Página {page} de {totalPages} · {total} cobros
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => setPage(page + 1)}
|
||||
>
|
||||
Siguientes
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isFetching && page > 1 ? (
|
||||
<p className="flex items-center justify-center gap-2 py-4 text-sm text-foreground/50">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
Actualizando…
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
32
apps/web/src/features/payments/copy.ts
Normal file
32
apps/web/src/features/payments/copy.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { PaymentDto } from '@gruperly/shared'
|
||||
import type { BadgeVariant } from '../../components/ui'
|
||||
|
||||
export const PAYMENT_STATUS_BADGE: Record<PaymentDto['status'], BadgeVariant> = {
|
||||
PENDING: 'neutral',
|
||||
PAID: 'success',
|
||||
OVERDUE: 'danger',
|
||||
CANCELLED: 'warning',
|
||||
}
|
||||
|
||||
export function paymentPeriodLabel(payment: PaymentDto): string {
|
||||
return payment.description ?? payment.groupName
|
||||
}
|
||||
|
||||
export function paymentDateLabel(payment: PaymentDto): string {
|
||||
if (payment.status === 'PAID' && payment.paidAt) {
|
||||
return `Cobrada el ${formatDay(payment.paidAt)}`
|
||||
}
|
||||
return `Vence el ${formatDay(payment.dueDate)}`
|
||||
}
|
||||
|
||||
/* Fechas sin hora: el vencimiento es un día, no un instante. */
|
||||
function formatDay(iso: string): string {
|
||||
const date = new Date(iso)
|
||||
const today = new Date()
|
||||
const sameYear = date.getFullYear() === today.getFullYear()
|
||||
return date.toLocaleDateString('es-MX', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
...(sameYear ? {} : { year: 'numeric' }),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user