diff --git a/apps/web/src/components/dashboard-ui.tsx b/apps/web/src/components/dashboard-ui.tsx index a014006..fbf398d 100644 --- a/apps/web/src/components/dashboard-ui.tsx +++ b/apps/web/src/components/dashboard-ui.tsx @@ -12,6 +12,7 @@ import { Label } from "@minmon/ui/components/label"; import { Select, SelectContent, + SelectGroup, SelectItem, SelectTrigger, SelectValue, @@ -28,8 +29,8 @@ import { } from "@minmon/ui/components/table"; import { Textarea } from "@minmon/ui/components/textarea"; import { Link } from "@tanstack/react-router"; -import { Check, ChevronRight, Trash2 } from "lucide-react"; -import { useEffect, useState, type ReactNode } from "react"; +import { Check, ChevronLeft, ChevronRight, Trash2, X } from "lucide-react"; +import { useEffect, useId, useMemo, useState, type ReactNode } from "react"; type BadgeVariant = "neutral" | "success" | "warning" | "destructive" | "info"; @@ -80,6 +81,7 @@ export function ResourceListCard({ items, emptyTitle, emptyDescription, + controls, }: { title: string; description: string; @@ -87,15 +89,139 @@ export function ResourceListCard({ items: TItem[]; emptyTitle: string; emptyDescription: string; + controls?: { + search: { + placeholder: string; + getText: (item: TItem) => string; + }; + filter?: { + label: string; + allLabel: string; + options: readonly { value: string; label: string }[]; + getValue: (item: TItem) => string | string[]; + }; + initialPageSize?: number; + pageSizeOptions?: readonly number[]; + }; }) { + const allFilterValue = "__all"; + const controlId = useId(); + const searchInputId = `${controlId}-search`; + const filterInputId = `${controlId}-filter`; + const pageSizeOptions = controls?.pageSizeOptions ?? [5, 10, 25]; + const [searchQuery, setSearchQuery] = useState(""); + const [filterValue, setFilterValue] = useState(allFilterValue); + const [pageSize, setPageSize] = useState(controls?.initialPageSize ?? 10); + const [page, setPage] = useState(1); + + const filteredItems = useMemo(() => { + if (!controls) return items; + + const normalizedQuery = searchQuery.trim().toLocaleLowerCase(); + + return items.filter((item) => { + const matchesSearch = + !normalizedQuery || controls.search.getText(item).toLocaleLowerCase().includes(normalizedQuery); + const itemFilterValue = controls.filter?.getValue(item); + const matchesFilter = + !controls.filter || + filterValue === allFilterValue || + (Array.isArray(itemFilterValue) + ? itemFilterValue.includes(filterValue) + : itemFilterValue === filterValue); + + return matchesSearch && matchesFilter; + }); + }, [controls, filterValue, items, searchQuery]); + + const pageCount = controls ? Math.max(1, Math.ceil(filteredItems.length / pageSize)) : 1; + const currentPage = Math.min(page, pageCount); + const visibleItems = controls + ? filteredItems.slice((currentPage - 1) * pageSize, currentPage * pageSize) + : filteredItems; + const hasActiveControls = Boolean(searchQuery || filterValue !== allFilterValue); + const selectedFilterLabel = controls?.filter + ? filterValue === allFilterValue + ? controls.filter.allLabel + : controls.filter.options.find((option) => option.value === filterValue)?.label + : undefined; + const firstVisibleItem = filteredItems.length ? (currentPage - 1) * pageSize + 1 : 0; + const lastVisibleItem = Math.min(currentPage * pageSize, filteredItems.length); + + useEffect(() => { + if (page > pageCount) { + setPage(pageCount); + } + }, [page, pageCount]); + + function resetControls() { + setSearchQuery(""); + setFilterValue(allFilterValue); + setPage(1); + } + return ( {title} {description} + {controls && items.length ? ( +
+
+ + { + setSearchQuery(event.target.value); + setPage(1); + }} + /> +
+ {controls.filter ? ( +
+ + +
+ ) : null} + {hasActiveControls ? ( + + ) : null} +
+ ) : null}
- {items.length ? ( + {visibleItems.length ? ( @@ -108,7 +234,7 @@ export function ResourceListCard({ - {items.map((item) => ( + {visibleItems.map((item) => ( {columns.map((column) => ( @@ -120,10 +246,74 @@ export function ResourceListCard({
+ ) : items.length ? ( + + Clear search and filter + + } + className="border-0" + /> ) : ( )}
+ {controls && items.length ? ( + +

+ Showing {firstVisibleItem}–{lastVisibleItem} of {filteredItems.length} +

+
+ + + Page {currentPage} of {pageCount} + + + +
+
+ ) : null}
); } @@ -329,11 +519,13 @@ export function SelectField({ - {options.map((option) => ( - - {option.label} - - ))} + + {options.map((option) => ( + + {option.label} + + ))} + diff --git a/apps/web/src/routes/dashboard.domains.tsx b/apps/web/src/routes/dashboard.domains.tsx index ff1d559..c2f2961 100644 --- a/apps/web/src/routes/dashboard.domains.tsx +++ b/apps/web/src/routes/dashboard.domains.tsx @@ -123,6 +123,32 @@ function RouteComponent() { items={domains.data} emptyTitle="No domains added" emptyDescription="Create a domain after adding a service." + controls={{ + search: { + placeholder: "Search domain, service, or IP address…", + getText: (item) => + [ + item.name, + serviceMap.get(item.serviceId), + item.expectedServerIp, + item.lastResolvedIp, + ...item.lastResolvedIps, + item.remarks, + ] + .filter(Boolean) + .join(" "), + }, + filter: { + label: "Filter by DNS status", + allLabel: "All DNS statuses", + options: [ + { value: "MATCH", label: "Match" }, + { value: "MISMATCH", label: "Mismatch" }, + { value: "UNRESOLVED", label: "Unresolved" }, + ], + getValue: (item) => item.resolutionStatus, + }, + }} /> ); diff --git a/apps/web/src/routes/dashboard.domains_.$domainId.tsx b/apps/web/src/routes/dashboard.domains_.$domainId.tsx index 17248a7..592ab62 100644 --- a/apps/web/src/routes/dashboard.domains_.$domainId.tsx +++ b/apps/web/src/routes/dashboard.domains_.$domainId.tsx @@ -1,4 +1,4 @@ -import { DetailCard, FormCard, PageSection, QueryStateCard, SelectField, TextAreaField, TextField } from "@/components/dashboard-ui"; +import { DetailCard, FormCard, PageSection, QueryStateCard, ResourceListCard, SelectField, TextAreaField, TextField } from "@/components/dashboard-ui"; import { queryClient, trpc, trpcClient } from "@/utils/trpc"; import { Button } from "@minmon/ui/components/button"; import { StatusBadge } from "@minmon/ui/components/status-badge"; @@ -29,6 +29,7 @@ function RouteComponent() { const { domainId } = Route.useParams(); const navigate = useNavigate(); const domain = useQuery(trpc.domains.byId.queryOptions({ id: domainId })); + const history = useQuery(trpc.domains.history.queryOptions({ id: domainId })); const services = useQuery(trpc.domains.serviceOptions.queryOptions()); const updateDomain = useMutation({ @@ -51,6 +52,7 @@ function RouteComponent() { ); } await queryClient.invalidateQueries({ queryKey: trpc.domains.byId.queryKey({ id: domainId }) }); + await queryClient.invalidateQueries({ queryKey: trpc.domains.history.queryKey({ id: domainId }) }); await queryClient.invalidateQueries({ queryKey: trpc.domains.list.queryKey() }); }, onError: (error) => toast.error(error.message), @@ -60,6 +62,7 @@ function RouteComponent() { onSuccess: async () => { toast.success("DNS check completed"); await queryClient.invalidateQueries({ queryKey: trpc.domains.byId.queryKey({ id: domainId }) }); + await queryClient.invalidateQueries({ queryKey: trpc.domains.history.queryKey({ id: domainId }) }); await queryClient.invalidateQueries({ queryKey: trpc.domains.list.queryKey() }); }, onError: (error) => toast.error(error.message), @@ -119,6 +122,82 @@ function RouteComponent() { /> + + {history.isLoading ? ( + + ) : history.isError || !history.data ? ( + + ) : ( + ( + {new Date(item.checkedAt).toLocaleString()} + ), + }, + { + key: "status", + header: "Status", + className: "w-36", + render: (item: (typeof history.data)[number]) => ( + {item.status} + ), + }, + { + key: "expectedServerIp", + header: "Expected IP", + render: (item: (typeof history.data)[number]) => item.expectedServerIp, + }, + { + key: "resolvedIps", + header: "Resolved IPv4", + render: (item: (typeof history.data)[number]) => item.resolvedIps.join(", ") || "-", + }, + { + key: "message", + header: "Result", + render: (item: (typeof history.data)[number]) => + item.message || + (item.status === "MATCH" + ? "Expected IP found" + : "Expected IP not found in the A records"), + }, + ]} + items={history.data} + emptyTitle="No DNS checks yet" + emptyDescription="Run Check DNS to create the first history entry for this domain." + controls={{ + search: { + placeholder: "Search IP address, status, or result…", + getText: (item) => + [item.status, item.expectedServerIp, ...item.resolvedIps, item.message] + .filter(Boolean) + .join(" "), + }, + filter: { + label: "Filter by DNS status", + allLabel: "All DNS statuses", + options: [ + { value: "MATCH", label: "Match" }, + { value: "MISMATCH", label: "Mismatch" }, + { value: "UNRESOLVED", label: "Unresolved" }, + ], + getValue: (item) => item.status, + }, + initialPageSize: 5, + }} + /> + )} + +
{ diff --git a/apps/web/src/routes/dashboard.notes.tsx b/apps/web/src/routes/dashboard.notes.tsx index 7152a4d..b527687 100644 --- a/apps/web/src/routes/dashboard.notes.tsx +++ b/apps/web/src/routes/dashboard.notes.tsx @@ -89,6 +89,19 @@ function RouteComponent() { items={notes.data} emptyTitle="No notes yet" emptyDescription="Add a note to document maintenance, incidents, or general server information." + controls={{ + search: { + placeholder: "Search title, note, category, or server…", + getText: (item) => + [item.title, item.content, item.category, serverMap.get(item.serverId)].filter(Boolean).join(" "), + }, + filter: { + label: "Filter by server", + allLabel: "All servers", + options: servers.data.map((item) => ({ value: item.id, label: item.name })), + getValue: (item) => item.serverId, + }, + }} /> ); diff --git a/apps/web/src/routes/dashboard.servers.tsx b/apps/web/src/routes/dashboard.servers.tsx index 7c2c2cc..06728f1 100644 --- a/apps/web/src/routes/dashboard.servers.tsx +++ b/apps/web/src/routes/dashboard.servers.tsx @@ -112,6 +112,33 @@ function RouteComponent() { items={servers.data} emptyTitle="No servers added" emptyDescription="Add your first server to start managing services, notes, and domains." + controls={{ + search: { + placeholder: "Search name, IP, location, or provider…", + getText: (item) => + [ + item.name, + item.primaryIpAddress, + item.secondaryIpAddress, + item.operatingSystem, + item.location, + item.provider, + item.description, + ] + .filter(Boolean) + .join(" "), + }, + filter: { + label: "Filter by server status", + allLabel: "All statuses", + options: [ + { value: "active", label: "Active" }, + { value: "maintenance", label: "Maintenance" }, + { value: "inactive", label: "Inactive" }, + ], + getValue: (item) => item.status, + }, + }} /> ); diff --git a/apps/web/src/routes/dashboard.servers_.$serverId.tsx b/apps/web/src/routes/dashboard.servers_.$serverId.tsx index 03c01fd..6acf02a 100644 --- a/apps/web/src/routes/dashboard.servers_.$serverId.tsx +++ b/apps/web/src/routes/dashboard.servers_.$serverId.tsx @@ -159,6 +159,12 @@ function RouteComponent() { items={notes.data} emptyTitle="No notes for this server" emptyDescription="Add a note to document maintenance, incidents, or internal server context." + controls={{ + search: { + placeholder: "Search attached notes…", + getText: (item) => [item.title, item.content, item.category].filter(Boolean).join(" "), + }, + }} /> )} diff --git a/apps/web/src/routes/dashboard.services.tsx b/apps/web/src/routes/dashboard.services.tsx index 1aec048..8f00b82 100644 --- a/apps/web/src/routes/dashboard.services.tsx +++ b/apps/web/src/routes/dashboard.services.tsx @@ -109,6 +109,33 @@ function RouteComponent() { items={services.data} emptyTitle="No services added" emptyDescription="Create a service after adding at least one server." + controls={{ + search: { + placeholder: "Search service, server, port, or protocol…", + getText: (item) => + [ + item.name, + serverMap.get(item.serverId), + item.internalPort, + item.externalPort, + item.protocol, + item.type, + item.description, + ] + .filter((value) => value !== null && value !== undefined) + .join(" "), + }, + filter: { + label: "Filter by service status", + allLabel: "All statuses", + options: [ + { value: "active", label: "Active" }, + { value: "maintenance", label: "Maintenance" }, + { value: "down", label: "Down" }, + ], + getValue: (item) => item.status, + }, + }} /> ); diff --git a/apps/web/src/routes/dashboard.users.tsx b/apps/web/src/routes/dashboard.users.tsx index 70f789c..0fd368f 100644 --- a/apps/web/src/routes/dashboard.users.tsx +++ b/apps/web/src/routes/dashboard.users.tsx @@ -157,6 +157,18 @@ function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permi items={users.data} emptyTitle="No users found" emptyDescription="Users appear here after they sign up or are seeded." + controls={{ + search: { + placeholder: "Search name, email, or role…", + getText: (item) => [item.name, item.email, ...item.roles.map((role) => role.name)].join(" "), + }, + filter: { + label: "Filter by role", + allLabel: "All roles", + options: roles.map((role) => ({ value: role.id, label: role.name })), + getValue: (item) => item.roles.map((role) => role.id), + }, + }} /> ); } diff --git a/packages/api/src/lib/domain-check.ts b/packages/api/src/lib/domain-check.ts index 48c9fca..beca956 100644 --- a/packages/api/src/lib/domain-check.ts +++ b/packages/api/src/lib/domain-check.ts @@ -1,4 +1,4 @@ -import { createDb, domain } from "@minmon/db"; +import { createDb, domain, domainCheckHistory } from "@minmon/db"; import { eq } from "drizzle-orm"; import { resolve4 } from "node:dns/promises"; import { Effect } from "effect"; @@ -46,22 +46,41 @@ export async function persistDomainCheck( database: ReturnType, input: { domainId: string; + expectedServerIp: string; result: DomainCheckResult; }, ) { - const [updatedDomain] = await database - .update(domain) - .set({ - resolutionStatus: input.result.status, - lastResolvedIps: input.result.resolvedIps, - lastResolvedIp: input.result.resolvedIps[0] ?? null, - lastCheckedAt: input.result.checkedAt, - lastCheckMessage: input.result.message, - }) - .where(eq(domain.id, input.domainId)) - .returning(); + return database.transaction(async (transaction) => { + const [historyEntry] = await transaction + .insert(domainCheckHistory) + .values({ + id: crypto.randomUUID(), + domainId: input.domainId, + expectedServerIp: input.expectedServerIp, + status: input.result.status, + resolvedIps: input.result.resolvedIps, + message: input.result.message, + checkedAt: input.result.checkedAt, + }) + .returning(); - return updatedDomain ?? null; + const [updatedDomain] = await transaction + .update(domain) + .set({ + resolutionStatus: input.result.status, + lastResolvedIps: input.result.resolvedIps, + lastResolvedIp: input.result.resolvedIps[0] ?? null, + lastCheckedAt: input.result.checkedAt, + lastCheckMessage: input.result.message, + }) + .where(eq(domain.id, input.domainId)) + .returning(); + + return { + domain: updatedDomain ?? null, + historyEntry: historyEntry ?? null, + }; + }); } export async function runAndPersistDomainCheck( @@ -79,13 +98,15 @@ export async function runAndPersistDomainCheck( }), ); - const updatedDomain = await persistDomainCheck(database, { + const persisted = await persistDomainCheck(database, { domainId: input.domainId, + expectedServerIp: input.expectedServerIp, result, }); return { result, - domain: updatedDomain, + domain: persisted.domain, + historyEntry: persisted.historyEntry, }; } diff --git a/packages/api/src/routers/domains.ts b/packages/api/src/routers/domains.ts index 9d0381c..58871de 100644 --- a/packages/api/src/routers/domains.ts +++ b/packages/api/src/routers/domains.ts @@ -1,5 +1,5 @@ import { db } from "@minmon/db"; -import { domain, service } from "@minmon/db"; +import { domain, domainCheckHistory, service } from "@minmon/db"; import { desc, eq } from "drizzle-orm"; import { runAndPersistDomainCheck } from "../lib/domain-check"; @@ -37,6 +37,16 @@ export const domainsRouter = router({ return requireDomain(input.id); }), + history: permissionedProcedure("domains.read").input(byIdSchema).query(async ({ input }) => { + await requireDomain(input.id); + + return db + .select() + .from(domainCheckHistory) + .where(eq(domainCheckHistory.domainId, input.id)) + .orderBy(desc(domainCheckHistory.checkedAt), desc(domainCheckHistory.id)); + }), + create: permissionedProcedure("domains.create").input(domainCreateSchema).mutation(async ({ input }) => { const { service: parentService, server: parentServer } = await requireServiceWithServer(input.serviceId); @@ -96,6 +106,7 @@ export const domainsRouter = router({ return { domain: result.domain ?? existing, check: result.result, + historyEntry: result.historyEntry, }; }), diff --git a/packages/db/src/migrations/0003_add_domain_check_history.sql b/packages/db/src/migrations/0003_add_domain_check_history.sql new file mode 100644 index 0000000..ed953e7 --- /dev/null +++ b/packages/db/src/migrations/0003_add_domain_check_history.sql @@ -0,0 +1,17 @@ +CREATE TABLE IF NOT EXISTS "domain_check_history" ( + "id" text PRIMARY KEY NOT NULL, + "domain_id" text NOT NULL, + "expected_server_ip" text NOT NULL, + "status" "domain_resolution_status" NOT NULL, + "resolved_ips" jsonb DEFAULT '[]'::jsonb NOT NULL, + "message" text, + "checked_at" timestamp DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "domain_check_history" ADD CONSTRAINT "domain_check_history_domain_id_domain_id_fk" FOREIGN KEY ("domain_id") REFERENCES "public"."domain"("id") ON DELETE cascade ON UPDATE no action; +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "domain_check_history_domain_id_idx" ON "domain_check_history" USING btree ("domain_id"); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "domain_check_history_checked_at_idx" ON "domain_check_history" USING btree ("checked_at"); +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "domain_check_history_status_idx" ON "domain_check_history" USING btree ("status"); diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index f7e79eb..125a618 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1782698400000, "tag": "0002_user_lifecycle_permissions", "breakpoints": true + }, + { + "idx": 3, + "version": "7", + "when": 1786104000000, + "tag": "0003_add_domain_check_history", + "breakpoints": true } ] } diff --git a/packages/db/src/schema/monitoring.ts b/packages/db/src/schema/monitoring.ts index 2cf8b03..4aa8fcd 100644 --- a/packages/db/src/schema/monitoring.ts +++ b/packages/db/src/schema/monitoring.ts @@ -121,6 +121,29 @@ export const domain = pgTable( ], ); +export const domainCheckHistory = pgTable( + "domain_check_history", + { + id: text("id").primaryKey(), + domainId: text("domain_id") + .notNull() + .references(() => domain.id, { onDelete: "cascade" }), + expectedServerIp: text("expected_server_ip").notNull(), + status: domainResolutionStatusEnum("status").notNull(), + resolvedIps: jsonb("resolved_ips") + .$type() + .default(sql`'[]'::jsonb`) + .notNull(), + message: text("message"), + checkedAt: timestamp("checked_at").defaultNow().notNull(), + }, + (table) => [ + index("domain_check_history_domain_id_idx").on(table.domainId), + index("domain_check_history_checked_at_idx").on(table.checkedAt), + index("domain_check_history_status_idx").on(table.status), + ], +); + export const note = pgTable( "note", { @@ -153,11 +176,19 @@ export const serviceRelations = relations(service, ({ one, many }) => ({ domains: many(domain), })); -export const domainRelations = relations(domain, ({ one }) => ({ +export const domainRelations = relations(domain, ({ one, many }) => ({ service: one(service, { fields: [domain.serviceId], references: [service.id], }), + checks: many(domainCheckHistory), +})); + +export const domainCheckHistoryRelations = relations(domainCheckHistory, ({ one }) => ({ + domain: one(domain, { + fields: [domainCheckHistory.domainId], + references: [domain.id], + }), })); export const noteRelations = relations(note, ({ one }) => ({ diff --git a/packages/db/src/seed.ts b/packages/db/src/seed.ts index e1fea45..da5da02 100644 --- a/packages/db/src/seed.ts +++ b/packages/db/src/seed.ts @@ -8,7 +8,7 @@ dotenv.config({ import { db } from "./index"; import { account, permission, role, rolePermission, user, userRole } from "./schema/auth"; -import { domain, note, server, service } from "./schema/monitoring"; +import { domain, domainCheckHistory, note, server, service } from "./schema/monitoring"; const now = new Date(); const earlierToday = new Date(now.getTime() - 45 * 60 * 1000); @@ -293,6 +293,20 @@ async function seedMonitoringData() { })), ); + await db.insert(domainCheckHistory).values( + domains + .filter((item) => item.lastCheckedAt) + .map((item) => ({ + id: `history_${item.id}`, + domainId: item.id, + expectedServerIp: item.expectedServerIp, + status: item.resolutionStatus, + resolvedIps: item.lastResolvedIps, + message: item.lastCheckMessage, + checkedAt: item.lastCheckedAt, + })), + ); + await db.insert(note).values( notes.map((item) => ({ ...item,