- Promotion nominations: members can nominate a peer for promotion from their profile, and a new /personnel/promotions page lets staff review and action the nominations (with an optional note on each). - Leadership transfers: a member's leadership can be handed over to another member, surfaced on the transfers page and in the roster (which also gains a staff remove-member dialog). - Adds the PromotionNominations and LeadershipTransfers collections (registered in the Payload config), their service libs, the migration, and integration coverage.
336 lines
10 KiB
TypeScript
336 lines
10 KiB
TypeScript
"use server";
|
|
|
|
import config from "@payload-config";
|
|
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
|
import { getPayload } from "payload";
|
|
import type { User } from "@/payload-types";
|
|
import { emitGameEvent } from "@/utils/event-log/emit";
|
|
import { EventTypes } from "@/utils/event-log/eventTypes";
|
|
import { isPerformanceLevelId } from "@/lib/evaluations/levels";
|
|
import {
|
|
evaluateEligibility,
|
|
getLatestSubordinateLevel,
|
|
getLeaderAggregate,
|
|
upsertEvaluation,
|
|
} from "@/lib/evaluations";
|
|
import { hasPermission } from "@/utils/access-control/hasPermission";
|
|
import { lexicalPlaintextLength } from "@/lib/lexical/text";
|
|
import type { LexicalStateValue } from "@/lib/lexical/text";
|
|
import {
|
|
INTEL_EXCERPT_MAX_LENGTH,
|
|
PERSONAL_EXCERPT_MAX_LENGTH,
|
|
} from "@/lib/profile/excerpt-limits";
|
|
import { promoteMember as promoteMemberService } from "@/lib/promotions";
|
|
import {
|
|
cancelNomination as cancelNominationCore,
|
|
submitNomination,
|
|
} from "@/lib/promotions/nominations";
|
|
|
|
interface ActionResult<T = undefined> {
|
|
success: boolean;
|
|
error?: string;
|
|
data?: T;
|
|
}
|
|
|
|
async function authenticate() {
|
|
const payloadConfig = await config;
|
|
const payload = await getPayload({ config: payloadConfig });
|
|
const { headers } = await import("next/headers");
|
|
const hdrs = await headers();
|
|
const { user } = await payload.auth({
|
|
headers: hdrs,
|
|
canSetHeaders: false,
|
|
});
|
|
|
|
if (!isPayloadUser(user)) {
|
|
throw new Error("Unauthorized");
|
|
}
|
|
|
|
return { payload, user };
|
|
}
|
|
|
|
async function findUserByUsername(
|
|
payload: Awaited<ReturnType<typeof getPayload>>,
|
|
username: string,
|
|
) {
|
|
const res = await payload.find({
|
|
collection: "users",
|
|
where: { username: { equals: username } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
return (res.docs[0] as { id: number; username: string } | undefined) ?? null;
|
|
}
|
|
|
|
/**
|
|
* Submit (or re-submit) a leadership evaluation for the given profile. The kind
|
|
* is derived server-side from the rater/ratee/mission relationship — it is never
|
|
* accepted from the client. Eligibility is the permission gate here; any logged-in
|
|
* user with a qualifying relationship may evaluate.
|
|
*/
|
|
export async function submitEvaluation(input: {
|
|
username: string;
|
|
missionId: number;
|
|
level: string;
|
|
comment?: string;
|
|
}): Promise<ActionResult<{ created: boolean }>> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
if (!isPerformanceLevelId(input.level)) {
|
|
return { success: false, error: "Unknown performance level." };
|
|
}
|
|
|
|
const ratee = await findUserByUsername(payload, input.username);
|
|
if (!ratee) {
|
|
return { success: false, error: "User not found." };
|
|
}
|
|
|
|
const eligibility = await evaluateEligibility(payload, {
|
|
raterId: user.id as number,
|
|
rateeId: ratee.id,
|
|
missionId: input.missionId,
|
|
});
|
|
if (!eligibility.eligible || !eligibility.kind) {
|
|
return { success: false, error: eligibility.reason ?? "Not eligible to evaluate." };
|
|
}
|
|
|
|
const { evaluation, created } = await upsertEvaluation(payload, {
|
|
raterId: user.id as number,
|
|
rateeId: ratee.id,
|
|
missionId: input.missionId,
|
|
kind: eligibility.kind,
|
|
level: input.level,
|
|
comment: input.comment,
|
|
});
|
|
|
|
// No actor on the event: the event log is readable by any logged-in user and
|
|
// must not leak who rated whom.
|
|
await emitGameEvent(payload, {
|
|
type: EventTypes.EvaluationSubmit,
|
|
message: "A leadership evaluation was submitted.",
|
|
targetCollection: "evaluations",
|
|
targetId: evaluation.id,
|
|
data: { kind: eligibility.kind },
|
|
});
|
|
|
|
return { success: true, data: { created } };
|
|
} catch (e) {
|
|
if (e instanceof Error && e.message === "Unauthorized") throw e;
|
|
return {
|
|
success: false,
|
|
error: e instanceof Error ? e.message : "Unknown error",
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Rater-free evaluation summary for a profile page. Any logged-in user may call
|
|
* this; the output contains no rater identity or comments — only the anonymous
|
|
* leader aggregate (with its visibility threshold) and the latest subordinate
|
|
* level.
|
|
*/
|
|
export async function getEvaluationSummary(
|
|
username: string,
|
|
): Promise<
|
|
| {
|
|
success: true;
|
|
data: {
|
|
leader: Awaited<ReturnType<typeof getLeaderAggregate>>;
|
|
subordinate: Awaited<ReturnType<typeof getLatestSubordinateLevel>>;
|
|
};
|
|
}
|
|
| { success: false; error: string }
|
|
> {
|
|
try {
|
|
const { payload } = await authenticate();
|
|
|
|
const ratee = await findUserByUsername(payload, username);
|
|
if (!ratee) {
|
|
return { success: false, error: "User not found." };
|
|
}
|
|
|
|
const [leader, subordinate] = await Promise.all([
|
|
getLeaderAggregate(payload, ratee.id),
|
|
getLatestSubordinateLevel(payload, ratee.id),
|
|
]);
|
|
|
|
return { success: true, data: { leader, subordinate } };
|
|
} catch (e) {
|
|
if (e instanceof Error && e.message === "Unauthorized") throw e;
|
|
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
|
}
|
|
}
|
|
|
|
async function findProfileOwner(
|
|
payload: Awaited<ReturnType<typeof getPayload>>,
|
|
profileId: number,
|
|
): Promise<{ ownerId: number } | null> {
|
|
const profile = await payload.findByID({
|
|
collection: "profiles",
|
|
id: profileId,
|
|
depth: 0,
|
|
select: { user: true },
|
|
overrideAccess: true,
|
|
});
|
|
|
|
if (!profile) return null;
|
|
|
|
const ownerId = typeof profile.user === "object" ? profile.user?.id : profile.user;
|
|
if (typeof ownerId !== "number") return null;
|
|
|
|
return { ownerId };
|
|
}
|
|
|
|
export async function updatePersonalExcerpt(input: {
|
|
profileId: number;
|
|
content: LexicalStateValue | null;
|
|
}): Promise<ActionResult> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
const profile = await findProfileOwner(payload, input.profileId);
|
|
if (!profile) {
|
|
return { success: false, error: "Profile not found." };
|
|
}
|
|
|
|
if (profile.ownerId !== user.id) {
|
|
return { success: false, error: "You can only edit your own personal excerpt." };
|
|
}
|
|
|
|
const blank = !input.content || lexicalPlaintextLength(input.content) === 0;
|
|
if (!blank && lexicalPlaintextLength(input.content) > PERSONAL_EXCERPT_MAX_LENGTH) {
|
|
return {
|
|
success: false,
|
|
error: `Personal excerpt must be ${PERSONAL_EXCERPT_MAX_LENGTH} characters or fewer.`,
|
|
};
|
|
}
|
|
|
|
await payload.update({
|
|
collection: "profiles",
|
|
id: input.profileId,
|
|
data: { dossier: { personalExcerpt: blank ? null : input.content } },
|
|
overrideAccess: true,
|
|
});
|
|
|
|
await emitGameEvent(payload, {
|
|
type: EventTypes.DossierPersonalExcerptUpdate,
|
|
message: "A personal excerpt was updated.",
|
|
targetCollection: "users",
|
|
targetId: profile.ownerId,
|
|
data: { profileId: input.profileId },
|
|
});
|
|
|
|
return { success: true };
|
|
} catch (e) {
|
|
if (e instanceof Error && e.message === "Unauthorized") throw e;
|
|
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
|
}
|
|
}
|
|
|
|
export async function updateIntelExcerpt(input: {
|
|
profileId: number;
|
|
content: LexicalStateValue | null;
|
|
}): Promise<ActionResult> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
const permitted = await hasPermission(payload, user, "profiles:intel_excerpt:update");
|
|
if (!permitted) {
|
|
return { success: false, error: "You are not allowed to edit intelligence records." };
|
|
}
|
|
|
|
const profile = await findProfileOwner(payload, input.profileId);
|
|
if (!profile) {
|
|
return { success: false, error: "Profile not found." };
|
|
}
|
|
|
|
const blank = !input.content || lexicalPlaintextLength(input.content) === 0;
|
|
if (!blank && lexicalPlaintextLength(input.content) > INTEL_EXCERPT_MAX_LENGTH) {
|
|
return {
|
|
success: false,
|
|
error: `Intelligence record must be ${INTEL_EXCERPT_MAX_LENGTH} characters or fewer.`,
|
|
};
|
|
}
|
|
|
|
await payload.update({
|
|
collection: "profiles",
|
|
id: input.profileId,
|
|
data: { dossier: { intelExcerpt: blank ? null : input.content } },
|
|
overrideAccess: true,
|
|
});
|
|
|
|
await emitGameEvent(payload, {
|
|
type: EventTypes.DossierIntelExcerptUpdate,
|
|
message: "An intelligence record was updated.",
|
|
targetCollection: "users",
|
|
targetId: profile.ownerId,
|
|
data: { profileId: input.profileId },
|
|
});
|
|
|
|
return { success: true };
|
|
} catch (e) {
|
|
if (e instanceof Error && e.message === "Unauthorized") throw e;
|
|
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Promote a member to a new rank. Authority is resolved server-side from the
|
|
* actor's rank promotionCeiling (or admin/developer bypass); the client only
|
|
* supplies the target username and rank id.
|
|
*/
|
|
export async function promoteMember(
|
|
username: string,
|
|
rankId: number,
|
|
): Promise<ActionResult<{ profileId: number }>> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
const result = await promoteMemberService(payload, user, username, rankId);
|
|
return { success: true, data: { profileId: result.profileId } };
|
|
} catch (e) {
|
|
if (e instanceof Error && e.message === "Unauthorized") throw e;
|
|
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Submit a promotion nomination for the given member (or a self-request when
|
|
* the nominee is the authenticated user). The division leader endorsement
|
|
* stage and the open-nomination guards are enforced by the service lib.
|
|
*/
|
|
export async function submitPromotionNomination(input: {
|
|
nomineeUsername: string;
|
|
accolades: string;
|
|
}): Promise<ActionResult<{ nominationId: number }>> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
const nominee = await findUserByUsername(payload, input.nomineeUsername);
|
|
if (!nominee) {
|
|
return { success: false, error: "User not found." };
|
|
}
|
|
|
|
const nomination = await submitNomination(payload, user, {
|
|
nomineeId: nominee.id,
|
|
accolades: input.accolades,
|
|
});
|
|
return { success: true, data: { nominationId: nomination.id } };
|
|
} catch (e) {
|
|
if (e instanceof Error && e.message === "Unauthorized") throw e;
|
|
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
|
}
|
|
}
|
|
|
|
/** Withdraw one of the caller's own pending promotion nominations. */
|
|
export async function cancelMyNomination(nominationId: number): Promise<ActionResult> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
await cancelNominationCore(payload, user, nominationId);
|
|
return { success: true };
|
|
} catch (e) {
|
|
if (e instanceof Error && e.message === "Unauthorized") throw e;
|
|
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
|
}
|
|
}
|