203 lines
7.2 KiB
TypeScript
203 lines
7.2 KiB
TypeScript
"use server";
|
|
|
|
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, getActiveCitizenship, getApplicationEligibility, searchActiveCitizenships } from "./repository";
|
|
import { prisma } from "../prisma";
|
|
import { formatAddress } from "@/lib/address";
|
|
import { Prisma } from "@/lib/generated/prisma/client";
|
|
import { removeImage, uploadImage } from "../image";
|
|
|
|
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()}`;
|
|
}
|
|
|
|
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 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;
|
|
}
|
|
}
|
|
throw new Error("Failed to generate a unique document number");
|
|
}
|
|
|
|
export const submitCitizenshipApplication = formAction(citizenshipApplicationSchema,
|
|
async (data) => {
|
|
const user = await requireUser();
|
|
|
|
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: _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,
|
|
});
|
|
|
|
let profileKey: string | undefined;
|
|
let signatureKey: string | undefined;
|
|
|
|
try {
|
|
profileKey = await uploadImage(profile, "citizenship/profiles", {
|
|
maxWidth: 800, maxHeight: 1000, fit: "cover",
|
|
});
|
|
|
|
signatureKey = await uploadImage(signature, "citizenship/signatures", {
|
|
maxWidth: 1000, maxHeight: 400, fit: "inside",
|
|
});
|
|
|
|
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
|
|
});
|
|
} catch (e) {
|
|
if (profileKey) await removeImage(profileKey);
|
|
if (signatureKey) await removeImage(signatureKey);
|
|
throw e;
|
|
}
|
|
|
|
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.findFirst({
|
|
where: { userId: application.userId, revokedAt: null },
|
|
});
|
|
if (existingCitizenship) {
|
|
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");
|
|
});
|
|
}
|
|
|
|
export async function rejectApplication(id: string, reason: 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 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 },
|
|
});
|
|
|
|
await Promise.allSettled([
|
|
removeImage(application.profileKey),
|
|
removeImage(application.signatureKey),
|
|
]);
|
|
|
|
revalidatePath("/account/citizenship/review");
|
|
});
|
|
}
|
|
|
|
export async function searchCitizensAction(query: string): Promise<ActionResult<{ id: string; firstName: string; secondName: string }[]>> {
|
|
return runAction(async () => {
|
|
// Gate behind admin for now, same as act creation - refine once
|
|
// position-based authority exists.
|
|
await requireAdmin();
|
|
|
|
const results = await searchActiveCitizenships(query);
|
|
return results.map((c) => ({ id: c.id, firstName: c.user.firstName, secondName: c.user.secondName }));
|
|
});
|
|
}
|
|
|
|
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");
|
|
});
|
|
} |