1
0
Fork 0

feat(contributions): add crowdsourced XP reward system

Reward users for helping build the app: wiki pages, mission planning
markers (queued until the mission completes), surveys, and manual awards.
Contribution XP folds into the existing virtual profile total, so it
flows into the level ladder, sidebar XP display, dashboard, and profile.

- contribution-entries ledger collection + profile progression.contributions.xpEarned bucket
- src/lib/contributions service (record/grant/expire/revoke, caps, idempotency, leaderboard) with a pure rules module
- per-mission planning-map delegation (missions:update grants) and a completed/cancelled map lock
- wiki, survey, and marker action/hook integration
- contribution:* event types, muteable notifications, permissions group, event targets
- profile Contributions section and /contributions leaderboard
- migration, reconcile tool, and integration tests
This commit is contained in:
Jason Fraley 2026-10-09 16:30:05 -04:00
parent b28708c590
commit 3a2ae34b83
43 changed files with 41569 additions and 81 deletions

View file

@ -130,6 +130,7 @@ lists the invariant that caused the most damage when ignored.
| Game map system | `src/lib/map/AGENTS.md` | Coordinates are meters, not degrees; water zones gate placement; `docs/map-system.md` predates the grid work |
| Mission planning map (Arma markers) | `src/lib/arma-markers/AGENTS.md` | Markers are mission-scoped; the Missions `beforeDelete` hook removes them (FK is NOT NULL) |
| Banking | `src/lib/banking/AGENTS.md` | `applyTransaction()` is the only balance-mutating path |
| Contributions & XP | `src/lib/contributions/AGENTS.md` | The service layer is the only writer of the ledger and the profile bucket; queued marker XP grants only when the mission completes |
| Marketplace & NPC negotiation | `src/lib/market/AGENTS.md` | Only "clean" locker stock can be listed; `buyListing()` is the single purchase path |
| Notifications | `src/lib/notifications/AGENTS.md` | `notifyUser()` is fire-and-forget via `overrideAccess` |
| Announcements | `src/lib/announcements/AGENTS.md` | Client-side evaluation (Shims pattern); role targeting uses Roles docs, not the legacy enum |

View file

@ -0,0 +1,125 @@
"use server";
import config from "@payload-config";
import { getPayload } from "payload";
import { revalidatePath } from "next/cache";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission, isSuperuser } from "@/utils/access-control/hasPermission";
import { recordContribution, revokeEntry } from "@/lib/contributions";
export 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 (!user || !isPayloadUser(user)) {
throw new Error("Unauthorized");
}
return { payload, user };
}
function failure(error: unknown): { success: false; error: string } {
const message = error instanceof Error ? error.message : "Unknown error";
return message === "Unauthorized"
? { success: false, error: "You must be logged in." }
: { success: false, error: message };
}
const MAX_MANUAL_POINTS = 1000;
/**
* Grant a manual contribution award (community help, event organizing, or any
* contribution without an automatic rule). Gated on
* `contribution-entries:moderate`; staff cannot award themselves below
* superuser level.
*/
export async function grantManualContribution(input: {
userId: number;
points: number;
summary: string;
link?: string | null;
}): Promise<ActionResult<{ entryId: number; points: number }>> {
try {
const { payload, user } = await authenticate();
if (!(await hasPermission(payload, user, "contribution-entries:moderate"))) {
throw new Error("You are not allowed to grant contribution XP.");
}
const points = Math.floor(Number(input.points));
if (!Number.isFinite(points) || points <= 0 || points > MAX_MANUAL_POINTS) {
throw new Error(`Points must be between 1 and ${MAX_MANUAL_POINTS}.`);
}
const summary = (input.summary ?? "").trim();
if (summary.length < 3) {
throw new Error("A reason is required.");
}
const targetUserId = Number(input.userId);
if (!Number.isInteger(targetUserId)) {
throw new Error("Invalid user.");
}
if (targetUserId === Number(user.id) && !(await isSuperuser(payload, user))) {
throw new Error("You cannot grant yourself contribution XP.");
}
const result = await recordContribution(payload, {
userId: targetUserId,
type: "manual",
sourceCollection: "manual",
sourceId: targetUserId,
summary,
actorId: Number(user.id),
actorName: user.displayName ?? user.username ?? null,
pointsOverride: points,
link: input.link ?? null,
// Each manual grant is intentionally distinct.
dedupeSuffix: String(Date.now()),
});
if (result.status !== "granted" || result.entryId == null) {
throw new Error("The grant could not be recorded.");
}
revalidatePath("/contributions");
return { success: true, data: { entryId: result.entryId, points: result.points } };
} catch (error) {
return failure(error);
}
}
/** Revoke a contribution entry (granted XP is pulled back). */
export async function revokeContribution(input: {
entryId: number;
reason: string;
}): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
if (!(await hasPermission(payload, user, "contribution-entries:moderate"))) {
throw new Error("You are not allowed to revoke contribution XP.");
}
const entryId = Number(input.entryId);
if (!Number.isInteger(entryId)) {
throw new Error("Invalid entry.");
}
const reason = (input.reason ?? "").trim();
if (reason.length < 3) {
throw new Error("A reason is required.");
}
await revokeEntry(payload, entryId, { reason, by: Number(user.id) });
revalidatePath("/contributions");
return { success: true };
} catch (error) {
return failure(error);
}
}

View file

@ -0,0 +1,157 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { TrophyIcon } from "lucide-react";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import {
getContributionLeaderboard,
getContributionSummary,
type LeaderboardRow,
} from "@/lib/contributions";
import {
ContributionLeaderboard,
type LeaderboardDisplayRow,
} from "@/components/frontend/contributions/ContributionLeaderboard";
type Payload = Awaited<ReturnType<typeof getPayload>>;
async function resolveNames(
payload: Payload,
rows: LeaderboardRow[],
): Promise<Map<number, string>> {
const ids = [...new Set(rows.map((row) => row.userId))];
const nameById = new Map<number, string>();
if (ids.length === 0) return nameById;
const res = await payload.find({
collection: "users",
where: { id: { in: ids } },
limit: ids.length,
depth: 0,
overrideAccess: true,
select: { displayName: true, username: true },
});
for (const user of res.docs) {
nameById.set(
Number(user.id),
(user.displayName as string | null) || (user.username as string | null) || `User #${user.id}`,
);
}
return nameById;
}
function toDisplayRows(
rows: LeaderboardRow[],
nameById: Map<number, string>,
currentUserId: number | null,
): LeaderboardDisplayRow[] {
return rows.map((row, index) => ({
rank: index + 1,
userId: row.userId,
name: nameById.get(row.userId) ?? `User #${row.userId}`,
points: row.points,
entries: row.entries,
isCurrentUser: currentUserId === row.userId,
}));
}
export default async function ContributionsPage() {
const payload = await getPayload({ config });
const { user } = await payload.auth({
headers: await nextHeaders(),
canSetHeaders: false,
});
const viewer = isPayloadUser(user) ? user : null;
const currentUserId = viewer ? Number(viewer.id) : null;
const monthStart = new Date();
monthStart.setDate(1);
monthStart.setHours(0, 0, 0, 0);
const [monthRows, allRows, viewerSummary] = await Promise.all([
getContributionLeaderboard(payload, { since: monthStart.toISOString(), limit: 25 }),
getContributionLeaderboard(payload, { limit: 25 }),
currentUserId
? getContributionSummary(payload, currentUserId, { isOwner: false, limit: 1 })
: Promise.resolve(null),
]);
const [monthNames, allNames] = await Promise.all([
resolveNames(payload, monthRows),
resolveNames(payload, allRows),
]);
const monthDisplay = toDisplayRows(monthRows, monthNames, currentUserId);
const allDisplay = toDisplayRows(allRows, allNames, currentUserId);
// If the viewer is outside the all-time top list, append their standing.
if (
currentUserId &&
viewerSummary &&
viewerSummary.granted > 0 &&
!allRows.some((row) => row.userId === currentUserId)
) {
const ahead = allRows.filter((row) => row.points > viewerSummary.granted).length;
allDisplay.push({
rank: ahead + 1,
userId: currentUserId,
name: "You",
points: viewerSummary.granted,
entries: 0,
isCurrentUser: true,
isOutsideTop: true,
});
}
return (
<div className="p-5 flex flex-col gap-6 max-w-5xl">
<div className="flex items-center gap-3">
<TrophyIcon className="size-6 text-amber-400" />
<div>
<h1 className="text-2xl font-bold tracking-tight uppercase">Contribution Leaderboard</h1>
<p className="text-sm text-muted-foreground">
XP earned by helping build the app: wiki pages, mission planning, surveys, and manual
awards.
</p>
</div>
</div>
{viewerSummary && (
<div className="grid grid-cols-2 gap-3">
<div className="border border-border rounded-lg p-4">
<p className="text-xs uppercase tracking-wider text-muted-foreground">Your granted XP</p>
<p className="text-2xl font-bold font-mono text-emerald-400">
{viewerSummary.granted.toLocaleString()}
</p>
</div>
<div className="border border-border rounded-lg p-4">
<p className="text-xs uppercase tracking-wider text-muted-foreground">Your queued XP</p>
<p className="text-2xl font-bold font-mono text-amber-400">
{viewerSummary.queued.toLocaleString()}
</p>
</div>
</div>
)}
<section className="flex flex-col gap-3">
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
This Month
</h2>
<ContributionLeaderboard
rows={monthDisplay}
emptyLabel="No contribution XP earned yet this month."
/>
</section>
<section className="flex flex-col gap-3">
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
All Time
</h2>
<ContributionLeaderboard
rows={allDisplay}
emptyLabel="No contribution XP has been earned yet."
/>
</section>
</div>
);
}

View file

@ -42,7 +42,15 @@ import {
isMissionPast,
} from "@/lib/attendance";
import { MissionPlanningMap } from "@/components/frontend/intelligence/missionMap/MissionPlanningMap";
import { listMissionMarkers } from "@/lib/intelligence/missionMap";
import {
PlanningAccessControl,
type PlanningUserOption,
} from "@/components/frontend/intelligence/missionMap/PlanningAccessControl";
import {
isMissionPlanLocked,
listMissionMarkers,
planningMapDelegateIds,
} from "@/lib/intelligence/missionMap";
interface MissionDetailPageProps {
params: Promise<{ id: string }>;
@ -261,14 +269,40 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
/>
);
// Planning map: visible to everyone who can see the mission once enabled;
// editors (missions:update or the creator) also get the opt-in control.
const canEditPlan = canControlSideOp;
// Planning map: visible to everyone who can see the mission once enabled.
// Curators (missions:update or the creator) manage the map and delegate
// per-mission access; delegates may place/edit only their own markers. The
// whole map freezes once the mission reaches a terminal state.
const planLocked = isMissionPlanLocked(mission);
const planDelegateIds = planningMapDelegateIds(mission);
const isPlanDelegate = currentUser ? planDelegateIds.includes(Number(currentUser.id)) : false;
const canCuratePlan = canControlSideOp && !planLocked;
const canDelegate = canManage && !planLocked;
const canEditPlan = (canControlSideOp || isPlanDelegate) && !planLocked;
const planningMapEnabled = mission.classification.planningMapEnabled === true;
const planMarkers =
map && planningMapEnabled ? await listMissionMarkers(payload, mission.id) : [];
const showPlanningMap = map !== null && (planningMapEnabled || canEditPlan);
let planningUsers: PlanningUserOption[] = [];
if (canDelegate && planningMapEnabled) {
const planningUsersRes = await payload.find({
collection: "users",
limit: 500,
depth: 0,
sort: "displayName",
overrideAccess: true,
select: { displayName: true, username: true },
});
planningUsers = planningUsersRes.docs.map((candidate) => ({
id: Number(candidate.id),
name:
(candidate.displayName as string | null) ||
(candidate.username as string | null) ||
`User #${candidate.id}`,
}));
}
const providedRoles = mission.missionRoles?.providedRoles ?? [];
const signupGate = roleSignupGate(mission);
const signupState = await getMissionRoleSignupState(payload, mission.id, currentUser?.id ?? null);
@ -421,12 +455,21 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
</header>
<div className="p-5 flex flex-col gap-6 max-w-7xl mx-auto w-full">
{planningMapEnabled && canDelegate && (
<PlanningAccessControl
missionId={mission.id}
initialDelegateIds={planDelegateIds}
users={planningUsers}
/>
)}
{showPlanningMap && map && (
<MissionPlanningMap
missionId={mission.id}
missionLabel={mission.codeName || mission.name}
enabled={planningMapEnabled}
canEdit={canEditPlan}
canCurate={canCuratePlan}
locked={planLocked}
map={{
id: map.id,
name: map.name,

View file

@ -4,18 +4,23 @@ import config from "@payload-config";
import { getPayload } from "payload";
import { revalidatePath } from "next/cache";
import {
canEditMissionPlan,
canContributeToMissionPlan,
canCurateMissionPlan,
clearMissionMarkers,
createMissionMarker,
deleteMissionMarker,
findVisibleMission,
isMissionPlanLocked,
listMissionMarkers,
updateMissionMarker,
type PlanActor,
} from "@/lib/intelligence/missionMap";
import type { MissionMarker, MissionMarkerData } from "@/lib/arma-markers/missionMarkers";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { recordContribution, revokeQueuedForSource } from "@/lib/contributions";
export interface ActionResult<T = undefined> {
success: boolean;
@ -44,14 +49,37 @@ function failure(error: unknown): { success: false; error: string } {
: { success: false, error: message };
}
/** Visible mission + editor gate shared by every mutation below. */
async function editableMission(missionId: number) {
/**
* Visible mission + contributor gate (curators and per-mission delegates) +
* terminal-state lock. Returns the actor descriptor the marker service uses to
* enforce own-marker ownership for delegates.
*/
async function contributableMission(missionId: number) {
const { payload, user } = await authenticate();
const mission = await findVisibleMission(payload, user, missionId);
if (!mission) throw new Error("Mission not found.");
if (!(await canEditMissionPlan(payload, user, mission))) {
if (isMissionPlanLocked(mission)) {
throw new Error("This mission's planning map is locked now that the mission has concluded.");
}
const canEditAny = await canCurateMissionPlan(payload, user, mission);
if (!canEditAny && !(await canContributeToMissionPlan(payload, user, mission))) {
throw new Error("You do not have permission to edit this mission's planning map.");
}
const actor: PlanActor = { userId: Number(user.id), canEditAny };
return { payload, user, mission, actor };
}
/** Visible mission + curator gate + terminal-state lock. */
async function curatableMission(missionId: number) {
const { payload, user } = await authenticate();
const mission = await findVisibleMission(payload, user, missionId);
if (!mission) throw new Error("Mission not found.");
if (isMissionPlanLocked(mission)) {
throw new Error("This mission's planning map is locked now that the mission has concluded.");
}
if (!(await canCurateMissionPlan(payload, user, mission))) {
throw new Error("You do not have permission to manage this mission's planning map.");
}
return { payload, user, mission };
}
@ -65,7 +93,7 @@ export async function setMissionPlanningMap(input: {
enabled: boolean;
}): Promise<ActionResult> {
try {
const { payload, user, mission } = await editableMission(input.missionId);
const { payload, user, mission } = await curatableMission(input.missionId);
const enabled = Boolean(input.enabled);
await payload.update({
collection: "missions",
@ -88,6 +116,49 @@ export async function setMissionPlanningMap(input: {
}
}
/**
* Set the mission's planning-map delegates. Gated on `missions:update` (a
* per-mission, temporary grant of planning capability). The field-level access
* on the Missions collection is the backstop; this explicit check gives a loud
* rejection instead of Payload's silent field strip.
*/
export async function setMissionPlanningDelegates(input: {
missionId: number;
userIds: number[];
}): Promise<ActionResult<{ userIds: number[] }>> {
try {
const { payload, user } = await authenticate();
if (!(await hasPermission(payload, user, "missions:update"))) {
throw new Error("You need mission update permission to manage planning access.");
}
const mission = await findVisibleMission(payload, user, input.missionId);
if (!mission) throw new Error("Mission not found.");
const userIds = [...new Set((input.userIds ?? []).map(Number).filter(Number.isInteger))];
await payload.update({
collection: "missions",
id: mission.id,
data: { classification: { planningMapDelegates: userIds } },
overrideAccess: true,
});
await emitGameEvent(payload, {
type: EventTypes.MissionPlanningDelegates,
message: `Updated planning-map access for ${mission.name} (${userIds.length} delegate${
userIds.length === 1 ? "" : "s"
})`,
actor: user.id as number,
targetCollection: "missions",
targetId: mission.id,
data: { userIds },
});
revalidatePath(`/intelligence/missions/${mission.id}`);
return { success: true, data: { userIds } };
} catch (error) {
return failure(error);
}
}
/** Re-read markers (any user who can see the mission). */
export async function getMissionMapMarkers(input: {
missionId: number;
@ -108,11 +179,11 @@ export async function saveMissionMapMarker(input: {
marker: MissionMarkerData;
}): Promise<ActionResult<MissionMarker>> {
try {
const { payload, user, mission } = await editableMission(input.missionId);
const { payload, user, mission, actor } = await contributableMission(input.missionId);
const isUpdate = typeof input.id === "number";
const marker = isUpdate
? await updateMissionMarker(payload, mission, input.id as number, input.marker)
: await createMissionMarker(payload, mission, input.marker, user.id as number);
? await updateMissionMarker(payload, mission, input.id as number, input.marker, actor)
: await createMissionMarker(payload, mission, input.marker, actor.userId);
await emitGameEvent(payload, {
type: isUpdate ? EventTypes.MissionMapMarkerUpdate : EventTypes.MissionMapMarkerCreate,
message: `${isUpdate ? "Updated" : "Placed"} planning marker ${markerLabel(marker)} on ${mission.name}`,
@ -121,6 +192,23 @@ export async function saveMissionMapMarker(input: {
targetId: mission.id,
data: { markerId: marker.id, shape: marker.shape },
});
if (!isUpdate) {
// Queued contribution XP: granted only if the marker survives in the
// plan when the mission completes (see the Missions afterChange sweep).
await recordContribution(payload, {
userId: actor.userId,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: `Placed a planning marker on "${mission.name}"`,
actorId: actor.userId,
actorName: user.displayName ?? user.username ?? null,
link: `/intelligence/missions/${mission.id}`,
});
}
return { success: true, data: marker };
} catch (error) {
return failure(error);
@ -132,8 +220,15 @@ export async function deleteMissionMapMarker(input: {
id: number;
}): Promise<ActionResult> {
try {
const { payload, user, mission } = await editableMission(input.missionId);
await deleteMissionMarker(payload, mission.id, input.id);
const { payload, user, mission, actor } = await contributableMission(input.missionId);
await deleteMissionMarker(payload, mission.id, input.id, actor);
// Removing a marker pulls back its queued XP (nothing was contributed).
await revokeQueuedForSource(
payload,
"mission-map-markers",
input.id,
"The planning marker was removed.",
);
await emitGameEvent(payload, {
type: EventTypes.MissionMapMarkerDelete,
message: `Removed a planning marker from ${mission.name}`,
@ -152,8 +247,17 @@ export async function clearMissionMapMarkers(input: {
missionId: number;
}): Promise<ActionResult<{ removed: number }>> {
try {
const { payload, user, mission } = await editableMission(input.missionId);
const { payload, user, mission } = await curatableMission(input.missionId);
const markers = await listMissionMarkers(payload, mission.id);
const removed = await clearMissionMarkers(payload, mission.id);
for (const marker of markers) {
await revokeQueuedForSource(
payload,
"mission-map-markers",
marker.id,
"The planning map was cleared.",
);
}
await emitGameEvent(payload, {
type: EventTypes.MissionMapMarkersClear,
message: `Cleared ${removed} planning marker${removed === 1 ? "" : "s"} from ${mission.name}`,

View file

@ -114,6 +114,7 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
scoreboard: true,
xp: true,
minigames: true,
contributions: true,
},
},
}),

View file

@ -48,7 +48,7 @@ export default async function HomePage() {
select: {
user: true,
rank: true,
progression: { xp: true, awards: true, scoreboard: true, minigames: true },
progression: { xp: true, awards: true, scoreboard: true, minigames: true, contributions: true },
createdAt: true,
},
}),

View file

@ -11,6 +11,8 @@ import { isSuperuser, hasPermission } from "@/utils/access-control/hasPermission
import { isDirectLeaderOf, isMissionEvaluable } from "@/lib/evaluations";
import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels";
import { getEvaluationSummary } from "./actions";
import { getContributionSummary } from "@/lib/contributions";
import { ContributionHistory } from "@/components/frontend/contributions/ContributionHistory";
import {
ArrowLeftIcon,
AwardIcon,
@ -281,6 +283,7 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
xp: true,
scoreboard: true,
minigames: true,
contributions: true,
},
createdAt: true,
},
@ -408,6 +411,9 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
);
const scoreboard = profile.progression?.scoreboard ?? {};
const xp = profile.progression?.xp ?? 0;
const contributionSummary = await getContributionSummary(payload, user.id, {
isOwner: isProfileOwner,
});
const experienceRes = await payload.find({
collection: "experience",
@ -793,6 +799,22 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
)}
</section>
{/* ── Contributions ──────────────────────────────────── */}
<section className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<SparkleIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Contributions
</h2>
</div>
<ContributionHistory
granted={contributionSummary.granted}
queued={contributionSummary.queued}
rows={contributionSummary.rows}
isOwner={isProfileOwner}
/>
</section>
{/* ── Progression ────────────────────────────────────── */}
<section className="flex flex-col gap-3">
<div className="flex items-center gap-2">

View file

@ -15,6 +15,14 @@ import {
setPageLockdown as setPageLockdownService,
updatePage,
} from "@/lib/wiki/service";
import {
contentHash,
recordContribution,
revokeEntriesForSource,
} from "@/lib/contributions";
import { CONTRIBUTION_RULES, contentDelta } from "@/lib/contributions/rules";
const WIKI_EDIT_MIN_DELTA = CONTRIBUTION_RULES["wiki-page-edit"].minEditDeltaChars ?? 0;
interface ActionResult<T = undefined> {
success: boolean;
@ -79,7 +87,7 @@ export async function createWikiPage(input: {
tags?: string[];
body: string;
summary?: string;
}): Promise<ActionResult<{ id: number; slug: string }>> {
}): Promise<ActionResult<{ id: number; slug: string; awardedXp: number }>> {
try {
const { payload, user } = await authenticate();
const docError = documentationEditError(user, input.category);
@ -93,7 +101,23 @@ export async function createWikiPage(input: {
targetId: page.id,
data: { slug: page.slug },
});
return { success: true, data: { id: page.id, slug: page.slug } };
let awardedXp = 0;
if (input.category !== "Documentation") {
const result = await recordContribution(payload, {
userId: Number(user.id),
type: "wiki-page-create",
sourceCollection: "wiki-pages",
sourceId: page.id,
summary: `Created wiki page "${page.title}"`,
actorId: Number(user.id),
actorName: user.displayName ?? user.username ?? null,
link: `/wiki/${page.slug}`,
});
awardedXp = result.status === "granted" ? result.points : 0;
}
return { success: true, data: { id: page.id, slug: page.slug, awardedXp } };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
@ -110,13 +134,16 @@ export async function updateWikiPage(input: {
category?: string;
tags?: string[];
summary?: string;
}): Promise<ActionResult<{ id: number; slug: string }>> {
}): Promise<ActionResult<{ id: number; slug: string; awardedXp: number }>> {
try {
const { payload, user } = await authenticate();
const page = await fetchPage(payload, input.id);
if (!page) return { success: false, error: "Wiki page not found." };
const docError = documentationEditError(user, input.category ?? page.category);
const effectiveCategory = input.category ?? page.category;
const docError = documentationEditError(user, effectiveCategory);
if (docError) return { success: false, error: docError };
const nextBody = input.body ?? page.body;
const delta = contentDelta(page.body, nextBody);
const updated = await updatePage(payload, user, page, input);
await emitGameEvent(payload, {
type: EventTypes.WikiPageEdit,
@ -126,7 +153,26 @@ export async function updateWikiPage(input: {
targetId: updated.id,
data: { slug: updated.slug },
});
return { success: true, data: { id: updated.id, slug: updated.slug } };
let awardedXp = 0;
if (effectiveCategory !== "Documentation" && delta >= WIKI_EDIT_MIN_DELTA) {
const result = await recordContribution(payload, {
userId: Number(user.id),
type: "wiki-page-edit",
sourceCollection: "wiki-pages",
sourceId: updated.id,
summary: `Edited wiki page "${updated.title}"`,
actorId: Number(user.id),
actorName: user.displayName ?? user.username ?? null,
link: `/wiki/${updated.slug}`,
// One entry per user per distinct content version, so repeat saves of
// the same text cannot double-mint while genuinely new edits still earn.
dedupeSuffix: `${user.id}:${contentHash(nextBody)}`,
});
awardedXp = result.status === "granted" ? result.points : 0;
}
return { success: true, data: { id: updated.id, slug: updated.slug, awardedXp } };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
@ -217,6 +263,14 @@ export async function deleteWikiPage(input: { id: number }): Promise<ActionResul
const page = await fetchPage(payload, input.id);
if (!page) return { success: false, error: "Wiki page not found." };
await deletePage(payload, user, page);
// Deleting a page (e.g. spam) pulls back any XP it earned.
await revokeEntriesForSource(
payload,
"wiki-pages",
page.id,
`The wiki page "${page.title}" was deleted.`,
Number(user.id),
);
await emitGameEvent(payload, {
type: EventTypes.WikiPageDelete,
message: `${user.displayName ?? user.username} deleted wiki page "${page.title}"`,

View file

@ -14,9 +14,10 @@ collections/
Shims.ts # Global: audience-targeted content (admin-only)
Announcements.ts # Banner/modal/dialog/toast announcements (admin-authored, client-evaluated)
users/ 11 files # Users (auth), Ranks, Profiles (incl. minigame stats), Awards,
users/ 12 files # Users (auth), Ranks, Profiles (incl. minigame stats), Awards,
# Qualifications, Assignments, AssignmentTransfers, Experience,
# Evaluations, Roles (dynamic RBAC), UserNotifications
# Evaluations, Roles (dynamic RBAC), UserNotifications,
# ContributionEntries (crowdsourced XP ledger)
intelligence/ 5 files # Missions, MissionAttendances, MissionRoleSignups,
# MissionMapMarkers (planning-map markers), Campaigns, Factions, Technologies
logistics/ 5 files # Structures (staffing defaults), Resources, Assets, Vehicles, Shipments

View file

@ -32,6 +32,9 @@ const TARGET_COLLECTIONS = [
{ label: "Wiki Pages", value: "wiki-pages" },
{ label: "Wiki Revisions", value: "wiki-revisions" },
{ label: "Wiki Templates", value: "wiki-templates" },
{ label: "Survey Submissions", value: "form-submissions" },
{ label: "Mission Map Markers", value: "mission-map-markers" },
{ label: "Contribution Entries", value: "contribution-entries" },
{ label: "Game Servers", value: "game-servers" },
{ label: "Assignment Transfers", value: "assignment-transfers" },
{ label: "Voice Scripts", value: "voice-scripts" },

View file

@ -4,6 +4,10 @@ import {
hasPermission,
isSuperuser,
} from "@/utils/access-control/hasPermission";
import {
expireQueuedEntriesForMission,
grantQueuedEntriesForMission,
} from "@/lib/contributions";
type AssignmentRef = { id: number } | number;
@ -111,6 +115,17 @@ export const Missions: CollectionConfig = {
});
}
},
// Queued marker XP dies with the mission (the entries keep a null
// mission ref afterwards for audit). Granted XP is left untouched.
async ({ id, req }) => {
const missionId = typeof id === "number" ? id : Number(id);
if (!Number.isInteger(missionId)) return;
await expireQueuedEntriesForMission(
req.payload,
missionId,
"The mission was deleted before it completed; queued contribution XP expired.",
);
},
],
beforeChange: [
// Loop-safe by construction: this mutates the incoming data of the very
@ -163,6 +178,34 @@ export const Missions: CollectionConfig = {
return data;
},
],
afterChange: [
// Contribution XP sweep: when a mission transitions to a terminal state,
// settle every queued contribution entry tied to it. Completed grants
// marker XP that survived in the plan; Cancelled expires it. Runs after
// every status write (auto-complete tick, server actions, admin panel),
// so both paths are covered without touching the tick script.
async ({ doc, previousDoc, req, operation }) => {
if (operation !== "update") return;
const nextStatus = doc?.ownershipAndStatus?.status;
const prevStatus = previousDoc?.ownershipAndStatus?.status;
if (nextStatus === prevStatus) return;
const missionId = typeof doc.id === "number" ? doc.id : null;
if (missionId === null) return;
try {
if (nextStatus === "Completed") {
await grantQueuedEntriesForMission(req.payload, missionId);
} else if (nextStatus === "Cancelled") {
await expireQueuedEntriesForMission(req.payload, missionId);
}
} catch (error) {
req.payload.logger.error(
`[Contributions] Failed to settle queued XP for mission ${missionId}: ${
error instanceof Error ? error.message : "unknown error"
}`,
);
}
},
],
},
access: {
create: async ({ req }) => {
@ -372,6 +415,23 @@ export const Missions: CollectionConfig = {
"Show this mission's map on the mission page so mission editors can place Arma 3 planning markers that only appear for this mission.",
},
},
{
name: "planningMapDelegates",
type: "relationship",
relationTo: "users",
hasMany: true,
label: "Planning Map Delegates",
admin: {
description:
"Users granted temporary permission to place and edit their own planning markers on this mission. Managed from the mission page by anyone with missions:update; the map locks for everyone once the mission completes or is cancelled.",
},
access: {
create: async ({ req }) =>
hasPermission(req.payload, req.user, "missions:update"),
update: async ({ req }) =>
hasPermission(req.payload, req.user, "missions:update"),
},
},
{
name: "missionType",
type: "select",

View file

@ -0,0 +1,142 @@
import type { CollectionConfig, Where } from "payload";
import {
CONTRIBUTION_SOURCE_COLLECTIONS,
CONTRIBUTION_STATUSES,
contributionTypeOptions,
} from "@/lib/contributions/rules";
const STATUS_LABELS: Record<string, string> = {
queued: "Queued",
granted: "Granted",
revoked: "Revoked",
expired: "Expired",
};
const SOURCE_LABELS: Record<string, string> = {
"wiki-pages": "Wiki Page",
"mission-map-markers": "Planning Marker",
"form-submissions": "Survey Submission",
manual: "Manual",
};
const readOnly = { admin: { readOnly: true } } as const;
/**
* Append-only ledger of crowdsourced contribution XP.
*
* Every row records one contribution and its lifecycle status:
* - `queued` : earned but awaiting a lifecycle event (planning markers)
* - `granted` : counts toward the user's XP total
* - `revoked` : pulled back (marker removed, spam page deleted, staff action)
* - `expired` : never granted (mission cancelled before completion)
*
* Writes are service-only (`src/lib/contributions/` runs with `overrideAccess`)
* so the collection denies create/update/delete outright; the admin panel is a
* read-only review surface. The profile's denormalized
* `progression.contributions.xpEarned` bucket mirrors the granted total.
*/
export const ContributionEntries: CollectionConfig = {
slug: "contribution-entries",
labels: { singular: "Contribution Entry", plural: "Contribution Entries" },
admin: {
group: "Contributions",
useAsTitle: "summary",
defaultColumns: ["user", "type", "status", "points", "summary", "createdAt"],
description:
"Ledger of crowdsourced contribution XP. Read-only here; grants and revokes flow through the Contributions service and the /contributions page.",
},
access: {
// REST/API: a user sees their own entries (any status) plus everyone's
// granted entries (for the profile history and leaderboard). The admin
// panel additionally needs contribution-entries:read + admin:...:manage
// (applied centrally in payload.config.ts).
read: ({ req }): boolean | Where => {
if (!req.user) return false;
return {
or: [{ user: { equals: req.user.id } }, { status: { equals: "granted" } }],
};
},
create: () => false,
update: () => false,
delete: () => false,
},
fields: [
{
name: "user",
type: "relationship",
relationTo: "users",
required: true,
index: true,
...readOnly,
},
{
name: "type",
type: "select",
required: true,
index: true,
options: contributionTypeOptions(),
...readOnly,
},
{
name: "status",
type: "select",
required: true,
index: true,
defaultValue: "queued",
options: CONTRIBUTION_STATUSES.map((value) => ({ label: STATUS_LABELS[value] ?? value, value })),
...readOnly,
},
{
name: "points",
type: "number",
required: true,
min: 0,
...readOnly,
},
{
name: "sourceCollection",
type: "select",
required: true,
options: CONTRIBUTION_SOURCE_COLLECTIONS.map((value) => ({
label: SOURCE_LABELS[value] ?? value,
value,
})),
...readOnly,
},
{
name: "sourceId",
type: "number",
admin: { readOnly: true, description: "Id of the source document (polymorphic)." },
},
{
name: "mission",
type: "relationship",
relationTo: "missions",
index: true,
admin: { readOnly: true, description: "Set for planning-marker contributions." },
},
{
name: "summary",
type: "text",
required: true,
...readOnly,
},
{
name: "idempotencyKey",
type: "text",
required: true,
unique: true,
index: true,
admin: {
readOnly: true,
description: "Prevents the same contribution from being counted twice.",
},
},
{ name: "queuedAt", type: "date", admin: { readOnly: true } },
{ name: "grantedAt", type: "date", admin: { readOnly: true } },
{ name: "grantedBy", type: "relationship", relationTo: "users", admin: { readOnly: true } },
{ name: "revokedAt", type: "date", admin: { readOnly: true } },
{ name: "revokedBy", type: "relationship", relationTo: "users", admin: { readOnly: true } },
{ name: "revokedReason", type: "textarea", admin: { readOnly: true } },
],
};

View file

@ -136,6 +136,7 @@ export const Profiles: CollectionConfig = {
blackjack?: { xpEarned?: number | null };
};
voiceover?: { xpEarned?: number | null };
contributions?: { xpEarned?: number | null };
};
const awardsList = progressionData?.awards || [];
const awardIds = awardsList.flatMap((entry) => {
@ -153,6 +154,7 @@ export const Profiles: CollectionConfig = {
const pokerXp = progressionData?.minigames?.poker?.xpEarned ?? 0;
const blackjackXp = progressionData?.minigames?.blackjack?.xpEarned ?? 0;
const voiceoverXp = progressionData?.voiceover?.xpEarned ?? 0;
const contributionsXp = progressionData?.contributions?.xpEarned ?? 0;
if (awardIds.length > 0) {
await req.payload
@ -201,6 +203,8 @@ export const Profiles: CollectionConfig = {
xpAcc += blackjackXp;
// Voiceover submissions: XP awarded per accepted submission
xpAcc += voiceoverXp;
// Contribution ledger: crowdsourced XP (granted entries only)
xpAcc += contributionsXp;
return xpAcc;
},
@ -780,6 +784,25 @@ export const Profiles: CollectionConfig = {
},
],
},
{
name: "contributions",
label: "Contributions",
type: "group",
admin: {
readOnly: true,
description:
"Granted crowdsourced contribution XP (wiki, planning markers, surveys, manual). Maintained by the contributions service from the contribution-entries ledger.",
},
fields: [
{
name: "xpEarned",
label: "Contribution XP",
type: "number",
defaultValue: 0,
admin: { readOnly: true },
},
],
},
],
},
],

View file

@ -22,6 +22,7 @@ import {
ShoppingBag,
Swords,
TrendingUp,
Trophy,
Truck,
UserCog,
Users,
@ -180,6 +181,11 @@ export const sidebarData = {
url: "/awards",
icon: Award,
},
{
title: "Leaderboard",
url: "/contributions",
icon: Trophy,
},
{
title: "Locker",
url: "/locker",

View file

@ -0,0 +1,116 @@
import { ClientDate } from "@/components/frontend/ClientDate";
import { Item, ItemContent } from "@/components/ui/item";
import { cn } from "@/lib/utils";
import { ClockIcon, SparkleIcon } from "lucide-react";
import type { ContributionSummaryRow } from "@/lib/contributions";
import { CONTRIBUTION_RULES } from "@/lib/contributions/rules";
const STATUS_STYLES: Record<string, string> = {
granted: "text-emerald-400 border-emerald-500/40",
queued: "text-amber-400 border-amber-500/40",
revoked: "text-rose-400 border-rose-500/40",
expired: "text-muted-foreground border-border",
};
const STATUS_LABELS: Record<string, string> = {
granted: "Granted",
queued: "Queued",
revoked: "Revoked",
expired: "Expired",
};
/**
* Granted / queued contribution XP totals plus a recent history list.
* Server-rendered; the profile page queries the ledger and passes rows in.
*/
export function ContributionHistory({
granted,
queued,
rows,
isOwner,
}: {
granted: number;
queued: number;
rows: ContributionSummaryRow[];
isOwner: boolean;
}) {
return (
<div className="flex flex-col gap-3">
<div className="grid grid-cols-2 gap-3">
<Item variant="outline" size="sm">
<ItemContent>
<span className="text-xs uppercase tracking-wider text-muted-foreground">
Granted XP
</span>
<span className="text-2xl font-bold font-mono text-emerald-400">
{granted.toLocaleString()}
</span>
</ItemContent>
</Item>
<Item variant="outline" size="sm">
<ItemContent>
<span className="text-xs uppercase tracking-wider text-muted-foreground">
Queued XP
</span>
<span className="text-2xl font-bold font-mono text-amber-400">
{queued.toLocaleString()}
</span>
<span className="text-[10px] text-muted-foreground">
Granted when the mission completes
</span>
</ItemContent>
</Item>
</div>
{rows.length > 0 ? (
<div className="border border-border rounded-lg overflow-hidden">
<ul className="divide-y divide-border/50">
{rows.map((row) => (
<li key={row.id} className="flex items-center gap-3 px-4 py-2.5">
{row.status === "queued" ? (
<ClockIcon className="size-3.5 shrink-0 text-amber-400" />
) : (
<SparkleIcon className="size-3.5 shrink-0 text-muted-foreground" />
)}
<div className="min-w-0 flex-1">
<p className="truncate text-sm">{row.summary}</p>
<p className="text-[11px] text-muted-foreground">
{CONTRIBUTION_RULES[row.type]?.label ?? row.type}
{row.revokedReason ? ` \u00b7 ${row.revokedReason}` : ""}
</p>
</div>
<span className="shrink-0 font-mono text-sm tabular-nums text-emerald-400">
+{row.points}
</span>
<span
className={cn(
"shrink-0 rounded-sm border px-1.5 py-0.5 text-[10px] uppercase tracking-wide",
STATUS_STYLES[row.status] ?? "text-muted-foreground border-border",
)}
>
{STATUS_LABELS[row.status] ?? row.status}
</span>
<span className="hidden shrink-0 text-xs text-muted-foreground sm:block">
<ClientDate
date={row.grantedAt ?? row.createdAt}
options={{ month: "short", day: "numeric" }}
/>
</span>
</li>
))}
</ul>
</div>
) : (
<Item variant="muted">
<ItemContent>
<p className="text-sm text-muted-foreground italic">
{isOwner
? "You have not earned any contribution XP yet. Edit the wiki, help plan a mission, or answer a survey."
: "No contributions on record yet."}
</p>
</ItemContent>
</Item>
)}
</div>
);
}

View file

@ -0,0 +1,93 @@
import { cn } from "@/lib/utils";
import { Item, ItemContent } from "@/components/ui/item";
export interface LeaderboardDisplayRow {
rank: number;
userId: number;
name: string;
points: number;
entries: number;
isCurrentUser: boolean;
/** True for a trailing row inserted when the viewer is outside the top list. */
isOutsideTop?: boolean;
}
function rankClass(rank: number, isOutsideTop?: boolean): string {
if (isOutsideTop) return "text-muted-foreground";
if (rank === 1) return "font-bold text-amber-400";
if (rank === 2) return "font-semibold text-slate-300";
if (rank === 3) return "font-semibold text-amber-700";
return "text-muted-foreground";
}
/** Read-only contribution XP leaderboard table. */
export function ContributionLeaderboard({
rows,
emptyLabel,
}: {
rows: LeaderboardDisplayRow[];
emptyLabel: string;
}) {
if (rows.length === 0) {
return (
<Item variant="muted">
<ItemContent>
<p className="text-sm text-muted-foreground italic">{emptyLabel}</p>
</ItemContent>
</Item>
);
}
return (
<div className="border border-border rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="bg-muted/50 border-b border-border">
<th className="text-left px-4 py-2.5 font-semibold uppercase text-xs tracking-wider text-muted-foreground">
#
</th>
<th className="text-left px-4 py-2.5 font-semibold uppercase text-xs tracking-wider text-muted-foreground">
Operator
</th>
<th className="text-right px-4 py-2.5 font-semibold uppercase text-xs tracking-wider text-muted-foreground">
Entries
</th>
<th className="text-right px-4 py-2.5 font-semibold uppercase text-xs tracking-wider text-muted-foreground">
XP
</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr
key={`${row.userId}-${row.isOutsideTop ? "out" : "in"}`}
className={cn(
"border-b border-border/50 last:border-b-0",
row.isCurrentUser && "bg-accent/40",
row.isOutsideTop && "text-muted-foreground opacity-80",
)}
>
<td className="px-4 py-2">
<span className={rankClass(row.rank, row.isOutsideTop)}>
{row.isOutsideTop ? "-" : row.rank}
</span>
</td>
<td className="px-4 py-2 min-w-0">
<span className="truncate">{row.name}</span>
{row.isCurrentUser && (
<span className="ml-2 text-[10px] uppercase tracking-wide text-primary">You</span>
)}
</td>
<td className="px-4 py-2 text-right font-mono tabular-nums text-muted-foreground">
{row.entries.toLocaleString()}
</td>
<td className="px-4 py-2 text-right font-mono font-semibold tabular-nums text-emerald-400">
{row.points.toLocaleString()}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}

View file

@ -46,7 +46,12 @@ export interface MissionPlanningMapProps {
missionId: number;
missionLabel: string;
enabled: boolean;
/** Can place markers and edit/delete their own (curators + delegates). */
canEdit: boolean;
/** Can manage the map itself: toggle it, clear all markers. Defaults to canEdit. */
canCurate?: boolean;
/** True once the mission is terminal: the map is frozen read-only. */
locked?: boolean;
map: { id: number; name: string; worldWidth: number; worldHeight: number };
initialMarkers: MissionMarker[];
}
@ -101,6 +106,8 @@ export function MissionPlanningMap({
missionLabel,
enabled,
canEdit,
canCurate = canEdit,
locked = false,
map,
initialMarkers,
}: MissionPlanningMapProps) {
@ -334,7 +341,7 @@ export function MissionPlanningMap({
const ref = String((missionId * 37) % 1000).padStart(3, "0");
if (!enabled) {
if (!canEdit) return null;
if (!canCurate) return null;
return (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-dashed border-white/15 px-4 py-3">
<div className="flex items-center gap-3">
@ -440,7 +447,9 @@ export function MissionPlanningMap({
/>
</div>
<div className="flex flex-wrap gap-2 border-t border-white/15 p-3">
<AlertDialog>
{canCurate && (
<>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" disabled={markers.length === 0}>
<EraserIcon />
@ -473,11 +482,19 @@ export function MissionPlanningMap({
<PowerOffIcon />
Disable
</Button>
</>
)}
</div>
</aside>
)}
</div>
{locked && (
<div className="border-t border-white/15 bg-amber-500/10 px-3 py-1.5 text-center font-mono text-[10px] uppercase tracking-widest text-amber-300">
Planning map locked // mission concluded
</div>
)}
{/* Readout footer */}
<div className="flex items-center border-t border-white/15 bg-black/60 py-1.5 backdrop-blur-sm">
<ReadoutCell value={String(counts.icons)} label="Icons" />

View file

@ -0,0 +1,112 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { UsersIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { setMissionPlanningDelegates } from "@/app/(frontend)/intelligence/missions/mapActions";
export interface PlanningUserOption {
id: number;
name: string;
}
/**
* Curator control (missions:update holders) for the per-mission planning-map
* delegation list. Delegates can then place and edit their own markers.
*/
export function PlanningAccessControl({
missionId,
initialDelegateIds,
users,
}: {
missionId: number;
initialDelegateIds: number[];
users: PlanningUserOption[];
}) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [selected, setSelected] = useState<number[]>(initialDelegateIds);
const [saving, setSaving] = useState(false);
const toggle = (id: number) =>
setSelected((prev) => (prev.includes(id) ? prev.filter((value) => value !== id) : [...prev, id]));
const save = async () => {
setSaving(true);
const res = await setMissionPlanningDelegates({ missionId, userIds: selected });
setSaving(false);
if (res.success) {
toast.success("Planning access updated.");
setOpen(false);
router.refresh();
} else {
toast.error(res.error ?? "Failed to update planning access.");
}
};
return (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-white/15 bg-black/30 px-4 py-3">
<div className="flex items-center gap-3">
<UsersIcon className="size-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Planning access</p>
<p className="text-xs text-muted-foreground">
Grant unit members temporary permission to place their own planning markers on this
mission. {initialDelegateIds.length} delegate{initialDelegateIds.length === 1 ? "" : "s"}.
</p>
</div>
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button size="sm" variant="outline">
Manage access
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Planning map access</DialogTitle>
<DialogDescription>
Select the members who may place and edit their own markers on this mission. Access
lasts until the mission concludes.
</DialogDescription>
</DialogHeader>
<div className="flex max-h-80 flex-col gap-1 overflow-y-auto py-2">
{users.map((user) => (
<label
key={user.id}
className="flex cursor-pointer items-center gap-2 rounded px-2 py-1 text-sm hover:bg-accent/40"
>
<input
type="checkbox"
checked={selected.includes(user.id)}
onChange={() => toggle(user.id)}
className="accent-primary"
/>
<span className="truncate">{user.name}</span>
</label>
))}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setOpen(false)} disabled={saving}>
Cancel
</Button>
<Button onClick={() => void save()} disabled={saving}>
{saving ? "Saving..." : "Save access"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}

View file

@ -147,7 +147,12 @@ export function WikiEditor({
return;
}
toast.success(mode === "create" ? "Wiki page created" : "Wiki page updated");
const awardedXp = result.data.awardedXp ?? 0;
toast.success(
`${mode === "create" ? "Wiki page created" : "Wiki page updated"}${
awardedXp > 0 ? ` \u00b7 +${awardedXp} XP` : ""
}`,
);
router.push(`/wiki/${result.data.slug}`);
}

View file

@ -24,6 +24,7 @@ lib/
attendance/ # Mission attendance service (single write path)
awards/ # Award grant eligibility + diff/notify/cleanup
banking/ # Transaction engine, account creation, currency config, formatting
contributions/ # Contribution/XP ledger, earning rules, queued/granted lifecycle
base/ # Staffing (hire/fire/headcount), structure upgrades, storage, base tick
evaluations/ # Evaluation levels + bot reminder plan (reminders.ts)
locker/ # Grid logic, placement validation, loadouts, attachments/skins
@ -65,7 +66,7 @@ base-tick script ── lib/base/tick.ts (processBaseTick: salaries, maintenance
## Pure vs Payload-dependent
- **Pure modules** (no Payload import, safe for client + server): `npcDialogue.ts`, `chatBubbles.ts`, `ticketMeta.ts`, `distance.ts`, `aim-trainer.ts`, `wiki/markdown.tsx`, `wiki/prepare.ts`, `wiki/templates.ts`, `wiki/wikilinks.ts`, `shims/evaluate.ts`, `storageRules.ts` (logic only)
- **Pure modules** (no Payload import, safe for client + server): `npcDialogue.ts`, `chatBubbles.ts`, `ticketMeta.ts`, `distance.ts`, `aim-trainer.ts`, `wiki/markdown.tsx`, `wiki/prepare.ts`, `wiki/templates.ts`, `wiki/wikilinks.ts`, `shims/evaluate.ts`, `storageRules.ts` (logic only), `contributions/rules.ts`
- **Payload-dependent** (import `@payload-config`, server-only): everything else
## Key modules
@ -76,6 +77,9 @@ Enforcement order: **prohibited → whitelist → per-item cap**. Functions: `ch
### `banking/index.ts`
`applyTransaction()` — single source of truth for balance math. Validates accounts, creates transaction + ledger entries, updates balances. `ensurePersonalAccount()` — dedup find-or-create. `getMainCurrencyId()` — resolves Game Rules main currency. `currencyConfigFromGameRules()` builds the `CurrencyConfig` threaded through banking/market UI.
### `contributions/`
Single write path for the `contribution-entries` ledger and the profile's `progression.contributions.xpEarned` bucket. `recordContribution()` applies rules/idempotency/caps; `grantQueuedEntriesForMission` / `expireQueuedEntriesForMission` run from the Missions `afterChange` sweep; `revokeEntry` / `revokeEntriesForSource` pull XP back. `rules.ts` holds the tunables (pure). Full guide: `src/lib/contributions/AGENTS.md`.
### `base/`
Staffing/upkeep engine for structures: `staffing.ts` (`hireStaff`/`fireStaff`/`setLaborHeadcount`/`assertStaffHiringEnabled`), `upgrade.ts` (`upgradeStructure` — consumes stored materials, swaps type via `upgradesInto`), `storage.ts` (`consumeStorage`/`storedAmount`), `tick.ts` (`processBaseTick` — salaries, maintenance, upkeep flags).

View file

@ -8,6 +8,6 @@ Optional per-mission planning layer: the mission's own map (`classification.map`
- **Marker assets**: `bun run markers:arma` (`src/tools/arma/extractMarkers.ts`, needs the game install + `hemtt`; default game root `/mnt/LData/SteamLibrary/steamapps/common/Arma 3`, override `--game`). Scans `Dta`, `Addons` and every DLC `addons` dir (skips `@` mod folders), parses + merges `CfgMarkers` / `CfgMarkerColors` / `CfgMarkerBrushes` / `CfgMarkerClasses` with inheritance, resolves `$STR_` names via stringtables, converts icons to PNG in `public/arma/markers/` (committed, so prod needs no game files) and regenerates `src/lib/arma-markers/catalog.generated.ts` (never edit by hand). Side-color expressions resolve to Arma's default profile colors (BLUFOR 0,0.3,0.6 etc.).
- **Catalog lib** (`src/lib/arma-markers/`, pure, client-safe): `index.ts` (case-insensitive `markerTypeOf`/`markerColorOf`/`markerBrushOf`, `resolveMarkerRgba` where color `Default` = the type's own config color, `markerTypesByCategory`), `missionMarkers.ts` (marker model mirroring Arma: shape icon/rectangle/ellipse/polyline + type/color/brush/text/size/direction/alpha/points; `normalizeMarkerInput` validation; `areaOutline` (direction = degrees clockwise from north, size = half-extents like `markerSize`); `hatchSegments` for pattern brushes; `armaGridRef`; `markersToSqf` export, y flipped against world height).
- **Collection**: `mission-map-markers` (`src/collections/intelligence/MissionMapMarkers.ts`, permission group "Mission Map Markers", REST access permission-gated). Missions gained `classification.planningMapEnabled` (opt-in) and a `beforeDelete` hook that removes the mission's markers (the FK is NOT NULL, so Payload's default ON DELETE SET NULL would fail the delete). Migration `20261003_190000_add_mission_map_markers` (hand-written; matches the generated schema).
- **Rules**: read = anyone who can read the mission (user-scoped `findByID`); edit = `missions:update` or the mission's `createdBy`. Service `src/lib/intelligence/missionMap.ts`; server actions `src/app/(frontend)/intelligence/missions/mapActions.ts` (`setMissionPlanningMap`, `getMissionMapMarkers`, `saveMissionMapMarker`, `deleteMissionMapMarker`, `clearMissionMapMarkers`; events `mission:planning-map-toggle` / `mission:map-marker-*` / `mission:map-markers-clear`, target `missions`). Max 1000 markers per mission.
- **Rules**: read = anyone who can read the mission (user-scoped `findByID`). Two edit tiers in `src/lib/intelligence/missionMap.ts`: **curators** (`missions:update` or the mission's `createdBy`) manage the whole plan (toggle, clear, edit/delete any marker); **delegates** (`classification.planningMapDelegates`, set per mission by `missions:update` holders via `setMissionPlanningDelegates`) may place markers and edit/delete only their own. The map locks for everyone (`isMissionPlanLocked`) once status is Completed/Cancelled. Placing a marker queues 2 contribution XP that grants only if the marker survives to completion (see `src/lib/contributions/AGENTS.md`). Service `src/lib/intelligence/missionMap.ts`; server actions `src/app/(frontend)/intelligence/missions/mapActions.ts` (`setMissionPlanningMap`, `setMissionPlanningDelegates`, `getMissionMapMarkers`, `saveMissionMapMarker`, `deleteMissionMapMarker`, `clearMissionMapMarkers`; events `mission:planning-map-toggle` / `mission:planning-delegates` / `mission:map-marker-*` / `mission:map-markers-clear`, target `missions`). Max 1000 markers per mission.
- **UI**: `src/components/frontend/intelligence/missionMap/` (tactical dossier section above the mission detail grid). `MissionPlanningMap` (state, debounced per-marker saves, 30s background refresh, Delete/Escape keys, SQF copy, Arma grid readout), `MissionMapCanvas` (Leaflet, basemap + roads/zones via `GET /api/map-features?mapId=&layers=base`, which skips structures/nodes/shipments), `MarkerToolPanel` (tools, type picker, colors, brush, text, scale/size, direction, opacity), `markerIcon.ts` + `iconStyle.ts` (icons render as texture MULTIPLIED by the marker color and masked by the texture alpha, exactly like Arma: white glyphs take the color, flags keep theirs). Editors see an "Enable planning map" card until it is on; non-editors see nothing until enabled.
- **Gotchas**: leaflet click/dblclick/mousedown/mouseup fire faster than React re-renders, so draft line vertices and the area drag start live in refs (state only drives the preview). URLs inside divIcon HTML must use single quotes (`url('...')`): a double quote ends the `style` attribute and the glyph silently disappears. Radix Select keeps `pointer-events: none` on `<body>` briefly after closing (affects scripted drags right after choosing a brush). Tests: `tests/int/mission-map.int.spec.ts`, `tests/e2e/mission-planning-map.e2e.spec.ts`.

View file

@ -0,0 +1,104 @@
# AGENTS.md: Contributions & XP
> **Parent**: `../../../AGENTS.md` (root guide: commands, Server Action convention, domain guide index).
Crowdsourced contribution XP: users earn XP for helping build the app (wiki pages, mission
planning markers, surveys, manual awards). The XP feeds the existing virtual profile total
(`Profiles.progression.xp`), so it shows up in the sidebar `XPDisplay`, the profile page, and the
level ladder with no extra wiring.
## Data model
- **`contribution-entries`** (`src/collections/users/ContributionEntries.ts`) — append-only ledger,
one row per contribution. Fields: `user`, `type`, `status`, `points` (snapshot), `sourceCollection`
+ `sourceId` (polymorphic ref), optional `mission`, `summary`, unique `idempotencyKey`,
`queuedAt`/`grantedAt`/`grantedBy`/`revokedAt`/`revokedBy`/`revokedReason`.
- Status lifecycle: `queued` → `granted` (counts toward XP) | `revoked` (pulled back) | `expired`
(never granted, e.g. mission cancelled).
- Access: REST read = own rows (any status) plus everyone's `granted` rows; create/update/delete
are `false` (service-only, `overrideAccess`). The admin panel is a read-only review surface.
- **`Profiles.progression.contributions.xpEarned`** — denormalized granted total, maintained only by
`addContributionXp`. Folded into the virtual XP `afterRead` sum in `Profiles.ts`. Any profile read
that displays XP must select `progression.contributions` (layout, home dashboard, profile page).
## Rules
`src/lib/contributions/rules.ts` (pure, client-safe) is the single source of tunables. Points are
snapshotted onto each entry, so editing a value rebalances future earnings only.
| Type | Points | Mode | Guards |
|---|---|---|---|
| `wiki-page-create` | 10 | instant | 50 XP/day cap; Documentation category excluded |
| `wiki-page-edit` | 5 | instant | 30 XP/day cap; min 200-char normalized content delta |
| `mission-map-marker` | 2 | queued | first 10 per user per mission |
| `survey-completion` | 5 | instant | one per submission (idempotency) |
| `manual` | grantor-set | instant | reason required, no self-grants below superuser |
## Service (`src/lib/contributions/`)
Single write path (the `applyTransaction()` principle): every entry creation, status flip, bucket
update, event, and notification flows through these functions.
- `recordContribution(payload, input)` — applies rules, idempotency (`type:sourceCollection:sourceId:dedupeSuffix`),
daily and per-mission caps. Instant types grant immediately (bucket + event + notification);
queued types just create the row.
- `grantQueuedEntriesForMission` / `expireQueuedEntriesForMission` — lifecycle sweeps called from the
Missions `afterChange` hook on Completed / Cancelled.
- `revokeEntry` / `revokeEntriesForSource` / `revokeQueuedForSource` — moderation and source-deletion
cleanup. Revoking a `granted` entry subtracts from the bucket.
- `getContributionSummary` (profile/history) / `getContributionLeaderboard` (the `/contributions` page).
- `buckets.ts` — `addContributionXp` (the only bucket mutator; broadcasts `profile-update` with
`xpGained` so the sidebar animates). `index.ts` — `contentHash` for wiki edit dedupe.
## Lifecycle (map markers)
- Placement (`saveMissionMapMarker`, create branch) → `recordContribution` queues 2 XP.
- Marker deleted / map cleared → `revokeQueuedForSource` marks the queued row `revoked`.
- Mission → **Completed** (auto-complete tick or manual status change, both via `payload.update`) →
Missions `afterChange` calls `grantQueuedEntriesForMission`: markers that still exist grant, the
rest revoke.
- Mission → **Cancelled** / deleted → `expireQueuedEntriesForMission`.
## Integration points
- **Wiki**: `createWikiPage` / `updateWikiPage` award on success (Documentation excluded; edits need
a substantive delta, deduped by content hash); `deleteWikiPage` revokes the page's entries.
- **Surveys**: `formBuilderConfig.ts` `form-submissions` `afterChange` awards `survey-completion`.
- **Missions**: `classification.planningMapDelegates` + `afterChange` sweep + `beforeDelete` expire.
- **Moderation**: `src/app/(frontend)/contributions/actions.ts` (`grantManualContribution`,
`revokeContribution`) gated on `contribution-entries:moderate`.
- **Events**: `contribution:queue/grant/revoke/expire` (public) + `mission:planning-delegates`;
`contribution-entries`, `form-submissions`, `mission-map-markers` are valid event targets.
- **Notifications**: muteable `contribution:xp-granted` / `contribution:xp-revoked`.
- **Permissions**: group "Contributions" — `contribution-entries:read/create/update/delete`,
`contribution-entries:moderate`, `admin:contribution-entries:manage`.
- **UI**: profile "Contributions" section (`ContributionHistory`), `/contributions` leaderboard
(`ContributionLeaderboard`, sidebar "Leaderboard" entry), mission planning-map delegation control
(`PlanningAccessControl`) and read-only lock banner.
## Planning-map access (two tiers)
- **Curators** (`missions:update` or the mission's `createdBy`) — toggle the map, place/edit/delete any
marker, clear all, manage delegates.
- **Delegates** (per-mission `classification.planningMapDelegates`, set by `missions:update` holders via
`setMissionPlanningDelegates`) — place markers and edit/delete only their own.
- The map locks for everyone (curators included) once status is Completed/Cancelled
(`isMissionPlanLocked`). The delegate list stays on the doc as an audit record.
## Anti-gaming
Idempotency key (unique index) prevents double-minting; daily/per-mission caps; wiki edit substance
threshold; queued-by-default for curatable work (planner deletion revokes); source deletion pulls XP
back; manual grants require a reason and block self-grants below superuser; everything is auditable in
the ledger plus the public event log.
## Gotchas
- The bucket is read-modify-write; concurrent grants to the same user can race (acceptable at unit
scale). Run `bun run src/tools/seed/reconcileContributionXp.ts` to rebuild it from the ledger.
- `missions_rels.path` is a plain varchar, so adding a hasMany relationship to Missions needs no
schema migration; the `contribution-entries` table and profile column do (migration
`20261009_201920_add_contribution_entries`).
- The Missions `afterChange` sweep must stay loop-safe: it writes entries/profiles, never missions.
- Tests: `tests/int/contributions.int.spec.ts`.

View file

@ -0,0 +1,54 @@
import type { Payload } from "payload";
import { broadcastToUser } from "@/lib/realtime/bus";
/**
* Apply a signed XP delta to a user's denormalized contribution bucket
* (`profiles.progression.contributions.xpEarned`).
*
* The contribution ledger remains the source of truth; this bucket exists so
* the hot profile read in `(frontend)/layout.tsx` never has to query the
* ledger. `src/tools/seed/reconcileContributionXp.ts` rebuilds it from the
* ledger if the two ever drift.
*
* A positive delta also broadcasts `profile-update` with `xpGained` so the
* sidebar XP display plays its "+N XP" animation (mirrors VoiceSubmissions).
*/
export async function addContributionXp(
payload: Payload,
userId: number,
delta: number,
): Promise<void> {
if (!Number.isFinite(delta) || delta === 0) return;
const res = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
select: { progression: { contributions: { xpEarned: true } } },
});
const profile = res.docs[0];
if (!profile) {
payload.logger.warn(
`[Contributions] No profile found for user ${userId}; XP delta ${delta} was not applied.`,
);
return;
}
const current = profile.progression?.contributions?.xpEarned ?? 0;
const next = Math.max(0, current + delta);
await payload.update({
collection: "profiles",
id: profile.id,
data: { progression: { contributions: { xpEarned: next } } },
overrideAccess: true,
depth: 0,
});
if (delta > 0) {
broadcastToUser("profile-update", userId, { profileId: profile.id, xpGained: delta });
}
}

View file

@ -0,0 +1,641 @@
import type { Payload, Where } from "payload";
import { createHash } from "crypto";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { notifyUser } from "@/lib/notifications";
import { addContributionXp } from "./buckets";
import {
CONTRIBUTION_RULES,
type ContributionSourceCollection,
type ContributionStatus,
type ContributionType,
} from "./rules";
/**
* Contribution / XP service — the single write path for the contribution
* ledger (`contribution-entries`) and the denormalized profile bucket.
*
* Follows the `applyTransaction()` principle: every entry creation, status
* transition, bucket update, event, and notification flows through these
* functions. Server actions, collection hooks, and the survey submission hook
* all call in here; nothing else touches the collection or the bucket.
*/
export interface ContributionEntryDoc {
id: number;
user: number | { id: number };
type: ContributionType;
status: ContributionStatus;
points: number;
sourceCollection: ContributionSourceCollection;
sourceId: number;
mission?: number | { id: number } | null;
summary: string;
idempotencyKey: string;
queuedAt?: string | null;
grantedAt?: string | null;
grantedBy?: number | { id: number } | null;
revokedAt?: string | null;
revokedBy?: number | { id: number } | null;
revokedReason?: string | null;
createdAt: string;
updatedAt: string;
}
export interface ContributionRecordResult {
status: "granted" | "queued" | "skipped";
points: number;
entryId?: number;
}
export interface RecordContributionInput {
userId: number;
type: ContributionType;
sourceCollection: ContributionSourceCollection;
sourceId: number;
summary: string;
/** Who caused the contribution (defaults to the earner). */
actorId?: number | null;
/** Display name for the event message (falls back to `User #id`). */
actorName?: string | null;
/** Internal path attached to the grant notification. */
link?: string | null;
/** Mission attribution for queued marker XP. */
missionId?: number | null;
/** Manual grants set their own amount (rule points are ignored). */
pointsOverride?: number | null;
/** Extra discriminator for the idempotency key (e.g. an edit content hash). */
dedupeSuffix?: string | null;
}
export interface ContributionSummaryRow {
id: number;
type: ContributionType;
status: ContributionStatus;
points: number;
summary: string;
missionId: number | null;
queuedAt: string | null;
grantedAt: string | null;
revokedReason: string | null;
createdAt: string;
}
export interface ContributionSummary {
granted: number;
queued: number;
rows: ContributionSummaryRow[];
}
function relId(value: number | { id: number } | null | undefined): number | null {
if (typeof value === "number") return value;
if (value && typeof value === "object") return value.id;
return null;
}
function actorLabel(userId: number, actorName?: string | null): string {
return actorName && actorName.trim().length > 0 ? actorName : `User #${userId}`;
}
/** Resolve a user's display name for human-readable event messages. */
async function resolveUserName(payload: Payload, userId: number): Promise<string> {
try {
const user = (await payload.findByID({
collection: "users",
id: userId,
depth: 0,
overrideAccess: true,
select: { displayName: true, username: true },
})) as unknown as { displayName?: string | null; username?: string | null };
return user.displayName || user.username || `User #${userId}`;
} catch {
return `User #${userId}`;
}
}
/** Deterministic content hash for deduping wiki edits. Server-only. */
export function contentHash(text: string): string {
return createHash("sha256").update(text).digest("hex").slice(0, 16);
}
function buildIdempotencyKey(input: RecordContributionInput): string {
return [input.type, input.sourceCollection, input.sourceId, input.dedupeSuffix ?? ""].join(":");
}
async function findByIdempotencyKey(
payload: Payload,
key: string,
): Promise<ContributionEntryDoc | null> {
const res = (await payload.find({
collection: "contribution-entries",
where: { idempotencyKey: { equals: key } },
limit: 1,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: ContributionEntryDoc[] };
return res.docs[0] ?? null;
}
/** Sum of points already earned from a type by a user in the last 24h. */
async function recentPointsForType(
payload: Payload,
userId: number,
type: ContributionType,
): Promise<number> {
const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
const res = (await payload.find({
collection: "contribution-entries",
where: {
and: [
{ user: { equals: userId } },
{ type: { equals: type } },
{ status: { equals: "granted" } },
{ createdAt: { greater_than_equal: since } },
],
},
limit: 200,
depth: 0,
overrideAccess: true,
select: { points: true },
})) as unknown as { docs: Pick<ContributionEntryDoc, "points">[] };
return res.docs.reduce((sum, doc) => sum + (doc.points ?? 0), 0);
}
/** Count of live (queued or granted) entries for a user on a mission. */
async function missionEntryCount(
payload: Payload,
userId: number,
type: ContributionType,
missionId: number,
): Promise<number> {
const { totalDocs } = await payload.count({
collection: "contribution-entries",
where: {
and: [
{ user: { equals: userId } },
{ type: { equals: type } },
{ mission: { equals: missionId } },
{ status: { in: ["queued", "granted"] } },
],
},
overrideAccess: true,
});
return totalDocs;
}
async function sourceStillExists(
payload: Payload,
sourceCollection: ContributionSourceCollection,
sourceId: number,
): Promise<boolean> {
if (sourceCollection === "manual") return true;
try {
const doc = await payload.findByID({
collection: sourceCollection,
id: sourceId,
depth: 0,
overrideAccess: true,
});
return Boolean(doc);
} catch {
return false;
}
}
async function emitGranted(
payload: Payload,
entry: ContributionEntryDoc,
actorId: number,
earnerName: string,
points: number,
type: ContributionType,
): Promise<void> {
await emitGameEvent(payload, {
type: EventTypes.ContributionGranted,
message: `${earnerName} earned ${points} XP: ${entry.summary}`,
actor: actorId,
targetCollection: entry.sourceCollection === "manual" ? undefined : entry.sourceCollection,
targetId: entry.sourceCollection === "manual" ? undefined : entry.sourceId,
data: { points, type, entryId: entry.id },
});
}
function entryUserId(entry: ContributionEntryDoc): number {
return relId(entry.user) ?? 0;
}
/**
* Record a contribution. Instant-mode types grant immediately; queued types
* wait for a lifecycle sweep. Enforces idempotency and daily/per-mission caps.
*/
export async function recordContribution(
payload: Payload,
input: RecordContributionInput,
): Promise<ContributionRecordResult> {
const rule = CONTRIBUTION_RULES[input.type];
const points = input.pointsOverride ?? rule.points ?? 0;
if (!Number.isFinite(points) || points <= 0) {
return { status: "skipped", points: 0 };
}
const key = buildIdempotencyKey(input);
const existing = await findByIdempotencyKey(payload, key);
if (existing) {
return {
status: existing.status === "granted" ? "granted" : "queued",
points: existing.points,
entryId: existing.id,
};
}
if (rule.dailyCap != null) {
const earnedToday = await recentPointsForType(payload, input.userId, input.type);
if (earnedToday + points > rule.dailyCap) {
return { status: "skipped", points: 0 };
}
}
if (rule.maxPerMission != null && input.missionId != null) {
const count = await missionEntryCount(payload, input.userId, input.type, input.missionId);
if (count >= rule.maxPerMission) {
return { status: "skipped", points: 0 };
}
}
const status: ContributionStatus = rule.mode === "instant" ? "granted" : "queued";
const nowIso = new Date().toISOString();
const created = (await payload.create({
collection: "contribution-entries",
data: {
user: input.userId,
type: input.type,
status,
points,
sourceCollection: input.sourceCollection,
sourceId: input.sourceId,
mission: input.missionId ?? null,
summary: input.summary,
idempotencyKey: key,
queuedAt: nowIso,
grantedAt: status === "granted" ? nowIso : null,
},
overrideAccess: true,
depth: 0,
})) as unknown as ContributionEntryDoc;
const actorId = input.actorId ?? input.userId;
if (status === "granted") {
await addContributionXp(payload, input.userId, points);
await emitGranted(
payload,
created,
actorId,
actorLabel(input.userId, input.actorName),
points,
input.type,
);
await notifyUser(payload, {
userId: input.userId,
type: "contribution:xp-granted",
title: `+${points} XP earned`,
message: created.summary,
link: input.link ?? "/contributions",
});
} else {
await emitGameEvent(payload, {
type: EventTypes.ContributionQueued,
message: `${actorLabel(input.userId, input.actorName)} queued ${points} XP: ${created.summary}`,
actor: actorId,
targetCollection: "missions",
targetId: input.missionId ?? undefined,
data: { points, type: input.type, entryId: created.id },
});
}
return { status, points, entryId: created.id };
}
/** Flip a queued entry to granted, applying the bucket delta and notifying. */
async function markGranted(
payload: Payload,
entry: ContributionEntryDoc,
reason: string,
): Promise<void> {
const userId = entryUserId(entry);
const nowIso = new Date().toISOString();
await payload.update({
collection: "contribution-entries",
id: entry.id,
data: { status: "granted", grantedAt: nowIso },
overrideAccess: true,
});
await addContributionXp(payload, userId, entry.points);
await emitGranted(payload, entry, userId, await resolveUserName(payload, userId), entry.points, entry.type);
await notifyUser(payload, {
userId,
type: "contribution:xp-granted",
title: `+${entry.points} XP granted`,
message: reason,
link: "/contributions",
});
}
/**
* Grant every queued entry on a mission whose source marker still exists.
* Entries whose marker was removed are revoked (backstop for a missed delete
* hook). Called from the Missions afterChange hook on a Completed transition.
*/
export async function grantQueuedEntriesForMission(
payload: Payload,
missionId: number,
): Promise<{ granted: number; revoked: number }> {
const res = (await payload.find({
collection: "contribution-entries",
where: { and: [{ mission: { equals: missionId } }, { status: { equals: "queued" } }] },
limit: 1000,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: ContributionEntryDoc[] };
let granted = 0;
let revoked = 0;
for (const entry of res.docs) {
const survives = await sourceStillExists(payload, entry.sourceCollection, entry.sourceId);
if (!survives) {
await revokeEntry(payload, entry.id, {
reason: "The contribution was removed before the mission completed.",
silent: true,
});
revoked += 1;
continue;
}
await markGranted(payload, entry, `Your contribution was kept in "${entry.summary}".`);
granted += 1;
}
return { granted, revoked };
}
/** Expire every queued entry on a mission (Cancelled, or stale drafts). */
export async function expireQueuedEntriesForMission(
payload: Payload,
missionId: number,
reason = "The mission was cancelled; queued contribution XP expired.",
): Promise<number> {
const res = (await payload.find({
collection: "contribution-entries",
where: { and: [{ mission: { equals: missionId } }, { status: { equals: "queued" } }] },
limit: 1000,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: ContributionEntryDoc[] };
const nowIso = new Date().toISOString();
for (const entry of res.docs) {
await payload.update({
collection: "contribution-entries",
id: entry.id,
data: { status: "expired", revokedAt: nowIso, revokedReason: reason },
overrideAccess: true,
});
await emitGameEvent(payload, {
type: EventTypes.ContributionExpired,
message: `Queued ${entry.points} XP expired: ${entry.summary}`,
targetCollection: "missions",
targetId: missionId,
data: { points: entry.points, type: entry.type, entryId: entry.id },
});
}
return res.docs.length;
}
export interface RevokeEntryOptions {
reason: string;
by?: number | null;
/** Suppress the user-facing notification (self-removals, bulk expiry). */
silent?: boolean;
}
/**
* Revoke a granted or queued entry. Granted entries subtract their points from
* the bucket so the ledger and the bucket never disagree about direction.
*/
export async function revokeEntry(
payload: Payload,
entryId: number,
options: RevokeEntryOptions,
): Promise<void> {
const entry = (await payload
.findByID({ collection: "contribution-entries", id: entryId, depth: 0, overrideAccess: true })
.catch(() => null)) as unknown as ContributionEntryDoc | null;
if (!entry) return;
if (entry.status === "revoked" || entry.status === "expired") return;
const wasGranted = entry.status === "granted";
const userId = entryUserId(entry);
const nowIso = new Date().toISOString();
await payload.update({
collection: "contribution-entries",
id: entry.id,
data: {
status: "revoked",
revokedAt: nowIso,
revokedBy: options.by ?? null,
revokedReason: options.reason,
},
overrideAccess: true,
});
if (wasGranted) {
await addContributionXp(payload, userId, -entry.points);
}
await emitGameEvent(payload, {
type: EventTypes.ContributionRevoked,
message: `Revoked ${entry.points} XP: ${entry.summary}`,
actor: options.by ?? undefined,
targetCollection: entry.sourceCollection === "manual" ? undefined : entry.sourceCollection,
targetId: entry.sourceCollection === "manual" ? undefined : entry.sourceId,
data: { points: entry.points, type: entry.type, entryId: entry.id, reason: options.reason },
});
if (wasGranted && !options.silent) {
await notifyUser(payload, {
userId,
type: "contribution:xp-revoked",
title: `${entry.points} XP revoked`,
message: options.reason,
link: "/contributions",
});
}
}
/**
* Revoke every live entry sourced from a document (e.g. a wiki page deleted as
* spam). Granted entries have their XP pulled back.
*/
export async function revokeEntriesForSource(
payload: Payload,
sourceCollection: ContributionSourceCollection,
sourceId: number,
reason: string,
by: number | null = null,
): Promise<number> {
if (sourceCollection === "manual") return 0;
const res = (await payload.find({
collection: "contribution-entries",
where: {
and: [
{ sourceCollection: { equals: sourceCollection } },
{ sourceId: { equals: sourceId } },
{ status: { in: ["queued", "granted"] } },
],
},
limit: 1000,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: ContributionEntryDoc[] };
for (const entry of res.docs) {
await revokeEntry(payload, entry.id, { reason, by, silent: by === null });
}
return res.docs.length;
}
/** Revoke the queued entry (if any) tied to a single source document. */
export async function revokeQueuedForSource(
payload: Payload,
sourceCollection: ContributionSourceCollection,
sourceId: number,
reason: string,
): Promise<void> {
const res = (await payload.find({
collection: "contribution-entries",
where: {
and: [
{ sourceCollection: { equals: sourceCollection } },
{ sourceId: { equals: sourceId } },
{ status: { equals: "queued" } },
],
},
limit: 20,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: ContributionEntryDoc[] };
for (const entry of res.docs) {
await revokeEntry(payload, entry.id, { reason, silent: true });
}
}
function toRow(doc: ContributionEntryDoc): ContributionSummaryRow {
return {
id: doc.id,
type: doc.type,
status: doc.status,
points: doc.points,
summary: doc.summary,
missionId: relId(doc.mission),
queuedAt: doc.queuedAt ?? null,
grantedAt: doc.grantedAt ?? null,
revokedReason: doc.revokedReason ?? null,
createdAt: doc.createdAt,
};
}
/** Sum a user's granted / queued XP and list their most recent entries. */
export async function getContributionSummary(
payload: Payload,
userId: number,
options: { isOwner: boolean; limit?: number } = { isOwner: false },
): Promise<ContributionSummary> {
const limit = options.limit ?? 25;
const [grantedRes, queuedRes, rowsRes] = await Promise.all([
payload.find({
collection: "contribution-entries",
where: { and: [{ user: { equals: userId } }, { status: { equals: "granted" } }] },
limit: 1000,
depth: 0,
overrideAccess: true,
select: { points: true },
}),
payload.find({
collection: "contribution-entries",
where: { and: [{ user: { equals: userId } }, { status: { equals: "queued" } }] },
limit: 1000,
depth: 0,
overrideAccess: true,
select: { points: true },
}),
payload.find({
collection: "contribution-entries",
where: options.isOwner
? { user: { equals: userId } }
: { and: [{ user: { equals: userId } }, { status: { equals: "granted" } }] },
sort: "-createdAt",
limit,
depth: 0,
overrideAccess: true,
}),
]);
const granted = (grantedRes.docs as unknown as { points: number }[]).reduce(
(sum, doc) => sum + (doc.points ?? 0),
0,
);
const queued = (queuedRes.docs as unknown as { points: number }[]).reduce(
(sum, doc) => sum + (doc.points ?? 0),
0,
);
return {
granted,
queued,
rows: (rowsRes.docs as unknown as ContributionEntryDoc[]).map(toRow),
};
}
export interface LeaderboardRow {
userId: number;
points: number;
entries: number;
}
/**
* Aggregate granted contribution XP per user over a window. Small-scale
* reduce in JS; swap for a Drizzle aggregate if the ledger ever grows large.
*/
export async function getContributionLeaderboard(
payload: Payload,
options: { since?: string | null; limit?: number } = {},
): Promise<LeaderboardRow[]> {
const conditions: Where[] = [{ status: { equals: "granted" } }];
if (options.since) {
conditions.push({ grantedAt: { greater_than_equal: options.since } });
}
const res = (await payload.find({
collection: "contribution-entries",
where: { and: conditions },
limit: 5000,
depth: 0,
overrideAccess: true,
select: { user: true, points: true },
})) as unknown as { docs: Pick<ContributionEntryDoc, "user" | "points">[] };
const byUser = new Map<number, LeaderboardRow>();
for (const doc of res.docs) {
const userId = relId(doc.user);
if (userId == null) continue;
const row = byUser.get(userId) ?? { userId, points: 0, entries: 0 };
row.points += doc.points ?? 0;
row.entries += 1;
byUser.set(userId, row);
}
return [...byUser.values()]
.sort((a, b) => b.points - a.points || a.userId - b.userId)
.slice(0, options.limit ?? 25);
}

View file

@ -0,0 +1,137 @@
/**
* Contribution / XP earning rules (pure, client-safe).
*
* This module holds the tunable configuration for every crowdsourced
* contribution type. It is deliberately free of Payload imports so the admin
* select options and rule labels can be shared anywhere.
*
* Points are snapshotted onto each ledger entry when it is created, so editing
* a value here rebalances future earnings only; historical entries keep the
* value they were earned at.
*/
export const CONTRIBUTION_TYPES = [
"wiki-page-create",
"wiki-page-edit",
"mission-map-marker",
"survey-completion",
"manual",
] as const;
export type ContributionType = (typeof CONTRIBUTION_TYPES)[number];
export const CONTRIBUTION_STATUSES = ["queued", "granted", "revoked", "expired"] as const;
export type ContributionStatus = (typeof CONTRIBUTION_STATUSES)[number];
/** The source document a contribution is attributed to (polymorphic ref). */
export const CONTRIBUTION_SOURCE_COLLECTIONS = [
"wiki-pages",
"mission-map-markers",
"form-submissions",
"manual",
] as const;
export type ContributionSourceCollection = (typeof CONTRIBUTION_SOURCE_COLLECTIONS)[number];
export interface ContributionRule {
readonly type: ContributionType;
/** Human-readable label for admin selectors and the profile history. */
readonly label: string;
/** Points awarded per entry. `null` means the amount is set by the grantor. */
readonly points: number | null;
/** `instant` grants immediately; `queued` awaits a lifecycle event. */
readonly mode: "instant" | "queued";
readonly description: string;
/** Max XP a user can earn from this type per rolling 24h window (null = none). */
readonly dailyCap: number | null;
/** Max entries a user can earn per mission for this type (null = none). */
readonly maxPerMission: number | null;
/** Minimum normalized content delta (chars) for an edit to qualify. */
readonly minEditDeltaChars: number | null;
}
export const CONTRIBUTION_RULES: Record<ContributionType, ContributionRule> = {
"wiki-page-create": {
type: "wiki-page-create",
label: "Wiki page created",
points: 10,
mode: "instant",
description: "Created a new wiki page (Documentation category excluded).",
dailyCap: 50,
maxPerMission: null,
minEditDeltaChars: null,
},
"wiki-page-edit": {
type: "wiki-page-edit",
label: "Wiki page edited",
points: 5,
mode: "instant",
description: "Made a substantive edit to a wiki page.",
dailyCap: 30,
maxPerMission: null,
minEditDeltaChars: 200,
},
"mission-map-marker": {
type: "mission-map-marker",
label: "Planning marker placed",
points: 2,
mode: "queued",
description:
"Placed a marker on a mission's planning map. XP is queued and granted if the marker is still in the plan when the mission completes.",
dailyCap: null,
maxPerMission: 10,
minEditDeltaChars: null,
},
"survey-completion": {
type: "survey-completion",
label: "Survey completed",
points: 5,
mode: "instant",
description: "Completed a unit survey.",
dailyCap: 25,
maxPerMission: null,
minEditDeltaChars: null,
},
manual: {
type: "manual",
label: "Manual award",
points: null,
mode: "instant",
description: "Manually granted XP for a contribution that has no automatic rule.",
dailyCap: null,
maxPerMission: null,
minEditDeltaChars: null,
},
};
export function isContributionType(value: unknown): value is ContributionType {
return typeof value === "string" && (CONTRIBUTION_TYPES as readonly string[]).includes(value);
}
export function isContributionStatus(value: unknown): value is ContributionStatus {
return typeof value === "string" && (CONTRIBUTION_STATUSES as readonly string[]).includes(value);
}
export function contributionRule(type: ContributionType): ContributionRule {
return CONTRIBUTION_RULES[type];
}
/** Select options for the ledger's `type` field and the rules reference table. */
export function contributionTypeOptions(): { label: string; value: ContributionType }[] {
return CONTRIBUTION_TYPES.map((type) => ({ label: CONTRIBUTION_RULES[type].label, value: type }));
}
/**
* Normalized content length used for the wiki edit substance threshold:
* whitespace is collapsed and case folded so formatting-only changes score ~0.
*/
export function normalizedContentLength(text: string | null | undefined): number {
if (!text) return 0;
return text.replace(/\s+/g, " ").trim().length;
}
/** Absolute normalized delta between two versions of a page body. */
export function contentDelta(before: string | null | undefined, after: string | null | undefined): number {
return Math.abs(normalizedContentLength(after) - normalizedContentLength(before));
}

View file

@ -29,7 +29,21 @@ function relId(value: unknown): number | null {
return null;
}
export async function canEditMissionPlan(
/** Ids of users delegated planning-map access on this mission. */
export function planningMapDelegateIds(mission: Pick<Mission, "classification">): number[] {
const delegates =
(mission.classification as { planningMapDelegates?: Array<number | { id: number }> } | undefined)
?.planningMapDelegates ?? [];
return delegates
.map((entry) => (typeof entry === "object" && entry !== null ? entry.id : entry))
.filter((id): id is number => typeof id === "number");
}
/**
* Curators manage the whole plan: place/edit/delete any marker, toggle the map,
* clear it. `missions:update` holders plus the mission's creator.
*/
export async function canCurateMissionPlan(
payload: Payload,
user: UserRef,
mission: Pick<Mission, "createdBy">,
@ -39,6 +53,32 @@ export async function canEditMissionPlan(
return hasPermission(payload, user, "missions:update");
}
/**
* Contributors can place markers and edit/delete only their own. Curators plus
* per-mission `planningMapDelegates`.
*/
export async function canContributeToMissionPlan(
payload: Payload,
user: UserRef,
mission: Pick<Mission, "createdBy" | "classification">,
): Promise<boolean> {
if (await canCurateMissionPlan(payload, user, mission)) return true;
if (!user) return false;
return planningMapDelegateIds(mission).includes(Number(user.id));
}
/** The planning map is frozen for everyone once the mission is terminal. */
export function isMissionPlanLocked(mission: Pick<Mission, "ownershipAndStatus">): boolean {
const status = mission.ownershipAndStatus?.status;
return status === "Completed" || status === "Cancelled";
}
export interface PlanActor {
userId: number;
/** Curators may touch any marker; delegates only their own. */
canEditAny: boolean;
}
/**
* Load a mission the user is allowed to see (null when hidden or missing).
* depth 1 so the map relation carries its world size.
@ -127,17 +167,21 @@ export async function updateMissionMarker(
mission: Mission,
markerId: number,
input: unknown,
actor: PlanActor,
): Promise<MissionMarker> {
await findMissionMarkerDoc(payload, mission.id, markerId);
const doc = await findMissionMarkerDoc(payload, mission.id, markerId);
if (!actor.canEditAny && relId(doc.createdBy) !== actor.userId) {
throw new Error("You can only edit your own planning markers.");
}
const normalized = normalizeMarkerInput(input, missionWorldSize(mission));
if (!normalized.ok) throw new Error(normalized.error);
const doc = await payload.update({
const updated = await payload.update({
collection: "mission-map-markers",
id: markerId,
data: markerToDocFields(normalized.data),
overrideAccess: true,
});
const marker = markerFromDoc(doc as MissionMapMarkerDoc);
const marker = markerFromDoc(updated as MissionMapMarkerDoc);
if (!marker) throw new Error("Failed to save marker.");
return marker;
}
@ -146,8 +190,12 @@ export async function deleteMissionMarker(
payload: Payload,
missionId: number,
markerId: number,
actor: PlanActor,
): Promise<void> {
await findMissionMarkerDoc(payload, missionId, markerId);
const doc = await findMissionMarkerDoc(payload, missionId, markerId);
if (!actor.canEditAny && relId(doc.createdBy) !== actor.userId) {
throw new Error("You can only delete your own planning markers.");
}
await payload.delete({ collection: "mission-map-markers", id: markerId, overrideAccess: true });
}

View file

@ -7,6 +7,6 @@
- **Schema**: `user` (→ users), `type` (text, e.g. `market:offer`), `title`, `message`, `link` (optional internal path), `read` (checkbox), timestamps.
- **Access**: users read/update only their own; create/delete developer only (creation happens via `notifyUser`, which uses `overrideAccess`).
- **Helper**: `notifyUser(payload, { userId, type?, title, message?, link? })` in `src/lib/notifications/index.ts` — fire-and-forget create. `notificationLabel(type)` maps types to short labels. Notification type strings: `market:offer`, `market:counter`, `market:accept`, `market:reject`, `market:withdrawn`, `market:sold`, `market:expired`.
- **Helper**: `notifyUser(payload, { userId, type?, title, message?, link? })` in `src/lib/notifications/index.ts` — fire-and-forget create. `notificationLabel(type)` maps types to short labels. Notification type strings: `market:offer`, `market:counter`, `market:accept`, `market:reject`, `market:withdrawn`, `market:sold`, `market:expired`, `contribution:xp-granted`, `contribution:xp-revoked`. Muteable types live in `notificationTypes.ts`.
- **UI**: `NotificationsBell` (`src/components/frontend/notifications/NotificationsBell.tsx`) mounted in `SiteHeader`. Polls `/api/user-notifications?limit=12&sort=-createdAt` (cookie auth) every 30s, shows an unread-count badge, dropdown with unread highlight + relative time, click-to-open-link, per-row mark-as-read check button on unread rows (`stopPropagation` — marks read without navigating, dropdown stays open), "Mark all read". Mark-read server actions live in `src/app/(frontend)/notifications/actions.ts` (`markNotificationsRead`, `markAllNotificationsRead`).
- **Wiring**: negotiation flows in `market/actions.ts` notify the counterparty at every step; `expireNegotiationsForListing` notifies interested buyers when a listing sells/cancels/expires.

View file

@ -22,6 +22,8 @@ export const MUTEABLE_NOTIFICATION_TYPES = [
{ label: "Blackjack", value: "blackjack:force-ended" },
{ label: "Blackjack table auto-ended", value: "blackjack:everyone-left" },
{ label: "Role slot promotions", value: "mission:role-promoted" },
{ label: "Contribution XP granted", value: "contribution:xp-granted" },
{ label: "Contribution XP revoked", value: "contribution:xp-revoked" },
] as const;
export type MuteableNotificationType = (typeof MUTEABLE_NOTIFICATION_TYPES)[number]["value"];
export const MUTEABLE_NOTIFICATION_VALUES = MUTEABLE_NOTIFICATION_TYPES.map((t) => t.value);

View file

@ -29,6 +29,7 @@ import {
requireAdminPageAccess,
requirePermission,
} from "@/utils/access-control/hasPermission";
import { recordContribution } from "@/lib/contributions";
type PluginOptions = Parameters<typeof formBuilderPlugin>[0];
@ -279,6 +280,38 @@ export function surveyFormBuilderConfig(): PluginOptions {
}
},
],
afterChange: [
// Award contribution XP for a completed survey. Idempotent by
// submission id, so a retried hook run cannot double-mint.
async ({ doc, req, operation }) => {
if (operation !== "create") return;
const userId = relationId(doc.user);
const formId = relationId(doc.form);
if (userId == null || formId == null) return;
let title = "a survey";
try {
const form = await req.payload.findByID({
collection: "forms",
id: formId,
depth: 0,
req,
});
if (form?.title) title = `"${form.title}"`;
} catch {
// Non-fatal: fall back to the generic summary.
}
await recordContribution(req.payload, {
userId,
type: "survey-completion",
sourceCollection: "form-submissions",
sourceId: doc.id,
summary: `Completed the survey ${title}`,
actorId: userId,
});
},
],
},
},
};

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -117,6 +117,8 @@ import * as migration_20261007_040914_add_reinforcement_pools from './20261007_0
import * as migration_20261007_044017_add_ticket_archival from './20261007_044017_add_ticket_archival';
import * as migration_20261007_183000_add_missing_mcp_key_capabilities from './20261007_183000_add_missing_mcp_key_capabilities';
import * as migration_20261009_160740_add_campaign_on_hold_status from './20261009_160740_add_campaign_on_hold_status';
import * as migration_20261009_185259_add_wiki_featured_curation from './20261009_185259_add_wiki_featured_curation';
import * as migration_20261009_201920_add_contribution_entries from './20261009_201920_add_contribution_entries';
export const migrations = [
{
@ -712,6 +714,16 @@ export const migrations = [
{
up: migration_20261009_160740_add_campaign_on_hold_status.up,
down: migration_20261009_160740_add_campaign_on_hold_status.down,
name: '20261009_160740_add_campaign_on_hold_status'
name: '20261009_160740_add_campaign_on_hold_status',
},
{
up: migration_20261009_185259_add_wiki_featured_curation.up,
down: migration_20261009_185259_add_wiki_featured_curation.down,
name: '20261009_185259_add_wiki_featured_curation',
},
{
up: migration_20261009_201920_add_contribution_entries.up,
down: migration_20261009_201920_add_contribution_entries.down,
name: '20261009_201920_add_contribution_entries'
},
];

View file

@ -89,6 +89,7 @@ export interface Config {
assignments: Assignment;
'assignment-transfers': AssignmentTransfer;
experience: Experience;
'contribution-entries': ContributionEntry;
'user-notifications': UserNotification;
evaluations: Evaluation;
'ribbon-submissions': RibbonSubmission;
@ -189,6 +190,7 @@ export interface Config {
assignments: AssignmentsSelect<false> | AssignmentsSelect<true>;
'assignment-transfers': AssignmentTransfersSelect<false> | AssignmentTransfersSelect<true>;
experience: ExperienceSelect<false> | ExperienceSelect<true>;
'contribution-entries': ContributionEntriesSelect<false> | ContributionEntriesSelect<true>;
'user-notifications': UserNotificationsSelect<false> | UserNotificationsSelect<true>;
evaluations: EvaluationsSelect<false> | EvaluationsSelect<true>;
'ribbon-submissions': RibbonSubmissionsSelect<false> | RibbonSubmissionsSelect<true>;
@ -478,6 +480,8 @@ export interface User {
| 'blackjack:force-ended'
| 'blackjack:everyone-left'
| 'mission:role-promoted'
| 'contribution:xp-granted'
| 'contribution:xp-revoked'
)[]
| null;
};
@ -515,6 +519,8 @@ export interface User {
| 'blackjack:force-ended'
| 'blackjack:everyone-left'
| 'mission:role-promoted'
| 'contribution:xp-granted'
| 'contribution:xp-revoked'
)[]
| null;
};
@ -903,6 +909,12 @@ export interface Role {
| 'form-submissions:delete'
| 'admin:forms:manage'
| 'admin:form-submissions:manage'
| 'contribution-entries:read'
| 'contribution-entries:create'
| 'contribution-entries:update'
| 'contribution-entries:delete'
| 'contribution-entries:moderate'
| 'admin:contribution-entries:manage'
| 'game-rules:read'
| 'game-rules:update'
| 'shims:read'
@ -2983,6 +2995,12 @@ export interface GameEventLog {
| 'form-submissions:delete'
| 'admin:forms:manage'
| 'admin:form-submissions:manage'
| 'contribution-entries:read'
| 'contribution-entries:create'
| 'contribution-entries:update'
| 'contribution-entries:delete'
| 'contribution-entries:moderate'
| 'admin:contribution-entries:manage'
| 'game-rules:read'
| 'game-rules:update'
| 'shims:read'
@ -3040,6 +3058,9 @@ export interface GameEventLog {
| 'wiki-pages'
| 'wiki-revisions'
| 'wiki-templates'
| 'form-submissions'
| 'mission-map-markers'
| 'contribution-entries'
| 'game-servers'
| 'assignment-transfers'
| 'voice-scripts'
@ -3257,6 +3278,12 @@ export interface Profile {
voiceover?: {
xpEarned?: number | null;
};
/**
* Granted crowdsourced contribution XP (wiki, planning markers, surveys, manual). Maintained by the contributions service from the contribution-entries ledger.
*/
contributions?: {
xpEarned?: number | null;
};
};
updatedAt: string;
createdAt: string;
@ -3538,44 +3565,37 @@ export interface Experience {
createdAt: string;
}
/**
* Ledger of crowdsourced contribution XP. Read-only here; grants and revokes flow through the Contributions service and the /contributions page.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "user-notifications".
* via the `definition` "contribution-entries".
*/
export interface UserNotification {
export interface ContributionEntry {
id: number;
user: number | User;
type: 'wiki-page-create' | 'wiki-page-edit' | 'mission-map-marker' | 'survey-completion' | 'manual';
status: 'queued' | 'granted' | 'revoked' | 'expired';
points: number;
sourceCollection: 'wiki-pages' | 'mission-map-markers' | 'form-submissions' | 'manual';
/**
* Machine-readable notification type, e.g. `market:offer`.
* Id of the source document (polymorphic).
*/
type?: string | null;
title: string;
message?: string | null;
sourceId?: number | null;
/**
* Optional internal path to navigate to when clicked.
* Set for planning-marker contributions.
*/
link?: string | null;
read?: boolean | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "evaluations".
*/
export interface Evaluation {
id: number;
mission?: (number | null) | Mission;
summary: string;
/**
* Who submitted this evaluation. Private, only visible to users with evaluations:read.
* Prevents the same contribution from being counted twice.
*/
rater: number | User;
ratee: number | User;
mission: number | Mission;
kind: 'leader-direct' | 'leader-indirect' | 'subordinate';
level: 'exceptional' | 'excellent' | 'proficient' | 'adequate' | 'moderate' | 'under-review';
/**
* Private free-text note. Never shown to normal users; managers only.
*/
comment?: string | null;
idempotencyKey: string;
queuedAt?: string | null;
grantedAt?: string | null;
grantedBy?: (number | null) | User;
revokedAt?: string | null;
revokedBy?: (number | null) | User;
revokedReason?: string | null;
updatedAt: string;
createdAt: string;
}
@ -3649,6 +3669,10 @@ export interface Mission {
* Show this mission's map on the mission page so mission editors can place Arma 3 planning markers that only appear for this mission.
*/
planningMapEnabled?: boolean | null;
/**
* Users granted temporary permission to place and edit their own planning markers on this mission. Managed from the mission page by anyone with missions:update; the map locks for everyone once the mission completes or is cancelled.
*/
planningMapDelegates?: (number | User)[] | null;
missionType: 'Zeus' | 'PvE' | 'PvP' | 'PvPvE' | 'Training' | 'Special';
campaign?: (number | null) | Campaign;
/**
@ -3892,6 +3916,48 @@ export interface ModList {
focalX?: number | null;
focalY?: number | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "user-notifications".
*/
export interface UserNotification {
id: number;
user: number | User;
/**
* Machine-readable notification type, e.g. `market:offer`.
*/
type?: string | null;
title: string;
message?: string | null;
/**
* Optional internal path to navigate to when clicked.
*/
link?: string | null;
read?: boolean | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "evaluations".
*/
export interface Evaluation {
id: number;
/**
* Who submitted this evaluation. Private, only visible to users with evaluations:read.
*/
rater: number | User;
ratee: number | User;
mission: number | Mission;
kind: 'leader-direct' | 'leader-indirect' | 'subordinate';
level: 'exceptional' | 'excellent' | 'proficient' | 'adequate' | 'moderate' | 'under-review';
/**
* Private free-text note. Never shown to normal users; managers only.
*/
comment?: string | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "ribbon-submissions".
@ -4951,6 +5017,16 @@ export interface WikiPage {
lockedBy?: (number | null) | User;
lockedAt?: string | null;
lastEditor?: (number | null) | User;
/**
* Index presentation controls. Only wiki moderators (intelligence division) can change these; they surface pages in the 'Start here' strip on /wiki.
*/
curation?: {
featured?: boolean | null;
/**
* Position in the featured strip (1 first). Blank sorts after numbered picks.
*/
featuredOrder?: number | null;
};
updatedAt: string;
createdAt: string;
}
@ -6485,6 +6561,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
contributionEntries?: {
/**
* Allow clients to find contribution-entries.
*/
find?: boolean | null;
/**
* Allow clients to create contribution-entries.
*/
create?: boolean | null;
/**
* Allow clients to update contribution-entries.
*/
update?: boolean | null;
/**
* Allow clients to delete contribution-entries.
*/
delete?: boolean | null;
};
userNotifications?: {
/**
* Allow clients to find user-notifications.
@ -7698,6 +7792,10 @@ export interface PayloadLockedDocument {
relationTo: 'experience';
value: number | Experience;
} | null)
| ({
relationTo: 'contribution-entries';
value: number | ContributionEntry;
} | null)
| ({
relationTo: 'user-notifications';
value: number | UserNotification;
@ -8595,6 +8693,11 @@ export interface ProfilesSelect<T extends boolean = true> {
| {
xpEarned?: T;
};
contributions?:
| T
| {
xpEarned?: T;
};
};
updatedAt?: T;
createdAt?: T;
@ -8699,6 +8802,29 @@ export interface ExperienceSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "contribution-entries_select".
*/
export interface ContributionEntriesSelect<T extends boolean = true> {
user?: T;
type?: T;
status?: T;
points?: T;
sourceCollection?: T;
sourceId?: T;
mission?: T;
summary?: T;
idempotencyKey?: T;
queuedAt?: T;
grantedAt?: T;
grantedBy?: T;
revokedAt?: T;
revokedBy?: T;
revokedReason?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "user-notifications_select".
@ -8810,6 +8936,7 @@ export interface MissionsSelect<T extends boolean = true> {
| {
map?: T;
planningMapEnabled?: T;
planningMapDelegates?: T;
missionType?: T;
campaign?: T;
customScripts?: T;
@ -9741,6 +9868,12 @@ export interface WikiPagesSelect<T extends boolean = true> {
lockedBy?: T;
lockedAt?: T;
lastEditor?: T;
curation?:
| T
| {
featured?: T;
featuredOrder?: T;
};
updatedAt?: T;
createdAt?: T;
}
@ -10664,6 +10797,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
contributionEntries?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
userNotifications?:
| T
| {

View file

@ -59,6 +59,7 @@ import { PlayerFlags } from "@/collections/game/PlayerFlags";
import { ReinforcementPools } from "@/collections/game/ReinforcementPools";
import { LaborClassifications } from "@/collections/game/LaborClassifications";
import { Experience } from "@/collections/users/Experience";
import { ContributionEntries } from "@/collections/users/ContributionEntries";
import { BankAccounts } from "@/collections/banking/BankAccounts";
import { BankTransactions } from "@/collections/banking/BankTransactions";
import { LedgerEntries } from "@/collections/banking/LedgerEntries";
@ -286,6 +287,7 @@ const collections = [
Assignments,
AssignmentTransfers,
Experience,
ContributionEntries,
UserNotifications,
Evaluations,
RibbonSubmissions,

View file

@ -704,6 +704,20 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "admin:form-submissions:manage", label: "Manage Submissions Admin Page" },
],
},
{
group: "Contributions",
permissions: [
{ value: "contribution-entries:read", label: "Read" },
{ value: "contribution-entries:create", label: "Create" },
{ value: "contribution-entries:update", label: "Update" },
{ value: "contribution-entries:delete", label: "Delete" },
{
value: "contribution-entries:moderate",
label: "Moderate (grant and revoke contribution XP)",
},
{ value: "admin:contribution-entries:manage", label: "Manage Admin Page" },
],
},
// ---- Globals -------------------------------------------------------------
{
@ -1101,6 +1115,12 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"form-submissions:delete",
"admin:forms:manage",
"admin:form-submissions:manage",
"contribution-entries:read",
"contribution-entries:create",
"contribution-entries:update",
"contribution-entries:delete",
"contribution-entries:moderate",
"admin:contribution-entries:manage",
"logistics:manage",
"intelligence:manage",
"profiles:intel_excerpt:update",

View file

@ -0,0 +1,70 @@
import { getPayload } from "payload";
import config from "@payload-config";
/**
* Rebuild every profile's denormalized `progression.contributions.xpEarned`
* bucket from the contribution-entries ledger (granted entries only).
*
* Usage: `bun run src/tools/seed/reconcileContributionXp.ts`.
* Idempotent; run after any manual ledger surgery or if a bucket drifts.
*/
export const reconcileContributionXp = async () => {
const payload = await getPayload({ config });
payload.logger.info("Reconciling contribution XP buckets from the ledger...");
// Sum granted points per user.
const granted = await payload.find({
collection: "contribution-entries",
where: { status: { equals: "granted" } },
limit: 20000,
depth: 0,
overrideAccess: true,
select: { user: true, points: true },
});
const totals = new Map<number, number>();
for (const entry of granted.docs) {
const userRef = entry.user as number | { id: number };
const userId = typeof userRef === "number" ? userRef : userRef?.id;
if (typeof userId !== "number") continue;
totals.set(userId, (totals.get(userId) ?? 0) + (entry.points ?? 0));
}
// Also reset users who have a bucket but no granted entries.
const profiles = await payload.find({
collection: "profiles",
limit: 20000,
depth: 0,
overrideAccess: true,
select: { user: true, progression: { contributions: { xpEarned: true } } },
});
let updated = 0;
for (const profile of profiles.docs) {
const userRef = profile.user as number | { id: number };
const userId = typeof userRef === "number" ? userRef : userRef?.id;
if (typeof userId !== "number") continue;
const expected = totals.get(userId) ?? 0;
const current = profile.progression?.contributions?.xpEarned ?? 0;
if (current === expected) continue;
await payload.update({
collection: "profiles",
id: profile.id,
data: { progression: { contributions: { xpEarned: expected } } },
overrideAccess: true,
});
updated += 1;
payload.logger.info(`Profile user=${userId}: ${current} -> ${expected}`);
}
payload.logger.info("--- reconcile summary ---");
payload.logger.info(`Granted entries scanned: ${granted.docs.length}`);
payload.logger.info(`Profiles scanned: ${profiles.docs.length}`);
payload.logger.info(`Profiles updated: ${updated}`);
};
await reconcileContributionXp();
process.exit(0);

View file

@ -46,7 +46,7 @@ Fire-and-forget create on `game-event-logs`. Always sets `system: true`. Silent
`EVENT_VISIBILITY_POLICIES` maps event types to defaults (`public`, or `restricted` with an any-of `requiredPermissions` gate); `resolveEventVisibility(type, override)` merges per-emit overrides with independent fallbacks. Restricted today: `npc:dialogue`, `flag:set`. The `game-event-logs` read access turns this into a Where clause (public OR required-permission OR actor-is-me; staff/superusers see all). Local API consumers must pass `user` + `overrideAccess: false` to respect it.
### Event types: `EventTypes` constants (~105 types across 15+ categories)
Defined in `eventTypes.ts`. Use these constants for TypeScript narrowing on the `type` field. Categories include: `mission:*`, `finance:*`, `market:*`, `structure:*`, `staff:*`, `logistics:*`, `bank:*`, `notification:*`, `locker:*`, `xp:*`, `ticket:*`, `wiki:*`, `minigame:*`, `attendance:*`, `system:*`.
Defined in `eventTypes.ts`. Use these constants for TypeScript narrowing on the `type` field. Categories include: `mission:*`, `finance:*`, `market:*`, `structure:*`, `staff:*`, `logistics:*`, `bank:*`, `notification:*`, `locker:*`, `contribution:*`, `ticket:*`, `wiki:*`, `minigame:*`, `attendance:*`, `system:*`.
### Display: `formatType(type)` — human-readable label for event types.

View file

@ -12,7 +12,7 @@
- **Emit**: `emitGameEvent(payload, { type, message, actor?, structure?, targetCollection?, targetId?, data?, visibility?, requiredPermissions? })` in `src/utils/event-log/emit.ts`. Silently catches errors (fire-and-forget). Always sets `system: true`; stamps visibility from the policy map.
- **Types**: `EventTypes` constants in `src/utils/event-log/eventTypes.ts` — add new event categories there without touching the collection. Using these constants gives TypeScript narrowing on the `type` field.
- **Wiring**: Server actions in `actions.ts` emit events after successful mutations. `GameStructures` afterChange hook catches admin-panel storage edits. `Structures` beforeChange hook emits `structure:resize`. `PlayerFlags` afterChange/afterDelete hooks emit restricted `flag:set` audit events for every flag write (admin-panel edits and dialogue effects alike).
- **targetCollection options**: `game-structures`, `structures`, `resources`, `assets`, `vehicles`, `game-vehicles`, `game-npcs`, `npc-staffing`, `factions`, `missions`, `campaigns`, `users`, `technologies`, `maps`, `shipments`, `bank-accounts`, `bank-transactions`, `ledger-entries`, `market-listings`, `market-negotiations`, `locker-storages`, `loadouts`, `evaluations`, `tickets`, `wiki-pages`, `wiki-revisions`, `wiki-templates`, `game-servers`, `assignment-transfers`, `player-flags`. If a new collection is added that should be a valid target, add an option here.
- **targetCollection options**: `game-structures`, `structures`, `resources`, `assets`, `vehicles`, `game-vehicles`, `game-npcs`, `npc-staffing`, `factions`, `missions`, `campaigns`, `users`, `technologies`, `maps`, `shipments`, `bank-accounts`, `bank-transactions`, `ledger-entries`, `market-listings`, `market-negotiations`, `locker-storages`, `loadouts`, `evaluations`, `tickets`, `wiki-pages`, `wiki-revisions`, `wiki-templates`, `game-servers`, `assignment-transfers`, `player-flags`, `form-submissions`, `mission-map-markers`, `contribution-entries`. If a new collection is added that should be a valid target, add an option here.
- **Narrative events**: admins/developers can create entries manually in the Payload admin panel with `system: false` for GM-written narrative events. These are visually distinct in the UI (amber accent, book icon).
### UI

View file

@ -52,7 +52,10 @@ interface GameEventInput {
| "promotion-nominations"
| "leadership-transfers"
| "player-flags"
| "reinforcement-pools";
| "reinforcement-pools"
| "form-submissions"
| "mission-map-markers"
| "contribution-entries";
targetId?: number;
data?: Record<string, unknown>;
/**

View file

@ -167,11 +167,17 @@ export const EventTypes = {
MissionMapMarkerUpdate: "mission:map-marker-update",
MissionMapMarkerDelete: "mission:map-marker-delete",
MissionMapMarkersClear: "mission:map-markers-clear",
MissionPlanningDelegates: "mission:planning-delegates",
// Contributions / XP
ContributionQueued: "contribution:queue",
ContributionGranted: "contribution:grant",
ContributionRevoked: "contribution:revoke",
ContributionExpired: "contribution:expire",
// Combat
PlayerKill: "combat:kill",
PlayerDeath: "combat:death",
// Reinforcement pools (Arma Zeus soft limits)
ReinforcementSpawn: "reinforcement:spawn",
ReinforcementRefund: "reinforcement:refund",

View file

@ -0,0 +1,357 @@
import { getPayload } from "payload";
import config from "@payload-config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Mission, User } from "@/payload-types";
import {
expireQueuedEntriesForMission,
getContributionLeaderboard,
getContributionSummary,
grantQueuedEntriesForMission,
recordContribution,
revokeEntry,
} from "@/lib/contributions";
import { createMissionMarker } from "@/lib/intelligence/missionMap";
type Payload = Awaited<ReturnType<typeof getPayload>>;
describe("Contribution / XP service", () => {
let payload: Payload;
const RUN = `contrib-${Date.now().toString(36)}`;
let mapId: number;
let mission: Mission;
let contributor: User;
let other: User;
const userIds: number[] = [];
const makeUser = async (username: string): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: username,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const makeMission = async (label: string): Promise<Mission> =>
(await payload.create({
collection: "missions",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Contribution test mission",
operationType: "main",
createdBy: contributor.id,
classification: {
map: mapId,
missionType: "PvE",
startDateTime: new Date(Date.now() + 2 * 86_400_000).toISOString(),
estimatedDuration: 60,
planningMapEnabled: true,
},
ownershipAndStatus: { authors: [contributor.id], status: "Scheduled", visibility: "unit" },
briefing: [],
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
missionRoles: { maxPlayers: 32, providedRoles: [] },
},
overrideAccess: true,
depth: 1,
})) as unknown as Mission;
const bucketFor = async (userId: number): Promise<number> => {
const res = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
select: { progression: { contributions: { xpEarned: true } } },
});
return res.docs[0]?.progression?.contributions?.xpEarned ?? 0;
};
const makeMarker = async (label: string) =>
createMissionMarker(
payload,
mission,
{ shape: "icon", markerType: "b_inf", color: "Default", position: [100, 100] },
contributor.id,
);
beforeAll(async () => {
payload = await getPayload({ config: await config });
const map = await payload.create({
collection: "maps",
data: {
name: `${RUN} Map`,
worldSizeWidth: 4096,
worldSizeHeight: 4096,
basemapMode: "image",
},
overrideAccess: true,
depth: 0,
});
mapId = map.id;
contributor = await makeUser(`${RUN}-contributor`);
other = await makeUser(`${RUN}-other`);
mission = await makeMission("Op");
});
afterAll(async () => {
if (!payload) return;
for (const userId of userIds) {
await payload
.delete({
collection: "contribution-entries",
where: { user: { equals: userId } },
overrideAccess: true,
})
.catch(() => {});
}
if (mission) {
await payload
.delete({ collection: "missions", id: mission.id, overrideAccess: true })
.catch(() => {});
}
for (const id of userIds) {
for (const collection of ["profiles"] as const) {
const docs = await payload
.find({ collection, where: { user: { equals: id } }, depth: 0, overrideAccess: true })
.catch(() => null);
for (const doc of docs?.docs ?? []) {
await payload.delete({ collection, id: doc.id, overrideAccess: true }).catch(() => {});
}
}
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
});
it("grants an instant manual contribution and bumps the profile bucket", async () => {
const before = await bucketFor(contributor.id);
const result = await recordContribution(payload, {
userId: contributor.id,
type: "manual",
sourceCollection: "manual",
sourceId: contributor.id,
summary: "Helped organize the unit event",
pointsOverride: 7,
dedupeSuffix: "event-1",
});
expect(result.status).toBe("granted");
expect(result.points).toBe(7);
expect(await bucketFor(contributor.id)).toBe(before + 7);
});
it("is idempotent: the same contribution cannot be counted twice", async () => {
const input = {
userId: contributor.id,
type: "manual" as const,
sourceCollection: "manual" as const,
sourceId: contributor.id,
summary: "Duplicate guard",
pointsOverride: 3,
dedupeSuffix: "dup-key",
};
const first = await recordContribution(payload, input);
const second = await recordContribution(payload, input);
expect(second.entryId).toBe(first.entryId);
const count = await payload.count({
collection: "contribution-entries",
where: { idempotencyKey: { equals: `manual:manual:${contributor.id}:dup-key` } },
overrideAccess: true,
});
expect(count.totalDocs).toBe(1);
});
it("queues marker XP and does not grant it until the mission completes", async () => {
const marker = await makeMarker("queue");
const before = await bucketFor(contributor.id);
const result = await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: `Placed a planning marker on "${mission.name}"`,
});
expect(result.status).toBe("queued");
expect(await bucketFor(contributor.id)).toBe(before);
const sweep = await grantQueuedEntriesForMission(payload, mission.id);
expect(sweep.granted).toBeGreaterThanOrEqual(1);
expect(await bucketFor(contributor.id)).toBe(before + 2);
});
it("revokes queued XP when the marker is gone at completion", async () => {
const marker = await makeMarker("vanishes");
await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: `Placed a planning marker on "${mission.name}"`,
});
await payload.delete({
collection: "mission-map-markers",
id: marker.id,
overrideAccess: true,
});
const before = await bucketFor(contributor.id);
const sweep = await grantQueuedEntriesForMission(payload, mission.id);
expect(sweep.revoked).toBeGreaterThanOrEqual(1);
expect(await bucketFor(contributor.id)).toBe(before);
});
it("expires queued XP when the mission is cancelled", async () => {
const marker = await makeMarker("cancelled");
await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: `Placed a planning marker on "${mission.name}"`,
});
const expired = await expireQueuedEntriesForMission(payload, mission.id);
expect(expired).toBeGreaterThanOrEqual(1);
const res = await payload.find({
collection: "contribution-entries",
where: {
and: [
{ sourceId: { equals: marker.id } },
{ sourceCollection: { equals: "mission-map-markers" } },
],
},
depth: 0,
overrideAccess: true,
});
expect(res.docs[0]?.status).toBe("expired");
});
it("pulls granted XP back on revocation", async () => {
const grant = await recordContribution(payload, {
userId: contributor.id,
type: "manual",
sourceCollection: "manual",
sourceId: contributor.id,
summary: "To be revoked",
pointsOverride: 9,
dedupeSuffix: "revoke-me",
});
const before = await bucketFor(contributor.id);
await revokeEntry(payload, grant.entryId as number, { reason: "Reversed by staff." });
expect(await bucketFor(contributor.id)).toBe(before - 9);
});
it("enforces the per-mission marker cap", async () => {
const capMission = await makeMission("Cap");
const capMarker = await createMissionMarker(
payload,
capMission,
{ shape: "icon", markerType: "b_inf", color: "Default", position: [100, 100] },
contributor.id,
);
let granted = 0;
// Cap is 10 per user per mission; the 11th attempt is skipped.
for (let i = 0; i < 11; i += 1) {
const result = await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: capMarker.id + 1000 + i,
missionId: capMission.id,
summary: "cap probe",
});
if (result.status === "queued") granted += 1;
}
expect(granted).toBe(10);
await payload
.delete({ collection: "missions", id: capMission.id, overrideAccess: true })
.catch(() => {});
});
it("preserves other progression fields when updating the bucket", async () => {
// Seed unrelated progression data on the other user's profile.
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: other.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const profileId = profileRes.docs[0]!.id;
await payload.update({
collection: "profiles",
id: profileId,
data: { progression: { minigames: { flappyBird: { gamesPlayed: 5 } }, scoreboard: { infantryKills: 3 } } },
overrideAccess: true,
});
await recordContribution(payload, {
userId: other.id,
type: "manual",
sourceCollection: "manual",
sourceId: other.id,
summary: "Merge safety check",
pointsOverride: 4,
dedupeSuffix: "merge-safety",
});
const after = await payload.findByID({
collection: "profiles",
id: profileId,
depth: 0,
overrideAccess: true,
});
expect(after.progression?.minigames?.flappyBird?.gamesPlayed).toBe(5);
expect(after.progression?.scoreboard?.infantryKills).toBe(3);
expect(after.progression?.contributions?.xpEarned).toBe(4);
});
it("aggregates the leaderboard from granted entries", async () => {
const board = await getContributionLeaderboard(payload, { limit: 25 });
const row = board.find((entry) => entry.userId === contributor.id);
expect(row).toBeDefined();
expect(row!.points).toBeGreaterThan(0);
});
it("hides non-granted rows from non-owners in the summary", async () => {
const summary = await getContributionSummary(payload, contributor.id, {
isOwner: false,
limit: 50,
});
expect(summary.rows.every((row) => row.status === "granted")).toBe(true);
expect(summary.granted).toBeGreaterThan(0);
});
it("exposes a user's own rows (including queued) to the owner", async () => {
const marker = await makeMarker("owner-view");
await recordContribution(payload, {
userId: contributor.id,
type: "mission-map-marker",
sourceCollection: "mission-map-markers",
sourceId: marker.id,
missionId: mission.id,
summary: "owner visibility",
});
const summary = await getContributionSummary(payload, contributor.id, {
isOwner: true,
limit: 100,
});
expect(summary.queued).toBeGreaterThan(0);
expect(summary.rows.some((row) => row.status === "queued")).toBe(true);
// Keep the shared mission clean for any later sweeps.
await expireQueuedEntriesForMission(payload, mission.id);
});
});

View file

@ -23,7 +23,7 @@ import {
type MissionMarker,
} from "@/lib/arma-markers/missionMarkers";
import {
canEditMissionPlan,
canCurateMissionPlan,
clearMissionMarkers,
createMissionMarker,
deleteMissionMarker,
@ -320,10 +320,10 @@ describe("Mission planning map service", () => {
});
it("lets the creator and missions:update holders edit, nobody else", async () => {
expect(await canEditMissionPlan(payload, creator, mission)).toBe(true);
expect(await canEditMissionPlan(payload, editor, mission)).toBe(true);
expect(await canEditMissionPlan(payload, outsider, mission)).toBe(false);
expect(await canEditMissionPlan(payload, null, mission)).toBe(false);
expect(await canCurateMissionPlan(payload, creator, mission)).toBe(true);
expect(await canCurateMissionPlan(payload, editor, mission)).toBe(true);
expect(await canCurateMissionPlan(payload, outsider, mission)).toBe(false);
expect(await canCurateMissionPlan(payload, null, mission)).toBe(false);
});
it("finds unit-visible missions with the world size", async () => {
@ -361,17 +361,26 @@ describe("Mission planning map service", () => {
},
editor.id,
);
const moved = await updateMissionMarker(payload, mission, area.id, {
...area,
position: [1100, 900],
});
const moved = await updateMissionMarker(
payload,
mission,
area.id,
{ ...area, position: [1100, 900] },
{ userId: Number(editor.id), canEditAny: true },
);
expect(moved.position).toEqual([1100, 900]);
expect(moved.size).toEqual([200, 50]);
expect(moved.direction).toBe(30);
// Outside the 4096 m world (+2 km margin): rejected.
await expect(
updateMissionMarker(payload, mission, area.id, { ...area, position: [9000, 9000] }),
updateMissionMarker(
payload,
mission,
area.id,
{ ...area, position: [9000, 9000] },
{ userId: Number(editor.id), canEditAny: true },
),
).rejects.toThrow("on the map");
const listed = await listMissionMarkers(payload, mission.id);
@ -380,14 +389,20 @@ describe("Mission planning map service", () => {
// A marker id from another mission cannot be touched through this one.
const other = await makeMission("Other", null);
try {
await expect(deleteMissionMarker(payload, other.id, icon.id)).rejects.toThrow(
"Marker not found",
);
await expect(
deleteMissionMarker(payload, other.id, icon.id, {
userId: Number(editor.id),
canEditAny: true,
}),
).rejects.toThrow("Marker not found");
} finally {
await payload.delete({ collection: "missions", id: other.id, overrideAccess: true });
}
await deleteMissionMarker(payload, mission.id, icon.id);
await deleteMissionMarker(payload, mission.id, icon.id, {
userId: Number(editor.id),
canEditAny: true,
});
expect((await listMissionMarkers(payload, mission.id)).map((m) => m.id)).toEqual([area.id]);
expect(await clearMissionMarkers(payload, mission.id)).toBe(1);
expect(await listMissionMarkers(payload, mission.id)).toEqual([]);