Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions app/api/resource-edits/methods.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import type { SupabaseClient } from "@supabase/supabase-js";
import type {
EditReviewStatus,
ResourceChangeLogEntry,
ResourceEdit,
ResourceEditCount,
ResourceEditQueueRow,
} from "~/types/ResourceEdit";
import type { ResourceEntry } from "~/types/ResourceEntry";
Expand Down Expand Up @@ -38,6 +40,46 @@ export const getResourceEditAPI = (client: SupabaseClient) => {

return (data ?? []) as ResourceEdit[];
},
/** Count of PENDING edits per resource — flags resources with multiple
* competing proposed edits. Backed by `resource_edit_counts`. */
getEditCounts: async () => {
const { data, error } = await client
.from("resource_edit_counts")
.select("*");

if (error) {
throw error;
}

return (data ?? []) as ResourceEditCount[];
},
/** Full history of decided (APPROVED/REJECTED) edits, most recent first
* within each resource. Backed by `resource_change_log`. */
getChangeLog: async () => {
const { data, error } = await client
.from("resource_change_log")
.select("*");

if (error) {
throw error;
}

return (data ?? []) as ResourceChangeLogEntry[];
},
/** Decided edit history for a single resource, e.g. for the review
* detail page's audit trail. Backed by `resource_change_log`. */
getChangeLogForResource: async (resourceId: number) => {
const { data, error } = await client
.from("resource_change_log")
.select("*")
.eq("resource_id", resourceId);

if (error) {
throw error;
}

return (data ?? []) as ResourceChangeLogEntry[];
},
getList: async (params: { review_status?: EditReviewStatus } = {}) => {
let query = table.select("*").order("submitted_at", { ascending: false });

Expand Down
57 changes: 32 additions & 25 deletions app/routes/authenticated/_layout.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Dashboard, Logout, RateReview } from "@mui/icons-material";
import { Box } from "@mui/material";
import { styled } from "@mui/material/styles";
import { Link, NavLink, Outlet } from "react-router";
import { Form, NavLink, Outlet } from "react-router";
import phlasklogo from "~/assets/PHLASK_v2.svg";
import { ThemeToggle } from "~/components/ThemeToggle";
import { WaveDivider } from "~/components/WaveDivider";
Expand Down Expand Up @@ -168,30 +168,37 @@ export default function DashboardLayout() {
</Box>
<ThemeToggle />
</Box>
<Box
component={Link}
to="/logout"
sx={(theme) => ({
display: "flex",
alignItems: "center",
gap: 1.25,
borderRadius: 3,
px: 2,
py: 1.25,
fontSize: "0.875rem",
fontWeight: 500,
textDecoration: "none",
color: navy[600],
transition: "background-color 0.2s ease",
"&:hover": { bgcolor: brand[50] },
...theme.applyStyles("dark", {
color: `${brand[100]}cc`,
"&:hover": { bgcolor: navy[800] },
}),
})}
>
<Logout fontSize="small" />
Logout
<Box component={Form} method="post" action="/logout">
<Box
component="button"
type="submit"
sx={(theme) => ({
display: "flex",
width: "100%",
alignItems: "center",
gap: 1.25,
borderRadius: 3,
border: "none",
bgcolor: "transparent",
px: 2,
py: 1.25,
fontSize: "0.875rem",
fontFamily: "inherit",
fontWeight: 500,
textAlign: "left",
cursor: "pointer",
color: navy[600],
transition: "background-color 0.2s ease",
"&:hover": { bgcolor: brand[50] },
...theme.applyStyles("dark", {
color: `${brand[100]}cc`,
"&:hover": { bgcolor: navy[800] },
}),
})}
>
<Logout fontSize="small" />
Logout
</Box>
</Box>
</Box>
</Box>
Expand Down
45 changes: 28 additions & 17 deletions app/routes/authenticated/dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,29 +29,40 @@ const RESOURCE_TYPES: ResourceType[] = ["WATER", "FOOD", "FORAGE", "BATHROOM"];
export const loader: LoaderFunction = async ({ request }) => {
const { client } = getDatabaseClient(request);
const editAPI = getResourceEditAPI(client);
const edits = await editAPI.getList();

// Every `resource_edits` row is either still PENDING (covered by the two
// queue views) or has been decided (covered by `resource_change_log`), so
// this trio fully reconstructs the stats below without ever scanning the
// full `resource_edits` table (with all its wide proposed-value columns).
const [pendingEdits, newResources, changeLog] = await Promise.all([
editAPI.getEditsQueue(),
editAPI.getNewResourcesQueue(),
editAPI.getChangeLog(),
]);

const pending = [...pendingEdits, ...newResources];

const submitterCounts = new Map<string, number>();
const approverCounts = new Map<string, number>();
const outstandingByType = new Map<string, number>();
let pendingCount = 0;

for (const edit of edits) {
const creator = edit.creator || "Unknown";
submitterCounts.set(creator, (submitterCounts.get(creator) ?? 0) + 1);
for (const edit of pending) {
const submitter = edit.submitted_by || "Unknown";
submitterCounts.set(submitter, (submitterCounts.get(submitter) ?? 0) + 1);
outstandingByType.set(
edit.resource_type,
(outstandingByType.get(edit.resource_type) ?? 0) + 1,
);
}

if (edit.review_status === "PENDING") {
pendingCount += 1;
outstandingByType.set(
edit.resource_type,
(outstandingByType.get(edit.resource_type) ?? 0) + 1,
);
}
for (const entry of changeLog) {
const submitter = entry.submitted_by || "Unknown";
submitterCounts.set(submitter, (submitterCounts.get(submitter) ?? 0) + 1);

if (edit.review_status === "APPROVED" && edit.reviewed_by) {
if (entry.review_status === "APPROVED" && entry.reviewed_by) {
approverCounts.set(
edit.reviewed_by,
(approverCounts.get(edit.reviewed_by) ?? 0) + 1,
entry.reviewed_by,
(approverCounts.get(entry.reviewed_by) ?? 0) + 1,
);
}
}
Expand All @@ -72,8 +83,8 @@ export const loader: LoaderFunction = async ({ request }) => {
}));

return {
totalEdits: edits.length,
pendingCount,
totalEdits: pending.length + changeLog.length,
pendingCount: pending.length,
topSubmitters,
topApprovers,
outstanding,
Expand Down
16 changes: 12 additions & 4 deletions app/routes/authenticated/logout.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { type LoaderFunction, redirect } from "react-router";
import {
type ActionFunction,
type LoaderFunction,
redirect,
} from "react-router";
import { getDatabaseClient } from "~/api/client.server";

export const loader: LoaderFunction = async ({ request }) => {
const { client } = getDatabaseClient(request);
// Signing out is a mutation, so it belongs in the action (POST), not a GET
// loader. A direct GET to this route just bounces back to the dashboard.
export const loader: LoaderFunction = () => redirect("/");

export const action: ActionFunction = async ({ request }) => {
const { client, headers } = getDatabaseClient(request);

await client.auth.signOut();

return redirect("/auth");
return redirect("/auth", { headers });
};
80 changes: 67 additions & 13 deletions app/routes/authenticated/reviews/detail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
TextField,
Typography,
} from "@mui/material";
import { useEffect, useState } from "react";
import { type SubmitEvent, useEffect, useState } from "react";
import {
type ActionFunction,
data,
Expand All @@ -33,7 +33,10 @@ import { getResourceEditAPI } from "~/api/resource-edits/methods";
import { getResourceEntryAPI } from "~/api/resources/methods";
import { userContext } from "~/context/user";
import { authMiddleware } from "~/middleware/auth";
import type { ResourceEdit } from "~/types/ResourceEdit";
import type {
ResourceChangeLogEntry,
ResourceEdit,
} from "~/types/ResourceEdit";
import type {
BathroomTag,
DispenserType,
Expand Down Expand Up @@ -173,16 +176,19 @@ export const loader: LoaderFunction = async ({ request, params }) => {
const edit = await editAPI.getById(id);

let resource: ResourceEntry | null = null;
let changeLog: ResourceChangeLogEntry[] = [];
if (edit.mapped_resource !== null) {
try {
const resourceAPI = getResourceEntryAPI(client);
resource = await resourceAPI.getById(edit.mapped_resource);
} catch {
resource = null;
}

changeLog = await editAPI.getChangeLogForResource(edit.mapped_resource);
}

return { edit, resource };
return { edit, resource, changeLog };
};

export const action: ActionFunction = async ({ request, params, context }) => {
Expand Down Expand Up @@ -238,9 +244,10 @@ export const action: ActionFunction = async ({ request, params, context }) => {
};

const ReviewDetail = () => {
const { edit, resource } = useLoaderData<{
const { edit, resource, changeLog } = useLoaderData<{
edit: ResourceEdit;
resource: ResourceEntry | null;
changeLog: ResourceChangeLogEntry[];
}>();
const actionData = useActionData<{ message?: string }>();
const fetcher = useFetcher<{ message?: string; ok?: boolean }>();
Expand Down Expand Up @@ -282,7 +289,13 @@ const ReviewDetail = () => {
value: EditableValues["bathroom"][K],
) => setValues((v) => ({ ...v, bathroom: { ...v.bathroom, [key]: value } }));

const handleSave = () => {
const handleSave = (event: SubmitEvent<HTMLFormElement>) => {
// The payload is a nested object (not flat form fields), so it's sent as
// JSON via the fetcher rather than a native form-encoded submission —
// still routed through a real <fetcher.Form> below for the submit
// semantics (Enter-to-submit, pending state, progressive enhancement).
event.preventDefault();

const payload: Partial<ResourceEntry> = {
name: values.name || null,
resource_type: values.resource_type,
Expand Down Expand Up @@ -380,6 +393,45 @@ const ReviewDetail = () => {
</Alert>
)}

{!isNew && changeLog.length > 0 && (
<Paper variant="outlined" sx={{ p: 2.5 }}>
<Typography variant="subtitle1" fontWeight={600} gutterBottom>
Change history
</Typography>
<TableContainer>
<Table size="small">
<TableBody>
{changeLog.map((entry) => (
<TableRow key={entry.edit_id}>
<TableCell>
<Chip
label={entry.review_status}
size="small"
color={statusChipColor(entry.review_status)}
/>
</TableCell>
<TableCell sx={{ color: "text.secondary" }}>
{entry.reviewed_by ?? "—"}
</TableCell>
<TableCell sx={{ color: "text.secondary" }}>
{entry.reviewed_at
? new Date(entry.reviewed_at).toLocaleString(
undefined,
{ dateStyle: "medium", timeStyle: "short" },
)
: "—"}
</TableCell>
<TableCell sx={{ color: "text.secondary" }}>
{entry.review_notes ?? "—"}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Paper>
)}

<TableContainer component={Paper} variant="outlined">
<Table size="small">
<TableBody>
Expand Down Expand Up @@ -776,14 +828,16 @@ const ReviewDetail = () => {

{isPending && (
<Stack direction="row" gap={2}>
<Button
variant="outlined"
onClick={handleSave}
loading={isSaving}
loadingPosition="start"
>
Save changes
</Button>
<fetcher.Form method="post" onSubmit={handleSave}>
<Button
type="submit"
variant="outlined"
loading={isSaving}
loadingPosition="start"
>
Save changes
</Button>
</fetcher.Form>

<Form method="post">
<Stack direction="row" gap={2}>
Expand Down
Loading