Merge main into feat/gro-107-ical-feed to resolve merge conflicts

- portal.ts: keep min(1) validation for customerNotes (more restrictive)
- index.ts: keep waitlistRouter import and both calendar + portal public routes
- Both routers can coexist in public section (different URL namespaces)

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Flea Flicker
2026-03-26 08:36:57 +00:00
9 changed files with 652 additions and 16 deletions
+92 -9
View File
@@ -110,20 +110,23 @@ jobs:
docker:
name: Build & Push Docker Images
runs-on: ubuntu-latest
needs: [build]
if: github.ref == 'refs/heads/main'
needs: [build, e2e]
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Generate version tag
- name: Generate image tag
id: version
run: |
TAG="$(date -u +%Y.%m.%d)-${GITHUB_SHA::7}"
if [ "${{ github.event_name }}" = "pull_request" ]; then
TAG="pr-${{ github.event.pull_request.number }}"
else
TAG="$(date -u +%Y.%m.%d)-${GITHUB_SHA::7}"
fi
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "Image version: $TAG"
echo "Image tag: $TAG"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
@@ -144,7 +147,7 @@ jobs:
push: true
tags: |
ghcr.io/groombook/api:${{ steps.version.outputs.tag }}
ghcr.io/groombook/api:latest
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/api:latest' || '' }}
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -157,7 +160,7 @@ jobs:
push: true
tags: |
ghcr.io/groombook/migrate:${{ steps.version.outputs.tag }}
ghcr.io/groombook/migrate:latest
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/migrate:latest' || '' }}
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -170,7 +173,7 @@ jobs:
push: true
tags: |
ghcr.io/groombook/seed:${{ steps.version.outputs.tag }}
ghcr.io/groombook/seed:latest
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/seed:latest' || '' }}
cache-from: type=gha
cache-to: type=gha,mode=max
@@ -182,6 +185,86 @@ jobs:
push: true
tags: |
ghcr.io/groombook/web:${{ steps.version.outputs.tag }}
ghcr.io/groombook/web:latest
${{ github.ref == 'refs/heads/main' && 'ghcr.io/groombook/web:latest' || '' }}
cache-from: type=gha
cache-to: type=gha,mode=max
deploy-dev:
name: Deploy PR to groombook-dev
runs-on: runners-groombook
needs: [docker]
if: github.event_name == 'pull_request'
permissions:
contents: read
pull-requests: write
steps:
- name: Install kubectl
run: |
curl -sLO "https://dl.k8s.io/release/$(curl -sL https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
chmod +x kubectl
sudo mv kubectl /usr/local/bin/
kubectl version --client
- name: Deploy to groombook-dev
env:
TAG: pr-${{ github.event.pull_request.number }}
PR_NUM: ${{ github.event.pull_request.number }}
run: |
echo "Deploying images tagged $TAG to groombook-dev..."
# Run migration with PR image
kubectl delete job migrate-schema -n groombook-dev --ignore-not-found
kubectl delete job "migrate-pr-$PR_NUM" -n groombook-dev --ignore-not-found
cat <<EOF | kubectl apply -n groombook-dev -f -
apiVersion: batch/v1
kind: Job
metadata:
name: migrate-pr-$PR_NUM
spec:
ttlSecondsAfterFinished: 3600
backoffLimit: 2
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: ghcr.io/groombook/migrate:$TAG
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: groombook-postgres-credentials
key: uri
EOF
kubectl wait --for=condition=complete "job/migrate-pr-$PR_NUM" \
-n groombook-dev --timeout=120s
# Update deployments
kubectl set image deployment/api api=ghcr.io/groombook/api:$TAG -n groombook-dev
kubectl set image deployment/web web=ghcr.io/groombook/web:$TAG -n groombook-dev
# Wait for rollout
kubectl rollout status deployment/api -n groombook-dev --timeout=120s
kubectl rollout status deployment/web -n groombook-dev --timeout=120s
echo "Deployment complete."
- name: Comment on PR
uses: actions/github-script@v7
with:
script: |
const pr = context.issue.number;
const tag = `pr-${pr}`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr,
body: [
'## Deployed to groombook-dev',
'',
`**Images:** \`${tag}\``,
'**URL:** https://dev.groombook.farh.net',
'',
'Ready for UAT validation.'
].join('\n')
});
+249
View File
@@ -0,0 +1,249 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Hono } from "hono";
const CLIENT_ID = "550e8400-e29b-41d4-a716-446655440001";
const APPOINTMENT_ID = "660e8400-e29b-41d4-a716-446655440002";
const SESSION_ID = "770e8400-e29b-41d4-a716-446655440003";
const futureDate = () => new Date(Date.now() + 30 * 60 * 1000);
const pastDate = () => new Date(Date.now() - 5 * 60 * 1000);
const ACTIVE_SESSION = {
id: SESSION_ID,
clientId: CLIENT_ID,
status: "active" as const,
expiresAt: futureDate(),
createdAt: new Date(),
};
const EXPIRED_SESSION = {
id: SESSION_ID,
clientId: CLIENT_ID,
status: "active" as const,
expiresAt: pastDate(),
createdAt: new Date(),
};
const APPOINTMENT = {
id: APPOINTMENT_ID,
clientId: CLIENT_ID,
startTime: futureDate(),
endTime: futureDate(),
customerNotes: null,
confirmationToken: "secret-token-leak-test",
};
let selectSessionRow: Record<string, unknown> | null = null;
let selectAppointmentRow: Record<string, unknown> | null = null;
let updatedValues: Record<string, unknown>[] = [];
function resetMock() {
selectSessionRow = null;
selectAppointmentRow = null;
updatedValues = [];
}
vi.mock("@groombook/db", () => {
function makeChainable(data: unknown[]): unknown {
const arr = [...data];
const chain = new Proxy(arr, {
get(target, prop) {
if (prop === "where" || prop === "orderBy" || prop === "limit") {
return () => chain;
}
// @ts-expect-error proxy
return target[prop];
},
});
return chain;
}
const impersonationSessions = new Proxy(
{ _name: "impersonationSessions" },
{ get: (t, p) => (p === "_name" ? "impersonationSessions" : { table: "impersonationSessions", column: p }) }
);
const appointments = new Proxy(
{ _name: "appointments" },
{ get: (t, p) => (p === "_name" ? "appointments" : { table: "appointments", column: p }) }
);
return {
getDb: () => ({
select: () => ({
from: (table: { _name: string }) => {
if (table._name === "impersonationSessions") {
return makeChainable(selectSessionRow ? [selectSessionRow] : []);
}
if (table._name === "appointments") {
return makeChainable(selectAppointmentRow ? [selectAppointmentRow] : []);
}
return makeChainable([]);
},
}),
update: () => ({
set: (vals: Record<string, unknown>) => ({
where: () => ({
returning: () => {
if (selectAppointmentRow) {
const updated = { ...selectAppointmentRow, ...vals };
updatedValues.push(vals);
return [updated];
}
return [];
},
}),
}),
}),
}),
impersonationSessions,
appointments,
eq: vi.fn(),
and: vi.fn(),
};
});
const { portalRouter } = await import("../routes/portal.js");
const app = new Hono();
app.route("/portal", portalRouter);
function jsonPatch(path: string, body: unknown, headers?: Record<string, string>) {
return app.request(path, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
...headers,
},
body: JSON.stringify(body),
});
}
beforeEach(() => resetMock());
describe("PATCH /portal/appointments/:id/notes", () => {
it("returns updated appointment with safe fields only", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Please be gentle with Fido" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toHaveProperty("id");
expect(body).toHaveProperty("customerNotes", "Please be gentle with Fido");
expect(body).toHaveProperty("updatedAt");
expect(body).not.toHaveProperty("confirmationToken");
expect(body).not.toHaveProperty("clientId");
});
it("returns 401 without X-Impersonation-Session-Id header", async () => {
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" }
);
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe("Unauthorized");
});
it("returns 401 with expired session", async () => {
selectSessionRow = EXPIRED_SESSION;
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe("Unauthorized");
});
it("returns 401 with ended session", async () => {
selectSessionRow = null;
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(401);
const body = await res.json();
expect(body.error).toBe("Unauthorized");
});
it("returns 403 when appointment belongs to different client", async () => {
selectSessionRow = { ...ACTIVE_SESSION, clientId: "different-client-id" };
selectAppointmentRow = { ...APPOINTMENT };
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(403);
const body = await res.json();
expect(body.error).toBe("Forbidden");
});
it("returns 422 for past appointment", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, startTime: pastDate() };
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
const body = await res.json();
expect(body.error).toMatch(/past|in-progress|cannot edit/i);
});
it("returns 422 when appointment is in progress", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT, startTime: new Date(Date.now() - 2 * 60 * 1000) };
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(422);
});
it("returns 404 when appointment not found", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = null;
const res = await jsonPatch(
`/portal/appointments/nonexistent-id/notes`,
{ customerNotes: "Test note" },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(404);
});
it("accepts notes at exactly 500 characters", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
const longNote = "a".repeat(500);
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: longNote },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.customerNotes).toBe(longNote);
});
it("rejects notes exceeding 500 characters", async () => {
selectSessionRow = ACTIVE_SESSION;
selectAppointmentRow = { ...APPOINTMENT };
const longNote = "a".repeat(501);
const res = await jsonPatch(
`/portal/appointments/${APPOINTMENT_ID}/notes`,
{ customerNotes: longNote },
{ "X-Impersonation-Session-Id": SESSION_ID }
);
expect(res.status).toBe(400);
});
});
+2
View File
@@ -61,6 +61,8 @@ app.get("/api/branding", async (c) => {
// Public iCal calendar feed — token auth in URL, no auth middleware required
app.route("/api/calendar", calendarRouter);
// Portal routes — no staff auth required, uses impersonation session for client auth
app.route("/api/portal", portalRouter);
// Protected API routes
const api = app.basePath("/api");
@@ -0,0 +1,194 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import type { Appointment } from "../portal/mockData.js";
import { parseTimeTo24Hour, isUpcoming, CustomerNotesSection } from "../portal/sections/Appointments.js";
const UPCOMING_APPT: Appointment = {
id: "appt-1",
petId: "pet-1",
petName: "Buddy",
groomerId: "groomer-1",
groomerName: "Sarah",
services: ["Bath & Brush"],
addOns: [],
date: "2027-01-01",
time: "10:00 AM",
duration: 60,
price: 50,
status: "confirmed",
notes: "",
customerNotes: "",
};
const PAST_APPT: Appointment = {
...UPCOMING_APPT,
id: "appt-2",
date: "2025-01-01",
time: "10:00 AM",
status: "completed",
};
describe("parseTimeTo24Hour", () => {
it("converts AM times correctly", () => {
expect(parseTimeTo24Hour("9:00 AM")).toBe("09:00:00");
expect(parseTimeTo24Hour("10:00 AM")).toBe("10:00:00");
expect(parseTimeTo24Hour("12:00 AM")).toBe("00:00:00");
});
it("converts PM times correctly", () => {
expect(parseTimeTo24Hour("1:00 PM")).toBe("13:00:00");
expect(parseTimeTo24Hour("2:00 PM")).toBe("14:00:00");
expect(parseTimeTo24Hour("11:00 PM")).toBe("23:00:00");
expect(parseTimeTo24Hour("12:00 PM")).toBe("12:00:00");
});
});
describe("isUpcoming", () => {
it("returns true for future confirmed appointments", () => {
expect(isUpcoming(UPCOMING_APPT)).toBe(true);
});
it("returns false for past appointments", () => {
expect(isUpcoming(PAST_APPT)).toBe(false);
});
it("returns false for cancelled appointments", () => {
expect(isUpcoming({ ...UPCOMING_APPT, status: "cancelled" })).toBe(false);
});
it("returns false for completed appointments", () => {
expect(isUpcoming({ ...UPCOMING_APPT, status: "completed" })).toBe(false);
});
});
describe("CustomerNotesSection", () => {
beforeEach(() => {
vi.clearAllMocks();
global.fetch = vi.fn();
});
it("renders textarea with existing notes", () => {
render(<CustomerNotesSection appointment={{ ...UPCOMING_APPT, customerNotes: "Test note" }} sessionId="test-session-id" />);
expect(screen.getByRole("textbox")).toHaveValue("Test note");
});
it("renders Save Notes button", () => {
render(<CustomerNotesSection appointment={UPCOMING_APPT} sessionId="test-session-id" />);
expect(screen.getByRole("button", { name: /Save Notes/i })).toBeInTheDocument();
});
it("sends X-Impersonation-Session-Id header when session exists", async () => {
vi.mocked(global.fetch).mockResolvedValue({
ok: true,
json: async () => ({ id: "appt-1", customerNotes: "Updated", updatedAt: new Date().toISOString() }),
} as Response);
render(<CustomerNotesSection appointment={UPCOMING_APPT} sessionId="test-session-id" />);
fireEvent.change(screen.getByRole("textbox"), { target: { value: "New note" } });
fireEvent.click(screen.getByRole("button", { name: /Save Notes/i }));
await waitFor(() => {
expect(global.fetch).toHaveBeenCalledWith(
"/api/portal/appointments/appt-1/notes",
expect.objectContaining({
headers: expect.objectContaining({
"X-Impersonation-Session-Id": "test-session-id",
}),
})
);
});
});
it("does not send X-Impersonation-Session-Id header when sessionId is null", async () => {
vi.mocked(global.fetch).mockResolvedValue({
ok: true,
json: async () => ({ id: "appt-1", customerNotes: "Updated", updatedAt: new Date().toISOString() }),
} as Response);
render(<CustomerNotesSection appointment={UPCOMING_APPT} sessionId={null} />);
fireEvent.change(screen.getByRole("textbox"), { target: { value: "New note" } });
fireEvent.click(screen.getByRole("button", { name: /Save Notes/i }));
await waitFor(() => {
expect(global.fetch).toHaveBeenCalledWith(
"/api/portal/appointments/appt-1/notes",
expect.objectContaining({
headers: expect.not.objectContaining({
"X-Impersonation-Session-Id": expect.anything(),
}),
})
);
});
});
it("shows error message when save fails", async () => {
vi.mocked(global.fetch).mockResolvedValue({
ok: false,
status: 401,
json: async () => ({ error: "Unauthorized" }),
} as Response);
render(<CustomerNotesSection appointment={UPCOMING_APPT} sessionId="test-session-id" />);
fireEvent.change(screen.getByRole("textbox"), { target: { value: "New note" } });
fireEvent.click(screen.getByRole("button", { name: /Save Notes/i }));
await waitFor(() => {
expect(screen.getByText(/Unauthorized/i)).toBeInTheDocument();
});
});
it("shows success message when save succeeds", async () => {
vi.mocked(global.fetch).mockResolvedValue({
ok: true,
json: async () => ({ id: "appt-1", customerNotes: "Saved", updatedAt: new Date().toISOString() }),
} as Response);
render(<CustomerNotesSection appointment={UPCOMING_APPT} sessionId="test-session-id" />);
fireEvent.change(screen.getByRole("textbox"), { target: { value: "Saved note" } });
fireEvent.click(screen.getByRole("button", { name: /Save Notes/i }));
await waitFor(() => {
expect(screen.getByText(/Saved!/i)).toBeInTheDocument();
});
});
it("disables button when notes unchanged", () => {
render(<CustomerNotesSection appointment={{ ...UPCOMING_APPT, customerNotes: "Existing" }} sessionId="test-session-id" />);
expect(screen.getByRole("button", { name: /Save Notes/i })).toBeDisabled();
});
it("enforces 500 character limit", () => {
render(<CustomerNotesSection appointment={UPCOMING_APPT} sessionId="test-session-id" />);
const textarea = screen.getByRole("textbox");
const longText = "a".repeat(600);
fireEvent.change(textarea, { target: { value: longText } });
expect(textarea).toHaveValue("a".repeat(500));
});
it("displays character count", () => {
render(<CustomerNotesSection appointment={UPCOMING_APPT} sessionId="test-session-id" />);
expect(screen.getByText(/0\/500/)).toBeInTheDocument();
});
it("shows exceeded character count in red when limit exceeded", () => {
render(<CustomerNotesSection appointment={UPCOMING_APPT} sessionId="test-session-id" />);
const textarea = screen.getByRole("textbox");
// Type characters one by one to exceed limit
const longText = "a".repeat(501);
fireEvent.change(textarea, { target: { value: longText } });
// The textarea value is truncated to 500, so counter shows 500/500
// The class check would need to verify text-red-500 appears
// Since the onChange truncates, we test that limit is enforced
expect(textarea).toHaveValue("a".repeat(500));
});
it("does not render save button for completed appointments", () => {
render(<CustomerNotesSection appointment={{ ...UPCOMING_APPT, status: "completed" }} sessionId="test-session-id" />);
expect(screen.queryByRole("button", { name: /Save Notes/i })).not.toBeInTheDocument();
});
it("does not render save button for cancelled appointments", () => {
render(<CustomerNotesSection appointment={{ ...UPCOMING_APPT, status: "cancelled" }} sessionId="test-session-id" />);
expect(screen.queryByRole("button", { name: /Save Notes/i })).not.toBeInTheDocument();
});
});
+1
View File
@@ -707,6 +707,7 @@ function AppointmentDetail({
? `✗ Customer cancelled${appt.cancelledAt ? ` (${new Date(appt.cancelledAt).toLocaleString()})` : ""}`
: "Pending"],
["Notes", appt.notes ?? "—"],
...(appt.customerNotes ? [["Customer Notes", appt.customerNotes] as [string, string]] : []),
...(appt.seriesId
? [["Series slot", `#${(appt.seriesIndex ?? 0) + 1}`] as [string, string]]
: []),
+1 -1
View File
@@ -114,7 +114,7 @@ export function CustomerPortal() {
case "dashboard":
return <Dashboard onNavigate={handleNavClick} readOnly={!!isReadOnly} />;
case "appointments":
return <AppointmentsSection readOnly={!!isReadOnly} />;
return <AppointmentsSection readOnly={!!isReadOnly} sessionId={session?.id ?? null} />;
case "pets":
return <PetProfiles readOnly={!!isReadOnly} />;
case "reports":
+12
View File
@@ -42,6 +42,7 @@ export interface Appointment {
price: number;
status: "confirmed" | "pending" | "waitlisted" | "completed" | "cancelled";
notes: string;
customerNotes: string;
reportCardId?: string;
}
@@ -177,18 +178,21 @@ export const UPCOMING_APPOINTMENTS: Appointment[] = [
services: ["Full Groom"], addOns: ["De-shedding Treatment"],
date: "2026-03-21", time: "10:00 AM", duration: 120, price: 145,
status: "confirmed", notes: "Spring shed is heavy — extra undercoat work needed",
customerNotes: "",
},
{
id: "a2", petId: "p2", petName: "Mochi", groomerId: "g3", groomerName: "Morgan",
services: ["Full Groom"], addOns: ["Teeth Brushing"],
date: "2026-03-25", time: "2:00 PM", duration: 100, price: 90,
status: "confirmed", notes: "First visit with Morgan — patient with anxious pets",
customerNotes: "",
},
{
id: "a3", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie",
services: ["Bath & Brush"], addOns: [],
date: "2026-04-18", time: "11:00 AM", duration: 45, price: 55,
status: "pending", notes: "",
customerNotes: "",
},
];
@@ -198,48 +202,56 @@ export const PAST_APPOINTMENTS: Appointment[] = [
services: ["Full Groom"], addOns: ["De-shedding Treatment", "Blueberry Facial"],
date: "2026-02-15", time: "10:00 AM", duration: 130, price: 160,
status: "completed", notes: "", reportCardId: "rc1",
customerNotes: "",
},
{
id: "pa2", petId: "p2", petName: "Mochi", groomerId: "g2", groomerName: "Alex",
services: ["Full Groom"], addOns: ["Teeth Brushing"],
date: "2026-02-20", time: "1:00 PM", duration: 100, price: 88,
status: "completed", notes: "", reportCardId: "rc2",
customerNotes: "",
},
{
id: "pa3", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie",
services: ["Bath & Brush"], addOns: [],
date: "2026-01-18", time: "9:00 AM", duration: 45, price: 55,
status: "completed", notes: "",
customerNotes: "",
},
{
id: "pa4", petId: "p2", petName: "Mochi", groomerId: "g2", groomerName: "Alex",
services: ["Puppy's First Groom"], addOns: [],
date: "2026-01-10", time: "3:00 PM", duration: 60, price: 62,
status: "completed", notes: "",
customerNotes: "",
},
{
id: "pa5", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie",
services: ["Full Groom"], addOns: ["Nail Grinding"],
date: "2025-12-20", time: "10:00 AM", duration: 105, price: 132,
status: "completed", notes: "Holiday groom",
customerNotes: "",
},
{
id: "pa6", petId: "p1", petName: "Biscuit", groomerId: "g2", groomerName: "Alex",
services: ["Full Groom"], addOns: [],
date: "2025-11-15", time: "11:00 AM", duration: 90, price: 110,
status: "completed", notes: "",
customerNotes: "",
},
{
id: "pa7", petId: "p2", petName: "Mochi", groomerId: "g3", groomerName: "Morgan",
services: ["Bath & Brush"], addOns: [],
date: "2025-11-08", time: "2:00 PM", duration: 45, price: 48,
status: "completed", notes: "",
customerNotes: "",
},
{
id: "pa8", petId: "p1", petName: "Biscuit", groomerId: "g1", groomerName: "Jamie",
services: ["Bath & Brush"], addOns: ["De-shedding Treatment"],
date: "2025-10-12", time: "10:00 AM", duration: 75, price: 85,
status: "completed", notes: "",
customerNotes: "",
},
];
+100 -6
View File
@@ -1,16 +1,38 @@
import { useState } from "react";
import { Calendar, Clock, Plus, ChevronRight, ChevronDown, Search, Repeat } from "lucide-react";
import { Calendar, Clock, Plus, ChevronRight, ChevronDown, Search, Repeat, Loader2 } from "lucide-react";
import { UPCOMING_APPOINTMENTS, PAST_APPOINTMENTS, PETS, SERVICES, GROOMERS } from "../mockData.js";
import type { Appointment, Pet, Service, Groomer } from "../mockData.js";
const MAX_CUSTOMER_NOTES = 500;
interface Props {
readOnly: boolean;
sessionId?: string | null;
}
function formatDate(dateStr: string): string {
export function formatDate(dateStr: string): string {
return new Date(dateStr).toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric", year: "numeric" });
}
export function parseTimeTo24Hour(time: string): string {
const parts = time.split(" ");
const hoursMinutes = parts[0] ?? "";
const period = parts[1] ?? "";
const [hoursStr, minutesStr] = hoursMinutes.split(":");
const hours = parseInt(hoursStr ?? "0", 10);
const minutes = parseInt(minutesStr ?? "0", 10);
let hours24 = hours;
if (period === "PM" && hours !== 12) hours24 += 12;
if (period === "AM" && hours === 12) hours24 = 0;
return `${hours24.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:00`;
}
export function isUpcoming(appt: Appointment): boolean {
const now = new Date();
const apptDate = new Date(`${appt.date}T${parseTimeTo24Hour(appt.time)}`);
return apptDate > now && appt.status !== "cancelled" && appt.status !== "completed";
}
const STATUS_COLORS: Record<string, string> = {
confirmed: "bg-green-100 text-green-700",
pending: "bg-amber-100 text-amber-700",
@@ -19,7 +41,7 @@ const STATUS_COLORS: Record<string, string> = {
cancelled: "bg-red-100 text-red-600",
};
export function AppointmentsSection({ readOnly }: Props) {
export function AppointmentsSection({ readOnly, sessionId }: Props) {
const [showBooking, setShowBooking] = useState(false);
const [expandedId, setExpandedId] = useState<string | null>(null);
const [tab, setTab] = useState<"upcoming" | "past">("upcoming");
@@ -61,6 +83,7 @@ export function AppointmentsSection({ readOnly }: Props) {
expanded={expandedId === appt.id}
onToggle={() => setExpandedId(expandedId === appt.id ? null : appt.id)}
readOnly={readOnly}
sessionId={sessionId}
/>
))}
{UPCOMING_APPOINTMENTS.length === 0 && (
@@ -78,6 +101,7 @@ export function AppointmentsSection({ readOnly }: Props) {
expanded={expandedId === appt.id}
onToggle={() => setExpandedId(expandedId === appt.id ? null : appt.id)}
readOnly={readOnly}
sessionId={sessionId}
/>
))}
</div>
@@ -94,9 +118,9 @@ export function AppointmentsSection({ readOnly }: Props) {
}
function AppointmentCard({
appointment: appt, expanded, onToggle, readOnly,
appointment: appt, expanded, onToggle, readOnly, sessionId,
}: {
appointment: Appointment; expanded: boolean; onToggle: () => void; readOnly: boolean;
appointment: Appointment; expanded: boolean; onToggle: () => void; readOnly: boolean; sessionId?: string | null;
}) {
return (
<div className="bg-white rounded-xl border border-stone-200 shadow-sm overflow-hidden">
@@ -138,8 +162,11 @@ function AppointmentCard({
{appt.notes && (
<p className="text-sm text-stone-600 bg-stone-50 rounded-lg px-3 py-2 mb-3">{appt.notes}</p>
)}
{isUpcoming(appt) && !readOnly && (
<CustomerNotesSection appointment={appt} sessionId={sessionId} />
)}
{appt.status !== "completed" && appt.status !== "cancelled" && !readOnly && (
<div className="flex gap-2">
<div className="flex gap-2 mt-3">
<button className="text-xs px-3 py-1.5 border border-stone-200 rounded-lg text-stone-600 hover:bg-stone-50">
Reschedule
</button>
@@ -161,6 +188,73 @@ function AppointmentCard({
);
}
export function CustomerNotesSection({ appointment: appt, sessionId }: { appointment: Appointment; sessionId?: string | null }) {
const [notes, setNotes] = useState(appt.customerNotes || "");
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState(false);
const [error, setError] = useState<string | null>(null);
const isDisabled = appt.status === "completed" || appt.status === "cancelled";
async function handleSave() {
setSaving(true);
setError(null);
setSaved(false);
try {
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (sessionId) {
headers["X-Impersonation-Session-Id"] = sessionId;
}
const res = await fetch(`/api/portal/appointments/${appt.id}/notes`, {
method: "PATCH",
headers,
body: JSON.stringify({ customerNotes: notes }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: "Failed to save" }));
throw new Error(err.error || `HTTP ${res.status}`);
}
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} catch (e) {
setError(e instanceof Error ? e.message : "Failed to save");
} finally {
setSaving(false);
}
}
return (
<div className="mt-3 p-3 bg-stone-50 rounded-lg">
<div className="flex items-center justify-between mb-1.5">
<label className="text-xs font-medium text-stone-600">Notes for your groomer</label>
<span className={`text-xs ${notes.length > MAX_CUSTOMER_NOTES ? "text-red-500" : "text-stone-400"}`}>
{notes.length}/{MAX_CUSTOMER_NOTES}
</span>
</div>
<textarea
value={notes}
onChange={e => setNotes(e.target.value.slice(0, MAX_CUSTOMER_NOTES))}
disabled={isDisabled}
className="w-full text-sm border border-stone-200 rounded-lg px-3 py-2 resize-none focus:outline-none focus:ring-2 focus:ring-(--color-accent) disabled:bg-stone-100 disabled:text-stone-400"
rows={3}
placeholder="Any special requests or notes for this appointment..."
/>
{error && <p className="text-xs text-red-500 mt-1">{error}</p>}
{saved && <p className="text-xs text-green-600 mt-1">Saved!</p>}
{!isDisabled && (
<button
onClick={handleSave}
disabled={saving || notes === appt.customerNotes}
className="mt-2 flex items-center gap-1.5 text-xs px-3 py-1.5 bg-(--color-accent) text-white rounded-lg font-medium hover:bg-(--color-accent-hover) disabled:opacity-50 disabled:cursor-not-allowed"
>
{saving && <Loader2 size={12} className="animate-spin" />}
{saving ? "Saving..." : "Save Notes"}
</button>
)}
</div>
);
}
function BookingFlow({ onClose, readOnly }: { onClose: () => void; readOnly: boolean }) {
const [step, setStep] = useState(1);
const [selectedPet, setSelectedPet] = useState<Pet | null>(null);
+1
View File
@@ -110,6 +110,7 @@ export interface Appointment {
confirmedAt: string | null;
cancelledAt: string | null;
confirmationToken: string | null;
customerNotes: string | null;
createdAt: string;
updatedAt: string;
}