Merge pull request (#5): telefono en el formato que usa WhatsApp
Deploy / deploy (push) Successful in 3m0s
Deploy / deploy (push) Successful in 3m0s
This commit was merged in pull request #5.
This commit is contained in:
@@ -0,0 +1,54 @@
|
|||||||
|
/**
|
||||||
|
* Chatear con el bot de WhatsApp desde la consola, sin Meta.
|
||||||
|
*
|
||||||
|
* Habla directo con `procesarMensaje`, que es lo mismo que invoca el webhook, así
|
||||||
|
* que ejercita la conversación completa contra la base a la que apunte DATABASE_URL
|
||||||
|
* (turnos incluidos: lo que reserves acá queda guardado).
|
||||||
|
*
|
||||||
|
* DATABASE_URL=... npx tsx scripts/chat-bot.ts [telefono]
|
||||||
|
*
|
||||||
|
* Acepta entrada interactiva o por tubería (una línea por mensaje).
|
||||||
|
* Comandos propios: /salir, /reset (borra la conversación de ese teléfono).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createInterface } from "readline";
|
||||||
|
import { prisma } from "../src/lib/prisma";
|
||||||
|
import { procesarMensaje } from "../src/lib/whatsapp-bot";
|
||||||
|
import { normalizarTelefono } from "../src/lib/telefono";
|
||||||
|
|
||||||
|
// Normalizado igual que en el bot: si no, /reset no encuentra la conversación.
|
||||||
|
const telefono = normalizarTelefono(process.argv[2] ?? "5493510000000");
|
||||||
|
|
||||||
|
function mostrar(resp: { tipo: string; texto: string; botones?: { titulo: string }[] }[]) {
|
||||||
|
for (const r of resp) {
|
||||||
|
console.log("\n🤖 " + r.texto.replace(/\n/g, "\n "));
|
||||||
|
if (r.tipo === "botones" && r.botones)
|
||||||
|
console.log(" [ " + r.botones.map((b) => b.titulo).join(" ] [ ") + " ]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log(`Chateando como ${telefono}. /salir para terminar, /reset para empezar de cero.`);
|
||||||
|
|
||||||
|
const rl = createInterface({ input: process.stdin, terminal: false });
|
||||||
|
|
||||||
|
for await (const linea of rl) {
|
||||||
|
const texto = linea.trim();
|
||||||
|
if (texto === "/salir") break;
|
||||||
|
if (texto === "/reset") {
|
||||||
|
await prisma.conversacionWhatsapp.deleteMany({ where: { telefono } });
|
||||||
|
console.log("\n(conversación borrada)");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
console.log(`\n👤 ${texto}`);
|
||||||
|
mostrar(await procesarMensaje(telefono, texto));
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch(async (e) => {
|
||||||
|
console.error(e);
|
||||||
|
await prisma.$disconnect();
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { prisma } from "@/lib/prisma";
|
import { prisma } from "@/lib/prisma";
|
||||||
|
import { aFormatoWhatsapp, esLocalArgentinoValido, normalizarTelefono } from "@/lib/telefono";
|
||||||
import nodemailer from "nodemailer";
|
import nodemailer from "nodemailer";
|
||||||
|
|
||||||
const transporter = nodemailer.createTransport({
|
const transporter = nodemailer.createTransport({
|
||||||
@@ -18,11 +19,29 @@ export async function POST(req: NextRequest) {
|
|||||||
if (!email || !nombre || !apellido || !telefono)
|
if (!email || !nombre || !apellido || !telefono)
|
||||||
return NextResponse.json({ error: "Todos los campos son requeridos" }, { status: 400 });
|
return NextResponse.json({ error: "Todos los campos son requeridos" }, { status: 400 });
|
||||||
|
|
||||||
|
if (!esLocalArgentinoValido(telefono))
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "El teléfono debe tener 10 dígitos, sin el 0 de la característica ni el 15" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
|
||||||
const existe = await prisma.cliente.findUnique({ where: { email: email.toLowerCase() } });
|
const existe = await prisma.cliente.findUnique({ where: { email: email.toLowerCase() } });
|
||||||
if (existe) return NextResponse.json({ error: "El email ya está registrado" }, { status: 409 });
|
if (existe) return NextResponse.json({ error: "El email ya está registrado" }, { status: 409 });
|
||||||
|
|
||||||
|
// `telefonoNorm` queda igual al `wa_id` que manda Meta, que es como lo busca el bot.
|
||||||
|
const telefonoNorm = aFormatoWhatsapp(telefono);
|
||||||
|
const yaUsado = await prisma.cliente.findFirst({ where: { telefonoNorm } });
|
||||||
|
if (yaUsado)
|
||||||
|
return NextResponse.json({ error: "Ese teléfono ya está registrado" }, { status: 409 });
|
||||||
|
|
||||||
const cliente = await prisma.cliente.create({
|
const cliente = await prisma.cliente.create({
|
||||||
data: { email: email.toLowerCase().trim(), nombre, apellido, telefono },
|
data: {
|
||||||
|
email: email.toLowerCase().trim(),
|
||||||
|
nombre,
|
||||||
|
apellido,
|
||||||
|
telefono: normalizarTelefono(telefono),
|
||||||
|
telefonoNorm,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
await transporter.sendMail({
|
await transporter.sendMail({
|
||||||
|
|||||||
@@ -5,19 +5,42 @@ import Link from "next/link";
|
|||||||
import Button from "@/components/ui/Button";
|
import Button from "@/components/ui/Button";
|
||||||
import Input from "@/components/ui/Input";
|
import Input from "@/components/ui/Input";
|
||||||
import Card from "@/components/ui/Card";
|
import Card from "@/components/ui/Card";
|
||||||
|
import { esLocalArgentinoValido } from "@/lib/telefono";
|
||||||
|
|
||||||
export default function RegistroPage() {
|
export default function RegistroPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [form, setForm] = useState({ email: "", nombre: "", apellido: "", telefono: "" });
|
const [form, setForm] = useState({ email: "", nombre: "", apellido: "", telefono: "" });
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
const [telefonoError, setTelefonoError] = useState("");
|
||||||
|
|
||||||
function set(field: string) {
|
function set(field: string) {
|
||||||
return (e: React.ChangeEvent<HTMLInputElement>) => setForm((f) => ({ ...f, [field]: e.target.value }));
|
return (e: React.ChangeEvent<HTMLInputElement>) => setForm((f) => ({ ...f, [field]: e.target.value }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// El teléfono se guarda como lo espera WhatsApp: solo característica + abonado,
|
||||||
|
// sin el 0 ni el 15 (el +54 9 lo pone el prefijo fijo del campo).
|
||||||
|
function handleTelefono(e: React.ChangeEvent<HTMLInputElement>) {
|
||||||
|
const soloDigitos = e.target.value.replace(/\D/g, "").slice(0, 10);
|
||||||
|
setForm((f) => ({ ...f, telefono: soloDigitos }));
|
||||||
|
// Mientras tipea sólo se avisa lo que ya es un error seguro; lo de "faltan
|
||||||
|
// dígitos" espera a que salga del campo, para no retarlo por la mitad.
|
||||||
|
if (soloDigitos.startsWith("0")) setTelefonoError("Sin el 0 de la característica");
|
||||||
|
else if (soloDigitos.startsWith("15")) setTelefonoError("Sin el 15, poné la característica");
|
||||||
|
else setTelefonoError("");
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleTelefonoBlur() {
|
||||||
|
if (form.telefono && !esLocalArgentinoValido(form.telefono))
|
||||||
|
setTelefonoError("Son 10 dígitos: característica sin el 0 y número sin el 15");
|
||||||
|
}
|
||||||
|
|
||||||
async function handleSubmit(e: React.FormEvent) {
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
if (!esLocalArgentinoValido(form.telefono)) {
|
||||||
|
setTelefonoError("Revisá el número: son 10 dígitos, sin el 0 y sin el 15");
|
||||||
|
return;
|
||||||
|
}
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError("");
|
setError("");
|
||||||
const res = await fetch("/api/cliente/registro", {
|
const res = await fetch("/api/cliente/registro", {
|
||||||
@@ -47,7 +70,21 @@ export default function RegistroPage() {
|
|||||||
<Input id="nombre" label="Nombre" placeholder="Juan" value={form.nombre} onChange={set("nombre")} required />
|
<Input id="nombre" label="Nombre" placeholder="Juan" value={form.nombre} onChange={set("nombre")} required />
|
||||||
<Input id="apellido" label="Apellido" placeholder="Pérez" value={form.apellido} onChange={set("apellido")} required />
|
<Input id="apellido" label="Apellido" placeholder="Pérez" value={form.apellido} onChange={set("apellido")} required />
|
||||||
<Input id="email" type="email" label="Email" placeholder="juan@email.com" value={form.email} onChange={set("email")} required />
|
<Input id="email" type="email" label="Email" placeholder="juan@email.com" value={form.email} onChange={set("email")} required />
|
||||||
<Input id="telefono" type="tel" label="Teléfono" placeholder="11 1234-5678" value={form.telefono} onChange={set("telefono")} required />
|
<Input
|
||||||
|
id="telefono"
|
||||||
|
type="tel"
|
||||||
|
inputMode="numeric"
|
||||||
|
label="Teléfono (celular)"
|
||||||
|
prefijo="+54 9"
|
||||||
|
placeholder="1141984844"
|
||||||
|
maxLength={10}
|
||||||
|
ayuda="Característica sin el 0 y número sin el 15. Es el celular con el que vas a poder sacar turnos por WhatsApp."
|
||||||
|
error={telefonoError}
|
||||||
|
value={form.telefono}
|
||||||
|
onChange={handleTelefono}
|
||||||
|
onBlur={handleTelefonoBlur}
|
||||||
|
required
|
||||||
|
/>
|
||||||
{error && <p className="text-sm text-red-500 text-center">{error}</p>}
|
{error && <p className="text-sm text-red-500 text-center">{error}</p>}
|
||||||
<Button type="submit" loading={loading} className="w-full">
|
<Button type="submit" loading={loading} className="w-full">
|
||||||
Crear cuenta
|
Crear cuenta
|
||||||
|
|||||||
@@ -3,9 +3,16 @@ import { InputHTMLAttributes } from "react";
|
|||||||
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
|
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
|
||||||
label?: string;
|
label?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
|
/** Texto fijo grisado antes del campo (ej: el prefijo de país del teléfono). */
|
||||||
|
prefijo?: string;
|
||||||
|
ayuda?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Input({ label, error, className = "", id, ...props }: InputProps) {
|
export default function Input({ label, error, prefijo, ayuda, className = "", id, ...props }: InputProps) {
|
||||||
|
const estiloInput = `border rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition bg-gray-100 text-gray-900 placeholder-gray-500 ${
|
||||||
|
error ? "border-red-400" : "border-gray-400"
|
||||||
|
} ${className}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-1">
|
<div className="flex flex-col gap-1">
|
||||||
{label && (
|
{label && (
|
||||||
@@ -13,13 +20,23 @@ export default function Input({ label, error, className = "", id, ...props }: In
|
|||||||
{label}
|
{label}
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
{prefijo ? (
|
||||||
|
<div
|
||||||
|
className={`flex items-center rounded-lg border bg-gray-100 focus-within:ring-2 focus-within:ring-blue-500 transition ${
|
||||||
|
error ? "border-red-400" : "border-gray-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="pl-3 pr-1 text-sm text-gray-500 select-none">{prefijo}</span>
|
||||||
<input
|
<input
|
||||||
id={id}
|
id={id}
|
||||||
className={`border rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition bg-gray-100 text-gray-900 placeholder-gray-500 ${
|
className={`flex-1 bg-transparent px-1 py-2 text-sm outline-none text-gray-900 placeholder-gray-500 ${className}`}
|
||||||
error ? "border-red-400" : "border-gray-400"
|
|
||||||
} ${className}`}
|
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<input id={id} className={estiloInput} {...props} />
|
||||||
|
)}
|
||||||
|
{ayuda && !error && <p className="text-xs text-gray-500">{ayuda}</p>}
|
||||||
{error && <p className="text-xs text-red-500">{error}</p>}
|
{error && <p className="text-xs text-red-500">{error}</p>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -6,3 +6,26 @@
|
|||||||
export function normalizarTelefono(valor: string): string {
|
export function normalizarTelefono(valor: string): string {
|
||||||
return (valor ?? "").replace(/\D/g, "");
|
return (valor ?? "").replace(/\D/g, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prefijo con el que WhatsApp identifica a los celulares argentinos: 54 (país) + 9 (móvil).
|
||||||
|
* En el registro web se muestra fijo y el cliente completa el resto, así el número queda
|
||||||
|
* guardado igual que el `wa_id` que después manda Meta y el bot lo reconoce.
|
||||||
|
*/
|
||||||
|
export const PREFIJO_WHATSAPP_AR = "549";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parte local del número: característica sin el 0 y abonado sin el 15.
|
||||||
|
* En Argentina son siempre 10 dígitos (ej: 11 4198-4844, 351 555-4444).
|
||||||
|
*/
|
||||||
|
export function esLocalArgentinoValido(local: string): boolean {
|
||||||
|
const d = normalizarTelefono(local);
|
||||||
|
// Ninguna característica argentina empieza con 0 (es el prefijo de larga distancia)
|
||||||
|
// ni con 15 (el viejo prefijo de celular), así que esos casos son error de tipeo.
|
||||||
|
return d.length === 10 && !d.startsWith("0") && !d.startsWith("15");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Número local a formato WhatsApp: 1141984844 → 5491141984844. */
|
||||||
|
export function aFormatoWhatsapp(local: string): string {
|
||||||
|
return PREFIJO_WHATSAPP_AR + normalizarTelefono(local);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user