migrate: replace Supabase REST with Drizzle/pg in water-log/time-tracking/reports/etc (wave 4)

This commit is contained in:
2026-06-07 03:05:00 +00:00
parent 01198111ea
commit b8317a200e
16 changed files with 346 additions and 545 deletions
+11 -22
View File
@@ -1,15 +1,6 @@
"use server";
import { createClient as createServiceClient } from "@supabase/supabase-js";
function getServiceClient() {
const roleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!roleKey) throw new Error("SUPABASE_SERVICE_ROLE_KEY is not set");
return createServiceClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
roleKey,
);
}
import { pool } from "@/lib/db";
type AdminActionPayload = {
action_type: "create" | "update" | "delete";
@@ -30,35 +21,33 @@ type UserActivityPayload = {
export async function logAdminAction(payload: AdminActionPayload): Promise<void> {
try {
const service = getServiceClient();
await service.rpc("log_admin_action", {
p_payload: {
await pool.query("SELECT log_admin_action($1::jsonb)", [
JSON.stringify({
action_type: payload.action_type,
admin_id: payload.admin_id ?? null,
admin_email: payload.admin_email ?? null,
affected_user_id: payload.affected_user_id ?? null,
brand_id: payload.brand_id ?? null,
details: payload.details ?? {},
},
});
} catch (e) {
}),
]);
} catch {
// logging failed silently
}
}
export async function logUserActivity(payload: UserActivityPayload): Promise<void> {
try {
const service = getServiceClient();
await service.rpc("log_user_activity", {
p_payload: {
await pool.query("SELECT log_user_activity($1::jsonb)", [
JSON.stringify({
user_id: payload.user_id,
activity_type: payload.activity_type,
details: payload.details ?? {},
ip_address: payload.ip_address ?? null,
user_agent: payload.user_agent ?? null,
},
});
} catch (e) {
}),
]);
} catch {
// logging failed silently
}
}
+23 -32
View File
@@ -1,15 +1,6 @@
"use server";
import { createClient as createServiceClient } from "@supabase/supabase-js";
function getServiceClient() {
const roleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!roleKey) throw new Error("SUPABASE_SERVICE_ROLE_KEY not set");
return createServiceClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
roleKey,
);
}
import { query } from "@/lib/db";
export type ResetAdminPasswordResult =
| { success: true; tempPassword: string }
@@ -17,35 +8,35 @@ export type ResetAdminPasswordResult =
/**
* Emergency recovery action — only usable in development or when the caller
* already has service role access. Resets the password for the specified email
* already has direct DB access. Resets the password for the specified email
* and returns the temp password so it can be displayed to the user.
*
* Now that Supabase auth is gone, this hits the `users` table directly and
* calls the same `update_user_password` SECURITY DEFINER RPC used by the
* self-service password change action.
*/
export async function resetAdminPassword(
email: string,
newPassword: string
): Promise<ResetAdminPasswordResult> {
const service = getServiceClient();
// Look up auth user by email
const { data: authUsers, error: listError } = await service.auth.admin.listUsers();
if (listError || !authUsers?.users) {
return { success: false, error: "Could not list users: " + listError?.message };
}
const authUser = authUsers.users.find((u) => u.email?.toLowerCase() === email.toLowerCase());
if (!authUser) {
// Look up the user by email
const { rows } = await query<{ id: string }>(
"SELECT id FROM users WHERE email = $1 LIMIT 1",
[email.toLowerCase()],
);
const user = rows[0];
if (!user) {
return { success: false, error: "No auth user found for that email address." };
}
// Update password via service role
const { error: updateError } = await service.auth.admin.updateUserById(
authUser.id,
{ password: newPassword, email_confirm: true }
);
if (updateError) {
return { success: false, error: updateError.message };
// Update password via SECURITY DEFINER RPC
try {
await query("SELECT update_user_password($1, $2)", [user.id, newPassword]);
return { success: true, tempPassword: newPassword };
} catch (err) {
return {
success: false,
error: err instanceof Error ? err.message : "Failed to update password",
};
}
return { success: true, tempPassword: newPassword };
}
}
+16 -37
View File
@@ -1,7 +1,7 @@
import "server-only";
import { getAdminUser } from "@/lib/admin-permissions";
import { svcHeaders } from "@/lib/svc-headers";
import { pool } from "@/lib/db";
export type BrandListItem = {
id: string;
@@ -16,49 +16,28 @@ export type BrandListItem = {
* - platform_admin: all brands (queried directly from the `brands` table)
* - everyone else: brands in `adminUser.brand_ids`
* - empty array for unauthenticated / no-access admins
*
* This is a plain async function (not a server action) so it can be called
* from server components and server actions without the "use server" wrapper.
* The BrandSelector client component receives the result as a prop.
*/
export async function listBrandsForAdmin(): Promise<BrandListItem[]> {
const adminUser = await getAdminUser();
if (!adminUser) return [];
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !serviceKey) return [];
if (adminUser.role === "platform_admin") {
try {
const res = await fetch(
`${supabaseUrl}/rest/v1/brands?select=id,name,slug,logo_url&order=name`,
{ headers: svcHeaders(serviceKey), cache: "no-store" }
);
if (!res.ok) return [];
const data = await res.json();
return Array.isArray(data) ? data : [];
} catch {
return [];
}
}
if (adminUser.brand_ids.length === 0) return [];
// Use PostgREST `in` filter. The brand_ids are UUIDs, so the quoting
// pattern in the spec is safe; the inner quotes are required by PostgREST
// for UUID literals.
const filter = `id=in.(${adminUser.brand_ids
.map((id) => `"${id}"`)
.join(",")})`;
try {
const res = await fetch(
`${supabaseUrl}/rest/v1/brands?${filter}&select=id,name,slug,logo_url&order=name`,
{ headers: svcHeaders(serviceKey), cache: "no-store" }
if (adminUser.role === "platform_admin") {
const { rows } = await pool.query<BrandListItem>(
`SELECT id, name, slug, logo_url FROM brands ORDER BY name`,
);
return rows;
}
if (adminUser.brand_ids.length === 0) return [];
const { rows } = await pool.query<BrandListItem>(
`SELECT id, name, slug, logo_url FROM brands
WHERE id = ANY($1::uuid[])
ORDER BY name`,
[adminUser.brand_ids],
);
if (!res.ok) return [];
const data = await res.json();
return Array.isArray(data) ? data : [];
return rows;
} catch {
return [];
}
+83 -79
View File
@@ -1,6 +1,6 @@
"use server";
import { svcHeaders } from "@/lib/svc-headers";
import { pool } from "@/lib/db";
export type CartItem = {
id: string;
@@ -64,9 +64,6 @@ export async function createOrder(
brandId?: string,
shippingAddress?: ShippingAddress
): Promise<CheckoutResult> {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
// ── Calculate tax if brand collects tax ─────────────────────────────────
let taxAmount = 0;
let taxRate = 0;
@@ -90,33 +87,22 @@ export async function createOrder(
}
}
const response = await fetch(
`${supabaseUrl}/rest/v1/rpc/create_order_with_items`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json", Prefer: "return=representation" },
body: JSON.stringify({
p_idempotency_key: idempotencyKey,
p_customer_name: customerName,
p_customer_email: customerEmail,
p_customer_phone: customerPhone,
p_stop_id: stopId,
p_items: items,
p_tax_amount: taxAmount,
p_tax_rate: taxRate,
p_tax_location: taxLocation || null,
}),
}
const { rows } = await pool.query<{ create_order_with_items: CreatedOrder | null }>(
`SELECT create_order_with_items($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9) AS "create_order_with_items"`,
[
idempotencyKey,
customerName,
customerEmail,
customerPhone,
stopId,
JSON.stringify(items),
taxAmount,
taxRate,
taxLocation || null,
],
);
const data = rows[0]?.create_order_with_items;
if (!response.ok) {
const err = await response.json().catch(() => ({ message: "Unknown error" }));
return { success: false, error: err.message ?? "Failed to create order" };
}
const data = await response.json();
// RPC returns a JSONB object with order + items
if (!data || !data.id) {
return { success: false, error: "Order created but data not returned" };
}
@@ -124,14 +110,20 @@ export async function createOrder(
// Send order receipt email
try {
const { sendOrderReceiptEmail } = await import("@/lib/email-service");
const rawItems = data.items ?? [];
const taxAmount = (data as { tax_amount?: number }).tax_amount ?? 0;
await sendOrderReceiptEmail({
customerName,
customerEmail,
orderId: data.id,
items: data.items ?? [],
items: rawItems.map((i) => ({
name: i.product_name,
quantity: i.quantity,
price: i.price,
})),
subtotal: data.subtotal ?? 0,
taxAmount: data.tax_amount ?? 0,
total: (data.subtotal ?? 0) + (data.tax_amount ?? 0),
taxAmount,
total: (data.subtotal ?? 0) + taxAmount,
fulfillment: items.some((i) => i.fulfillment === "ship") ? "ship" : "pickup",
stopCity: data.stop_city ?? undefined,
stopState: data.stop_state ?? undefined,
@@ -140,31 +132,22 @@ export async function createOrder(
stopLocation: data.stop_location ?? undefined,
brandName: "Tuxedo Corn",
});
} catch (e) {
} catch {
// Email failure should not fail the order
}
return { success: true, order: data as CreatedOrder };
return { success: true, order: data };
}
// ── Cart Persistence ──────────────────────────────────────────────────────────
export async function getServerCart(userId: string): Promise<CartItem[]> {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
try {
const response = await fetch(
`${supabaseUrl}/rest/v1/rpc/get_user_cart`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_user_id: userId }),
}
const { rows } = await pool.query<{ get_user_cart: CartItem[] | null }>(
`SELECT get_user_cart($1) AS "get_user_cart"`,
[userId],
);
if (!response.ok) return [];
const data = await response.json();
const data = rows[0]?.get_user_cart;
return Array.isArray(data) ? data : [];
} catch {
return [];
@@ -177,24 +160,15 @@ export async function mergeLocalCart(
): Promise<{ merged: CartItem[] }> {
if (!localCart || localCart.length === 0) return { merged: [] };
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
// Fetch server cart
let serverCart: CartItem[] = [];
try {
const response = await fetch(
`${supabaseUrl}/rest/v1/rpc/get_user_cart`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_user_id: userId }),
}
const { rows } = await pool.query<{ get_user_cart: CartItem[] | null }>(
`SELECT get_user_cart($1) AS "get_user_cart"`,
[userId],
);
if (response.ok) {
const data = await response.json();
serverCart = Array.isArray(data) ? data : [];
}
const data = rows[0]?.get_user_cart;
serverCart = Array.isArray(data) ? data : [];
} catch {
// proceed with local cart only
}
@@ -227,13 +201,9 @@ export async function mergeLocalCart(
// Persist merged cart to server
try {
await fetch(
`${supabaseUrl}/rest/v1/rpc/upsert_user_cart`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_user_id: userId, p_items: merged }),
}
await pool.query(
`SELECT upsert_user_cart($1, $2::jsonb)`,
[userId, JSON.stringify(merged)],
);
} catch {
// best-effort — localStorage is still source of truth for now
@@ -243,19 +213,53 @@ export async function mergeLocalCart(
}
export async function clearServerCart(userId: string): Promise<void> {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
try {
await fetch(
`${supabaseUrl}/rest/v1/rpc/clear_user_cart`,
{
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({ p_user_id: userId }),
}
await pool.query(
`SELECT clear_user_cart($1)`,
[userId],
);
} catch {
// ignore
}
}
}
// ── Stop picker (used by cart + checkout client components) ───────────────
export type PublicStop = {
id: string;
city: string;
state: string;
date: string;
time: string;
location: string;
brand_id: string;
};
export async function getPublicStopsForBrand(brandId: string): Promise<PublicStop[]> {
const { rows } = await pool.query<PublicStop>(
`SELECT id, city, state, date, time, location, brand_id
FROM stops
WHERE active = true AND brand_id = $1
ORDER BY date`,
[brandId],
);
return rows;
}
export type ProductAvailability = {
product_id: string;
is_available: boolean;
};
export async function checkStopProductAvailability(
stopId: string,
productIds: string[]
): Promise<ProductAvailability[]> {
if (!productIds || productIds.length === 0) return [];
const { rows } = await pool.query<{ check_stop_product_availability: ProductAvailability[] | null }>(
`SELECT check_stop_product_availability($1, $2::uuid[]) AS "check_stop_product_availability"`,
[stopId, productIds],
);
const data = rows[0]?.check_stop_product_availability;
return Array.isArray(data) ? data : [];
}
+30 -60
View File
@@ -1,10 +1,7 @@
"use server";
import { getAdminUser } from "@/lib/admin-permissions";
import { svcHeaders } from "@/lib/svc-headers";
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
import { pool } from "@/lib/db";
// ── Types ────────────────────────────────────────────────────────────────────
@@ -65,25 +62,22 @@ export type CreatePainLogData = {
description?: string | null;
};
// ── Internal fetch helper ────────────────────────────────────────────────────
// ── Internal RPC helper ──────────────────────────────────────────────────────
async function platformRPC<T>(rpcName: string, body: Record<string, unknown> = {}): Promise<T> {
async function platformRPC<T>(rpcName: string): Promise<T> {
const adminUser = await getAdminUser();
if (!adminUser) throw new Error("Not authenticated");
if (adminUser.role !== "platform_admin") throw new Error("Access denied: platform admin only");
const response = await fetch(`${supabaseUrl}/rest/v1/rpc/${rpcName}`, {
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const { rows } = await pool.query<Record<string, T>>(
`SELECT ${rpcName}() AS "${rpcName}"`,
);
if (!response.ok) {
const err = await response.text();
throw new Error(`RPC ${rpcName} failed: ${err}`);
const data = rows[0]?.[rpcName];
if (data == null) {
return null as T;
}
return response.json() as Promise<T>;
return data as T;
}
// ── Platform actions ─────────────────────────────────────────────────────────
@@ -104,19 +98,11 @@ export async function getPainLog(): Promise<PainLogItem[]> {
const adminUser = await getAdminUser();
if (!adminUser) throw new Error("Not authenticated");
const response = await fetch(
`${supabaseUrl}/rest/v1/founder_pain_log_platform?select=*`,
{
headers: svcHeaders(supabaseKey),
}
const { rows } = await pool.query<PainLogItem>(
`SELECT * FROM founder_pain_log_platform ORDER BY created_at DESC`,
);
if (!response.ok) {
const err = await response.text();
throw new Error(`Failed to fetch pain log: ${err}`);
}
return response.json() as Promise<PainLogItem[]>;
return rows;
}
export async function createPainLogItem(data: CreatePainLogData): Promise<{ success: boolean; error?: string }> {
@@ -125,22 +111,17 @@ export async function createPainLogItem(data: CreatePainLogData): Promise<{ succ
if (!adminUser) return { success: false, error: "Not authenticated" };
if (adminUser.role !== "platform_admin") return { success: false, error: "Access denied" };
const response = await fetch(`${supabaseUrl}/rest/v1/founder_pain_log`, {
method: "POST",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json", Prefer: "return=representation" },
body: JSON.stringify({
brand_id: data.brand_id || null,
severity: data.severity,
category: data.category,
title: data.title,
description: data.description || null,
}),
});
if (!response.ok) {
const err = await response.text();
return { success: false, error: err };
}
await pool.query(
`INSERT INTO founder_pain_log (brand_id, severity, category, title, description)
VALUES ($1, $2, $3, $4, $5)`,
[
data.brand_id || null,
data.severity,
data.category,
data.title,
data.description || null,
],
);
return { success: true };
} catch (e) {
@@ -154,26 +135,15 @@ export async function resolvePainLogItem(id: string): Promise<{ success: boolean
if (!adminUser) return { success: false, error: "Not authenticated" };
if (adminUser.role !== "platform_admin") return { success: false, error: "Access denied" };
const response = await fetch(
`${supabaseUrl}/rest/v1/founder_pain_log?id=eq.${id}`,
{
method: "PATCH",
headers: { ...svcHeaders(supabaseKey), "Content-Type": "application/json" },
body: JSON.stringify({
status: "resolved",
resolved_at: new Date().toISOString(),
resolved_by: adminUser.id,
}),
}
await pool.query(
`UPDATE founder_pain_log
SET status = 'resolved', resolved_at = now(), resolved_by = $2
WHERE id = $1`,
[id, adminUser.id],
);
if (!response.ok) {
const err = await response.text();
return { success: false, error: err };
}
return { success: true };
} catch (e) {
return { success: false, error: String(e) };
}
}
}