This commit is contained in:
Ivan Rezchikov
2026-07-28 17:05:45 +03:00
parent e826e7b099
commit e234407a17
30 changed files with 1873 additions and 74 deletions
+136
View File
@@ -0,0 +1,136 @@
"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<ActionResult> {
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<ActionResult> {
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<ActionResult> {
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<ActionResult> {
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();
}
+48
View File
@@ -0,0 +1,48 @@
export type ActCapability =
| "SIGN_FEDERAL_LAW_SENATE"
| "SIGN_FEDERAL_LAW_HOUSE"
| "SIGN_AS_HEAD_OF_STATE"
| "SIGN_SENATE_APPOINTMENT"
| "SIGN_TREATY"
| "SIGN_RATIFICATION"
| "SIGN_REGIONAL_ACT";
export type FlowPhase = {
key: string;
label: string;
capability: ActCapability;
isFinal: boolean;
allowVeto?: boolean;
vetoLabel?: string;
};
export type ActFlow = FlowPhase[];
const singleSignature = (capability: ActCapability, label: string): ActFlow => [
{ key: "ADOPTION", label, capability, isFinal: true, allowVeto: true, vetoLabel: "Reject" },
];
const FEDERAL_LAW_FLOW: ActFlow = [
{ key: "SENATE_ADOPTION", label: "Awaiting the Senate", capability: "SIGN_FEDERAL_LAW_SENATE", isFinal: false, allowVeto: true, vetoLabel: "Reject" },
{ key: "HOUSE_ADOPTION", label: "Awaiting the House of Representatives", capability: "SIGN_FEDERAL_LAW_HOUSE", isFinal: false, allowVeto: true, vetoLabel: "Reject" },
{ key: "PRESIDENT_DECISION", label: "Under review by the President", capability: "SIGN_AS_HEAD_OF_STATE", isFinal: true, allowVeto: true, vetoLabel: "Veto" },
];
const FLOWS_BY_ACT_TYPE_CODE: Record<string, ActFlow> = {
FEDERAL_LAW: FEDERAL_LAW_FLOW,
SENATE_APPOINTMENT: singleSignature("SIGN_SENATE_APPOINTMENT", "Awaiting the Senate"),
TREATY: singleSignature("SIGN_TREATY", "Awaiting the President's signature"),
RATIFICATION_ACT: singleSignature("SIGN_RATIFICATION", "Awaiting the Senate"),
REGIONAL_ACT: singleSignature("SIGN_REGIONAL_ACT", "Awaiting the regional government"),
};
export function getActFlow(actTypeCode: string): ActFlow {
const flow = FLOWS_BY_ACT_TYPE_CODE[actTypeCode];
if (!flow) throw new Error(`No flow configured for act type "${actTypeCode}"`);
return flow;
}
export function getNextPhase(flow: ActFlow, approvals: { phaseKey: string }[]): FlowPhase | undefined {
const done = new Set(approvals.map((a) => a.phaseKey));
return flow.find((p) => !done.has(p.key));
}
+187
View File
@@ -0,0 +1,187 @@
import { prisma } from "../prisma";
import { getCurrentUser } from "../user";
import { ActFormData } from "./validation";
import { ActBlockRecord, ArticleContent, AppointmentClause } from "./types";
import { Prisma } from "@/lib/generated/prisma/client";
const actTypeSelect = {
id: true, name: true, code: true, allowedIssuerKind: true, allowedIssuerInstitutionCode: true,
} as const;
const institutionSelect = { id: true, name: true, kind: true, code: true, appointedByInstitutionId: true } as const;
const regionSelect = { id: true, name: true } as const;
export async function getActTypes() {
return prisma.actType.findMany({ select: actTypeSelect });
}
export async function getInstitutions() {
return prisma.institution.findMany({ where: { isActive: true }, select: institutionSelect });
}
export async function getRegions() {
return prisma.region.findMany({ select: regionSelect });
}
export async function getActTypeById(id: string) {
return prisma.actType.findUnique({ where: { id }, select: actTypeSelect });
}
export async function getInstitutionById(id: string) {
return prisma.institution.findUnique({ where: { id }, select: institutionSelect });
}
export async function createAct(data: ActFormData) {
const user = await getCurrentUser();
if (!user) throw new Error("Failed to fetch user");
return prisma.$transaction(async (tx) => {
const act = await tx.act.create({
data: {
actTypeId: data.actTypeId,
issuingInstitutionId: data.issuingInstitutionId,
regionId: data.regionId || null,
authorId: user.id,
title: data.title,
legalStatus: "DRAFT",
},
});
const version = await tx.actVersion.create({
data: { actId: act.id, isCurrent: true, createdBy: user.id },
});
let position = 0;
const blocks: { versionId: string; stableKey: string; type: string; position: number; content: object }[] = [];
if (data.preambleText?.trim()) {
blocks.push({
versionId: version.id,
stableKey: "preamble",
type: "PREAMBLE",
position: position++,
content: { text: data.preambleText },
});
}
for (const article of data.articles) {
blocks.push({
versionId: version.id,
stableKey: article.id,
type: "ARTICLE",
position: position++,
content: {
title: article.title ?? null,
intro: article.intro ?? null,
markerStyle: article.markerStyle,
clauses: article.clauses,
},
});
}
await tx.actBlock.createMany({ data: blocks });
return act;
});
}
export async function getActs() {
return prisma.act.findMany({
select: {
id: true,
title: true,
numberInSeries: true,
numberYear: true,
createdAt: true,
legalStatus: true,
actType: { select: actTypeSelect },
issuingInstitution: { select: institutionSelect },
},
orderBy: { createdAt: "desc" },
});
}
export async function getActById(id: string) {
return prisma.act.findUnique({ where: { id } });
}
export async function getActVersions(actId: string) {
return prisma.actVersion.findMany({ where: { actId }, orderBy: { createdAt: "desc" } });
}
export async function getCurrentActVersion(actId: string) {
return prisma.actVersion.findFirst({ where: { actId, isCurrent: true } });
}
export async function getActApprovals(actVersionId: string) {
return prisma.actApproval.findMany({
where: { actVersionId },
select: { id: true, phaseKey: true, decision: true, citizenshipId: true, name: true, role: true, decidedAt: true },
orderBy: { decidedAt: "asc" },
});
}
export async function recordApproval(
actId: string, actVersionId: string, phaseKey: string,
citizenshipId: string, name: string, role: string, isFinal: boolean
) {
return prisma.$transaction(async (tx) => {
await tx.actApproval.create({ data: { actVersionId, phaseKey, decision: "APPROVE", citizenshipId, name, role } });
const act = await tx.act.findUniqueOrThrow({ where: { id: actId } });
if (!isFinal) return act;
const acts = await prisma.act.findMany({ where: { issuingInstitutionId: act.issuingInstitutionId, legalStatus: "IN_FORCE", numberYear: new Date().getFullYear() }, orderBy: { updatedAt: "desc" } });
await applyAppointmentEffects(tx, actId, actVersionId);
return tx.act.update({ where: { id: actId }, data: { legalStatus: "IN_FORCE", numberInSeries: acts[0]?.numberInSeries || 0 + 1, numberYear: new Date().getFullYear() } });
});
}
export async function recordVeto(
actId: string, actVersionId: string, phaseKey: string,
citizenshipId: string, name: string, role: string
) {
return prisma.$transaction(async (tx) => {
await tx.actApproval.create({ data: { actVersionId, phaseKey, decision: "VETO", citizenshipId, name, role } });
return tx.act.update({ where: { id: actId }, data: { legalStatus: "NOT_ADOPTED" } });
});
}
export async function getActBlocks(versionId: string): Promise<ActBlockRecord[]> {
return prisma.actBlock.findMany({
where: { versionId },
orderBy: { position: "asc" },
}) as Promise<ActBlockRecord[]>;
}
async function applyAppointmentEffects(tx: Prisma.TransactionClient, actId: string, versionId: string) {
const articleBlocks = await tx.actBlock.findMany({ where: { versionId, type: "ARTICLE" } });
const appointmentClauses = articleBlocks.flatMap((block) => {
const content = block.content as unknown as ArticleContent;
return content.clauses.filter((c): c is AppointmentClause => c.kind === "APPOINTMENT");
});
for (const clause of appointmentClauses) {
if (clause.action === "ASSIGN") {
await tx.citizenshipPosition.updateMany({
where: { positionId: clause.positionId, resignedAt: null },
data: { resignedAt: new Date() },
});
await tx.citizenshipPosition.create({
data: { citizenshipId: clause.citizenshipId, positionId: clause.positionId, actId },
});
} else {
await tx.citizenshipPosition.updateMany({
where: { positionId: clause.positionId, citizenshipId: clause.citizenshipId, resignedAt: null },
data: { resignedAt: new Date() },
});
}
}
}
export async function putActIntoForce(actId: string) {
return prisma.$transaction(async (tx) => {
const version = await tx.actVersion.findFirstOrThrow({ where: { actId, isCurrent: true } });
await applyAppointmentEffects(tx, actId, version.id);
return tx.act.update({ where: { id: actId }, data: { legalStatus: "IN_FORCE" } });
});
}
+83
View File
@@ -0,0 +1,83 @@
export const CLAUSE_MARKER_STYLES = ["NONE", "LETTERS", "NUMBERS"] as const;
export type ClauseMarkerStyle = typeof CLAUSE_MARKER_STYLES[number];
export type ActLegalStatus = "DRAFT" | "IN_FORCE" | "AMENDED" | "REPEALED" | "EXPIRED" | "NOT_ADOPTED";
export const LEGAL_STATUS_LABELS: Record<ActLegalStatus, string> = {
DRAFT: "Not yet in force",
IN_FORCE: "In force",
AMENDED: "Amended",
REPEALED: "Repealed",
EXPIRED: "Expired",
NOT_ADOPTED: "Not adopted",
};
export type TextClause = { id: string; kind: "TEXT"; text: string };
export type AppointmentClause = {
id: string;
kind: "APPOINTMENT";
action: "ASSIGN" | "DISMISS";
positionId: string;
citizenshipId: string;
citizenshipName: string;
};
export type Clause = TextClause | AppointmentClause;
export type ArticleContent = {
id: string;
title: string;
intro?: string;
markerStyle: ClauseMarkerStyle;
clauses: Clause[];
};
export type PreambleContent = { text: string };
export type ActBlockContent = ArticleContent | PreambleContent;
export type ActBlockType = "PREAMBLE" | "ARTICLE";
export type ActBlockRecord = {
id: string;
versionId: string;
stableKey: string;
type: ActBlockType;
position: number;
content: ActBlockContent;
};
export type ActEditorData = {
actTypeId: string;
issuingInstitutionId: string;
regionId: string | null;
title?: string;
preambleText?: string;
articles: ArticleContent[];
};
export type ActType = { id: string; name: string; code: string; allowedIssuerKind: string };
export type Institution = { id: string; name: string; kind: string; appointedByInstitutionId: string | null };
export type Region = { id: string; name: string };
export type PositionOption = { id: string; name: string; institutionId: string };
export type ActSignature = {
id: string;
citizenshipId: string;
name: string;
role: string;
signedAt: Date;
};
export type ApprovalDecision = "APPROVE" | "VETO";
export type ActApprovalRecord = {
id: string;
phaseKey: string;
decision: ApprovalDecision;
citizenshipId: string;
name: string;
role: string;
decidedAt: Date;
};
+48
View File
@@ -0,0 +1,48 @@
import { z } from "zod";
import { CLAUSE_MARKER_STYLES } from "./types";
const textClauseSchema = z.object({
id: z.string(),
kind: z.literal("TEXT"),
text: z.string().min(1),
});
const appointmentClauseSchema = z.object({
id: z.string(),
kind: z.literal("APPOINTMENT"),
action: z.enum(["ASSIGN", "DISMISS"]),
positionId: z.string().min(1, "A position is required"),
citizenshipId: z.string().min(1, "A citizen must be selected"),
citizenshipName: z.string().min(1),
});
const clauseSchema = z.discriminatedUnion("kind", [textClauseSchema, appointmentClauseSchema]);
const articleSchema = z.object({
id: z.string(),
title: z.string().optional(),
intro: z.string().optional(),
markerStyle: z.enum(CLAUSE_MARKER_STYLES),
clauses: z.array(clauseSchema).min(1),
});
export const actSchema = z.object({
actTypeId: z.string().min(1, "Act type is required"),
issuingInstitutionId: z.string().min(1, "Issuing institution is required"),
regionId: z.string().nullable(),
title: z.string().min(1, "Act must have a title"),
preambleText: z.string().optional(),
articles: z.array(articleSchema).min(1, "At least one article is required"),
});
export type ActFormData = z.infer<typeof actSchema>;
export function validateAct(data: unknown): { success: true; data: ActFormData } | { success: false; errors: string[] } {
const result = actSchema.safeParse(data);
if (!result.success) {
const fieldErrors = result.error.flatten().fieldErrors ?? {};
const messages = Object.values(fieldErrors).flat().filter(Boolean);
return { success: false, errors: messages };
}
return { success: true, data: result.data };
}