Compare commits

..

1 Commits

Author SHA1 Message Date
Flea Flicker a222bd4542 fix(auth): add email-based staff auto-linking in resolveStaffMiddleware
Add email-based auto-linking fallback so staff records without a userId are
automatically linked on first authenticated request. This fixes a UAT blocker
where all authenticated API routes returned HTTP 403 after login because
Better-Auth user IDs don't match seed-created staff records.

Fallback chain:
1. userId match (existing fast path)
2. oidcSub match (legacy records)
3. email match + auto-link (new)
2026-04-15 05:39:34 +00:00
4 changed files with 12 additions and 84 deletions
+12 -47
View File
@@ -8,7 +8,6 @@ import {
invoices, invoices,
invoiceLineItems, invoiceLineItems,
invoiceTipSplits, invoiceTipSplits,
refunds,
appointments, appointments,
services, services,
clients, clients,
@@ -126,8 +125,8 @@ const tipSplitSchema = z.object({
}) })
).min(1).refine( ).min(1).refine(
(splits) => { (splits) => {
const totalBps = splits.reduce((sum, s) => sum + Math.round(s.sharePct * 100), 0); const total = splits.reduce((sum, s) => sum + s.sharePct, 0);
return totalBps === 10000; return Math.abs(total - 100) < 0.01;
}, },
{ message: "Split percentages must sum to 100" } { message: "Split percentages must sum to 100" }
), ),
@@ -171,13 +170,12 @@ invoicesRouter.post(
} }
}); });
const [updatedInvoice] = await db.select().from(invoices).where(eq(invoices.id, id)); const splits = await db
const [lineItems, tipSplits] = await Promise.all([ .select()
db.select().from(invoiceLineItems).where(eq(invoiceLineItems.invoiceId, id)), .from(invoiceTipSplits)
db.select().from(invoiceTipSplits).where(eq(invoiceTipSplits.invoiceId, id)), .where(eq(invoiceTipSplits.invoiceId, id));
]);
return c.json({ ...updatedInvoice, lineItems, tipSplits }, 201); return c.json(splits, 201);
} }
); );
@@ -302,13 +300,6 @@ invoicesRouter.post("/from-appointment/:appointmentId", async (c) => {
return c.json({ ...invoice, lineItems: [lineItem] }, 201); return c.json({ ...invoice, lineItems: [lineItem] }, 201);
}); });
const ALLOWED_TRANSITIONS: Record<string, string[]> = {
draft: ["pending", "void"],
pending: ["draft", "paid", "void"],
paid: ["void"],
void: [],
};
// Update invoice // Update invoice
invoicesRouter.patch( invoicesRouter.patch(
"/:id", "/:id",
@@ -324,14 +315,8 @@ invoicesRouter.patch(
.where(eq(invoices.id, id)); .where(eq(invoices.id, id));
if (!current) return c.json({ error: "Not found" }, 404); if (!current) return c.json({ error: "Not found" }, 404);
if (body.status !== undefined) { if (current.status === "void") {
const allowed = ALLOWED_TRANSITIONS[current.status] ?? []; return c.json({ error: "Cannot modify a voided invoice" }, 422);
if (!allowed.includes(body.status)) {
return c.json(
{ error: `Invalid status transition from ${current.status} to ${body.status}` },
422
);
}
} }
const update: Record<string, unknown> = { ...body, updatedAt: new Date() }; const update: Record<string, unknown> = { ...body, updatedAt: new Date() };
@@ -369,7 +354,6 @@ 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(),
idempotencyKey: z.string().max(255).optional(),
}); });
invoicesRouter.post( invoicesRouter.post(
@@ -395,28 +379,9 @@ invoicesRouter.post(
return c.json({ error: "No Stripe payment intent found for this invoice" }, 422); return c.json({ error: "No Stripe payment intent found for this invoice" }, 422);
} }
return await db.transaction(async (tx) => { const result = await processRefund(id, body.amountCents);
if (body.idempotencyKey) { if (!result) return c.json({ error: "Refund failed" }, 500);
const [existing] = await tx
.select()
.from(refunds)
.where(eq(refunds.idempotencyKey, body.idempotencyKey));
if (existing) {
return c.json({ refundId: existing.stripeRefundId });
}
}
const result = await processRefund(id, body.amountCents); return c.json({ refundId: result.refundId });
if (!result) return c.json({ error: "Refund failed" }, 500);
await tx.insert(refunds).values({
invoiceId: id,
stripeRefundId: result.refundId,
idempotencyKey: body.idempotencyKey ?? null,
amountCents: body.amountCents ?? null,
});
return c.json({ refundId: result.refundId });
});
} }
); );
-11
View File
@@ -1,11 +0,0 @@
CREATE TABLE "refunds" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
"invoice_id" uuid NOT NULL REFERENCES "invoices"("id") ON DELETE RESTRICT,
"stripe_refund_id" text NOT NULL,
"idempotency_key" text UNIQUE,
"amount_cents" integer,
"created_at" timestamp NOT NULL DEFAULT NOW()
);
CREATE INDEX "idx_refunds_invoice_id" ON "refunds"("invoice_id");
CREATE INDEX "idx_refunds_idempotency_key" ON "refunds"("idempotency_key");
@@ -190,13 +190,6 @@
"when": 1775568867192, "when": 1775568867192,
"tag": "0026_stripe_payment", "tag": "0026_stripe_payment",
"breakpoints": true "breakpoints": true
},
{
"idx": 27,
"version": "7",
"when": 1775655267192,
"tag": "0027_refunds",
"breakpoints": true
} }
] ]
} }
-19
View File
@@ -300,25 +300,6 @@ export const invoiceTipSplits = pgTable(
(t) => [index("idx_invoice_tip_splits_invoice_id").on(t.invoiceId)] (t) => [index("idx_invoice_tip_splits_invoice_id").on(t.invoiceId)]
); );
// Refund records with idempotency key support
export const refunds = pgTable(
"refunds",
{
id: uuid("id").primaryKey().defaultRandom(),
invoiceId: uuid("invoice_id")
.notNull()
.references(() => invoices.id, { onDelete: "restrict" }),
stripeRefundId: text("stripe_refund_id").notNull(),
idempotencyKey: text("idempotency_key").unique(),
amountCents: integer("amount_cents"),
createdAt: timestamp("created_at").notNull().defaultNow(),
},
(t) => [
index("idx_refunds_invoice_id").on(t.invoiceId),
index("idx_refunds_idempotency_key").on(t.idempotencyKey),
]
);
// Tracks which reminder emails have been sent per appointment (prevents duplicates). // Tracks which reminder emails have been sent per appointment (prevents duplicates).
// reminder_type values: "confirmation", "24h", "2h" // reminder_type values: "confirmation", "24h", "2h"
export const reminderLogs = pgTable( export const reminderLogs = pgTable(