Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e82c232b44 | |||
| 6893676a93 | |||
| 625fadd4eb | |||
| a1941e8acf | |||
| fe2e093b92 | |||
| 2af1671891 | |||
| ad80722eee | |||
| c811b58c62 | |||
| 1dfcdcc2cb | |||
| f74e034495 | |||
| 4c46cec4e3 | |||
| 251b36b863 | |||
| 10ad5e7b04 |
+20
-9
@@ -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 { getPresignedGetUrl } from "./lib/s3.js";
|
import { getObject } 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,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
|
// 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 };
|
||||||
|
|
||||||
let logoUrl: string | null = null;
|
// Return the public proxy path so browser never sees a raw S3 URL
|
||||||
if (settings.logoKey) {
|
const logoUrl = settings.logoKey ? "/api/branding/logo" : null;
|
||||||
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
|
||||||
|
|||||||
@@ -68,6 +68,25 @@ 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,
|
||||||
|
|||||||
@@ -101,6 +101,8 @@ invoicesRouter.get(
|
|||||||
paymentMethod: invoices.paymentMethod,
|
paymentMethod: invoices.paymentMethod,
|
||||||
paidAt: invoices.paidAt,
|
paidAt: invoices.paidAt,
|
||||||
notes: invoices.notes,
|
notes: invoices.notes,
|
||||||
|
stripePaymentIntentId: invoices.stripePaymentIntentId,
|
||||||
|
stripeRefundId: invoices.stripeRefundId,
|
||||||
createdAt: invoices.createdAt,
|
createdAt: invoices.createdAt,
|
||||||
updatedAt: invoices.updatedAt,
|
updatedAt: invoices.updatedAt,
|
||||||
})
|
})
|
||||||
@@ -480,40 +482,50 @@ invoicesRouter.post(
|
|||||||
|
|
||||||
// Payment stats for admin dashboard
|
// Payment stats for admin dashboard
|
||||||
invoicesRouter.get("/stats/summary", async (c) => {
|
invoicesRouter.get("/stats/summary", async (c) => {
|
||||||
const db = getDb();
|
try {
|
||||||
const now = new Date();
|
const db = getDb();
|
||||||
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
const now = new Date();
|
||||||
|
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
||||||
|
|
||||||
const [revenueResult] = await db
|
const [revenueResult] = await db
|
||||||
.select({ total: sql<number>`coalesce(sum(total_cents), 0)` })
|
.select({ total: sql<number>`coalesce(sum(total_cents), 0)` })
|
||||||
.from(invoices)
|
.from(invoices)
|
||||||
.where(and(eq(invoices.status, "paid"), sql`${invoices.paidAt} >= ${startOfMonth}`));
|
.where(and(eq(invoices.status, "paid"), sql`${invoices.paidAt} >= ${startOfMonth}`));
|
||||||
|
|
||||||
const [outstandingResult] = await db
|
const [outstandingResult] = await db
|
||||||
.select({ total: sql<number>`coalesce(sum(total_cents), 0)` })
|
.select({ total: sql<number>`coalesce(sum(total_cents), 0)` })
|
||||||
.from(invoices)
|
.from(invoices)
|
||||||
.where(eq(invoices.status, "pending"));
|
.where(eq(invoices.status, "pending"));
|
||||||
|
|
||||||
const [refundsResult] = await db
|
const [refundsResult] = await db
|
||||||
.select({ total: sql<number>`coalesce(sum(amount_cents), 0)` })
|
.select({ total: sql<number>`coalesce(sum(amount_cents), 0)` })
|
||||||
.from(refunds)
|
.from(refunds)
|
||||||
.where(sql`${refunds.createdAt} >= ${startOfMonth}`);
|
.where(sql`${refunds.createdAt} >= ${startOfMonth}`);
|
||||||
|
|
||||||
const methodBreakdown = await db
|
const methodBreakdown = await db
|
||||||
.select({
|
.select({
|
||||||
method: invoices.paymentMethod,
|
method: invoices.paymentMethod,
|
||||||
total: sql<number>`count(*)`,
|
total: sql<number>`count(*)`,
|
||||||
})
|
})
|
||||||
.from(invoices)
|
.from(invoices)
|
||||||
.where(and(eq(invoices.status, "paid"), sql`${invoices.paidAt} >= ${startOfMonth}`))
|
.where(and(eq(invoices.status, "paid"), sql`${invoices.paidAt} >= ${startOfMonth}`))
|
||||||
.groupBy(invoices.paymentMethod);
|
.groupBy(invoices.paymentMethod);
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
revenueThisMonth: revenueResult?.total ?? 0,
|
revenueThisMonth: revenueResult?.total ?? 0,
|
||||||
outstanding: outstandingResult?.total ?? 0,
|
outstanding: outstandingResult?.total ?? 0,
|
||||||
refundsThisMonth: refundsResult?.total ?? 0,
|
refundsThisMonth: refundsResult?.total ?? 0,
|
||||||
methodBreakdown,
|
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)
|
// Get Stripe payment details for an invoice (card last4, payment status, refund status)
|
||||||
|
|||||||
@@ -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, getPresignedGetUrl, deleteObject, putObject } from "../lib/s3.js";
|
import { getPresignedUploadUrl, deleteObject, putObject, getObject } 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,7 +215,8 @@ settingsRouter.post(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /api/admin/settings/logo
|
* 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) => {
|
settingsRouter.get("/logo", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
@@ -224,8 +225,14 @@ settingsRouter.get("/logo", async (c) => {
|
|||||||
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 url = await getPresignedGetUrl(row.logoKey);
|
const { body, contentType } = await getObject(row.logoKey);
|
||||||
return c.json({ url, logoKey: row.logoKey });
|
return new Response(Buffer.from(body), {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"Content-Type": contentType,
|
||||||
|
"Cache-Control": "public, max-age=86400",
|
||||||
|
},
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -44,6 +44,16 @@ test.beforeEach(async ({ page }) => {
|
|||||||
json: { newClients: [], activeInPeriodCount: 0, churnRisk: [], churnRiskTotal: 0 },
|
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")) {
|
if (url.includes("/api/invoices")) {
|
||||||
return route.fulfill({ json: { data: [], total: 0 } });
|
return route.fulfill({ json: { data: [], total: 0 } });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -112,9 +112,17 @@ export function AppointmentsPage() {
|
|||||||
const [viewMode, setViewMode] = useState<"status" | "groomer">("status");
|
const [viewMode, setViewMode] = useState<"status" | "groomer">("status");
|
||||||
// null key = unassigned; staffId string = that groomer; undefined set = all visible
|
// null key = unassigned; staffId string = that groomer; undefined set = all visible
|
||||||
const [hiddenGroomers, setHiddenGroomers] = useState<Set<string | null>>(new Set());
|
const [hiddenGroomers, setHiddenGroomers] = useState<Set<string | null>>(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);
|
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 loadAppointments = useCallback(() => {
|
||||||
const from = weekStart.toISOString();
|
const from = weekStart.toISOString();
|
||||||
const to = addDays(weekStart, 7).toISOString();
|
const to = addDays(weekStart, 7).toISOString();
|
||||||
@@ -314,6 +322,24 @@ export function AppointmentsPage() {
|
|||||||
</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" }}>${(paymentStats.revenueThisMonth / 100).toFixed(2)}</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" }}>${(paymentStats.outstanding / 100).toFixed(2)}</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" }}>${(paymentStats.refundsThisMonth / 100).toFixed(2)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* ── View Mode + Groomer Filters ── */}
|
{/* ── View Mode + Groomer Filters ── */}
|
||||||
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.75rem", flexWrap: "wrap" }}>
|
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.75rem", flexWrap: "wrap" }}>
|
||||||
<span style={{ fontSize: 13, fontWeight: 600, color: "#374151" }}>Color by:</span>
|
<span style={{ fontSize: 13, fontWeight: 600, color: "#374151" }}>Color by:</span>
|
||||||
|
|||||||
@@ -173,22 +173,21 @@ 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 [showRefundDialog, setShowRefundDialog] = useState(false);
|
||||||
const [refundType, setRefundType] = useState<"full" | "partial">("full");
|
const [refundType, setRefundType] = useState<"full" | "partial">("full");
|
||||||
const [partialAmount, setPartialAmount] = useState("");
|
const [refundAmount, setRefundAmount] = useState("");
|
||||||
const [stripeDetails, setStripeDetails] = useState<{ cardLast4: string | null; paymentStatus: string | null; stripeRefundId: string | null } | null>(null);
|
const [refundError, setRefundError] = useState<string | null>(null);
|
||||||
|
const [refunding, setRefunding] = useState(false);
|
||||||
|
|
||||||
// Fetch Stripe details when modal opens for paid invoices with a payment intent
|
// Fetch current staff role to determine manager access
|
||||||
|
const [staffMe, setStaffMe] = useState<{ role: string; isSuperUser: boolean } | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (invoice.status === "paid" && invoice.stripePaymentIntentId) {
|
fetch("/api/staff/me")
|
||||||
fetch(`/api/invoices/${invoice.id}/stripe-details`)
|
.then((r) => r.json())
|
||||||
.then((r) => r.ok ? r.json() : null)
|
.then((d) => setStaffMe(d))
|
||||||
.then((data) => { if (data) setStripeDetails(data); })
|
.catch(() => setStaffMe(null));
|
||||||
.catch(() => {});
|
}, []);
|
||||||
} else {
|
const isManager = staffMe && (staffMe.role === "manager" || staffMe.isSuperUser);
|
||||||
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 +291,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,15 +350,15 @@ 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 && (
|
{invoice.stripePaymentIntentId && (
|
||||||
<>
|
<>
|
||||||
{stripeDetails.cardLast4 && (
|
{invoice.cardLast4 && (
|
||||||
<SummaryRow label="Card" value={`•••• ${stripeDetails.cardLast4}`} />
|
<SummaryRow label="Card" value={`•••• ${invoice.cardLast4}`} />
|
||||||
)}
|
)}
|
||||||
{stripeDetails.paymentStatus && (
|
{invoice.paymentStatus && (
|
||||||
<SummaryRow label="Stripe status" value={stripeDetails.paymentStatus} />
|
<SummaryRow label="Stripe status" value={invoice.paymentStatus} />
|
||||||
)}
|
)}
|
||||||
{stripeDetails.stripeRefundId && (
|
{invoice.stripeRefundId && (
|
||||||
<SummaryRow label="Refund" value="Refunded" />
|
<SummaryRow label="Refund" value="Refunded" />
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
@@ -510,77 +480,85 @@ 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", borderTop: "1px solid #e2e8f0", paddingTop: "1rem" }}>
|
||||||
{invoice.status === "paid" && invoice.stripePaymentIntentId && (
|
{invoice.stripeRefundId && (
|
||||||
<button
|
<div style={{ marginBottom: "0.75rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
|
||||||
onClick={() => setShowRefundDialog(true)}
|
<span style={{ background: "#fef3c7", color: "#92400e", padding: "0.2rem 0.6rem", borderRadius: 4, fontSize: 13, fontWeight: 600 }}>Refunded</span>
|
||||||
style={{ ...btnStyle, color: "#b45309", borderColor: "#b45309" }}
|
</div>
|
||||||
>
|
|
||||||
Refund
|
|
||||||
</button>
|
|
||||||
)}
|
)}
|
||||||
<button onClick={onClose} style={btnStyle}>Close</button>
|
<div style={{ display: "flex", gap: "0.5rem", justifyContent: "flex-end" }}>
|
||||||
|
{invoice.status === "paid" && invoice.stripePaymentIntentId && !invoice.stripeRefundId && isManager && (
|
||||||
|
<button onClick={() => setShowRefundDialog(true)} style={{ ...btnStyle, color: "#fff", backgroundColor: "#7c3aed", borderColor: "#7c3aed" }}>
|
||||||
|
Refund
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button onClick={onClose} style={btnStyle}>Close</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Refund Dialog */}
|
|
||||||
{showRefundDialog && (
|
{showRefundDialog && (
|
||||||
<Modal onClose={() => setShowRefundDialog(false)}>
|
<div style={{ marginTop: "1rem", border: "1px solid #e2e8f0", borderRadius: 8, padding: "1rem", background: "#f9fafb" }}>
|
||||||
<h2 style={{ marginTop: 0 }}>Issue Refund</h2>
|
<p style={{ fontWeight: 600, margin: "0 0 0.75rem" }}>Process Refund</p>
|
||||||
<p style={{ fontSize: 14, color: "#6b7280", marginBottom: "1rem" }}>
|
<div style={{ display: "flex", gap: "0.75rem", marginBottom: "0.75rem" }}>
|
||||||
Invoice total: <strong>{fmtMoney(invoice.totalCents)}</strong>
|
<label style={{ display: "flex", alignItems: "center", gap: "0.25rem", cursor: "pointer" }}>
|
||||||
</p>
|
<input type="radio" checked={refundType === "full"} onChange={() => setRefundType("full")} />
|
||||||
<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
|
Full refund
|
||||||
</label>
|
</label>
|
||||||
<label style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontWeight: 600 }}>
|
<label style={{ display: "flex", alignItems: "center", gap: "0.25rem", cursor: "pointer" }}>
|
||||||
<input
|
<input type="radio" checked={refundType === "partial"} onChange={() => setRefundType("partial")} />
|
||||||
type="radio"
|
|
||||||
name="refundType"
|
|
||||||
value="partial"
|
|
||||||
checked={refundType === "partial"}
|
|
||||||
onChange={() => setRefundType("partial")}
|
|
||||||
/>
|
|
||||||
Partial refund
|
Partial refund
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
{refundType === "partial" && (
|
{refundType === "partial" && (
|
||||||
<div style={{ marginBottom: "1rem" }}>
|
<div style={{ marginBottom: "0.75rem" }}>
|
||||||
<input
|
<input
|
||||||
type="number"
|
type="number"
|
||||||
min="0.01"
|
min="0.01"
|
||||||
step="0.01"
|
step="0.01"
|
||||||
placeholder="0.00"
|
placeholder="Amount ($)"
|
||||||
value={partialAmount}
|
value={refundAmount}
|
||||||
onChange={(e) => setPartialAmount(e.target.value)}
|
onChange={(e) => setRefundAmount(e.target.value)}
|
||||||
style={{ ...inputStyle, width: 120 }}
|
style={{ ...inputStyle, width: 100 }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{error && <p style={{ color: "red", margin: "0.5rem 0" }}>{error}</p>}
|
{refundError && <p style={{ color: "red", margin: "0 0 0.5rem", fontSize: 13 }}>{refundError}</p>}
|
||||||
<div style={{ display: "flex", gap: "0.5rem", marginTop: "0.75rem" }}>
|
<div style={{ display: "flex", gap: "0.5rem" }}>
|
||||||
<button
|
<button
|
||||||
onClick={issueRefund}
|
onClick={async () => {
|
||||||
disabled={saving}
|
setRefunding(true);
|
||||||
style={{ ...btnStyle, backgroundColor: "#b45309", color: "#fff", borderColor: "#b45309" }}
|
setRefundError(null);
|
||||||
|
try {
|
||||||
|
const body = refundType === "partial" ? { amountCents: Math.round(parseFloat(refundAmount) * 100) } : {};
|
||||||
|
const res = await fetch(`/api/invoices/${invoice.id}/refund`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
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) {
|
||||||
|
setRefundError(e instanceof Error ? e.message : "Refund failed");
|
||||||
|
} finally {
|
||||||
|
setRefunding(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={refunding}
|
||||||
|
style={{ ...btnStyle, color: "#fff", backgroundColor: "#7c3aed", borderColor: "#7c3aed" }}
|
||||||
>
|
>
|
||||||
{saving ? "Processing…" : "Issue Refund"}
|
{refunding ? "Processing…" : "Process Refund"}
|
||||||
</button>
|
|
||||||
<button onClick={() => setShowRefundDialog(false)} style={btnStyle}>
|
|
||||||
Cancel
|
|
||||||
</button>
|
</button>
|
||||||
|
<button onClick={() => { setShowRefundDialog(false); setRefundError(null); }} style={btnStyle}>Cancel</button>
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</div>
|
||||||
)}
|
)}
|
||||||
</Modal>
|
|
||||||
|
</Modal>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -89,24 +89,14 @@ 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) => {
|
||||||
let logoUrl: string | null = null;
|
// The logo is now proxied through the API server so the browser
|
||||||
if (data.logoKey) {
|
// never receives an S3 URL — use the proxy path directly as the src.
|
||||||
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,
|
logoUrl: data.logoKey ? "/api/admin/settings/logo" : null,
|
||||||
logoBase64: data.logoBase64 ?? null,
|
logoBase64: data.logoBase64 ?? null,
|
||||||
logoMimeType: data.logoMimeType ?? null,
|
logoMimeType: data.logoMimeType ?? null,
|
||||||
});
|
});
|
||||||
@@ -172,15 +162,7 @@ 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) {
|
||||||
|
|||||||
Reference in New Issue
Block a user