Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 660d3e0741 |
+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
|
||||||
|
|||||||
@@ -77,12 +77,7 @@ export async function getObject(key: string): Promise<{ body: Buffer; contentTyp
|
|||||||
Key: key,
|
Key: key,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
const chunks: Uint8Array[] = [];
|
const body = await response.Body!.transformToBuffer();
|
||||||
// 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";
|
const contentType = response.ContentType ?? "application/octet-stream";
|
||||||
return { body, contentType };
|
return { body, contentType };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -422,7 +422,7 @@ invoicesRouter.patch(
|
|||||||
|
|
||||||
// ─── 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 +477,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,
|
||||||
|
|||||||
@@ -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, 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();
|
||||||
@@ -218,7 +218,7 @@ settingsRouter.post(
|
|||||||
* Proxies the logo from S3 so the browser never sees an S3 URL.
|
* Proxies the logo from S3 so the browser never sees an S3 URL.
|
||||||
* Returns the image bytes with proper Content-Type.
|
* 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);
|
||||||
@@ -226,13 +226,9 @@ settingsRouter.get("/logo", requireSuperUser(), async (c) => {
|
|||||||
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 { body, contentType } = await getObject(row.logoKey);
|
||||||
return new Response(Buffer.from(body), {
|
c.header("Content-Type", contentType);
|
||||||
status: 200,
|
c.header("Cache-Control", "public, max-age=86400");
|
||||||
headers: {
|
return c.body(body);
|
||||||
"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,16 +44,6 @@ 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 } });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -162,7 +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 }));
|
setForm((f) => ({ ...f, logoKey, logoUrl: "/api/admin/settings/logo", logoBase64: null, logoMimeType: null }));
|
||||||
setMessage({ type: "success", text: "Logo uploaded." });
|
setMessage({ type: "success", text: "Logo uploaded." });
|
||||||
refresh();
|
refresh();
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
|
|||||||
@@ -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