feat: citizenship built
This commit is contained in:
@@ -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 };
|
||||
}
|
||||
])
|
||||
Reference in New Issue
Block a user