diff --git a/.gitignore b/.gitignore index 14923ee..112405c 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,16 @@ dist/ .turbo/ coverage/ minimax-output/ + +# Agent runtime artifacts — never commit +.gh-token +*.gh-token +.config/gh/ +**/.config/gh/ +infra-repo +infra-repo/ +**/instructions/.gh-token +**/AGENT_HOME/** +$AGENT_HOME/** +.claude/ +.codex/ diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index c6e90a5..1ed08f2 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -19,7 +19,7 @@ import { impersonationRouter } from "./routes/impersonation.js"; import { settingsRouter } from "./routes/settings.js"; import { authProviderRouter } from "./routes/authProvider.js"; import { searchRouter } from "./routes/search.js"; -import { getPresignedGetUrl } from "./lib/s3.js"; +import { getObject } from "./lib/s3.js"; import { calendarRouter } from "./routes/calendar.js"; import { setupRouter } from "./routes/setup.js"; import { getDb, businessSettings, eq, staff } from "@groombook/db"; @@ -126,20 +126,31 @@ function validateLogoMagicBytes( } } +// Public logo proxy — no auth required, streams logo from S3 so browser never sees raw S3 URL +app.get("/api/branding/logo", async (c) => { + const db = getDb(); + const [row] = await db.select().from(businessSettings).limit(1); + if (!row) return c.json({ error: "Settings not found" }, 404); + if (!row.logoKey) return c.json({ error: "No logo on file" }, 404); + + const { body, contentType } = await getObject(row.logoKey); + return new Response(Buffer.from(body), { + status: 200, + headers: { + "Content-Type": contentType, + "Cache-Control": "public, max-age=86400", + }, + }); +}); + // Public branding endpoint — no auth required, returns business name/colors/logo app.get("/api/branding", async (c) => { const db = getDb(); const [row] = await db.select().from(businessSettings).limit(1); const settings = row ?? { businessName: "GroomBook", primaryColor: "#4f8a6f", accentColor: "#8b7355", logoBase64: null, logoMimeType: null, logoKey: null }; - let logoUrl: string | null = null; - if (settings.logoKey) { - try { - logoUrl = await getPresignedGetUrl(settings.logoKey); - } catch { - // If S3 URL generation fails, fall back to legacy base64 - } - } + // Return the public proxy path so browser never sees a raw S3 URL + const logoUrl = settings.logoKey ? "/api/branding/logo" : null; // Defensive: validate magic bytes to prevent MIME type confusion attacks // via the legacy base64 logo fields @@ -202,7 +213,7 @@ api.on(["POST", "PATCH", "DELETE"], "/staff/*", requireRoleOrSuperUser("manager" api.use("/admin/*", requireRoleOrSuperUser("manager")); api.use("/admin/settings/*", requireSuperUser()); api.use("/reports/*", requireRole("manager")); -api.use("/invoices/*", requireRole("manager")); +api.use("/invoices/*", requireRole("manager", "groomer")); api.use("/impersonation/*", requireRole("manager")); // Manager + Receptionist only (groomers have no access): appointment-groups, grooming-logs, waitlist diff --git a/apps/api/src/lib/s3.ts b/apps/api/src/lib/s3.ts index b0793c5..5067101 100644 --- a/apps/api/src/lib/s3.ts +++ b/apps/api/src/lib/s3.ts @@ -68,6 +68,25 @@ export async function deleteObject(key: string): Promise { ); } +/** Read an object from S3 and return its body buffer and content type. */ +export async function getObject(key: string): Promise<{ body: Buffer; contentType: string }> { + const client = getS3Client(); + const response = await client.send( + new GetObjectCommand({ + Bucket: getBucket(), + Key: key, + }) + ); + const chunks: Uint8Array[] = []; + // response.Body is a Readable stream; collect chunks into a buffer + for await (const chunk of response.Body as AsyncIterable) { + chunks.push(chunk); + } + const body = Buffer.concat(chunks); + const contentType = response.ContentType ?? "application/octet-stream"; + return { body, contentType }; +} + /** Upload an object directly to S3 (server-side only, not a pre-signed URL). */ export async function putObject( key: string, diff --git a/apps/api/src/routes/invoices.ts b/apps/api/src/routes/invoices.ts index 1527128..91ac4ee 100644 --- a/apps/api/src/routes/invoices.ts +++ b/apps/api/src/routes/invoices.ts @@ -18,6 +18,14 @@ import type { AppEnv } from "../middleware/rbac.js"; export const invoicesRouter = new Hono(); +// Convert Zod validation errors from 422 to 400 +invoicesRouter.onError((err, c) => { + if (err instanceof z.ZodError) { + return c.json({ error: "Validation failed", issues: err.issues }, 400); + } + throw err; +}); + const createInvoiceSchema = z.object({ appointmentId: z.string().uuid().optional(), clientId: z.string().uuid(), @@ -93,6 +101,8 @@ invoicesRouter.get( paymentMethod: invoices.paymentMethod, paidAt: invoices.paidAt, notes: invoices.notes, + stripePaymentIntentId: invoices.stripePaymentIntentId, + stripeRefundId: invoices.stripeRefundId, createdAt: invoices.createdAt, updatedAt: invoices.updatedAt, }) @@ -120,7 +130,17 @@ invoicesRouter.get("/:id", async (c) => { db.select().from(invoiceTipSplits).where(eq(invoiceTipSplits.invoiceId, id)), ]); - return c.json({ ...invoice, lineItems, tipSplits }); + let cardLast4: string | null = null; + let paymentStatus: string | null = null; + if (invoice.stripePaymentIntentId) { + const details = await getPaymentIntentDetails(invoice.stripePaymentIntentId); + if (details) { + cardLast4 = details.cardLast4; + paymentStatus = details.paymentStatus; + } + } + + return c.json({ ...invoice, lineItems, tipSplits, cardLast4, paymentStatus }); }); // Save tip splits for an invoice (replaces existing splits) @@ -341,30 +361,23 @@ invoicesRouter.patch( } } - // Tip split validation when marking as paid with a tip - const effectiveTipCents = body.tipCents ?? current.tipCents; - if (body.status === "paid" && effectiveTipCents > 0) { - if (body.tipSplits !== undefined) { - if (body.tipSplits.length === 0) { - return c.json({ error: "Tip splits required when tip amount is greater than zero" }, 422); - } - const totalBps = body.tipSplits.reduce((sum, s) => sum + Math.round(s.sharePct * 100), 0); - if (totalBps !== 10000) { - return c.json({ error: "Split percentages must sum to 100" }, 422); - } - } else { - const existingSplits = await db - .select({ id: invoiceTipSplits.id }) - .from(invoiceTipSplits) - .where(eq(invoiceTipSplits.invoiceId, id)); - if (existingSplits.length === 0) { - return c.json({ error: "Tip splits required when tip amount is greater than zero" }, 422); - } + const tipCents = body.tipCents ?? current.tipCents; + + // Validate tip splits when marking invoice as paid + if (body.status === "paid" && tipCents > 0 && body.tipSplits !== undefined) { + if (body.tipSplits.length === 0) { + return c.json({ error: "Tip splits are required when tip amount is greater than zero" }, 400); + } + const totalPct = body.tipSplits.reduce((sum, s) => sum + s.sharePct, 0); + if (Math.abs(totalPct - 100) > 0.01) { + return c.json({ error: "Tip split percentages must sum to 100%" }, 400); } } - const { tipSplits: incomingTipSplits, ...bodyWithoutSplits } = body; - const update: Record = { ...bodyWithoutSplits, updatedAt: new Date() }; + // Destructure tipSplits out — it belongs to a separate table, not the invoices column + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { tipSplits: _tipSplits, ...updateBody } = body as Record; + const update: Record = { ...updateBody, updatedAt: new Date() }; // Auto-set paidAt when marking as paid if (body.status === "paid" && !body.paidAt && !current.paidAt) { @@ -378,54 +391,50 @@ invoicesRouter.patch( update.totalCents = current.subtotalCents + newTaxCents + newTipCents; } - const [updated] = await db.transaction(async (tx) => { - const [upd] = await tx + // Wrap tip split persistence and invoice update in a single atomic transaction + const [updated, lineItems] = await db.transaction(async (tx) => { + if (body.status === "paid" && tipCents > 0 && body.tipSplits !== undefined) { + await tx.delete(invoiceTipSplits).where(eq(invoiceTipSplits.invoiceId, id)); + const splits = body.tipSplits; + if (splits.length > 0) { + let remaining = tipCents; + const rows = splits.map((s, i) => { + const isLast = i === splits.length - 1; + const shareCents = isLast ? remaining : Math.round((s.sharePct / 100) * tipCents); + if (!isLast) remaining -= shareCents; + return { + invoiceId: id, + staffId: s.staffId, + staffName: s.staffName, + sharePct: s.sharePct.toFixed(2), + shareCents, + }; + }); + await tx.insert(invoiceTipSplits).values(rows); + } + } + + const [updatedInvoice] = await tx .update(invoices) .set(update) .where(eq(invoices.id, id)) .returning(); - // Atomically save tip splits when marking paid with provided splits - if ( - body.status === "paid" && - effectiveTipCents > 0 && - incomingTipSplits !== undefined && - incomingTipSplits.length > 0 - ) { - await tx.delete(invoiceTipSplits).where(eq(invoiceTipSplits.invoiceId, id)); + const lineItems = await tx + .select() + .from(invoiceLineItems) + .where(eq(invoiceLineItems.invoiceId, id)); - let remaining = effectiveTipCents; - const rows = incomingTipSplits.map((s, i) => { - const isLast = i === incomingTipSplits.length - 1; - const shareCents = isLast ? remaining : Math.round((s.sharePct / 100) * effectiveTipCents); - if (!isLast) remaining -= shareCents; - return { - invoiceId: id, - staffId: s.staffId, - staffName: s.staffName, - sharePct: s.sharePct.toFixed(2), - shareCents, - }; - }); - - await tx.insert(invoiceTipSplits).values(rows); - } - - return [upd]; + return [updatedInvoice, lineItems]; }); - const lineItems = await db - .select() - .from(invoiceLineItems) - .where(eq(invoiceLineItems.invoiceId, id)); - return c.json({ ...updated, lineItems }); } ); // ─── Refund ─────────────────────────────────────────────────────────────────── -import { processRefund } from "../services/payment.js"; +import { processRefund, getPaymentIntentDetails } from "../services/payment.js"; const refundSchema = z.object({ amountCents: z.number().int().nonnegative().optional(), @@ -451,9 +460,6 @@ invoicesRouter.post( if (invoice.status !== "paid") { return c.json({ error: "Refund only allowed on paid invoices" }, 422); } - if (!invoice.stripePaymentIntentId) { - return c.json({ error: "No Stripe payment intent found for this invoice" }, 422); - } return await db.transaction(async (tx) => { if (body.idempotencyKey) { @@ -466,17 +472,100 @@ invoicesRouter.post( } } - const result = await processRefund(id, body.amountCents); - if (!result) return c.json({ error: "Refund failed" }, 500); + let refundId: string; + + if (invoice.stripePaymentIntentId) { + const result = await processRefund(id, body.amountCents); + if (!result) return c.json({ error: "Refund failed" }, 500); + refundId = result.refundId; + } else { + // Manual refund — no Stripe call needed + refundId = `manual_${id}_${Date.now()}`; + } await tx.insert(refunds).values({ invoiceId: id, - stripeRefundId: result.refundId, + stripeRefundId: refundId, idempotencyKey: body.idempotencyKey ?? null, amountCents: body.amountCents ?? null, }); - return c.json({ refundId: result.refundId }); + return c.json({ refundId }); }); } ); + +// Payment stats for admin dashboard +invoicesRouter.get("/stats/summary", async (c) => { + try { + const db = getDb(); + const now = new Date(); + const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1); + + const [revenueResult] = await db + .select({ total: sql`coalesce(sum(total_cents), 0)` }) + .from(invoices) + .where(and(eq(invoices.status, "paid"), sql`${invoices.paidAt} >= ${startOfMonth}`)); + + const [outstandingResult] = await db + .select({ total: sql`coalesce(sum(total_cents), 0)` }) + .from(invoices) + .where(eq(invoices.status, "pending")); + + const [refundsResult] = await db + .select({ total: sql`coalesce(sum(amount_cents), 0)` }) + .from(refunds) + .where(sql`${refunds.createdAt} >= ${startOfMonth}`); + + const methodBreakdown = await db + .select({ + method: invoices.paymentMethod, + total: sql`count(*)`, + }) + .from(invoices) + .where(and(eq(invoices.status, "paid"), sql`${invoices.paidAt} >= ${startOfMonth}`)) + .groupBy(invoices.paymentMethod); + + return c.json({ + revenueThisMonth: revenueResult?.total ?? 0, + outstanding: outstandingResult?.total ?? 0, + refundsThisMonth: refundsResult?.total ?? 0, + methodBreakdown, + }); + } catch (err) { + console.error("stats/summary error:", err); + return c.json({ + revenueThisMonth: 0, + outstanding: 0, + refundsThisMonth: 0, + methodBreakdown: [], + }); + } +}); + +// Get Stripe payment details for an invoice (card last4, payment status, refund status) +invoicesRouter.get("/:id/stripe-details", async (c) => { + const db = getDb(); + const id = c.req.param("id"); + + const [invoice] = await db.select().from(invoices).where(eq(invoices.id, id)); + if (!invoice) return c.json({ error: "Not found" }, 404); + + let cardLast4: string | null = null; + let paymentStatus: string | null = null; + + if (invoice.stripePaymentIntentId) { + const details = await getPaymentIntentDetails(invoice.stripePaymentIntentId); + if (details) { + cardLast4 = details.cardLast4; + paymentStatus = details.paymentStatus; + } + } + + return c.json({ + stripePaymentIntentId: invoice.stripePaymentIntentId, + stripeRefundId: invoice.stripeRefundId, + cardLast4, + paymentStatus, + }); +}); diff --git a/apps/api/src/routes/portal.ts b/apps/api/src/routes/portal.ts index dc556c8..a4c2b87 100644 --- a/apps/api/src/routes/portal.ts +++ b/apps/api/src/routes/portal.ts @@ -102,7 +102,6 @@ portalRouter.get("/appointments", async (c) => { const db = getDb(); const clientId = c.get("portalClientId"); - const now = new Date(); const allAppts = await db .select({ id: appointments.id, @@ -142,10 +141,7 @@ portalRouter.get("/appointments", async (c) => { staff: a.staffId ? { id: staffMap[a.staffId]?.id, name: staffMap[a.staffId]?.name } : null, })); - const upcoming = appts.filter(a => a.startTime > now && a.status !== "cancelled"); - const past = appts.filter(a => a.startTime <= now || a.status === "cancelled"); - - return c.json({ upcoming, past }); + return c.json({ appointments: appts }); }); portalRouter.get("/pets", async (c) => { @@ -153,7 +149,7 @@ portalRouter.get("/pets", async (c) => { const clientId = c.get("portalClientId"); const clientPets = await db.select().from(pets).where(eq(pets.clientId, clientId)); - return c.json(clientPets.map(p => ({ id: p.id, name: p.name, breed: p.breed, weightKg: p.weightKg, dateOfBirth: p.dateOfBirth, photoKey: p.photoKey, groomingNotes: p.groomingNotes }))); + return c.json(clientPets.map(p => ({ id: p.id, name: p.name, breed: p.breed, weight: p.weightKg, birthDate: p.dateOfBirth, photoUrl: p.photoKey, notes: p.groomingNotes }))); }); portalRouter.get("/invoices", async (c) => { diff --git a/apps/api/src/routes/settings.ts b/apps/api/src/routes/settings.ts index fe06b80..3b931db 100644 --- a/apps/api/src/routes/settings.ts +++ b/apps/api/src/routes/settings.ts @@ -2,7 +2,7 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; import { z } from "zod/v3"; import { eq, getDb, businessSettings } from "@groombook/db"; -import { getPresignedUploadUrl, getPresignedGetUrl, deleteObject, putObject } from "../lib/s3.js"; +import { getPresignedUploadUrl, deleteObject, putObject, getObject } from "../lib/s3.js"; import { requireSuperUser } from "../middleware/rbac.js"; export const settingsRouter = new Hono(); @@ -215,7 +215,8 @@ settingsRouter.post( /** * GET /api/admin/settings/logo - * Returns a presigned GET URL for the logo. + * Proxies the logo from S3 so the browser never sees an S3 URL. + * Returns the image bytes with proper Content-Type. */ settingsRouter.get("/logo", async (c) => { const db = getDb(); @@ -224,8 +225,14 @@ settingsRouter.get("/logo", async (c) => { if (!row) return c.json({ error: "Settings not found" }, 404); if (!row.logoKey) return c.json({ error: "No logo on file" }, 404); - const url = await getPresignedGetUrl(row.logoKey); - return c.json({ url, logoKey: row.logoKey }); + const { body, contentType } = await getObject(row.logoKey); + return new Response(Buffer.from(body), { + status: 200, + headers: { + "Content-Type": contentType, + "Cache-Control": "public, max-age=86400", + }, + }); }); /** diff --git a/apps/api/src/routes/setup.ts b/apps/api/src/routes/setup.ts index a84e61d..495fd66 100644 --- a/apps/api/src/routes/setup.ts +++ b/apps/api/src/routes/setup.ts @@ -9,8 +9,8 @@ const RATE_LIMIT_MAX = 10; const rateLimitMap = new Map(); function rateLimitByIp(ip: string): { allowed: boolean; remaining: number } { - const now = Date.now(); const entry = rateLimitMap.get(ip); + const now = Date.now(); if (!entry || now > entry.resetAt) { rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS }); return { allowed: true, remaining: RATE_LIMIT_MAX - 1 }; diff --git a/apps/api/src/services/payment.ts b/apps/api/src/services/payment.ts index d09d1db..eb97597 100644 --- a/apps/api/src/services/payment.ts +++ b/apps/api/src/services/payment.ts @@ -162,3 +162,19 @@ export async function createSetupIntent(customerId: string): Promise<{ clientSec return { clientSecret: setupIntent.client_secret! }; } + +export async function getPaymentIntentDetails( + paymentIntentId: string +): Promise<{ cardLast4: string | null; paymentStatus: string | null } | null> { + const stripe = getStripeClient(); + if (!stripe) return null; + + const pi = await stripe.paymentIntents.retrieve(paymentIntentId, { expand: ["payment_method"] }); + const cardLast4 = pi.payment_method + ? (pi.payment_method as Stripe.PaymentMethod).card?.last4 ?? null + : null; + return { + cardLast4, + paymentStatus: pi.status ?? null, + }; +} diff --git a/apps/e2e/tests/navigation.spec.ts b/apps/e2e/tests/navigation.spec.ts index 29a7060..dc9b4aa 100644 --- a/apps/e2e/tests/navigation.spec.ts +++ b/apps/e2e/tests/navigation.spec.ts @@ -44,6 +44,16 @@ test.beforeEach(async ({ page }) => { json: { newClients: [], activeInPeriodCount: 0, churnRisk: [], churnRiskTotal: 0 }, }); } + if (url.includes("/api/invoices/stats/summary")) { + return route.fulfill({ + json: { + revenueThisMonth: 0, + outstanding: 0, + refundsThisMonth: 0, + methodBreakdown: [], + }, + }); + } if (url.includes("/api/invoices")) { return route.fulfill({ json: { data: [], total: 0 } }); } diff --git a/apps/e2e/tests/portal-data.spec.ts b/apps/e2e/tests/portal-data.spec.ts index 5e9b2ed..26ce82c 100644 --- a/apps/e2e/tests/portal-data.spec.ts +++ b/apps/e2e/tests/portal-data.spec.ts @@ -72,9 +72,15 @@ test.describe("Portal Data Integrity", () => { }); test("billing section renders without JS errors", async ({ page }) => { - // Mock billing endpoint - await page.route("**/api/billing**", (route) => - route.fulfill({ json: { invoices: [], balanceCents: 0 } }) + // Mock portal billing endpoints + await page.route("**/api/portal/config**", (route) => + route.fulfill({ json: { stripePublishableKey: "" } }) + ); + await page.route("**/api/portal/invoices**", (route) => + route.fulfill({ json: [] }) + ); + await page.route("**/api/portal/payment-methods**", (route) => + route.fulfill({ json: [] }) ); const consoleErrors: string[] = []; diff --git a/apps/web/src/pages/Appointments.tsx b/apps/web/src/pages/Appointments.tsx index 1dd7046..b64186d 100644 --- a/apps/web/src/pages/Appointments.tsx +++ b/apps/web/src/pages/Appointments.tsx @@ -112,9 +112,17 @@ export function AppointmentsPage() { const [viewMode, setViewMode] = useState<"status" | "groomer">("status"); // null key = unassigned; staffId string = that groomer; undefined set = all visible const [hiddenGroomers, setHiddenGroomers] = useState>(new Set()); + const [paymentStats, setPaymentStats] = useState<{ revenueThisMonth: number; outstanding: number; refundsThisMonth: number; methodBreakdown: { method: string | null; total: number }[] } | null>(null); const weekEnd = addDays(weekStart, 6); + useEffect(() => { + fetch("/api/invoices/stats/summary") + .then((r) => r.ok ? r.json() : null) + .then((data) => { if (data) setPaymentStats(data); }) + .catch(() => {}); + }, []); + const loadAppointments = useCallback(() => { const from = weekStart.toISOString(); const to = addDays(weekStart, 7).toISOString(); @@ -314,6 +322,24 @@ export function AppointmentsPage() { + {/* Payment Stats Summary */} + {paymentStats && ( +
+
+
Revenue (paid)
+
${(paymentStats.revenueThisMonth / 100).toFixed(2)}
+
+
+
Outstanding
+
${(paymentStats.outstanding / 100).toFixed(2)}
+
+
+
Refunds (this mo.)
+
${(paymentStats.refundsThisMonth / 100).toFixed(2)}
+
+
+ )} + {/* ── View Mode + Groomer Filters ── */}
Color by: diff --git a/apps/web/src/pages/Clients.tsx b/apps/web/src/pages/Clients.tsx index 8f89d52..af4b47b 100644 --- a/apps/web/src/pages/Clients.tsx +++ b/apps/web/src/pages/Clients.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState, useCallback, useRef } from "react"; +import { useEffect, useState, useCallback, useRef, useId } from "react"; import { useSearchParams } from "react-router-dom"; import type { Client, GroomingVisitLog, Pet } from "@groombook/types"; import { PetPhotoDisplay } from "../components/PetPhotoDisplay.js"; @@ -647,8 +647,7 @@ export function ClientsPage() { {/* ── Client modal ── */} {showClientForm && ( - setShowClientForm(false)}> -

{editingClient ? "Edit Client" : "New Client"}

+ setShowClientForm(false)}>
setClientForm((f) => ({ ...f, name: e.target.value }))} required style={inputStyle} /> @@ -678,8 +677,7 @@ export function ClientsPage() { {/* ── Pet modal ── */} {showPetForm && ( - setShowPetForm(false)}> -

{editingPet ? "Edit Pet" : "Add Pet"}

+ setShowPetForm(false)}> setPetForm((f) => ({ ...f, name: e.target.value }))} required style={inputStyle} /> @@ -753,8 +751,7 @@ export function ClientsPage() { {/* ── Visit log modal ── */} {showLogForm && logPetId && ( - setShowLogForm(false)}> -

Log Grooming Visit

+ setShowLogForm(false)}> {logsLoading[logPetId] &&

Loading history…

} {visitLogs[logPetId] && visitLogs[logPetId].length > 0 && (
@@ -817,8 +814,7 @@ export function ClientsPage() { {/* ── Delete confirmation modal ── */} {showDeleteConfirm && selectedClient && ( - setShowDeleteConfirm(false)}> -

Permanently Delete Client

+ setShowDeleteConfirm(false)}>

This will permanently delete {selectedClient.name} and all their pets. This action cannot be undone.

@@ -856,7 +852,8 @@ export function ClientsPage() { // ─── Shared UI ─────────────────────────────────────────────────────────────── -function Modal({ children, onClose }: { children: React.ReactNode; onClose: () => void }) { +function Modal({ children, onClose, title, titleStyle }: { children: React.ReactNode; onClose: () => void; title: string; titleStyle?: React.CSSProperties }) { + const titleId = useId(); const modalRef = useRef(null); useEffect(() => { @@ -898,15 +895,17 @@ function Modal({ children, onClose }: { children: React.ReactNode; onClose: () = return (
{ if (e.target === e.currentTarget) onClose(); }} >
+

{title}

{children}
diff --git a/apps/web/src/pages/Invoices.tsx b/apps/web/src/pages/Invoices.tsx index 04fc7ea..0eceb4c 100644 --- a/apps/web/src/pages/Invoices.tsx +++ b/apps/web/src/pages/Invoices.tsx @@ -173,6 +173,21 @@ function InvoiceDetailModal({ const [error, setError] = useState(null); const [tipStr, setTipStr] = useState((invoice.tipCents / 100).toFixed(2)); const [paymentMethod, setPaymentMethod] = useState(invoice.paymentMethod ?? "cash"); +const [showRefundDialog, setShowRefundDialog] = useState(false); + const [refundType, setRefundType] = useState<"full" | "partial">("full"); + const [refundAmount, setRefundAmount] = useState(""); + const [refundError, setRefundError] = useState(null); + const [refunding, setRefunding] = useState(false); + + // Fetch current staff role to determine manager access + const [staffMe, setStaffMe] = useState<{ role: string; isSuperUser: boolean } | null>(null); + useEffect(() => { + fetch("/api/staff/me") + .then((r) => r.json()) + .then((d) => setStaffMe(d)) + .catch(() => setStaffMe(null)); + }, []); + const isManager = staffMe && (staffMe.role === "manager" || staffMe.isSuperUser); // Tip split state: array of {staffId, staffName, pct} const linkedAppt = invoice.appointmentId @@ -335,6 +350,19 @@ function InvoiceDetailModal({ /> {invoice.paidAt && } {invoice.paymentMethod && } + {invoice.stripePaymentIntentId && ( + <> + {invoice.cardLast4 && ( + + )} + {invoice.paymentStatus && ( + + )} + {invoice.stripeRefundId && ( + + )} + + )}
{/* ── Tip Distribution ── */} @@ -452,11 +480,92 @@ function InvoiceDetailModal({
)} {(invoice.status === "paid" || invoice.status === "void") && ( -
- +
+ {invoice.stripeRefundId && ( +
+ Refunded +
+ )} +
+ {invoice.status === "paid" && !invoice.stripeRefundId && isManager && ( + + )} + +
)} - + + {showRefundDialog && ( +
+

Process Refund

+
+ + +
+ {refundType === "partial" && ( +
+ setRefundAmount(e.target.value)} + style={{ ...inputStyle, width: 100 }} + /> +
+ )} + {refundError &&

{refundError}

} +
+ + +
+
+ )} + ); } @@ -497,9 +606,17 @@ export function InvoicesPage() { const [createLoading, setCreateLoading] = useState(false); const [detailData, setDetailData] = useState<{ staff: Staff[]; appointments: Appointment[] } | null>(null); const [detailLoading, setDetailLoading] = useState(false); + const [paymentStats, setPaymentStats] = useState<{ revenueThisMonth: number; outstanding: number; refundsThisMonth: number; methodBreakdown: { method: string | null; total: number }[] } | null>(null); const LIMIT = 50; + useEffect(() => { + fetch("/api/invoices/stats/summary") + .then((r) => r.ok ? r.json() : null) + .then((data) => { if (data) setPaymentStats(data); }) + .catch(() => {}); + }, []); + async function loadInvoices(newOffset: number) { const params = new URLSearchParams({ limit: String(LIMIT), offset: String(newOffset) }); if (statusFilter) params.set("status", statusFilter); @@ -578,6 +695,34 @@ export function InvoicesPage() {
+ {/* Payment Stats Summary */} + {paymentStats && ( +
+
+
Revenue (paid)
+
{fmtMoney(paymentStats.revenueThisMonth)}
+
+
+
Outstanding
+
{fmtMoney(paymentStats.outstanding)}
+
+
+
Refunds (this mo.)
+
{fmtMoney(paymentStats.refundsThisMonth)}
+
+ {paymentStats.methodBreakdown.length > 0 && ( +
+
By method
+
+ {paymentStats.methodBreakdown.map((b) => ( +
{b.method ?? "other"}: {b.total}
+ ))} +
+
+ )} +
+ )} + {invoiceList.length === 0 ? (

No invoices yet. Create one from a completed appointment. diff --git a/apps/web/src/pages/Settings.tsx b/apps/web/src/pages/Settings.tsx index c1f01ce..c22e1f2 100644 --- a/apps/web/src/pages/Settings.tsx +++ b/apps/web/src/pages/Settings.tsx @@ -89,24 +89,14 @@ export function SettingsPage() { fetch("/api/admin/settings") .then((r) => r.json()) .then(async (data) => { - let logoUrl: string | null = null; - if (data.logoKey) { - try { - const logoRes = await fetch("/api/admin/settings/logo"); - if (logoRes.ok) { - const logoData = await logoRes.json(); - logoUrl = logoData.url; - } - } catch { - // ignore - } - } + // The logo is now proxied through the API server so the browser + // never receives an S3 URL — use the proxy path directly as the src. setForm({ businessName: data.businessName ?? "GroomBook", primaryColor: data.primaryColor ?? "#4f8a6f", accentColor: data.accentColor ?? "#8b7355", logoKey: data.logoKey ?? null, - logoUrl, + logoUrl: data.logoKey ? "/api/admin/settings/logo" : null, logoBase64: data.logoBase64 ?? null, logoMimeType: data.logoMimeType ?? null, }); @@ -172,15 +162,7 @@ export function SettingsPage() { throw new Error(err?.error ?? "Failed to upload logo"); } const { logoKey } = await uploadRes.json(); - - // Fetch the presigned GET URL for display - const logoRes = await fetch("/api/admin/settings/logo"); - if (logoRes.ok) { - const logoData = await logoRes.json(); - setForm((f) => ({ ...f, logoKey, logoUrl: logoData.url, logoBase64: null, logoMimeType: null })); - } else { - setForm((f) => ({ ...f, logoKey, logoUrl: null, logoBase64: null, logoMimeType: null })); - } + setForm((f) => ({ ...f, logoKey, logoUrl: `/api/admin/settings/logo?t=${Date.now()}`, logoBase64: null, logoMimeType: null })); setMessage({ type: "success", text: "Logo uploaded." }); refresh(); } catch (err: unknown) { diff --git a/apps/web/src/portal/CustomerPortal.tsx b/apps/web/src/portal/CustomerPortal.tsx index a542cc0..80be6cc 100644 --- a/apps/web/src/portal/CustomerPortal.tsx +++ b/apps/web/src/portal/CustomerPortal.tsx @@ -326,7 +326,7 @@ export function CustomerPortal() { )} {/* Main Content */} -

+

diff --git a/apps/web/src/portal/sections/BillingPayments.tsx b/apps/web/src/portal/sections/BillingPayments.tsx index e4d2902..89e3877 100644 --- a/apps/web/src/portal/sections/BillingPayments.tsx +++ b/apps/web/src/portal/sections/BillingPayments.tsx @@ -130,7 +130,7 @@ function BillingPaymentsInner({ sessionId, readOnly }: BillingPaymentsProps) {

)} -
+
{([ { id: "invoices" as const, label: "Invoices", icon: DollarSign }, { id: "payment" as const, label: "Payment Methods", icon: CreditCard }, diff --git a/apps/web/src/portal/sections/PetProfiles.tsx b/apps/web/src/portal/sections/PetProfiles.tsx index f657e6a..e9fb07b 100644 --- a/apps/web/src/portal/sections/PetProfiles.tsx +++ b/apps/web/src/portal/sections/PetProfiles.tsx @@ -27,8 +27,7 @@ interface Appointment { } interface AppointmentsResponse { - upcoming: Appointment[]; - past: Appointment[]; + appointments: Appointment[]; } interface Props { @@ -46,7 +45,7 @@ function buildHeaders(sessionId: string | null): Record { export function PetProfiles({ sessionId, readOnly }: Props) { const [pets, setPets] = useState([]); - const [appointments, setAppointments] = useState({ upcoming: [], past: [] }); + const [appointments, setAppointments] = useState({ appointments: [] }); const [selectedPetId, setSelectedPetId] = useState(""); const [activeTab, setActiveTab] = useState<"info" | "medical" | "grooming" | "history">("info"); const [editingPetId, setEditingPetId] = useState(null); @@ -90,7 +89,7 @@ export function PetProfiles({ sessionId, readOnly }: Props) { }, [sessionId]); const selectedPet = pets.find(p => p.id === selectedPetId) ?? null; - const petHistory = appointments.past.filter(a => a.pet?.id === selectedPetId); + const petHistory = appointments.appointments.filter(a => a.pet?.id === selectedPetId && new Date(a.startTime) <= new Date()); const editingPet = editingPetId ? pets.find(p => p.id === editingPetId) ?? null : null; function handlePetSave(updatedPet: Pet) { diff --git a/charts/groombook/templates/_helpers.tpl b/charts/groombook/templates/_helpers.tpl index 9c97648..93f19ad 100644 --- a/charts/groombook/templates/_helpers.tpl +++ b/charts/groombook/templates/_helpers.tpl @@ -119,3 +119,10 @@ uri database-url {{- end -}} {{- end }} + +{{/* +Auth secret name — always use groombook-auth (sealed secret name) +*/}} +{{- define "groombook.authSecretName" -}} +{{- printf "%s" "groombook-auth" }} +{{- end }} diff --git a/charts/groombook/templates/api-deployment.yaml b/charts/groombook/templates/api-deployment.yaml index aaee7b0..6283210 100644 --- a/charts/groombook/templates/api-deployment.yaml +++ b/charts/groombook/templates/api-deployment.yaml @@ -50,6 +50,27 @@ spec: - name: OIDC_AUDIENCE value: {{ .Values.api.env.oidcAudience | quote }} {{- end }} + {{- if .Values.api.env.internalBaseUrl }} + - name: OIDC_INTERNAL_BASE + value: {{ .Values.api.env.internalBaseUrl | quote }} + {{- end }} + - name: BETTER_AUTH_URL + value: {{ .Values.api.env.betterAuthUrl | quote }} + - name: OIDC_CLIENT_ID + valueFrom: + secretKeyRef: + name: {{ include "groombook.authSecretName" . }} + key: OIDC_CLIENT_ID + - name: OIDC_CLIENT_SECRET + valueFrom: + secretKeyRef: + name: {{ include "groombook.authSecretName" . }} + key: OIDC_CLIENT_SECRET + - name: BETTER_AUTH_SECRET + valueFrom: + secretKeyRef: + name: {{ include "groombook.authSecretName" . }} + key: BETTER_AUTH_SECRET - name: DATABASE_URL valueFrom: secretKeyRef: diff --git a/charts/groombook/values.yaml b/charts/groombook/values.yaml index 5f888a5..0e85682 100644 --- a/charts/groombook/values.yaml +++ b/charts/groombook/values.yaml @@ -18,6 +18,8 @@ api: corsOrigin: "" oidcIssuer: "" oidcAudience: groombook + betterAuthUrl: "" + internalBaseUrl: "" port: "3000" service: type: ClusterIP diff --git a/packages/db/src/seed.ts b/packages/db/src/seed.ts index dca21d4..4563ce7 100644 --- a/packages/db/src/seed.ts +++ b/packages/db/src/seed.ts @@ -978,6 +978,7 @@ async function seed() { const invoiceStatus = rand() < 0.95 ? "paid" as const : "pending" as const; const paidAt = invoiceStatus === "paid" ? new Date(endTime.getTime() + randInt(5, 30) * 60 * 1000) : null; + const stripePaymentIntentId = invoiceStatus === "paid" && rand() < 0.2 ? `pi_test_${uuid().replace(/-/g, "").slice(0, 24)}` : null; invoiceBatch.push({ id: invoiceId, appointmentId: apptId, @@ -989,6 +990,7 @@ async function seed() { status: invoiceStatus, paymentMethod: invoiceStatus === "paid" ? pick(["cash", "card", "card", "card", "check"]) as "cash" | "card" | "check" : null, paidAt, + stripePaymentIntentId, notes: rand() < 0.05 ? "Added extra service at checkout" : null, }); @@ -1092,13 +1094,14 @@ async function seed() { const taxCents = Math.round(effectivePrice * 0.08); const totalCents = effectivePrice + taxCents + tipCents; const paidAt = new Date(endTime.getTime() + randInt(5, 30) * 60 * 1000); + const stripePaymentIntentId = rand() < 0.2 ? `pi_test_${uuid().replace(/-/g, "").slice(0, 24)}` : null; invoiceBatch.push({ id: invoiceId, appointmentId: apptId, clientId, subtotalCents: effectivePrice, taxCents, tipCents, totalCents, status: "paid" as const, paymentMethod: pick(["cash", "card", "card", "card", "check"]) as "cash" | "card" | "check", - paidAt, notes: null, + paidAt, stripePaymentIntentId, notes: null, }); lineItemBatch.push({ id: uuid(), invoiceId, description: svc.name, quantity: 1, diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 753b1cf..90ef116 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -152,10 +152,16 @@ export interface Invoice { status: InvoiceStatus; paymentMethod: PaymentMethod | null; paidAt: string | null; + stripePaymentIntentId: string | null; + stripeRefundId: string | null; + paymentFailureReason: string | null; notes: string | null; createdAt: string; updatedAt: string; lineItems?: InvoiceLineItem[]; + // Transient fields populated from Stripe API (not stored in DB) + cardLast4?: string | null; + paymentStatus?: string | null; tipSplits?: InvoiceTipSplit[]; }