temp
This commit is contained in:
@@ -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();
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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" } });
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -7,7 +7,7 @@ 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 } from "./repository";
|
||||
import { createApplication, getActiveCitizenship, getApplicationEligibility, searchActiveCitizenships } from "./repository";
|
||||
import { prisma } from "../prisma";
|
||||
import { formatAddress } from "@/lib/address";
|
||||
import { Prisma } from "@/lib/generated/prisma/client";
|
||||
@@ -179,6 +179,17 @@ export async function rejectApplication(id: string, reason: string): Promise<Act
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -102,4 +102,28 @@ export async function getActiveCitizenship(userId: string) {
|
||||
return prisma.citizenship.findFirst({
|
||||
where: { userId, revokedAt: null },
|
||||
});
|
||||
}
|
||||
|
||||
// Used by the acts appointment picker - only active citizens are eligible
|
||||
// to hold a position.
|
||||
export async function searchActiveCitizenships(query: string) {
|
||||
const q = query.trim();
|
||||
if (!q) return [];
|
||||
|
||||
return prisma.citizenship.findMany({
|
||||
where: {
|
||||
revokedAt: null,
|
||||
user: {
|
||||
OR: [
|
||||
{ firstName: { contains: q, mode: "insensitive" } },
|
||||
{ secondName: { contains: q, mode: "insensitive" } },
|
||||
],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
user: { select: { firstName: true, secondName: true } },
|
||||
},
|
||||
take: 10,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { AppError } from "../action-result";
|
||||
import { prisma } from "../prisma";
|
||||
import { requireAdmin } from "../user/require";
|
||||
import { formAction } from "../form-action";
|
||||
import z from "zod";
|
||||
|
||||
const createPositionSchema = z.object({
|
||||
name: z.string().min(1, "Name of a position cannot be empty"),
|
||||
institutionId: z.string().min(1, "Incorrect institution is provided"),
|
||||
});
|
||||
|
||||
// Defines an office (e.g. "Mayor of X") within an institution. This does NOT
|
||||
// assign anyone to it - filling/vacating a position happens through an
|
||||
// appointment act, see lib/acts.
|
||||
export const createPosition = formAction(createPositionSchema, async (data) => {
|
||||
await requireAdmin();
|
||||
|
||||
const institution = await prisma.institution.findUnique({ where: { id: data.institutionId } });
|
||||
if (!institution) {
|
||||
throw new AppError("Incorrect institution is provided");
|
||||
}
|
||||
|
||||
await prisma.position.create({ data: { name: data.name, institutionId: data.institutionId } });
|
||||
revalidatePath("/account/positions");
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { prisma } from "../prisma";
|
||||
import { Position } from "./types";
|
||||
|
||||
const positionSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
institutionId: true,
|
||||
institution: { select: { id: true, name: true, kind: true } },
|
||||
capabilities: { select: { capability: true } },
|
||||
} as const;
|
||||
|
||||
export async function getPositions() {
|
||||
return prisma.position.findMany({ select: positionSelect, orderBy: { name: "asc" } });
|
||||
}
|
||||
|
||||
export async function getPositionById(id: string) {
|
||||
return prisma.position.findUnique({ where: { id }, select: positionSelect });
|
||||
}
|
||||
|
||||
export async function createPosition(position: Omit<Position, "id">) {
|
||||
return prisma.position.create({ data: position });
|
||||
}
|
||||
|
||||
// Current (non-resigned) holder of a position, if any.
|
||||
export async function getCurrentHolder(positionId: string) {
|
||||
return prisma.citizenshipPosition.findFirst({
|
||||
where: { positionId, resignedAt: null },
|
||||
include: { citizenship: { include: { user: { select: { firstName: true, secondName: true } } } } },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getCitizenshipPositions(citizenshipId: string) {
|
||||
return prisma.citizenshipPosition.findMany({
|
||||
where: { citizenshipId },
|
||||
include: { position: { select: positionSelect } },
|
||||
orderBy: { assignedAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getUserPositions(userId: string) {
|
||||
return prisma.citizenshipPosition.findMany({
|
||||
where: { citizenship: { userId }, resignedAt: null },
|
||||
include: { position: { select: positionSelect }, act: { select: { title: true, numberInSeries: true, numberYear: true, actType: { select: { name: true } } } } },
|
||||
orderBy: { assignedAt: "desc" },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
export type Position = {
|
||||
id: string;
|
||||
name: string;
|
||||
institutionId: string;
|
||||
}
|
||||
|
||||
export type CitizenshipPosition = {
|
||||
id: string;
|
||||
citizenshipId: string;
|
||||
positionId: string;
|
||||
assignedAt: Date;
|
||||
resignedAt: Date | null;
|
||||
actId: string | null;
|
||||
}
|
||||
+5
-2
@@ -5,6 +5,9 @@ import { PrismaClient } from "@/lib/generated/prisma/client";
|
||||
const connectionString = `${process.env.DATABASE_URL}`;
|
||||
|
||||
const adapter = new PrismaPg({ connectionString });
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
|
||||
export { prisma };
|
||||
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter });
|
||||
|
||||
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
||||
Reference in New Issue
Block a user