feat(whatsapp): mensajes automáticos semanales con proveedor intercambiable
- Puerto MessagingProvider con adaptadores OpenWA (MVP, QR) y Kapso (setup link de Meta + templates), elegido con WHATSAPP_PROVIDER. - Vinculación del WhatsApp del profesor en el onboarding y en Ajustes. - Job semanal (lunes 10:00 AR): recordatorio de pago y reenganche a alumnos en riesgo (cooldown 14 días), con switches por grupo. - Idempotencia por (kind, attendee, semana ISO), webhooks firmados con HMAC y deduplicados, normalización de teléfonos a E.164. - Servicio openwa en docker-compose y guía en docs/whatsapp.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
89
apps/web/src/features/groups/detail/GroupAutomationsCard.tsx
Normal file
89
apps/web/src/features/groups/detail/GroupAutomationsCard.tsx
Normal file
@@ -0,0 +1,89 @@
|
||||
import type { GroupAutomationsDto } from '@gruperly/shared'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { MessageCircle } from 'lucide-react'
|
||||
import { Switch } from '../../../components/ui'
|
||||
import { automationBlockedReason, useWhatsappStatus, WEEKLY_SEND_LABEL } from '../../whatsapp'
|
||||
import { useGroupDetail } from './GroupDetailProvider'
|
||||
|
||||
type Automation = {
|
||||
key: keyof GroupAutomationsDto
|
||||
kind: 'PAYMENT_REMINDER' | 'REENGAGEMENT'
|
||||
title: string
|
||||
description: string
|
||||
}
|
||||
|
||||
const AUTOMATIONS: readonly Automation[] = [
|
||||
{
|
||||
key: 'autoPaymentReminders',
|
||||
kind: 'PAYMENT_REMINDER',
|
||||
title: 'Recordatorio semanal de pago',
|
||||
description: 'A quien tenga un cobro pendiente o vencido, con su link de pago.',
|
||||
},
|
||||
{
|
||||
key: 'autoReengagement',
|
||||
kind: 'REENGAGEMENT',
|
||||
title: 'Mensaje de reenganche semanal',
|
||||
description: 'A los miembros en riesgo por faltas. Como mucho uno cada 2 semanas.',
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* Los envíos automáticos por WhatsApp del grupo. Solo el dueño los cambia: los
|
||||
* mensajes salen de su número. Se pueden apagar siempre; prenderlos exige un
|
||||
* WhatsApp vinculado y el mensaje aprobado.
|
||||
*/
|
||||
export function GroupAutomationsCard() {
|
||||
const { group, updateAutomations, isUpdatingAutomations, isGroupOwner } = useGroupDetail()
|
||||
const whatsappQuery = useWhatsappStatus({ enabled: isGroupOwner })
|
||||
if (!group || !isGroupOwner) return null
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border border-border bg-surface">
|
||||
<header className="flex items-start gap-3 px-4 pt-3">
|
||||
<span className="rounded-lg bg-success-soft p-2">
|
||||
<MessageCircle className="size-4 text-success" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-sm font-semibold text-primary">Mensajes automáticos por WhatsApp</h2>
|
||||
<p className="text-xs text-foreground/50">{WEEKLY_SEND_LABEL}</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<ul className="divide-y divide-border">
|
||||
{AUTOMATIONS.map((automation) => {
|
||||
const checked = group[automation.key]
|
||||
const blocked = automationBlockedReason(whatsappQuery.data, automation.kind)
|
||||
const hintId = `automation-${automation.key}-hint`
|
||||
return (
|
||||
<li key={automation.key} className="flex items-start gap-3 px-4 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm text-primary">{automation.title}</p>
|
||||
<p id={hintId} className="text-xs text-foreground/50">
|
||||
{automation.description}
|
||||
{blocked && !checked ? (
|
||||
<>
|
||||
{' '}
|
||||
<span className="text-warning">{blocked}</span>{' '}
|
||||
{whatsappQuery.data?.status !== 'active' ? (
|
||||
<Link to="/settings" className="font-medium text-accent-fg underline">
|
||||
Ir a Ajustes
|
||||
</Link>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={checked}
|
||||
disabled={isUpdatingAutomations || (!checked && blocked !== null)}
|
||||
aria-label={automation.title}
|
||||
aria-describedby={hintId}
|
||||
onCheckedChange={(next) => updateAutomations({ [automation.key]: next })}
|
||||
/>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type {
|
||||
AttendeeDto,
|
||||
UpdateGroupAutomations,
|
||||
AttendeeListItem,
|
||||
GroupDto,
|
||||
GroupPreRegistrationDto,
|
||||
@@ -10,6 +11,7 @@ import type {
|
||||
GroupRiskLevel,
|
||||
} from '@gruperly/shared'
|
||||
import { useToast } from '../../../components/ui'
|
||||
import { useAuth } from '../../../context/AuthProvider'
|
||||
import {
|
||||
ApiError,
|
||||
approveGroupPreRegistration,
|
||||
@@ -22,6 +24,7 @@ import {
|
||||
promoteGroupWaitlistEntry,
|
||||
rejectGroupPreRegistration,
|
||||
removeGroupWaitlistEntry,
|
||||
updateGroupAutomations,
|
||||
} from '../../../lib/api'
|
||||
import { useRemoveAttendee } from './useRemoveAttendee'
|
||||
|
||||
@@ -80,6 +83,10 @@ type GroupDetailContextValue = {
|
||||
copyInviteLink: () => Promise<void>
|
||||
copyWhatsappMessage: () => Promise<void>
|
||||
openWhatsapp: () => Promise<void>
|
||||
/** Solo el dueño ve y cambia las automatizaciones: salen de su WhatsApp. */
|
||||
isGroupOwner: boolean
|
||||
updateAutomations: (patch: UpdateGroupAutomations) => void
|
||||
isUpdatingAutomations: boolean
|
||||
}
|
||||
|
||||
const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
||||
@@ -87,6 +94,7 @@ const GroupDetailContext = createContext<GroupDetailContextValue | null>(null)
|
||||
export function GroupDetailProvider({ groupId, children }: { groupId: string; children: ReactNode }) {
|
||||
const queryClient = useQueryClient()
|
||||
const toast = useToast()
|
||||
const { user } = useAuth()
|
||||
|
||||
const [isInviteModalOpen, setIsInviteModalOpen] = useState(false)
|
||||
const [listSection, setListSectionState] = useState<ListSection>('members')
|
||||
@@ -172,6 +180,19 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
},
|
||||
})
|
||||
|
||||
const automationsMutation = useMutation({
|
||||
mutationFn: (patch: UpdateGroupAutomations) => updateGroupAutomations(groupId, patch),
|
||||
onSuccess: (automations) => {
|
||||
queryClient.setQueryData<GroupDto>(['group', groupId], (current) =>
|
||||
current ? { ...current, ...automations } : current,
|
||||
)
|
||||
toast.success('Guardamos los mensajes automáticos del grupo.')
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message || 'No se pudieron guardar los mensajes automáticos.')
|
||||
},
|
||||
})
|
||||
|
||||
const removeAttendeeMutation = useRemoveAttendee({
|
||||
groupId,
|
||||
onRemoved: () => setAttendeeToRemove(null),
|
||||
@@ -303,6 +324,9 @@ export function GroupDetailProvider({ groupId, children }: { groupId: string; ch
|
||||
group,
|
||||
groupTitle,
|
||||
groupQueryPending: groupQuery.isPending,
|
||||
isGroupOwner: Boolean(group && user && group.createdById === user.id),
|
||||
updateAutomations: (patch) => automationsMutation.mutate(patch),
|
||||
isUpdatingAutomations: automationsMutation.isPending,
|
||||
riskLevel: riskOverviewQuery.data?.items.find((item) => item.groupId === groupId)?.riskLevel ?? 'NONE',
|
||||
attendees,
|
||||
attendeesTotal,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Loader2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Button } from '../../../components/ui'
|
||||
import { ChargeMembersModal } from './ChargeMembersModal'
|
||||
import { GroupAutomationsCard } from './GroupAutomationsCard'
|
||||
import { GroupHeader } from './GroupHeader'
|
||||
import { GroupInfoCard } from './GroupInfoCard'
|
||||
import { InviteLinkModal } from './InviteLinkModal'
|
||||
@@ -52,6 +53,7 @@ export function GroupDetailView() {
|
||||
) : (
|
||||
<>
|
||||
<GroupInfoCard />
|
||||
<GroupAutomationsCard />
|
||||
<MembersWaitlistSection />
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { OnboardingGroupDto } from '@gruperly/shared'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { ArrowRight, CheckCircle2, CreditCard } from 'lucide-react'
|
||||
import { ArrowRight, CheckCircle2, CreditCard, MessageCircle } from 'lucide-react'
|
||||
import { Badge, Button } from '../../components/ui'
|
||||
import { useAuth } from '../../context/AuthProvider'
|
||||
import { MP_PROVIDER_NAME, useMpStatus } from '../mp'
|
||||
import { useWhatsappStatus } from '../whatsapp'
|
||||
import { BILLING_LABELS, formatPrice, formatSchedule } from './constants'
|
||||
|
||||
type ConfirmationStepProps = {
|
||||
@@ -17,6 +18,8 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
|
||||
const { refresh } = useAuth()
|
||||
const statusQuery = useMpStatus()
|
||||
const isMpConnected = statusQuery.data?.status === 'active'
|
||||
const whatsappQuery = useWhatsappStatus()
|
||||
const isWhatsappConnected = whatsappQuery.data?.status === 'active'
|
||||
|
||||
const goToDashboard = () => {
|
||||
// Revalidates the cache (onboarding state, session, groups) before redirecting.
|
||||
@@ -86,6 +89,23 @@ export function ConfirmationStep({ group }: ConfirmationStepProps) {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 rounded-xl bg-primary-soft px-4 py-3">
|
||||
<MessageCircle className="size-4 shrink-0 text-accent" />
|
||||
<p className="text-xs text-primary">
|
||||
{isWhatsappConnected ? (
|
||||
<>
|
||||
Tu WhatsApp está vinculado. Activá los recordatorios de pago y el reenganche desde la
|
||||
ficha del grupo.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Para enviar recordatorios automáticos, vinculá{' '}
|
||||
<span className="font-semibold">WhatsApp</span> desde Ajustes.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button variant="primary" className="w-full" onClick={goToDashboard}>
|
||||
Ir a mi Panel
|
||||
<ArrowRight className="size-4" />
|
||||
|
||||
@@ -9,10 +9,13 @@ import { useAuth } from '../../context/AuthProvider'
|
||||
import { getOnboardingStatus } from '../../lib/api'
|
||||
import type { MpCallbackFeedback } from '../mp'
|
||||
import { mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
||||
import type { WhatsappCallbackFeedback } from '../whatsapp'
|
||||
import { readWhatsappCallbackFeedback, whatsappStatusQueryKey } from '../whatsapp'
|
||||
|
||||
const WELCOME_STEP = 0
|
||||
const PAYMENT_STEP = 2
|
||||
const FIRST_GROUP_STEP = 3
|
||||
const WHATSAPP_STEP = 3
|
||||
const FIRST_GROUP_STEP = 4
|
||||
|
||||
type OnboardingContextValue = {
|
||||
step: number
|
||||
@@ -22,6 +25,8 @@ type OnboardingContextValue = {
|
||||
setCountry: (country: CountryCode) => void
|
||||
/** Lo que volvió de Mercado Pago en `?mp=`, ya traducido a feedback. */
|
||||
mpFeedback: MpCallbackFeedback | null
|
||||
/** Lo que volvió de una vinculación de WhatsApp por redirect en `?wa=`. */
|
||||
waFeedback: WhatsappCallbackFeedback | null
|
||||
createdGroup: OnboardingGroupDto | null
|
||||
setCreatedGroup: (group: OnboardingGroupDto) => void
|
||||
statusQuery: UseQueryResult<OnboardingStatusDto>
|
||||
@@ -37,6 +42,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
||||
const [step, setStep] = useState(WELCOME_STEP)
|
||||
const [country, setCountry] = useState<CountryCode>(DEFAULT_COUNTRY)
|
||||
const [mpFeedback, setMpFeedback] = useState<MpCallbackFeedback | null>(null)
|
||||
const [waFeedback, setWaFeedback] = useState<WhatsappCallbackFeedback | null>(null)
|
||||
const [createdGroup, setCreatedGroup] = useState<OnboardingGroupDto | null>(null)
|
||||
|
||||
const statusQuery = useQuery({
|
||||
@@ -68,14 +74,33 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
||||
void navigate({ to: '/onboarding', search: {}, replace: true })
|
||||
}, [callbackFeedback, navigate, queryClient])
|
||||
|
||||
const whatsappCallbackFeedback = useMemo(
|
||||
() => readWhatsappCallbackFeedback(search.wa, search.reason),
|
||||
[search.wa, search.reason],
|
||||
)
|
||||
|
||||
// Igual que `?mp=`: al volver de una vinculación por redirect (Kapso) se
|
||||
// muestra el resultado en el paso de WhatsApp y se limpian los parámetros.
|
||||
useEffect(() => {
|
||||
if (!whatsappCallbackFeedback) return
|
||||
|
||||
setWaFeedback(whatsappCallbackFeedback)
|
||||
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||
setStep(WHATSAPP_STEP)
|
||||
void navigate({ to: '/onboarding', search: {}, replace: true })
|
||||
}, [whatsappCallbackFeedback, navigate, queryClient])
|
||||
|
||||
useEffect(() => {
|
||||
const status = statusQuery.data
|
||||
if (!status) return
|
||||
// Si dejó el onboarding después de vincular los cobros, se retoma en el
|
||||
// grupo. Con la cuenta ya activa el paso 1 ya muestra "Cambiar de cuenta",
|
||||
// así que solo se salta desde la bienvenida.
|
||||
// Si dejó el onboarding después de vincular los cobros, se retoma en
|
||||
// WhatsApp (o en el grupo, si también lo vinculó). Con la cuenta ya activa
|
||||
// el paso de Cobros muestra "Cambiar de cuenta", así que solo se salta
|
||||
// desde la bienvenida.
|
||||
if (status.step === 'PAYMENT_CONNECTED') {
|
||||
setStep((current) => (current === WELCOME_STEP ? FIRST_GROUP_STEP : current))
|
||||
const resumeAt = status.whatsappConnected ? FIRST_GROUP_STEP : WHATSAPP_STEP
|
||||
setStep((current) => (current === WELCOME_STEP ? resumeAt : current))
|
||||
}
|
||||
}, [statusQuery.data])
|
||||
|
||||
@@ -87,6 +112,7 @@ export function OnboardingProvider({ children }: { children: ReactNode }) {
|
||||
country,
|
||||
setCountry,
|
||||
mpFeedback,
|
||||
waFeedback,
|
||||
createdGroup,
|
||||
setCreatedGroup,
|
||||
statusQuery,
|
||||
|
||||
@@ -11,11 +11,13 @@ import { useOnboarding } from './OnboardingProvider'
|
||||
import { PaymentStep } from './PaymentStep'
|
||||
import { Stepper } from './Stepper'
|
||||
import { WelcomeStep } from './WelcomeStep'
|
||||
import { WhatsappStep } from './WhatsappStep'
|
||||
|
||||
const STEPS = [
|
||||
{ label: 'Bienvenida' },
|
||||
{ label: 'País' },
|
||||
{ label: 'Cobros' },
|
||||
{ label: 'WhatsApp' },
|
||||
{ label: 'Tu grupo' },
|
||||
{ label: 'Listo' },
|
||||
]
|
||||
@@ -23,7 +25,8 @@ const STEPS = [
|
||||
export function OnboardingView() {
|
||||
const { user, isPending: authPending } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
const { step, setStep, mpFeedback, createdGroup, setCreatedGroup, statusQuery } = useOnboarding()
|
||||
const { step, setStep, mpFeedback, waFeedback, createdGroup, setCreatedGroup, statusQuery } =
|
||||
useOnboarding()
|
||||
|
||||
useEffect(() => {
|
||||
if (statusQuery.data?.completed) {
|
||||
@@ -89,15 +92,18 @@ export function OnboardingView() {
|
||||
<PaymentStep feedback={mpFeedback} onNext={() => setStep(3)} onBack={() => setStep(1)} />
|
||||
) : null}
|
||||
{step === 3 ? (
|
||||
<WhatsappStep feedback={waFeedback} onNext={() => setStep(4)} onBack={() => setStep(2)} />
|
||||
) : null}
|
||||
{step === 4 ? (
|
||||
<FirstGroupStep
|
||||
onBack={() => setStep(2)}
|
||||
onBack={() => setStep(3)}
|
||||
onCompleted={(group) => {
|
||||
setCreatedGroup(group)
|
||||
setStep(4)
|
||||
setStep(5)
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
{step === 4 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
|
||||
{step === 5 && createdGroup ? <ConfirmationStep group={createdGroup} /> : null}
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
|
||||
123
apps/web/src/features/onboarding/WhatsappStep.tsx
Normal file
123
apps/web/src/features/onboarding/WhatsappStep.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
import { ArrowLeft, ArrowRight, BadgeCheck, CheckCircle2, Loader2 } from 'lucide-react'
|
||||
import { Badge, Button } from '../../components/ui'
|
||||
import type { WhatsappCallbackFeedback } from '../whatsapp'
|
||||
import {
|
||||
linksWithQr,
|
||||
useStartWhatsappConnection,
|
||||
useWhatsappStatus,
|
||||
WhatsappQrModal,
|
||||
whatsappCallbackErrorMessage,
|
||||
whatsappStatusBadgeVariant,
|
||||
whatsappStatusLabel,
|
||||
} from '../whatsapp'
|
||||
|
||||
type WhatsappStepProps = {
|
||||
/** Resultado de una vinculación por redirect, leído de `?wa=` al volver. */
|
||||
feedback: WhatsappCallbackFeedback | null
|
||||
onNext: () => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Paso "WhatsApp" del onboarding: vincular el número desde el que salen los
|
||||
* recordatorios de pago y los mensajes de reenganche.
|
||||
*
|
||||
* Es salteable igual que "Cobros": se puede hacer después desde Ajustes, y los
|
||||
* envíos automáticos se activan grupo por grupo.
|
||||
*/
|
||||
export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
|
||||
const statusQuery = useWhatsappStatus()
|
||||
const connection = useStartWhatsappConnection()
|
||||
|
||||
const status = statusQuery.data?.status ?? 'none'
|
||||
const isConnected = status === 'active'
|
||||
const usesQr = statusQuery.data ? linksWithQr(statusQuery.data.provider) : true
|
||||
|
||||
return (
|
||||
<section className="space-y-5">
|
||||
<header className="space-y-1">
|
||||
<h2 className="text-2xl font-bold text-primary">Conectá tu WhatsApp</h2>
|
||||
<p className="text-sm text-foreground/60">
|
||||
Gruperly le recuerda los pagos a tus miembros y escribe a los que dejaron de venir, una
|
||||
vez por semana y desde tu número.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{feedback?.kind === 'success' || (isConnected && !feedback) ? (
|
||||
<p className="flex items-start gap-2 rounded-xl bg-success-soft px-4 py-3 text-sm text-success">
|
||||
<CheckCircle2 className="mt-0.5 size-4 shrink-0" />
|
||||
Tu WhatsApp quedó vinculado
|
||||
{statusQuery.data?.displayPhoneNumber ? ` (${statusQuery.data.displayPhoneNumber})` : ''}.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{feedback?.kind === 'error' ? (
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">
|
||||
{whatsappCallbackErrorMessage(feedback.reason)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
|
||||
<div className="flex items-center justify-between gap-3 px-4 py-3">
|
||||
<p className="text-sm font-medium text-primary">WhatsApp</p>
|
||||
<Badge variant={whatsappStatusBadgeVariant(status)}>{whatsappStatusLabel(status)}</Badge>
|
||||
</div>
|
||||
|
||||
<div className="px-4 py-3">
|
||||
{statusQuery.isPending ? (
|
||||
<p className="flex items-center gap-2 text-sm text-foreground/50">
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
Consultando tu WhatsApp…
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm text-foreground/60">
|
||||
{usesQr
|
||||
? 'Vas a escanear un código QR desde WhatsApp, como cuando usás WhatsApp Web.'
|
||||
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}{' '}
|
||||
Los envíos automáticos los prendés después en cada grupo.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isConnected ? (
|
||||
<div className="px-4 py-3">
|
||||
<Button
|
||||
variant="primary"
|
||||
className="w-full"
|
||||
disabled={connection.isStarting || statusQuery.isError}
|
||||
onClick={() => void connection.start('onboarding')}
|
||||
>
|
||||
{connection.isStarting ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<BadgeCheck className="size-4" />
|
||||
)}
|
||||
{connection.isStarting ? 'Abriendo…' : 'Vincular WhatsApp'}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{connection.error ? (
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||
) : null}
|
||||
|
||||
<WhatsappQrModal
|
||||
isOpen={connection.isQrOpen}
|
||||
onClose={connection.closeQr}
|
||||
initialQrCode={connection.initialQrCode}
|
||||
/>
|
||||
|
||||
<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="outline" className="flex-1 lg:flex-none" onClick={onNext}>
|
||||
{isConnected ? 'Continuar' : 'Lo hago después'}
|
||||
<ArrowRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -3,9 +3,13 @@ import { Fingerprint } from 'lucide-react'
|
||||
import { Button } from '../../components/ui'
|
||||
import { signOut } from '../../lib/auth-client'
|
||||
import { MpStatusCard } from '../mp'
|
||||
import { WhatsappStatusCard } from '../whatsapp'
|
||||
import { AppearanceCard } from './AppearanceCard'
|
||||
import { useCallbackFeedbackToast } from './useCallbackFeedbackToast'
|
||||
|
||||
export function SettingsView() {
|
||||
useCallbackFeedbackToast()
|
||||
|
||||
const handleSignOut = async () => {
|
||||
await signOut({
|
||||
fetchOptions: { headers: { 'Cache-Control': 'no-cache' } },
|
||||
@@ -34,6 +38,8 @@ export function SettingsView() {
|
||||
|
||||
<MpStatusCard />
|
||||
|
||||
<WhatsappStatusCard />
|
||||
|
||||
<AppearanceCard />
|
||||
|
||||
<Button variant="outline" onClick={handleSignOut}>
|
||||
|
||||
43
apps/web/src/features/settings/useCallbackFeedbackToast.ts
Normal file
43
apps/web/src/features/settings/useCallbackFeedbackToast.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate, useSearch } from '@tanstack/react-router'
|
||||
import { useEffect } from 'react'
|
||||
import { useToast } from '../../components/ui'
|
||||
import { mpCallbackErrorMessage, mpStatusQueryKey, readMpCallbackFeedback } from '../mp'
|
||||
import {
|
||||
readWhatsappCallbackFeedback,
|
||||
whatsappCallbackErrorMessage,
|
||||
whatsappStatusQueryKey,
|
||||
} from '../whatsapp'
|
||||
|
||||
/**
|
||||
* Al volver a Ajustes desde Mercado Pago (`?mp=`) o desde una vinculación de
|
||||
* WhatsApp por redirect (`?wa=`) se avisa el resultado con un toast y se limpian
|
||||
* los parámetros: si no, recargar la página repetiría el aviso.
|
||||
*/
|
||||
export function useCallbackFeedbackToast() {
|
||||
const search = useSearch({ from: '/_authenticated/settings' })
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const toast = useToast()
|
||||
|
||||
useEffect(() => {
|
||||
const mp = readMpCallbackFeedback(search.mp, search.reason)
|
||||
const wa = readWhatsappCallbackFeedback(search.wa, search.reason)
|
||||
if (!mp && !wa) return
|
||||
|
||||
if (mp) {
|
||||
if (mp.kind === 'success') toast.success('Tu cuenta de Mercado Pago quedó vinculada.')
|
||||
else toast.error(mpCallbackErrorMessage(mp.reason))
|
||||
void queryClient.invalidateQueries({ queryKey: mpStatusQueryKey })
|
||||
}
|
||||
if (wa) {
|
||||
if (wa.kind === 'success') toast.success('Tu WhatsApp quedó vinculado.')
|
||||
else toast.error(whatsappCallbackErrorMessage(wa.reason))
|
||||
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||
}
|
||||
|
||||
void navigate({ to: '/settings', search: {}, replace: true })
|
||||
// `toast` cambia en cada aviso: el efecto depende solo de la URL, si no se
|
||||
// dispararía otra vez con cada toast.
|
||||
}, [search.mp, search.wa, search.reason, navigate, queryClient])
|
||||
}
|
||||
67
apps/web/src/features/whatsapp/WhatsappQrModal.tsx
Normal file
67
apps/web/src/features/whatsapp/WhatsappQrModal.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import { Loader2, Smartphone } from 'lucide-react'
|
||||
import { useEffect } from 'react'
|
||||
import { Modal, useToast } from '../../components/ui'
|
||||
import { useWhatsappStatus } from './useWhatsappStatus'
|
||||
|
||||
type WhatsappQrModalProps = {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
/** QR de la respuesta de `connect`; se reemplaza por el del estado apenas llega. */
|
||||
initialQrCode: string | null
|
||||
}
|
||||
|
||||
/**
|
||||
* Vinculación por QR: el profesor lo escanea desde su teléfono como un
|
||||
* "dispositivo vinculado". El estado se consulta cada 2 s mientras está
|
||||
* pendiente, así que el QR se renueva y el modal se cierra solo al vincularse.
|
||||
*/
|
||||
export function WhatsappQrModal({ isOpen, onClose, initialQrCode }: WhatsappQrModalProps) {
|
||||
const toast = useToast()
|
||||
const statusQuery = useWhatsappStatus({ enabled: isOpen })
|
||||
const status = statusQuery.data?.status
|
||||
const qrCode = statusQuery.data?.qrCode ?? initialQrCode
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
if (status === 'active') {
|
||||
toast.success('¡Listo! Tu WhatsApp quedó vinculado.')
|
||||
onClose()
|
||||
} else if (status === 'disconnected') {
|
||||
toast.error('La vinculación no se completó. Volvé a intentarlo.')
|
||||
onClose()
|
||||
}
|
||||
}, [isOpen, status, onClose, toast])
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title="Vinculá tu WhatsApp"
|
||||
description="Escaneá el código con el teléfono donde usás WhatsApp."
|
||||
maxWidth="sm"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<div className="mx-auto flex size-64 items-center justify-center rounded-xl border border-border bg-white p-2">
|
||||
{qrCode ? (
|
||||
<img src={qrCode} alt="Código QR para vincular WhatsApp" className="size-full" />
|
||||
) : (
|
||||
<Loader2 className="size-8 animate-spin text-foreground/40" />
|
||||
)}
|
||||
</div>
|
||||
<ol className="space-y-1.5 text-sm text-foreground/70">
|
||||
<li>1. Abrí WhatsApp en tu teléfono.</li>
|
||||
<li>
|
||||
2. Tocá <span className="font-medium text-primary">Dispositivos vinculados</span> y
|
||||
después <span className="font-medium text-primary">Vincular un dispositivo</span>.
|
||||
</li>
|
||||
<li>3. Apuntá la cámara a este código.</li>
|
||||
</ol>
|
||||
<p className="flex items-start gap-2 rounded-xl bg-primary-soft px-3 py-2 text-xs text-foreground/70">
|
||||
<Smartphone className="mt-0.5 size-4 shrink-0 text-accent" />
|
||||
Los mensajes van a salir desde tu número. Podés desvincularlo cuando quieras desde
|
||||
Ajustes o desde tu teléfono.
|
||||
</p>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
175
apps/web/src/features/whatsapp/WhatsappStatusCard.tsx
Normal file
175
apps/web/src/features/whatsapp/WhatsappStatusCard.tsx
Normal file
@@ -0,0 +1,175 @@
|
||||
import { BadgeCheck, Loader2, MessageCircle, Unlink } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { Badge, Button, Modal } from '../../components/ui'
|
||||
import { formatMpConnectionDate } from '../mp'
|
||||
import {
|
||||
linksWithQr,
|
||||
readinessLabel,
|
||||
WEEKLY_SEND_LABEL,
|
||||
WHATSAPP_UNAVAILABLE_MESSAGE,
|
||||
whatsappStatusBadgeVariant,
|
||||
whatsappStatusLabel,
|
||||
} from './copy'
|
||||
import { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
||||
import { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
||||
import { useWhatsappStatus } from './useWhatsappStatus'
|
||||
import { WhatsappQrModal } from './WhatsappQrModal'
|
||||
|
||||
/**
|
||||
* WhatsApp en Ajustes: vincular el número desde el que salen los recordatorios
|
||||
* de pago y los mensajes de reenganche, ver si cada mensaje ya se puede enviar
|
||||
* y desvincularlo. El mismo control vive en el paso del onboarding.
|
||||
*/
|
||||
export function WhatsappStatusCard() {
|
||||
const statusQuery = useWhatsappStatus()
|
||||
const connection = useStartWhatsappConnection()
|
||||
const { disconnectWhatsapp: disconnect, isDisconnecting } = useDisconnectWhatsapp()
|
||||
const [isConfirmingDisconnect, setIsConfirmingDisconnect] = useState(false)
|
||||
|
||||
if (statusQuery.isPending) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
|
||||
<Loader2 className="size-4 animate-spin text-foreground/40" />
|
||||
<p className="text-sm text-foreground/50">Consultando tu WhatsApp…</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (statusQuery.isError || !statusQuery.data) {
|
||||
return (
|
||||
<div className="rounded-xl border border-border bg-surface px-4 py-3">
|
||||
<p className="text-sm font-medium text-primary">WhatsApp</p>
|
||||
<p className="mt-0.5 text-xs text-foreground/50">{WHATSAPP_UNAVAILABLE_MESSAGE}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const data = statusQuery.data
|
||||
const status = data.status
|
||||
const connectedAt = formatMpConnectionDate(data.connectedAt)
|
||||
const isActive = status === 'active'
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="divide-y divide-border rounded-xl border border-border bg-surface">
|
||||
<div className="px-4 py-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="text-sm font-medium text-primary">WhatsApp</p>
|
||||
<Badge variant={whatsappStatusBadgeVariant(status)}>{whatsappStatusLabel(status)}</Badge>
|
||||
</div>
|
||||
<p className="mt-0.5 text-xs text-foreground/50">
|
||||
Tu número para los recordatorios de pago y los mensajes de reenganche automáticos.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{isActive ? (
|
||||
<>
|
||||
<div className="flex items-center gap-3 px-4 py-3">
|
||||
<span className="rounded-lg bg-success-soft p-2">
|
||||
<MessageCircle className="size-4 text-success" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm text-primary">
|
||||
{data.displayPhoneNumber ?? 'Número vinculado'}
|
||||
</p>
|
||||
{connectedAt ? (
|
||||
<p className="text-xs text-foreground/50">Vinculado el {connectedAt}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setIsConfirmingDisconnect(true)}
|
||||
disabled={isDisconnecting}
|
||||
>
|
||||
{isDisconnecting ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Unlink className="size-4" />
|
||||
)}
|
||||
Desvincular
|
||||
</Button>
|
||||
</div>
|
||||
<dl className="space-y-1.5 px-4 py-3 text-sm">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<dt className="text-foreground/60">Recordatorio de pago</dt>
|
||||
<dd className="text-primary">{readinessLabel(data.readiness.PAYMENT_REMINDER)}</dd>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<dt className="text-foreground/60">Mensaje de reenganche</dt>
|
||||
<dd className="text-primary">{readinessLabel(data.readiness.REENGAGEMENT)}</dd>
|
||||
</div>
|
||||
<p className="pt-1 text-xs text-foreground/50">
|
||||
Los activás en cada grupo. {WEEKLY_SEND_LABEL}
|
||||
</p>
|
||||
</dl>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-start gap-3 px-4 py-3">
|
||||
<span className="rounded-lg bg-primary-soft p-2">
|
||||
<MessageCircle className="size-4 text-foreground/70" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm text-primary">
|
||||
{status === 'requires_reconnect' ? 'Volvé a vincular tu número' : 'Vinculá tu número'}
|
||||
</p>
|
||||
<p className="text-xs text-foreground/50">
|
||||
{linksWithQr(data.provider)
|
||||
? 'Escaneás un código QR desde WhatsApp, como en WhatsApp Web.'
|
||||
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
disabled={connection.isStarting}
|
||||
onClick={() => void connection.start('settings')}
|
||||
>
|
||||
{connection.isStarting ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<BadgeCheck className="size-4" />
|
||||
)}
|
||||
{connection.isStarting ? 'Abriendo…' : 'Vincular'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{connection.error ? (
|
||||
<p className="rounded-xl bg-danger-soft px-4 py-3 text-sm text-danger">{connection.error}</p>
|
||||
) : null}
|
||||
|
||||
<WhatsappQrModal
|
||||
isOpen={connection.isQrOpen}
|
||||
onClose={connection.closeQr}
|
||||
initialQrCode={connection.initialQrCode}
|
||||
/>
|
||||
|
||||
<Modal
|
||||
isOpen={isConfirmingDisconnect}
|
||||
onClose={() => setIsConfirmingDisconnect(false)}
|
||||
title="Desvincular WhatsApp"
|
||||
description="Los recordatorios y los mensajes de reenganche automáticos dejan de enviarse hasta que lo vuelvas a vincular."
|
||||
maxWidth="sm"
|
||||
>
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button variant="outline" onClick={() => setIsConfirmingDisconnect(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={isDisconnecting}
|
||||
onClick={() => {
|
||||
setIsConfirmingDisconnect(false)
|
||||
disconnect()
|
||||
}}
|
||||
>
|
||||
{isDisconnecting ? <Loader2 className="size-4 animate-spin" /> : null}
|
||||
Desvincular
|
||||
</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
126
apps/web/src/features/whatsapp/copy.ts
Normal file
126
apps/web/src/features/whatsapp/copy.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import type {
|
||||
WhatsappAccountStatus,
|
||||
WhatsappCallbackReason,
|
||||
WhatsappProvider,
|
||||
WhatsappReadiness,
|
||||
WhatsappStatusDto,
|
||||
} from '@gruperly/shared'
|
||||
|
||||
/* Copy de WhatsApp en un solo lugar: el paso del onboarding, la tarjeta de
|
||||
Ajustes y las automatizaciones del grupo dicen exactamente lo mismo. Las
|
||||
funciones son puras para cubrirlas con tests sin renderizar nada. */
|
||||
|
||||
export const WHATSAPP_CONNECT_ERROR_MESSAGE =
|
||||
'No pudimos empezar la vinculación. Revisá tu conexión e intentá de nuevo.'
|
||||
|
||||
export const WHATSAPP_UNAVAILABLE_MESSAGE =
|
||||
'La vinculación con WhatsApp no está disponible en este momento.'
|
||||
|
||||
/** Día y hora en que salen los mensajes automáticos (lo fija el job del backend). */
|
||||
export const WEEKLY_SEND_LABEL = 'Se envían los lunes a las 10:00 (hora de Argentina).'
|
||||
|
||||
/** El resultado de una vinculación por redirect (Kapso), tal como vuelve en `?wa=`. */
|
||||
export type WhatsappCallbackFeedback =
|
||||
| { kind: 'success' }
|
||||
| { kind: 'error'; reason: WhatsappCallbackReason }
|
||||
|
||||
const KNOWN_REASONS: readonly WhatsappCallbackReason[] = [
|
||||
'invalid_setup',
|
||||
'setup_failed',
|
||||
'provider_error',
|
||||
'number_in_use',
|
||||
]
|
||||
|
||||
/** Traduce `?wa=` de la URL a la retroalimentación que se muestra en pantalla. */
|
||||
export function readWhatsappCallbackFeedback(
|
||||
wa: string | undefined,
|
||||
reason: string | undefined,
|
||||
): WhatsappCallbackFeedback | null {
|
||||
if (wa === 'success') return { kind: 'success' }
|
||||
if (wa !== 'error') return null
|
||||
return {
|
||||
kind: 'error',
|
||||
reason: KNOWN_REASONS.includes(reason as WhatsappCallbackReason)
|
||||
? (reason as WhatsappCallbackReason)
|
||||
: 'provider_error',
|
||||
}
|
||||
}
|
||||
|
||||
const REASON_MESSAGES: Record<WhatsappCallbackReason, string> = {
|
||||
invalid_setup: 'La vinculación venció o ya se había usado. Volvé a intentarlo.',
|
||||
setup_failed: 'No se pudo terminar la vinculación en Meta. Volvé a intentarlo.',
|
||||
provider_error: 'WhatsApp no pudo completar la vinculación.',
|
||||
number_in_use: 'Ese número de WhatsApp ya está vinculado a otro profesor.',
|
||||
}
|
||||
|
||||
export function whatsappCallbackErrorMessage(reason: WhatsappCallbackReason): string {
|
||||
return REASON_MESSAGES[reason]
|
||||
}
|
||||
|
||||
export function whatsappStatusLabel(status: WhatsappAccountStatus): string {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return 'Vinculado'
|
||||
case 'pending':
|
||||
return 'Vinculando…'
|
||||
case 'requires_reconnect':
|
||||
return 'Necesita vincularse de nuevo'
|
||||
case 'disconnected':
|
||||
case 'none':
|
||||
return 'Sin vincular'
|
||||
}
|
||||
}
|
||||
|
||||
export function whatsappStatusBadgeVariant(
|
||||
status: WhatsappAccountStatus,
|
||||
): 'success' | 'warning' | 'neutral' | 'info' {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return 'success'
|
||||
case 'pending':
|
||||
return 'info'
|
||||
case 'requires_reconnect':
|
||||
return 'warning'
|
||||
case 'disconnected':
|
||||
case 'none':
|
||||
return 'neutral'
|
||||
}
|
||||
}
|
||||
|
||||
/** Qué se le explica al profesor según el estado de un tipo de mensaje. */
|
||||
export function readinessLabel(readiness: WhatsappReadiness): string {
|
||||
switch (readiness) {
|
||||
case 'ready':
|
||||
return 'Listo para enviar'
|
||||
case 'pending':
|
||||
return 'En revisión por Meta'
|
||||
case 'blocked':
|
||||
return 'No disponible'
|
||||
}
|
||||
}
|
||||
|
||||
/** Si la vinculación se hace escaneando un QR dentro de Gruperly. */
|
||||
export function linksWithQr(provider: WhatsappProvider): boolean {
|
||||
return provider === 'OPENWA'
|
||||
}
|
||||
|
||||
/**
|
||||
* Por qué un switch de automatización está deshabilitado, o null si se puede
|
||||
* usar. Se puede apagar siempre: lo que se bloquea es prenderla sin WhatsApp.
|
||||
*/
|
||||
export function automationBlockedReason(
|
||||
status: WhatsappStatusDto | undefined,
|
||||
kind: 'PAYMENT_REMINDER' | 'REENGAGEMENT',
|
||||
): string | null {
|
||||
if (!status || status.status !== 'active') {
|
||||
return 'Vinculá tu WhatsApp en Ajustes para activar los envíos automáticos.'
|
||||
}
|
||||
switch (status.readiness[kind]) {
|
||||
case 'ready':
|
||||
return null
|
||||
case 'pending':
|
||||
return 'Meta todavía está revisando el mensaje. Suele tardar hasta 24 horas.'
|
||||
case 'blocked':
|
||||
return 'Meta rechazó este mensaje. Escribinos para revisarlo.'
|
||||
}
|
||||
}
|
||||
16
apps/web/src/features/whatsapp/index.ts
Normal file
16
apps/web/src/features/whatsapp/index.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
export {
|
||||
automationBlockedReason,
|
||||
linksWithQr,
|
||||
readinessLabel,
|
||||
readWhatsappCallbackFeedback,
|
||||
WEEKLY_SEND_LABEL,
|
||||
type WhatsappCallbackFeedback,
|
||||
whatsappCallbackErrorMessage,
|
||||
whatsappStatusBadgeVariant,
|
||||
whatsappStatusLabel,
|
||||
} from './copy'
|
||||
export { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
|
||||
export { useStartWhatsappConnection } from './useStartWhatsappConnection'
|
||||
export { useWhatsappStatus, whatsappStatusQueryKey } from './useWhatsappStatus'
|
||||
export { WhatsappQrModal } from './WhatsappQrModal'
|
||||
export { WhatsappStatusCard } from './WhatsappStatusCard'
|
||||
28
apps/web/src/features/whatsapp/useDisconnectWhatsapp.ts
Normal file
28
apps/web/src/features/whatsapp/useDisconnectWhatsapp.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useToast } from '../../components/ui'
|
||||
import { disconnectWhatsapp } from '../../lib/api'
|
||||
import { whatsappStatusQueryKey } from './useWhatsappStatus'
|
||||
|
||||
export function useDisconnectWhatsapp() {
|
||||
const queryClient = useQueryClient()
|
||||
const toast = useToast()
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: disconnectWhatsapp,
|
||||
onSuccess: (result) => {
|
||||
if (result.disconnected) {
|
||||
toast.success('Desvinculamos tu WhatsApp. Los envíos automáticos quedan en pausa.')
|
||||
}
|
||||
void queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||
void queryClient.invalidateQueries({ queryKey: ['onboarding', 'status'] })
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
toast.error(error.message || 'No pudimos desvincular tu WhatsApp.')
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
disconnectWhatsapp: () => mutation.mutate(),
|
||||
isDisconnecting: mutation.isPending,
|
||||
}
|
||||
}
|
||||
55
apps/web/src/features/whatsapp/useStartWhatsappConnection.ts
Normal file
55
apps/web/src/features/whatsapp/useStartWhatsappConnection.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import type { WhatsappReturnTo } from '@gruperly/shared'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { ApiError, startWhatsappConnection } from '../../lib/api'
|
||||
import { WHATSAPP_CONNECT_ERROR_MESSAGE, WHATSAPP_UNAVAILABLE_MESSAGE } from './copy'
|
||||
import { whatsappStatusQueryKey } from './useWhatsappStatus'
|
||||
|
||||
/**
|
||||
* Empieza la vinculación de WhatsApp sin saber qué proveedor hay detrás:
|
||||
* - `redirect` (Kapso): el navegador navega al flujo de Meta y vuelve con `?wa=`.
|
||||
* - `qr` (OpenWA): se abre el modal con el QR; el estado se consulta solo hasta
|
||||
* que el teléfono lo escanea.
|
||||
*/
|
||||
export function useStartWhatsappConnection() {
|
||||
const queryClient = useQueryClient()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isStarting, setIsStarting] = useState(false)
|
||||
const [qrCode, setQrCode] = useState<string | null>(null)
|
||||
const [isQrOpen, setIsQrOpen] = useState(false)
|
||||
|
||||
const start = async (returnTo: WhatsappReturnTo) => {
|
||||
setError(null)
|
||||
setIsStarting(true)
|
||||
try {
|
||||
const { start: next } = await startWhatsappConnection(returnTo)
|
||||
if (next.type === 'redirect') {
|
||||
window.location.assign(next.url)
|
||||
return
|
||||
}
|
||||
setQrCode(next.qrCode)
|
||||
// El estado pasa a `pending` y empieza el sondeo que trae el QR nuevo. Se
|
||||
// espera el refetch antes de abrir el modal: con el estado viejo en caché
|
||||
// (`disconnected`) el modal se cerraría apenas abre.
|
||||
await queryClient.invalidateQueries({ queryKey: whatsappStatusQueryKey })
|
||||
setIsQrOpen(true)
|
||||
} catch (caught) {
|
||||
setError(
|
||||
caught instanceof ApiError && caught.status === 503
|
||||
? WHATSAPP_UNAVAILABLE_MESSAGE
|
||||
: WHATSAPP_CONNECT_ERROR_MESSAGE,
|
||||
)
|
||||
}
|
||||
setIsStarting(false)
|
||||
}
|
||||
|
||||
return {
|
||||
start,
|
||||
isStarting,
|
||||
error,
|
||||
/** QR de la respuesta inicial; el modal prefiere el del estado, que se renueva. */
|
||||
initialQrCode: qrCode,
|
||||
isQrOpen,
|
||||
closeQr: () => setIsQrOpen(false),
|
||||
}
|
||||
}
|
||||
28
apps/web/src/features/whatsapp/useWhatsappStatus.ts
Normal file
28
apps/web/src/features/whatsapp/useWhatsappStatus.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWhatsappStatus } from '../../lib/api'
|
||||
|
||||
/** La misma clave en toda la app: el onboarding, Ajustes y la ficha del grupo. */
|
||||
export const whatsappStatusQueryKey = ['whatsapp', 'status'] as const
|
||||
|
||||
/** Cada cuánto se consulta mientras la vinculación está en curso (QR en pantalla). */
|
||||
const PENDING_POLL_MS = 2000
|
||||
|
||||
type UseWhatsappStatusOptions = {
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Estado del WhatsApp del profesor. Mientras está `pending` se consulta cada 2 s:
|
||||
* así el QR se renueva y la vinculación se completa sola, aunque el webhook del
|
||||
* proveedor no llegue (desarrollo local).
|
||||
*/
|
||||
export function useWhatsappStatus({ enabled = true }: UseWhatsappStatusOptions = {}) {
|
||||
return useQuery({
|
||||
queryKey: whatsappStatusQueryKey,
|
||||
queryFn: getWhatsappStatus,
|
||||
enabled,
|
||||
retry: false,
|
||||
refetchInterval: (query) =>
|
||||
query.state.data?.status === 'pending' ? PENDING_POLL_MS : false,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user