Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9f49255253 |
-13
@@ -8,16 +8,3 @@ dist/
|
|||||||
.turbo/
|
.turbo/
|
||||||
coverage/
|
coverage/
|
||||||
minimax-output/
|
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/
|
|
||||||
|
|||||||
+10
-21
@@ -19,7 +19,7 @@ import { impersonationRouter } from "./routes/impersonation.js";
|
|||||||
import { settingsRouter } from "./routes/settings.js";
|
import { settingsRouter } from "./routes/settings.js";
|
||||||
import { authProviderRouter } from "./routes/authProvider.js";
|
import { authProviderRouter } from "./routes/authProvider.js";
|
||||||
import { searchRouter } from "./routes/search.js";
|
import { searchRouter } from "./routes/search.js";
|
||||||
import { getObject } from "./lib/s3.js";
|
import { getPresignedGetUrl } from "./lib/s3.js";
|
||||||
import { calendarRouter } from "./routes/calendar.js";
|
import { calendarRouter } from "./routes/calendar.js";
|
||||||
import { setupRouter } from "./routes/setup.js";
|
import { setupRouter } from "./routes/setup.js";
|
||||||
import { getDb, businessSettings, eq, staff } from "@groombook/db";
|
import { getDb, businessSettings, eq, staff } from "@groombook/db";
|
||||||
@@ -126,31 +126,20 @@ 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
|
// Public branding endpoint — no auth required, returns business name/colors/logo
|
||||||
app.get("/api/branding", async (c) => {
|
app.get("/api/branding", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const [row] = await db.select().from(businessSettings).limit(1);
|
const [row] = await db.select().from(businessSettings).limit(1);
|
||||||
const settings = row ?? { businessName: "GroomBook", primaryColor: "#4f8a6f", accentColor: "#8b7355", logoBase64: null, logoMimeType: null, logoKey: null };
|
const settings = row ?? { businessName: "GroomBook", primaryColor: "#4f8a6f", accentColor: "#8b7355", logoBase64: null, logoMimeType: null, logoKey: null };
|
||||||
|
|
||||||
// Return the public proxy path so browser never sees a raw S3 URL
|
let logoUrl: string | null = null;
|
||||||
const logoUrl = settings.logoKey ? "/api/branding/logo" : null;
|
if (settings.logoKey) {
|
||||||
|
try {
|
||||||
|
logoUrl = await getPresignedGetUrl(settings.logoKey);
|
||||||
|
} catch {
|
||||||
|
// If S3 URL generation fails, fall back to legacy base64
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Defensive: validate magic bytes to prevent MIME type confusion attacks
|
// Defensive: validate magic bytes to prevent MIME type confusion attacks
|
||||||
// via the legacy base64 logo fields
|
// via the legacy base64 logo fields
|
||||||
@@ -213,7 +202,7 @@ api.on(["POST", "PATCH", "DELETE"], "/staff/*", requireRoleOrSuperUser("manager"
|
|||||||
api.use("/admin/*", requireRoleOrSuperUser("manager"));
|
api.use("/admin/*", requireRoleOrSuperUser("manager"));
|
||||||
api.use("/admin/settings/*", requireSuperUser());
|
api.use("/admin/settings/*", requireSuperUser());
|
||||||
api.use("/reports/*", requireRole("manager"));
|
api.use("/reports/*", requireRole("manager"));
|
||||||
api.use("/invoices/*", requireRole("manager", "groomer"));
|
api.use("/invoices/*", requireRole("manager"));
|
||||||
api.use("/impersonation/*", requireRole("manager"));
|
api.use("/impersonation/*", requireRole("manager"));
|
||||||
|
|
||||||
// Manager + Receptionist only (groomers have no access): appointment-groups, grooming-logs, waitlist
|
// Manager + Receptionist only (groomers have no access): appointment-groups, grooming-logs, waitlist
|
||||||
|
|||||||
@@ -68,25 +68,6 @@ export async function deleteObject(key: string): Promise<void> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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<Uint8Array>) {
|
|
||||||
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). */
|
/** Upload an object directly to S3 (server-side only, not a pre-signed URL). */
|
||||||
export async function putObject(
|
export async function putObject(
|
||||||
key: string,
|
key: string,
|
||||||
|
|||||||
+55
-117
@@ -18,14 +18,6 @@ import type { AppEnv } from "../middleware/rbac.js";
|
|||||||
|
|
||||||
export const invoicesRouter = new Hono<AppEnv>();
|
export const invoicesRouter = new Hono<AppEnv>();
|
||||||
|
|
||||||
// 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({
|
const createInvoiceSchema = z.object({
|
||||||
appointmentId: z.string().uuid().optional(),
|
appointmentId: z.string().uuid().optional(),
|
||||||
clientId: z.string().uuid(),
|
clientId: z.string().uuid(),
|
||||||
@@ -349,23 +341,30 @@ invoicesRouter.patch(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const tipCents = body.tipCents ?? current.tipCents;
|
// Tip split validation when marking as paid with a tip
|
||||||
|
const effectiveTipCents = body.tipCents ?? current.tipCents;
|
||||||
// Validate tip splits when marking invoice as paid
|
if (body.status === "paid" && effectiveTipCents > 0) {
|
||||||
if (body.status === "paid" && tipCents > 0 && body.tipSplits !== undefined) {
|
if (body.tipSplits !== undefined) {
|
||||||
if (body.tipSplits.length === 0) {
|
if (body.tipSplits.length === 0) {
|
||||||
return c.json({ error: "Tip splits are required when tip amount is greater than zero" }, 400);
|
return c.json({ error: "Tip splits required when tip amount is greater than zero" }, 422);
|
||||||
}
|
}
|
||||||
const totalPct = body.tipSplits.reduce((sum, s) => sum + s.sharePct, 0);
|
const totalBps = body.tipSplits.reduce((sum, s) => sum + Math.round(s.sharePct * 100), 0);
|
||||||
if (Math.abs(totalPct - 100) > 0.01) {
|
if (totalBps !== 10000) {
|
||||||
return c.json({ error: "Tip split percentages must sum to 100%" }, 400);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destructure tipSplits out — it belongs to a separate table, not the invoices column
|
const { tipSplits: incomingTipSplits, ...bodyWithoutSplits } = body;
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
const update: Record<string, unknown> = { ...bodyWithoutSplits, updatedAt: new Date() };
|
||||||
const { tipSplits: _tipSplits, ...updateBody } = body as Record<string, unknown>;
|
|
||||||
const update: Record<string, unknown> = { ...updateBody, updatedAt: new Date() };
|
|
||||||
|
|
||||||
// Auto-set paidAt when marking as paid
|
// Auto-set paidAt when marking as paid
|
||||||
if (body.status === "paid" && !body.paidAt && !current.paidAt) {
|
if (body.status === "paid" && !body.paidAt && !current.paidAt) {
|
||||||
@@ -379,50 +378,54 @@ invoicesRouter.patch(
|
|||||||
update.totalCents = current.subtotalCents + newTaxCents + newTipCents;
|
update.totalCents = current.subtotalCents + newTaxCents + newTipCents;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wrap tip split persistence and invoice update in a single atomic transaction
|
const [updated] = await db.transaction(async (tx) => {
|
||||||
const [updated, lineItems] = await db.transaction(async (tx) => {
|
const [upd] = await 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)
|
.update(invoices)
|
||||||
.set(update)
|
.set(update)
|
||||||
.where(eq(invoices.id, id))
|
.where(eq(invoices.id, id))
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
const lineItems = await tx
|
// Atomically save tip splits when marking paid with provided splits
|
||||||
.select()
|
if (
|
||||||
.from(invoiceLineItems)
|
body.status === "paid" &&
|
||||||
.where(eq(invoiceLineItems.invoiceId, id));
|
effectiveTipCents > 0 &&
|
||||||
|
incomingTipSplits !== undefined &&
|
||||||
|
incomingTipSplits.length > 0
|
||||||
|
) {
|
||||||
|
await tx.delete(invoiceTipSplits).where(eq(invoiceTipSplits.invoiceId, id));
|
||||||
|
|
||||||
return [updatedInvoice, lineItems];
|
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];
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const lineItems = await db
|
||||||
|
.select()
|
||||||
|
.from(invoiceLineItems)
|
||||||
|
.where(eq(invoiceLineItems.invoiceId, id));
|
||||||
|
|
||||||
return c.json({ ...updated, lineItems });
|
return c.json({ ...updated, lineItems });
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// ─── Refund ───────────────────────────────────────────────────────────────────
|
// ─── Refund ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
import { processRefund, getPaymentIntentDetails } from "../services/payment.js";
|
import { processRefund } from "../services/payment.js";
|
||||||
|
|
||||||
const refundSchema = z.object({
|
const refundSchema = z.object({
|
||||||
amountCents: z.number().int().nonnegative().optional(),
|
amountCents: z.number().int().nonnegative().optional(),
|
||||||
@@ -477,68 +480,3 @@ 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<number>`coalesce(sum(total_cents), 0)` })
|
|
||||||
.from(invoices)
|
|
||||||
.where(and(eq(invoices.status, "paid"), sql`${invoices.paidAt} >= ${startOfMonth}`));
|
|
||||||
|
|
||||||
const [outstandingResult] = await db
|
|
||||||
.select({ total: sql<number>`coalesce(sum(total_cents), 0)` })
|
|
||||||
.from(invoices)
|
|
||||||
.where(eq(invoices.status, "pending"));
|
|
||||||
|
|
||||||
const [refundsResult] = await db
|
|
||||||
.select({ total: sql<number>`coalesce(sum(amount_cents), 0)` })
|
|
||||||
.from(refunds)
|
|
||||||
.where(sql`${refunds.createdAt} >= ${startOfMonth}`);
|
|
||||||
|
|
||||||
const methodBreakdown = await db
|
|
||||||
.select({
|
|
||||||
method: invoices.paymentMethod,
|
|
||||||
total: sql<number>`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,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -102,6 +102,7 @@ portalRouter.get("/appointments", async (c) => {
|
|||||||
const db = getDb();
|
const db = getDb();
|
||||||
const clientId = c.get("portalClientId");
|
const clientId = c.get("portalClientId");
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
const allAppts = await db
|
const allAppts = await db
|
||||||
.select({
|
.select({
|
||||||
id: appointments.id,
|
id: appointments.id,
|
||||||
@@ -141,7 +142,10 @@ portalRouter.get("/appointments", async (c) => {
|
|||||||
staff: a.staffId ? { id: staffMap[a.staffId]?.id, name: staffMap[a.staffId]?.name } : null,
|
staff: a.staffId ? { id: staffMap[a.staffId]?.id, name: staffMap[a.staffId]?.name } : null,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return c.json({ appointments: appts });
|
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 });
|
||||||
});
|
});
|
||||||
|
|
||||||
portalRouter.get("/pets", async (c) => {
|
portalRouter.get("/pets", async (c) => {
|
||||||
@@ -149,7 +153,7 @@ portalRouter.get("/pets", async (c) => {
|
|||||||
const clientId = c.get("portalClientId");
|
const clientId = c.get("portalClientId");
|
||||||
|
|
||||||
const clientPets = await db.select().from(pets).where(eq(pets.clientId, clientId));
|
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, weight: p.weightKg, birthDate: p.dateOfBirth, photoUrl: p.photoKey, notes: p.groomingNotes })));
|
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 })));
|
||||||
});
|
});
|
||||||
|
|
||||||
portalRouter.get("/invoices", async (c) => {
|
portalRouter.get("/invoices", async (c) => {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { Hono } from "hono";
|
|||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { eq, getDb, businessSettings } from "@groombook/db";
|
import { eq, getDb, businessSettings } from "@groombook/db";
|
||||||
import { getPresignedUploadUrl, deleteObject, putObject, getObject } from "../lib/s3.js";
|
import { getPresignedUploadUrl, getPresignedGetUrl, deleteObject, putObject } from "../lib/s3.js";
|
||||||
import { requireSuperUser } from "../middleware/rbac.js";
|
import { requireSuperUser } from "../middleware/rbac.js";
|
||||||
|
|
||||||
export const settingsRouter = new Hono();
|
export const settingsRouter = new Hono();
|
||||||
@@ -215,24 +215,17 @@ settingsRouter.post(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /api/admin/settings/logo
|
* GET /api/admin/settings/logo
|
||||||
* Proxies the logo from S3 so the browser never sees an S3 URL.
|
* Returns a presigned GET URL for the logo.
|
||||||
* Returns the image bytes with proper Content-Type.
|
|
||||||
*/
|
*/
|
||||||
settingsRouter.get("/logo", requireSuperUser(), async (c) => {
|
settingsRouter.get("/logo", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
|
|
||||||
const [row] = await db.select().from(businessSettings).limit(1);
|
const [row] = await db.select().from(businessSettings).limit(1);
|
||||||
if (!row) return c.json({ error: "Settings not found" }, 404);
|
if (!row) return c.json({ error: "Settings not found" }, 404);
|
||||||
if (!row.logoKey) return c.json({ error: "No logo on file" }, 404);
|
if (!row.logoKey) return c.json({ error: "No logo on file" }, 404);
|
||||||
|
|
||||||
const { body, contentType } = await getObject(row.logoKey);
|
const url = await getPresignedGetUrl(row.logoKey);
|
||||||
return new Response(Buffer.from(body), {
|
return c.json({ url, logoKey: row.logoKey });
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
"Content-Type": contentType,
|
|
||||||
"Cache-Control": "public, max-age=86400",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ const RATE_LIMIT_MAX = 10;
|
|||||||
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
|
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
|
||||||
|
|
||||||
function rateLimitByIp(ip: string): { allowed: boolean; remaining: number } {
|
function rateLimitByIp(ip: string): { allowed: boolean; remaining: number } {
|
||||||
const entry = rateLimitMap.get(ip);
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
const entry = rateLimitMap.get(ip);
|
||||||
if (!entry || now > entry.resetAt) {
|
if (!entry || now > entry.resetAt) {
|
||||||
rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
|
rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
|
||||||
return { allowed: true, remaining: RATE_LIMIT_MAX - 1 };
|
return { allowed: true, remaining: RATE_LIMIT_MAX - 1 };
|
||||||
|
|||||||
@@ -162,19 +162,3 @@ export async function createSetupIntent(customerId: string): Promise<{ clientSec
|
|||||||
|
|
||||||
return { clientSecret: setupIntent.client_secret! };
|
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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ test.beforeEach(async ({ page }) => {
|
|||||||
json: { newClients: [], activeInPeriodCount: 0, churnRisk: [], churnRiskTotal: 0 },
|
json: { newClients: [], activeInPeriodCount: 0, churnRisk: [], churnRiskTotal: 0 },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// Specific route must come before /api/invoices to avoid intercepting stats/summary
|
||||||
if (url.includes("/api/invoices/stats/summary")) {
|
if (url.includes("/api/invoices/stats/summary")) {
|
||||||
return route.fulfill({
|
return route.fulfill({
|
||||||
json: {
|
json: {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect, useState, useCallback, useRef, useId } from "react";
|
import { useEffect, useState, useCallback, useRef } from "react";
|
||||||
import { useSearchParams } from "react-router-dom";
|
import { useSearchParams } from "react-router-dom";
|
||||||
import type { Client, GroomingVisitLog, Pet } from "@groombook/types";
|
import type { Client, GroomingVisitLog, Pet } from "@groombook/types";
|
||||||
import { PetPhotoDisplay } from "../components/PetPhotoDisplay.js";
|
import { PetPhotoDisplay } from "../components/PetPhotoDisplay.js";
|
||||||
@@ -647,7 +647,8 @@ export function ClientsPage() {
|
|||||||
|
|
||||||
{/* ── Client modal ── */}
|
{/* ── Client modal ── */}
|
||||||
{showClientForm && (
|
{showClientForm && (
|
||||||
<Modal title={editingClient ? "Edit Client" : "New Client"} onClose={() => setShowClientForm(false)}>
|
<Modal onClose={() => setShowClientForm(false)}>
|
||||||
|
<h2 style={{ marginTop: 0 }}>{editingClient ? "Edit Client" : "New Client"}</h2>
|
||||||
<form onSubmit={submitClient}>
|
<form onSubmit={submitClient}>
|
||||||
<Field label="Full name">
|
<Field label="Full name">
|
||||||
<input value={clientForm.name} onChange={(e) => setClientForm((f) => ({ ...f, name: e.target.value }))} required style={inputStyle} />
|
<input value={clientForm.name} onChange={(e) => setClientForm((f) => ({ ...f, name: e.target.value }))} required style={inputStyle} />
|
||||||
@@ -677,7 +678,8 @@ export function ClientsPage() {
|
|||||||
|
|
||||||
{/* ── Pet modal ── */}
|
{/* ── Pet modal ── */}
|
||||||
{showPetForm && (
|
{showPetForm && (
|
||||||
<Modal title={editingPet ? "Edit Pet" : "Add Pet"} onClose={() => setShowPetForm(false)}>
|
<Modal onClose={() => setShowPetForm(false)}>
|
||||||
|
<h2 style={{ marginTop: 0 }}>{editingPet ? "Edit Pet" : "Add Pet"}</h2>
|
||||||
<form onSubmit={submitPet}>
|
<form onSubmit={submitPet}>
|
||||||
<Field label="Pet name">
|
<Field label="Pet name">
|
||||||
<input value={petForm.name} onChange={(e) => setPetForm((f) => ({ ...f, name: e.target.value }))} required style={inputStyle} />
|
<input value={petForm.name} onChange={(e) => setPetForm((f) => ({ ...f, name: e.target.value }))} required style={inputStyle} />
|
||||||
@@ -751,7 +753,8 @@ export function ClientsPage() {
|
|||||||
|
|
||||||
{/* ── Visit log modal ── */}
|
{/* ── Visit log modal ── */}
|
||||||
{showLogForm && logPetId && (
|
{showLogForm && logPetId && (
|
||||||
<Modal title="Log Grooming Visit" onClose={() => setShowLogForm(false)}>
|
<Modal onClose={() => setShowLogForm(false)}>
|
||||||
|
<h2 style={{ marginTop: 0 }}>Log Grooming Visit</h2>
|
||||||
{logsLoading[logPetId] && <p style={{ fontSize: 13, color: "#6b7280" }}>Loading history…</p>}
|
{logsLoading[logPetId] && <p style={{ fontSize: 13, color: "#6b7280" }}>Loading history…</p>}
|
||||||
{visitLogs[logPetId] && visitLogs[logPetId].length > 0 && (
|
{visitLogs[logPetId] && visitLogs[logPetId].length > 0 && (
|
||||||
<div style={{ marginBottom: "1rem" }}>
|
<div style={{ marginBottom: "1rem" }}>
|
||||||
@@ -814,7 +817,8 @@ export function ClientsPage() {
|
|||||||
|
|
||||||
{/* ── Delete confirmation modal ── */}
|
{/* ── Delete confirmation modal ── */}
|
||||||
{showDeleteConfirm && selectedClient && (
|
{showDeleteConfirm && selectedClient && (
|
||||||
<Modal title="Permanently Delete Client" titleStyle={{ color: "#dc2626" }} onClose={() => setShowDeleteConfirm(false)}>
|
<Modal onClose={() => setShowDeleteConfirm(false)}>
|
||||||
|
<h2 style={{ marginTop: 0, color: "#dc2626" }}>Permanently Delete Client</h2>
|
||||||
<p style={{ fontSize: 14, color: "#374151" }}>
|
<p style={{ fontSize: 14, color: "#374151" }}>
|
||||||
This will permanently delete <strong>{selectedClient.name}</strong> and all their pets. This action cannot be undone.
|
This will permanently delete <strong>{selectedClient.name}</strong> and all their pets. This action cannot be undone.
|
||||||
</p>
|
</p>
|
||||||
@@ -852,8 +856,7 @@ export function ClientsPage() {
|
|||||||
|
|
||||||
// ─── Shared UI ───────────────────────────────────────────────────────────────
|
// ─── Shared UI ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function Modal({ children, onClose, title, titleStyle }: { children: React.ReactNode; onClose: () => void; title: string; titleStyle?: React.CSSProperties }) {
|
function Modal({ children, onClose }: { children: React.ReactNode; onClose: () => void }) {
|
||||||
const titleId = useId();
|
|
||||||
const modalRef = useRef<HTMLDivElement>(null);
|
const modalRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -895,17 +898,15 @@ function Modal({ children, onClose, title, titleStyle }: { children: React.React
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.45)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100 }}
|
style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.45)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100 }}
|
||||||
onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
|
onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
ref={modalRef}
|
ref={modalRef}
|
||||||
role="dialog"
|
|
||||||
aria-modal="true"
|
|
||||||
aria-labelledby={titleId}
|
|
||||||
style={{ background: "#fff", borderRadius: 8, padding: "1.5rem", maxWidth: 480, width: "calc(100% - 2rem)", maxHeight: "90vh", overflowY: "auto", boxShadow: "0 20px 60px rgba(0,0,0,0.3)" }}
|
style={{ background: "#fff", borderRadius: 8, padding: "1.5rem", maxWidth: 480, width: "calc(100% - 2rem)", maxHeight: "90vh", overflowY: "auto", boxShadow: "0 20px 60px rgba(0,0,0,0.3)" }}
|
||||||
>
|
>
|
||||||
<h2 id={titleId} style={{ marginTop: 0, ...titleStyle }}>{title}</h2>
|
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -173,22 +173,6 @@ function InvoiceDetailModal({
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [tipStr, setTipStr] = useState((invoice.tipCents / 100).toFixed(2));
|
const [tipStr, setTipStr] = useState((invoice.tipCents / 100).toFixed(2));
|
||||||
const [paymentMethod, setPaymentMethod] = useState<string>(invoice.paymentMethod ?? "cash");
|
const [paymentMethod, setPaymentMethod] = useState<string>(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}
|
// Tip split state: array of {staffId, staffName, pct}
|
||||||
const linkedAppt = invoice.appointmentId
|
const linkedAppt = invoice.appointmentId
|
||||||
@@ -292,35 +276,6 @@ 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 <Modal onClose={onClose}><p style={{ padding: "1rem" }}>Loading…</p></Modal>;
|
if (loading) return <Modal onClose={onClose}><p style={{ padding: "1rem" }}>Loading…</p></Modal>;
|
||||||
|
|
||||||
const tipCentsCalc = Math.round(parseFloat(tipStr) * 100) || 0;
|
const tipCentsCalc = Math.round(parseFloat(tipStr) * 100) || 0;
|
||||||
@@ -380,19 +335,6 @@ function InvoiceDetailModal({
|
|||||||
/>
|
/>
|
||||||
{invoice.paidAt && <SummaryRow label="Paid on" value={fmtDate(invoice.paidAt)} />}
|
{invoice.paidAt && <SummaryRow label="Paid on" value={fmtDate(invoice.paidAt)} />}
|
||||||
{invoice.paymentMethod && <SummaryRow label="Payment" value={invoice.paymentMethod} />}
|
{invoice.paymentMethod && <SummaryRow label="Payment" value={invoice.paymentMethod} />}
|
||||||
{stripeDetails && (
|
|
||||||
<>
|
|
||||||
{stripeDetails.cardLast4 && (
|
|
||||||
<SummaryRow label="Card" value={`•••• ${stripeDetails.cardLast4}`} />
|
|
||||||
)}
|
|
||||||
{stripeDetails.paymentStatus && (
|
|
||||||
<SummaryRow label="Stripe status" value={stripeDetails.paymentStatus} />
|
|
||||||
)}
|
|
||||||
{stripeDetails.stripeRefundId && (
|
|
||||||
<SummaryRow label="Refund" value="Refunded" />
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ── Tip Distribution ── */}
|
{/* ── Tip Distribution ── */}
|
||||||
@@ -510,76 +452,10 @@ function InvoiceDetailModal({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{(invoice.status === "paid" || invoice.status === "void") && (
|
{(invoice.status === "paid" || invoice.status === "void") && (
|
||||||
<div style={{ marginTop: "1rem", display: "flex", justifyContent: "flex-end", gap: "0.5rem" }}>
|
<div style={{ marginTop: "1rem", display: "flex", justifyContent: "flex-end" }}>
|
||||||
{invoice.status === "paid" && invoice.stripePaymentIntentId && (
|
|
||||||
<button
|
|
||||||
onClick={() => setShowRefundDialog(true)}
|
|
||||||
style={{ ...btnStyle, color: "#b45309", borderColor: "#b45309" }}
|
|
||||||
>
|
|
||||||
Refund
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
<button onClick={onClose} style={btnStyle}>Close</button>
|
<button onClick={onClose} style={btnStyle}>Close</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Refund Dialog */}
|
|
||||||
{showRefundDialog && (
|
|
||||||
<Modal onClose={() => setShowRefundDialog(false)}>
|
|
||||||
<h2 style={{ marginTop: 0 }}>Issue Refund</h2>
|
|
||||||
<p style={{ fontSize: 14, color: "#6b7280", marginBottom: "1rem" }}>
|
|
||||||
Invoice total: <strong>{fmtMoney(invoice.totalCents)}</strong>
|
|
||||||
</p>
|
|
||||||
<div style={{ marginBottom: "0.75rem" }}>
|
|
||||||
<label style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontWeight: 600, marginBottom: "0.5rem" }}>
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
name="refundType"
|
|
||||||
value="full"
|
|
||||||
checked={refundType === "full"}
|
|
||||||
onChange={() => setRefundType("full")}
|
|
||||||
/>
|
|
||||||
Full refund
|
|
||||||
</label>
|
|
||||||
<label style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontWeight: 600 }}>
|
|
||||||
<input
|
|
||||||
type="radio"
|
|
||||||
name="refundType"
|
|
||||||
value="partial"
|
|
||||||
checked={refundType === "partial"}
|
|
||||||
onChange={() => setRefundType("partial")}
|
|
||||||
/>
|
|
||||||
Partial refund
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
{refundType === "partial" && (
|
|
||||||
<div style={{ marginBottom: "1rem" }}>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
min="0.01"
|
|
||||||
step="0.01"
|
|
||||||
placeholder="0.00"
|
|
||||||
value={partialAmount}
|
|
||||||
onChange={(e) => setPartialAmount(e.target.value)}
|
|
||||||
style={{ ...inputStyle, width: 120 }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{error && <p style={{ color: "red", margin: "0.5rem 0" }}>{error}</p>}
|
|
||||||
<div style={{ display: "flex", gap: "0.5rem", marginTop: "0.75rem" }}>
|
|
||||||
<button
|
|
||||||
onClick={issueRefund}
|
|
||||||
disabled={saving}
|
|
||||||
style={{ ...btnStyle, backgroundColor: "#b45309", color: "#fff", borderColor: "#b45309" }}
|
|
||||||
>
|
|
||||||
{saving ? "Processing…" : "Issue Refund"}
|
|
||||||
</button>
|
|
||||||
<button onClick={() => setShowRefundDialog(false)} style={btnStyle}>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</Modal>
|
|
||||||
)}
|
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -621,17 +497,9 @@ export function InvoicesPage() {
|
|||||||
const [createLoading, setCreateLoading] = useState(false);
|
const [createLoading, setCreateLoading] = useState(false);
|
||||||
const [detailData, setDetailData] = useState<{ staff: Staff[]; appointments: Appointment[] } | null>(null);
|
const [detailData, setDetailData] = useState<{ staff: Staff[]; appointments: Appointment[] } | null>(null);
|
||||||
const [detailLoading, setDetailLoading] = useState(false);
|
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;
|
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) {
|
async function loadInvoices(newOffset: number) {
|
||||||
const params = new URLSearchParams({ limit: String(LIMIT), offset: String(newOffset) });
|
const params = new URLSearchParams({ limit: String(LIMIT), offset: String(newOffset) });
|
||||||
if (statusFilter) params.set("status", statusFilter);
|
if (statusFilter) params.set("status", statusFilter);
|
||||||
@@ -710,34 +578,6 @@ export function InvoicesPage() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Payment Stats Summary */}
|
|
||||||
{paymentStats && (
|
|
||||||
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: "0.75rem", marginBottom: "1.25rem" }}>
|
|
||||||
<div style={{ background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 8, padding: "0.75rem 1rem" }}>
|
|
||||||
<div style={{ fontSize: 12, color: "#166534", fontWeight: 600, marginBottom: "0.25rem" }}>Revenue (paid)</div>
|
|
||||||
<div style={{ fontSize: 20, fontWeight: 700, color: "#15803d" }}>{fmtMoney(paymentStats.revenueThisMonth)}</div>
|
|
||||||
</div>
|
|
||||||
<div style={{ background: "#fefce8", border: "1px solid #fde047", borderRadius: 8, padding: "0.75rem 1rem" }}>
|
|
||||||
<div style={{ fontSize: 12, color: "#854d0e", fontWeight: 600, marginBottom: "0.25rem" }}>Outstanding</div>
|
|
||||||
<div style={{ fontSize: 20, fontWeight: 700, color: "#a16207" }}>{fmtMoney(paymentStats.outstanding)}</div>
|
|
||||||
</div>
|
|
||||||
<div style={{ background: "#fef2f2", border: "1px solid #fecaca", borderRadius: 8, padding: "0.75rem 1rem" }}>
|
|
||||||
<div style={{ fontSize: 12, color: "#991b1b", fontWeight: 600, marginBottom: "0.25rem" }}>Refunds (this mo.)</div>
|
|
||||||
<div style={{ fontSize: 20, fontWeight: 700, color: "#dc2626" }}>{fmtMoney(paymentStats.refundsThisMonth)}</div>
|
|
||||||
</div>
|
|
||||||
{paymentStats.methodBreakdown.length > 0 && (
|
|
||||||
<div style={{ background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: 8, padding: "0.75rem 1rem" }}>
|
|
||||||
<div style={{ fontSize: 12, color: "#475569", fontWeight: 600, marginBottom: "0.25rem" }}>By method</div>
|
|
||||||
<div style={{ fontSize: 13, color: "#64748b" }}>
|
|
||||||
{paymentStats.methodBreakdown.map((b) => (
|
|
||||||
<div key={b.method ?? "unknown"}>{b.method ?? "other"}: {b.total}</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{invoiceList.length === 0 ? (
|
{invoiceList.length === 0 ? (
|
||||||
<p style={{ color: "#6b7280" }}>
|
<p style={{ color: "#6b7280" }}>
|
||||||
No invoices yet. Create one from a completed appointment.
|
No invoices yet. Create one from a completed appointment.
|
||||||
|
|||||||
@@ -89,14 +89,24 @@ export function SettingsPage() {
|
|||||||
fetch("/api/admin/settings")
|
fetch("/api/admin/settings")
|
||||||
.then((r) => r.json())
|
.then((r) => r.json())
|
||||||
.then(async (data) => {
|
.then(async (data) => {
|
||||||
// The logo is now proxied through the API server so the browser
|
let logoUrl: string | null = null;
|
||||||
// never receives an S3 URL — use the proxy path directly as the src.
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
setForm({
|
setForm({
|
||||||
businessName: data.businessName ?? "GroomBook",
|
businessName: data.businessName ?? "GroomBook",
|
||||||
primaryColor: data.primaryColor ?? "#4f8a6f",
|
primaryColor: data.primaryColor ?? "#4f8a6f",
|
||||||
accentColor: data.accentColor ?? "#8b7355",
|
accentColor: data.accentColor ?? "#8b7355",
|
||||||
logoKey: data.logoKey ?? null,
|
logoKey: data.logoKey ?? null,
|
||||||
logoUrl: data.logoKey ? "/api/admin/settings/logo" : null,
|
logoUrl,
|
||||||
logoBase64: data.logoBase64 ?? null,
|
logoBase64: data.logoBase64 ?? null,
|
||||||
logoMimeType: data.logoMimeType ?? null,
|
logoMimeType: data.logoMimeType ?? null,
|
||||||
});
|
});
|
||||||
@@ -162,7 +172,15 @@ export function SettingsPage() {
|
|||||||
throw new Error(err?.error ?? "Failed to upload logo");
|
throw new Error(err?.error ?? "Failed to upload logo");
|
||||||
}
|
}
|
||||||
const { logoKey } = await uploadRes.json();
|
const { logoKey } = await uploadRes.json();
|
||||||
setForm((f) => ({ ...f, logoKey, logoUrl: `/api/admin/settings/logo?t=${Date.now()}`, logoBase64: null, logoMimeType: null }));
|
|
||||||
|
// 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 }));
|
||||||
|
}
|
||||||
setMessage({ type: "success", text: "Logo uploaded." });
|
setMessage({ type: "success", text: "Logo uploaded." });
|
||||||
refresh();
|
refresh();
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
|
|||||||
@@ -27,7 +27,8 @@ interface Appointment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface AppointmentsResponse {
|
interface AppointmentsResponse {
|
||||||
appointments: Appointment[];
|
upcoming: Appointment[];
|
||||||
|
past: Appointment[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -45,7 +46,7 @@ function buildHeaders(sessionId: string | null): Record<string, string> {
|
|||||||
|
|
||||||
export function PetProfiles({ sessionId, readOnly }: Props) {
|
export function PetProfiles({ sessionId, readOnly }: Props) {
|
||||||
const [pets, setPets] = useState<Pet[]>([]);
|
const [pets, setPets] = useState<Pet[]>([]);
|
||||||
const [appointments, setAppointments] = useState<AppointmentsResponse>({ appointments: [] });
|
const [appointments, setAppointments] = useState<AppointmentsResponse>({ upcoming: [], past: [] });
|
||||||
const [selectedPetId, setSelectedPetId] = useState<string>("");
|
const [selectedPetId, setSelectedPetId] = useState<string>("");
|
||||||
const [activeTab, setActiveTab] = useState<"info" | "medical" | "grooming" | "history">("info");
|
const [activeTab, setActiveTab] = useState<"info" | "medical" | "grooming" | "history">("info");
|
||||||
const [editingPetId, setEditingPetId] = useState<string | null>(null);
|
const [editingPetId, setEditingPetId] = useState<string | null>(null);
|
||||||
@@ -89,7 +90,7 @@ export function PetProfiles({ sessionId, readOnly }: Props) {
|
|||||||
}, [sessionId]);
|
}, [sessionId]);
|
||||||
|
|
||||||
const selectedPet = pets.find(p => p.id === selectedPetId) ?? null;
|
const selectedPet = pets.find(p => p.id === selectedPetId) ?? null;
|
||||||
const petHistory = appointments.appointments.filter(a => a.pet?.id === selectedPetId && new Date(a.startTime) <= new Date());
|
const petHistory = appointments.past.filter(a => a.pet?.id === selectedPetId);
|
||||||
const editingPet = editingPetId ? pets.find(p => p.id === editingPetId) ?? null : null;
|
const editingPet = editingPetId ? pets.find(p => p.id === editingPetId) ?? null : null;
|
||||||
|
|
||||||
function handlePetSave(updatedPet: Pet) {
|
function handlePetSave(updatedPet: Pet) {
|
||||||
|
|||||||
@@ -152,16 +152,10 @@ export interface Invoice {
|
|||||||
status: InvoiceStatus;
|
status: InvoiceStatus;
|
||||||
paymentMethod: PaymentMethod | null;
|
paymentMethod: PaymentMethod | null;
|
||||||
paidAt: string | null;
|
paidAt: string | null;
|
||||||
stripePaymentIntentId: string | null;
|
|
||||||
stripeRefundId: string | null;
|
|
||||||
paymentFailureReason: string | null;
|
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
lineItems?: InvoiceLineItem[];
|
lineItems?: InvoiceLineItem[];
|
||||||
// Transient fields populated from Stripe API (not stored in DB)
|
|
||||||
cardLast4?: string | null;
|
|
||||||
paymentStatus?: string | null;
|
|
||||||
tipSplits?: InvoiceTipSplit[];
|
tipSplits?: InvoiceTipSplit[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user