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