import { useEffect, useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api, type CurrentUser, type TodoInput, type TodoItem } from "../api/client";
import DetailDrawer from "../components/DetailDrawer";
import EmptyState from "../components/EmptyState";
import { ErrorNotice } from "../components/Notice";
import { BlockSkeleton } from "../components/Skeleton";
import TimeAgo from "../components/TimeAgo";
import { refreshMyWork } from "../hooks/useMyWork";
import { formatDate } from "../utils/date";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
import { removeWithUndo } from "../utils/undoable";
type Person = { id: number; name: string; role: string };
type Place = { type: "server" | "device"; id: number; name: string };
const today = () => new Date().toISOString().slice(0, 10);
export function dueWords(t: TodoItem): { text: string; className: string } | null {
if (!t.dueDate) return null;
const days = Math.round((Date.parse(`${t.dueDate}T00:00:00Z`) - Date.parse(`${today()}T00:00:00Z`)) / 86_400_000);
if (t.doneAt) return { text: formatDate(new Date(`${t.dueDate}T12:00:00Z`)), className: "text-secondary" };
if (days < 0) return { text: `${-days} ${days === -1 ? "day" : "days"} overdue`, className: "text-red" };
if (days === 0) return { text: "due today", className: "text-yellow" };
if (days === 1) return { text: "due tomorrow", className: "text-yellow" };
return { text: `due ${formatDate(new Date(`${t.dueDate}T12:00:00Z`))}`, className: days <= 7 ? "text-yellow" : "text-secondary" };
}
/** The same form to make a job and to change one. */
function JobForm({ initial, people, places, busy, submitLabel, onSubmit, onCancel }: { initial: TodoInput & { targetKey?: string }; people: Person[]; places: Place[]; busy: boolean; submitLabel: string; onSubmit: (v: TodoInput) => void; onCancel?: () => void }) {
const [title, setTitle] = useState(initial.title);
const [detail, setDetail] = useState(initial.detail ?? "");
const [due, setDue] = useState(initial.dueDate ?? "");
const [who, setWho] = useState(initial.assigneeId ? String(initial.assigneeId) : "");
const [about, setAbout] = useState(initial.targetType && initial.targetId ? `${initial.targetType}:${initial.targetId}` : "");
return (
);
}
/**
* The small jobs of a homelab, written down: what, by when, for whom and about which server or device. A job with a day is in Coming up; one handed to somebody is in
* their My work. Ticking one off keeps it (under Done), and it can be brought back.
*/
export default function Todo({ user }: { user: CurrentUser }) {
const canEdit = user.role === "admin" || user.role === "operator";
const [params, setParams] = useSearchParams();
const mineOnly = params.get("who") === "me";
const [list, setList] = useState(null);
const [people, setPeople] = useState([]);
const [places, setPlaces] = useState([]);
const [error, setError] = useState(null);
const [busy, setBusy] = useState(false);
const [editing, setEditing] = useState(null);
const [showDone, setShowDone] = useState(false);
function load() {
api.todos
.list()
.then((res) => {
setList(res.todos);
setPeople(res.people);
})
.catch((err) => setError(readableError(err)));
refreshMyWork();
}
useEffect(load, []);
useEffect(() => {
// What a job can be about: the servers, and the network devices when there are any.
Promise.all([api.servers.list().catch(() => null), api.network.overview().catch(() => null)]).then(([s, n]) =>
setPlaces([...(s?.servers ?? []).map((x) => ({ type: "server" as const, id: x.id, name: x.name })), ...(n?.devices ?? []).map((x) => ({ type: "device" as const, id: x.id, name: x.name }))]),
);
}, []);
const visible = useMemo(() => (list ?? []).filter((t) => !mineOnly || t.assignee?.id === user.id), [list, mineOnly, user.id]);
const open = visible.filter((t) => !t.doneAt);
const done = visible.filter((t) => t.doneAt);
async function create(v: TodoInput) {
setBusy(true);
setError(null);
try {
await api.todos.create(v);
toast.success("Added.");
load();
} catch (err) {
setError(readableError(err));
} finally {
setBusy(false);
}
}
async function save(t: TodoItem, v: TodoInput) {
setBusy(true);
try {
await api.todos.update(t.id, v);
setEditing(null);
toast.success("Saved.");
load();
} catch (err) {
toast.error(readableError(err));
} finally {
setBusy(false);
}
}
async function tick(t: TodoItem, finished: boolean) {
try {
await api.todos.update(t.id, { done: finished });
if (finished) {
toast.success(`Done: ${t.title}`, {
label: "Undo",
onClick: async () => {
try {
await api.todos.update(t.id, { done: false });
} catch (err) {
toast.error(readableError(err));
} finally {
load();
}
},
});
}
load();
} catch (err) {
toast.error(readableError(err));
}
}
async function remove(t: TodoItem) {
setEditing(null);
await removeWithUndo({
remove: () => api.todos.remove(t.id),
restore: () => api.todos.create({ title: t.title, detail: t.detail, dueDate: t.dueDate, assigneeId: t.assignee?.id ?? null, targetType: t.target?.type ?? null, targetId: t.target?.id ?? null }).then((r) => (t.doneAt ? api.todos.update(r.todo.id, { done: true }) : r)),
message: `Removed "${t.title}".`,
reload: load,
});
}
const row = (t: TodoItem) => {
const due = dueWords(t);
return (
void tick(t, !t.doneAt)} />
{t.title}
{t.detail &&
{t.detail}
}
{due && {due.text}}
{t.assignee && {t.assignee.name}}
{t.target && {t.target.name}}
{t.doneAt && (
done
{t.doneBy ? ` by ${t.doneBy}` : ""}
)}
{canEdit && (
)}
);
};
return (
<>
To do
The small jobs: replace the battery, move the NAS to the new switch. A job with a day is in Coming up; one handed to somebody is in their My work.
{canEdit && (
Add a job
void create(v)} />
)}
{list === null && !error && }
{list !== null && open.length === 0 && (
)}
{open.length > 0 && (
)}
{done.length > 0 && (
Done ({done.length})
{showDone &&
}
)}
{editing && (
setEditing(null)}>
void save(editing, v)}
onCancel={() => setEditing(null)}
/>
)}
>
);
}