feat: citizenship built
This commit is contained in:
+1
-1
@@ -1,4 +1,4 @@
|
||||
import crypto from "crypto"
|
||||
import crypto from "crypto";
|
||||
|
||||
export function generatePkce() {
|
||||
const verifier = crypto.randomBytes(32).toString("base64url");
|
||||
|
||||
+2
-1
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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" } })
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
])
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
@@ -1,4 +1,4 @@
|
||||
"use server"
|
||||
"use server";
|
||||
|
||||
import { generatePkce, generateState } from "@/lib/auth/pkce";
|
||||
import { pkceConfig } from "@/lib/cookieConfig";
|
||||
|
||||
+2
-2
@@ -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))
|
||||
|
||||
Reference in New Issue
Block a user