feat: images upload
This commit is contained in:
+147
-110
@@ -1,16 +1,17 @@
|
||||
"use server";
|
||||
|
||||
import { getCurrentUser } from "@/lib/user";
|
||||
import { redirect } from "next/navigation";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { requireUser, requireAdmin } from "@/lib/user/require";
|
||||
import { runAction, isPrismaError } from "@/lib/run-action";
|
||||
import { AppError, type ActionResult } from "@/lib/action-result";
|
||||
import { formAction } from "@/lib/form-action";
|
||||
import { citizenshipApplicationSchema } from "./validation";
|
||||
import { createApplication } from "./repository";
|
||||
import { createApplication, getActiveCitizenship, getApplicationEligibility } from "./repository";
|
||||
import { prisma } from "../prisma";
|
||||
|
||||
export type ApplicationState = {
|
||||
success: boolean;
|
||||
errors: string[];
|
||||
};
|
||||
import { formatAddress } from "@/lib/address";
|
||||
import { Prisma } from "@/lib/generated/prisma/client";
|
||||
import { uploadImage } from "../image";
|
||||
|
||||
function generateDocumentNumber(): string {
|
||||
const letter = () => String.fromCharCode(65 + Math.floor(Math.random() * 26));
|
||||
@@ -18,117 +19,153 @@ function generateDocumentNumber(): string {
|
||||
return `${letter()}${digits}${letter()}`;
|
||||
}
|
||||
|
||||
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 isEuResident = formData.get("isEuResident") as string;
|
||||
|
||||
const raw: Record<string, string> = {
|
||||
applicationType,
|
||||
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 === "NATURALIZATION") {
|
||||
raw.naturalizationReason = (formData.get("naturalizationReason") as string) ?? "";
|
||||
async function createIdentityDocument(
|
||||
tx: Prisma.TransactionClient,
|
||||
data: {
|
||||
citizenshipId: string;
|
||||
address: string;
|
||||
regionId: string | null;
|
||||
city: string | null;
|
||||
street: string | null;
|
||||
customAddress: string | null;
|
||||
issuedAt: Date;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
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 };
|
||||
) {
|
||||
const maxAttempts = 5;
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
try {
|
||||
return await tx.identityDocument.create({ data: { ...data, documentNumber: generateDocumentNumber() } });
|
||||
} catch (error) {
|
||||
if (!isPrismaError(error, "P2002") || attempt === maxAttempts - 1) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
...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: [] };
|
||||
throw new Error("Failed to generate a unique document number");
|
||||
}
|
||||
|
||||
export async function approveApplication(id: string) {
|
||||
const user = await getCurrentUser();
|
||||
if (!user) redirect("/");
|
||||
export const submitCitizenshipApplication = formAction(citizenshipApplicationSchema,
|
||||
async (data) => {
|
||||
const user = await requireUser();
|
||||
|
||||
const application = await prisma.citizenshipApplication.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: "APPROVED",
|
||||
reviewedAt: new Date(),
|
||||
reviewedBy: user.id,
|
||||
},
|
||||
const eligibility = await getApplicationEligibility(user.id, user.birthDate);
|
||||
if (!eligibility.eligible) throw new AppError(eligibility.reason!);
|
||||
|
||||
const isEuResidentYes = data.isEuResident === "yes";
|
||||
const { profile, signature, isEuResident, ...applicationData } = data;
|
||||
let regionName: string | null = null;
|
||||
|
||||
if (isEuResidentYes) {
|
||||
const region = await prisma.region.findUnique({ where: { id: data.regionId } });
|
||||
if (!region) {
|
||||
throw new AppError("Selected region is invalid.", { regionId: ["Selected region is invalid."] });
|
||||
}
|
||||
regionName = region.name;
|
||||
}
|
||||
|
||||
const address = formatAddress({
|
||||
isEuResident: isEuResidentYes,
|
||||
street: data.street,
|
||||
city: data.city,
|
||||
regionName,
|
||||
customAddress: data.customAddress,
|
||||
});
|
||||
|
||||
const profileKey = await uploadImage(profile, "citizenship/profiles");
|
||||
const signatureKey = await uploadImage(signature, "citizenship/signatures");
|
||||
|
||||
await createApplication(user.id, {
|
||||
surname: user.secondName,
|
||||
givenNames: user.firstName,
|
||||
sex: user.sex,
|
||||
birthDate: user.birthDate!,
|
||||
...applicationData,
|
||||
address,
|
||||
regionId: isEuResidentYes ? data.regionId! : null,
|
||||
city: isEuResidentYes ? data.city! : null,
|
||||
street: isEuResidentYes ? data.street! : null,
|
||||
customAddress: isEuResidentYes ? null : data.customAddress!,
|
||||
profileKey,
|
||||
signatureKey
|
||||
});
|
||||
|
||||
revalidatePath("/account/citizenship");
|
||||
redirect("/account/citizenship");
|
||||
}
|
||||
);
|
||||
|
||||
export async function approveApplication(id: string): Promise<ActionResult> {
|
||||
return runAction(async () => {
|
||||
const user = await requireAdmin();
|
||||
|
||||
const application = await prisma.citizenshipApplication.findUnique({ where: { id } });
|
||||
if (!application) throw new AppError("Application not found.");
|
||||
if (application.status !== "PENDING") throw new AppError("This application is no longer pending review.");
|
||||
if (application.userId === user.id) throw new AppError("You cannot approve your own application.");
|
||||
|
||||
const existingCitizenship = await prisma.citizenship.findUnique({ where: { userId: application.userId } });
|
||||
if (existingCitizenship && !existingCitizenship.revokedAt) {
|
||||
throw new AppError("This applicant is already a citizen.");
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now);
|
||||
expiresAt.setFullYear(expiresAt.getFullYear() + 10);
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.citizenshipApplication.update({
|
||||
where: { id, status: "PENDING" },
|
||||
data: { status: "APPROVED", reviewedAt: now, reviewedBy: user.id },
|
||||
});
|
||||
|
||||
const citizenship = await tx.citizenship.create({
|
||||
data: { userId: application.userId, applicationId: application.id },
|
||||
});
|
||||
|
||||
await createIdentityDocument(tx, {
|
||||
citizenshipId: citizenship.id,
|
||||
address: application.address,
|
||||
regionId: application.regionId,
|
||||
city: application.city,
|
||||
street: application.street,
|
||||
customAddress: application.customAddress,
|
||||
issuedAt: now,
|
||||
expiresAt,
|
||||
});
|
||||
});
|
||||
|
||||
revalidatePath("/account/citizenship/review");
|
||||
});
|
||||
|
||||
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("/");
|
||||
export async function rejectApplication(id: string, reason: string): Promise<ActionResult> {
|
||||
return runAction(async () => {
|
||||
const user = await requireAdmin();
|
||||
|
||||
await prisma.citizenshipApplication.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: "REJECTED",
|
||||
rejectionReason: reason,
|
||||
reviewedAt: new Date(),
|
||||
reviewedBy: user.id,
|
||||
},
|
||||
const application = await prisma.citizenshipApplication.findUnique({ where: { id } });
|
||||
if (!application) throw new AppError("Application not found.");
|
||||
if (application.status !== "PENDING") throw new AppError("This application is no longer pending review.");
|
||||
if (application.userId === user.id) throw new AppError("You cannot reject your own application.");
|
||||
|
||||
const trimmedReason = reason.trim();
|
||||
if (!trimmedReason) throw new AppError("A rejection reason is required.");
|
||||
|
||||
await prisma.citizenshipApplication.update({
|
||||
where: { id, status: "PENDING" },
|
||||
data: { status: "REJECTED", rejectionReason: trimmedReason, reviewedAt: new Date(), reviewedBy: user.id },
|
||||
});
|
||||
|
||||
revalidatePath("/account/citizenship/review");
|
||||
});
|
||||
}
|
||||
|
||||
revalidatePath("/account/citizenship/review");
|
||||
export async function renounceCitizenship(): Promise<ActionResult> {
|
||||
return runAction(async () => {
|
||||
const user = await requireUser();
|
||||
|
||||
const citizenship = await getActiveCitizenship(user.id);
|
||||
if (!citizenship) throw new AppError("Citizenship not found.");
|
||||
|
||||
await prisma.citizenship.update({ where: { id: citizenship.id }, data: { revokedAt: new Date() } });
|
||||
revalidatePath("/account/citizenship");
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import type { ApplicationType } from "./types";
|
||||
import type { ApplicationType, EyeColor } from "./types";
|
||||
|
||||
type CreateData = {
|
||||
surname: string;
|
||||
@@ -9,17 +9,58 @@ type CreateData = {
|
||||
applicationType: ApplicationType;
|
||||
previousCountry?: string | null;
|
||||
previousRegion?: string | null;
|
||||
birthRegion?: string | null;
|
||||
naturalizationReason?: string | null;
|
||||
address: string;
|
||||
regionId?: string | null;
|
||||
city?: string | null;
|
||||
street?: string | null;
|
||||
customAddress?: string | null;
|
||||
height: string;
|
||||
eyeColor: string;
|
||||
height: number;
|
||||
eyeColor: EyeColor;
|
||||
profileKey: string;
|
||||
signatureKey: string;
|
||||
};
|
||||
|
||||
export type ApplicationEligibility = {
|
||||
eligible: boolean;
|
||||
reason: string | null;
|
||||
};
|
||||
|
||||
export async function getApplicationEligibility(
|
||||
userId: string,
|
||||
birthDate: Date | null | undefined
|
||||
): Promise<ApplicationEligibility> {
|
||||
if (!birthDate) {
|
||||
return {
|
||||
eligible: false,
|
||||
reason:
|
||||
"Date of birth is required. Update your profile in Kotosoft ID and synchronise your account.",
|
||||
};
|
||||
}
|
||||
|
||||
const citizenship = await prisma.citizenship.findUnique({ where: { userId } });
|
||||
if (citizenship && !citizenship.revokedAt) {
|
||||
return {
|
||||
eligible: false,
|
||||
reason: "You are already a citizen of the European Federation.",
|
||||
};
|
||||
}
|
||||
|
||||
const applications = await prisma.citizenshipApplication.findMany({
|
||||
where: { userId },
|
||||
select: { status: true },
|
||||
});
|
||||
|
||||
if (applications.some((application) => application.status === "PENDING")) {
|
||||
return {
|
||||
eligible: false,
|
||||
reason: "You already have a pending application.",
|
||||
};
|
||||
}
|
||||
|
||||
return { eligible: true, reason: null };
|
||||
}
|
||||
|
||||
export async function createApplication(userId: string, data: CreateData) {
|
||||
return prisma.citizenshipApplication.create({
|
||||
data: {
|
||||
@@ -40,10 +81,26 @@ export async function getPendingApplications() {
|
||||
return prisma.citizenshipApplication.findMany({
|
||||
where: { status: "PENDING" },
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: { user: true },
|
||||
})
|
||||
include: {
|
||||
user: {
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
citizenships: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPendingApplicationsCount(): Promise<number> {
|
||||
return prisma.citizenshipApplication.count({ where: { status: "PENDING" } })
|
||||
}
|
||||
return prisma.citizenshipApplication.count({ where: { status: "PENDING" } });
|
||||
}
|
||||
|
||||
export async function getActiveCitizenship(userId: string) {
|
||||
const citizenship = await prisma.citizenship.findUnique({ where: { userId } });
|
||||
if (!citizenship || citizenship.revokedAt) return null;
|
||||
return citizenship;
|
||||
}
|
||||
|
||||
@@ -26,16 +26,23 @@ export type CitizenshipApplication = {
|
||||
previousRegion: string | null;
|
||||
naturalizationReason: string | null;
|
||||
address: string;
|
||||
height: string;
|
||||
eyeColor: string;
|
||||
height: number;
|
||||
eyeColor: EyeColor;
|
||||
status: CitizenshipApplicationStatus;
|
||||
rejectionReason: string | null;
|
||||
reviewedAt: Date | null;
|
||||
reviewedBy: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
profileKey: string;
|
||||
signatureKey: string;
|
||||
profile: File;
|
||||
signature: File;
|
||||
};
|
||||
|
||||
export type CitizenshipApplicationWithWarning = CitizenshipApplication & {
|
||||
nameMismatch: boolean
|
||||
}
|
||||
nameMismatch: boolean;
|
||||
previousCitizenship: boolean;
|
||||
profileUrl: string;
|
||||
signatureUrl: string;
|
||||
};
|
||||
|
||||
@@ -1,39 +1,70 @@
|
||||
import { z } from "zod";
|
||||
import { EYE_COLORS } from "./types";
|
||||
|
||||
const MAX_FILE_SIZE = 5 * 1024 * 1024;
|
||||
const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/png", "image/webp"];
|
||||
|
||||
const imageFileSchema = z
|
||||
.instanceof(File, { error: "A file is required" })
|
||||
.refine((file) => file.size > 0, "A file is required")
|
||||
.refine((file) => file.size <= MAX_FILE_SIZE, "Image must be smaller than 5MB")
|
||||
.refine((file) => ACCEPTED_IMAGE_TYPES.includes(file.type), "Only JPEG, PNG, or WEBP images are allowed");
|
||||
|
||||
const baseFields = {
|
||||
height: z.string().regex(/^\d+$/, "Height must be a number").min(1, "Height is required"),
|
||||
eyeColor: z.string().min(1, "Eye colour is required"),
|
||||
height: z.coerce
|
||||
.number({ error: "Height is required" })
|
||||
.int("Height must be a whole number")
|
||||
.min(60, "Height must be at least 60 cm")
|
||||
.max(240, "Height must be at most 240 cm"),
|
||||
eyeColor: z.enum(EYE_COLORS, { error: "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(),
|
||||
}
|
||||
city: z.string().trim().optional(),
|
||||
street: z.string().trim().optional(),
|
||||
customAddress: z.string().trim().optional(),
|
||||
profile: imageFileSchema,
|
||||
signature: imageFileSchema,
|
||||
};
|
||||
|
||||
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,
|
||||
}).superRefine(validateAddress)
|
||||
const previousCitizenshipSchema = z
|
||||
.object({
|
||||
applicationType: z.literal("PREVIOUS_CITIZENSHIP"),
|
||||
previousCountry: z.enum(["DUS", "REA"], { error: "Invalid country of previous citizenship" }),
|
||||
previousRegion: z.string().trim().min(1, "Region of previous citizenship 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)
|
||||
const naturalizationSchema = z
|
||||
.object({
|
||||
applicationType: z.literal("NATURALIZATION"),
|
||||
naturalizationReason: z.string().trim().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) {
|
||||
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" })
|
||||
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" })
|
||||
if (!data.customAddress) {
|
||||
ctx.addIssue({ code: "custom", path: ["customAddress"], message: "Address is required" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const citizenshipApplicationSchema = z.discriminatedUnion("applicationType", [
|
||||
previousCitizenshipSchema,
|
||||
naturalizationSchema,
|
||||
])
|
||||
]);
|
||||
Reference in New Issue
Block a user