feat: citizenship built

This commit is contained in:
Ivan Rezchikov
2026-07-03 15:03:35 +03:00
parent c60ab9e8f9
commit 2eb0de5357
46 changed files with 1150 additions and 257 deletions
+1 -1
View File
@@ -73,7 +73,7 @@ export default function EditPageClient({ page, pageType, initialBlocks = [] }: P
return (
<div className="flex flex-col p-16 gap-12">
<div className="flex flex-row items-center justify-between">
<h1 className="">Edit page</h1>
<h1>Edit page</h1>
<div className="flex flex-row gap-3">
<Button
disabled={isPending}
+3 -3
View File
@@ -10,8 +10,8 @@ import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Separator } from "@/components/ui/separator";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { ArchiveButton } from "./archiveButton";
import { PinToggleButton } from "./pinToggleButton";
import { ArchiveButton } from "./archive-button";
import { PinToggleButton } from "./pin-toggle-button";
import { getNavLinkByPageId } from "@/lib/navlinks/repository";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import Image from "next/image";
@@ -171,7 +171,7 @@ export default async function Page({ params }: { params: Promise<{ type: string;
<div className="flex flex-col p-16 gap-12">
<div className={cn("flex flex-col gap-4 justify-center", isNews && "items-center")}>
<div className="flex flex-row items-center gap-6">
<h1 className="">{page?.title}</h1>
<h1>{page?.title}</h1>
{user?.isAdmin && (
<div className="flex flex-row gap-2 items-center">
<Link href={`/${page.type.toLowerCase()}/${page.slug}/edit`}>
@@ -1,4 +1,4 @@
"use client"
"use client";
import { cn } from "@/lib/utils";
import { BookOpenTextIcon, SignatureIcon, UserIcon } from "lucide-react";
@@ -35,7 +35,7 @@ export function ApplicationsDialog({ applications }: { applications: Citizenship
<PlusIcon size={16} /><p>Created on {formatDate(application.createdAt)}</p>
</div>
<div className={cn("flex flex-row gap-2 items-center", application.status !== "PENDING" && "text-muted-foreground")}>
<ClockFadingIcon size={16} /><p>{application.status === "PENDING" ? "On review" : `Reviewed on ${formatDate(application.reviewedAt)}`}</p>
<ClockFadingIcon size={16} /><p>{application.status === "PENDING" ? "On review" : application.reviewedAt ? `Reviewed on ${formatDate(application.reviewedAt)}` : "Reviewed"}</p>
</div>
{application.status === "REJECTED" && (
<div className="flex flex-col gap-0.5 mt-2">
+76 -50
View File
@@ -37,6 +37,7 @@ type Props = {
secondName: string;
sex: string;
birthDate: Date | null;
regions: { id: string; name: string }[];
};
const initialState: ApplicationState = { success: false, errors: [] };
@@ -46,18 +47,19 @@ function formatDate(d: Date | null): string {
return d.toISOString().split("T")[0];
}
type AppType = "PREVIOUS_CITIZENSHIP" | "BORN_IN_TERRITORY" | "NATURALIZATION";
type AppType = "PREVIOUS_CITIZENSHIP" | "NATURALIZATION";
export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDate }: Props) {
export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDate, regions }: Props) {
const [appType, setAppType] = useState<AppType | "">("");
const [state, formAction, isPending] = useActionState(submitCitizenshipApplication, initialState);
const [isEuResident, setIsEuResident] = useState<boolean | null>(null);
return (
<form action={formAction}>
<FieldGroup>
<FieldSet>
<FieldLegend>Personal information</FieldLegend>
<Alert className="border-amber-200 bg-amber-50 text-amber-900">
<Alert variant="warning">
<InfoIcon />
<AlertTitle>Important notice</AlertTitle>
<AlertDescription>
@@ -131,18 +133,6 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
</FieldContent>
</Field>
</FieldLabel>
<FieldLabel htmlFor="born-territory">
<Field orientation="horizontal">
<RadioGroupItem value="BORN_IN_TERRITORY" id="born-territory" />
<FieldContent>
<span className="text-sm font-medium">Born in territory</span>
<FieldDescription>
I was born in the European Federation, the former Duspean
Republic, or the Country of Reality, and do not hold citizenship.
</FieldDescription>
</FieldContent>
</Field>
</FieldLabel>
<FieldLabel htmlFor="naturalization">
<Field orientation="horizontal">
<RadioGroupItem value="NATURALIZATION" id="naturalization" />
@@ -181,26 +171,7 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
required
/>
<FieldDescription>
The region or authority that issued your previous citizenship. The list of regions is <Link href="/page/regions">here</Link>.
</FieldDescription>
</Field>
</FieldGroup>
</FieldSet>
)}
{appType === "BORN_IN_TERRITORY" && (
<FieldSet>
<FieldLegend>Birth details</FieldLegend>
<FieldGroup>
<Field>
<FieldLabel htmlFor="birthRegion">Region of birth</FieldLabel>
<Input
id="birthRegion"
name="birthRegion"
placeholder="City, Region, Country"
required
/>
<FieldDescription>
The municipality, region, and country where you were born. The list of regions is <Link href="/page/regions">here</Link>.
The region or authority that issued your previous citizenship.
</FieldDescription>
</Field>
</FieldGroup>
@@ -225,24 +196,79 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
</FieldGroup>
</FieldSet>
)}
<FieldSet>
<FieldLegend>Place of residence</FieldLegend>
<FieldDescription>
This will appear on your identity document.
</FieldDescription>
<FieldGroup>
<Field>
<FieldLabel>Is your residence in the European Federation?</FieldLabel>
<RadioGroup
name="isEuResident"
onValueChange={(v) => setIsEuResident(v === "yes")}
>
<Field orientation="horizontal">
<RadioGroupItem value="yes" id="eu-yes" />
<FieldLabel htmlFor="eu-yes">Yes</FieldLabel>
</Field>
<Field orientation="horizontal">
<RadioGroupItem value="no" id="eu-no" />
<FieldLabel htmlFor="eu-no">No</FieldLabel>
</Field>
</RadioGroup>
</Field>
{isEuResident === true && (
<>
<Field>
<FieldLabel htmlFor="regionId">Region</FieldLabel>
<Select name="regionId" required>
<SelectTrigger id="regionId">
<SelectValue placeholder="Select region" />
</SelectTrigger>
<SelectContent>
{regions.map((r) => (
<SelectItem key={r.id} value={r.id}>
{r.name}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel htmlFor="city">City</FieldLabel>
<Input id="city" name="city" placeholder="City or town" required />
</Field>
<Field>
<FieldLabel htmlFor="street">Street and house number</FieldLabel>
<Input id="street" name="street" placeholder="12 Via di Roma" required />
</Field>
</>
)}
{isEuResident === false && (
<Field>
<FieldLabel htmlFor="customAddress">Full address</FieldLabel>
<Input
id="customAddress"
name="customAddress"
placeholder="Street, City, Country"
required
/>
<FieldDescription>
Enter your full address as it should appear on the document.
</FieldDescription>
</Field>
)}
</FieldGroup>
</FieldSet>
<FieldSet>
<FieldLegend>Additional information</FieldLegend>
<FieldDescription>
Provide details required for your identity document.
</FieldDescription>
<FieldGroup>
<Field>
<FieldLabel htmlFor="address">Current address</FieldLabel>
<Input
id="address"
name="address"
placeholder="Street, City, Region"
required
/>
<FieldDescription>
Your current place of residence.
</FieldDescription>
</Field>
<div className="grid grid-cols-2 gap-4">
<Field>
<FieldLabel htmlFor="height">Height (in cm)</FieldLabel>
@@ -274,16 +300,16 @@ export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDa
</FieldGroup>
</FieldSet>
{state.errors.length > 0 && (
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-900">
<Alert className="bg-red-50 p-3 text-red-900">
<ul className="list-disc pl-4">
{state.errors.map((err, i) => (
<li key={i}>{err}</li>
))}
</ul>
</div>
</Alert>
)}
<Field orientation="horizontal">
<Button type="submit">{isPending && <Spinner />}Submit application</Button>
<Button type="submit" disabled={isPending}>{isPending && <Spinner />}Submit application</Button>
</Field>
</FieldGroup>
</form>
+5 -1
View File
@@ -2,9 +2,10 @@ import Footer from "@/components/footer";
import Header from "@/components/header";
import { getCurrentUser } from "@/lib/user";
import { redirect } from "next/navigation";
import { AccountMenu } from "../../menu";
import { AccountMenu } from "../../account-menu";
import { CitizenshipApplicationForm } from "./form";
import { getUserApplications } from "@/lib/citizenship/repository";
import { prisma } from "@/lib/prisma";
export default async function CitizenshipApplication() {
const user = await getCurrentUser();
@@ -14,6 +15,8 @@ export default async function CitizenshipApplication() {
const canApply = applications.length === 0 || applications.every((a) => a.status === "REJECTED");
if (!canApply) redirect("/account/citizenship");
const regions = await prisma.region.findMany({ orderBy: { name: "asc" } });
return (
<>
<Header />
@@ -28,6 +31,7 @@ export default async function CitizenshipApplication() {
secondName={user.secondName}
sex={user.sex}
birthDate={user.birthDate}
regions={regions}
/>
</div>
</div>
+121 -81
View File
@@ -2,7 +2,7 @@ import Footer from "@/components/footer";
import Header from "@/components/header";
import { getCurrentUser } from "@/lib/user";
import { redirect } from "next/navigation";
import { AccountMenu } from "../menu";
import { AccountMenu } from "../account-menu";
import { InfoIcon } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
@@ -13,14 +13,31 @@ import {
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { ApplicationsDialog } from "./applicationsDialog";
import { getUserApplications } from "@/lib/citizenship/repository";
import { ApplicationsDialog } from "./applications-dialog";
import { getPendingApplicationsCount, getUserApplications } from "@/lib/citizenship/repository";
import { prisma } from "@/lib/prisma";
import { CitizenshipApplication } from "@/lib/citizenship/types";
import { getIdentityCardData, IdentityCardData } from "@/lib/id/repository";
import IdCard from "@/components/id-card";
export default async function Citizenship() {
const user = await getCurrentUser();
if (!user) redirect("/");
const user = await getCurrentUser()
if (!user) redirect("/")
const applications = await getUserApplications(user.id);
const citizenship = await prisma.citizenship.findUnique({ where: { userId: user.id } })
let applications: CitizenshipApplication[] = []
let pendingCount = 0
let identityDocument: IdentityCardData | null = null
if (citizenship) {
identityDocument = await getIdentityCardData(user.id)
} else {
applications = await getUserApplications(user.id)
if (user.isAdmin) {
pendingCount = await getPendingApplicationsCount()
}
}
return (
<>
@@ -30,85 +47,108 @@ export default async function Citizenship() {
<div className="flex flex-col gap-8 max-w-lg">
<div className="flex flex-col gap-6 w-min">
<h2>Citizenship</h2>
<Alert className="border-amber-200 bg-amber-50 text-amber-900">
<InfoIcon />
<AlertTitle>You are not a citizen of the European Federation</AlertTitle>
<AlertDescription>
You currently hold non-citizen status. Certain civic services and
identity documents are available only to
citizens of the European Federation.
</AlertDescription>
</Alert>
<div className="flex flex-col gap-3">
<div className="flex flex-row gap-3 w-max">
<Link href="/page/citizenship"><Button variant="secondary">Learn more about citizenship</Button></Link>
<Link href="/account/citizenship/apply"><Button>Apply for the citizenship</Button></Link>
{citizenship ? (
<div className="flex flex-col gap-8">
<IdCard data={identityDocument} />
</div>
{applications.length > 0 && <ApplicationsDialog applications={applications} />}
</div>
<Accordion type="single" collapsible>
<AccordionItem value="eligibility">
<AccordionTrigger>
<h4>Who is eligible for citizenship?</h4>
</AccordionTrigger>
<AccordionContent>
Citizenship may be granted to persons born in the European
Federation, the former Duspean Republic, or the Country of Reality,
as well as to individuals who held citizenship of the Duspean
Republic or the Country of Reality on 31 March 2026.
<br />
<br />
Foreign nationals who demonstrate a commitment to the development,
prosperity, and values of the European Federation may also be
eligible for naturalisation under federal law.
</AccordionContent>
</AccordionItem>
<AccordionItem value="rights">
<AccordionTrigger>
<h4>What rights does citizenship provide?</h4>
</AccordionTrigger>
<AccordionContent>
Citizens enjoy all rights and protections guaranteed by the
Constitution and laws of the European Federation, including the
right to obtain federal identity documents, participate in federal
elections, and receive protection from federal authorities.
</AccordionContent>
</AccordionItem>
<AccordionItem value="documents">
<AccordionTrigger>
<h4>What documents are required?</h4>
</AccordionTrigger>
<AccordionContent>
Applicants may be asked to provide proof of
residence in the European Federation, evidence of eligibility, and any additional documents
required by the competent authority.
</AccordionContent>
</AccordionItem>
<AccordionItem value="processing">
<AccordionTrigger>
<h4>How long does the application process take?</h4>
</AccordionTrigger>
<AccordionContent>
Processing times vary depending on the complexity of the
application and the volume of requests currently under review.
Applicants can track the status of their application through their
account.
</AccordionContent>
</AccordionItem>
<AccordionItem value="dual">
<AccordionTrigger>
<h4>Is dual citizenship permitted?</h4>
</AccordionTrigger>
<AccordionContent>
The European Federation generally permits dual citizenship unless
otherwise restricted by federal law or international agreements.
</AccordionContent>
</AccordionItem>
</Accordion>
) : (
<div className="flex flex-col gap-6 w-min">
<Alert variant="warning">
<InfoIcon />
<AlertTitle>You are not a citizen of the European Federation</AlertTitle>
<AlertDescription>
You currently hold non-citizen status. Certain civic services and
identity documents are available only to citizens of the European Federation.
</AlertDescription>
</Alert>
<div className="flex flex-col gap-3">
<div className="flex flex-row gap-3 w-max">
<Link href="/page/citizenship">
<Button variant="secondary">Learn more about citizenship</Button>
</Link>
<Link href="/account/citizenship/apply">
<Button>Apply for citizenship</Button>
</Link>
</div>
{applications.length > 0 && (
<ApplicationsDialog applications={applications} />
)}
{user.isAdmin && (
<Link href="/account/citizenship/review">
<Button variant="secondary" className="w-full">
Review citizenship applications
<div className="flex items-center justify-center bg-black/50 text-white w-3.5 h-3.5 text-xs rounded-full">
{pendingCount}
</div>
</Button>
</Link>
)}
</div>
<Accordion type="single" collapsible>
<AccordionItem value="eligibility">
<AccordionTrigger>
<h4>Who is eligible for citizenship?</h4>
</AccordionTrigger>
<AccordionContent>
Citizenship may be granted to persons born in the European
Federation, the former Duspean Republic, or the Country of Reality,
as well as to individuals who held citizenship of the Duspean
Republic or the Country of Reality on 31 March 2026.
<br />
<br />
Foreign nationals who demonstrate a commitment to the development,
prosperity, and values of the European Federation may also be
eligible for naturalisation under federal law.
</AccordionContent>
</AccordionItem>
<AccordionItem value="rights">
<AccordionTrigger>
<h4>What rights does citizenship provide?</h4>
</AccordionTrigger>
<AccordionContent>
Citizens enjoy all rights and protections guaranteed by the
Constitution and laws of the European Federation, including the
right to obtain federal identity documents, participate in federal
elections, and receive protection from federal authorities.
</AccordionContent>
</AccordionItem>
<AccordionItem value="documents">
<AccordionTrigger>
<h4>What documents are required?</h4>
</AccordionTrigger>
<AccordionContent>
Applicants may be asked to provide proof of
residence in the European Federation, evidence of eligibility, and any additional documents
required by the competent authority.
</AccordionContent>
</AccordionItem>
<AccordionItem value="processing">
<AccordionTrigger>
<h4>How long does the application process take?</h4>
</AccordionTrigger>
<AccordionContent>
Processing times vary depending on the complexity of the
application and the volume of requests currently under review.
Applicants can track the status of their application through their
account.
</AccordionContent>
</AccordionItem>
<AccordionItem value="dual">
<AccordionTrigger>
<h4>Is dual citizenship permitted?</h4>
</AccordionTrigger>
<AccordionContent>
The European Federation generally permits dual citizenship unless
otherwise restricted by federal law or international agreements.
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
)}
</div>
</div>
</div>
<Footer />
</>
);
)
}
@@ -0,0 +1,147 @@
"use client"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Separator } from "@/components/ui/separator";
import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
import { approveApplication, rejectApplication } from "@/lib/citizenship/actions";
import { CitizenshipApplicationWithWarning } from "@/lib/citizenship/types";
import { formatDate } from "@/lib/utils";
import { TriangleAlertIcon } from "lucide-react";
import { useState } from "react";
export default function ApplicationCard({ application, onClose }: { application: CitizenshipApplicationWithWarning | undefined, onClose: () => void }) {
const [rejectOpen, setRejectOpen] = useState(false)
const [reason, setReason] = useState("")
const [isloading, setIsLoading] = useState(false)
if (!application?.id) {
return (
<div className="w-sm flex items-center justify-center ring-1 ring-foreground/10 rounded-xl text-muted-foreground px-4">
Click on a row to see the application
</div>
)
}
async function handleApprove() {
setIsLoading(true)
await approveApplication(application.id)
setIsLoading(false)
onClose()
}
async function handleReject() {
if (!reason.trim()) return
setIsLoading(true)
await rejectApplication(application.id, reason)
setIsLoading(false)
setRejectOpen(false)
onClose()
}
return (
<>
<Card size="sm" className="mx-auto w-full">
<CardHeader>
<CardTitle><h3>{application.givenNames} {application.surname}</h3></CardTitle>
<CardDescription>{application.applicationType === "PREVIOUS_CITIZENSHIP" ? "Previous citizenship application" : "Naturalization application"}</CardDescription>
</CardHeader>
<CardContent className="max-w-sm">
<div className="flex flex-col gap-1">
<h4 className="mb-1">Personal information</h4>
{ application.nameMismatch && (
<Alert className="mb-2" variant="warning">
<TriangleAlertIcon />
<AlertTitle>Name mismatch</AlertTitle>
<AlertDescription className="w-fit max-w-full">The name on this application differs from the applicant's Kotosoft ID. Verify before approving.</AlertDescription>
</Alert>
)}
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Given names</p>
<p>{application.givenNames}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Surname</p>
<p>{application.surname}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Sex</p>
<p>{application.sex}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Birthdate</p>
<p>{formatDate(application.birthDate)}</p>
</div>
<div className="flex flex-col gap-0.5">
<p className="text-muted-foreground">Address</p>
<p className="truncate">{application.address}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Height</p>
<p>{application.height} cm</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground">Eye color</p>
<p>{application.eyeColor}</p>
</div>
<Separator className="my-2" />
<h4 className="mb-1">Eligibility proofs</h4>
{
application.applicationType == "PREVIOUS_CITIZENSHIP" && (
<div className="flex flex-col gap-1">
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground truncate">Country of previous citizenship</p>
<p className="truncate">{application.previousCountry == "DUS" ? "Duspean Republic" : "Country of Reality"}</p>
</div>
<div className="flex flex-row gap-4 items-center">
<p className="text-muted-foreground truncate">Region of previous residence</p>
<p className="truncate">{application.previousRegion}</p>
</div>
</div>
)
}
{
application.applicationType == "NATURALIZATION" && (
<div className="flex flex-col gap-0.5">
<p className="text-muted-foreground">Naturalization reason</p>
<p>{application.naturalizationReason}</p>
</div>
)
}
</div>
</CardContent>
<CardFooter className="gap-2">
<Button onClick={handleApprove} disabled={isloading}>
{isloading && <Spinner />}Approve
</Button>
<Button variant="outline" onClick={() => setRejectOpen(true)} disabled={isloading}>
{isloading && <Spinner />}Reject
</Button>
<Button variant="outline" onClick={onClose}>Close</Button>
</CardFooter>
</Card>
<Dialog open={rejectOpen} onOpenChange={setRejectOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle asChild><h3>Reject application</h3></DialogTitle>
<DialogDescription>Provide a reason. The applicant will see this.</DialogDescription>
</DialogHeader>
<Textarea
placeholder="Reason for rejection..."
value={reason}
onChange={(e) => setReason(e.target.value)}
/>
<DialogFooter>
<Button variant="outline" onClick={() => setRejectOpen(false)}>Cancel</Button>
<Button variant="destructive" onClick={handleReject} disabled={!reason.trim() || isloading}>
{isloading && <Spinner />}Confirm rejection
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
+26
View File
@@ -0,0 +1,26 @@
"use client"
import { CitizenshipApplication } from "@/lib/citizenship/types";
import { DataTable } from "./data-table";
import { columns } from "./columns";
import ApplicationCard from "./application-card";
import { useState } from "react";
export default function ReviewPageClient({ applications }: { applications: CitizenshipApplication[] }) {
const [selectedApplicationId, setSelectedApplicationId] = useState("");
return (
<>
<div className="flex flex-row gap-16">
<div className="flex flex-col gap-8">
<div className="flex flex-col gap-6">
<h2>Review citizenship applications</h2>
</div>
<DataTable columns={columns} data={applications} onRowClick={(app) => setSelectedApplicationId(app.id)} />
</div>
<ApplicationCard application={applications.find((a) => a.id === selectedApplicationId)} onClose={() => setSelectedApplicationId("")} />
</div>
</>
)
}
@@ -0,0 +1,37 @@
"use client"
import { ColumnDef } from "@tanstack/react-table";
import { CitizenshipApplication } from "@/lib/citizenship/types";
import { Badge } from "@/components/ui/badge";
import { formatDate } from "@/lib/utils";
export const columns: ColumnDef<CitizenshipApplication>[] = [
{
accessorKey: "surname",
header: "Applicant",
cell: ({ row }) => {
const application = row.original
return <span>{application.givenNames} {application.surname}</span>
},
},
{
accessorKey: "birthDate",
header: "Birth date",
cell: ({ row }) => formatDate(row.getValue("birthDate")),
},
{
accessorKey: "applicationType",
header: "Type",
cell: ({ row }) => {
return <span>{row.original.applicationType === "PREVIOUS_CITIZENSHIP" ? "Previous citizenship" : "Naturalization"}</span>
},
},
{
accessorKey: "status",
header: "Status",
cell: ({ row }) => {
const status = row.getValue("status") as string
return <Badge variant={status === "PENDING" ? "outline" : "default"}>{status}</Badge>
},
},
]
@@ -0,0 +1,51 @@
"use client"
import { ColumnDef, flexRender, getCoreRowModel, useReactTable } from "@tanstack/react-table";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
onRowClick?: (row: TData) => void;
}
export function DataTable<TData, TValue>({ columns, data, onRowClick }: DataTableProps<TData, TValue>) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div className="overflow-hidden rounded-md w-full">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id}>
{header.isPlaceholder ? null : flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
))}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowCount() === 0 && <h5 className="mt-2 text-muted-foreground">There are no pending applications</h5>}
{table.getRowModel().rows.map((row) => (
<TableRow key={row.id} className="cursor-pointer" onClick={() => onRowClick?.(row.original)}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
)
}
+30
View File
@@ -0,0 +1,30 @@
import Header from "@/components/header";
import Footer from "@/components/footer";
import ReviewPageClient from "./client";
import { getCurrentUser } from "@/lib/user";
import { redirect } from "next/navigation";
import { AccountMenu } from "../../account-menu";
import { getPendingApplications } from "@/lib/citizenship/repository";
export default async function ReviewPage() {
const user = await getCurrentUser();
if (!user?.isAdmin) redirect("/account/citizenship");
const applications = await getPendingApplications()
const applicationsWithWarning = applications.map((app) => ({
...app,
nameMismatch: app.givenNames !== app.user.firstName || app.surname !== app.user.secondName,
}))
return (
<>
<Header />
<div className="flex flex-row py-16 gap-8">
<AccountMenu />
<ReviewPageClient applications={applicationsWithWarning} />
</div>
<Footer />
</>
);
}
@@ -1,4 +1,4 @@
"use client"
"use client";
import { useTransition } from "react";
import {
@@ -1,4 +1,4 @@
"use client"
"use client";
import { useTransition } from "react";
import { Button } from "@/components/ui/button";
+4 -4
View File
@@ -5,10 +5,10 @@ import { getCurrentUser } from "@/lib/user";
import { formatDate } from "@/lib/utils";
import { BookOpenTextIcon, SignatureIcon, UserIcon } from "lucide-react";
import { redirect } from "next/navigation";
import { DeleteDialog } from "./deleteDialog";
import { LogoutButton } from "./logoutButton";
import { UpdateButton } from "./updateButton";
import { AccountMenu } from "./menu";
import { DeleteDialog } from "./delete-dialog";
import { LogoutButton } from "./logout-button";
import { UpdateButton } from "./update-button";
import { AccountMenu } from "./account-menu";
function ProfileField({ label, value }: { label: string; value: string }) {
return (
@@ -1,4 +1,4 @@
"use client"
"use client";
import { useTransition } from "react";
import { Button } from "@/components/ui/button";
+1 -1
View File
@@ -65,7 +65,7 @@ export default function CreatePageClient() {
return (
<div className="flex flex-col p-16 gap-12">
<div className="flex flex-row items-center justify-between">
<h1 className="">Create page</h1>
<h1>Create page</h1>
<div className="flex flex-row gap-3">
<Button
variant="outline"
+3 -3
View File
@@ -1,7 +1,7 @@
import DraftsDialog from "@/components/drafts";
import DraftsDialog from "@/components/drafts-dialog";
import Footer from "@/components/footer";
import Header from "@/components/header";
import { NewsCard } from "@/components/newsCard";
import { NewsCard } from "@/components/news-card";
import { Button } from "@/components/ui/button";
import { getPages } from "@/lib/pages/repository";
import { getCurrentUser } from "@/lib/user";
@@ -21,7 +21,7 @@ export default async function News() {
<Header />
<div className="flex flex-col p-16 gap-16">
<div className="flex flex-row items-center justify-between">
<h1 className="">News</h1>
<h1>News</h1>
<div className="flex flex-row items-center gap-4">
{user?.isAdmin && (
<div className="flex flex-row items-center gap-4">
+2 -2
View File
@@ -1,6 +1,6 @@
import Footer from "@/components/footer";
import Header from "@/components/header";
import { NewsCard } from "@/components/newsCard";
import { NewsCard } from "@/components/news-card";
import { getPages } from "@/lib/pages/repository";
import { ArrowRightIcon } from "lucide-react";
import Link from "next/link";
@@ -39,7 +39,7 @@ export default async function Home() {
</div>
</div>
<div className="flex flex-col gap-8 mt-8">
<h1 className="">Recent news</h1>
<h1>Recent news</h1>
<div className="flex flex-col gap-6">
{
news.length > 0 ? news.map((n) => (
+5
View File
@@ -7,6 +7,7 @@
"dependencies": {
"@prisma/adapter-pg": "^7.8.0",
"@prisma/client": "^7.8.0",
"@tanstack/react-table": "^8.21.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"jose": "^6.2.3",
@@ -442,6 +443,10 @@
"@tailwindcss/postcss": ["@tailwindcss/[email protected]", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.1", "@tailwindcss/oxide": "4.3.1", "postcss": "8.5.15", "tailwindcss": "4.3.1" } }, "sha512-dNJuNbdEJT/SWRuXTYP1WSamelsz3ztkUsdtWQPjrexysrTpaEPM40P/71knXiXLYEojqPOEGitVLLpPMS5T6A=="],
"@tanstack/react-table": ["@tanstack/[email protected]", "", { "dependencies": { "@tanstack/table-core": "8.21.3" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww=="],
"@tanstack/table-core": ["@tanstack/[email protected]", "", {}, "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg=="],
"@ts-morph/common": ["@ts-morph/[email protected]", "", { "dependencies": { "fast-glob": "^3.3.3", "minimatch": "^10.0.1", "path-browserify": "^1.0.1" } }, "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="],
"@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg=="],
@@ -1,6 +1,6 @@
"use client"
"use client";
import { Button } from "@/components/ui/button"
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
@@ -8,7 +8,7 @@ import {
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
} from "@/components/ui/dialog";
import { deletePageAction } from "@/lib/pages/actions";
import { PencilIcon, XIcon } from "lucide-react";
import Link from "next/link";
@@ -24,9 +24,9 @@ export default function DraftsDialog({ drafts }: { drafts: Draft[]}) {
async function deletePage(id: string, type: PageType) {
setIsDeletingId(id);
try {
await deletePageAction(id, type)
await deletePageAction(id, type);
} finally {
setIsDeletingId("")
setIsDeletingId("");
}
}
+161
View File
@@ -0,0 +1,161 @@
import { IdentityCardData } from "@/lib/id/repository";
import { formatDate } from "@/lib/utils";
import Image from "next/image";
import { Button } from "./ui/button";
import { Menu } from "lucide-react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
type DialogField = {
key: keyof IdentityCardData;
label: string;
};
const DIALOG_FIELDS: DialogField[] = [
{ key: "sex", label: "Sex" },
{ key: "birthDate", label: "Date of birth" },
{ key: "authority", label: "Authority" },
{ key: "nationality", label: "Nationality" },
{ key: "issueDate", label: "Date of issue" },
{ key: "expiryDate", label: "Date of expiry" },
{ key: "issuingCountry", label: "Issuing country" },
{ key: "origin", label: "Place of origin" },
{ key: "height", label: "Height" },
{ key: "eyeColor", label: "Eye color" },
];
const ADDRESS_FIELD: DialogField = { key: "address", label: "Address" };
function formatFieldValue(key: keyof IdentityCardData, value: unknown) {
if (value instanceof Date) return formatDate(value);
if (value == null) return "—";
if (key === "height") return `${value} cm`;
return String(value);
}
function CardPattern() {
return (
<svg className="absolute inset-0 w-full h-full" aria-hidden="true">
<defs>
<pattern id="id-card-waves" width="120" height="16" patternUnits="userSpaceOnUse">
<path d="M0 8 Q15 2 30 8 T60 8 T90 8 T120 8" fill="none" stroke="#bfdbfe" strokeWidth="1" />
</pattern>
<pattern id="id-card-dots" width="24" height="24" patternUnits="userSpaceOnUse">
<circle cx="4" cy="4" r="1.5" fill="white" />
<circle cx="16" cy="14" r="1.5" fill="white" />
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#id-card-waves)" />
<rect width="100%" height="100%" fill="url(#id-card-dots)" />
</svg>
);
}
export default function IdCard({ data }: { data: IdentityCardData }) {
return (
<div className="relative w-96 bg-blue-50 rounded-lg p-4 overflow-hidden">
<CardPattern />
<div className="relative z-10">
<div className="flex flex-row items-center justify-between">
<div className="flex flex-row gap-3 items-center">
<Image src="/emblem.png" width={24} height={24} alt="Emblem" />
<h2>ID Card</h2>
</div>
<h3>{data.documentNumber}</h3>
<Dialog>
<DialogTrigger asChild>
<Button size="icon-sm">
<Menu />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<div className="flex flex-row gap-3">
<div className="relative w-12 h-14 shrink-0 rounded overflow-hidden">
<Image src="/profile.png" fill alt="Profile" className="object-cover" />
</div>
<div className="flex flex-col gap-0 justify-center">
<DialogTitle asChild>
<h4 className="uppercase">{data.surname} {data.givenNames}</h4>
</DialogTitle>
<h4 className="text-muted-foreground">{data.documentNumber}</h4>
</div>
</div>
</DialogHeader>
<div className="grid grid-cols-2 gap-x-6 gap-y-2">
{DIALOG_FIELDS.map(({ key, label }) => (
<div className="flex flex-col" key={key}>
<h5 className="text-blue-500">{label}</h5>
<h4 className="leading-6">{formatFieldValue(key, data[key])}</h4>
</div>
))}
<div className="flex flex-col col-span-2">
<h5 className="text-blue-500">{ADDRESS_FIELD.label}</h5>
<h4 className="leading-6">{formatFieldValue(ADDRESS_FIELD.key, data[ADDRESS_FIELD.key])}</h4>
</div>
</div>
</DialogContent>
</Dialog>
</div>
<div className="flex flex-row gap-8 mt-4">
<div className="flex flex-col gap-4 w-24 shrink-0">
<div className="relative w-24 h-28 shrink-0">
<Image src="/profile.png" fill alt="Profile" className="object-cover" />
</div>
<div className="relative w-24 h-12 shrink-0">
<Image src="/signature.png" fill alt="Signature" className="object-contain" />
</div>
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-wrap gap-x-6 gap-y-2">
<div className="flex flex-col min-w-fit">
<h5 className="text-blue-500">Surname</h5>
<h4 className="uppercase">{data.surname}</h4>
</div>
<div className="flex flex-col min-w-fit">
<h5 className="text-blue-500">Given name(s)</h5>
<h4 className="uppercase">{data.givenNames}</h4>
</div>
</div>
<div className="flex flex-wrap gap-x-6 gap-y-2">
<div className="flex flex-col min-w-fit">
<h5 className="text-blue-500">Sex</h5>
<h4>{data.sex}</h4>
</div>
<div className="flex flex-col min-w-fit">
<h5 className="text-blue-500">Date of birth</h5>
<h4>{formatDate(data.birthDate)}</h4>
</div>
</div>
<div className="flex flex-wrap gap-x-6 gap-y-2">
<div className="flex flex-col min-w-fit">
<h5 className="text-blue-500">Authority</h5>
<h4 className="leading-6">{data.authority}</h4>
</div>
<div className="flex flex-col min-w-fit">
<h5 className="text-blue-500">Nationality</h5>
<h4>{data.nationality}</h4>
</div>
</div>
<div className="flex flex-wrap gap-x-6 gap-y-2">
<div className="flex flex-col min-w-fit">
<h5 className="text-blue-500">Issue date</h5>
<h4>{formatDate(data.issueDate)}</h4>
</div>
<div className="flex flex-col min-w-fit">
<h5 className="text-blue-500">Date of expiry</h5>
<h4>{formatDate(data.expiryDate)}</h4>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
@@ -1,10 +1,10 @@
import { Page, PageMeta } from "@/lib/pages/types";
import { PageMeta, PagePublic } from "@/lib/pages/types";
import { CalendarIcon, Globe2Icon } from "lucide-react";
import Link from "next/link";
import { Badge } from "./ui/badge";
import { formatDate } from "@/lib/utils";
export function NewsCard({ news }: { news: Page }) {
export function NewsCard({ news }: { news: PagePublic }) {
return (
<div className="flex flex-col gap-2">
<Link href={`/news/${news.slug}`} className="w-max">
@@ -20,5 +20,5 @@ export function NewsCard({ news }: { news: Page }) {
</div>
</div>
</div>
)
);
}
+2
View File
@@ -11,6 +11,8 @@ const alertVariants = cva(
default: "bg-card text-card-foreground",
destructive:
"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
warning:
"border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-5",
},
},
defaultVariants: {
+103
View File
@@ -0,0 +1,103 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({
className,
size = "default",
...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn(
"cn-font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className
)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-(--card-spacing)", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
className
)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
+1 -1
View File
@@ -1,4 +1,4 @@
import crypto from "crypto"
import crypto from "crypto";
export function generatePkce() {
const verifier = crypto.randomBytes(32).toString("base64url");
+2 -1
View File
@@ -33,7 +33,8 @@ export async function getSessionUserId(): Promise<string | null> {
try {
const { payload } = await jwtVerify(token, getSecret());
return payload.sub ?? null;
} catch {
} catch (e) {
console.error("Session verification failed:", e);
return null;
}
}
+82 -4
View File
@@ -5,12 +5,19 @@ import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import { citizenshipApplicationSchema } from "./validation";
import { createApplication } from "./repository";
import { prisma } from "../prisma";
export type ApplicationState = {
success: boolean;
errors: string[];
};
function generateDocumentNumber(): string {
const letter = () => String.fromCharCode(65 + Math.floor(Math.random() * 26));
const digits = Math.floor(Math.random() * 1_000_000).toString().padStart(6, "0");
return `${letter()}${digits}${letter()}`;
}
export async function submitCitizenshipApplication(
_prevState: ApplicationState,
formData: FormData
@@ -19,19 +26,22 @@ export async function submitCitizenshipApplication(
if (!user) redirect("/");
const applicationType = formData.get("applicationType") as string;
const isEuResident = formData.get("isEuResident") as string;
const raw: Record<string, string> = {
applicationType,
address: (formData.get("address") as string) ?? "",
height: (formData.get("height") as string) ?? "",
eyeColor: (formData.get("eyeColor") as string) ?? "",
isEuResident,
regionId: (formData.get("regionId") as string) ?? "",
city: (formData.get("city") as string) ?? "",
street: (formData.get("street") as string) ?? "",
customAddress: (formData.get("customAddress") as string) ?? "",
};
if (applicationType === "PREVIOUS_CITIZENSHIP") {
raw.previousCountry = (formData.get("previousCountry") as string) ?? "";
raw.previousRegion = (formData.get("previousRegion") as string) ?? "";
} else if (applicationType === "BORN_IN_TERRITORY") {
raw.birthRegion = (formData.get("birthRegion") as string) ?? "";
} else if (applicationType === "NATURALIZATION") {
raw.naturalizationReason = (formData.get("naturalizationReason") as string) ?? "";
}
@@ -43,14 +53,82 @@ export async function submitCitizenshipApplication(
return { success: false, errors: messages };
}
const { isEuResident: _, regionId, city, street, customAddress, ...applicationData } = parsed.data;
const address = _ === "yes"
? `${street}, ${city}, ${regionId}, EU`
: customAddress!;
await createApplication(user.id, {
surname: user.secondName,
givenNames: user.firstName,
sex: user.sex,
birthDate: user.birthDate ?? new Date(),
...parsed.data,
...applicationData,
address,
regionId: _ === "yes" ? regionId : null,
city: _ === "yes" ? city : null,
street: _ === "yes" ? street : null,
customAddress: _ === "yes" ? null : customAddress,
});
revalidatePath("/account/citizenship");
return { success: true, errors: [] };
}
export async function approveApplication(id: string) {
const user = await getCurrentUser();
if (!user) redirect("/");
const application = await prisma.citizenshipApplication.update({
where: { id },
data: {
status: "APPROVED",
reviewedAt: new Date(),
reviewedBy: user.id,
},
});
const citizenship = await prisma.citizenship.create({
data: {
userId: application.userId,
applicationId: application.id,
},
});
const now = new Date();
const expiresAt = new Date(now);
expiresAt.setFullYear(expiresAt.getFullYear() + 10);
await prisma.identityDocument.create({
data: {
citizenshipId: citizenship.id,
documentNumber: generateDocumentNumber(),
regionId: application.regionId,
city: application.city,
street: application.street,
customAddress: application.customAddress,
issuedAt: now,
expiresAt,
},
});
revalidatePath("/account/citizenship/review");
}
export async function rejectApplication(id: string, reason: string) {
const user = await getCurrentUser();
if (!user) redirect("/");
await prisma.citizenshipApplication.update({
where: { id },
data: {
status: "REJECTED",
rejectionReason: reason,
reviewedAt: new Date(),
reviewedBy: user.id,
},
});
revalidatePath("/account/citizenship/review");
}
+17 -1
View File
@@ -12,6 +12,10 @@ type CreateData = {
birthRegion?: string | null;
naturalizationReason?: string | null;
address: string;
regionId?: string | null;
city?: string | null;
street?: string | null;
customAddress?: string | null;
height: string;
eyeColor: string;
};
@@ -28,6 +32,18 @@ export async function createApplication(userId: string, data: CreateData) {
export async function getUserApplications(userId: string) {
return prisma.citizenshipApplication.findMany({
where: { userId },
orderBy: { createdAt: "desc" },
orderBy: { createdAt: "asc" },
});
}
export async function getPendingApplications() {
return prisma.citizenshipApplication.findMany({
where: { status: "PENDING" },
orderBy: { createdAt: "desc" },
include: { user: true },
})
}
export async function getPendingApplicationsCount(): Promise<number> {
return prisma.citizenshipApplication.count({ where: { status: "PENDING" } })
}
+6 -2
View File
@@ -1,7 +1,7 @@
export const CITIZENSHIP_APPLICATION_STATUSES = ["PENDING", "APPROVED", "REJECTED"] as const;
export type CitizenshipApplicationStatus = typeof CITIZENSHIP_APPLICATION_STATUSES[number];
export const APPLICATION_TYPES = ["PREVIOUS_CITIZENSHIP", "BORN_IN_TERRITORY", "NATURALIZATION"] as const;
export const APPLICATION_TYPES = ["PREVIOUS_CITIZENSHIP", "NATURALIZATION"] as const;
export type ApplicationType = typeof APPLICATION_TYPES[number];
export const EYE_COLORS = [
@@ -24,7 +24,6 @@ export type CitizenshipApplication = {
applicationType: ApplicationType;
previousCountry: string | null;
previousRegion: string | null;
birthRegion: string | null;
naturalizationReason: string | null;
address: string;
height: string;
@@ -32,6 +31,11 @@ export type CitizenshipApplication = {
status: CitizenshipApplicationStatus;
rejectionReason: string | null;
reviewedAt: Date | null;
reviewedBy: string | null;
createdAt: Date;
updatedAt: Date;
};
export type CitizenshipApplicationWithWarning = CitizenshipApplication & {
nameMismatch: boolean
}
+20 -25
View File
@@ -1,44 +1,39 @@
import { z } from "zod";
const baseFields = {
address: z.string().min(1, "Address is required"),
height: z.string().min(1, "Height is required"),
height: z.string().regex(/^\d+$/, "Height must be a number").min(1, "Height is required"),
eyeColor: z.string().min(1, "Eye colour is required"),
};
isEuResident: z.enum(["yes", "no"]),
regionId: z.string().optional(),
city: z.string().optional(),
street: z.string().optional(),
customAddress: z.string().optional(),
}
const previousCitizenshipSchema = z.object({
applicationType: z.literal("PREVIOUS_CITIZENSHIP"),
previousCountry: z.string().min(1, "Country of previous citizenship is required"),
previousRegion: z.string().min(1, "Region of previous citizenship is required"),
...baseFields,
});
const bornInTerritorySchema = z.object({
applicationType: z.literal("BORN_IN_TERRITORY"),
birthRegion: z.string().min(1, "Region of birth is required"),
...baseFields,
});
}).superRefine(validateAddress)
const naturalizationSchema = z.object({
applicationType: z.literal("NATURALIZATION"),
naturalizationReason: z.string().min(1, "Reason for naturalisation is required"),
...baseFields,
});
}).superRefine(validateAddress)
function validateAddress(data: { isEuResident: string, regionId?: string, city?: string, street?: string, customAddress?: string }, ctx: z.RefinementCtx) {
if (data.isEuResident === "yes") {
if (!data.regionId) ctx.addIssue({ code: "custom", path: ["regionId"], message: "Region is required" })
if (!data.city) ctx.addIssue({ code: "custom", path: ["city"], message: "City is required" })
if (!data.street) ctx.addIssue({ code: "custom", path: ["street"], message: "Street is required" })
} else {
if (!data.customAddress) ctx.addIssue({ code: "custom", path: ["customAddress"], message: "Address is required" })
}
}
export const citizenshipApplicationSchema = z.discriminatedUnion("applicationType", [
previousCitizenshipSchema,
bornInTerritorySchema,
naturalizationSchema,
]);
export type CitizenshipApplicationFormData = z.infer<typeof citizenshipApplicationSchema>;
export function validateCitizenshipApplication(data: unknown) {
const result = citizenshipApplicationSchema.safeParse(data);
if (!result.success) {
const fieldErrors = result.error.flatten().fieldErrors ?? {};
const messages = Object.values(fieldErrors).flat().filter(Boolean);
return { success: false as const, errors: messages };
}
return { success: true as const, data: result.data };
}
])
+76
View File
@@ -0,0 +1,76 @@
import { prisma } from "@/lib/prisma";
export type IdentityCardData = {
documentNumber: string;
issuingCountry: "EUR";
nationality: "EUR";
surname: string;
givenNames: string;
sex: "M" | "F";
birthDate: Date;
address: string;
height: string;
eyeColor: string;
issueDate: Date;
expiryDate: Date;
authority: string;
origin: string | null;
};
export async function getIdentityCardData(userId: string): Promise<IdentityCardData | null> {
const doc = await prisma.identityDocument.findFirst({
where: {
citizenship: { userId },
},
select: {
documentNumber: true,
issuedAt: true,
expiresAt: true,
regionId: true,
city: true,
street: true,
customAddress: true,
region: {
select: { name: true },
},
citizenship: {
select: {
application: {
select: {
surname: true,
givenNames: true,
sex: true,
birthDate: true,
address: true,
height: true,
eyeColor: true,
},
},
},
},
},
});
if (!doc) return null;
const app = doc.citizenship.application;
return {
documentNumber: doc.documentNumber,
issuingCountry: "EUR",
nationality: "EUR",
surname: app.surname,
givenNames: app.givenNames,
sex: app.sex === "MALE" ? "M" : "F",
birthDate: app.birthDate,
address: app.address,
height: app.height,
eyeColor: app.eyeColor,
issueDate: doc.issuedAt,
expiryDate: doc.expiresAt,
authority: doc.region?.name ?? "European Federation",
origin: doc.regionId && doc.city
? `${doc.city}, ${doc.regionId}, EU`
: doc.customAddress ?? null,
};
}
-1
View File
@@ -8,7 +8,6 @@ export async function pinPageAction(pageId: string) {
const page = await prisma.page.findUnique({ where: { id: pageId } });
if (!page) throw new Error(`Page not found: ${pageId}`);
await addNavLink({ pageId });
revalidatePath("/", "layout");
}
+57 -37
View File
@@ -1,19 +1,37 @@
import { getCurrentUser } from "../user";
import type { Block, Page, PageMeta, PageStatus, PageType } from "./types";
import type { Block, Page, PageMeta, PagePublic, PageStatus, PageType } from "./types";
import { prisma } from "../prisma";
import { Prisma } from "@/lib/generated/prisma/client";
const publicPageSelect = {
id: true,
slug: true,
title: true,
type: true,
status: true,
meta: true,
createdAt: true,
updatedAt: true,
publishedAt: true,
} as const;
export async function getPages(type: PageType, status: PageStatus, limit?: number) {
return await prisma.page.findMany({ where: { type, status }, take: limit, orderBy: { publishedAt: "desc" }, }) as Page[];
return prisma.page.findMany({
where: { type, status },
select: publicPageSelect,
take: limit,
orderBy: { publishedAt: "desc" },
}) as Promise<PagePublic[]>;
}
export async function getPageById(id: string) {
return await prisma.page.findUnique({ where: { id: id } });
return prisma.page.findUnique({ where: { id } }) as Promise<Page | null>;
}
export async function getPageBySlug(slug: string, type?: PageType) {
return await prisma.page.findFirst({
return prisma.page.findFirst({
where: { slug, ...(type ? { type } : {}) },
}) as Page | null;
}) as Promise<Page | null>;
}
export async function createPage(slug: string, title: string, type: PageType, status: PageStatus, blocks: Block[], meta?: PageMeta) {
@@ -23,39 +41,41 @@ export async function createPage(slug: string, title: string, type: PageType, st
}
if (!user.isAdmin) {
throw new Error("Access denied")
throw new Error("Access denied");
}
const existingPage = await prisma.page.findUnique({ where: { slug } });
if (existingPage) {
throw new Error("Page already exists");
}
const page = await prisma.page.create({
data: {
slug,
title,
type,
status,
meta: meta ?? {},
publishedAt: status === "PUBLISHED" ? new Date() : null,
createdBy: user.id
},
});
if (blocks.length > 0) {
await prisma.block.createMany({
data: blocks.map((block) => ({
pageId: page.id,
parentId: block.parentId,
type: block.type,
position: block.position,
content: block.content,
})),
try {
const page = await prisma.page.create({
data: {
slug,
title,
type,
status,
meta: meta ?? {},
publishedAt: status === "PUBLISHED" ? new Date() : null,
createdBy: user.id,
},
});
}
return page;
if (blocks.length > 0) {
await prisma.block.createMany({
data: blocks.map((block) => ({
pageId: page.id,
parentId: block.parentId,
type: block.type,
position: block.position,
content: block.content as object,
})),
});
}
return page;
} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
throw new Error("Page already exists");
}
throw e;
}
}
export async function updatePage(
@@ -81,7 +101,7 @@ export async function updatePage(
meta: meta ?? {},
publishedAt: isNewlyPublished ? new Date() : undefined,
updatedAt: new Date(),
updatedBy: user.id
updatedBy: user.id,
},
});
@@ -94,7 +114,7 @@ export async function updatePage(
parentId: b.parentId,
type: b.type,
position: b.position,
content: b.content as any,
content: b.content as object,
})),
})]
: []),
@@ -120,4 +140,4 @@ export async function getBlocksByPageId(pageId: string) {
where: { pageId },
orderBy: { position: "asc" },
}) as Promise<Block[]>;
}
}
+14 -2
View File
@@ -17,12 +17,24 @@ export type Page = {
status: PageStatus;
meta: PageMeta;
createdAt: Date;
updatedAt: Date | null;
updatedAt: Date;
publishedAt: Date | null;
createdBy: string;
createdBy: string | null;
updatedBy: string | null;
}
export type PagePublic = {
id: string;
slug: string;
title: string;
type: PageType;
status: PageStatus;
meta: PageMeta;
createdAt: Date;
updatedAt: Date;
publishedAt: Date | null;
}
export const BLOCK_TYPES = ["PARAGRAPH", "HEADING", "QUOTE", "DIVIDER", "CALLOUT", "IMAGE", "LIST", "TABLE", "LINK"] as const;
export type BlockType = typeof BLOCK_TYPES[number];
+20 -1
View File
@@ -1,12 +1,31 @@
import { z } from "zod";
const blockContentSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("PARAGRAPH"), text: z.string() }),
z.object({ type: z.literal("HEADING"), text: z.string(), level: z.union([z.literal(1), z.literal(2), z.literal(3)]) }),
z.object({ type: z.literal("QUOTE"), text: z.string(), author: z.string().optional() }),
z.object({ type: z.literal("DIVIDER") }),
z.object({ type: z.literal("CALLOUT"), title: z.string(), text: z.string() }),
z.object({ type: z.literal("IMAGE"), url: z.string(), caption: z.string().optional() }),
z.object({ type: z.literal("LIST"), style: z.enum(["BULLET", "ORDERED"]), items: z.array(z.string()) }),
z.object({ type: z.literal("TABLE"), headers: z.array(z.string()), rows: z.array(z.array(z.string())) }),
z.object({ type: z.literal("LINK"), label: z.string(), href: z.string() }),
]);
export const pageSchema = z.object({
id: z.string().nullable(),
title: z.string().min(1, "Title is required"),
slug: z.string().min(1, "Slug is required"),
type: z.enum(["NEWS", "PAGE"]),
status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]),
blocks: z.array(z.any()),
blocks: z.array(z.object({
id: z.string(),
pageId: z.string(),
parentId: z.string().nullable(),
type: z.enum(["PARAGRAPH", "HEADING", "QUOTE", "DIVIDER", "CALLOUT", "IMAGE", "LIST", "TABLE", "LINK"]),
position: z.number(),
content: blockContentSchema,
})),
meta: z.object({
location: z.string().optional(),
tags: z.array(z.string()).optional(),
+1 -1
View File
@@ -1,4 +1,4 @@
"use server"
"use server";
import { generatePkce, generateState } from "@/lib/auth/pkce";
import { pkceConfig } from "@/lib/cookieConfig";
+2 -2
View File
@@ -1,5 +1,5 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
+1
View File
@@ -11,6 +11,7 @@
"dependencies": {
"@prisma/adapter-pg": "^7.8.0",
"@prisma/client": "^7.8.0",
"@tanstack/react-table": "^8.21.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"jose": "^6.2.3",
+60 -20
View File
@@ -32,6 +32,9 @@ model User {
editedPages Page[] @relation("PageEditor")
citizenshipApplications CitizenshipApplication[]
reviewedApplications CitizenshipApplication[] @relation("CitizenshipReviewer")
citizenships Citizenship[]
}
enum PageStatus {
@@ -100,34 +103,71 @@ enum CitizenshipApplicationStatus {
enum ApplicationType {
PREVIOUS_CITIZENSHIP
BORN_IN_TERRITORY
NATURALIZATION
}
model CitizenshipApplication {
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
surname String
givenNames String
sex Sex
birthDate DateTime
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
surname String
givenNames String
sex Sex
birthDate DateTime
applicationType ApplicationType
previousCountry String?
previousRegion String?
birthRegion String?
naturalizationReason String?
address String
height String
eyeColor String
status CitizenshipApplicationStatus @default(PENDING)
address String
regionId String?
city String?
street String?
customAddress String?
height String
eyeColor String
status CitizenshipApplicationStatus @default(PENDING)
rejectionReason String?
reviewedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
reviewedAt DateTime?
reviewedBy String?
reviewer User? @relation("CitizenshipReviewer", fields: [reviewedBy], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
citizenship Citizenship?
}
model Citizenship {
id String @id @default(uuid())
userId String @unique
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
applicationId String @unique
application CitizenshipApplication @relation(fields: [applicationId], references: [id])
issuedAt DateTime @default(now())
revokedAt DateTime?
document IdentityDocument?
}
model IdentityDocument {
id String @id @default(uuid())
citizenshipId String @unique
citizenship Citizenship @relation(fields: [citizenshipId], references: [id], onDelete: Cascade)
documentNumber String @unique
regionId String?
region Region? @relation(fields: [regionId], references: [id])
city String?
street String?
customAddress String?
issuedAt DateTime @default(now())
expiresAt DateTime
}
model Region {
id String @id
name String
capital String
documents IdentityDocument[]
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB