feat(email): wire end-to-end welcome-email opt-out

users.digestOptOut existed in the schema (on the never-used
ownerProfiles table) but had no UI, no API, and no cron enforcement —
fully dead. Closing the loop:

- Schema: moved digestOptOut from ownerProfiles → users (where every
  user already has a row, no parallel-table juggling). pnpm db:push
  applied; ownerProfiles is still dead but tidier.
- API: extended PATCH /api/account to accept digestOptOut: boolean.
  New GET /api/account returns { name, email, locale, digestOptOut }
  so the settings page can hydrate without session-token changes.
- Cron: /api/cron/emails now reads users.digestOptOut and DELETEs
  pending welcome items for opted-out users instead of sending them.
  Returns { sent, failed, skipped } for visibility.
- Settings UI: new "Email preferences" card between Profile and
  Password with a clear checkbox; copy makes explicit that
  transactional emails (vaccination reminders, health alerts, order
  confirmations) are not affected.

Users who don't want the day-1/3/7 onboarding series can finally
turn it off without losing transactional notifications.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-04-25 18:47:56 +02:00
1 parent b544f572b7
commit 00627fbce4
4 files changed
+110 -5

No files matched your search

+68 -2
View File
@@ -1,9 +1,9 @@
"use client";
import { useState, useTransition } from "react";
import { useState, useTransition, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { User, Lock, CheckCircle } from "lucide-react";
import { User, Lock, CheckCircle, Mail } from "lucide-react";
import { PASSWORD_MIN_LENGTH } from "@/lib/config/auth";
import { PasswordInput } from "@/components/portal/PasswordInput";
import { userRoleLabel } from "@/lib/config/users";
@@ -38,6 +38,38 @@ export default function SettingsPage() {
}
}
/* ── Email preferences section ───────────────────────────────────────── */
const [digestOptOut, setDigestOptOut] = useState<boolean | null>(null);
const [emailSaving, setEmailSaving] = useState(false);
const [emailMsg, setEmailMsg] = useState<{ ok: boolean; text: string } | null>(null);
useEffect(() => {
fetch("/api/account")
.then((r) => r.json())
.then(({ data }) => setDigestOptOut(Boolean(data?.digestOptOut)))
.catch(() => setDigestOptOut(false));
}, []);
async function toggleWelcomeDigest(next: boolean) {
setDigestOptOut(next);
setEmailMsg(null);
setEmailSaving(true);
const res = await fetch("/api/account", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ digestOptOut: next }),
});
const data = await res.json();
setEmailSaving(false);
if (data.success) {
setEmailMsg({ ok: true, text: next ? "Onboarding emails turned off." : "Onboarding emails turned on." });
} else {
// Roll back UI on failure
setDigestOptOut(!next);
setEmailMsg({ ok: false, text: data.error ?? "Update failed." });
}
}
/* ── Password section ────────────────────────────────────────────────── */
const [currentPw, setCurrentPw] = useState("");
const [newPw, setNewPw] = useState("");
@@ -145,6 +177,40 @@ export default function SettingsPage() {
</form>
</div>
{/* ── Email preferences ───────────────────────────────────────── */}
<div className="card p-6">
<div className="flex items-center gap-2 mb-5">
<div className="w-8 h-8 rounded-lg bg-[var(--teal-light)] flex items-center justify-center">
<Mail className="w-4 h-4 text-[var(--teal)]" />
</div>
<h2 className="font-semibold text-[var(--ink)]">Email preferences</h2>
</div>
<label className="flex items-start gap-3 cursor-pointer">
<input
type="checkbox"
checked={digestOptOut === true}
disabled={digestOptOut === null || emailSaving}
onChange={(e) => toggleWelcomeDigest(e.target.checked)}
className="mt-0.5 w-4 h-4 rounded border-[var(--border)] text-[var(--teal)] focus:ring-[var(--teal)]"
/>
<span className="text-sm">
<span className="font-medium text-[var(--ink)] block">Skip the onboarding email series</span>
<span className="text-[var(--muted)] block mt-0.5">
You&apos;ll still receive transactional emails for your pets — vaccination reminders,
health alerts, order confirmations — these are necessary for the service.
</span>
</span>
</label>
{emailMsg && (
<p className={`mt-3 ${emailMsg.ok ? "alert-success flex items-center gap-2" : "alert-error"}`}>
{emailMsg.ok && <CheckCircle className="w-4 h-4 flex-shrink-0" />}
{emailMsg.text}
</p>
)}
</div>
{/* ── Password ─────────────────────────────────────────────────── */}
<div className="card p-6">
<div className="flex items-center gap-2 mb-5">
+28
View File
@@ -15,6 +15,7 @@ const updateAccountSchema = z.object({
name: z.string().min(1).max(100).optional(),
currentPassword: z.string().optional(),
newPassword: z.string().min(PASSWORD_MIN_LENGTH).optional(),
digestOptOut: z.boolean().optional(),
}).refine(
(d) => !(d.newPassword && !d.currentPassword),
{ message: "Current password is required to set a new password", path: ["currentPassword"] },
@@ -76,6 +77,29 @@ export async function POST(req: NextRequest) {
}
}
/** GET /api/account — returns the current user's editable preferences. */
export async function GET() {
const { session, error } = await requireSession();
if (error) return error;
const db = getInstance();
const [user] = await db
.select({
name: users.name,
email: users.email,
locale: users.locale,
digestOptOut: users.digestOptOut,
})
.from(users)
.where(eq(users.id, session.user.id))
.limit(1);
if (!user) {
return NextResponse.json({ success: false, error: "Account not found" }, { status: 404 });
}
return NextResponse.json({ success: true, data: user });
}
export async function PATCH(req: NextRequest) {
const { session, error } = await requireSession();
if (error) return error;
@@ -102,6 +126,10 @@ export async function PATCH(req: NextRequest) {
updates.name = parsed.data.name.trim();
}
if (typeof parsed.data.digestOptOut === "boolean") {
updates.digestOptOut = parsed.data.digestOptOut;
}
if (parsed.data.newPassword) {
if (!user.password) {
return NextResponse.json(
+12 -2
View File
@@ -29,13 +29,14 @@ export async function POST(req: NextRequest) {
// Fetch all user emails in one query to avoid N+1
const userIds = [...new Set(pending.map((item) => item.userId))];
const userRows = await db
.select({ id: users.id, name: users.name, email: users.email })
.select({ id: users.id, name: users.name, email: users.email, digestOptOut: users.digestOptOut })
.from(users)
.where(inArray(users.id, userIds));
const userMap = new Map(userRows.map((u) => [u.id, u]));
let sent = 0;
let failed = 0;
let skipped = 0;
for (const item of pending) {
const templateFn = TEMPLATE_MAP[item.templateKey as TemplateKey];
@@ -44,6 +45,15 @@ export async function POST(req: NextRequest) {
const user = userMap.get(item.userId);
if (!user?.email) continue;
// Respect the user's opt-out — drop the queued item so it doesn't
// re-process tomorrow. Welcome emails are non-critical; no need to
// keep audit history of cancelled ones.
if (user.digestOptOut) {
await db.delete(emailQueue).where(eq(emailQueue.id, item.id));
skipped++;
continue;
}
try {
const { subject, html } = templateFn(item.payload);
await sendEmail({ to: user.email, subject, html });
@@ -63,5 +73,5 @@ export async function POST(req: NextRequest) {
}
}
return NextResponse.json({ success: true, data: { sent, failed } });
return NextResponse.json({ success: true, data: { sent, failed, skipped } });
}
+2 -1
View File
@@ -93,6 +93,8 @@ export const users = pgTable("users", {
verifiedAt: timestamp("verified_at", { mode: "date" }),
/** Persisted UI locale — set by LocaleSwitcher; null = use defaultLocale. */
locale: varchar("locale", { length: 5 }),
/** When true, skip the welcome email digest (day-1/3/7 onboarding sequence). */
digestOptOut: boolean("digest_opt_out").notNull().default(false),
createdAt: timestamp("created_at", { mode: "date" }).notNull().defaultNow(),
});
@@ -140,7 +142,6 @@ export const ownerProfiles = pgTable("owner_profiles", {
country: varchar("country", { length: 2 }),
timezone: varchar("timezone", { length: 60 }),
bio: text("bio"),
digestOptOut: boolean("digest_opt_out").notNull().default(false),
createdAt: timestamp("created_at", { mode: "date" }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date" }).notNull().defaultNow(),
});