"use server"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { validateAct } from "./validation"; import { requireAdmin, requireUser } from "../user/require"; import { runAction } from "../run-action"; import { AppError, type ActionResult } from "../action-result"; import { createAct, getActApprovals, getActById, getActs, getActTypeById, getCurrentActVersion, getInstitutionById, putActIntoForce, recordApproval, recordVeto, } from "./repository"; import { getPositionById, getCitizenshipPositions } from "../positions/repository"; import { getActiveCitizenship } from "../citizenship/repository"; import { ActEditorData, AppointmentClause } from "./types"; import { ActCapability, getActFlow, getNextPhase } from "./flows"; export async function saveActAction(params: ActEditorData): Promise { return runAction(async () => { await requireAdmin(); const parsed = validateAct(params); if (!parsed.success) { throw new AppError("Please ensure that at least 1 article here is in the act"); } const actType = await getActTypeById(parsed.data.actTypeId); if (!actType) throw new AppError("Selected act type does not exist"); const institution = await getInstitutionById(parsed.data.issuingInstitutionId); if (!institution) throw new AppError("Selected institution does not exist"); if (actType.allowedIssuerKind !== institution.kind) { throw new AppError("This act type is not allowed for the selected institution"); } if (actType.allowedIssuerInstitutionCode && institution.code !== actType.allowedIssuerInstitutionCode) { throw new AppError(`This act type can only be issued by ${actType.allowedIssuerInstitutionCode}`); } const appointmentClauses = parsed.data.articles .flatMap((a) => a.clauses) .filter((c): c is AppointmentClause => c.kind === "APPOINTMENT"); for (const clause of appointmentClauses) { const position = await getPositionById(clause.positionId); if (!position) throw new AppError("One of the selected positions does not exist"); const requiredIssuerId = position.institution.appointedByInstitutionId ?? position.institutionId; if (requiredIssuerId !== institution.id) { throw new AppError(`${institution.name} does not have the authority to appoint or dismiss ${position.name}`); } } const act = await createAct(parsed.data); revalidatePath("/acts"); redirect(`/acts/${act.id}`); }); } async function userHoldsCapability(userId: string, capability: ActCapability) { const citizenship = await getActiveCitizenship(userId); if (!citizenship) return { citizenship: null, position: null }; const positions = await getCitizenshipPositions(citizenship.id); const position = positions.find( (p) => !p.resignedAt && p.position.capabilities.some((c) => c.capability === capability) ); return { citizenship, position }; } async function loadDecidablePhase(actId: string) { const act = await getActById(actId); if (!act) throw new AppError("Act not found"); if (act.legalStatus !== "DRAFT") throw new AppError("This act has already been decided on"); const actType = await getActTypeById(act.actTypeId); if (!actType) throw new AppError("Act type not found"); const version = await getCurrentActVersion(actId); if (!version) throw new AppError("Act version not found"); const approvals = await getActApprovals(version.id); const flow = getActFlow(actType.code); const phase = getNextPhase(flow, approvals); if (!phase) throw new AppError("This act has completed its approval process"); return { act, version, phase }; } export async function approveActAction(actId: string): Promise { return runAction(async () => { const user = await requireUser(); const { version, phase } = await loadDecidablePhase(actId); const { citizenship, position } = await userHoldsCapability(user.id, phase.capability); if (!citizenship) throw new AppError("Only citizens can decide on acts"); if (!position) throw new AppError("You do not hold a position with the authority to approve this act at its current phase"); await recordApproval( actId, version.id, phase.key, citizenship.id, `${user.firstName} ${user.secondName}`, position.position.name, phase.isFinal ); revalidatePath(`/acts/${actId}`); }); } export async function vetoActAction(actId: string): Promise { return runAction(async () => { const user = await requireUser(); const { version, phase } = await loadDecidablePhase(actId); if (!phase.allowVeto) throw new AppError("This phase cannot veto the act"); const { citizenship, position } = await userHoldsCapability(user.id, phase.capability); if (!citizenship) throw new AppError("Only citizens can decide on acts"); if (!position) throw new AppError("You do not hold a position with the authority to veto this act"); await recordVeto(actId, version.id, phase.key, citizenship.id, `${user.firstName} ${user.secondName}`, position.position.name); revalidatePath(`/acts/${actId}`); }); } export async function putActIntoForceAction(actId: string): Promise { return runAction(async () => { await requireAdmin(); const act = await getActById(actId); if (!act) throw new AppError("Act not found"); await putActIntoForce(actId); revalidatePath(`/acts/${actId}`); }); } export async function getAllActs() { return await getActs(); }