feat: citizenship applications
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
"use server";
|
||||
|
||||
import { getCurrentUser } from "@/lib/user";
|
||||
import { redirect } from "next/navigation";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { citizenshipApplicationSchema } from "./validation";
|
||||
import { createApplication } from "./repository";
|
||||
|
||||
export type ApplicationState = {
|
||||
success: boolean;
|
||||
errors: string[];
|
||||
};
|
||||
|
||||
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 raw: Record<string, string> = {
|
||||
applicationType,
|
||||
address: (formData.get("address") as string) ?? "",
|
||||
height: (formData.get("height") as string) ?? "",
|
||||
eyeColor: (formData.get("eyeColor") 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) ?? "";
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
await createApplication(user.id, {
|
||||
surname: user.secondName,
|
||||
givenNames: user.firstName,
|
||||
sex: user.sex,
|
||||
birthDate: user.birthDate ?? new Date(),
|
||||
...parsed.data,
|
||||
});
|
||||
|
||||
revalidatePath("/account/citizenship");
|
||||
return { success: true, errors: [] };
|
||||
}
|
||||
Reference in New Issue
Block a user