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..4d83402 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(), @@ -341,30 +349,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 +379,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(), @@ -480,3 +477,68 @@ invoicesRouter.post( }); } ); + +// Payment stats for admin dashboard +invoicesRouter.get("/stats/summary", async (c) => { + 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, + }); +}); + +// 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/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..76dcbfd 100644 --- a/apps/web/src/pages/Invoices.tsx +++ b/apps/web/src/pages/Invoices.tsx @@ -173,6 +173,22 @@ 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 [partialAmount, setPartialAmount] = useState(""); + const [stripeDetails, setStripeDetails] = useState<{ cardLast4: string | null; paymentStatus: string | null; stripeRefundId: string | null } | null>(null); + + // Fetch Stripe details when modal opens for paid invoices with a payment intent + useEffect(() => { + if (invoice.status === "paid" && invoice.stripePaymentIntentId) { + fetch(`/api/invoices/${invoice.id}/stripe-details`) + .then((r) => r.ok ? r.json() : null) + .then((data) => { if (data) setStripeDetails(data); }) + .catch(() => {}); + } else { + setStripeDetails(null); + } + }, [invoice.id, invoice.status, invoice.stripePaymentIntentId]); // Tip split state: array of {staffId, staffName, pct} const linkedAppt = invoice.appointmentId @@ -276,6 +292,35 @@ function InvoiceDetailModal({ } } + async function issueRefund() { + const amountCents = refundType === "partial" + ? Math.round(parseFloat(partialAmount) * 100) + : undefined; + if (refundType === "partial" && (!amountCents || amountCents <= 0)) { + setError("Enter a valid refund amount"); + return; + } + setSaving(true); + setError(null); + try { + const res = await fetch(`/api/invoices/${invoice.id}/refund`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(amountCents ? { amountCents } : {}), + }); + if (!res.ok) { + const err = (await res.json()) as { error?: string }; + throw new Error(err.error ?? `HTTP ${res.status}`); + } + setShowRefundDialog(false); + onUpdated(); + } catch (e: unknown) { + setError(e instanceof Error ? e.message : "Failed to issue refund"); + } finally { + setSaving(false); + } + } + if (loading) return

Loading…

; const tipCentsCalc = Math.round(parseFloat(tipStr) * 100) || 0; @@ -335,6 +380,19 @@ function InvoiceDetailModal({ /> {invoice.paidAt && } {invoice.paymentMethod && } + {stripeDetails && ( + <> + {stripeDetails.cardLast4 && ( + + )} + {stripeDetails.paymentStatus && ( + + )} + {stripeDetails.stripeRefundId && ( + + )} + + )}
{/* ── Tip Distribution ── */} @@ -452,10 +510,76 @@ function InvoiceDetailModal({ )} {(invoice.status === "paid" || invoice.status === "void") && ( -
+
+ {invoice.status === "paid" && invoice.stripePaymentIntentId && ( + + )}
)} + + {/* Refund Dialog */} + {showRefundDialog && ( + setShowRefundDialog(false)}> +

Issue Refund

+

+ Invoice total: {fmtMoney(invoice.totalCents)} +

+
+ + +
+ {refundType === "partial" && ( +
+ setPartialAmount(e.target.value)} + style={{ ...inputStyle, width: 120 }} + /> +
+ )} + {error &&

{error}

} +
+ + +
+
+ )} ); } @@ -497,9 +621,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 +710,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/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/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[]; }