Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5b33efdddd |
@@ -202,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
|
||||||
|
|||||||
@@ -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,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -71,18 +71,10 @@ export function PetProfiles({ sessionId, readOnly }: Props) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const petsData = await petsRes.json();
|
const petsData = await petsRes.json();
|
||||||
const apptsData = await apptsRes.json();
|
const apptsData: AppointmentsResponse = await apptsRes.json();
|
||||||
|
|
||||||
setPets(petsData.map((p: { id: string; name: string; breed: string; weightKg: number; dateOfBirth: string; photoKey: string | null; groomingNotes: string | null }) => ({
|
setPets(petsData);
|
||||||
id: p.id,
|
setAppointments(apptsData);
|
||||||
name: p.name,
|
|
||||||
breed: p.breed,
|
|
||||||
weight: p.weightKg,
|
|
||||||
birthDate: p.dateOfBirth,
|
|
||||||
photoUrl: p.photoKey ?? null,
|
|
||||||
notes: p.groomingNotes ?? null,
|
|
||||||
})));
|
|
||||||
setAppointments({ upcoming: apptsData?.upcoming || [], past: apptsData?.past || [] });
|
|
||||||
|
|
||||||
if (petsData.length > 0 && !selectedPetId) {
|
if (petsData.length > 0 && !selectedPetId) {
|
||||||
setSelectedPetId(petsData[0].id);
|
setSelectedPetId(petsData[0].id);
|
||||||
|
|||||||
@@ -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