Saved filters on list pages (1.49.2)
Manage registrations, Users, Events and Reports: save the current filters under a name, apply one with a click, star one as the default for the page (not applied over a deep link). Per person, stored on the server, removed when an account is anonymised. /api/saved-filters. Migration 20261028180000_saved_filters. Completes roadmap section 9. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,6 +15,7 @@ import { AreaTrendChart } from "@/components/charts/AreaTrendChart";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { registrationOptionUnitPrice } from "@/lib/pricing";
|
||||
import { CampusFilter, matchesCampus } from "@/components/shared/CampusFilter";
|
||||
import { SavedFilters } from "@/components/shared/SavedFilters";
|
||||
import type { ConsentRow, Event, EventCashup, EventFinancials, EventSeries, MedicalRow, Payment, Registration, SeriesComparison, Ticket, UserSummary } from "@/types";
|
||||
|
||||
const METHOD_KEYS = ["cash", "card", "eft", "other"] as const;
|
||||
@@ -1512,15 +1513,29 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
|
||||
)}
|
||||
{error && <div className="p-3 mb-3 border rounded bg-red-50 text-red-700 text-sm">{error}</div>}
|
||||
|
||||
<CampusFilter
|
||||
value={campus}
|
||||
onChange={v => { setCampus(v); setSelectedEventIds([]); }}
|
||||
withChurchWide
|
||||
everyLabel="All campuses (church-wide total)"
|
||||
className="mb-3"
|
||||
id="reports-campus"
|
||||
mine
|
||||
/>
|
||||
<div className="flex flex-wrap items-start gap-3 mb-3">
|
||||
<CampusFilter
|
||||
value={campus}
|
||||
onChange={v => { setCampus(v); setSelectedEventIds([]); }}
|
||||
withChurchWide
|
||||
everyLabel="All campuses (church-wide total)"
|
||||
id="reports-campus"
|
||||
mine
|
||||
/>
|
||||
<SavedFilters
|
||||
page="reports"
|
||||
value={{ report, events: selectedEventIds, from: dateFrom, to: dateTo, campus, past: showPastEvents, inactive: showInactiveEvents, closed: showClosedEvents }}
|
||||
onApply={p => {
|
||||
if (typeof p.report === "string" && REPORTS.some(r => r.key === p.report)) setReport(p.report as ReportKey);
|
||||
setCampus(String(p.campus || ""));
|
||||
setShowPastEvents(p.past === true); setShowInactiveEvents(p.inactive === true); setShowClosedEvents(p.closed !== false);
|
||||
setSelectedEventIds(Array.isArray(p.events) ? p.events : []);
|
||||
setDateFrom(String(p.from || "")); setDateTo(String(p.to || ""));
|
||||
setReady(false);
|
||||
}}
|
||||
skipDefault={!!searchParams.get("report")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ReportsShell
|
||||
events={filteredEvents}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Bookmark, Star, Trash2, Check } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
|
||||
export type FilterValues = Record<string, string | number | boolean | string[]>;
|
||||
type Saved = { id: string; name: string; params: FilterValues; isDefault: boolean };
|
||||
|
||||
/**
|
||||
* Saved filters on a list page (1.49.2): apply one with a click, save the current filters under a
|
||||
* name, star one as the default (applied when the page opens, unless the link already says what
|
||||
* to show — `skipDefault`). Stored per person on the server.
|
||||
*/
|
||||
export function SavedFilters({ page, value, onApply, skipDefault = false, className = "" }: {
|
||||
page: "registrations" | "users" | "events" | "reports";
|
||||
value: FilterValues;
|
||||
onApply: (params: FilterValues) => void;
|
||||
skipDefault?: boolean;
|
||||
className?: string;
|
||||
}) {
|
||||
const { token } = useAuth();
|
||||
const [list, setList] = useState<Saved[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [asDefault, setAsDefault] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [applied, setApplied] = useState<string | null>(null);
|
||||
const defaultDone = useRef(false);
|
||||
const boxRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!token) return;
|
||||
try {
|
||||
const rows = await apiFetch<Saved[]>(`/api/saved-filters?page=${page}`, { authToken: token });
|
||||
setList(rows);
|
||||
// The default, once, when the page opens.
|
||||
if (!defaultDone.current) {
|
||||
defaultDone.current = true;
|
||||
const def = rows.find(r => r.isDefault);
|
||||
if (def && !skipDefault) { onApply(def.params); setApplied(def.id); }
|
||||
}
|
||||
} catch { /* the page works without them */ }
|
||||
// onApply/skipDefault are read once, for the default.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [token, page]);
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
// Close when clicking elsewhere.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (e: MouseEvent) => { if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false); };
|
||||
document.addEventListener("mousedown", onDown);
|
||||
return () => document.removeEventListener("mousedown", onDown);
|
||||
}, [open]);
|
||||
|
||||
const act = async (fn: () => Promise<unknown>) => {
|
||||
setError(null);
|
||||
try { await fn(); await load(); } catch (e) { setError(errorMessage(e) || "Couldn't save that"); }
|
||||
};
|
||||
const save = () => act(async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const row = await apiFetch<Saved>("/api/saved-filters", { method: "POST", authToken: token || undefined, body: { page, name, params: value, isDefault: asDefault } });
|
||||
setApplied(row.id); setName(""); setAsDefault(false);
|
||||
} finally { setSaving(false); }
|
||||
});
|
||||
const toggleDefault = (f: Saved) => act(() => apiFetch(`/api/saved-filters/${f.id}`, { method: "PUT", authToken: token || undefined, body: { isDefault: !f.isDefault } }));
|
||||
const remove = (f: Saved) => act(async () => {
|
||||
if (!confirm(`Delete the saved filter "${f.name}"?`)) return;
|
||||
await apiFetch(`/api/saved-filters/${f.id}`, { method: "DELETE", authToken: token || undefined });
|
||||
});
|
||||
|
||||
const current = list.find(f => f.id === applied);
|
||||
return (
|
||||
<div className={`relative inline-block ${className}`} ref={boxRef} data-testid="saved-filters">
|
||||
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open}
|
||||
className="inline-flex items-center gap-1.5 text-sm px-2.5 py-1.5 rounded border bg-white hover:bg-gray-50">
|
||||
<Bookmark className="w-4 h-4" /> {current ? current.name : "Saved filters"}{list.length > 0 && !current ? ` (${list.length})` : ""}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute z-30 mt-1 w-72 right-0 sm:left-0 sm:right-auto rounded-xl border bg-white shadow-lg p-2 space-y-2" role="dialog" aria-label="Saved filters">
|
||||
{list.length === 0 ? (
|
||||
<p className="text-xs text-gray-500 px-1">No saved filters yet. Set the filters the way you like them and save them here.</p>
|
||||
) : (
|
||||
<ul className="max-h-60 overflow-y-auto">
|
||||
{list.map(f => (
|
||||
<li key={f.id} className="flex items-center gap-1 rounded hover:bg-gray-50">
|
||||
<button type="button" className="flex-1 text-left text-sm px-2 py-1.5 truncate" onClick={() => { onApply(f.params); setApplied(f.id); setOpen(false); }}>
|
||||
{applied === f.id && <Check className="inline w-3.5 h-3.5 mr-1 text-brand-600" />}{f.name}
|
||||
</button>
|
||||
<button type="button" onClick={() => toggleDefault(f)} title={f.isDefault ? "Default — click to stop" : "Make this the default when the page opens"} aria-label={f.isDefault ? `${f.name} is the default` : `Make ${f.name} the default`} className="p-1">
|
||||
<Star className={`w-4 h-4 ${f.isDefault ? "fill-amber-400 text-amber-500" : "text-gray-300 hover:text-gray-500"}`} />
|
||||
</button>
|
||||
<button type="button" onClick={() => remove(f)} aria-label={`Delete ${f.name}`} className="p-1 text-gray-300 hover:text-red-600"><Trash2 className="w-4 h-4" /></button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<div className="border-t pt-2 space-y-1.5">
|
||||
<label className="block text-xs text-gray-600" htmlFor={`save-filter-${page}`}>Save the current filters as</label>
|
||||
<div className="flex gap-1.5">
|
||||
<input id={`save-filter-${page}`} className="flex-1 min-w-0 border rounded px-2 py-1 text-sm" placeholder="e.g. Camp — unpaid" value={name} onChange={e => setName(e.target.value)} onKeyDown={e => { if (e.key === "Enter" && name.trim()) save(); }} />
|
||||
<button type="button" disabled={saving || !name.trim()} onClick={save} className="px-2.5 py-1 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50">Save</button>
|
||||
</div>
|
||||
<label className="flex items-center gap-1.5 text-xs text-gray-600"><input type="checkbox" checked={asDefault} onChange={e => setAsDefault(e.target.checked)} /> Use when this page opens</label>
|
||||
{error && <p className="text-xs text-red-600">{error}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user