Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 08e15dafd5 | |||
| ffb3cd139a | |||
| 85cff19c59 |
@@ -195,8 +195,8 @@ describe("POST /clients", () => {
|
|||||||
expect(insertedValues[0]!.name).toBe("Charlie");
|
expect(insertedValues[0]!.name).toBe("Charlie");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("creates a client with required fields", async () => {
|
it("creates a client with only required name field", async () => {
|
||||||
const res = await jsonRequest("POST", "/clients", { name: "Dana", email: "dana@example.com" });
|
const res = await jsonRequest("POST", "/clients", { name: "Dana" });
|
||||||
expect(res.status).toBe(201);
|
expect(res.status).toBe(201);
|
||||||
expect(insertedValues[0]!.name).toBe("Dana");
|
expect(insertedValues[0]!.name).toBe("Dana");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
getDb,
|
getDb,
|
||||||
gte,
|
gte,
|
||||||
lt,
|
lt,
|
||||||
|
sql,
|
||||||
appointments,
|
appointments,
|
||||||
clients,
|
clients,
|
||||||
pets,
|
pets,
|
||||||
@@ -31,6 +32,8 @@ function getReminderWindows(): { label: string; hours: number }[] {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Checks for upcoming appointments that need reminders and sends them.
|
||||||
|
// Runs every minute — idempotent via reminder_logs unique constraint.
|
||||||
export async function runReminderCheck(): Promise<void> {
|
export async function runReminderCheck(): Promise<void> {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
@@ -59,69 +62,74 @@ export async function runReminderCheck(): Promise<void> {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const appointmentIds: string[] = upcoming.map((a) => a.id as string);
|
||||||
|
|
||||||
|
if (appointmentIds.length === 0) continue;
|
||||||
|
|
||||||
|
// Batch-fetch already-sent appointment IDs (both EMAIL and SMS channels)
|
||||||
|
const sentAppointmentIds = new Set(
|
||||||
|
(
|
||||||
|
await db
|
||||||
|
.select({ appointmentId: reminderLogs.appointmentId })
|
||||||
|
.from(reminderLogs)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(reminderLogs.reminderType, window.label),
|
||||||
|
appointmentIds.length === 1
|
||||||
|
? eq(reminderLogs.appointmentId, appointmentIds[0]!)
|
||||||
|
: sql`${reminderLogs.appointmentId} = ANY(${appointmentIds})`
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).map((r) => r.appointmentId)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Batch-fetch all appointment data with related joins in a single query
|
||||||
|
const joinedRows = await db
|
||||||
|
.select({
|
||||||
|
appointmentId: appointments.id,
|
||||||
|
startTime: appointments.startTime,
|
||||||
|
clientId: appointments.clientId,
|
||||||
|
petId: appointments.petId,
|
||||||
|
serviceId: appointments.serviceId,
|
||||||
|
staffId: appointments.staffId,
|
||||||
|
confirmationToken: appointments.confirmationToken,
|
||||||
|
clientName: clients.name,
|
||||||
|
clientEmail: clients.email,
|
||||||
|
clientEmailOptOut: clients.emailOptOut,
|
||||||
|
clientPhone: clients.phone,
|
||||||
|
clientSmsOptIn: clients.smsOptIn,
|
||||||
|
petName: pets.name,
|
||||||
|
serviceName: services.name,
|
||||||
|
staffName: staff.name,
|
||||||
|
})
|
||||||
|
.from(appointments)
|
||||||
|
.innerJoin(clients, eq(appointments.clientId, clients.id))
|
||||||
|
.innerJoin(pets, eq(appointments.petId, pets.id))
|
||||||
|
.innerJoin(services, eq(appointments.serviceId, services.id))
|
||||||
|
.leftJoin(staff, eq(appointments.staffId, staff.id))
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
sql`${appointments.id} = ANY(${appointmentIds})`,
|
||||||
|
gte(appointments.startTime, windowStart),
|
||||||
|
lt(appointments.startTime, windowEnd),
|
||||||
|
eq(appointments.status, "scheduled")
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
const appointmentMap = new Map<string, typeof joinedRows[number]>();
|
||||||
|
for (const row of joinedRows) {
|
||||||
|
appointmentMap.set(row.appointmentId, row);
|
||||||
|
}
|
||||||
|
|
||||||
for (const appt of upcoming) {
|
for (const appt of upcoming) {
|
||||||
const [emailLog] = await db
|
// Already sent a reminder for this appointment in this window
|
||||||
.select({ id: reminderLogs.id })
|
if (sentAppointmentIds.has(appt.id)) continue;
|
||||||
.from(reminderLogs)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(reminderLogs.appointmentId, appt.id),
|
|
||||||
eq(reminderLogs.reminderType, window.label),
|
|
||||||
eq(reminderLogs.channel, "email")
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
const [smsLog] = await db
|
const row = appointmentMap.get(appt.id);
|
||||||
.select({ id: reminderLogs.id })
|
if (!row) continue;
|
||||||
.from(reminderLogs)
|
if (!row.petName || !row.serviceName) continue;
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(reminderLogs.appointmentId, appt.id),
|
|
||||||
eq(reminderLogs.reminderType, window.label),
|
|
||||||
eq(reminderLogs.channel, "sms")
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
const [client] = await db
|
|
||||||
.select({
|
|
||||||
name: clients.name,
|
|
||||||
email: clients.email,
|
|
||||||
emailOptOut: clients.emailOptOut,
|
|
||||||
smsOptIn: clients.smsOptIn,
|
|
||||||
phone: clients.phone,
|
|
||||||
})
|
|
||||||
.from(clients)
|
|
||||||
.where(eq(clients.id, appt.clientId))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!client || !client.email || client.emailOptOut) continue;
|
|
||||||
|
|
||||||
const [pet] = await db
|
|
||||||
.select({ name: pets.name })
|
|
||||||
.from(pets)
|
|
||||||
.where(eq(pets.id, appt.petId))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
const [service] = await db
|
|
||||||
.select({ name: services.name })
|
|
||||||
.from(services)
|
|
||||||
.where(eq(services.id, appt.serviceId))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
let groomerName: string | null = null;
|
|
||||||
if (appt.staffId) {
|
|
||||||
const [groomer] = await db
|
|
||||||
.select({ name: staff.name })
|
|
||||||
.from(staff)
|
|
||||||
.where(eq(staff.id, appt.staffId))
|
|
||||||
.limit(1);
|
|
||||||
groomerName = groomer?.name ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!pet || !service) continue;
|
|
||||||
|
|
||||||
|
// Generate confirmation token if missing
|
||||||
let confirmationToken = appt.confirmationToken;
|
let confirmationToken = appt.confirmationToken;
|
||||||
if (!confirmationToken) {
|
if (!confirmationToken) {
|
||||||
confirmationToken = randomBytes(32).toString("hex");
|
confirmationToken = randomBytes(32).toString("hex");
|
||||||
@@ -131,22 +139,22 @@ export async function runReminderCheck(): Promise<void> {
|
|||||||
.where(eq(appointments.id, appt.id));
|
.where(eq(appointments.id, appt.id));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!emailLog) {
|
const clientName = row.clientName;
|
||||||
|
const petName = row.petName;
|
||||||
|
const serviceName = row.serviceName;
|
||||||
|
const groomerName = row.staffName ?? null;
|
||||||
|
const startTime = appt.startTime;
|
||||||
|
|
||||||
|
// EMAIL reminder
|
||||||
|
if (row.clientEmail && !row.clientEmailOptOut) {
|
||||||
const sent = await sendEmail(
|
const sent = await sendEmail(
|
||||||
buildReminderEmail(
|
buildReminderEmail(
|
||||||
client.email,
|
row.clientEmail,
|
||||||
{
|
{ clientName, petName, serviceName, groomerName, startTime },
|
||||||
clientName: client.name,
|
|
||||||
petName: pet.name,
|
|
||||||
serviceName: service.name,
|
|
||||||
groomerName,
|
|
||||||
startTime: appt.startTime,
|
|
||||||
},
|
|
||||||
window.hours,
|
window.hours,
|
||||||
confirmationToken
|
confirmationToken
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
if (sent) {
|
if (sent) {
|
||||||
await db
|
await db
|
||||||
.insert(reminderLogs)
|
.insert(reminderLogs)
|
||||||
@@ -155,20 +163,21 @@ export async function runReminderCheck(): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!smsLog && client.smsOptIn && client.phone) {
|
// SMS reminder
|
||||||
|
if (row.clientPhone && row.clientSmsOptIn) {
|
||||||
const apiUrl = process.env.API_URL ?? "http://localhost:3000";
|
const apiUrl = process.env.API_URL ?? "http://localhost:3000";
|
||||||
const confirmUrl = `${apiUrl}/api/book/confirm/${confirmationToken}`;
|
const confirmUrl = `${apiUrl}/api/book/confirm/${confirmationToken}`;
|
||||||
const cancelUrl = `${apiUrl}/api/book/cancel/${confirmationToken}`;
|
const cancelUrl = `${apiUrl}/api/book/cancel/${confirmationToken}`;
|
||||||
const when = window.hours >= 24 ? "tomorrow" : `in ${window.hours} hours`;
|
const when = window.hours >= 24 ? "tomorrow" : `in ${window.hours} hours`;
|
||||||
const smsBody = [
|
const smsBody = [
|
||||||
`Hi ${client.name}, just a reminder: ${pet.name}'s grooming appointment is ${when}.`,
|
`Hi ${clientName}, just a reminder: ${petName}'s grooming appointment is ${when}.`,
|
||||||
`Service: ${service.name}${groomerName ? ` with ${groomerName}` : ""}`,
|
`Service: ${serviceName}${groomerName ? ` with ${groomerName}` : ""}`,
|
||||||
`Confirm: ${confirmUrl}`,
|
`Confirm: ${confirmUrl}`,
|
||||||
`Cancel: ${cancelUrl}`,
|
`Cancel: ${cancelUrl}`,
|
||||||
TCPA_OPT_OUT,
|
TCPA_OPT_OUT,
|
||||||
].join(". ");
|
].join(". ");
|
||||||
try {
|
try {
|
||||||
const smsOk = await smsSend(client.phone, smsBody);
|
const smsOk = await smsSend(row.clientPhone, smsBody);
|
||||||
if (smsOk) {
|
if (smsOk) {
|
||||||
await db
|
await db
|
||||||
.insert(reminderLogs)
|
.insert(reminderLogs)
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
-- SMS opt-in fields for clients
|
-- SMS opt-in fields for clients (idempotent)
|
||||||
ALTER TABLE "clients" ADD COLUMN "sms_opt_in" boolean NOT NULL DEFAULT false;
|
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "sms_opt_in" boolean NOT NULL DEFAULT false;
|
||||||
ALTER TABLE "clients" ADD COLUMN "sms_consent_date" timestamp;
|
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "sms_consent_date" timestamp;
|
||||||
ALTER TABLE "clients" ADD COLUMN "sms_opt_out_date" timestamp;
|
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "sms_opt_out_date" timestamp;
|
||||||
ALTER TABLE "clients" ADD COLUMN "sms_consent_text" text;
|
ALTER TABLE "clients" ADD COLUMN IF NOT EXISTS "sms_consent_text" text;
|
||||||
|
|
||||||
-- Add channel column to reminder_logs with default 'email'
|
-- Add channel column to reminder_logs with default 'email' (idempotent)
|
||||||
ALTER TABLE "reminder_logs" ADD COLUMN "channel" text NOT NULL DEFAULT 'email';
|
ALTER TABLE "reminder_logs" ADD COLUMN IF NOT EXISTS "channel" text NOT NULL DEFAULT 'email';
|
||||||
|
|
||||||
-- Drop the old unique constraint and recreate with channel
|
-- Drop old unique constraints if they exist (idempotent)
|
||||||
ALTER TABLE "reminder_logs" DROP CONSTRAINT "reminder_logs_appointment_id_reminder_type_unique";
|
ALTER TABLE "reminder_logs" DROP CONSTRAINT IF EXISTS "reminder_logs_appointment_id_reminder_type_key";
|
||||||
|
ALTER TABLE "reminder_logs" DROP CONSTRAINT IF EXISTS "reminder_logs_appointment_id_reminder_type_unique";
|
||||||
|
|
||||||
|
-- Add new unique constraint with channel
|
||||||
ALTER TABLE "reminder_logs" ADD CONSTRAINT "reminder_logs_appointment_id_reminder_type_channel_unique" UNIQUE ("appointment_id", "reminder_type", "channel");
|
ALTER TABLE "reminder_logs" ADD CONSTRAINT "reminder_logs_appointment_id_reminder_type_channel_unique" UNIQUE ("appointment_id", "reminder_type", "channel");
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
-- Migration: 0029_db_indexes_constraints.sql
|
|
||||||
-- Add missing indexes on appointments, pets, clients tables and NOT NULL constraint on clients.email
|
|
||||||
|
|
||||||
-- Backfill NULL emails before setting NOT NULL
|
|
||||||
UPDATE clients SET email = concat('unknown-', id::text, '@placeholder.local') WHERE email IS NULL;
|
|
||||||
|
|
||||||
-- Add indexes on appointments table
|
|
||||||
CREATE INDEX idx_appointments_client_id ON appointments(client_id);
|
|
||||||
CREATE INDEX idx_appointments_staff_id ON appointments(staff_id);
|
|
||||||
CREATE INDEX idx_appointments_start_time ON appointments(start_time);
|
|
||||||
CREATE INDEX idx_appointments_status ON appointments(status);
|
|
||||||
|
|
||||||
-- Add index on pets table
|
|
||||||
CREATE INDEX idx_pets_client_id ON pets(client_id);
|
|
||||||
|
|
||||||
-- Add index on clients table
|
|
||||||
CREATE INDEX idx_clients_email ON clients(email);
|
|
||||||
|
|
||||||
-- Set NOT NULL on clients.email (after backfill)
|
|
||||||
ALTER TABLE clients ALTER COLUMN email SET NOT NULL;
|
|
||||||
+40
-48
@@ -102,55 +102,47 @@ export const verification = pgTable("verification", {
|
|||||||
|
|
||||||
// ─── Tables ───────────────────────────────────────────────────────────────────
|
// ─── Tables ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const clients = pgTable(
|
export const clients = pgTable("clients", {
|
||||||
"clients",
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
{
|
name: text("name").notNull(),
|
||||||
id: uuid("id").primaryKey().defaultRandom(),
|
email: text("email"),
|
||||||
name: text("name").notNull(),
|
phone: text("phone"),
|
||||||
email: text("email").notNull(),
|
address: text("address"),
|
||||||
phone: text("phone"),
|
notes: text("notes"),
|
||||||
address: text("address"),
|
emailOptOut: boolean("email_opt_out").notNull().default(false),
|
||||||
notes: text("notes"),
|
smsOptIn: boolean("sms_opt_in").notNull().default(false),
|
||||||
emailOptOut: boolean("email_opt_out").notNull().default(false),
|
smsConsentDate: timestamp("sms_consent_date"),
|
||||||
smsOptIn: boolean("sms_opt_in").notNull().default(false),
|
smsOptOutDate: timestamp("sms_opt_out_date"),
|
||||||
smsConsentDate: timestamp("sms_consent_date"),
|
smsConsentText: text("sms_consent_text"),
|
||||||
smsOptOutDate: timestamp("sms_opt_out_date"),
|
stripeCustomerId: text("stripe_customer_id"),
|
||||||
smsConsentText: text("sms_consent_text"),
|
status: clientStatusEnum("status").notNull().default("active"),
|
||||||
stripeCustomerId: text("stripe_customer_id"),
|
disabledAt: timestamp("disabled_at"),
|
||||||
status: clientStatusEnum("status").notNull().default("active"),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
disabledAt: timestamp("disabled_at"),
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
});
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
|
||||||
},
|
|
||||||
(t) => [index("idx_clients_email").on(t.email)]
|
|
||||||
);
|
|
||||||
|
|
||||||
export const pets = pgTable(
|
export const pets = pgTable("pets", {
|
||||||
"pets",
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
{
|
clientId: uuid("client_id")
|
||||||
id: uuid("id").primaryKey().defaultRandom(),
|
.notNull()
|
||||||
clientId: uuid("client_id")
|
.references(() => clients.id, { onDelete: "cascade" }),
|
||||||
.notNull()
|
name: text("name").notNull(),
|
||||||
.references(() => clients.id, { onDelete: "cascade" }),
|
species: text("species").notNull(),
|
||||||
name: text("name").notNull(),
|
breed: text("breed"),
|
||||||
species: text("species").notNull(),
|
weightKg: numeric("weight_kg", { precision: 5, scale: 2 }),
|
||||||
breed: text("breed"),
|
dateOfBirth: timestamp("date_of_birth"),
|
||||||
weightKg: numeric("weight_kg", { precision: 5, scale: 2 }),
|
healthAlerts: text("health_alerts"),
|
||||||
dateOfBirth: timestamp("date_of_birth"),
|
groomingNotes: text("grooming_notes"),
|
||||||
healthAlerts: text("health_alerts"),
|
cutStyle: text("cut_style"),
|
||||||
groomingNotes: text("grooming_notes"),
|
shampooPreference: text("shampoo_preference"),
|
||||||
cutStyle: text("cut_style"),
|
specialCareNotes: text("special_care_notes"),
|
||||||
shampooPreference: text("shampoo_preference"),
|
customFields: jsonb("custom_fields").$type<Record<string, string>>().notNull().default({}),
|
||||||
specialCareNotes: text("special_care_notes"),
|
photoKey: text("photo_key"),
|
||||||
customFields: jsonb("custom_fields").$type<Record<string, string>>().notNull().default({}),
|
photoUploadedAt: timestamp("photo_uploaded_at"),
|
||||||
photoKey: text("photo_key"),
|
image: text("image"),
|
||||||
photoUploadedAt: timestamp("photo_uploaded_at"),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
image: text("image"),
|
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
});
|
||||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
|
||||||
},
|
|
||||||
(t) => [index("idx_pets_client_id").on(t.clientId)]
|
|
||||||
);
|
|
||||||
|
|
||||||
export const services = pgTable("services", {
|
export const services = pgTable("services", {
|
||||||
id: uuid("id").primaryKey().defaultRandom(),
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
|||||||
Reference in New Issue
Block a user