feat(operations): gate logistics extractions behind an officer review screen
Logistics operation-extraction effects now park as pending_action instead of auto-settling. Officers visit Operations > Extractions to keep, scrap, or expel each line; only kept lines deposit into HQ. A capacity failure leaves the effect retryable (pending_action) so a full HQ can free space and re-resolve. Adds resolveLogisticsExtraction/listPendingExtractions actions + ExtractionReview UI + tests.
This commit is contained in:
parent
40b074a693
commit
acf47a75ea
17 changed files with 46313 additions and 25 deletions
|
|
@ -4,8 +4,13 @@ import config from "@payload-config";
|
|||
import { getPayload } from "payload";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { replayOperationEvent } from "@/lib/operations/reconcile";
|
||||
import { backfillOperationEvents } from "@/lib/operations/rollout";
|
||||
import { listPendingExtractions } from "@/lib/operations/surfaceQuery";
|
||||
import { resolveLogisticsExtraction } from "@/lib/operations/settlementExtraction";
|
||||
import type { ExtractionDecisions } from "@/lib/operations/settlementTypes";
|
||||
import type { PendingExtraction } from "@/lib/operations/surfaceQuery";
|
||||
|
||||
export interface ActionResult<T> {
|
||||
success: boolean;
|
||||
|
|
@ -46,3 +51,47 @@ export async function reconcileBackfill(): Promise<ActionResult<{ processed: num
|
|||
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pending-extraction review queue: logistics extractions parked as
|
||||
* `pending_action` awaiting an officer's keep / scrap / expel decision before
|
||||
* they deposit at HQ. Read is access-controlled (any logged-in user sees what
|
||||
* they may read); the queue is officer-facing in practice.
|
||||
*/
|
||||
export async function getPendingExtractions(): Promise<ActionResult<{ extractions: PendingExtraction[]; total: number }>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!user) return { success: false, error: "Authentication required." };
|
||||
const result = await listPendingExtractions(payload, { id: user.id });
|
||||
return { success: true, data: result };
|
||||
} catch (e) {
|
||||
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Officer resolution of a gated logistics extraction. `decisions` is a
|
||||
* per-line [{ relationTo, id, decision }] array (decision: keep | scrap |
|
||||
* expel); pass `null` to keep every line. Kept lines deposit at HQ; scrap/expel
|
||||
* lines are held back. A capacity failure leaves the effect parked for a retry.
|
||||
*/
|
||||
export async function resolveExtraction(
|
||||
effectId: number,
|
||||
decisions: ExtractionDecisions | null,
|
||||
): Promise<ActionResult<{ status?: string; kept?: number; heldBack?: number }>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!user) return { success: false, error: "Authentication required." };
|
||||
if (!(await hasPermission(payload, user, "operation-readiness:read"))) {
|
||||
return { success: false, error: "Insufficient permissions." };
|
||||
}
|
||||
const result = await resolveLogisticsExtraction(payload, effectId, decisions);
|
||||
if (!result.success) return { success: false, error: result.error ?? "Resolution failed." };
|
||||
return {
|
||||
success: true,
|
||||
data: { status: "applied" },
|
||||
};
|
||||
} catch (e) {
|
||||
return { success: false, error: e instanceof Error ? e.message : "Unknown error" };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
56
src/app/(frontend)/operations/extractions/page.tsx
Normal file
56
src/app/(frontend)/operations/extractions/page.tsx
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { getPendingExtractions } from "@/app/(frontend)/operations/actions";
|
||||
import { ExtractionReview, PageShell, OperationsRealtimeRefresher } from "@/components/frontend/operations";
|
||||
import type { PendingExtraction } from "@/lib/operations/surfaceQuery";
|
||||
|
||||
export const metadata = {
|
||||
title: "Pending Extractions // Operations Review",
|
||||
};
|
||||
|
||||
export default async function PendingExtractionsPage() {
|
||||
const payload = await getPayload({ config });
|
||||
const { user: authUser } = await payload.auth({
|
||||
headers: await nextHeaders(),
|
||||
canSetHeaders: false,
|
||||
});
|
||||
const user = isPayloadUser(authUser) ? authUser : null;
|
||||
|
||||
// Fetch inside a try so a transient failure shows a clean state, not a crash.
|
||||
let extractions: PendingExtraction[] = [];
|
||||
let error: string | null = null;
|
||||
if (user) {
|
||||
const res = await getPendingExtractions();
|
||||
if (res.success) extractions = res.data?.extractions ?? [];
|
||||
else error = res.error ?? "Failed to load pending extractions.";
|
||||
} else {
|
||||
error = "Sign in to review pending extractions.";
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
|
||||
<OperationsRealtimeRefresher />
|
||||
<PageShell
|
||||
title="Pending extractions"
|
||||
meta="EXTRACTION RETURNS // REVIEW & DEPOSIT"
|
||||
dataTour="page-header-extractions"
|
||||
>
|
||||
<p className="max-w-2xl text-sm text-white/70">
|
||||
Logistics extractions are parked here until an officer reviews them. Choose to deposit
|
||||
each line at HQ or hold it back. Kept lines deposit on resolve; capacity is re-checked
|
||||
then, so drop lines to fit a full HQ and retry.
|
||||
</p>
|
||||
</PageShell>
|
||||
|
||||
{error ? (
|
||||
<div role="alert" className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm text-rose-300">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<ExtractionReview extractions={extractions} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -81,10 +81,22 @@ export const OperationEffects: CollectionConfig = {
|
|||
options: [
|
||||
{ label: "Applied", value: "applied" },
|
||||
{ label: "Pending", value: "pending" },
|
||||
{
|
||||
label: "Awaiting Action",
|
||||
value: "pending_action",
|
||||
},
|
||||
{ label: "Failed", value: "failed" },
|
||||
{ label: "Reversed", value: "reversed" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "decisions",
|
||||
type: "json",
|
||||
admin: {
|
||||
description:
|
||||
"Per-item officer resolution for a gated extraction: [{ relationTo, id, decision }]. decision is keep (deposit), scrap, or expel (hold back). Absent = not yet reviewed.",
|
||||
},
|
||||
},
|
||||
{ name: "payload", type: "json" },
|
||||
{
|
||||
name: "reversalOf",
|
||||
|
|
|
|||
|
|
@ -99,6 +99,11 @@ export const sidebarData = {
|
|||
url: "/operations/reservations",
|
||||
icon: ClipboardList,
|
||||
},
|
||||
{
|
||||
title: "Extractions",
|
||||
url: "/operations/extractions",
|
||||
icon: ClipboardCheck,
|
||||
},
|
||||
],
|
||||
navLogistics: [
|
||||
{
|
||||
|
|
|
|||
191
src/components/frontend/operations/ExtractionReview.tsx
Normal file
191
src/components/frontend/operations/ExtractionReview.tsx
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { CornerBrackets } from "./CornerBrackets";
|
||||
import { DOSSIER, STATUS_TONE_CLASSES } from "./tokens";
|
||||
import { resolveExtraction } from "@/app/(frontend)/operations/actions";
|
||||
import type { PendingExtraction } from "@/lib/operations/surfaceQuery";
|
||||
import type { ExtractionLineDecision } from "@/lib/operations/settlementTypes";
|
||||
|
||||
/**
|
||||
* Officer review surface for gated logistics extractions. Each parked effect
|
||||
* renders as a dossier card: the HQ it will deposit to, the manifest lines
|
||||
* (resource + quantity), and a keep / scrap / expel toggle per line. Resolving
|
||||
* deposits the kept lines at HQ and settles the linked reservation; the card
|
||||
* removes itself on success.
|
||||
*
|
||||
* `keep` deposits at HQ, `scrap` / `expel` hold the line back. A line may be
|
||||
* resolved to `keep` even when the HQ is full: capacity is re-checked at
|
||||
* resolve time, so the officer can drop lines to fit and retry.
|
||||
*/
|
||||
const DECISIONS = ["keep", "scrap", "expel"] as const;
|
||||
type Decision = (typeof DECISIONS)[number];
|
||||
|
||||
const DECISION_TONE: Record<Decision, string> = {
|
||||
keep: STATUS_TONE_CLASSES.success,
|
||||
scrap: STATUS_TONE_CLASSES.warning,
|
||||
expel: STATUS_TONE_CLASSES.danger,
|
||||
};
|
||||
|
||||
const DECISION_LABEL: Record<Decision, string> = {
|
||||
keep: "Deposit",
|
||||
scrap: "Scrap",
|
||||
expel: "Hold back",
|
||||
};
|
||||
|
||||
export function ExtractionReview({
|
||||
extractions,
|
||||
}: {
|
||||
extractions: PendingExtraction[];
|
||||
}) {
|
||||
const [remaining, setRemaining] = useState<PendingExtraction[]>(extractions);
|
||||
const [decisions, setDecisions] = useState<Record<number, Record<number, Decision>>>(
|
||||
() => Object.fromEntries(remaining.map((ex) => [ex.id, defaultLines(ex.lines)])),
|
||||
);
|
||||
const [submitting, setSubmitting] = useState<number | null>(null);
|
||||
const [notice, setNotice] = useState<{ tone: "success" | "danger"; text: string } | null>(null);
|
||||
|
||||
function defaultLines(lines: PendingExtraction["lines"]): Record<number, Decision> {
|
||||
const map: Record<number, Decision> = {};
|
||||
for (const line of lines) map[line.resourceId] = "keep";
|
||||
return map;
|
||||
}
|
||||
|
||||
function setDecision(effectId: number, resourceId: number, decision: Decision) {
|
||||
setDecisions((prev) => ({
|
||||
...prev,
|
||||
[effectId]: { ...prev[effectId], [resourceId]: decision },
|
||||
}));
|
||||
}
|
||||
|
||||
async function handleResolve(ex: PendingExtraction) {
|
||||
setSubmitting(ex.id);
|
||||
setNotice(null);
|
||||
try {
|
||||
const lineDecisions: ExtractionLineDecision[] = ex.lines.map((line) => ({
|
||||
relationTo: "resources",
|
||||
id: line.resourceId,
|
||||
decision: decisions[ex.id]?.[line.resourceId] ?? "keep",
|
||||
}));
|
||||
const result = await resolveExtraction(ex.id, lineDecisions);
|
||||
if (!result.success) {
|
||||
setNotice({ tone: "danger", text: result.error ?? "Resolution failed." });
|
||||
return;
|
||||
}
|
||||
setRemaining((prev) => prev.filter((other) => other.id !== ex.id));
|
||||
setNotice({ tone: "success", text: "Extraction resolved and deposited to HQ." });
|
||||
} catch (e) {
|
||||
setNotice({
|
||||
tone: "danger",
|
||||
text: e instanceof Error ? e.message : "Unexpected error.",
|
||||
});
|
||||
} finally {
|
||||
setSubmitting(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (remaining.length === 0) {
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-4">
|
||||
<div className="rounded-lg border border-white/10 bg-card/60 px-6 py-12 text-center">
|
||||
<p className="text-sm font-medium text-white/80">No extractions awaiting review</p>
|
||||
<p className="mt-1.5 text-xs text-muted-foreground">
|
||||
Logistics extractions are parked here until an officer reviews them.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-5">
|
||||
{notice ? (
|
||||
<div
|
||||
role="alert"
|
||||
className={`rounded-md border px-4 py-3 text-sm ${STATUS_TONE_CLASSES[notice.tone]}`}
|
||||
>
|
||||
{notice.text}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{remaining.map((ex) => {
|
||||
const lineDecisions = decisions[ex.id] ?? {};
|
||||
const kept = ex.lines.filter((l) => lineDecisions[l.resourceId] === "keep").length;
|
||||
const held = ex.lines.length - kept;
|
||||
return (
|
||||
<article
|
||||
key={ex.id}
|
||||
aria-label={`Extraction ${ex.operationId}`}
|
||||
className="relative overflow-hidden rounded-lg border border-white/10 bg-card/70"
|
||||
>
|
||||
<CornerBrackets />
|
||||
<header className="flex items-baseline justify-between gap-3 border-b border-white/10 px-5 py-3">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-mono text-sm font-semibold tracking-wide text-white/90">
|
||||
{ex.operationId}
|
||||
</p>
|
||||
<p className="mt-0.5 font-mono text-[11px] text-white/50">
|
||||
{ex.hqName ? `HQ: ${ex.hqName}` : "HQ: unknown"} · {new Date(ex.occurredAt).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className="shrink-0 rounded border border-amber-500/30 bg-amber-500/10 px-2 py-0.5 font-mono text-[10px] uppercase tracking-widest text-amber-300"
|
||||
data-slot="pending-badge"
|
||||
>
|
||||
Awaiting review
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<div className="divide-y divide-white/5">
|
||||
{ex.lines.map((line) => {
|
||||
const current = lineDecisions[line.resourceId] ?? "keep";
|
||||
return (
|
||||
<div key={line.resourceId} className="flex items-center justify-between gap-4 px-5 py-3">
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm text-white/85">{line.resourceName}</p>
|
||||
<p className="font-mono text-xs text-white/45">+{line.amount}</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1" role="group">
|
||||
{DECISIONS.map((d) => (
|
||||
<button
|
||||
key={d}
|
||||
type="button"
|
||||
onClick={() => setDecision(ex.id, line.resourceId, d)}
|
||||
aria-pressed={current === d}
|
||||
className={`rounded px-2.5 py-1 font-mono text-[10px] uppercase tracking-wide transition ${
|
||||
current === d
|
||||
? DECISION_TONE[d]
|
||||
: "border border-white/10 bg-black/30 text-white/40 hover:text-white/60"
|
||||
}`}
|
||||
>
|
||||
{DECISION_LABEL[d]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between border-t border-white/10 px-5 py-3">
|
||||
<span className="font-mono text-[11px] text-white/50">
|
||||
{kept} deposit / {held} held back
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleResolve(ex)}
|
||||
disabled={submitting !== null}
|
||||
aria-busy={submitting === ex.id}
|
||||
className="inline-flex items-center gap-2 rounded border border-white/15 bg-white/10 px-4 py-1.5 text-xs font-medium text-white transition hover:bg-white/20 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{submitting === ex.id ? "Resolving…" : "Resolve"}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { DOSSIER };
|
||||
|
|
@ -19,3 +19,4 @@ export {
|
|||
export { LedgerTable, type LedgerTableFilters } from "./LedgerTable";
|
||||
export { AarView } from "./AarView";
|
||||
export { ReconcilePanel, type ReconcilableEvent } from "./ReconcilePanel";
|
||||
export { ExtractionReview } from "./ExtractionReview";
|
||||
|
|
|
|||
|
|
@ -43,15 +43,20 @@ export async function applyOperationEffect(
|
|||
)) as unknown as OperationEffect | null;
|
||||
if (!effect) return null;
|
||||
if (effect.status === "applied" || effect.status === "reversed") return effect;
|
||||
// pending_action is terminal for the auto-dispatcher: the extraction gate
|
||||
// parked this effect for officer review; applyOperationEffect must not
|
||||
// overwrite it with "applied".
|
||||
if (effect.status === "pending_action") return effect;
|
||||
|
||||
try {
|
||||
const note = await dispatchEffect(payload, effect, req);
|
||||
const { note, status = "applied" } = await dispatchEffect(payload, effect, req);
|
||||
const applied = status === "applied";
|
||||
return (await payload.update({
|
||||
collection: "operation-effects",
|
||||
id: effect.id,
|
||||
data: {
|
||||
status: "applied",
|
||||
appliedAt: new Date().toISOString(),
|
||||
status,
|
||||
appliedAt: applied ? new Date().toISOString() : null,
|
||||
reconciliationNotes: note ?? null,
|
||||
},
|
||||
overrideAccess: true,
|
||||
|
|
@ -73,22 +78,24 @@ export async function applyOperationEffect(
|
|||
}
|
||||
}
|
||||
|
||||
type DispatchResult = { note?: string | null; status?: "applied" | "pending_action" };
|
||||
|
||||
async function dispatchEffect(
|
||||
payload: Payload,
|
||||
effect: OperationEffect,
|
||||
req?: PayloadRequest,
|
||||
): Promise<string | null> {
|
||||
): Promise<DispatchResult> {
|
||||
switch (effect.effectType) {
|
||||
case "operation.started":
|
||||
return null;
|
||||
return { note: null };
|
||||
case "operation.objective-updated":
|
||||
return handleObjective(payload, effect);
|
||||
return { note: await handleObjective(payload, effect) };
|
||||
case "operation.extraction-recorded":
|
||||
return handleExtraction(payload, effect, req);
|
||||
return await handleExtraction(payload, effect, req);
|
||||
case "operation.inventory-recorded":
|
||||
return handleInventoryLoss(payload, effect, req);
|
||||
return { note: await handleInventoryLoss(payload, effect, req) };
|
||||
case "operation.ended":
|
||||
return handleOperationEnd(payload, effect, req);
|
||||
return { note: await handleOperationEnd(payload, effect, req) };
|
||||
default:
|
||||
throw new SettlementFailure("internal-error", `Unknown effect type "${effect.effectType}".`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,13 +24,26 @@ import {
|
|||
parsePlayerLine,
|
||||
} from "./settlementParse";
|
||||
import { SettlementFailure } from "./settlementTypes";
|
||||
import type { ExtractionPayloadV1, LogisticsExtractionLine } from "./settlementTypes";
|
||||
import type {
|
||||
ExtractionDecision,
|
||||
ExtractionDecisions,
|
||||
ExtractionPayloadV1,
|
||||
LogisticsExtractionLine,
|
||||
} from "./settlementTypes";
|
||||
|
||||
/**
|
||||
* Extraction settlement: converts a validated extraction effect into one
|
||||
* provenance-linked HQ deposit (logistics) or personal-locker credit
|
||||
* (player). Both paths preflight the whole manifest before any write, so a
|
||||
* rejected effect never leaves a partial deposit or credit behind.
|
||||
*
|
||||
* Logistics extraction gate: a validated logistics extraction no longer
|
||||
* auto-deposits. Instead `handleExtraction` resolves the manifest's resources
|
||||
* (so an unresolved reference fails at emit) and parks the effect as
|
||||
* `pending_action` for officer review. The officer resolves it later via
|
||||
* `resolveLogisticsExtraction`, which deposits the kept lines and settles the
|
||||
* linked reservation. Scrap/expel lines are held back (no deposit). Player
|
||||
* extractions still auto-apply, since they credit a personal locker.
|
||||
*/
|
||||
|
||||
type AuditUser = Parameters<typeof addResourceInternal>[1];
|
||||
|
|
@ -53,7 +66,7 @@ export async function handleExtraction(
|
|||
payload: Payload,
|
||||
effect: OperationEffect,
|
||||
req?: PayloadRequest,
|
||||
): Promise<string | null> {
|
||||
): Promise<{ note?: string | null; status: "applied" | "pending_action" }> {
|
||||
const parsed = parseExtractionPayload(effect.payload);
|
||||
if (!parsed.ok) throw new SettlementFailure(parsed.code, parsed.message);
|
||||
const ext = parsed.value;
|
||||
|
|
@ -66,19 +79,140 @@ export async function handleExtraction(
|
|||
}
|
||||
// Record-only extraction (legacy `{ player }` shape): AAR evidence, no
|
||||
// inventory movement.
|
||||
if (!ext.kind) return null;
|
||||
if (!ext.kind) return { status: "applied" };
|
||||
|
||||
const rawLines = ext.items ?? [];
|
||||
if (ext.kind === "logistics") {
|
||||
await settleLogisticsExtraction(payload, ext, rawLines, req);
|
||||
} else {
|
||||
await settlePlayerExtraction(payload, effect, ext, rawLines, req);
|
||||
// Gate instead of deposit: resolve the manifest, then park for officer
|
||||
// review. The linked reservation is settled at resolve time, not here.
|
||||
await gateLogisticsExtraction(payload, ext, effect, req);
|
||||
return { status: "pending_action" };
|
||||
}
|
||||
|
||||
await settlePlayerExtraction(payload, effect, ext, ext.items ?? [], req);
|
||||
|
||||
if (ext.reservationKey) {
|
||||
return await settleLinkedReservation(payload, ext, effect.id, req);
|
||||
return { note: await settleLinkedReservation(payload, ext, effect.id, req), status: "applied" };
|
||||
}
|
||||
return null;
|
||||
return { status: "applied" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Extraction gate for logistics deposits. Resolves every manifest resource so
|
||||
* an unresolved reference fails here (at emit), matching player-extraction
|
||||
* behavior, then parks the effect as `pending_action` instead of depositing.
|
||||
* Capacity is intentionally checked at resolve time so an officer can drop
|
||||
* lines (scrap/expel) to fit a full HQ.
|
||||
*/
|
||||
async function gateLogisticsExtraction(
|
||||
payload: Payload,
|
||||
ext: ExtractionPayloadV1,
|
||||
effect: OperationEffect,
|
||||
req?: PayloadRequest,
|
||||
): Promise<void> {
|
||||
for (const raw of ext.items ?? []) {
|
||||
const line = parseLogisticsLine(raw);
|
||||
if (!line.ok) throw new SettlementFailure(line.code, line.message);
|
||||
const resource = await findByIdOrNull(payload, "resources", line.value.resourceId, req);
|
||||
if (!resource) {
|
||||
throw new SettlementFailure(
|
||||
"unresolved-asset",
|
||||
`Resource #${line.value.resourceId} does not exist.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await payload.update({
|
||||
collection: "operation-effects",
|
||||
id: effect.id,
|
||||
data: { status: "pending_action", decisions: null },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
req,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Officer resolution of a gated logistics extraction. Applies the decisions
|
||||
* (keep deposits, scrap/expel hold back), deposits the kept lines at HQ, and
|
||||
* settles the linked reservation. A capacity/full-store failure at resolve
|
||||
* marks the effect `failed` and leaves nothing half-deposited.
|
||||
*/
|
||||
export async function resolveLogisticsExtraction(
|
||||
payload: Payload,
|
||||
effectId: number,
|
||||
decisions: ExtractionDecisions | null,
|
||||
req?: PayloadRequest,
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
const rawEffect = await findByIdOrNull(payload, "operation-effects", effectId, req);
|
||||
const effect = rawEffect as unknown as OperationEffect | null;
|
||||
if (!effect) return { success: false, error: "Effect not found." };
|
||||
if (effect.effectType !== "operation.extraction-recorded") {
|
||||
return { success: false, error: "Effect is not an extraction." };
|
||||
}
|
||||
if (effect.status !== "pending_action") {
|
||||
return { success: false, error: `Effect is not awaiting action (status: ${effect.status}).` };
|
||||
}
|
||||
|
||||
const parsed = parseExtractionPayload(effect.payload);
|
||||
if (!parsed.ok) return { success: false, error: parsed.message };
|
||||
const ext = parsed.value;
|
||||
if (ext.kind !== "logistics") {
|
||||
return { success: false, error: "Only logistics extractions are gated." };
|
||||
}
|
||||
|
||||
// Map decisions by resource id, then keep every line not scrap/expel. A line
|
||||
// not named in the decisions array defaults to keep.
|
||||
const decisionById = new Map<number, ExtractionDecision>();
|
||||
for (const d of decisions ?? []) decisionById.set(d.id, d.decision);
|
||||
const keptRaw: unknown[] = [];
|
||||
for (const raw of ext.items ?? []) {
|
||||
const line = parseLogisticsLine(raw);
|
||||
if (!line.ok) continue;
|
||||
const decision = decisionById.get(line.value.resourceId);
|
||||
if (decision === "scrap" || decision === "expel") continue;
|
||||
keptRaw.push(raw);
|
||||
}
|
||||
|
||||
try {
|
||||
await settleLogisticsExtraction(payload, ext, keptRaw, req);
|
||||
if (ext.reservationKey) {
|
||||
await settleLinkedReservation(payload, ext, effect.id, req);
|
||||
}
|
||||
} catch (error) {
|
||||
const code = error instanceof SettlementFailure ? error.code : "internal-error";
|
||||
const message = error instanceof Error ? error.message : "unknown error";
|
||||
// Leave the effect pending_action so the officer can retry — drop a line
|
||||
// or free HQ space and resolve again. A capacity/storage failure is
|
||||
// recoverable, unlike an unresolved asset (which fails at the gate).
|
||||
await payload.update({
|
||||
collection: "operation-effects",
|
||||
id: effect.id,
|
||||
data: {
|
||||
status: "pending_action",
|
||||
decisions,
|
||||
reconciliationNotes: `${code}: ${message}`,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
req,
|
||||
});
|
||||
return { success: false, error: message };
|
||||
}
|
||||
|
||||
await payload.update({
|
||||
collection: "operation-effects",
|
||||
id: effect.id,
|
||||
data: {
|
||||
status: "applied",
|
||||
decisions,
|
||||
appliedAt: new Date().toISOString(),
|
||||
reconciliationNotes: null,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
req,
|
||||
});
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
async function settleLogisticsExtraction(
|
||||
|
|
|
|||
|
|
@ -91,6 +91,28 @@ export interface LogisticsExtractionLine {
|
|||
amount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Officer resolution for a gated logistics extraction line:
|
||||
* - keep: deposit the line at HQ (the default; lines not named here keep)
|
||||
* - scrap / expel: hold the line back (no deposit), recorded for reporting
|
||||
*/
|
||||
export type ExtractionDecision = "keep" | "scrap" | "expel";
|
||||
|
||||
/** One officer decision for a single extraction line. */
|
||||
export interface ExtractionLineDecision {
|
||||
relationTo: "resources" | "assets" | "vehicles";
|
||||
id: number;
|
||||
decision: ExtractionDecision;
|
||||
}
|
||||
|
||||
/**
|
||||
* The officer's decisions on a gated logistics extraction effect.
|
||||
* Absent (null) means unreviewed: the effect is parked for officer review.
|
||||
* Once resolved this is an array; an empty array means "keep everything".
|
||||
* Each line not named here defaults to "keep".
|
||||
*/
|
||||
export type ExtractionDecisions = ExtractionLineDecision[];
|
||||
|
||||
export interface PlayerExtractionLine {
|
||||
assetId: number;
|
||||
quantity: number;
|
||||
|
|
|
|||
|
|
@ -264,3 +264,139 @@ export async function getOperationAar(
|
|||
reservations,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pending-extraction review queue. Every logistics extraction is gated: its
|
||||
* effect parks as `pending_action` before it deposits at HQ, so a logistics
|
||||
* officer reviews the manifest and decides keep / scrap / expel per line via
|
||||
* `resolveLogisticsExtraction`. This surface lists those parked effects with
|
||||
* the manifest resolved to human-readable lines; no raw payload JSON leaks.
|
||||
*
|
||||
* The queue is permission-gated like the rest of the ledger: a viewer without
|
||||
* `operation-ledger:read` reads through access control and sees only what they
|
||||
* are allowed to.
|
||||
*/
|
||||
export interface PendingExtractionLine {
|
||||
resourceId: number;
|
||||
resourceName: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export interface PendingExtraction {
|
||||
id: number;
|
||||
effectKey: string;
|
||||
operationId: string;
|
||||
occurredAt: string;
|
||||
hqStructureId: number | null;
|
||||
hqName: string | null;
|
||||
notes: string | null;
|
||||
lines: PendingExtractionLine[];
|
||||
}
|
||||
|
||||
export interface PendingExtractionResult {
|
||||
extractions: PendingExtraction[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export async function listPendingExtractions(
|
||||
payload: PayloadType,
|
||||
user: SurfaceUser,
|
||||
): Promise<PendingExtractionResult> {
|
||||
const found = await payload.find({
|
||||
collection: "operation-effects",
|
||||
where: {
|
||||
and: [
|
||||
{ status: { equals: "pending_action" } },
|
||||
{ effectType: { equals: "operation.extraction-recorded" } },
|
||||
],
|
||||
},
|
||||
sort: "-createdAt",
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
user: user ?? undefined,
|
||||
});
|
||||
|
||||
// Collect every resource id and HQ id so we can resolve names in two batched
|
||||
// queries instead of one per line.
|
||||
const resourceIds: number[] = [];
|
||||
const hqIds: number[] = [];
|
||||
const rows = found.docs.map((doc) => {
|
||||
const effect = doc as unknown as {
|
||||
id: number;
|
||||
effectKey: string;
|
||||
operationId: string;
|
||||
createdAt: string;
|
||||
reconciliationNotes: string | null;
|
||||
payload: Record<string, unknown>;
|
||||
};
|
||||
const manifest = effect.payload ?? {};
|
||||
const items = Array.isArray(manifest["items"])
|
||||
? (manifest["items"] as Array<Record<string, unknown>>)
|
||||
: [];
|
||||
const lines = items
|
||||
.map((it) => {
|
||||
const resourceId = it["resourceId"] as number;
|
||||
if (typeof resourceId === "number") resourceIds.push(resourceId);
|
||||
return {
|
||||
resourceId,
|
||||
amount: typeof it["amount"] === "number" ? it["amount"] : 0,
|
||||
};
|
||||
})
|
||||
.filter((line) => typeof line.resourceId === "number");
|
||||
const hqId = manifest["hqStructureId"] as number;
|
||||
if (typeof hqId === "number") hqIds.push(hqId);
|
||||
return { effect, lines };
|
||||
});
|
||||
|
||||
const [resourceRows, hqRows] = await Promise.all([
|
||||
resourceIds.length
|
||||
? payload.find({
|
||||
collection: "resources",
|
||||
where: { id: { in: resourceIds } },
|
||||
limit: resourceIds.length,
|
||||
depth: 0,
|
||||
})
|
||||
: { docs: [] },
|
||||
hqIds.length
|
||||
? payload.find({
|
||||
collection: "game-structures",
|
||||
where: { id: { in: hqIds } },
|
||||
limit: hqIds.length,
|
||||
depth: 0,
|
||||
})
|
||||
: { docs: [] },
|
||||
]);
|
||||
|
||||
const resourceNames = new Map(
|
||||
resourceRows.docs.map((r) => {
|
||||
const row = r as { id: number; name: string };
|
||||
return [row.id, row.name] as const;
|
||||
}),
|
||||
);
|
||||
const hqNames = new Map(
|
||||
hqRows.docs.map((r) => {
|
||||
const row = r as { id: number; name: string };
|
||||
return [row.id, row.name] as const;
|
||||
}),
|
||||
);
|
||||
|
||||
const extractions: PendingExtraction[] = rows.map(({ effect, lines }) => {
|
||||
const hqId = (effect.payload["hqStructureId"] as number) ?? null;
|
||||
return {
|
||||
id: effect.id,
|
||||
effectKey: effect.effectKey,
|
||||
operationId: effect.operationId,
|
||||
occurredAt: effect.createdAt,
|
||||
hqStructureId: hqId,
|
||||
hqName: hqId != null ? hqNames.get(hqId) ?? null : null,
|
||||
notes: effect.reconciliationNotes,
|
||||
lines: lines.map((line) => ({
|
||||
resourceId: line.resourceId,
|
||||
resourceName: resourceNames.get(line.resourceId) ?? `Resource #${line.resourceId}`,
|
||||
amount: line.amount,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
return { extractions, total: extractions.length };
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because one or more lines are too long
|
|
@ -150,6 +150,7 @@ import * as migration_20261020_201242_add_room_fixture_blocks_station from './20
|
|||
import * as migration_20261022_170228_add_vehicle_mod_field from './20261022_170228_add_vehicle_mod_field';
|
||||
import * as migration_20261026_073228_add_vehicle_category_static_and_drone from './20261026_073228_add_vehicle_category_static_and_drone';
|
||||
import * as migration_20261026_195910_add_vehicle_disallowed_cargo_field from './20261026_195910_add_vehicle_disallowed_cargo_field';
|
||||
import * as migration_20261026_205453_add_operation_effects_pending_action_and_decisions from './20261026_205453_add_operation_effects_pending_action_and_decisions';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -912,4 +913,9 @@ export const migrations = [
|
|||
down: migration_20261026_195910_add_vehicle_disallowed_cargo_field.down,
|
||||
name: '20261026_195910_add_vehicle_disallowed_cargo_field',
|
||||
},
|
||||
{
|
||||
up: migration_20261026_205453_add_operation_effects_pending_action_and_decisions.up,
|
||||
down: migration_20261026_205453_add_operation_effects_pending_action_and_decisions.down,
|
||||
name: '20261026_205453_add_operation_effects_pending_action_and_decisions'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -6480,7 +6480,19 @@ export interface OperationEffect {
|
|||
| 'operation.objective-updated'
|
||||
| 'operation.extraction-recorded'
|
||||
| 'operation.inventory-recorded';
|
||||
status: 'applied' | 'pending' | 'failed' | 'reversed';
|
||||
status: 'applied' | 'pending' | 'pending_action' | 'failed' | 'reversed';
|
||||
/**
|
||||
* Per-item officer resolution for a gated extraction: [{ relationTo, id, decision }]. decision is keep (deposit), scrap, or expel (hold back). Absent = not yet reviewed.
|
||||
*/
|
||||
decisions?:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
}
|
||||
| unknown[]
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null;
|
||||
payload?:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
|
|
@ -11971,6 +11983,7 @@ export interface OperationEffectsSelect<T extends boolean = true> {
|
|||
effectKey?: T;
|
||||
effectType?: T;
|
||||
status?: T;
|
||||
decisions?: T;
|
||||
payload?: T;
|
||||
reversalOf?: T;
|
||||
reversedBy?: T;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { getTestPayload } from "../helpers/get-test-payload";
|
|||
import { Payload } from "payload";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { applyEconomyEffect, DEFAULT_ECONOMY_CAPS } from "@/lib/operations/economy";
|
||||
import { resolveLogisticsExtraction } from "@/lib/operations/settlementExtraction";
|
||||
import { ECONOMY_NOTE_PREFIX, type EconomyRecord } from "@/lib/operations/economyConfig";
|
||||
import { resetMarketStateDocs } from "@/lib/economy/consumption";
|
||||
import { applyTransaction, ensurePersonalAccount } from "@/lib/banking";
|
||||
|
|
@ -148,7 +149,13 @@ async function hookExtraction(
|
|||
expect(effects.docs).toHaveLength(1);
|
||||
const effect = effects.docs[0] as { id: number; status: string };
|
||||
opEffectIds.push(effect.id);
|
||||
expect(effect.status).toBe("applied");
|
||||
// A player extraction applies immediately; a logistics extraction is gated
|
||||
// and parks as pending_action. Resolve it (keep all) so the returned effect
|
||||
// is the applied, market-feeding one the adapter expects.
|
||||
if (effect.status === "pending_action") {
|
||||
const resolved = await resolveLogisticsExtraction(payload, effect.id, null);
|
||||
expect(resolved.success).toBe(true);
|
||||
}
|
||||
return { effectId: effect.id, eventId: sync.eventId as string };
|
||||
}
|
||||
|
||||
|
|
|
|||
242
tests/int/operation-extractions-surface.int.spec.ts
Normal file
242
tests/int/operation-extractions-surface.int.spec.ts
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
import { getTestPayload } from "../helpers/get-test-payload";
|
||||
import { Payload } from "payload";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { listPendingExtractions } from "@/lib/operations/surfaceQuery";
|
||||
import type { Structure } from "@/payload-types";
|
||||
|
||||
let payload: Payload;
|
||||
const RUN = `extractions-surf-${Date.now().toString(36)}`;
|
||||
|
||||
const userIds: number[] = [];
|
||||
const resourceIds: number[] = [];
|
||||
const structureIds: number[] = [];
|
||||
const blueprintIds: number[] = [];
|
||||
const effectIds: number[] = [];
|
||||
let serverId: number;
|
||||
let mapId: number;
|
||||
let resourceA: number;
|
||||
let resourceB: number;
|
||||
let superUserId: number;
|
||||
let plainUserId: number;
|
||||
|
||||
async function makeUser(label: string): Promise<number> {
|
||||
const user = await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username: `${RUN}-${label}`,
|
||||
discordUsername: `${RUN}-${label}-discord`,
|
||||
steamId: `${RUN}-steam-${label}`,
|
||||
password: "Test1234",
|
||||
displayName: `${RUN} ${label}`,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
userIds.push(user.id);
|
||||
return user.id;
|
||||
}
|
||||
|
||||
async function makeResource(label: string): Promise<number> {
|
||||
const resource = await payload.create({
|
||||
collection: "resources",
|
||||
data: {
|
||||
name: `${RUN} ${label}`,
|
||||
codeName: `${RUN}-${label}`,
|
||||
approvalStatus: "in_progress",
|
||||
type: "physical",
|
||||
baseValue: 1,
|
||||
rarity: "common",
|
||||
unitOfMeasure: "kg",
|
||||
massPerUnit: 1,
|
||||
gridWidth: 1,
|
||||
gridHeight: 1,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
resourceIds.push(resource.id);
|
||||
return resource.id;
|
||||
}
|
||||
|
||||
async function makeHq(label: string, blueprintId: number): Promise<number> {
|
||||
const structure = await payload.create({
|
||||
collection: "game-structures",
|
||||
data: {
|
||||
name: `${RUN} ${label}`,
|
||||
type: blueprintId,
|
||||
map: mapId,
|
||||
coordinates: [100, 100],
|
||||
constructionStatus: "complete",
|
||||
storedResources: [],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
structureIds.push(structure.id);
|
||||
return structure.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a real logistics extraction sync event; the pipeline derives the
|
||||
* operation-event + extraction-recorded effect and parks it as `pending_action`.
|
||||
* Returns the created effect.
|
||||
*/
|
||||
async function emitExtraction(
|
||||
label: string,
|
||||
operationId: string,
|
||||
hqId: number,
|
||||
resourceId: number,
|
||||
amount: number,
|
||||
): Promise<number> {
|
||||
const syncDoc = await payload.create({
|
||||
collection: "arma-sync-events",
|
||||
data: {
|
||||
eventId: `${RUN}-${label}`,
|
||||
server: serverId,
|
||||
type: "operation.extraction",
|
||||
occurredAt: new Date().toISOString(),
|
||||
payload: {
|
||||
operationId,
|
||||
version: 1,
|
||||
actorId: null,
|
||||
kind: "logistics",
|
||||
hqStructureId: hqId,
|
||||
items: [{ resourceId, amount }],
|
||||
},
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
const opEvents = await payload.find({
|
||||
collection: "operation-events",
|
||||
where: { sourceEvent: { equals: syncDoc.id } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const effects = await payload.find({
|
||||
collection: "operation-effects",
|
||||
where: { operationEvent: { equals: opEvents.docs[0].id } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const effectId = effects.docs[0].id as number;
|
||||
effectIds.push(effectId);
|
||||
return effectId;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getTestPayload();
|
||||
|
||||
superUserId = await makeUser("admin");
|
||||
plainUserId = await makeUser("soldier");
|
||||
|
||||
const server = await payload.create({
|
||||
collection: "game-servers",
|
||||
data: { serverId: `${RUN}-srv`, name: `${RUN} Server`, status: "online" },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
serverId = server.id;
|
||||
|
||||
const map = await payload.create({
|
||||
collection: "maps",
|
||||
data: { name: `${RUN} Map`, worldSizeWidth: 4096, worldSizeHeight: 4096, basemapMode: "image" },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
mapId = map.id;
|
||||
|
||||
resourceA = await makeResource("Ammo");
|
||||
resourceB = await makeResource("Fuel");
|
||||
|
||||
const blueprint = await payload.create({
|
||||
collection: "structures",
|
||||
data: {
|
||||
name: `${RUN} HQ Depot`,
|
||||
codeName: `${RUN}-hq-depot`,
|
||||
approvalStatus: "in_progress",
|
||||
description: { root: { children: [{ text: "" }], direction: "ltr", format: "" }, version: 1 } as unknown as Structure["description"],
|
||||
category: "logistics",
|
||||
materials: [{ resource: resourceA, amount: 1 }],
|
||||
constructionDurationMinutes: 1,
|
||||
terrainType: "land",
|
||||
maxHealth: 100,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
blueprintIds.push(blueprint.id);
|
||||
|
||||
const hq = await makeHq("HQ", blueprint.id);
|
||||
|
||||
// Two parked logistics extractions awaiting an officer's decision.
|
||||
await emitExtraction(`${RUN}-evt-keep`, `${RUN}-op-keep`, hq, resourceA, 25);
|
||||
await emitExtraction(`${RUN}-evt-hold`, `${RUN}-op-hold`, hq, resourceB, 40);
|
||||
// A third logistics extraction that the officer already resolved (applied)
|
||||
// must NOT surface as pending.
|
||||
const doneEffectId = await emitExtraction(`${RUN}-evt-done`, `${RUN}-op-done`, hq, resourceA, 10);
|
||||
await payload.update({
|
||||
collection: "operation-effects",
|
||||
id: doneEffectId,
|
||||
data: { status: "applied", appliedAt: new Date().toISOString() },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (!payload) return;
|
||||
for (const id of effectIds) {
|
||||
await payload.delete({ collection: "operation-effects", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of structureIds) {
|
||||
await payload.delete({ collection: "game-structures", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of blueprintIds) {
|
||||
await payload.delete({ collection: "structures", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of resourceIds) {
|
||||
await payload.delete({ collection: "resources", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
|
||||
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
|
||||
for (const id of userIds) {
|
||||
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
describe("listPendingExtractions surface", () => {
|
||||
it("returns only pending_action extractions with resolved resource and HQ names", async () => {
|
||||
const result = await listPendingExtractions(payload, { id: superUserId });
|
||||
|
||||
expect(result.total).toBe(2);
|
||||
expect(result.extractions).toHaveLength(2);
|
||||
|
||||
const byOp = Object.fromEntries(result.extractions.map((ex) => [ex.operationId, ex]));
|
||||
expect(byOp[`${RUN}-op-keep`]).toBeDefined();
|
||||
expect(byOp[`${RUN}-op-hold`]).toBeDefined();
|
||||
expect(byOp[`${RUN}-op-done`]).toBeUndefined();
|
||||
|
||||
const keep = byOp[`${RUN}-op-keep`];
|
||||
expect(keep?.hqName).toContain("HQ");
|
||||
expect(keep?.hqStructureId).toBeGreaterThan(0);
|
||||
expect(keep?.lines).toEqual([
|
||||
{ resourceId: resourceA, resourceName: `${RUN} Ammo`, amount: 25 },
|
||||
]);
|
||||
expect(keep?.notes).toBeNull();
|
||||
|
||||
const hold = byOp[`${RUN}-op-hold`];
|
||||
expect(hold?.lines).toEqual([
|
||||
{ resourceId: resourceB, resourceName: `${RUN} Fuel`, amount: 40 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("opens the queue to any authenticated viewer (read is access-controlled open)", async () => {
|
||||
const forSoldier = await listPendingExtractions(payload, { id: plainUserId });
|
||||
expect(forSoldier.total).toBe(2);
|
||||
expect(forSoldier.extractions.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
|
@ -2,6 +2,7 @@ import { getTestPayload } from "../helpers/get-test-payload";
|
|||
import { Payload } from "payload";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { processOperationEvent } from "@/lib/operations/process";
|
||||
import { resolveLogisticsExtraction } from "@/lib/operations/settlementExtraction";
|
||||
import { reserveOperationAssets, type SettlementRecord } from "@/lib/operations/allocation";
|
||||
import { ensureLockerStorage, getLockerGridDimensions } from "@/lib/locker";
|
||||
import type { GameStructure, LockerStorage, OperationReservation, Structure } from "@/payload-types";
|
||||
|
|
@ -493,8 +494,27 @@ describe("Operation settlement", () => {
|
|||
expect(effects).toHaveLength(1);
|
||||
const effect = effects[0];
|
||||
expect(effect.effectType).toBe("operation.extraction-recorded");
|
||||
expect(effect.status).toBe("applied");
|
||||
expect(effect.appliedAt).toBeTruthy();
|
||||
|
||||
// Gated: the logistics extraction parks for officer review instead of
|
||||
// auto-depositing. Nothing is deposited and the reservation is untouched.
|
||||
expect(effect.status).toBe("pending_action");
|
||||
expect(effect.appliedAt).toBeNull();
|
||||
expect(effect.decisions).toBeNull();
|
||||
expect(await storedAmountAt(hqId, resourceAId)).toBe(0);
|
||||
expect((await findReservation(reservationKey))?.status).not.toBe("settled");
|
||||
|
||||
// The officer resolves it keeping everything (decisions = null => keep all).
|
||||
const resolved = await resolveLogisticsExtraction(payload, effect.id, null);
|
||||
expect(resolved.success).toBe(true);
|
||||
|
||||
// Re-read: the effect is now applied after the officer's resolution.
|
||||
const afterResolve = await payload.findByID({
|
||||
collection: "operation-effects",
|
||||
id: effect.id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect((afterResolve as unknown as typeof effect).status).toBe("applied");
|
||||
|
||||
// Exactly one deposit: 25 units at the designated HQ, none at the origin.
|
||||
expect(await storedAmountAt(hqId, resourceAId)).toBe(25);
|
||||
|
|
@ -602,7 +622,19 @@ describe("Operation settlement", () => {
|
|||
|
||||
const effects = await effectsForOperation(operationId);
|
||||
expect(effects).toHaveLength(1);
|
||||
expect(effects[0].status).toBe("applied");
|
||||
expect(effects[0].status).toBe("pending_action");
|
||||
|
||||
// Gated: an officer resolves the parked extraction, which then deposits.
|
||||
const resolved = await resolveLogisticsExtraction(payload, effects[0].id, null);
|
||||
expect(resolved.success).toBe(true);
|
||||
|
||||
const afterResolve = await payload.findByID({
|
||||
collection: "operation-effects",
|
||||
id: effects[0].id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect((afterResolve as unknown as { status: string }).status).toBe("applied");
|
||||
expect(await storedAmountAt(hqId, resourceAId)).toBe(10);
|
||||
});
|
||||
|
||||
|
|
@ -666,8 +698,23 @@ describe("Operation settlement", () => {
|
|||
|
||||
const effects = await effectsForOperation(operationId);
|
||||
expect(effects).toHaveLength(1);
|
||||
expect(effects[0].status).toBe("failed");
|
||||
expect(effects[0].reconciliationNotes).toContain("hq-capacity");
|
||||
// Gated: the effect parks for officer review (assets resolved) before it can
|
||||
// fail on capacity. Only after the officer resolves does the full HQ surface.
|
||||
expect(effects[0].status).toBe("pending_action");
|
||||
expect(await storedAmountAt(hqId, resourceAId)).toBe(0);
|
||||
|
||||
const resolved = await resolveLogisticsExtraction(payload, effects[0].id, null);
|
||||
expect(resolved.success).toBe(false);
|
||||
|
||||
// Still pending (recoverable): the officer can retry once HQ frees up.
|
||||
const afterResolve = await payload.findByID({
|
||||
collection: "operation-effects",
|
||||
id: effects[0].id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect((afterResolve as unknown as { status: string }).status).toBe("pending_action");
|
||||
expect((afterResolve as unknown as { reconciliationNotes: string }).reconciliationNotes).toContain("hq-capacity");
|
||||
expect(await storedAmountAt(hqId, resourceAId)).toBe(0);
|
||||
});
|
||||
|
||||
|
|
@ -777,6 +824,10 @@ describe("Operation settlement", () => {
|
|||
consumed: { cargo: [{ resourceId: resourceAId, amount: 6 }] },
|
||||
});
|
||||
|
||||
// Officer reviews and keeps the extracted cargo before the mission fails.
|
||||
const extractEffects = await effectsForOperation(operationId);
|
||||
await resolveLogisticsExtraction(payload, extractEffects[0].id, null);
|
||||
|
||||
await emitRawEvent(`${RUN}-evt-fail-end`, "operation.end", {
|
||||
operationId,
|
||||
version: 1,
|
||||
|
|
@ -819,6 +870,146 @@ describe("Operation settlement", () => {
|
|||
expect(freshExtraction.reversedBy).toBeNull();
|
||||
});
|
||||
|
||||
async function makeSecondResource(): Promise<number> {
|
||||
const resource = await payload.create({
|
||||
collection: "resources",
|
||||
data: {
|
||||
name: `${RUN} Scrap Ore`,
|
||||
codeName: `${RUN}-scrap-ore`,
|
||||
approvalStatus: "in_progress",
|
||||
type: "physical",
|
||||
baseValue: 1,
|
||||
rarity: "common",
|
||||
unitOfMeasure: "kg",
|
||||
massPerUnit: 1,
|
||||
gridWidth: 1,
|
||||
gridHeight: 1,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
resourceIds.push(resource.id);
|
||||
return resource.id;
|
||||
}
|
||||
|
||||
it("holds back scrap/expel lines and deposits only the kept lines on resolve", async () => {
|
||||
const secondResourceId = await makeSecondResource();
|
||||
const operationId = `${RUN}-op-scrap`;
|
||||
const hqId = await makeStructure("hq-scrap", hqBlueprintId);
|
||||
|
||||
await emitRawEvent(`${RUN}-evt-scrap`, "operation.extraction", {
|
||||
operationId,
|
||||
version: 1,
|
||||
actorId: extractorId,
|
||||
kind: "logistics",
|
||||
hqStructureId: hqId,
|
||||
items: [
|
||||
{ resourceId: resourceAId, amount: 20 },
|
||||
{ resourceId: secondResourceId, amount: 30 },
|
||||
],
|
||||
});
|
||||
const effect = (await effectsForOperation(operationId))[0];
|
||||
expect(effect.status).toBe("pending_action");
|
||||
|
||||
// Keep resourceA, scrap the second resource.
|
||||
const decisions = [
|
||||
{ relationTo: "resources" as const, id: secondResourceId, decision: "scrap" as const },
|
||||
];
|
||||
const resolved = await resolveLogisticsExtraction(payload, effect.id, decisions);
|
||||
expect(resolved.success).toBe(true);
|
||||
|
||||
// Only the kept line deposits; the scraped line is held back entirely.
|
||||
expect(await storedAmountAt(hqId, resourceAId)).toBe(20);
|
||||
expect(await storedAmountAt(hqId, secondResourceId)).toBe(0);
|
||||
|
||||
const afterResolve = await payload.findByID({
|
||||
collection: "operation-effects",
|
||||
id: effect.id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect((afterResolve as unknown as { status: string }).status).toBe("applied");
|
||||
expect((afterResolve as unknown as { decisions: unknown }).decisions).toEqual(decisions);
|
||||
});
|
||||
|
||||
it("lets the officer make room on a full HQ by expelling a line", async () => {
|
||||
const secondResourceId = await makeSecondResource();
|
||||
const operationId = `${RUN}-op-fit`;
|
||||
// cappedBlueprintId caps at 5 mass; pre-stock 3 so a kept line of 1 fits.
|
||||
const hqId = await makeStructure("hq-fit", cappedBlueprintId);
|
||||
await payload.update({
|
||||
collection: "game-structures",
|
||||
id: hqId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
data: {
|
||||
storedResources: [
|
||||
{ resource: resourceAId, amount: 3, gridX: 0, gridY: 0, rotated: false },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
await emitRawEvent(`${RUN}-evt-fit`, "operation.extraction", {
|
||||
operationId,
|
||||
version: 1,
|
||||
actorId: extractorId,
|
||||
kind: "logistics",
|
||||
hqStructureId: hqId,
|
||||
items: [
|
||||
{ resourceId: resourceAId, amount: 10 },
|
||||
{ resourceId: secondResourceId, amount: 1 },
|
||||
],
|
||||
});
|
||||
const effect = (await effectsForOperation(operationId))[0];
|
||||
|
||||
// Keeping everything overflows the cap -> resolve fails but stays pending
|
||||
// (retryable) so the officer can retry after freeing room.
|
||||
const keepAll = await resolveLogisticsExtraction(payload, effect.id, null);
|
||||
expect(keepAll.success).toBe(false);
|
||||
|
||||
const afterKeepAll = await payload.findByID({
|
||||
collection: "operation-effects",
|
||||
id: effect.id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect((afterKeepAll as unknown as { status: string }).status).toBe("pending_action");
|
||||
expect(
|
||||
(afterKeepAll as unknown as { reconciliationNotes: string }).reconciliationNotes,
|
||||
).toContain("hq-capacity");
|
||||
|
||||
// Expel the big resourceA line so the small line fits (3 + 1 = 5 <= cap).
|
||||
const decisions = [{ relationTo: "resources" as const, id: resourceAId, decision: "expel" as const }];
|
||||
const resolved = await resolveLogisticsExtraction(payload, effect.id, decisions);
|
||||
expect(resolved.success).toBe(true);
|
||||
|
||||
// resourceA is held back (unchanged); only the kept secondResource deposits.
|
||||
expect(await storedAmountAt(hqId, resourceAId)).toBe(3);
|
||||
expect(await storedAmountAt(hqId, secondResourceId)).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects resolving an effect that is no longer awaiting action", async () => {
|
||||
const operationId = `${RUN}-op-status`;
|
||||
const hqId = await makeStructure("hq-status", hqBlueprintId);
|
||||
|
||||
await emitRawEvent(`${RUN}-evt-status`, "operation.extraction", {
|
||||
operationId,
|
||||
version: 1,
|
||||
actorId: extractorId,
|
||||
kind: "logistics",
|
||||
hqStructureId: hqId,
|
||||
items: [{ resourceId: resourceAId, amount: 5 }],
|
||||
});
|
||||
const effect = (await effectsForOperation(operationId))[0];
|
||||
|
||||
const ok = await resolveLogisticsExtraction(payload, effect.id, null);
|
||||
expect(ok.success).toBe(true);
|
||||
|
||||
const again = await resolveLogisticsExtraction(payload, effect.id, null);
|
||||
expect(again.success).toBe(false);
|
||||
expect(again.error).toMatch(/not awaiting action/i);
|
||||
});
|
||||
|
||||
it("updates the AAR for an objective-only operation without touching inventory", async () => {
|
||||
const operationId = `${RUN}-op-obj`;
|
||||
const hqId = await makeStructure("hq-obj", hqBlueprintId);
|
||||
|
|
|
|||
Loading…
Reference in a new issue