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");
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user