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:
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"
|
||||
|
||||
Reference in New Issue
Block a user