tia/src/app/api/family/route.ts
Mannu bdb5199d5f fix(settings): pediatrician save + edit mode
- API: dynamic SET clause (only updates fields present in body) fixes
  undefined param bug and allows clearing fields; replaces blanket COALESCE
- Settings UI: display/edit toggle — saved details shown with Edit button,
  inputs open on first visit or when editing; Save shows inline error on
  failure and brief "Saved!" on success

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 01:00:00 +05:30

62 lines
No EOL
2.3 KiB
TypeScript

import { NextResponse } from "next/server";
import { sql } from "@/db";
import { requireFamily } from "@/lib/auth";
// GET - get family details
export async function GET(request: Request) {
const auth = await requireFamily();
if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });
try {
const family = await sql.unsafe(
`SELECT id, name, tier, max_children, max_members, pediatrician_phone, pediatrician_name FROM families WHERE id = $1`,
[auth.session!.familyId]
);
if (!family || family.length === 0) {
return NextResponse.json({ error: "Family not found" }, { status: 404 });
}
return NextResponse.json({ family: family[0] });
} catch (error) {
console.error(error);
return NextResponse.json({ error: String(error) }, { status: 500 });
}
}
// PATCH - update family
export async function PATCH(request: Request) {
const auth = await requireFamily();
if (!auth.success) return NextResponse.json({ error: auth.error }, { status: auth.status });
try {
const body = await request.json();
const { name, pediatricianPhone, pediatricianName, tier } = body;
// Only update fields that are explicitly present in the request body.
// This avoids COALESCE masking clears and undefined params causing errors.
const setClauses: string[] = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const params: any[] = [];
if (name !== undefined) { setClauses.push(`name = $${params.push(name)}`); }
if (pediatricianPhone !== undefined) { setClauses.push(`pediatrician_phone = $${params.push(pediatricianPhone || null)}`); }
if (pediatricianName !== undefined) { setClauses.push(`pediatrician_name = $${params.push(pediatricianName || null)}`); }
if (tier !== undefined) { setClauses.push(`tier = $${params.push(tier)}`); }
if (setClauses.length === 0) return NextResponse.json({ success: true });
setClauses.push("updated_at = NOW()");
params.push(auth.session!.familyId);
await sql.unsafe(
`UPDATE families SET ${setClauses.join(", ")} WHERE id = $${params.length}`,
params
);
return NextResponse.json({ success: true });
} catch (error) {
console.error(error);
return NextResponse.json({ error: String(error) }, { status: 500 });
}
}