Compare commits
9
Commits
89012c215f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
646d6d326d | ||
|
|
cb8d4aeed3 | ||
|
|
04da7c325b | ||
|
|
8eefce6534 | ||
|
|
e4f0d5bca1 | ||
|
|
746e6e57be | ||
|
|
2a85485de4 | ||
|
|
db97576fc5 | ||
|
|
669c2027b9 |
@@ -1,87 +0,0 @@
|
|||||||
name: Build and Deploy
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
lint-frontend:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Node.js
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: '20'
|
|
||||||
cache: 'npm'
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Lint frontend
|
|
||||||
run: npm run lint
|
|
||||||
|
|
||||||
build-frontend:
|
|
||||||
needs: lint-frontend
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Node.js
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: '20'
|
|
||||||
cache: 'npm'
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Build frontend
|
|
||||||
run: npm run build
|
|
||||||
|
|
||||||
- name: Build and push Docker image
|
|
||||||
run: |
|
|
||||||
docker build -t ${{ vars.DOCKER_REGISTRY }}/${{ vars.DOCKER_IMAGE }}:latest .
|
|
||||||
docker push ${{ vars.DOCKER_REGISTRY }}/${{ vars.DOCKER_IMAGE }}:latest
|
|
||||||
|
|
||||||
deploy:
|
|
||||||
needs: build-frontend
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup SSH key
|
|
||||||
run: |
|
|
||||||
mkdir -p ~/.ssh
|
|
||||||
cat > ~/.ssh/deploy_key << 'EOF'
|
|
||||||
${{ secrets.DEPLOY_SSH_KEY }}
|
|
||||||
EOF
|
|
||||||
chmod 600 ~/.ssh/deploy_key
|
|
||||||
ssh-keyscan -p ${{ vars.DEPLOY_PORT }} ${{ vars.DEPLOY_HOST }} >> ~/.ssh/known_hosts 2>/dev/null || true
|
|
||||||
|
|
||||||
- name: Create .env file on server
|
|
||||||
run: |
|
|
||||||
ssh -i ~/.ssh/deploy_key -p ${{ vars.DEPLOY_PORT }} ${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }} \
|
|
||||||
"cat > /opt/app/.env" << 'ENVEOF'
|
|
||||||
PUBLIC_URL=${{ vars.PUBLIC_URL }}
|
|
||||||
DATABASE_URL=${{ secrets.DATABASE_URL }}
|
|
||||||
KOTOSOFT_ID_API_PUBLIC_URL=${{ vars.KOTOSOFT_ID_API_PUBLIC_URL }}
|
|
||||||
KOTOSOFT_ID_API_URL=${{ vars.KOTOSOFT_ID_API_URL }}
|
|
||||||
KOTOSOFT_CLIENT_ID=${{ secrets.KOTOSOFT_CLIENT_ID }}
|
|
||||||
KOTOSOFT_CLIENT_SECRET=${{ secrets.KOTOSOFT_CLIENT_SECRET }}
|
|
||||||
JWT_SECRET=${{ secrets.JWT_SECRET }}
|
|
||||||
MINIO_ACCESS_KEY=${{ secrets.MINIO_ACCESS_KEY }}
|
|
||||||
MINIO_SECRET_KEY=${{ secrets.MINIO_SECRET_KEY }}
|
|
||||||
MINIO_PUBLIC_URL=${{ vars.MINIO_PUBLIC_URL }}
|
|
||||||
LETSENCRYPT_HOST=${{ vars.DOMAIN }}
|
|
||||||
LETSENCRYPT_EMAIL=${{ vars.LETSENCRYPT_EMAIL }}
|
|
||||||
DOMAIN=${{ vars.DOMAIN }}
|
|
||||||
ENVEOF
|
|
||||||
|
|
||||||
- name: Deploy with Docker Compose
|
|
||||||
run: |
|
|
||||||
ssh -i ~/.ssh/deploy_key -p ${{ vars.DEPLOY_PORT }} ${{ vars.DEPLOY_USER }}@${{ vars.DEPLOY_HOST }} \
|
|
||||||
"cd /opt/app && docker compose -p ${{ vars.DOCKER_COMPOSE_PROJECT }} up -d"
|
|
||||||
@@ -45,3 +45,5 @@ next-env.d.ts
|
|||||||
|
|
||||||
/lib/generated/prisma
|
/lib/generated/prisma
|
||||||
.prisma/
|
.prisma/
|
||||||
|
|
||||||
|
docker-compose.yml
|
||||||
+2
-1
@@ -17,7 +17,8 @@ COPY --from=builder /app/public ./public
|
|||||||
COPY --from=builder /app/prisma ./prisma
|
COPY --from=builder /app/prisma ./prisma
|
||||||
COPY --from=builder /app/next.config.ts ./next.config.ts
|
COPY --from=builder /app/next.config.ts ./next.config.ts
|
||||||
RUN npm prune --omit=dev
|
RUN npm prune --omit=dev
|
||||||
EXPOSE 80
|
USER node
|
||||||
|
EXPOSE 3000
|
||||||
CMD ["npm", "start", "--", "-p", "3000", "-H", "0.0.0.0"]
|
CMD ["npm", "start", "--", "-p", "3000", "-H", "0.0.0.0"]
|
||||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||||
CMD wget -q --spider http://localhost:3000/ || exit 1
|
CMD wget -q --spider http://localhost:3000/ || exit 1
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { BookOpenTextIcon, BriefcaseBusinessIcon, UserIcon } from "lucide-react";
|
import { BookOpenTextIcon, UserIcon } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
|
|
||||||
@@ -15,11 +15,6 @@ const menuItems = [
|
|||||||
href: "/account/citizenship",
|
href: "/account/citizenship",
|
||||||
label: "Citizenship",
|
label: "Citizenship",
|
||||||
icon: BookOpenTextIcon,
|
icon: BookOpenTextIcon,
|
||||||
},
|
|
||||||
{
|
|
||||||
href: "/account/positions",
|
|
||||||
label: "Positions",
|
|
||||||
icon: BriefcaseBusinessIcon,
|
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
"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 (
|
|
||||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
|
||||||
<DialogTrigger asChild>
|
|
||||||
<Button variant="secondary" className="w-max">Create a new position</Button>
|
|
||||||
</DialogTrigger>
|
|
||||||
<DialogContent>
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle asChild><h3>Create a new position</h3></DialogTitle>
|
|
||||||
</DialogHeader>
|
|
||||||
<FieldGroup>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel htmlFor="name">Position name</FieldLabel>
|
|
||||||
<Input
|
|
||||||
placeholder="Position name"
|
|
||||||
value={name}
|
|
||||||
onChange={(e) => setName(e.target.value)}
|
|
||||||
/>
|
|
||||||
{state.fieldErrors?.name && <FieldError>{state.fieldErrors.name}</FieldError>}
|
|
||||||
</Field>
|
|
||||||
<Field>
|
|
||||||
<FieldLabel htmlFor="name">Institution</FieldLabel>
|
|
||||||
<Select onValueChange={setInstitutionId} value={institutionId}>
|
|
||||||
<SelectTrigger>
|
|
||||||
<SelectValue placeholder="Select institution" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{
|
|
||||||
institutions.map((institution) => (
|
|
||||||
<SelectItem key={institution.id} value={institution.id}>{institution.name}</SelectItem>
|
|
||||||
))
|
|
||||||
}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
{state.fieldErrors?.institutionId && <FieldError>{state.fieldErrors.institutionId}</FieldError>}
|
|
||||||
</Field>
|
|
||||||
</FieldGroup>
|
|
||||||
{state.error && <FieldError>{state.error}</FieldError>}
|
|
||||||
<DialogFooter>
|
|
||||||
<DialogClose asChild>
|
|
||||||
<Button variant="outline" disabled={isPending}>Cancel</Button>
|
|
||||||
</DialogClose>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
disabled={isPending}
|
|
||||||
onClick={handleSubmit}>
|
|
||||||
{isPending && <Spinner />}Create
|
|
||||||
</Button>
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
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 (
|
|
||||||
<div className="flex flex-col md:flex-row p-4 md:p-16 gap-8 md:gap-16 mb-4 md:mb-0">
|
|
||||||
<AccountMenu />
|
|
||||||
<div className="flex flex-col gap-8 max-w-lg">
|
|
||||||
<div className="flex flex-col gap-6">
|
|
||||||
<div className="flex flex-col gap-1">
|
|
||||||
<h2>Positions</h2>
|
|
||||||
<p className="text-muted-foreground text-sm">Here are your positions in the European Federation</p>
|
|
||||||
</div>
|
|
||||||
{userPositions.length === 0 ? <p className="text-muted-foreground">You do not have any positions</p> :
|
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
{userPositions.map((position) => (
|
|
||||||
<div key={position.id} className="flex flex-col gap-0.5">
|
|
||||||
<h4>{position.position.name}</h4>
|
|
||||||
<p className="text-muted-foreground">Assigned on {formatDate(position.assignedAt)} by <Link href={`/acts/${position.actId}`} className="underline">{position.act?.actType.name} {position.act?.numberInSeries && `№${position.act.numberInSeries}/${position.act.numberYear}`}</Link></p>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
{user.isAdmin && (
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
<CreatePositionDialog institutions={institutions} />
|
|
||||||
<p className="text-muted-foreground">
|
|
||||||
To assign or dismiss someone from a position, create an appointment act.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,220 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
"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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,422 +0,0 @@
|
|||||||
"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} />;
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
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} />;
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export function GET() {
|
||||||
|
return Response.json({ ok: true });
|
||||||
|
}
|
||||||
+1
-1
@@ -5,7 +5,7 @@ import { getPages } from "@/lib/pages/repository";
|
|||||||
import { getCurrentUser } from "@/lib/user";
|
import { getCurrentUser } from "@/lib/user";
|
||||||
import { Metadata } from "next";
|
import { Metadata } from "next";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import SearchBar from "../../components/searchBar";
|
import SearchBar from "./searchBar";
|
||||||
|
|
||||||
export const metadata: Metadata = { title: "News" };
|
export const metadata: Metadata = { title: "News" };
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export default function Footer() {
|
|||||||
<footer className="flex flex-col w-full px-4 lg:px-16 py-8 gap-8 bg-muted">
|
<footer className="flex flex-col w-full px-4 lg:px-16 py-8 gap-8 bg-muted">
|
||||||
<div className="flex flex-col lg:flex-row lg:items-center gap-4">
|
<div className="flex flex-col lg:flex-row lg:items-center gap-4">
|
||||||
<Image
|
<Image
|
||||||
src="/emblems/europe.png"
|
src="/emblem.png"
|
||||||
width={28}
|
width={28}
|
||||||
height={28}
|
height={28}
|
||||||
alt="Emblem of the European Federation"
|
alt="Emblem of the European Federation"
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ export default async function Header() {
|
|||||||
return (
|
return (
|
||||||
<header className="relative flex items-center justify-between w-full h-16 px-4 sm:px-8 bg-white sm:bg-gray-100">
|
<header className="relative flex items-center justify-between w-full h-16 px-4 sm:px-8 bg-white sm:bg-gray-100">
|
||||||
<Link href="/" className="flex items-center gap-4 shrink-0">
|
<Link href="/" className="flex items-center gap-4 shrink-0">
|
||||||
<Image src="/emblems/europe.png" width={28} height={28} alt="Emblem of the European Federation" />
|
<Image src="/emblem.png" width={28} height={28} alt="Emblem of the European Federation" />
|
||||||
<h3 className="hidden sm:block">European Federation</h3>
|
<h3 className="hidden sm:block">European Federation</h3>
|
||||||
</Link>
|
</Link>
|
||||||
<div className="hidden md:flex absolute left-1/2 -translate-x-1/2 items-center gap-6">
|
<div className="hidden md:flex absolute left-1/2 -translate-x-1/2 items-center gap-6">
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ export default function IdentityCard({ data }: { data: IdentityCardData }) {
|
|||||||
<div className="relative z-10">
|
<div className="relative z-10">
|
||||||
<div className="flex flex-row items-center justify-between">
|
<div className="flex flex-row items-center justify-between">
|
||||||
<div className="flex flex-row gap-3 items-center">
|
<div className="flex flex-row gap-3 items-center">
|
||||||
<Image src="/emblems/europe.png" width={24} height={24} alt="Emblem" />
|
<Image src="/emblem.png" width={24} height={24} alt="Emblem" />
|
||||||
<h2>ID Card</h2>
|
<h2>ID Card</h2>
|
||||||
</div>
|
</div>
|
||||||
<h3>{data.documentNumber}</h3>
|
<h3>{data.documentNumber}</h3>
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export function MobileNav({ links, isAuthenticated }: { links: NavLink[]; isAuth
|
|||||||
<div className="fixed inset-0 z-50 bg-white flex flex-col">
|
<div className="fixed inset-0 z-50 bg-white flex flex-col">
|
||||||
<div className="flex items-center justify-between h-16 px-4">
|
<div className="flex items-center justify-between h-16 px-4">
|
||||||
<Link href="/" onClick={() => setOpen(false)} className="flex items-center gap-4 shrink-0">
|
<Link href="/" onClick={() => setOpen(false)} className="flex items-center gap-4 shrink-0">
|
||||||
<Image src="/emblems/europe.png" width={28} height={28} alt="Emblem of the European Federation" />
|
<Image src="/emblem.png" width={28} height={28} alt="Emblem of the European Federation" />
|
||||||
<h3 className="hidden sm:block">European Federation</h3>
|
<h3 className="hidden sm:block">European Federation</h3>
|
||||||
</Link>
|
</Link>
|
||||||
<Button variant="ghost" size="icon" onClick={() => setOpen(false)} aria-label="Close menu">
|
<Button variant="ghost" size="icon" onClick={() => setOpen(false)} aria-label="Close menu">
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
services:
|
|
||||||
eu:
|
|
||||||
image: 172.17.0.1:5000/eu:latest
|
|
||||||
restart: unless-stopped
|
|
||||||
environment:
|
|
||||||
PUBLIC_URL: ${PUBLIC_URL}
|
|
||||||
DATABASE_URL: ${DATABASE_URL}
|
|
||||||
|
|
||||||
KOTOSOFT_ID_API_PUBLIC_URL: ${KOTOSOFT_ID_API_PUBLIC_URL}
|
|
||||||
KOTOSOFT_ID_API_URL: ${KOTOSOFT_ID_API_URL}
|
|
||||||
KOTOSOFT_CLIENT_ID: ${KOTOSOFT_CLIENT_ID}
|
|
||||||
KOTOSOFT_CLIENT_SECRET: ${KOTOSOFT_CLIENT_SECRET}
|
|
||||||
|
|
||||||
JWT_SECRET: ${JWT_SECRET}
|
|
||||||
SESSION_MAX_AGE: 604800
|
|
||||||
|
|
||||||
MINIO_ACCESS_KEY: ${MINIO_ACCESS_KEY}
|
|
||||||
MINIO_SECRET_KEY: ${MINIO_SECRET_KEY}
|
|
||||||
MINIO_PUBLIC_URL: ${MINIO_PUBLIC_URL}
|
|
||||||
|
|
||||||
VIRTUAL_HOST: ${DOMAIN}
|
|
||||||
VIRTUAL_PORT: 3000
|
|
||||||
LETSENCRYPT_HOST: ${DOMAIN}
|
|
||||||
LETSENCRYPT_EMAIL: ${LETSENCRYPT_EMAIL}
|
|
||||||
expose:
|
|
||||||
- "3000"
|
|
||||||
networks:
|
|
||||||
- proxy
|
|
||||||
- eu_net
|
|
||||||
|
|
||||||
networks:
|
|
||||||
proxy:
|
|
||||||
external: true
|
|
||||||
eu_net:
|
|
||||||
external: true
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
"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<ActionResult> {
|
|
||||||
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<ActionResult> {
|
|
||||||
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<ActionResult> {
|
|
||||||
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<ActionResult> {
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
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<string, ActFlow> = {
|
|
||||||
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));
|
|
||||||
}
|
|
||||||
@@ -1,187 +0,0 @@
|
|||||||
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<ActBlockRecord[]> {
|
|
||||||
return prisma.actBlock.findMany({
|
|
||||||
where: { versionId },
|
|
||||||
orderBy: { position: "asc" },
|
|
||||||
}) as Promise<ActBlockRecord[]>;
|
|
||||||
}
|
|
||||||
|
|
||||||
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" } });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
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<ActLegalStatus, string> = {
|
|
||||||
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;
|
|
||||||
};
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
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<typeof actSchema>;
|
|
||||||
|
|
||||||
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 };
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,7 @@ import { runAction, isPrismaError } from "@/lib/run-action";
|
|||||||
import { AppError, type ActionResult } from "@/lib/action-result";
|
import { AppError, type ActionResult } from "@/lib/action-result";
|
||||||
import { formAction } from "@/lib/form-action";
|
import { formAction } from "@/lib/form-action";
|
||||||
import { citizenshipApplicationSchema } from "./validation";
|
import { citizenshipApplicationSchema } from "./validation";
|
||||||
import { createApplication, getActiveCitizenship, getApplicationEligibility, searchActiveCitizenships } from "./repository";
|
import { createApplication, getActiveCitizenship, getApplicationEligibility } from "./repository";
|
||||||
import { prisma } from "../prisma";
|
import { prisma } from "../prisma";
|
||||||
import { formatAddress } from "@/lib/address";
|
import { formatAddress } from "@/lib/address";
|
||||||
import { Prisma } from "@/lib/generated/prisma/client";
|
import { Prisma } from "@/lib/generated/prisma/client";
|
||||||
@@ -179,17 +179,6 @@ export async function rejectApplication(id: string, reason: string): Promise<Act
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function searchCitizensAction(query: string): Promise<ActionResult<{ id: string; firstName: string; secondName: string }[]>> {
|
|
||||||
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<ActionResult> {
|
export async function renounceCitizenship(): Promise<ActionResult> {
|
||||||
return runAction(async () => {
|
return runAction(async () => {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
|
|||||||
@@ -103,27 +103,3 @@ export async function getActiveCitizenship(userId: string) {
|
|||||||
where: { userId, revokedAt: null },
|
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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
+37
-12
@@ -1,29 +1,42 @@
|
|||||||
import crypto from "crypto";
|
import crypto from "crypto";
|
||||||
import sharp from "sharp";
|
import sharp from "sharp";
|
||||||
|
import { DeleteObjectCommand, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
|
||||||
|
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||||
|
|
||||||
import { AppError } from "@/lib/action-result";
|
import { AppError } from "@/lib/action-result";
|
||||||
import { getMinioClient } from "@/lib/minio";
|
import { BUCKET, getInternalClient, getPublicClient } from "@/lib/storage";
|
||||||
|
|
||||||
const BUCKET = "uploads";
|
|
||||||
const MAX_FILE_SIZE = 5 * 1024 * 1024;
|
const MAX_FILE_SIZE = 5 * 1024 * 1024;
|
||||||
const ALLOWED_INPUT_FORMATS = new Set(["jpeg", "png", "webp"]);
|
const ALLOWED_INPUT_FORMATS = new Set(["jpeg", "png", "webp"]);
|
||||||
|
|
||||||
export async function uploadImage(file: File, directory: string, options: { maxWidth?: number; maxHeight?: number; fit?: "inside" | "cover" }): Promise<string> {
|
const DIRECTORY_RE = /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*$/;
|
||||||
|
const KEY_RE = /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.webp$/;
|
||||||
|
|
||||||
|
const URL_WINDOW_SEC = 60 * 60;
|
||||||
|
const URL_EXPIRES_SEC = URL_WINDOW_SEC * 2;
|
||||||
|
|
||||||
|
export async function uploadImage(
|
||||||
|
file: File,
|
||||||
|
directory: string,
|
||||||
|
options: { maxWidth?: number; maxHeight?: number; fit?: "inside" | "cover" } = {},
|
||||||
|
): Promise<string> {
|
||||||
|
if (!DIRECTORY_RE.test(directory)) throw new Error("Invalid upload directory");
|
||||||
if (file.size === 0) throw new AppError("A file is required");
|
if (file.size === 0) throw new AppError("A file is required");
|
||||||
if (file.size > MAX_FILE_SIZE) throw new AppError("Image must be smaller than 5MB");
|
if (file.size > MAX_FILE_SIZE) throw new AppError("Image must be smaller than 5MB");
|
||||||
|
|
||||||
const input = Buffer.from(await file.arrayBuffer());
|
const input = Buffer.from(await file.arrayBuffer());
|
||||||
|
if (input.length > MAX_FILE_SIZE) throw new AppError("Image must be smaller than 5MB");
|
||||||
|
|
||||||
const image = sharp(input, {
|
const image = sharp(input, {
|
||||||
failOn: "error",
|
failOn: "error",
|
||||||
limitInputPixels: 30_000_000,
|
limitInputPixels: 30_000_000,
|
||||||
|
sequentialRead: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const metadata = await image.metadata();
|
const metadata = await image.metadata();
|
||||||
if (!metadata.format || !ALLOWED_INPUT_FORMATS.has(metadata.format)) {
|
if (!metadata.format || !ALLOWED_INPUT_FORMATS.has(metadata.format)) {
|
||||||
throw new AppError("Only JPEG, PNG, or WEBP images are allowed");
|
throw new AppError("Only JPEG, PNG, or WEBP images are allowed");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!metadata.width || !metadata.height || metadata.width < 100 || metadata.height < 100) {
|
if (!metadata.width || !metadata.height || metadata.width < 100 || metadata.height < 100) {
|
||||||
throw new AppError("Image is too small");
|
throw new AppError("Image is too small");
|
||||||
}
|
}
|
||||||
@@ -41,19 +54,31 @@ export async function uploadImage(file: File, directory: string, options: { maxW
|
|||||||
.webp({ quality: 80, effort: 4 })
|
.webp({ quality: 80, effort: 4 })
|
||||||
.toBuffer();
|
.toBuffer();
|
||||||
|
|
||||||
const key = `${directory}/${crypto.randomUUID()}.webp`;
|
const key = `${directory}/${crypto.randomUUID()}.webp`;
|
||||||
await getMinioClient().putObject(BUCKET, key, output, output.length, { "Content-Type": "image/webp" });
|
await getInternalClient().send(
|
||||||
|
new PutObjectCommand({
|
||||||
|
Bucket: BUCKET,
|
||||||
|
Key: key,
|
||||||
|
Body: output,
|
||||||
|
ContentLength: output.length,
|
||||||
|
ContentType: "image/webp",
|
||||||
|
CacheControl: "public, max-age=31536000, immutable",
|
||||||
|
}),
|
||||||
|
);
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function removeImage(key: string) {
|
export async function removeImage(key: string) {
|
||||||
await getMinioClient().removeObject(BUCKET, key)
|
if (!KEY_RE.test(key)) throw new Error("Invalid image key");
|
||||||
|
await getInternalClient().send(new DeleteObjectCommand({ Bucket: BUCKET, Key: key }));
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getImageUrl(key: string): Promise<string> {
|
export async function getImageUrl(key: string): Promise<string> {
|
||||||
return getMinioClient().presignedGetObject(
|
if (!KEY_RE.test(key)) throw new Error("Invalid image key");
|
||||||
BUCKET,
|
const windowMs = URL_WINDOW_SEC * 1000;
|
||||||
key,
|
const signingDate = new Date(Math.floor(Date.now() / windowMs) * windowMs);
|
||||||
60 * 5
|
return getSignedUrl(getPublicClient(), new GetObjectCommand({ Bucket: BUCKET, Key: key }), {
|
||||||
);
|
expiresIn: URL_EXPIRES_SEC,
|
||||||
|
signingDate,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
import { Client } from "minio";
|
|
||||||
|
|
||||||
let _client: Client | null = null;
|
|
||||||
|
|
||||||
export function getMinioClient(): Client {
|
|
||||||
if (!_client) {
|
|
||||||
const url = new URL(process.env.MINIO_PUBLIC_URL!);
|
|
||||||
_client = new Client({
|
|
||||||
endPoint: url.hostname,
|
|
||||||
port: url.port ? Number(url.port) : 443,
|
|
||||||
useSSL: url.protocol === "https:",
|
|
||||||
accessKey: process.env.MINIO_ACCESS_KEY!,
|
|
||||||
secretKey: process.env.MINIO_SECRET_KEY!,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return _client;
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
"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");
|
|
||||||
});
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
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<Position, "id">) {
|
|
||||||
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" },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
+2
-5
@@ -5,9 +5,6 @@ import { PrismaClient } from "@/lib/generated/prisma/client";
|
|||||||
const connectionString = `${process.env.DATABASE_URL}`;
|
const connectionString = `${process.env.DATABASE_URL}`;
|
||||||
|
|
||||||
const adapter = new PrismaPg({ connectionString });
|
const adapter = new PrismaPg({ connectionString });
|
||||||
|
const prisma = new PrismaClient({ adapter });
|
||||||
|
|
||||||
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
|
export { prisma };
|
||||||
|
|
||||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter });
|
|
||||||
|
|
||||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { S3Client } from "@aws-sdk/client-s3";
|
||||||
|
|
||||||
|
function env(name: string): string {
|
||||||
|
const value = process.env[name];
|
||||||
|
if (!value) throw new Error(`Missing environment variable: ${name}`);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BUCKET = process.env.RUSTFS_BUCKET ?? "uploads";
|
||||||
|
const REGION = process.env.RUSTFS_REGION ?? "us-east-1";
|
||||||
|
|
||||||
|
let internalClient: S3Client | null = null;
|
||||||
|
let publicClient: S3Client | null = null;
|
||||||
|
|
||||||
|
const credentials = () => ({
|
||||||
|
accessKeyId: env("RUSTFS_ACCESS_KEY"),
|
||||||
|
secretAccessKey: env("RUSTFS_SECRET_KEY"),
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
export function getInternalClient(): S3Client {
|
||||||
|
internalClient ??= new S3Client({
|
||||||
|
endpoint: `http://${env("RUSTFS_INTERNAL_HOST")}:${process.env.RUSTFS_INTERNAL_PORT ?? 9000}`,
|
||||||
|
region: REGION,
|
||||||
|
credentials: credentials(),
|
||||||
|
forcePathStyle: true,
|
||||||
|
requestChecksumCalculation: "WHEN_REQUIRED",
|
||||||
|
responseChecksumValidation: "WHEN_REQUIRED",
|
||||||
|
maxAttempts: 3,
|
||||||
|
requestHandler: { connectionTimeout: 3_000, requestTimeout: 15_000 },
|
||||||
|
});
|
||||||
|
return internalClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPublicClient(): S3Client {
|
||||||
|
publicClient ??= new S3Client({
|
||||||
|
endpoint: new URL(env("RUSTFS_PUBLIC_URL")).origin,
|
||||||
|
region: REGION,
|
||||||
|
credentials: credentials(),
|
||||||
|
forcePathStyle: true,
|
||||||
|
requestChecksumCalculation: "WHEN_REQUIRED",
|
||||||
|
responseChecksumValidation: "WHEN_REQUIRED",
|
||||||
|
});
|
||||||
|
return publicClient;
|
||||||
|
}
|
||||||
+13
-9
@@ -1,22 +1,26 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
const minioHost = process.env.MINIO_PUBLIC_URL ? new URL(process.env.MINIO_PUBLIC_URL).hostname : "localhost";
|
const publicUrl = process.env.RUSTFS_PUBLIC_URL ? new URL(process.env.RUSTFS_PUBLIC_URL) : null;
|
||||||
const minioPort = process.env.MINIO_PUBLIC_URL ? new URL(process.env.MINIO_PUBLIC_URL).port : undefined;
|
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
images: {
|
images: {
|
||||||
remotePatterns: [
|
remotePatterns: publicUrl
|
||||||
{
|
? [
|
||||||
hostname: minioHost,
|
{
|
||||||
...(minioPort ? { port: minioPort } : {}),
|
protocol: publicUrl.protocol === "https:" ? "https" : "http",
|
||||||
},
|
hostname: publicUrl.hostname,
|
||||||
],
|
...(publicUrl.port ? { port: publicUrl.port } : {}),
|
||||||
|
pathname: `/${process.env.RUSTFS_BUCKET ?? "uploads"}/**`,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
},
|
},
|
||||||
experimental: {
|
experimental: {
|
||||||
serverActions: {
|
serverActions: {
|
||||||
bodySizeLimit: "5mb",
|
bodySizeLimit: "6mb",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
output: "standalone",
|
||||||
};
|
};
|
||||||
|
|
||||||
export default nextConfig;
|
export default nextConfig;
|
||||||
+34
-25
@@ -9,39 +9,41 @@
|
|||||||
"lint": "eslint"
|
"lint": "eslint"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@aws-sdk/client-s3": "^3.1169.0",
|
||||||
|
"@aws-sdk/s3-request-presigner": "^3.1169.0",
|
||||||
"@imgly/background-removal": "^1.7.0",
|
"@imgly/background-removal": "^1.7.0",
|
||||||
"@prisma/adapter-pg": "^7.8.0",
|
"@prisma/adapter-pg": "^7.10.1",
|
||||||
"@prisma/client": "^7.8.0",
|
"@prisma/client": "^7.10.1",
|
||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"jose": "^6.2.3",
|
"jose": "^6.2.17",
|
||||||
"lucide-react": "^1.20.0",
|
"lucide-react": "^1.73.0",
|
||||||
"minio": "^8.0.7",
|
"next": "16.4.6",
|
||||||
"next": "16.2.9",
|
"pg": "^8.23.1",
|
||||||
"pg": "^8.21.0",
|
"radix-ui": "^1.8.1",
|
||||||
"radix-ui": "^1.6.0",
|
|
||||||
"react": "19.2.4",
|
"react": "19.2.4",
|
||||||
"react-dom": "19.2.4",
|
"react-dom": "19.2.4",
|
||||||
"shadcn": "^4.11.0",
|
"server-only": "^0.0.1",
|
||||||
"sharp": "^0.35.3",
|
"sharp": "^0.35.5",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.8",
|
||||||
"tailwind-merge": "^3.6.0",
|
"tailwind-merge": "^3.7.0",
|
||||||
"tw-animate-css": "^1.4.0",
|
"tw-animate-css": "^1.4.0",
|
||||||
"uuid": "^14.0.0",
|
"uuid": "^14.0.3",
|
||||||
"zod": "^4.4.3"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tailwindcss/postcss": "^4",
|
"@tailwindcss/postcss": "^4.3.5",
|
||||||
"@types/node": "^20",
|
"@types/node": "^20.19.43",
|
||||||
"@types/pg": "^8.20.0",
|
"@types/pg": "^8.23.1",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19.3.0",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19.3.0",
|
||||||
"eslint": "^9",
|
"eslint": "^9.39.5",
|
||||||
"eslint-config-next": "16.2.9",
|
"eslint-config-next": "16.4.6",
|
||||||
"prisma": "^7.8.0",
|
"prisma": "^7.10.1",
|
||||||
"tailwindcss": "^4",
|
"shadcn": "^4.23.0",
|
||||||
"typescript": "^5"
|
"tailwindcss": "^4.3.5",
|
||||||
|
"typescript": "^5.9.3"
|
||||||
},
|
},
|
||||||
"ignoreScripts": [
|
"ignoreScripts": [
|
||||||
"sharp",
|
"sharp",
|
||||||
@@ -54,5 +56,12 @@
|
|||||||
"protobufjs",
|
"protobufjs",
|
||||||
"sharp",
|
"sharp",
|
||||||
"unrs-resolver"
|
"unrs-resolver"
|
||||||
]
|
],
|
||||||
|
"overrides": {
|
||||||
|
"fast-xml-parser": "^5.10.1",
|
||||||
|
"source-map-js": "^1.2.2",
|
||||||
|
"baseline-browser-mapping": "^2.11.0",
|
||||||
|
"fast-uri": "^3.1.6",
|
||||||
|
"zod": "^4.6.7"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+64
-254
@@ -27,25 +27,23 @@ enum EyeColor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model User {
|
model User {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
kotosoftId String @unique
|
kotosoftId String @unique
|
||||||
email String @unique
|
email String @unique
|
||||||
firstName String
|
firstName String
|
||||||
secondName String
|
secondName String
|
||||||
sex Sex
|
sex Sex
|
||||||
birthDate DateTime?
|
birthDate DateTime?
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
isAdmin Boolean @default(false)
|
isAdmin Boolean @default(false)
|
||||||
|
|
||||||
pages Page[] @relation("PageAuthor")
|
pages Page[] @relation("PageAuthor")
|
||||||
editedPages Page[] @relation("PageEditor")
|
editedPages Page[] @relation("PageEditor")
|
||||||
|
|
||||||
citizenshipApplications CitizenshipApplication[]
|
citizenshipApplications CitizenshipApplication[]
|
||||||
reviewedApplications CitizenshipApplication[] @relation("CitizenshipReviewer")
|
reviewedApplications CitizenshipApplication[] @relation("CitizenshipReviewer")
|
||||||
|
|
||||||
citizenships Citizenship[]
|
citizenships Citizenship[]
|
||||||
|
|
||||||
acts Act[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
enum PageStatus {
|
enum PageStatus {
|
||||||
@@ -70,20 +68,20 @@ model Page {
|
|||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
publishedAt DateTime?
|
publishedAt DateTime?
|
||||||
|
|
||||||
createdBy String?
|
createdBy String?
|
||||||
author User? @relation("PageAuthor", fields: [createdBy], references: [id])
|
author User? @relation("PageAuthor", fields: [createdBy], references: [id])
|
||||||
|
|
||||||
updatedBy String?
|
updatedBy String?
|
||||||
editor User? @relation("PageEditor", fields: [updatedBy], references: [id])
|
editor User? @relation("PageEditor", fields: [updatedBy], references: [id])
|
||||||
|
|
||||||
blocks Block[]
|
blocks Block[]
|
||||||
navLinks NavLink[]
|
navLinks NavLink[]
|
||||||
}
|
}
|
||||||
|
|
||||||
model Block {
|
model Block {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
pageId String
|
pageId String
|
||||||
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
|
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
parentId String?
|
parentId String?
|
||||||
parent Block? @relation("BlockChildren", fields: [parentId], references: [id])
|
parent Block? @relation("BlockChildren", fields: [parentId], references: [id])
|
||||||
@@ -97,13 +95,13 @@ model Block {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model NavLink {
|
model NavLink {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
label String?
|
label String?
|
||||||
order Int
|
order Int
|
||||||
|
|
||||||
pageId String?
|
pageId String?
|
||||||
page Page? @relation(fields: [pageId], references: [id], onDelete: SetNull)
|
page Page? @relation(fields: [pageId], references: [id], onDelete: SetNull)
|
||||||
href String?
|
href String?
|
||||||
}
|
}
|
||||||
|
|
||||||
enum CitizenshipApplicationStatus {
|
enum CitizenshipApplicationStatus {
|
||||||
@@ -118,35 +116,35 @@ enum ApplicationType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model CitizenshipApplication {
|
model CitizenshipApplication {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
userId String
|
userId String
|
||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
surname String
|
surname String
|
||||||
givenNames String
|
givenNames String
|
||||||
sex Sex
|
sex Sex
|
||||||
birthDate DateTime
|
birthDate DateTime
|
||||||
applicationType ApplicationType
|
applicationType ApplicationType
|
||||||
previousCountry String?
|
previousCountry String?
|
||||||
previousRegion String?
|
previousRegion String?
|
||||||
naturalizationReason String?
|
naturalizationReason String?
|
||||||
address String
|
address String
|
||||||
regionId String?
|
regionId String?
|
||||||
region Region? @relation(fields: [regionId], references: [id])
|
region Region? @relation(fields: [regionId], references: [id])
|
||||||
city String?
|
city String?
|
||||||
street String?
|
street String?
|
||||||
customAddress String?
|
customAddress String?
|
||||||
height Int
|
height Int
|
||||||
eyeColor EyeColor
|
eyeColor EyeColor
|
||||||
status CitizenshipApplicationStatus @default(PENDING)
|
status CitizenshipApplicationStatus @default(PENDING)
|
||||||
rejectionReason String?
|
rejectionReason String?
|
||||||
reviewedAt DateTime?
|
reviewedAt DateTime?
|
||||||
reviewedBy String?
|
reviewedBy String?
|
||||||
reviewer User? @relation("CitizenshipReviewer", fields: [reviewedBy], references: [id])
|
reviewer User? @relation("CitizenshipReviewer", fields: [reviewedBy], references: [id])
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
updatedAt DateTime @updatedAt
|
updatedAt DateTime @updatedAt
|
||||||
profileKey String
|
profileKey String
|
||||||
signatureKey String
|
signatureKey String
|
||||||
citizenship Citizenship?
|
citizenship Citizenship?
|
||||||
}
|
}
|
||||||
|
|
||||||
model Citizenship {
|
model Citizenship {
|
||||||
@@ -156,225 +154,37 @@ model Citizenship {
|
|||||||
issuedAt DateTime @default(now())
|
issuedAt DateTime @default(now())
|
||||||
revokedAt DateTime?
|
revokedAt DateTime?
|
||||||
|
|
||||||
user User @relation(fields: [userId], references: [id])
|
user User @relation(fields: [userId], references: [id])
|
||||||
application CitizenshipApplication @relation(fields: [applicationId], references: [id])
|
application CitizenshipApplication @relation(fields: [applicationId], references: [id])
|
||||||
identityDocuments IdentityDocument[]
|
identityDocuments IdentityDocument[]
|
||||||
positions CitizenshipPosition[]
|
|
||||||
approvals ActApproval[]
|
|
||||||
|
|
||||||
@@index([userId])
|
@@index([userId])
|
||||||
}
|
}
|
||||||
|
|
||||||
model IdentityDocument {
|
model IdentityDocument {
|
||||||
id String @id @default(uuid())
|
id String @id @default(uuid())
|
||||||
citizenshipId String
|
citizenshipId String
|
||||||
citizenship Citizenship @relation(fields: [citizenshipId], references: [id], onDelete: Cascade)
|
citizenship Citizenship @relation(fields: [citizenshipId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
documentNumber String @unique
|
documentNumber String @unique
|
||||||
address String
|
address String
|
||||||
|
|
||||||
regionId String?
|
regionId String?
|
||||||
region Region? @relation(fields: [regionId], references: [id])
|
region Region? @relation(fields: [regionId], references: [id])
|
||||||
city String?
|
city String?
|
||||||
street String?
|
street String?
|
||||||
customAddress String?
|
customAddress String?
|
||||||
|
|
||||||
issuedAt DateTime @default(now())
|
issuedAt DateTime @default(now())
|
||||||
expiresAt DateTime
|
expiresAt DateTime
|
||||||
|
|
||||||
@@index([citizenshipId, issuedAt])
|
@@index([citizenshipId, issuedAt])
|
||||||
}
|
}
|
||||||
|
|
||||||
model Region {
|
model Region {
|
||||||
id String @id
|
id String @id
|
||||||
name String
|
name String
|
||||||
capital String
|
capital String
|
||||||
documents IdentityDocument[]
|
documents IdentityDocument[]
|
||||||
applications CitizenshipApplication[]
|
applications CitizenshipApplication[]
|
||||||
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])
|
|
||||||
}
|
}
|
||||||
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 81 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 86 KiB |
Reference in New Issue
Block a user