feat: citizenship applications
This commit is contained in:
@@ -1,12 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useTransition } from "react";
|
||||
import { useRef, useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Editor, { EditorData } from "@/components/editor";
|
||||
import { savePageAction } from "@/lib/pages/actions";
|
||||
import { validatePage } from "@/lib/pages/validation";
|
||||
import { Block, Page, PageMeta, PageType } from "@/lib/pages/types";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
type Props = {
|
||||
page: Page | null;
|
||||
@@ -17,10 +19,11 @@ type Props = {
|
||||
export default function EditPageClient({ page, pageType, initialBlocks = [] }: Props) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [fieldErrors, setFieldErrors] = useState<{ title?: string[]; slug?: string[] }>({});
|
||||
|
||||
const dataRef = useRef<EditorData>({
|
||||
title: page?.title ?? "",
|
||||
type: page?.type ?? "",
|
||||
type: pageType,
|
||||
slug: page?.slug ?? "",
|
||||
location: (page?.meta as PageMeta)?.location ?? "",
|
||||
tags: (page?.meta as PageMeta)?.tags ?? [],
|
||||
@@ -30,7 +33,7 @@ export default function EditPageClient({ page, pageType, initialBlocks = [] }: P
|
||||
function handleSave(status: "DRAFT" | "PUBLISHED") {
|
||||
startTransition(async () => {
|
||||
const data = dataRef.current;
|
||||
await savePageAction({
|
||||
const payload = {
|
||||
id: page?.id ?? null,
|
||||
slug: data.slug || data.title.toLowerCase().replace(/\s+/g, "-"),
|
||||
title: data.title,
|
||||
@@ -38,8 +41,32 @@ export default function EditPageClient({ page, pageType, initialBlocks = [] }: P
|
||||
status,
|
||||
blocks: data.blocks,
|
||||
meta: { location: data.location, tags: data.tags },
|
||||
});
|
||||
router.push(`/${page?.type.toLowerCase()}/${data.slug}`);
|
||||
};
|
||||
|
||||
const parsed = validatePage(payload);
|
||||
if (!parsed.success) {
|
||||
const errors: { title?: string[]; slug?: string[] } = {};
|
||||
for (const msg of parsed.errors) {
|
||||
if (msg.toLowerCase().includes("title")) {
|
||||
(errors.title ??= []).push(msg);
|
||||
} else if (msg.toLowerCase().includes("slug")) {
|
||||
(errors.slug ??= []).push(msg);
|
||||
}
|
||||
}
|
||||
setFieldErrors(errors);
|
||||
toast.error(parsed.errors.join(", "));
|
||||
return;
|
||||
}
|
||||
|
||||
setFieldErrors({});
|
||||
|
||||
try {
|
||||
await savePageAction(payload);
|
||||
toast.success("Page saved");
|
||||
router.push(`/${pageType.toLowerCase()}/${data.slug}`);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Failed to save page");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -61,8 +88,10 @@ export default function EditPageClient({ page, pageType, initialBlocks = [] }: P
|
||||
page={page}
|
||||
type={pageType}
|
||||
initialBlocks={initialBlocks}
|
||||
errors={fieldErrors}
|
||||
onChange={(data) => {
|
||||
dataRef.current = data;
|
||||
setFieldErrors({});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -15,7 +15,7 @@ export default async function EditPage({ params }: { params: Promise<{ type: str
|
||||
const pageType = type.toUpperCase() as PageType;
|
||||
if (!PAGE_TYPES.includes(pageType)) notFound();
|
||||
|
||||
const page = await getPageBySlug(slug);
|
||||
const page = await getPageBySlug(slug, pageType);
|
||||
if (!page) notFound();
|
||||
const blocks = page ? await getBlocksByPageId(page.id) : [];
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Header from "@/components/header";
|
||||
import Footer from "@/components/footer";
|
||||
import { getPageBySlug, getBlocksByPageId } from "@/lib/pages/repository";
|
||||
import { getCurrentUser, getUser } from "@/lib/user";
|
||||
import { getCurrentUser, getUsers } from "@/lib/user";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Block, PAGE_TYPES, PageMeta, PageType } from "@/lib/pages/types";
|
||||
import { cn, formatDate } from "@/lib/utils";
|
||||
@@ -140,15 +140,16 @@ export default async function Page({ params }: { params: Promise<{ type: string;
|
||||
const pageType = type.toUpperCase() as PageType;
|
||||
if (!PAGE_TYPES.includes(pageType)) notFound();
|
||||
|
||||
const page = await getPageBySlug(slug);
|
||||
const page = await getPageBySlug(slug, pageType);
|
||||
if (!page || (!user?.isAdmin && page.status == "ARCHIVED")) notFound();
|
||||
|
||||
const navlink = await getNavLinkByPageId(page.id);
|
||||
|
||||
const blocks = page ? await getBlocksByPageId(page.id) : [];
|
||||
|
||||
const createdBy = await getUser(page?.createdBy);
|
||||
const updatedBy = await getUser(page?.updatedBy);
|
||||
const users = await getUsers(page.createdBy, page.updatedBy);
|
||||
const createdBy = users.find((u) => u.id === page.createdBy) ?? null;
|
||||
const updatedBy = users.find((u) => u.id === page.updatedBy) ?? null;
|
||||
|
||||
const isNews = page.type === "NEWS";
|
||||
const isArchived = page.status === "ARCHIVED";
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { CitizenshipApplication } from "@/lib/citizenship/types";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { cn, formatDate } from "@/lib/utils";
|
||||
import { CheckIcon, ClockFadingIcon, PlusIcon, XIcon } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function ApplicationsDialog({ applications }: { applications: CitizenshipApplication[] }) {
|
||||
return (
|
||||
<Dialog>
|
||||
<DialogTrigger asChild><Button variant="secondary">Citizenship applications</Button></DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle asChild><h3>Citizenship applications</h3></DialogTitle>
|
||||
<DialogDescription>Here are your citizenship applications</DialogDescription>
|
||||
<Accordion type="single" collapsible>
|
||||
{applications.map((application, i) => (
|
||||
<AccordionItem key={application.id} value={application.id}>
|
||||
<AccordionTrigger><h3>Application №{i + 1}</h3></AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex flex-row gap-2 items-center text-muted-foreground">
|
||||
<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>
|
||||
</div>
|
||||
{application.status === "REJECTED" && (
|
||||
<div className="flex flex-col gap-0.5 mt-2">
|
||||
<div className="flex flex-row gap-2 items-center text-destructive">
|
||||
<XIcon size={16} /><p>Rejected</p>
|
||||
</div>
|
||||
<p className="text-muted-foreground">{application.rejectionReason}</p>
|
||||
</div>
|
||||
)}
|
||||
{application.status === "APPROVED" && (
|
||||
<div className="flex flex-row gap-2 items-center mt-2">
|
||||
<CheckIcon size={16} /><p>Approved</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
</DialogHeader>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
"use client";
|
||||
|
||||
import { useActionState, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Field,
|
||||
FieldContent,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldLegend,
|
||||
FieldSet,
|
||||
} from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
} from "@/components/ui/alert";
|
||||
import { InfoIcon } from "lucide-react";
|
||||
import { submitCitizenshipApplication, type ApplicationState } from "@/lib/citizenship/actions";
|
||||
import { EYE_COLORS } from "@/lib/citizenship/types";
|
||||
import Link from "next/link";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
|
||||
type Props = {
|
||||
firstName: string;
|
||||
secondName: string;
|
||||
sex: string;
|
||||
birthDate: Date | null;
|
||||
};
|
||||
|
||||
const initialState: ApplicationState = { success: false, errors: [] };
|
||||
|
||||
function formatDate(d: Date | null): string {
|
||||
if (!d) return "";
|
||||
return d.toISOString().split("T")[0];
|
||||
}
|
||||
|
||||
type AppType = "PREVIOUS_CITIZENSHIP" | "BORN_IN_TERRITORY" | "NATURALIZATION";
|
||||
|
||||
export function CitizenshipApplicationForm({ firstName, secondName, sex, birthDate }: Props) {
|
||||
const [appType, setAppType] = useState<AppType | "">("");
|
||||
const [state, formAction, isPending] = useActionState(submitCitizenshipApplication, initialState);
|
||||
|
||||
return (
|
||||
<form action={formAction}>
|
||||
<FieldGroup>
|
||||
<FieldSet>
|
||||
<FieldLegend>Personal information</FieldLegend>
|
||||
<Alert className="border-amber-200 bg-amber-50 text-amber-900">
|
||||
<InfoIcon />
|
||||
<AlertTitle>Important notice</AlertTitle>
|
||||
<AlertDescription>
|
||||
Personal data is sourced from your account profile. Please ensure that all information is accurate.
|
||||
If corrections are required, update your details in Kotosoft ID and synchronise your account.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="surname">Surname</FieldLabel>
|
||||
<Input
|
||||
id="surname"
|
||||
value={secondName}
|
||||
readOnly
|
||||
className="bg-muted text-muted-foreground"
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="givenNames">Given names</FieldLabel>
|
||||
<Input
|
||||
id="givenNames"
|
||||
value={firstName}
|
||||
readOnly
|
||||
className="bg-muted text-muted-foreground"
|
||||
/>
|
||||
</Field>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Field>
|
||||
<FieldLabel htmlFor="sex">Sex</FieldLabel>
|
||||
<Input
|
||||
id="sex"
|
||||
value={sex === "MALE" ? "Male" : "Female"}
|
||||
readOnly
|
||||
className="bg-muted text-muted-foreground"
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="birthDate">Date of birth</FieldLabel>
|
||||
<Input
|
||||
id="birthDate"
|
||||
value={formatDate(birthDate)}
|
||||
readOnly
|
||||
className="bg-muted text-muted-foreground"
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
<FieldSet>
|
||||
<FieldLegend>Eligibility basis</FieldLegend>
|
||||
<FieldDescription>
|
||||
Select the basis on which you are applying for citizenship.
|
||||
</FieldDescription>
|
||||
<RadioGroup
|
||||
name="applicationType"
|
||||
value={appType}
|
||||
onValueChange={(v) => setAppType(v as AppType)}
|
||||
required
|
||||
>
|
||||
<FieldLabel htmlFor="prev-citizen">
|
||||
<Field orientation="horizontal">
|
||||
<RadioGroupItem value="PREVIOUS_CITIZENSHIP" id="prev-citizen" />
|
||||
<FieldContent>
|
||||
<span className="text-sm font-medium">
|
||||
Previous citizenship holder
|
||||
</span>
|
||||
<FieldDescription>
|
||||
I held citizenship of the Duspean Republic or the Country of
|
||||
Reality on 31 March 2026.
|
||||
</FieldDescription>
|
||||
</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" />
|
||||
<FieldContent>
|
||||
<span className="text-sm font-medium">Naturalisation</span>
|
||||
<FieldDescription>
|
||||
I am a foreign national seeking naturalisation.
|
||||
</FieldDescription>
|
||||
</FieldContent>
|
||||
</Field>
|
||||
</FieldLabel>
|
||||
</RadioGroup>
|
||||
</FieldSet>
|
||||
{appType === "PREVIOUS_CITIZENSHIP" && (
|
||||
<FieldSet>
|
||||
<FieldLegend>Previous citizenship details</FieldLegend>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="previousCountry">Country</FieldLabel>
|
||||
<Select name="previousCountry" defaultValue="">
|
||||
<SelectTrigger id="previousCountry">
|
||||
<SelectValue placeholder="Select country" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="DUS">Duspean Republic</SelectItem>
|
||||
<SelectItem value="REA">Country of Reality</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="previousRegion">Region of issuance</FieldLabel>
|
||||
<Input
|
||||
id="previousRegion"
|
||||
name="previousRegion"
|
||||
placeholder="State, region, or territory"
|
||||
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>.
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
)}
|
||||
{appType === "NATURALIZATION" && (
|
||||
<FieldSet>
|
||||
<FieldLegend>Naturalisation statement</FieldLegend>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="naturalizationReason">
|
||||
Why do you wish to become a citizen of the European Federation?
|
||||
</FieldLabel>
|
||||
<Textarea
|
||||
id="naturalizationReason"
|
||||
name="naturalizationReason"
|
||||
placeholder="Explain your motivation for seeking citizenship..."
|
||||
rows={4}
|
||||
required
|
||||
/>
|
||||
</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>
|
||||
<Input
|
||||
id="height"
|
||||
type="number"
|
||||
name="height"
|
||||
min={60}
|
||||
max={240}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="eyeColor">Eye colour</FieldLabel>
|
||||
<Select name="eyeColor" defaultValue="">
|
||||
<SelectTrigger id="eyeColor">
|
||||
<SelectValue placeholder="Select eye colour" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{EYE_COLORS.map((color) => (
|
||||
<SelectItem key={color} value={color}>
|
||||
{color}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
{state.errors.length > 0 && (
|
||||
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-900">
|
||||
<ul className="list-disc pl-4">
|
||||
{state.errors.map((err, i) => (
|
||||
<li key={i}>{err}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<Field orientation="horizontal">
|
||||
<Button type="submit">{isPending && <Spinner />}Submit application</Button>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
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 { CitizenshipApplicationForm } from "./form";
|
||||
import { getUserApplications } from "@/lib/citizenship/repository";
|
||||
|
||||
export default async function CitizenshipApplication() {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) redirect("/");
|
||||
|
||||
const applications = await getUserApplications(user.id);
|
||||
const canApply = applications.length === 0 || applications.every((a) => a.status === "REJECTED");
|
||||
if (!canApply) redirect("/account/citizenship");
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header />
|
||||
<div className="flex flex-row py-16 gap-8">
|
||||
<AccountMenu />
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="flex flex-col gap-6">
|
||||
<h2>Citizenship application</h2>
|
||||
<div className="w-96 flex flex-col gap-6">
|
||||
<CitizenshipApplicationForm
|
||||
firstName={user.firstName}
|
||||
secondName={user.secondName}
|
||||
sex={user.sex}
|
||||
birthDate={user.birthDate}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Footer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
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 { InfoIcon } from "lucide-react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion";
|
||||
import { ApplicationsDialog } from "./applicationsDialog";
|
||||
import { getUserApplications } from "@/lib/citizenship/repository";
|
||||
|
||||
export default async function Citizenship() {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) redirect("/");
|
||||
|
||||
const applications = await getUserApplications(user.id);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header />
|
||||
<div className="flex flex-row py-16 gap-8">
|
||||
<AccountMenu />
|
||||
<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>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
<Footer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
Dialog, DialogClose, DialogContent, DialogDescription,
|
||||
DialogFooter, DialogHeader, DialogTitle, DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import deleteUserAction from "../actions/delete";
|
||||
import { deleteUserAction } from "@/lib/user/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import logout from "../actions/logout";
|
||||
import { logout } from "@/lib/user/actions";
|
||||
|
||||
export function LogoutButton() {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"use client"
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { BookOpenTextIcon, SignatureIcon, UserIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
const menuItems = [
|
||||
{
|
||||
href: "/account",
|
||||
label: "Profile",
|
||||
icon: UserIcon,
|
||||
},
|
||||
{
|
||||
href: "/account/citizenship",
|
||||
label: "Citizenship",
|
||||
icon: BookOpenTextIcon,
|
||||
},
|
||||
{
|
||||
href: "/account/signature",
|
||||
label: "Signature",
|
||||
icon: SignatureIcon,
|
||||
},
|
||||
];
|
||||
|
||||
export function AccountMenu() {
|
||||
const pathname = usePathname();
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-56 gap-2 mx-16 shrink-0">
|
||||
{menuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const active = pathname === item.href;
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={item.href}
|
||||
key={item.href}
|
||||
className={cn(
|
||||
"flex flex-row gap-2 items-center underline-offset-8 decoration-2 duration-200",
|
||||
active
|
||||
? "text-foreground underline mb-1.5"
|
||||
: "text-muted-foreground hover:text-foreground hover:underline"
|
||||
)}
|
||||
>
|
||||
<Icon size={16} />
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+4
-16
@@ -1,6 +1,5 @@
|
||||
import Footer from "@/components/footer";
|
||||
import Header from "@/components/header";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { getCurrentUser } from "@/lib/user";
|
||||
import { formatDate } from "@/lib/utils";
|
||||
@@ -8,6 +7,8 @@ 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";
|
||||
|
||||
function ProfileField({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
@@ -26,20 +27,7 @@ export default async function Account() {
|
||||
<>
|
||||
<Header />
|
||||
<div className="flex flex-row py-16 gap-8">
|
||||
<div className="flex flex-col w-56 gap-2 mx-16 shrink-0">
|
||||
<div className="flex flex-row gap-2 items-center text-foreground underline underline-offset-8 decoration-2 mb-1.5">
|
||||
<UserIcon size={16} />
|
||||
<h4>Profile</h4>
|
||||
</div>
|
||||
<div className="flex flex-row gap-2 items-center text-muted-foreground hover:text-foreground hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">
|
||||
<BookOpenTextIcon size={16} />
|
||||
<h4>Citizenship</h4>
|
||||
</div>
|
||||
<div className="flex flex-row gap-2 items-center text-muted-foreground hover:text-foreground hover:underline underline-offset-8 decoration-2 duration-200 cursor-pointer">
|
||||
<SignatureIcon size={16} />
|
||||
<h4>Signature</h4>
|
||||
</div>
|
||||
</div>
|
||||
<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">
|
||||
@@ -61,7 +49,7 @@ export default async function Account() {
|
||||
<h4>Update personal details</h4>
|
||||
<p className="text-muted-foreground">Syncs your name, email, and birthday from Kotosoft ID</p>
|
||||
</div>
|
||||
<Button variant="secondary">Update</Button>
|
||||
<UpdateButton />
|
||||
</div>
|
||||
<div className="flex flex-row items-center justify-between">
|
||||
<div className="flex flex-col">
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client"
|
||||
|
||||
import { useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { toast } from "sonner";
|
||||
import { updateUserAction } from "@/lib/user/actions";
|
||||
|
||||
export function UpdateButton() {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="secondary"
|
||||
disabled={isPending}
|
||||
onClick={() =>
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await updateUserAction();
|
||||
toast.success("Profile updated");
|
||||
} catch {
|
||||
toast.error("Failed to update profile. Your session may have expired. Try signing in again.");
|
||||
}
|
||||
})
|
||||
}
|
||||
>
|
||||
{isPending && <Spinner />}Update
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
"use server"
|
||||
|
||||
import { deleteUser } from "@/lib/user/repository"
|
||||
import logout from "./logout";
|
||||
|
||||
export default async function deleteUserAction(userId: string ) {
|
||||
await deleteUser(userId);
|
||||
await logout();
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
"use server"
|
||||
|
||||
import { generatePkce, generateState } from "@/lib/auth/pkce";
|
||||
import { pkceConfig } from "@/lib/cookieConfig";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default async function login() {
|
||||
const { verifier, challenge } = generatePkce();
|
||||
const state = generateState();
|
||||
|
||||
const store = await cookies();
|
||||
store.set("pkce_verifier", verifier, pkceConfig);
|
||||
store.set("oauth_state", state, pkceConfig);
|
||||
|
||||
const params = new URLSearchParams({
|
||||
client_id: process.env.KOTOSOFT_ID_CLIENT_ID!,
|
||||
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
|
||||
scope: "profile:read",
|
||||
response_type: "code",
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: "S256",
|
||||
state,
|
||||
});
|
||||
|
||||
redirect(`${process.env.KOTOSOFT_ID_API_URL}/oauth/authorize?${params}`);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
"use server"
|
||||
|
||||
import { deleteSession } from "@/lib/auth/session";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default async function logout() {
|
||||
await deleteSession();
|
||||
redirect("/");
|
||||
}
|
||||
@@ -5,7 +5,35 @@ import { createSession } from "@/lib/auth/session";
|
||||
import { exchangeCode, fetchKotosoftUser } from "@/lib/kotosoft/client";
|
||||
import { findOrCreateUser } from "@/lib/user/repository";
|
||||
|
||||
const rateLimitMap = new Map<string, { count: number; resetAt: number }>();
|
||||
const RATE_LIMIT_WINDOW = 60_000;
|
||||
const RATE_LIMIT_MAX = 10;
|
||||
|
||||
function checkRateLimit(ip: string): boolean {
|
||||
const now = Date.now();
|
||||
const entry = rateLimitMap.get(ip);
|
||||
if (!entry || now > entry.resetAt) {
|
||||
rateLimitMap.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW });
|
||||
return true;
|
||||
}
|
||||
entry.count++;
|
||||
return entry.count <= RATE_LIMIT_MAX;
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const url = process.env.PUBLIC_URL;
|
||||
if (url) {
|
||||
const requestOrigin = request.nextUrl.origin;
|
||||
if (requestOrigin !== url) {
|
||||
return NextResponse.json({ message: "Access denied" }, { status: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
const ip = request.headers.get("x-forwarded-for") ?? request.headers.get("x-real-ip") ?? "unknown";
|
||||
if (!checkRateLimit(ip)) {
|
||||
return NextResponse.json({ message: "Too many requests" }, { status: 429 });
|
||||
}
|
||||
|
||||
const { searchParams } = request.nextUrl;
|
||||
const code = searchParams.get("code");
|
||||
const state = searchParams.get("state");
|
||||
@@ -32,8 +60,9 @@ export async function GET(request: NextRequest) {
|
||||
email: kotosoftUser.email,
|
||||
firstName: kotosoftUser.first_name,
|
||||
secondName: kotosoftUser.second_name,
|
||||
sex: kotosoftUser.sex,
|
||||
sex: kotosoftUser.sex as "MALE" | "FEMALE",
|
||||
birthDate: kotosoftUser.birth_date,
|
||||
isAdmin: false,
|
||||
});
|
||||
|
||||
await createSession(user.id);
|
||||
|
||||
+38
-5
@@ -1,15 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useTransition } from "react";
|
||||
import { useRef, useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Editor, { EditorData } from "@/components/editor";
|
||||
import { savePageAction } from "@/lib/pages/actions";
|
||||
import { validatePage } from "@/lib/pages/validation";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function CreatePageClient() {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [fieldErrors, setFieldErrors] = useState<{ title?: string[]; slug?: string[] }>({});
|
||||
const dataRef = useRef<EditorData>({
|
||||
title: "",
|
||||
type: "NEWS",
|
||||
@@ -22,7 +25,7 @@ export default function CreatePageClient() {
|
||||
function handleSave(status: "DRAFT" | "PUBLISHED") {
|
||||
startTransition(async () => {
|
||||
const data = dataRef.current;
|
||||
await savePageAction({
|
||||
const payload = {
|
||||
id: null,
|
||||
slug: data.slug || data.title.toLowerCase().replace(/\s+/g, "-"),
|
||||
title: data.title,
|
||||
@@ -30,8 +33,32 @@ export default function CreatePageClient() {
|
||||
status,
|
||||
blocks: data.blocks,
|
||||
meta: { location: data.location, tags: data.tags },
|
||||
});
|
||||
router.push("/news");
|
||||
};
|
||||
|
||||
const parsed = validatePage(payload);
|
||||
if (!parsed.success) {
|
||||
const errors: { title?: string[]; slug?: string[] } = {};
|
||||
for (const msg of parsed.errors) {
|
||||
if (msg.toLowerCase().includes("title")) {
|
||||
(errors.title ??= []).push(msg);
|
||||
} else if (msg.toLowerCase().includes("slug")) {
|
||||
(errors.slug ??= []).push(msg);
|
||||
}
|
||||
}
|
||||
setFieldErrors(errors);
|
||||
toast.error(parsed.errors.join(", "));
|
||||
return;
|
||||
}
|
||||
|
||||
setFieldErrors({});
|
||||
|
||||
try {
|
||||
await savePageAction(payload);
|
||||
toast.success("Page saved");
|
||||
router.push("/news");
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : "Failed to save page");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -54,7 +81,13 @@ export default function CreatePageClient() {
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Editor onChange={(data) => { dataRef.current = data; }} />
|
||||
<Editor
|
||||
onChange={(data) => {
|
||||
dataRef.current = data;
|
||||
setFieldErrors({});
|
||||
}}
|
||||
errors={fieldErrors}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+5
-1
@@ -2,6 +2,7 @@ import type { Metadata } from "next";
|
||||
import localFont from "next/font/local"
|
||||
import "./globals.css";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
|
||||
const helvetica = localFont({
|
||||
src: "../public/fonts/HelveticaNeue-Medium.otf",
|
||||
@@ -23,7 +24,10 @@ export default function RootLayout({
|
||||
lang="en"
|
||||
className={cn("h-full", "antialiased", helvetica.className, "font-sans")}
|
||||
>
|
||||
<body className="min-h-full flex flex-col">{children}</body>
|
||||
<body className="min-h-full flex flex-col">
|
||||
{children}
|
||||
<Toaster />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
+6
-6
@@ -16,25 +16,25 @@ export default async function Home() {
|
||||
<div className="grid grid-cols-[2fr_1fr_1fr_1fr] gap-8">
|
||||
<Link href="/page/citizenship">
|
||||
<div className="flex items-end h-64 p-4 rounded-lg bg-primary text-primary-foreground">
|
||||
<h1 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Become a citizen<ArrowRightIcon size={30} /></h1>
|
||||
<h1 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Become a citizen<ArrowRightIcon size={30} /></h1>
|
||||
</div>
|
||||
</Link>
|
||||
<div className="grid grid-rows-2 gap-8">
|
||||
<Link href="/page/president">
|
||||
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
|
||||
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Learn more about the President</h2>
|
||||
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Learn more about the President</h2>
|
||||
</div>
|
||||
</Link>
|
||||
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
|
||||
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Acknowledge with the Federal Government</h2>
|
||||
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Acknowledge with the Federal Government</h2>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-rows-2 gap-8">
|
||||
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
|
||||
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Regions of the Federation</h2>
|
||||
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Regions of the Federation</h2>
|
||||
</div>
|
||||
<div className="flex items-end h-28 p-2.5 rounded-lg bg-muted">
|
||||
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover: duration-200 cursor-pointer">Receive consular services abroad</h2>
|
||||
<h2 className="flex flex-row items-center gap-2 hover:gap-4 hover:duration-200 cursor-pointer">Receive consular services abroad</h2>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -47,7 +47,7 @@ export default async function Home() {
|
||||
)) : <h2 className="text-muted-foreground">There are no news yet...</h2>
|
||||
}
|
||||
</div>
|
||||
<Link href="/news"><h3 className="w-max flex flex-row items-center gap-2 hover:gap-2.5 hover: duration-200 cursor-pointer">See all news<ArrowRightIcon size={20} /></h3></Link>
|
||||
<Link href="/news"><h3 className="w-max flex flex-row items-center gap-2 hover:gap-2.5 hover:duration-200 cursor-pointer">See all news<ArrowRightIcon size={20} /></h3></Link>
|
||||
</div>
|
||||
</div>
|
||||
<Footer />
|
||||
|
||||
@@ -17,9 +17,11 @@
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"shadcn": "^4.11.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"uuid": "^14.0.0",
|
||||
"zod": "^4.4.3",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
@@ -1384,6 +1386,8 @@
|
||||
|
||||
"sisteransi": ["[email protected]", "", {}, "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="],
|
||||
|
||||
"sonner": ["[email protected]", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w=="],
|
||||
|
||||
"source-map": ["[email protected]", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
|
||||
|
||||
"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
@@ -1536,7 +1540,7 @@
|
||||
|
||||
"zeptomatch": ["[email protected]", "", { "dependencies": { "grammex": "^3.1.11", "graphmatch": "^1.1.0" } }, "sha512-KiGErG2J0G82LSpniV0CtIzjlJ10E04j02VOudJsPyPwNZgGnRKQy7I1R7GMyg/QswnE4l7ohSGrQbQbjXPPDA=="],
|
||||
|
||||
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
|
||||
|
||||
"zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
|
||||
|
||||
@@ -1558,8 +1562,6 @@
|
||||
|
||||
"@modelcontextprotocol/sdk/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
|
||||
|
||||
"@modelcontextprotocol/sdk/zod": ["[email protected]", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
|
||||
|
||||
"@next/eslint-plugin-next/fast-glob": ["[email protected]", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.4" } }, "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg=="],
|
||||
|
||||
"@prisma/engines/@prisma/get-platform": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.8.0" } }, "sha512-WlxgRGnolL8VH2EmkH1R/DkKNr/mVdS3G2h42IZFFZ3eUrH9OT6t73kIOSlkkrv50wG123Iq8d96ufv5LlZktw=="],
|
||||
@@ -1622,8 +1624,6 @@
|
||||
|
||||
"eslint-plugin-import/tsconfig-paths": ["[email protected]", "", { "dependencies": { "@types/json5": "^0.0.29", "json5": "^1.0.2", "minimist": "^1.2.6", "strip-bom": "^3.0.0" } }, "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg=="],
|
||||
|
||||
"eslint-plugin-react-hooks/zod": ["[email protected]", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
|
||||
|
||||
"fast-glob/glob-parent": ["[email protected]", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"is-bun-module/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA=="],
|
||||
@@ -1654,6 +1654,8 @@
|
||||
|
||||
"restore-cursor/onetime": ["[email protected]", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="],
|
||||
|
||||
"shadcn/zod": ["[email protected]", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||
|
||||
"sharp/semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA=="],
|
||||
|
||||
"string-width/emoji-regex": ["[email protected]", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
|
||||
|
||||
@@ -14,16 +14,17 @@ import { PencilIcon, XIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { PageType } from "@/lib/pages/types";
|
||||
|
||||
type Draft = { id: string; title: string; slug: string; updatedAt: Date };
|
||||
type Draft = { id: string; type: PageType; title: string; slug: string; updatedAt: Date | null };
|
||||
|
||||
export default function DraftsDialog({ drafts }: { drafts: Draft[]}) {
|
||||
const [isDeletingId, setIsDeletingId] = useState("");
|
||||
|
||||
async function deletePage(id: string) {
|
||||
async function deletePage(id: string, type: PageType) {
|
||||
setIsDeletingId(id);
|
||||
try {
|
||||
await deletePageAction(id)
|
||||
await deletePageAction(id, type)
|
||||
} finally {
|
||||
setIsDeletingId("")
|
||||
}
|
||||
@@ -51,7 +52,7 @@ export default function DraftsDialog({ drafts }: { drafts: Draft[]}) {
|
||||
<Link href={`/news/${draft.slug}/edit`}>
|
||||
<Button variant="secondary" size="icon-sm"><PencilIcon /></Button>
|
||||
</Link>
|
||||
<Button disabled={isDeletingId === draft.id} variant="secondary" size="icon-sm" onClick={() => deletePage(draft.id)}>
|
||||
<Button disabled={isDeletingId === draft.id} variant="secondary" size="icon-sm" onClick={() => deletePage(draft.id, draft.type)}>
|
||||
{isDeletingId === draft.id ? <Spinner /> : <XIcon />}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
+13
-7
@@ -1,9 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field";
|
||||
import { Field, FieldError, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field";
|
||||
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
|
||||
import { Block, BlockType, Page, PageMeta, PageType } from "@/lib/pages/types";
|
||||
import { Globe2Icon, PlusIcon, Trash2Icon, XIcon, GripVerticalIcon, ChevronDownIcon, ImageIcon, QuoteIcon, AlertCircleIcon, MinusIcon, ListIcon, TableIcon, TypeIcon, AlignLeftIcon, InfoIcon, DotIcon, ListOrderedIcon, LinkIcon } from "lucide-react";
|
||||
@@ -29,6 +30,7 @@ type EditorProps = {
|
||||
type?: PageType;
|
||||
initialBlocks?: Block[];
|
||||
onChange: (data: EditorData) => void;
|
||||
errors?: { title?: string[]; slug?: string[] };
|
||||
};
|
||||
|
||||
const BLOCK_ICONS: Record<BlockType, React.ReactNode> = {
|
||||
@@ -55,7 +57,7 @@ const BLOCK_LABELS: Record<BlockType, string> = {
|
||||
LINK: "Link"
|
||||
};
|
||||
|
||||
export default function Editor({ page, initialBlocks = [], onChange }: EditorProps) {
|
||||
export default function Editor({ page, initialBlocks = [], onChange, errors }: EditorProps) {
|
||||
const meta = (page?.meta as PageMeta) ?? {};
|
||||
|
||||
const [title, setTitle] = useState(page?.title ?? "");
|
||||
@@ -94,7 +96,7 @@ export default function Editor({ page, initialBlocks = [], onChange }: EditorPro
|
||||
setBlocks([
|
||||
...blocks,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
id: uuidv4(),
|
||||
pageId: page?.id ?? "",
|
||||
parentId: null,
|
||||
type: blockType,
|
||||
@@ -139,11 +141,12 @@ export default function Editor({ page, initialBlocks = [], onChange }: EditorPro
|
||||
<FieldSet>
|
||||
<h2 className=" mb-6">Meta</h2>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<Field data-invalid={!!errors?.title?.length}>
|
||||
<FieldLabel htmlFor="title">Title</FieldLabel>
|
||||
<InputGroup>
|
||||
<InputGroupInput
|
||||
id="title"
|
||||
aria-invalid={!!errors?.title?.length}
|
||||
value={title}
|
||||
placeholder="Enter page title"
|
||||
onChange={(e) => {
|
||||
@@ -152,6 +155,7 @@ export default function Editor({ page, initialBlocks = [], onChange }: EditorPro
|
||||
}}
|
||||
/>
|
||||
</InputGroup>
|
||||
{errors?.title && <FieldError errors={errors.title.map(m => ({ message: m }))} />}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="type">Page type</FieldLabel>
|
||||
@@ -167,11 +171,12 @@ export default function Editor({ page, initialBlocks = [], onChange }: EditorPro
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field>
|
||||
<Field data-invalid={!!errors?.slug?.length}>
|
||||
<FieldLabel htmlFor="slug">Slug</FieldLabel>
|
||||
<InputGroup>
|
||||
<InputGroupInput id="slug" value={slug} placeholder="page-slug" onChange={(e) => setSlug(e.target.value)} />
|
||||
<InputGroupInput id="slug" aria-invalid={!!errors?.slug?.length} value={slug} placeholder="page-slug" onChange={(e) => setSlug(e.target.value)} />
|
||||
</InputGroup>
|
||||
{errors?.slug && <FieldError errors={errors.slug.map(m => ({ message: m }))} />}
|
||||
</Field>
|
||||
{type === "NEWS" && (
|
||||
<Field>
|
||||
@@ -193,7 +198,7 @@ export default function Editor({ page, initialBlocks = [], onChange }: EditorPro
|
||||
value={tagInput}
|
||||
placeholder="Add a tag and press Enter"
|
||||
onChange={(e) => setTagInput(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && addTag()}
|
||||
onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addTag(); } }}
|
||||
/>
|
||||
<InputGroupAddon align="inline-end">
|
||||
<InputGroupButton onClick={addTag}>Add</InputGroupButton>
|
||||
@@ -617,6 +622,7 @@ function getDefaultContent(type: BlockType): Block["content"] {
|
||||
case "LIST": return { type: "LIST", style: "BULLET", items: [""] };
|
||||
case "TABLE": return { type: "TABLE", headers: ["", ""], rows: [["", ""]] };
|
||||
case "IMAGE": return { type: "IMAGE", url: "", caption: "" };
|
||||
case "LINK": return { type: "LINK", label: "", href: "" };
|
||||
default: return { type: "PARAGRAPH", text: "" };
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import Image from "next/image";
|
||||
import { Button } from "./ui/button";
|
||||
import login from "@/app/actions/login";
|
||||
import { login } from "@/lib/user/actions";
|
||||
import { getCurrentUser } from "@/lib/user";
|
||||
import Link from "next/link";
|
||||
import { getNavLinks } from "@/lib/navlinks/repository";
|
||||
@@ -23,7 +23,7 @@ export default async function Header() {
|
||||
<div className="absolute left-1/2 -translate-x-1/2 flex items-center gap-6">
|
||||
{
|
||||
links.map((link) => (
|
||||
<Link className="hover:underline underline-offset-8 decoration-2 duration-200" key={link.id} href={link.href || `/${link.page.type.toLowerCase()}/${link.page.slug}`}><h3>{link.label ?? link.page?.title}</h3></Link>
|
||||
<Link className="hover:underline underline-offset-8 decoration-2 duration-200" key={link.id} href={link.href || (link.page ? `/${link.page.type.toLowerCase()}/${link.page.slug}` : "/")}><h3>{link.label ?? link.page?.title}</h3></Link>
|
||||
))
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -8,7 +8,7 @@ export function NewsCard({ news }: { news: Page }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Link href={`/news/${news.slug}`} className="w-max">
|
||||
<h2 className="hover: duration-200 cursor-pointer">{news.title}</h2>
|
||||
<h2 className="hover:underline underline-offset-8 decoration-2 hover:duration-200 cursor-pointer">{news.title}</h2>
|
||||
</Link>
|
||||
<div className="flex flex-row gap-8 items-center">
|
||||
<p className="flex gap-2 items-center"><CalendarIcon size={16} />{formatDate(news.publishedAt)}</p>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import { Accordion as AccordionPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Accordion({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||
return (
|
||||
<AccordionPrimitive.Root
|
||||
data-slot="accordion"
|
||||
className={cn("flex w-full flex-col", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||
return (
|
||||
<AccordionPrimitive.Item
|
||||
data-slot="accordion-item"
|
||||
className={cn("not-last:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||
return (
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
data-slot="accordion-trigger"
|
||||
className={cn(
|
||||
"group/accordion-trigger relative flex flex-1 items-start justify-between rounded-lg border border-transparent py-2.5 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:after:border-ring disabled:pointer-events-none disabled:opacity-50 **:data-[slot=accordion-trigger-icon]:ml-auto **:data-[slot=accordion-trigger-icon]:size-4 **:data-[slot=accordion-trigger-icon]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDownIcon
|
||||
data-slot="accordion-trigger-icon"
|
||||
className="pointer-events-none shrink-0 group-aria-expanded/accordion-trigger:hidden"
|
||||
/>
|
||||
<ChevronUpIcon
|
||||
data-slot="accordion-trigger-icon"
|
||||
className="pointer-events-none hidden shrink-0 group-aria-expanded/accordion-trigger:inline"
|
||||
/>
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
)
|
||||
}
|
||||
|
||||
function AccordionContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||
return (
|
||||
<AccordionPrimitive.Content
|
||||
data-slot="accordion-content"
|
||||
className={cn(
|
||||
"overflow-hidden text-sm data-[state=open]:animate-accordion-down data-[state=closed]:animate-accordion-up",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="pt-0 pb-2.5 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground [&_p:not(:last-child)]:mb-4">
|
||||
{children}
|
||||
</div>
|
||||
</AccordionPrimitive.Content>
|
||||
)
|
||||
}
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
|
||||
@@ -242,7 +242,7 @@ function DropdownMenuSubContent({
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn("z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||
className={cn("z-50 min-w-24 origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { RadioGroup as RadioGroupPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function RadioGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Root
|
||||
data-slot="radio-group"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function RadioGroupItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Item
|
||||
data-slot="radio-group-item"
|
||||
className={cn(
|
||||
"aspect-square size-4 shrink-0 rounded-full border border-input shadow-xs outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
|
||||
<div className="size-1.5 rounded-full bg-current" />
|
||||
</RadioGroupPrimitive.Indicator>
|
||||
</RadioGroupPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
export { RadioGroup, RadioGroupItem }
|
||||
@@ -0,0 +1,25 @@
|
||||
"use client"
|
||||
|
||||
import { Toaster as SonnerToaster, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
return (
|
||||
<SonnerToaster
|
||||
className="toaster group"
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast:
|
||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "group-[.toast]:text-muted-foreground",
|
||||
actionButton:
|
||||
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||
cancelButton:
|
||||
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
+5
-3
@@ -2,7 +2,9 @@ import { SignJWT, jwtVerify } from "jose";
|
||||
import { cookies } from "next/headers";
|
||||
import { cookieConfig } from "@/lib/cookieConfig";
|
||||
|
||||
const secret = new TextEncoder().encode(process.env.JWT_SECRET!);
|
||||
function getSecret() {
|
||||
return new TextEncoder().encode(process.env.JWT_SECRET!);
|
||||
}
|
||||
|
||||
async function signJwt(userId: string) {
|
||||
return await new SignJWT({})
|
||||
@@ -10,7 +12,7 @@ async function signJwt(userId: string) {
|
||||
.setSubject(userId)
|
||||
.setIssuedAt()
|
||||
.setExpirationTime(`${process.env.SESSION_MAX_AGE}s`)
|
||||
.sign(secret);
|
||||
.sign(getSecret());
|
||||
}
|
||||
|
||||
export async function createSession(userId: string) {
|
||||
@@ -29,7 +31,7 @@ export async function getSessionUserId(): Promise<string | null> {
|
||||
if (!token) return null;
|
||||
|
||||
try {
|
||||
const { payload } = await jwtVerify(token, secret);
|
||||
const { payload } = await jwtVerify(token, getSecret());
|
||||
return payload.sub ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -7,6 +7,11 @@ export async function setTokens(accessToken: string, refreshToken: string, ttl:
|
||||
store.set("refresh_token", refreshToken, { ...cookieConfig, path: "/", maxAge: ttl * 7 * 24 * 60 * 60 });
|
||||
}
|
||||
|
||||
export async function getAccessToken() {
|
||||
const store = await cookies();
|
||||
return store.get("access_token")?.value ?? null;
|
||||
}
|
||||
|
||||
export async function deleteOAuthCookies() {
|
||||
const store = await cookies();
|
||||
store.delete("pkce_verifier");
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"use server";
|
||||
|
||||
import { getCurrentUser } from "@/lib/user";
|
||||
import { redirect } from "next/navigation";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { citizenshipApplicationSchema } from "./validation";
|
||||
import { createApplication } from "./repository";
|
||||
|
||||
export type ApplicationState = {
|
||||
success: boolean;
|
||||
errors: string[];
|
||||
};
|
||||
|
||||
export async function submitCitizenshipApplication(
|
||||
_prevState: ApplicationState,
|
||||
formData: FormData
|
||||
): Promise<ApplicationState> {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) redirect("/");
|
||||
|
||||
const applicationType = formData.get("applicationType") 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) ?? "",
|
||||
};
|
||||
|
||||
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) ?? "";
|
||||
}
|
||||
|
||||
const parsed = citizenshipApplicationSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
const fieldErrors = parsed.error.flatten().fieldErrors ?? {};
|
||||
const messages = Object.values(fieldErrors).flat().filter(Boolean);
|
||||
return { success: false, errors: messages };
|
||||
}
|
||||
|
||||
await createApplication(user.id, {
|
||||
surname: user.secondName,
|
||||
givenNames: user.firstName,
|
||||
sex: user.sex,
|
||||
birthDate: user.birthDate ?? new Date(),
|
||||
...parsed.data,
|
||||
});
|
||||
|
||||
revalidatePath("/account/citizenship");
|
||||
return { success: true, errors: [] };
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { ApplicationType } from "./types";
|
||||
|
||||
type CreateData = {
|
||||
surname: string;
|
||||
givenNames: string;
|
||||
sex: "MALE" | "FEMALE";
|
||||
birthDate: Date;
|
||||
applicationType: ApplicationType;
|
||||
previousCountry?: string | null;
|
||||
previousRegion?: string | null;
|
||||
birthRegion?: string | null;
|
||||
naturalizationReason?: string | null;
|
||||
address: string;
|
||||
height: string;
|
||||
eyeColor: string;
|
||||
};
|
||||
|
||||
export async function createApplication(userId: string, data: CreateData) {
|
||||
return prisma.citizenshipApplication.create({
|
||||
data: {
|
||||
userId,
|
||||
...data,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserApplications(userId: string) {
|
||||
return prisma.citizenshipApplication.findMany({
|
||||
where: { userId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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 type ApplicationType = typeof APPLICATION_TYPES[number];
|
||||
|
||||
export const EYE_COLORS = [
|
||||
"Blue",
|
||||
"Green",
|
||||
"Brown",
|
||||
"Hazel",
|
||||
"Gray",
|
||||
"Amber",
|
||||
] as const;
|
||||
export type EyeColor = typeof EYE_COLORS[number];
|
||||
|
||||
export type CitizenshipApplication = {
|
||||
id: string;
|
||||
userId: string;
|
||||
surname: string;
|
||||
givenNames: string;
|
||||
sex: "MALE" | "FEMALE";
|
||||
birthDate: Date;
|
||||
applicationType: ApplicationType;
|
||||
previousCountry: string | null;
|
||||
previousRegion: string | null;
|
||||
birthRegion: string | null;
|
||||
naturalizationReason: string | null;
|
||||
address: string;
|
||||
height: string;
|
||||
eyeColor: string;
|
||||
status: CitizenshipApplicationStatus;
|
||||
rejectionReason: string | null;
|
||||
reviewedAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const baseFields = {
|
||||
address: z.string().min(1, "Address is required"),
|
||||
height: z.string().min(1, "Height is required"),
|
||||
eyeColor: z.string().min(1, "Eye colour is required"),
|
||||
};
|
||||
|
||||
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,
|
||||
});
|
||||
|
||||
const naturalizationSchema = z.object({
|
||||
applicationType: z.literal("NATURALIZATION"),
|
||||
naturalizationReason: z.string().min(1, "Reason for naturalisation is required"),
|
||||
...baseFields,
|
||||
});
|
||||
|
||||
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 };
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { Block, PageMeta, PageStatus, PageType } from "./types";
|
||||
import { archivePage, createPage, deletePage, updatePage } from "./repository";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { deleteNavLinkByPageId } from "../navlinks/repository";
|
||||
import { validatePage } from "./validation";
|
||||
|
||||
export async function savePageAction(params: {
|
||||
id: string | null,
|
||||
@@ -15,6 +16,10 @@ export async function savePageAction(params: {
|
||||
blocks: Block[],
|
||||
meta?: PageMeta
|
||||
}) {
|
||||
const parsed = validatePage(params);
|
||||
if (!parsed.success) {
|
||||
throw new Error(parsed.errors.join("; "));
|
||||
}
|
||||
|
||||
if (params.id) {
|
||||
await updatePage(params.id, params.title, params.type, params.status, params.blocks, params.meta);
|
||||
|
||||
+11
-7
@@ -1,18 +1,19 @@
|
||||
import { getCurrentUser } from "../user";
|
||||
import { Block, PageMeta, PageStatus, PageType } from "./types";
|
||||
import type { Block, Page, PageMeta, PageStatus, PageType } from "./types";
|
||||
import { prisma } from "../prisma";
|
||||
|
||||
export async function getPages(type: PageType, status: PageStatus, limit?: number) {
|
||||
// return await prisma.page.findMany({ where: { type, status }, take: limit, orderBy: { publishedAt: "desc" }, });
|
||||
return []
|
||||
return await prisma.page.findMany({ where: { type, status }, take: limit, orderBy: { publishedAt: "desc" }, }) as Page[];
|
||||
}
|
||||
|
||||
export async function getPageById(id: string) {
|
||||
return await prisma.page.findUnique({ where: { id: id } });
|
||||
}
|
||||
|
||||
export async function getPageBySlug(slug: string) {
|
||||
return await prisma.page.findUnique({ where: { slug } });
|
||||
export async function getPageBySlug(slug: string, type?: PageType) {
|
||||
return await prisma.page.findFirst({
|
||||
where: { slug, ...(type ? { type } : {}) },
|
||||
}) as Page | null;
|
||||
}
|
||||
|
||||
export async function createPage(slug: string, title: string, type: PageType, status: PageStatus, blocks: Block[], meta?: PageMeta) {
|
||||
@@ -68,6 +69,9 @@ export async function updatePage(
|
||||
const user = await getCurrentUser();
|
||||
if (!user?.isAdmin) throw new Error("Access denied");
|
||||
|
||||
const currentPage = await prisma.page.findUnique({ where: { id }, select: { status: true } });
|
||||
const isNewlyPublished = status === "PUBLISHED" && currentPage?.status !== "PUBLISHED";
|
||||
|
||||
const page = await prisma.page.update({
|
||||
where: { id },
|
||||
data: {
|
||||
@@ -75,7 +79,7 @@ export async function updatePage(
|
||||
type,
|
||||
status,
|
||||
meta: meta ?? {},
|
||||
publishedAt: status === "PUBLISHED" ? new Date() : undefined,
|
||||
publishedAt: isNewlyPublished ? new Date() : undefined,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: user.id
|
||||
},
|
||||
@@ -115,5 +119,5 @@ export async function getBlocksByPageId(pageId: string) {
|
||||
return prisma.block.findMany({
|
||||
where: { pageId },
|
||||
orderBy: { position: "asc" },
|
||||
});
|
||||
}) as Promise<Block[]>;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { z } from "zod";
|
||||
|
||||
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()),
|
||||
meta: z.object({
|
||||
location: z.string().optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
export type PageFormData = z.infer<typeof pageSchema>;
|
||||
|
||||
export function validatePage(data: unknown): { success: true; data: PageFormData } | { success: false; errors: string[] } {
|
||||
const result = pageSchema.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
-1
@@ -1,5 +1,5 @@
|
||||
import { getSessionUserId } from "@/lib/auth/session";
|
||||
import { findUserById } from "@/lib/user/repository";
|
||||
import { findUserById, findUsersByIds } from "@/lib/user/repository";
|
||||
import { fetchKotosoftUser } from "./kotosoft/client";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
@@ -13,3 +13,9 @@ export async function getUser(id: string | null) {
|
||||
if (!id) return null;
|
||||
return findUserById(id);
|
||||
}
|
||||
|
||||
export async function getUsers(...ids: (string | null | undefined)[]) {
|
||||
const filtered = ids.filter((id): id is string => !!id);
|
||||
if (filtered.length === 0) return [];
|
||||
return findUsersByIds(filtered);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
"use server"
|
||||
|
||||
import { generatePkce, generateState } from "@/lib/auth/pkce";
|
||||
import { pkceConfig } from "@/lib/cookieConfig";
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { deleteSession } from "@/lib/auth/session";
|
||||
import { deleteUser, updateUser } from "./repository";
|
||||
import { getAccessToken } from "@/lib/auth/tokens";
|
||||
import { fetchKotosoftUser } from "@/lib/kotosoft/client";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
export async function login() {
|
||||
const { verifier, challenge } = generatePkce();
|
||||
const state = generateState();
|
||||
|
||||
const store = await cookies();
|
||||
store.set("pkce_verifier", verifier, pkceConfig);
|
||||
store.set("oauth_state", state, pkceConfig);
|
||||
|
||||
const params = new URLSearchParams({
|
||||
client_id: process.env.KOTOSOFT_ID_CLIENT_ID!,
|
||||
redirect_uri: `${process.env.PUBLIC_URL}/api/callback`,
|
||||
scope: "profile:read",
|
||||
response_type: "code",
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: "S256",
|
||||
state,
|
||||
});
|
||||
|
||||
redirect(`${process.env.KOTOSOFT_ID_API_URL}/oauth/authorize?${params}`);
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
await deleteSession();
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
export async function deleteUserAction(userId: string) {
|
||||
await deleteUser(userId);
|
||||
await deleteSession();
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
export async function updateUserAction() {
|
||||
const accessToken = await getAccessToken();
|
||||
if (!accessToken) throw new Error("Not authenticated");
|
||||
|
||||
const kotosoftUser = await fetchKotosoftUser(accessToken);
|
||||
|
||||
const { getSessionUserId } = await import("@/lib/auth/session");
|
||||
const userId = await getSessionUserId();
|
||||
if (!userId) throw new Error("Not authenticated");
|
||||
|
||||
await updateUser(userId, {
|
||||
email: kotosoftUser.email,
|
||||
firstName: kotosoftUser.first_name,
|
||||
secondName: kotosoftUser.second_name,
|
||||
sex: kotosoftUser.sex as "MALE" | "FEMALE",
|
||||
birthDate: kotosoftUser.birth_date,
|
||||
});
|
||||
|
||||
revalidatePath("/account")
|
||||
}
|
||||
+13
-2
@@ -10,6 +10,12 @@ export async function findUserById(id: string) {
|
||||
return prisma.user.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
export async function findUsersByIds(ids: string[]) {
|
||||
const filtered = ids.filter(Boolean);
|
||||
if (filtered.length === 0) return [];
|
||||
return prisma.user.findMany({ where: { id: { in: filtered } } });
|
||||
}
|
||||
|
||||
export async function findOrCreateUser(data: UserData) {
|
||||
const existing = await findUserByKotosoftId(data.kotosoftId);
|
||||
if (existing) return existing;
|
||||
@@ -17,8 +23,13 @@ export async function findOrCreateUser(data: UserData) {
|
||||
return prisma.user.create({
|
||||
data: {
|
||||
id: uuidv4(),
|
||||
...data,
|
||||
birthDate: new Date(data.birthDate),
|
||||
kotosoftId: data.kotosoftId,
|
||||
email: data.email,
|
||||
firstName: data.firstName,
|
||||
secondName: data.secondName,
|
||||
sex: data.sex,
|
||||
birthDate: data.birthDate ? new Date(data.birthDate) : null,
|
||||
isAdmin: data.isAdmin,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
+2
-2
@@ -3,7 +3,7 @@ export type UserData = {
|
||||
email: string;
|
||||
firstName: string;
|
||||
secondName: string;
|
||||
sex: string;
|
||||
birthDate: string;
|
||||
sex: "MALE" | "FEMALE";
|
||||
birthDate?: string;
|
||||
isAdmin: boolean;
|
||||
}
|
||||
+3
-1
@@ -21,9 +21,11 @@
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"shadcn": "^4.11.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"uuid": "^14.0.0"
|
||||
"uuid": "^14.0.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
|
||||
+5
-6
@@ -1,14 +1,13 @@
|
||||
// This file was generated by Prisma, and assumes you have installed the following:
|
||||
// npm install --save-dev prisma dotenv
|
||||
import "dotenv/config";
|
||||
import { defineConfig } from "prisma/config";
|
||||
import type { PrismaConfig } from "prisma";
|
||||
import { env } from "prisma/config";
|
||||
|
||||
export default defineConfig({
|
||||
export default {
|
||||
schema: "prisma/schema.prisma",
|
||||
migrations: {
|
||||
path: "prisma/migrations",
|
||||
},
|
||||
datasource: {
|
||||
url: process.env["DATABASE_URL"],
|
||||
url: env("DATABASE_URL"),
|
||||
},
|
||||
});
|
||||
} satisfies PrismaConfig;
|
||||
|
||||
+43
-1
@@ -24,12 +24,14 @@ model User {
|
||||
firstName String
|
||||
secondName String
|
||||
sex Sex
|
||||
birthDate DateTime
|
||||
birthDate DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
isAdmin Boolean @default(false)
|
||||
|
||||
pages Page[] @relation("PageAuthor")
|
||||
editedPages Page[] @relation("PageEditor")
|
||||
|
||||
citizenshipApplications CitizenshipApplication[]
|
||||
}
|
||||
|
||||
enum PageStatus {
|
||||
@@ -89,3 +91,43 @@ model NavLink {
|
||||
page Page? @relation(fields: [pageId], references: [id], onDelete: SetNull)
|
||||
href String?
|
||||
}
|
||||
|
||||
enum CitizenshipApplicationStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
applicationType ApplicationType
|
||||
|
||||
previousCountry String?
|
||||
previousRegion String?
|
||||
birthRegion String?
|
||||
naturalizationReason String?
|
||||
|
||||
address String
|
||||
height String
|
||||
eyeColor String
|
||||
|
||||
status CitizenshipApplicationStatus @default(PENDING)
|
||||
rejectionReason String?
|
||||
reviewedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
Reference in New Issue
Block a user