diff --git a/app/account/account-menu.tsx b/app/account/account-menu.tsx
index 026fbaf..5c4f9bc 100644
--- a/app/account/account-menu.tsx
+++ b/app/account/account-menu.tsx
@@ -1,7 +1,7 @@
"use client";
import { cn } from "@/lib/utils";
-import { BookOpenTextIcon, UserIcon } from "lucide-react";
+import { BookOpenTextIcon, BriefcaseBusinessIcon, UserIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
@@ -15,6 +15,11 @@ const menuItems = [
href: "/account/citizenship",
label: "Citizenship",
icon: BookOpenTextIcon,
+ },
+ {
+ href: "/account/positions",
+ label: "Positions",
+ icon: BriefcaseBusinessIcon,
}
];
diff --git a/app/account/positions/create-position-dialog.tsx b/app/account/positions/create-position-dialog.tsx
new file mode 100644
index 0000000..b8a34f9
--- /dev/null
+++ b/app/account/positions/create-position-dialog.tsx
@@ -0,0 +1,92 @@
+"use client";
+
+import {
+ Dialog, DialogClose, DialogContent,
+ DialogFooter, DialogHeader, DialogTitle, DialogTrigger,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+import { Spinner } from "@/components/ui/spinner";
+import { createPosition } from "@/lib/positions/actions";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { startTransition, useActionState, useEffect, useState } from "react";
+import { initialFormState } from "@/lib/form-action";
+import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
+import { Institution } from "@/lib/acts/types";
+import { toast } from "sonner";
+
+export function CreatePositionDialog({ institutions }: { institutions: Institution[] }) {
+ const [state, formAction, isPending] = useActionState(createPosition, initialFormState);
+ const [isOpen, setIsOpen] = useState(false);
+ const [name, setName] = useState("");
+ const [institutionId, setInstitutionId] = useState("");
+
+ const handleSubmit = () => {
+ const formData = new FormData();
+ formData.set("name", name);
+ formData.set("institutionId", institutionId);
+
+ startTransition(() => formAction(formData));
+ };
+
+ useEffect(() => {
+ if (state.success) {
+ setIsOpen(false);
+ setName("");
+ setInstitutionId("");
+ toast("Position successfully created")
+ }
+ }, [state.success]);
+
+ return (
+
+
+ Create a new position
+
+
+
+ Create a new position
+
+
+
+ Position name
+ setName(e.target.value)}
+ />
+ {state.fieldErrors?.name && {state.fieldErrors.name} }
+
+
+ Institution
+
+
+
+
+
+ {
+ institutions.map((institution) => (
+ {institution.name}
+ ))
+ }
+
+
+ {state.fieldErrors?.institutionId && {state.fieldErrors.institutionId} }
+
+
+ {state.error && {state.error} }
+
+
+ Cancel
+
+
+ {isPending && }Create
+
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/app/account/positions/page.tsx b/app/account/positions/page.tsx
new file mode 100644
index 0000000..d99198e
--- /dev/null
+++ b/app/account/positions/page.tsx
@@ -0,0 +1,58 @@
+import { getCurrentUser, getUsers } from "@/lib/user";
+import { redirect } from "next/navigation";
+import { AccountMenu } from "../account-menu";
+import { Metadata } from "next";
+import { getUserPositions } from "@/lib/positions/repository";
+import { Button } from "@/components/ui/button";
+import { CreatePositionDialog } from "./create-position-dialog";
+import { getInstitutions } from "@/lib/acts/repository";
+import { formatDate } from "@/lib/utils";
+import Link from "next/link";
+
+export const metadata: Metadata = {
+ title: "Positions",
+ robots: {
+ index: false,
+ follow: false,
+ },
+};
+
+export default async function Account() {
+ const user = await getCurrentUser();
+ if (!user) redirect("/");
+
+ const userPositions = await getUserPositions(user.id);
+ const institutions = await getInstitutions();
+
+ return (
+
+
+
+
+
+
Positions
+
Here are your positions in the European Federation
+
+ {userPositions.length === 0 ?
You do not have any positions
:
+
+ {userPositions.map((position) => (
+
+
{position.position.name}
+
Assigned on {formatDate(position.assignedAt)} by {position.act?.actType.name} {position.act?.numberInSeries && `№${position.act.numberInSeries}/${position.act.numberYear}`}
+
+ ))}
+
+ }
+ {user.isAdmin && (
+
+
+
+ To assign or dismiss someone from a position, create an appointment act.
+
+
+ )}
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/app/acts/[id]/approve-button.tsx b/app/acts/[id]/approve-button.tsx
new file mode 100644
index 0000000..9e6af5b
--- /dev/null
+++ b/app/acts/[id]/approve-button.tsx
@@ -0,0 +1,20 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Spinner } from "@/components/ui/spinner";
+import { useAction } from "@/hooks/useAction";
+import { approveActAction } from "@/lib/acts/actions";
+import { CheckIcon } from "lucide-react";
+
+export function ApproveButton({ actId }: { actId: string }) {
+ const { run, isPending } = useAction(approveActAction, {
+ successMessage: "Approved",
+ });
+
+ return (
+ run(actId)}>
+ {isPending ? : }
+ Approve
+
+ );
+}
\ No newline at end of file
diff --git a/app/acts/[id]/page.tsx b/app/acts/[id]/page.tsx
new file mode 100644
index 0000000..5bf42ff
--- /dev/null
+++ b/app/acts/[id]/page.tsx
@@ -0,0 +1,220 @@
+import { Badge } from "@/components/ui/badge";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ ArticleContent,
+ PreambleContent,
+ LEGAL_STATUS_LABELS,
+} from "@/lib/acts/types";
+import {
+ getActById,
+ getActTypeById,
+ getInstitutionById,
+ getActVersions,
+ getCurrentActVersion,
+ getActBlocks,
+ getActApprovals,
+} from "@/lib/acts/repository";
+import { getPositions, getCitizenshipPositions } from "@/lib/positions/repository";
+import { getActiveCitizenship } from "@/lib/citizenship/repository";
+import { getActFlow, getNextPhase } from "@/lib/acts/flows";
+import { ApproveButton } from "./approve-button";
+import { VetoButton } from "./veto-button";
+import { getCurrentUser, getUsers } from "@/lib/user";
+import { cn, formatDate } from "@/lib/utils";
+import { Metadata } from "next";
+import { Merriweather } from "next/font/google";
+import Image from "next/image";
+import Link from "next/link";
+import { notFound } from "next/navigation";
+
+const documentText = Merriweather({ weight: "400" });
+const documentHeading = Merriweather({ weight: "700" });
+
+export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise {
+ const { id } = await params;
+
+ const act = await getActById(id);
+ if (!act) return {};
+
+ const type = await getActTypeById(act.actTypeId);
+
+ return {
+ title: `${type?.name ?? ""}${act.title ? ` “${act.title}”` : ""}`,
+ };
+}
+
+export default async function Act({ params }: { params: Promise<{ id: string }> }) {
+ const { id } = await params;
+ const user = await getCurrentUser();
+
+ const act = await getActById(id);
+ if (!act) notFound();
+
+ const type = await getActTypeById(act.actTypeId);
+ const institution = await getInstitutionById(act.issuingInstitutionId);
+ const [author] = await getUsers(act.authorId);
+ const versions = await getActVersions(id);
+ const version = await getCurrentActVersion(id);
+ if (!version) notFound();
+
+ const blocks = await getActBlocks(version.id);
+ const needsRegion = institution?.kind === "REGION";
+ const preamble = blocks.find((b) => b.type === "PREAMBLE");
+ const preambleContent = preamble?.content as PreambleContent | undefined;
+
+ const approvals = await getActApprovals(version.id);
+ const positions = await getPositions();
+ const positionNames = new Map(positions.map((p) => [p.id, p.name]));
+
+ const flow = getActFlow(type?.code ?? "");
+ const phase = getNextPhase(flow, approvals);
+ const stageLabel = phase?.label ?? "Completed";
+
+ let canApprove = false;
+ let canVeto = false;
+
+ if (user && act.legalStatus === "DRAFT" && phase) {
+ const citizenship = await getActiveCitizenship(user.id);
+ if (citizenship) {
+ const citizenshipPositions = await getCitizenshipPositions(citizenship.id);
+ const holds = citizenshipPositions.some(
+ (p) => !p.resignedAt && p.position.capabilities.some((c) => c.capability === phase.capability)
+ );
+ canApprove = holds;
+ canVeto = holds && !!phase.allowVeto;
+ }
+ }
+
+ return (
+
+
+
+
+
+
+
+ {type?.name} {act.title && `“${act.title}”`}{" "}
+ {act.numberInSeries ? `№${act.numberInSeries}/${act.numberYear}` : without a number }
+
+
+
+
+
+
Issuing institution
+
{institution?.name}
+
+
+
Author
+
{author?.firstName} {author?.secondName}
+
+
+
Created
+
{formatDate(act.createdAt)}
+
+
+
Version from
+
{formatDate(version.createdAt)}
+
+
+
Process stage
+
{stageLabel}
+
+
+
Legal status
+ {act.legalStatus === "NOT_ADOPTED" ?
{LEGAL_STATUS_LABELS[act.legalStatus]} :
{LEGAL_STATUS_LABELS[act.legalStatus]}
}
+
+
+
+
+
+ History
+
+
+
+ {versions.map((v) =>
+ v.id === version.id ? (
+
+
Version from {formatDate(v.createdAt)}
+ Current
+
+ ) : (
+
+
Version from {formatDate(v.createdAt)}
+
Outdated
+
+ )
+ )}
+
+
+
+ { (canApprove || canVeto) && (
+
+
+ Signature
+ You are able to sign or reject this act
+
+
+ {canApprove && }
+ {canVeto && }
+
+
+ )}
+
+
+
+
+
+
{!needsRegion ? "European Federation" : "Region"}
+ {institution?.name}
+
+
+ {type?.name} {act.numberInSeries && `№${act.numberInSeries}/${act.numberYear}`} {act.title && `“${act.title}”`}
+
+
+
+ {preambleContent && (
+
{preambleContent.text}
+ )}
+ {blocks
+ .filter((b) => b.type === "ARTICLE")
+ .map((block, index) => {
+ const article = block.content as ArticleContent;
+ return (
+
+
+
+ Article {index + 1}{article.title && `. ${article.title}.`}
+
+
+ {article.intro &&
{article.intro} }
+
+ {article.clauses.map((clause, clauseIndex) => (
+
+ {article.markerStyle === "NUMBERS" && `${clauseIndex + 1}. `}
+ {article.markerStyle === "LETTERS" && `${String.fromCharCode(97 + clauseIndex)}) `}
+ {clause.kind === "APPOINTMENT"
+ ? `${clause.action === "ASSIGN" ? "Appoint" : "Dismiss"} ${clause.citizenshipName} ${clause.action === "ASSIGN" ? "to" : "from"} ${positionNames.get(clause.positionId) ?? "an unknown position"}.`
+ : clause.text}
+
+ ))}
+
+
+ );
+ })}
+
+
+ {approvals.map((a) => (
+
+
{a.name}
+
{a.role}
+
+ {a.decision === "APPROVE" ? "Approved" : "Vetoed"} at {formatDate(a.decidedAt)}
+
+
+ ))}
+
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/app/acts/[id]/veto-button.tsx b/app/acts/[id]/veto-button.tsx
new file mode 100644
index 0000000..35af5f2
--- /dev/null
+++ b/app/acts/[id]/veto-button.tsx
@@ -0,0 +1,20 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Spinner } from "@/components/ui/spinner";
+import { useAction } from "@/hooks/useAction";
+import { vetoActAction } from "@/lib/acts/actions";
+import { XIcon } from "lucide-react";
+
+export function VetoButton({ actId, vetoLabel }: { actId: string, vetoLabel: string }) {
+ const { run, isPending } = useAction(vetoActAction, {
+ successMessage: "Vetoed",
+ });
+
+ return (
+ run(actId)}>
+ {isPending ? : }
+ {vetoLabel}
+
+ );
+}
\ No newline at end of file
diff --git a/app/acts/create/client.tsx b/app/acts/create/client.tsx
new file mode 100644
index 0000000..f2900c2
--- /dev/null
+++ b/app/acts/create/client.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { useRef } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import ActEditor from "./editor";
+import { saveActAction } from "@/lib/acts/actions";
+import { Spinner } from "@/components/ui/spinner";
+import { useAction } from "@/hooks/useAction";
+import { ActEditorData } from "@/lib/acts/types";
+
+export default function CreateActClient({ actTypes, institutions, regions, positions }: {
+ actTypes: { id: string; name: string; allowedIssuerKind: string }[];
+ institutions: { id: string; name: string; kind: string; appointedByInstitutionId: string | null }[];
+ regions: { id: string; name: string }[];
+ positions: { id: string; name: string; institutionId: string }[];
+}) {
+ const router = useRouter();
+
+ const { run, isPending } = useAction(saveActAction, {
+ successMessage: "Act saved",
+ onSuccess: () => router.push("/acts"),
+ });
+
+ const dataRef = useRef({
+ actTypeId: "",
+ issuingInstitutionId: "",
+ title: "",
+ preambleText: "",
+ regionId: null,
+ articles: [],
+ });
+
+ function handleSave() {
+ const data = dataRef.current;
+ run(data);
+ }
+
+ return (
+
+
+
Create act
+
+
+ {isPending && }
+ Save
+
+
+
+
{ dataRef.current = data; }}
+ />
+
+ );
+}
\ No newline at end of file
diff --git a/app/acts/create/editor.tsx b/app/acts/create/editor.tsx
new file mode 100644
index 0000000..6d9fd0d
--- /dev/null
+++ b/app/acts/create/editor.tsx
@@ -0,0 +1,422 @@
+"use client";
+
+import { useState, useEffect, useRef } from "react";
+import { v4 as uuidv4 } from "uuid";
+import { Button } from "@/components/ui/button";
+import { Field, FieldError, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field";
+import { InputGroup, InputGroupInput } from "@/components/ui/input-group";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { PlusIcon, XIcon, ChevronDownIcon, ChevronUpIcon, Trash2Icon, ListOrderedIcon, CaseLowerIcon, UserCogIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+import Image from "next/image";
+import { Merriweather } from "next/font/google";
+import { ActEditorData, ActType, ArticleContent, Clause, ClauseMarkerStyle, Institution, PositionOption, Region } from "@/lib/acts/types";
+import { searchCitizensAction } from "@/lib/citizenship/actions";
+
+const documentText = Merriweather({ weight: "400" });
+const documentHeading = Merriweather({ weight: "700" });
+
+type ActEditorProps = {
+ actTypes: ActType[];
+ institutions: Institution[];
+ regions: Region[];
+ positions: PositionOption[];
+ initial?: Partial;
+ onChange: (data: ActEditorData) => void;
+ errors?: { title?: string[]; issuingInstitutionId?: string[] };
+};
+
+const LETTER_MARKERS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];
+
+function computeMarker(style: ClauseMarkerStyle, index: number): string | null {
+ if (style === "NONE") return null;
+ if (style === "LETTERS") return `${LETTER_MARKERS[index] ?? index + 1})`;
+ return `${index + 1}.`;
+}
+
+function makeEmptyTextClause(): Clause {
+ return { id: uuidv4(), kind: "TEXT", text: "" };
+}
+
+function makeEmptyAppointmentClause(): Clause {
+ return { id: uuidv4(), kind: "APPOINTMENT", action: "ASSIGN", positionId: "", citizenshipId: "", citizenshipName: "" };
+}
+
+function makeEmptyArticle(): ArticleContent {
+ return { id: uuidv4(), title: "", markerStyle: "NONE", clauses: [makeEmptyTextClause()] };
+}
+
+export default function ActEditor({ actTypes, institutions, regions, positions, initial, onChange, errors }: ActEditorProps) {
+ const [issuingInstitutionId, setIssuingInstitutionId] = useState(initial?.issuingInstitutionId ?? "");
+ const [actTypeId, setActTypeId] = useState(initial?.actTypeId ?? "");
+ const [regionId, setRegionId] = useState(initial?.regionId ?? "");
+ const [title, setTitle] = useState(initial?.title ?? "");
+ const [preambleText, setPreambleText] = useState(initial?.preambleText ?? "");
+ const [articles, setArticles] = useState(initial?.articles ?? [makeEmptyArticle()]);
+
+ const onChangeRef = useRef(onChange);
+ useEffect(() => { onChangeRef.current = onChange; });
+
+ useEffect(() => {
+ onChangeRef.current({ actTypeId, issuingInstitutionId, regionId, title, preambleText, articles });
+ }, [actTypeId, issuingInstitutionId, regionId, title, preambleText, articles]);
+
+ const appointablePositions = positions.filter((p) => {
+ const owner = institutions.find((i) => i.id === p.institutionId);
+ const requiredIssuerId = owner?.appointedByInstitutionId ?? owner?.id;
+ return requiredIssuerId === issuingInstitutionId;
+ });
+
+ const selectedInstitution = institutions.find((i) => i.id === issuingInstitutionId);
+ const availableActTypes = selectedInstitution
+ ? actTypes.filter((t) => t.allowedIssuerKind === selectedInstitution.kind)
+ : [];
+ const needsRegion = selectedInstitution?.kind === "REGION";
+
+ function updateArticle(id: string, patch: Partial) {
+ setArticles(articles.map((a) => (a.id === id ? { ...a, ...patch } : a)));
+ }
+
+ function addArticle() {
+ setArticles([...articles, makeEmptyArticle()]);
+ }
+
+ function removeArticle(id: string) {
+ setArticles(articles.filter((a) => a.id !== id));
+ }
+
+ function moveArticle(from: number, to: number) {
+ const updated = [...articles];
+ const [moved] = updated.splice(from, 1);
+ updated.splice(to, 0, moved);
+ setArticles(updated);
+ }
+
+ return (
+
+
+ Meta
+
+
+ Issuing institution
+ {
+ setIssuingInstitutionId(v);
+ setActTypeId("");
+ setRegionId("");
+ }}
+ >
+
+
+ {institutions.map((i) => (
+ {i.name}
+ ))}
+
+
+ {errors?.issuingInstitutionId && ({ message: m }))} />}
+
+
+
+ Act type
+
+
+
+ {availableActTypes.map((t) => (
+ {t.name}
+ ))}
+
+
+
+
+ {needsRegion && (
+
+ Region
+
+
+
+ {regions.map((r) => (
+ {r.name}
+ ))}
+
+
+
+ )}
+
+
+ Title
+
+ setTitle(e.target.value)}
+ />
+
+ {errors?.title && ({ message: m }))} />}
+
+
+
+
+
+
+
+
+
{!needsRegion ? "European Federation" : regions.find((region) => region.id === regionId)?.name}
+ {institutions.find((i) => i.id === issuingInstitutionId)?.name}
+
+
+ Draft of a {actTypes.find((a) => a.id === actTypeId)?.name} {title && `“${title}”`}
+
+
+
+
setPreambleText(e.target.value)}
+ />
+
+ {articles.map((article, index) => (
+
+
+
updateArticle(article.id, patch)}
+ />
+
+
+ moveArticle(index, index - 1)} disabled={index === 0}>
+
+
+ moveArticle(index, index + 1)} disabled={index === articles.length - 1}>
+
+
+ {articles.length > 1 && (
+ removeArticle(article.id)}>
+
+
+ )}
+
+
+ ))}
+
+
+ Add article
+
+
+
+
+ );
+}
+
+function ArticleEditor({
+ content,
+ articleIndex,
+ appointablePositions,
+ onChange,
+}: {
+ content: ArticleContent;
+ articleIndex: number;
+ appointablePositions: PositionOption[];
+ onChange: (patch: Partial) => void;
+}) {
+ const clauses = content.clauses ?? [makeEmptyTextClause()];
+
+ function updateClause(id: string, patch: Partial) {
+ onChange({ clauses: clauses.map((c) => (c.id === id ? { ...c, ...patch } as Clause : c)) });
+ }
+
+ function addClause(afterIndex: number, clause: Clause) {
+ const updated = [...clauses];
+ updated.splice(afterIndex + 1, 0, clause);
+ onChange({ clauses: updated });
+ }
+
+ function removeClause(id: string) {
+ const updated = clauses.filter((c) => c.id !== id);
+ onChange({ clauses: updated.length ? updated : [makeEmptyTextClause()] });
+ }
+
+ return (
+
+
+
Article {articleIndex + 1}
+ onChange({ title: e.target.value })}
+ />
+ onChange({ markerStyle: v as ClauseMarkerStyle })}>
+
+
+ No markers
+ Letters
+ Numbers
+
+
+
+
+ {content.markerStyle !== "NONE" && (
+
onChange({ intro: e.target.value })}
+ />
+ )}
+
+
+ {clauses.map((clause, i) => {
+ const marker = computeMarker(content.markerStyle, i);
+ return (
+
+ {marker &&
{marker} }
+ {clause.kind === "APPOINTMENT" ? (
+
updateClause(clause.id, patch)}
+ />
+ ) : (
+ updateClause(clause.id, { text: e.target.value })}
+ />
+ )}
+
+
addClause(i, makeEmptyTextClause())}>
+
addClause(i, makeEmptyAppointmentClause())}
+ >
+
+
+ {clauses.length > 1 && (
+
removeClause(clause.id)}>
+ )}
+
+
+ );
+ })}
+
+
+ );
+}
+
+// Renders an appointment clause inline as a fill-in-the-blank sentence:
+// "[Appoint|Dismiss] [citizen] [to|from] [position]."
+function AppointmentClauseEditor({
+ clause,
+ positions,
+ onChange,
+}: {
+ clause: Extract;
+ positions: PositionOption[];
+ onChange: (patch: Partial) => void;
+}) {
+ return (
+
+ onChange({ action: v as "ASSIGN" | "DISMISS" })}>
+
+
+ Appoint
+ Dismiss
+
+
+ onChange({ citizenshipId: c?.id ?? "", citizenshipName: c?.name ?? "" })}
+ />
+ {clause.action === "ASSIGN" ? "to" : "from"}
+ onChange({ positionId: v })}>
+
+
+ {positions.map((p) => (
+ {p.name}
+ ))}
+
+
+ .
+
+ );
+}
+
+function CitizenshipPicker({
+ value,
+ onSelect,
+}: {
+ value: { id: string; name: string } | null;
+ onSelect: (value: { id: string; name: string } | null) => void;
+}) {
+ const [query, setQuery] = useState("");
+ const [results, setResults] = useState<{ id: string; firstName: string; secondName: string }[]>([]);
+
+ useEffect(() => {
+ if (!query.trim()) { setResults([]); return; }
+ const timeout = setTimeout(async () => {
+ const result = await searchCitizensAction(query);
+ if (result.success) setResults(result.data);
+ }, 250);
+ return () => clearTimeout(timeout);
+ }, [query]);
+
+ if (value) {
+ return (
+
+ {value.name}
+ onSelect(null)}>
+
+ );
+ }
+
+ return (
+
+ setQuery(e.target.value)}
+ />
+ {results.length > 0 && (
+
+ {results.map((c) => (
+ { onSelect({ id: c.id, name: `${c.firstName} ${c.secondName}` }); setQuery(""); setResults([]); }}
+ >
+ {c.firstName} {c.secondName}
+
+ ))}
+
+ )}
+
+ );
+}
+
+function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent) => void; className?: string; placeholder?: string }) {
+ const ref = useRef(null);
+
+ useEffect(() => {
+ if (ref.current) {
+ ref.current.style.height = "auto";
+ ref.current.style.height = `${ref.current.scrollHeight}px`;
+ }
+ }, [value]);
+
+ return ;
+}
diff --git a/app/acts/create/page.tsx b/app/acts/create/page.tsx
new file mode 100644
index 0000000..4bcd738
--- /dev/null
+++ b/app/acts/create/page.tsx
@@ -0,0 +1,30 @@
+import { getCurrentUser } from "@/lib/user";
+import { redirect } from "next/navigation";
+import CreateActClient from "./client";
+import { Metadata } from "next";
+import { getActTypes, getInstitutions, getRegions } from "@/lib/acts/repository";
+import { getPositions, getUserPositions } from "@/lib/positions/repository";
+
+export const metadata: Metadata = {
+ title: "Create act",
+ robots: { index: false, follow: false },
+};
+
+export default async function CreateAct() {
+ const user = await getCurrentUser();
+ if (!user) redirect("/");
+
+ const [actTypes, institutions, regions, positions, userPositions] = await Promise.all([
+ getActTypes(),
+ getInstitutions(),
+ getRegions(),
+ getPositions(),
+ getUserPositions(user.id),
+ ]);
+
+ if (userPositions.length === 0) {
+ redirect("/");
+ }
+
+ return userPositions.some((position) => position.position.institutionId === institution.id))} regions={regions} positions={positions} />;
+}
\ No newline at end of file
diff --git a/app/acts/page.tsx b/app/acts/page.tsx
new file mode 100644
index 0000000..4b435ce
--- /dev/null
+++ b/app/acts/page.tsx
@@ -0,0 +1,55 @@
+import { Button } from "@/components/ui/button";
+import { getCurrentUser } from "@/lib/user";
+import { Metadata } from "next";
+import Link from "next/link";
+import SearchBar from "../../components/searchBar";
+import { getAllActs } from "@/lib/acts/actions";
+import { CalendarIcon, LandmarkIcon } from "lucide-react";
+import { formatDate } from "@/lib/utils";
+
+export const metadata: Metadata = { title: "Acts" };
+
+export default async function Acts({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
+ const { q } = await searchParams;
+ const user = await getCurrentUser();
+ const acts = await getAllActs();
+
+ const query = q?.trim().toLowerCase() ?? "";
+
+ const filteredActs = query
+ ? acts.filter((a) =>
+ `${a.actType.name.toLowerCase()} ${a.title.toLowerCase()} ${a.issuingInstitution.name.toLowerCase()}`.includes(query)
+ )
+ : acts;
+
+ return (
+
+
+
Acts
+
+
+ {user?.isAdmin && (
+
+ Create a new act
+
+ )}
+
+
+
+ {
+ filteredActs.length > 0 ? filteredActs.map((a) => (
+
+
+
{a.actType.name} {a.numberInSeries && `${a.numberInSeries}/${a.numberYear}`} “{a.title}”
+
+
+
{a.issuingInstitution.name}
+
{formatDate(a.createdAt)}
+
+
+ )) :
There are no acts yet...
+ }
+
+
+ );
+}
\ No newline at end of file
diff --git a/app/news/page.tsx b/app/news/page.tsx
index e6f3395..4aa35d5 100644
--- a/app/news/page.tsx
+++ b/app/news/page.tsx
@@ -5,7 +5,7 @@ import { getPages } from "@/lib/pages/repository";
import { getCurrentUser } from "@/lib/user";
import { Metadata } from "next";
import Link from "next/link";
-import SearchBar from "./searchBar";
+import SearchBar from "../../components/searchBar";
export const metadata: Metadata = { title: "News" };
diff --git a/components/footer.tsx b/components/footer.tsx
index b189616..7195c78 100644
--- a/components/footer.tsx
+++ b/components/footer.tsx
@@ -6,7 +6,7 @@ export default function Footer() {
-
+
European Federation
diff --git a/components/identity-card.tsx b/components/identity-card.tsx
index 0e5de8f..03aefbe 100644
--- a/components/identity-card.tsx
+++ b/components/identity-card.tsx
@@ -75,7 +75,7 @@ export default function IdentityCard({ data }: { data: IdentityCardData }) {
-
+
ID Card
{data.documentNumber}
diff --git a/components/mobile-nav.tsx b/components/mobile-nav.tsx
index 883a561..3e1a3aa 100644
--- a/components/mobile-nav.tsx
+++ b/components/mobile-nav.tsx
@@ -21,7 +21,7 @@ export function MobileNav({ links, isAuthenticated }: { links: NavLink[]; isAuth
setOpen(false)} className="flex items-center gap-4 shrink-0">
-
+
European Federation
setOpen(false)} aria-label="Close menu">
diff --git a/app/news/searchBar.tsx b/components/searchBar.tsx
similarity index 100%
rename from app/news/searchBar.tsx
rename to components/searchBar.tsx
diff --git a/lib/acts/actions.ts b/lib/acts/actions.ts
new file mode 100644
index 0000000..30007e1
--- /dev/null
+++ b/lib/acts/actions.ts
@@ -0,0 +1,136 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import { redirect } from "next/navigation";
+import { validateAct } from "./validation";
+import { requireAdmin, requireUser } from "../user/require";
+import { runAction } from "../run-action";
+import { AppError, type ActionResult } from "../action-result";
+import {
+ createAct, getActApprovals, getActById, getActs, getActTypeById, getCurrentActVersion,
+ getInstitutionById, putActIntoForce, recordApproval, recordVeto,
+} from "./repository";
+import { getPositionById, getCitizenshipPositions } from "../positions/repository";
+import { getActiveCitizenship } from "../citizenship/repository";
+import { ActEditorData, AppointmentClause } from "./types";
+import { ActCapability, getActFlow, getNextPhase } from "./flows";
+
+export async function saveActAction(params: ActEditorData): Promise {
+ return runAction(async () => {
+ await requireAdmin();
+
+ const parsed = validateAct(params);
+ if (!parsed.success) {
+ throw new AppError("Please ensure that at least 1 article here is in the act");
+ }
+
+ const actType = await getActTypeById(parsed.data.actTypeId);
+ if (!actType) throw new AppError("Selected act type does not exist");
+
+ const institution = await getInstitutionById(parsed.data.issuingInstitutionId);
+ if (!institution) throw new AppError("Selected institution does not exist");
+
+ if (actType.allowedIssuerKind !== institution.kind) {
+ throw new AppError("This act type is not allowed for the selected institution");
+ }
+ if (actType.allowedIssuerInstitutionCode && institution.code !== actType.allowedIssuerInstitutionCode) {
+ throw new AppError(`This act type can only be issued by ${actType.allowedIssuerInstitutionCode}`);
+ }
+
+ const appointmentClauses = parsed.data.articles
+ .flatMap((a) => a.clauses)
+ .filter((c): c is AppointmentClause => c.kind === "APPOINTMENT");
+
+ for (const clause of appointmentClauses) {
+ const position = await getPositionById(clause.positionId);
+ if (!position) throw new AppError("One of the selected positions does not exist");
+
+ const requiredIssuerId = position.institution.appointedByInstitutionId ?? position.institutionId;
+ if (requiredIssuerId !== institution.id) {
+ throw new AppError(`${institution.name} does not have the authority to appoint or dismiss ${position.name}`);
+ }
+ }
+
+ const act = await createAct(parsed.data);
+ revalidatePath("/acts");
+ redirect(`/acts/${act.id}`);
+ });
+}
+
+async function userHoldsCapability(userId: string, capability: ActCapability) {
+ const citizenship = await getActiveCitizenship(userId);
+ if (!citizenship) return { citizenship: null, position: null };
+
+ const positions = await getCitizenshipPositions(citizenship.id);
+ const position = positions.find(
+ (p) => !p.resignedAt && p.position.capabilities.some((c) => c.capability === capability)
+ );
+ return { citizenship, position };
+}
+
+async function loadDecidablePhase(actId: string) {
+ const act = await getActById(actId);
+ if (!act) throw new AppError("Act not found");
+ if (act.legalStatus !== "DRAFT") throw new AppError("This act has already been decided on");
+
+ const actType = await getActTypeById(act.actTypeId);
+ if (!actType) throw new AppError("Act type not found");
+
+ const version = await getCurrentActVersion(actId);
+ if (!version) throw new AppError("Act version not found");
+
+ const approvals = await getActApprovals(version.id);
+ const flow = getActFlow(actType.code);
+ const phase = getNextPhase(flow, approvals);
+ if (!phase) throw new AppError("This act has completed its approval process");
+
+ return { act, version, phase };
+}
+
+export async function approveActAction(actId: string): Promise {
+ return runAction(async () => {
+ const user = await requireUser();
+ const { version, phase } = await loadDecidablePhase(actId);
+
+ const { citizenship, position } = await userHoldsCapability(user.id, phase.capability);
+ if (!citizenship) throw new AppError("Only citizens can decide on acts");
+ if (!position) throw new AppError("You do not hold a position with the authority to approve this act at its current phase");
+
+ await recordApproval(
+ actId, version.id, phase.key, citizenship.id,
+ `${user.firstName} ${user.secondName}`, position.position.name, phase.isFinal
+ );
+ revalidatePath(`/acts/${actId}`);
+ });
+}
+
+export async function vetoActAction(actId: string): Promise {
+ return runAction(async () => {
+ const user = await requireUser();
+ const { version, phase } = await loadDecidablePhase(actId);
+ if (!phase.allowVeto) throw new AppError("This phase cannot veto the act");
+
+ const { citizenship, position } = await userHoldsCapability(user.id, phase.capability);
+ if (!citizenship) throw new AppError("Only citizens can decide on acts");
+ if (!position) throw new AppError("You do not hold a position with the authority to veto this act");
+
+ await recordVeto(actId, version.id, phase.key, citizenship.id, `${user.firstName} ${user.secondName}`, position.position.name);
+ revalidatePath(`/acts/${actId}`);
+ });
+}
+
+export async function putActIntoForceAction(actId: string): Promise {
+ return runAction(async () => {
+ await requireAdmin();
+
+ const act = await getActById(actId);
+ if (!act) throw new AppError("Act not found");
+
+ await putActIntoForce(actId);
+ revalidatePath(`/acts/${actId}`);
+ });
+}
+
+export async function getAllActs() {
+ return await getActs();
+}
\ No newline at end of file
diff --git a/lib/acts/flows.ts b/lib/acts/flows.ts
new file mode 100644
index 0000000..cf1854d
--- /dev/null
+++ b/lib/acts/flows.ts
@@ -0,0 +1,48 @@
+export type ActCapability =
+ | "SIGN_FEDERAL_LAW_SENATE"
+ | "SIGN_FEDERAL_LAW_HOUSE"
+ | "SIGN_AS_HEAD_OF_STATE"
+ | "SIGN_SENATE_APPOINTMENT"
+ | "SIGN_TREATY"
+ | "SIGN_RATIFICATION"
+ | "SIGN_REGIONAL_ACT";
+
+export type FlowPhase = {
+ key: string;
+ label: string;
+ capability: ActCapability;
+ isFinal: boolean;
+ allowVeto?: boolean;
+ vetoLabel?: string;
+};
+
+export type ActFlow = FlowPhase[];
+
+const singleSignature = (capability: ActCapability, label: string): ActFlow => [
+ { key: "ADOPTION", label, capability, isFinal: true, allowVeto: true, vetoLabel: "Reject" },
+];
+
+const FEDERAL_LAW_FLOW: ActFlow = [
+ { key: "SENATE_ADOPTION", label: "Awaiting the Senate", capability: "SIGN_FEDERAL_LAW_SENATE", isFinal: false, allowVeto: true, vetoLabel: "Reject" },
+ { key: "HOUSE_ADOPTION", label: "Awaiting the House of Representatives", capability: "SIGN_FEDERAL_LAW_HOUSE", isFinal: false, allowVeto: true, vetoLabel: "Reject" },
+ { key: "PRESIDENT_DECISION", label: "Under review by the President", capability: "SIGN_AS_HEAD_OF_STATE", isFinal: true, allowVeto: true, vetoLabel: "Veto" },
+];
+
+const FLOWS_BY_ACT_TYPE_CODE: Record = {
+ FEDERAL_LAW: FEDERAL_LAW_FLOW,
+ SENATE_APPOINTMENT: singleSignature("SIGN_SENATE_APPOINTMENT", "Awaiting the Senate"),
+ TREATY: singleSignature("SIGN_TREATY", "Awaiting the President's signature"),
+ RATIFICATION_ACT: singleSignature("SIGN_RATIFICATION", "Awaiting the Senate"),
+ REGIONAL_ACT: singleSignature("SIGN_REGIONAL_ACT", "Awaiting the regional government"),
+};
+
+export function getActFlow(actTypeCode: string): ActFlow {
+ const flow = FLOWS_BY_ACT_TYPE_CODE[actTypeCode];
+ if (!flow) throw new Error(`No flow configured for act type "${actTypeCode}"`);
+ return flow;
+}
+
+export function getNextPhase(flow: ActFlow, approvals: { phaseKey: string }[]): FlowPhase | undefined {
+ const done = new Set(approvals.map((a) => a.phaseKey));
+ return flow.find((p) => !done.has(p.key));
+}
\ No newline at end of file
diff --git a/lib/acts/repository.ts b/lib/acts/repository.ts
new file mode 100644
index 0000000..b7cef4a
--- /dev/null
+++ b/lib/acts/repository.ts
@@ -0,0 +1,187 @@
+import { prisma } from "../prisma";
+import { getCurrentUser } from "../user";
+import { ActFormData } from "./validation";
+import { ActBlockRecord, ArticleContent, AppointmentClause } from "./types";
+import { Prisma } from "@/lib/generated/prisma/client";
+
+const actTypeSelect = {
+ id: true, name: true, code: true, allowedIssuerKind: true, allowedIssuerInstitutionCode: true,
+} as const;
+const institutionSelect = { id: true, name: true, kind: true, code: true, appointedByInstitutionId: true } as const;
+const regionSelect = { id: true, name: true } as const;
+
+export async function getActTypes() {
+ return prisma.actType.findMany({ select: actTypeSelect });
+}
+
+export async function getInstitutions() {
+ return prisma.institution.findMany({ where: { isActive: true }, select: institutionSelect });
+}
+
+export async function getRegions() {
+ return prisma.region.findMany({ select: regionSelect });
+}
+
+export async function getActTypeById(id: string) {
+ return prisma.actType.findUnique({ where: { id }, select: actTypeSelect });
+}
+
+export async function getInstitutionById(id: string) {
+ return prisma.institution.findUnique({ where: { id }, select: institutionSelect });
+}
+
+export async function createAct(data: ActFormData) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Failed to fetch user");
+
+ return prisma.$transaction(async (tx) => {
+ const act = await tx.act.create({
+ data: {
+ actTypeId: data.actTypeId,
+ issuingInstitutionId: data.issuingInstitutionId,
+ regionId: data.regionId || null,
+ authorId: user.id,
+ title: data.title,
+ legalStatus: "DRAFT",
+ },
+ });
+
+ const version = await tx.actVersion.create({
+ data: { actId: act.id, isCurrent: true, createdBy: user.id },
+ });
+
+ let position = 0;
+ const blocks: { versionId: string; stableKey: string; type: string; position: number; content: object }[] = [];
+
+ if (data.preambleText?.trim()) {
+ blocks.push({
+ versionId: version.id,
+ stableKey: "preamble",
+ type: "PREAMBLE",
+ position: position++,
+ content: { text: data.preambleText },
+ });
+ }
+
+ for (const article of data.articles) {
+ blocks.push({
+ versionId: version.id,
+ stableKey: article.id,
+ type: "ARTICLE",
+ position: position++,
+ content: {
+ title: article.title ?? null,
+ intro: article.intro ?? null,
+ markerStyle: article.markerStyle,
+ clauses: article.clauses,
+ },
+ });
+ }
+
+ await tx.actBlock.createMany({ data: blocks });
+
+ return act;
+ });
+}
+
+export async function getActs() {
+ return prisma.act.findMany({
+ select: {
+ id: true,
+ title: true,
+ numberInSeries: true,
+ numberYear: true,
+ createdAt: true,
+ legalStatus: true,
+ actType: { select: actTypeSelect },
+ issuingInstitution: { select: institutionSelect },
+ },
+ orderBy: { createdAt: "desc" },
+ });
+}
+
+export async function getActById(id: string) {
+ return prisma.act.findUnique({ where: { id } });
+}
+
+export async function getActVersions(actId: string) {
+ return prisma.actVersion.findMany({ where: { actId }, orderBy: { createdAt: "desc" } });
+}
+
+export async function getCurrentActVersion(actId: string) {
+ return prisma.actVersion.findFirst({ where: { actId, isCurrent: true } });
+}
+
+export async function getActApprovals(actVersionId: string) {
+ return prisma.actApproval.findMany({
+ where: { actVersionId },
+ select: { id: true, phaseKey: true, decision: true, citizenshipId: true, name: true, role: true, decidedAt: true },
+ orderBy: { decidedAt: "asc" },
+ });
+}
+
+export async function recordApproval(
+ actId: string, actVersionId: string, phaseKey: string,
+ citizenshipId: string, name: string, role: string, isFinal: boolean
+) {
+ return prisma.$transaction(async (tx) => {
+ await tx.actApproval.create({ data: { actVersionId, phaseKey, decision: "APPROVE", citizenshipId, name, role } });
+ const act = await tx.act.findUniqueOrThrow({ where: { id: actId } });
+ if (!isFinal) return act;
+
+ const acts = await prisma.act.findMany({ where: { issuingInstitutionId: act.issuingInstitutionId, legalStatus: "IN_FORCE", numberYear: new Date().getFullYear() }, orderBy: { updatedAt: "desc" } });
+ await applyAppointmentEffects(tx, actId, actVersionId);
+ return tx.act.update({ where: { id: actId }, data: { legalStatus: "IN_FORCE", numberInSeries: acts[0]?.numberInSeries || 0 + 1, numberYear: new Date().getFullYear() } });
+ });
+}
+
+export async function recordVeto(
+ actId: string, actVersionId: string, phaseKey: string,
+ citizenshipId: string, name: string, role: string
+) {
+ return prisma.$transaction(async (tx) => {
+ await tx.actApproval.create({ data: { actVersionId, phaseKey, decision: "VETO", citizenshipId, name, role } });
+ return tx.act.update({ where: { id: actId }, data: { legalStatus: "NOT_ADOPTED" } });
+ });
+}
+
+export async function getActBlocks(versionId: string): Promise {
+ return prisma.actBlock.findMany({
+ where: { versionId },
+ orderBy: { position: "asc" },
+ }) as Promise;
+}
+
+async function applyAppointmentEffects(tx: Prisma.TransactionClient, actId: string, versionId: string) {
+ const articleBlocks = await tx.actBlock.findMany({ where: { versionId, type: "ARTICLE" } });
+
+ const appointmentClauses = articleBlocks.flatMap((block) => {
+ const content = block.content as unknown as ArticleContent;
+ return content.clauses.filter((c): c is AppointmentClause => c.kind === "APPOINTMENT");
+ });
+
+ for (const clause of appointmentClauses) {
+ if (clause.action === "ASSIGN") {
+ await tx.citizenshipPosition.updateMany({
+ where: { positionId: clause.positionId, resignedAt: null },
+ data: { resignedAt: new Date() },
+ });
+ await tx.citizenshipPosition.create({
+ data: { citizenshipId: clause.citizenshipId, positionId: clause.positionId, actId },
+ });
+ } else {
+ await tx.citizenshipPosition.updateMany({
+ where: { positionId: clause.positionId, citizenshipId: clause.citizenshipId, resignedAt: null },
+ data: { resignedAt: new Date() },
+ });
+ }
+ }
+}
+
+export async function putActIntoForce(actId: string) {
+ return prisma.$transaction(async (tx) => {
+ const version = await tx.actVersion.findFirstOrThrow({ where: { actId, isCurrent: true } });
+ await applyAppointmentEffects(tx, actId, version.id);
+ return tx.act.update({ where: { id: actId }, data: { legalStatus: "IN_FORCE" } });
+ });
+}
\ No newline at end of file
diff --git a/lib/acts/types.ts b/lib/acts/types.ts
new file mode 100644
index 0000000..eca2913
--- /dev/null
+++ b/lib/acts/types.ts
@@ -0,0 +1,83 @@
+export const CLAUSE_MARKER_STYLES = ["NONE", "LETTERS", "NUMBERS"] as const;
+export type ClauseMarkerStyle = typeof CLAUSE_MARKER_STYLES[number];
+
+export type ActLegalStatus = "DRAFT" | "IN_FORCE" | "AMENDED" | "REPEALED" | "EXPIRED" | "NOT_ADOPTED";
+
+export const LEGAL_STATUS_LABELS: Record = {
+ DRAFT: "Not yet in force",
+ IN_FORCE: "In force",
+ AMENDED: "Amended",
+ REPEALED: "Repealed",
+ EXPIRED: "Expired",
+ NOT_ADOPTED: "Not adopted",
+};
+
+export type TextClause = { id: string; kind: "TEXT"; text: string };
+
+export type AppointmentClause = {
+ id: string;
+ kind: "APPOINTMENT";
+ action: "ASSIGN" | "DISMISS";
+ positionId: string;
+ citizenshipId: string;
+ citizenshipName: string;
+};
+
+export type Clause = TextClause | AppointmentClause;
+
+export type ArticleContent = {
+ id: string;
+ title: string;
+ intro?: string;
+ markerStyle: ClauseMarkerStyle;
+ clauses: Clause[];
+};
+
+export type PreambleContent = { text: string };
+
+export type ActBlockContent = ArticleContent | PreambleContent;
+
+export type ActBlockType = "PREAMBLE" | "ARTICLE";
+
+export type ActBlockRecord = {
+ id: string;
+ versionId: string;
+ stableKey: string;
+ type: ActBlockType;
+ position: number;
+ content: ActBlockContent;
+};
+
+export type ActEditorData = {
+ actTypeId: string;
+ issuingInstitutionId: string;
+ regionId: string | null;
+ title?: string;
+ preambleText?: string;
+ articles: ArticleContent[];
+};
+
+export type ActType = { id: string; name: string; code: string; allowedIssuerKind: string };
+export type Institution = { id: string; name: string; kind: string; appointedByInstitutionId: string | null };
+export type Region = { id: string; name: string };
+export type PositionOption = { id: string; name: string; institutionId: string };
+
+export type ActSignature = {
+ id: string;
+ citizenshipId: string;
+ name: string;
+ role: string;
+ signedAt: Date;
+};
+
+export type ApprovalDecision = "APPROVE" | "VETO";
+
+export type ActApprovalRecord = {
+ id: string;
+ phaseKey: string;
+ decision: ApprovalDecision;
+ citizenshipId: string;
+ name: string;
+ role: string;
+ decidedAt: Date;
+};
\ No newline at end of file
diff --git a/lib/acts/validation.ts b/lib/acts/validation.ts
new file mode 100644
index 0000000..639857f
--- /dev/null
+++ b/lib/acts/validation.ts
@@ -0,0 +1,48 @@
+import { z } from "zod";
+import { CLAUSE_MARKER_STYLES } from "./types";
+
+const textClauseSchema = z.object({
+ id: z.string(),
+ kind: z.literal("TEXT"),
+ text: z.string().min(1),
+});
+
+const appointmentClauseSchema = z.object({
+ id: z.string(),
+ kind: z.literal("APPOINTMENT"),
+ action: z.enum(["ASSIGN", "DISMISS"]),
+ positionId: z.string().min(1, "A position is required"),
+ citizenshipId: z.string().min(1, "A citizen must be selected"),
+ citizenshipName: z.string().min(1),
+});
+
+const clauseSchema = z.discriminatedUnion("kind", [textClauseSchema, appointmentClauseSchema]);
+
+const articleSchema = z.object({
+ id: z.string(),
+ title: z.string().optional(),
+ intro: z.string().optional(),
+ markerStyle: z.enum(CLAUSE_MARKER_STYLES),
+ clauses: z.array(clauseSchema).min(1),
+});
+
+export const actSchema = z.object({
+ actTypeId: z.string().min(1, "Act type is required"),
+ issuingInstitutionId: z.string().min(1, "Issuing institution is required"),
+ regionId: z.string().nullable(),
+ title: z.string().min(1, "Act must have a title"),
+ preambleText: z.string().optional(),
+ articles: z.array(articleSchema).min(1, "At least one article is required"),
+});
+
+export type ActFormData = z.infer;
+
+export function validateAct(data: unknown): { success: true; data: ActFormData } | { success: false; errors: string[] } {
+ const result = actSchema.safeParse(data);
+ if (!result.success) {
+ const fieldErrors = result.error.flatten().fieldErrors ?? {};
+ const messages = Object.values(fieldErrors).flat().filter(Boolean);
+ return { success: false, errors: messages };
+ }
+ return { success: true, data: result.data };
+}
diff --git a/lib/citizenship/actions.ts b/lib/citizenship/actions.ts
index a5c3d75..599a549 100644
--- a/lib/citizenship/actions.ts
+++ b/lib/citizenship/actions.ts
@@ -7,7 +7,7 @@ import { runAction, isPrismaError } from "@/lib/run-action";
import { AppError, type ActionResult } from "@/lib/action-result";
import { formAction } from "@/lib/form-action";
import { citizenshipApplicationSchema } from "./validation";
-import { createApplication, getActiveCitizenship, getApplicationEligibility } from "./repository";
+import { createApplication, getActiveCitizenship, getApplicationEligibility, searchActiveCitizenships } from "./repository";
import { prisma } from "../prisma";
import { formatAddress } from "@/lib/address";
import { Prisma } from "@/lib/generated/prisma/client";
@@ -179,6 +179,17 @@ export async function rejectApplication(id: string, reason: string): Promise> {
+ return runAction(async () => {
+ // Gate behind admin for now, same as act creation - refine once
+ // position-based authority exists.
+ await requireAdmin();
+
+ const results = await searchActiveCitizenships(query);
+ return results.map((c) => ({ id: c.id, firstName: c.user.firstName, secondName: c.user.secondName }));
+ });
+}
+
export async function renounceCitizenship(): Promise {
return runAction(async () => {
const user = await requireUser();
diff --git a/lib/citizenship/repository.ts b/lib/citizenship/repository.ts
index 4fa18c4..4ae8532 100644
--- a/lib/citizenship/repository.ts
+++ b/lib/citizenship/repository.ts
@@ -102,4 +102,28 @@ export async function getActiveCitizenship(userId: string) {
return prisma.citizenship.findFirst({
where: { userId, revokedAt: null },
});
+}
+
+// Used by the acts appointment picker - only active citizens are eligible
+// to hold a position.
+export async function searchActiveCitizenships(query: string) {
+ const q = query.trim();
+ if (!q) return [];
+
+ return prisma.citizenship.findMany({
+ where: {
+ revokedAt: null,
+ user: {
+ OR: [
+ { firstName: { contains: q, mode: "insensitive" } },
+ { secondName: { contains: q, mode: "insensitive" } },
+ ],
+ },
+ },
+ select: {
+ id: true,
+ user: { select: { firstName: true, secondName: true } },
+ },
+ take: 10,
+ });
}
\ No newline at end of file
diff --git a/lib/positions/actions.ts b/lib/positions/actions.ts
new file mode 100644
index 0000000..0e4e945
--- /dev/null
+++ b/lib/positions/actions.ts
@@ -0,0 +1,28 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import { AppError } from "../action-result";
+import { prisma } from "../prisma";
+import { requireAdmin } from "../user/require";
+import { formAction } from "../form-action";
+import z from "zod";
+
+const createPositionSchema = z.object({
+ name: z.string().min(1, "Name of a position cannot be empty"),
+ institutionId: z.string().min(1, "Incorrect institution is provided"),
+});
+
+// Defines an office (e.g. "Mayor of X") within an institution. This does NOT
+// assign anyone to it - filling/vacating a position happens through an
+// appointment act, see lib/acts.
+export const createPosition = formAction(createPositionSchema, async (data) => {
+ await requireAdmin();
+
+ const institution = await prisma.institution.findUnique({ where: { id: data.institutionId } });
+ if (!institution) {
+ throw new AppError("Incorrect institution is provided");
+ }
+
+ await prisma.position.create({ data: { name: data.name, institutionId: data.institutionId } });
+ revalidatePath("/account/positions");
+});
diff --git a/lib/positions/repository.ts b/lib/positions/repository.ts
new file mode 100644
index 0000000..60f4314
--- /dev/null
+++ b/lib/positions/repository.ts
@@ -0,0 +1,46 @@
+import { prisma } from "../prisma";
+import { Position } from "./types";
+
+const positionSelect = {
+ id: true,
+ name: true,
+ institutionId: true,
+ institution: { select: { id: true, name: true, kind: true } },
+ capabilities: { select: { capability: true } },
+} as const;
+
+export async function getPositions() {
+ return prisma.position.findMany({ select: positionSelect, orderBy: { name: "asc" } });
+}
+
+export async function getPositionById(id: string) {
+ return prisma.position.findUnique({ where: { id }, select: positionSelect });
+}
+
+export async function createPosition(position: Omit) {
+ return prisma.position.create({ data: position });
+}
+
+// Current (non-resigned) holder of a position, if any.
+export async function getCurrentHolder(positionId: string) {
+ return prisma.citizenshipPosition.findFirst({
+ where: { positionId, resignedAt: null },
+ include: { citizenship: { include: { user: { select: { firstName: true, secondName: true } } } } },
+ });
+}
+
+export async function getCitizenshipPositions(citizenshipId: string) {
+ return prisma.citizenshipPosition.findMany({
+ where: { citizenshipId },
+ include: { position: { select: positionSelect } },
+ orderBy: { assignedAt: "desc" },
+ });
+}
+
+export async function getUserPositions(userId: string) {
+ return prisma.citizenshipPosition.findMany({
+ where: { citizenship: { userId }, resignedAt: null },
+ include: { position: { select: positionSelect }, act: { select: { title: true, numberInSeries: true, numberYear: true, actType: { select: { name: true } } } } },
+ orderBy: { assignedAt: "desc" },
+ });
+}
diff --git a/lib/positions/types.ts b/lib/positions/types.ts
new file mode 100644
index 0000000..9c51d5c
--- /dev/null
+++ b/lib/positions/types.ts
@@ -0,0 +1,14 @@
+export type Position = {
+ id: string;
+ name: string;
+ institutionId: string;
+}
+
+export type CitizenshipPosition = {
+ id: string;
+ citizenshipId: string;
+ positionId: string;
+ assignedAt: Date;
+ resignedAt: Date | null;
+ actId: string | null;
+}
\ No newline at end of file
diff --git a/lib/prisma.ts b/lib/prisma.ts
index e32b011..e758e04 100644
--- a/lib/prisma.ts
+++ b/lib/prisma.ts
@@ -5,6 +5,9 @@ import { PrismaClient } from "@/lib/generated/prisma/client";
const connectionString = `${process.env.DATABASE_URL}`;
const adapter = new PrismaPg({ connectionString });
-const prisma = new PrismaClient({ adapter });
-export { prisma };
\ No newline at end of file
+const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
+
+export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter });
+
+if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
\ No newline at end of file
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 17783fb..186c726 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -27,23 +27,25 @@ enum EyeColor {
}
model User {
- id String @id @default(uuid())
- kotosoftId String @unique
- email String @unique
+ id String @id @default(uuid())
+ kotosoftId String @unique
+ email String @unique
firstName String
secondName String
sex Sex
birthDate DateTime?
- createdAt DateTime @default(now())
- isAdmin Boolean @default(false)
+ createdAt DateTime @default(now())
+ isAdmin Boolean @default(false)
- pages Page[] @relation("PageAuthor")
- editedPages Page[] @relation("PageEditor")
+ pages Page[] @relation("PageAuthor")
+ editedPages Page[] @relation("PageEditor")
citizenshipApplications CitizenshipApplication[]
- reviewedApplications CitizenshipApplication[] @relation("CitizenshipReviewer")
+ reviewedApplications CitizenshipApplication[] @relation("CitizenshipReviewer")
citizenships Citizenship[]
+
+ acts Act[]
}
enum PageStatus {
@@ -68,20 +70,20 @@ model Page {
updatedAt DateTime @updatedAt
publishedAt DateTime?
- createdBy String?
- author User? @relation("PageAuthor", fields: [createdBy], references: [id])
+ createdBy String?
+ author User? @relation("PageAuthor", fields: [createdBy], references: [id])
- updatedBy String?
- editor User? @relation("PageEditor", fields: [updatedBy], references: [id])
+ updatedBy String?
+ editor User? @relation("PageEditor", fields: [updatedBy], references: [id])
- blocks Block[]
- navLinks NavLink[]
+ blocks Block[]
+ navLinks NavLink[]
}
model Block {
- id String @id @default(uuid())
- pageId String
- page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
+ id String @id @default(uuid())
+ pageId String
+ page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
parentId String?
parent Block? @relation("BlockChildren", fields: [parentId], references: [id])
@@ -95,13 +97,13 @@ model Block {
}
model NavLink {
- id String @id @default(uuid())
- label String?
+ id String @id @default(uuid())
+ label String?
order Int
- pageId String?
- page Page? @relation(fields: [pageId], references: [id], onDelete: SetNull)
- href String?
+ pageId String?
+ page Page? @relation(fields: [pageId], references: [id], onDelete: SetNull)
+ href String?
}
enum CitizenshipApplicationStatus {
@@ -116,35 +118,35 @@ enum ApplicationType {
}
model CitizenshipApplication {
- id String @id @default(uuid())
- userId String
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
- surname String
- givenNames String
- sex Sex
- birthDate DateTime
- applicationType ApplicationType
- previousCountry String?
- previousRegion String?
+ id String @id @default(uuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ surname String
+ givenNames String
+ sex Sex
+ birthDate DateTime
+ applicationType ApplicationType
+ previousCountry String?
+ previousRegion String?
naturalizationReason String?
- address String
- regionId String?
- region Region? @relation(fields: [regionId], references: [id])
- city String?
- street String?
- customAddress String?
- height Int
- eyeColor EyeColor
- status CitizenshipApplicationStatus @default(PENDING)
- rejectionReason String?
- reviewedAt DateTime?
- reviewedBy String?
- reviewer User? @relation("CitizenshipReviewer", fields: [reviewedBy], references: [id])
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- profileKey String
- signatureKey String
- citizenship Citizenship?
+ address String
+ regionId String?
+ region Region? @relation(fields: [regionId], references: [id])
+ city String?
+ street String?
+ customAddress String?
+ height Int
+ eyeColor EyeColor
+ status CitizenshipApplicationStatus @default(PENDING)
+ rejectionReason String?
+ reviewedAt DateTime?
+ reviewedBy String?
+ reviewer User? @relation("CitizenshipReviewer", fields: [reviewedBy], references: [id])
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ profileKey String
+ signatureKey String
+ citizenship Citizenship?
}
model Citizenship {
@@ -154,37 +156,225 @@ model Citizenship {
issuedAt DateTime @default(now())
revokedAt DateTime?
- user User @relation(fields: [userId], references: [id])
- application CitizenshipApplication @relation(fields: [applicationId], references: [id])
+ user User @relation(fields: [userId], references: [id])
+ application CitizenshipApplication @relation(fields: [applicationId], references: [id])
identityDocuments IdentityDocument[]
+ positions CitizenshipPosition[]
+ approvals ActApproval[]
@@index([userId])
}
model IdentityDocument {
- id String @id @default(uuid())
- citizenshipId String
- citizenship Citizenship @relation(fields: [citizenshipId], references: [id], onDelete: Cascade)
+ id String @id @default(uuid())
+ citizenshipId String
+ citizenship Citizenship @relation(fields: [citizenshipId], references: [id], onDelete: Cascade)
- documentNumber String @unique
+ documentNumber String @unique
address String
- regionId String?
- region Region? @relation(fields: [regionId], references: [id])
- city String?
- street String?
- customAddress String?
+ regionId String?
+ region Region? @relation(fields: [regionId], references: [id])
+ city String?
+ street String?
+ customAddress String?
- issuedAt DateTime @default(now())
- expiresAt DateTime
+ issuedAt DateTime @default(now())
+ expiresAt DateTime
@@index([citizenshipId, issuedAt])
}
model Region {
- id String @id
+ id String @id
name String
capital String
documents IdentityDocument[]
applications CitizenshipApplication[]
-}
\ No newline at end of file
+ acts Act[]
+}
+
+enum InstitutionKind {
+ LEGISLATIVE_CHAMBER
+ HEAD_OF_STATE
+ HEAD_OF_GOVERNMENT
+ DEPARTMENT
+ AGENCY
+ REGION
+ COURT
+}
+
+model Institution {
+ id String @id @default(uuid())
+ kind InstitutionKind
+ name String
+ code String? @unique
+ parentId String?
+ parent Institution? @relation("InstitutionHierarchy", fields: [parentId], references: [id])
+ children Institution[] @relation("InstitutionHierarchy")
+ isActive Boolean @default(true)
+
+ appointedByInstitutionId String?
+ appointedBy Institution? @relation("InstitutionAppointer", fields: [appointedByInstitutionId], references: [id])
+ appointsInto Institution[] @relation("InstitutionAppointer")
+
+ acts Act[]
+
+ positions Position[]
+}
+
+enum ActCapability {
+ SIGN_FEDERAL_LAW_SENATE
+ SIGN_FEDERAL_LAW_HOUSE
+ SIGN_AS_HEAD_OF_STATE
+ SIGN_AS_HEAD_OF_GOVERNMENT
+ SIGN_AS_HEAD_OF_DEPARTMENT
+ SIGN_AS_HEAD_OF_AGENCY
+ SIGN_AS_JUDGE
+ SIGN_SENATE_APPOINTMENT
+ SIGN_TREATY
+ SIGN_RATIFICATION
+ SIGN_REGIONAL_ACT
+}
+
+model Position {
+ id String @id @default(uuid())
+ name String
+ institutionId String
+ institution Institution @relation(fields: [institutionId], references: [id], onDelete: Cascade)
+
+ capabilities PositionCapability[]
+ holders CitizenshipPosition[]
+
+ @@unique([institutionId, name])
+}
+
+model PositionCapability {
+ id String @id @default(uuid())
+ positionId String
+ position Position @relation(fields: [positionId], references: [id], onDelete: Cascade)
+ capability ActCapability
+
+ @@unique([positionId, capability])
+}
+
+model CitizenshipPosition {
+ id String @id @default(uuid())
+ citizenshipId String
+ citizenship Citizenship @relation(fields: [citizenshipId], references: [id], onDelete: Cascade)
+ positionId String
+ position Position @relation(fields: [positionId], references: [id], onDelete: Cascade)
+ assignedAt DateTime @default(now())
+ resignedAt DateTime?
+
+ actId String?
+ act Act? @relation(fields: [actId], references: [id])
+
+ @@index([positionId, resignedAt])
+ @@index([citizenshipId])
+}
+
+model ActType {
+ id String @id @default(uuid())
+ code String @unique
+ name String
+ allowedIssuerKind InstitutionKind
+ allowedIssuerInstitutionCode String?
+ legalRank Int
+ numberingScope String
+
+ acts Act[]
+}
+
+enum ActLegalStatus {
+ DRAFT
+ IN_FORCE
+ AMENDED
+ REPEALED
+ EXPIRED
+ NOT_ADOPTED
+}
+
+model Act {
+ id String @id @default(uuid())
+
+ actTypeId String
+ actType ActType @relation(fields: [actTypeId], references: [id])
+
+ issuingInstitutionId String
+ issuingInstitution Institution @relation(fields: [issuingInstitutionId], references: [id])
+
+ regionId String?
+ region Region? @relation(fields: [regionId], references: [id])
+
+ authorId String
+ author User @relation(fields: [authorId], references: [id])
+
+ numberYear Int?
+ numberInSeries Int?
+
+ legalStatus ActLegalStatus @default(DRAFT)
+
+ title String
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ versions ActVersion[]
+ citizenshipPositions CitizenshipPosition[]
+}
+
+model ActVersion {
+ id String @id @default(uuid())
+ actId String
+ act Act @relation(fields: [actId], references: [id], onDelete: Cascade)
+
+ effectiveFrom DateTime?
+ isCurrent Boolean @default(true)
+
+ createdAt DateTime @default(now())
+ createdBy String
+
+ blocks ActBlock[]
+ approvals ActApproval[]
+
+ @@index([actId, effectiveFrom])
+}
+
+model ActBlock {
+ id String @id @default(uuid())
+ versionId String
+ version ActVersion @relation(fields: [versionId], references: [id], onDelete: Cascade)
+
+ stableKey String
+ type String
+ position Float
+ content Json
+
+ @@unique([versionId, stableKey])
+ @@index([versionId, position])
+}
+
+enum ApprovalDecision {
+ APPROVE
+ VETO
+}
+
+model ActApproval {
+ id String @id @default(uuid())
+ actVersionId String
+ actVersion ActVersion @relation(fields: [actVersionId], references: [id], onDelete: Cascade)
+
+ phaseKey String
+ decision ApprovalDecision
+
+ citizenshipId String
+ citizenship Citizenship @relation(fields: [citizenshipId], references: [id])
+
+ name String
+ role String
+
+ decidedAt DateTime @default(now())
+
+ @@unique([actVersionId, phaseKey])
+}
diff --git a/public/emblems/DU.png b/public/emblems/DU.png
new file mode 100755
index 0000000..d7458b2
Binary files /dev/null and b/public/emblems/DU.png differ
diff --git a/public/emblem.png b/public/emblems/europe.png
similarity index 100%
rename from public/emblem.png
rename to public/emblems/europe.png