This commit is contained in:
Ivan Rezchikov
2026-07-28 17:05:45 +03:00
parent e826e7b099
commit e234407a17
30 changed files with 1873 additions and 74 deletions
+20
View File
@@ -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 (
<Button className="w-max" disabled={isPending} onClick={() => run(actId)}>
{isPending ? <Spinner /> : <CheckIcon />}
Approve
</Button>
);
}
+220
View File
@@ -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<Metadata> {
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 (
<div className="flex flex-col p-4 md:p-16 gap-8 md:gap-16 mb-4 md:mb-0">
<div className="flex flex-col gap-8 md:flex-row justify-between">
<div className="flex flex-col gap-8">
<Card size="sm" className="h-max">
<CardHeader>
<CardTitle>
<h3>
{type?.name} {act.title && `“${act.title}”`}{" "}
{act.numberInSeries ? `№${act.numberInSeries}/${act.numberYear}` : <span className="text-muted-foreground">without a number</span>}
</h3>
</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col">
<p className="text-muted-foreground">Issuing institution</p>
<p>{institution?.name}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Author</p>
<p>{author?.firstName} {author?.secondName}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Created</p>
<p>{formatDate(act.createdAt)}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Version from</p>
<p>{formatDate(version.createdAt)}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Process stage</p>
<p>{stageLabel}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Legal status</p>
{act.legalStatus === "NOT_ADOPTED" ? <Badge variant="destructive">{LEGAL_STATUS_LABELS[act.legalStatus]}</Badge> : <p>{LEGAL_STATUS_LABELS[act.legalStatus]}</p>}
</div>
</CardContent>
</Card>
<Card size="sm" className="h-max">
<CardHeader>
<CardTitle><h3>History</h3></CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-4">
{versions.map((v) =>
v.id === version.id ? (
<div className="flex flex-col gap-1" key={v.id}>
<h4>Version from {formatDate(v.createdAt)}</h4>
<Badge>Current</Badge>
</div>
) : (
<Link href={`/acts/${act.id}/${v.id}`} className="flex flex-col gap-1" key={v.id}>
<h4 className="text-muted-foreground">Version from {formatDate(v.createdAt)}</h4>
<Badge variant="secondary">Outdated</Badge>
</Link>
)
)}
</div>
</CardContent>
</Card>
{ (canApprove || canVeto) && (
<Card size="sm" className="h-max">
<CardHeader>
<CardTitle><h3>Signature</h3></CardTitle>
<CardDescription><p>You are able to sign or reject this act</p></CardDescription>
</CardHeader>
<CardContent className="flex flex-row gap-3">
{canApprove && <ApproveButton actId={act.id} />}
{canVeto && <VetoButton actId={act.id} vetoLabel={phase?.vetoLabel || "Veto"} />}
</CardContent>
</Card>
)}
</div>
<div className="flex flex-1 flex-col gap-6">
<div className="flex flex-col items-center gap-6">
<Image src="/emblems/europe.png" width={52} height={32} alt="Emblem of the European Federation" />
<div className={cn("flex flex-col gap-1", documentHeading.className)}>
<h3 className="text-center">{!needsRegion ? "European Federation" : "Region"}</h3>
<h3 className="text-center">{institution?.name}</h3>
</div>
<h3 className={cn("text-center", documentHeading.className)}>
{type?.name} {act.numberInSeries && `№${act.numberInSeries}/${act.numberYear}`} {act.title && `“${act.title}”`}
</h3>
</div>
<div className="flex flex-col gap-4">
{preambleContent && (
<h4 className={cn("shrink-0", documentText.className)}>{preambleContent.text}</h4>
)}
{blocks
.filter((b) => b.type === "ARTICLE")
.map((block, index) => {
const article = block.content as ArticleContent;
return (
<div className="flex flex-col gap-2" key={block.stableKey}>
<div className="flex items-center gap-2">
<h4 className={cn("shrink-0", documentHeading.className)}>
Article {index + 1}{article.title && `. ${article.title}.`}
</h4>
</div>
{article.intro && <h4 className={documentText.className}>{article.intro}</h4>}
<div className="flex flex-col gap-2">
{article.clauses.map((clause, clauseIndex) => (
<h4 key={clause.id} className={documentText.className}>
{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}
</h4>
))}
</div>
</div>
);
})}
</div>
<div className="flex flex-col gap-4">
{approvals.map((a) => (
<div className="flex flex-col gap-1 border-4 border-primary w-max p-2" key={a.id}>
<h4 className={documentHeading.className}>{a.name}</h4>
<h4 className={documentText.className}>{a.role}</h4>
<p className={documentText.className}>
{a.decision === "APPROVE" ? "Approved" : "Vetoed"} at {formatDate(a.decidedAt)}
</p>
</div>
))}
</div>
</div>
</div>
</div>
);
}
+20
View File
@@ -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 (
<Button variant="destructive" className="w-max" disabled={isPending} onClick={() => run(actId)}>
{isPending ? <Spinner /> : <XIcon />}
{vetoLabel}
</Button>
);
}
+59
View File
@@ -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<ActEditorData>({
actTypeId: "",
issuingInstitutionId: "",
title: "",
preambleText: "",
regionId: null,
articles: [],
});
function handleSave() {
const data = dataRef.current;
run(data);
}
return (
<div className="flex flex-col p-4 md:p-16 gap-6 md:gap-12 mb-4 md:mb-0">
<div className="flex flex-col gap-4 md:flex-row md:items-center justify-between">
<h1>Create act</h1>
<div className="flex flex-row gap-3">
<Button disabled={isPending} onClick={handleSave}>
{isPending && <Spinner />}
Save
</Button>
</div>
</div>
<ActEditor
actTypes={actTypes}
institutions={institutions}
regions={regions}
positions={positions}
onChange={(data) => { dataRef.current = data; }}
/>
</div>
);
}
+422
View File
@@ -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<ActEditorData>;
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<ArticleContent[]>(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<ArticleContent>) {
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 (
<div className="flex flex-col gap-10">
<FieldSet>
<h2 className="md:mb-4">Meta</h2>
<FieldGroup>
<Field data-invalid={!!errors?.issuingInstitutionId?.length}>
<FieldLabel>Issuing institution</FieldLabel>
<Select
value={issuingInstitutionId}
onValueChange={(v) => {
setIssuingInstitutionId(v);
setActTypeId("");
setRegionId("");
}}
>
<SelectTrigger><SelectValue placeholder="Select an institution" /></SelectTrigger>
<SelectContent>
{institutions.map((i) => (
<SelectItem key={i.id} value={i.id}>{i.name}</SelectItem>
))}
</SelectContent>
</Select>
{errors?.issuingInstitutionId && <FieldError errors={errors.issuingInstitutionId.map((m) => ({ message: m }))} />}
</Field>
<Field>
<FieldLabel>Act type</FieldLabel>
<Select value={actTypeId} onValueChange={setActTypeId}>
<SelectTrigger><SelectValue placeholder={issuingInstitutionId ? "Select a type" : "Select an institution first"} /></SelectTrigger>
<SelectContent>
{availableActTypes.map((t) => (
<SelectItem key={t.id} value={t.id}>{t.name}</SelectItem>
))}
</SelectContent>
</Select>
</Field>
{needsRegion && (
<Field>
<FieldLabel>Region</FieldLabel>
<Select value={regionId} onValueChange={setRegionId}>
<SelectTrigger><SelectValue placeholder="Select a region" /></SelectTrigger>
<SelectContent>
{regions.map((r) => (
<SelectItem key={r.id} value={r.id}>{r.name}</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)}
<Field data-invalid={!!errors?.title?.length}>
<FieldLabel htmlFor="title">Title</FieldLabel>
<InputGroup>
<InputGroupInput
id="title"
value={title}
placeholder="On Citizenship"
onChange={(e) => setTitle(e.target.value)}
/>
</InputGroup>
{errors?.title && <FieldError errors={errors.title.map((m) => ({ message: m }))} />}
</Field>
</FieldGroup>
</FieldSet>
<div className="flex flex-col gap-6">
<div className="flex flex-col items-center gap-6">
<Image src="/emblems/europe.png" width={52} height={32} alt="Emblem of the European Federation" />
<div className={cn("flex flex-col items-center gap-1", documentHeading.className)}>
<h3>{!needsRegion ? "European Federation" : regions.find((region) => region.id === regionId)?.name}</h3>
<h3>{institutions.find((i) => i.id === issuingInstitutionId)?.name}</h3>
</div>
<h3 className={documentHeading.className}>
Draft of a {actTypes.find((a) => a.id === actTypeId)?.name} {title && `“${title}”`}
</h3>
</div>
<AutoResizeTextarea
className={cn("w-full bg-transparent resize-none outline-none leading-relaxed placeholder:text-muted-foreground", documentText.className)}
placeholder="Preamble (optional)"
value={preambleText}
onChange={(e) => setPreambleText(e.target.value)}
/>
<div className="flex flex-col gap-6">
{articles.map((article, index) => (
<div key={article.id} className="group relative flex flex-row gap-2 items-start">
<div className="flex-1 min-w-0">
<ArticleEditor
content={article}
articleIndex={index}
appointablePositions={positions}
onChange={(patch) => updateArticle(article.id, patch)}
/>
</div>
<div className="flex flex-col gap-1 items-center lg:opacity-0 group-hover:opacity-100 transition-opacity shrink-0 pt-2">
<Button variant="ghost" size="icon-sm" onClick={() => moveArticle(index, index - 1)} disabled={index === 0}>
<ChevronUpIcon />
</Button>
<Button variant="ghost" size="icon-sm" onClick={() => moveArticle(index, index + 1)} disabled={index === articles.length - 1}>
<ChevronDownIcon />
</Button>
{articles.length > 1 && (
<Button variant="ghost" size="icon-sm" onClick={() => removeArticle(article.id)}>
<Trash2Icon />
</Button>
)}
</div>
</div>
))}
<Button variant="outline" size="sm" className="w-max mt-4 gap-1.5 text-muted-foreground" onClick={addArticle}>
<PlusIcon size={14} />
Add article
</Button>
</div>
</div>
</div>
);
}
function ArticleEditor({
content,
articleIndex,
appointablePositions,
onChange,
}: {
content: ArticleContent;
articleIndex: number;
appointablePositions: PositionOption[];
onChange: (patch: Partial<ArticleContent>) => void;
}) {
const clauses = content.clauses ?? [makeEmptyTextClause()];
function updateClause(id: string, patch: Partial<Clause>) {
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 (
<div className="flex flex-col gap-2.5">
<div className="flex items-center gap-2">
<h4 className={cn("shrink-0", documentHeading.className)}>Article {articleIndex + 1}</h4>
<input
className={cn("flex-1 min-w-0 bg-transparent outline-none placeholder:text-muted-foreground", documentHeading.className)}
placeholder="Article title (optional)"
value={content.title ?? ""}
onChange={(e) => onChange({ title: e.target.value })}
/>
<Select value={content.markerStyle} onValueChange={(v) => onChange({ markerStyle: v as ClauseMarkerStyle })}>
<SelectTrigger className="w-36 h-7"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="NONE">No markers</SelectItem>
<SelectItem value="LETTERS"><CaseLowerIcon /> Letters</SelectItem>
<SelectItem value="NUMBERS"><ListOrderedIcon /> Numbers</SelectItem>
</SelectContent>
</Select>
</div>
{content.markerStyle !== "NONE" && (
<AutoResizeTextarea
className={cn("flex-1 min-w-0 bg-transparent outline-none placeholder:text-muted-foreground", documentText.className)}
placeholder="Introductory text..."
value={content.intro ?? ""}
onChange={(e) => onChange({ intro: e.target.value })}
/>
)}
<div className="flex flex-col gap-2">
{clauses.map((clause, i) => {
const marker = computeMarker(content.markerStyle, i);
return (
<div key={clause.id} className="flex gap-2 items-start group">
{marker && <span className="text-muted-foreground shrink-0 pt-1">{marker}</span>}
{clause.kind === "APPOINTMENT" ? (
<AppointmentClauseEditor
clause={clause}
positions={appointablePositions}
onChange={(patch) => updateClause(clause.id, patch)}
/>
) : (
<AutoResizeTextarea
className={cn(
"flex-1 min-w-0 bg-transparent resize-none outline-none placeholder:text-muted-foreground",
documentText.className,
marker && "italic"
)}
placeholder="Text..."
value={clause.text}
onChange={(e) => updateClause(clause.id, { text: e.target.value })}
/>
)}
<div className="flex gap-0.5 opacity-0 group-hover:opacity-100 shrink-0">
<Button variant="ghost" size="icon-sm" title="Add text clause" onClick={() => addClause(i, makeEmptyTextClause())}><PlusIcon /></Button>
<Button
variant="ghost"
size="icon-sm"
title="Add appointment clause"
disabled={appointablePositions.length === 0}
onClick={() => addClause(i, makeEmptyAppointmentClause())}
>
<UserCogIcon />
</Button>
{clauses.length > 1 && (
<Button variant="ghost" size="icon-sm" onClick={() => removeClause(clause.id)}><XIcon /></Button>
)}
</div>
</div>
);
})}
</div>
</div>
);
}
// 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<Clause, { kind: "APPOINTMENT" }>;
positions: PositionOption[];
onChange: (patch: Partial<Clause>) => void;
}) {
return (
<div className={cn("flex-1 min-w-0 flex flex-wrap items-center gap-1.5", documentText.className)}>
<Select value={clause.action} onValueChange={(v) => onChange({ action: v as "ASSIGN" | "DISMISS" })}>
<SelectTrigger className="h-7 w-28"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="ASSIGN">Appoint</SelectItem>
<SelectItem value="DISMISS">Dismiss</SelectItem>
</SelectContent>
</Select>
<CitizenshipPicker
value={clause.citizenshipId ? { id: clause.citizenshipId, name: clause.citizenshipName } : null}
onSelect={(c) => onChange({ citizenshipId: c?.id ?? "", citizenshipName: c?.name ?? "" })}
/>
<span className="text-muted-foreground">{clause.action === "ASSIGN" ? "to" : "from"}</span>
<Select value={clause.positionId} onValueChange={(v) => onChange({ positionId: v })}>
<SelectTrigger className="h-7 min-w-40"><SelectValue placeholder="a position" /></SelectTrigger>
<SelectContent>
{positions.map((p) => (
<SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
))}
</SelectContent>
</Select>
<span>.</span>
</div>
);
}
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 (
<span className="inline-flex items-center gap-1 border-b border-dotted">
{value.name}
<Button variant="ghost" size="icon-sm" className="h-5 w-5" onClick={() => onSelect(null)}><XIcon size={12} /></Button>
</span>
);
}
return (
<span className="relative inline-block">
<input
className="bg-transparent outline-none border-b border-dotted placeholder:text-muted-foreground w-40"
placeholder="a citizen"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
{results.length > 0 && (
<div className="absolute z-10 mt-1 w-48 bg-popover border rounded-md shadow-md">
{results.map((c) => (
<button
key={c.id}
type="button"
className="w-full text-left px-3 py-1.5 hover:bg-accent text-sm not-italic"
onClick={() => { onSelect({ id: c.id, name: `${c.firstName} ${c.secondName}` }); setQuery(""); setResults([]); }}
>
{c.firstName} {c.secondName}
</button>
))}
</div>
)}
</span>
);
}
function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void; className?: string; placeholder?: string }) {
const ref = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (ref.current) {
ref.current.style.height = "auto";
ref.current.style.height = `${ref.current.scrollHeight}px`;
}
}, [value]);
return <textarea ref={ref} rows={1} className={cn("overflow-hidden", className)} placeholder={placeholder} value={value} onChange={onChange} />;
}
+30
View File
@@ -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 <CreateActClient actTypes={actTypes} institutions={institutions.filter((institution) => userPositions.some((position) => position.position.institutionId === institution.id))} regions={regions} positions={positions} />;
}
+55
View File
@@ -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 (
<div className="flex flex-col p-4 md:p-16 gap-8 md:gap-16 mb-4 md:mb-0">
<div className="flex flex-col gap-4 md:flex-row md:items-center justify-between">
<h1>Acts</h1>
<SearchBar />
<div className="flex flex-row items-center gap-4">
{user?.isAdmin && (
<div className="flex flex-row items-center gap-4">
<Link href="/acts/create/"><Button variant="secondary">Create a new act</Button></Link>
</div>
)}
</div>
</div>
<div className="flex flex-col gap-6">
{
filteredActs.length > 0 ? filteredActs.map((a) => (
<div className="flex flex-col gap-2 md:gap-1" key={a.id}>
<Link href={`/acts/${a.id}`} className="max-w-vh">
<h3 className="hover:underline underline-offset-8 decoration-2 cursor-pointer truncate">{a.actType.name} {a.numberInSeries && `${a.numberInSeries}/${a.numberYear}`} “{a.title}”</h3>
</Link>
<div className="flex flex-col md:flex-row gap-0.5 md:gap-8 md:items-center">
<p className="flex gap-2 items-center"><LandmarkIcon size={16} /><span className="truncate">{a.issuingInstitution.name}</span></p>
<p className="flex gap-2 items-center"><CalendarIcon size={16} />{formatDate(a.createdAt)}</p>
</div>
</div>
)) : <h2 className="text-muted-foreground">There are no acts yet...</h2>
}
</div>
</div>
);
}