1
0
Fork 0
polaris-task-force/src/lib/shipping/lifecycle.ts
Z8MB1E f8ce3f3dcc feat(logistics): timestamp shipment lifecycle with client relay
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-09-20 02:43:29 -04:00

418 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { Payload } from "payload";
import type { GameStructure, GameVehicle, Shipment, Vehicle } from "@/payload-types";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { notifyUser } from "@/lib/notifications";
import { checkStorageDeposit, storageViolationMessage } from "@/lib/storageRules";
import { isPointArray, type MapPoint } from "@/lib/map/points";
import { maybeStartConstruction } from "@/lib/map/construction";
type ShipmentDoc = Shipment & {
transportVehicle: GameVehicle & { type: Vehicle };
origin: GameStructure;
destination: GameStructure;
};
export interface AdvanceLog {
error?: (message: string) => void;
}
function docId(value: GameStructure | GameVehicle | number): number {
return typeof value === "object" ? value.id : value;
}
/**
* One idempotent lifecycle step for an active shipment, derived entirely from
* timestamps so any caller (game tick, detail-page load, server actions) can
* advance it without waiting for the next tick:
*
* - fuel burn is continuous: fuelConsumed = fuelCost x elapsed fraction, and
* the vehicle drains by the delta since the stored value (re-running at the
* same instant writes the same numbers),
* - dispatched flips to in_transit as soon as the vehicle is moving,
* - arrival runs the full delivery (storage rules, cargo credit, auto-return,
* events, notification) and is guarded by a fresh status re-check.
*/
export async function advanceShipment(
payload: Payload,
shipmentDoc: ShipmentDoc,
now: Date = new Date(),
log?: AdvanceLog,
): Promise<void> {
if (shipmentDoc.status !== "dispatched" && shipmentDoc.status !== "in_transit") return;
if (!shipmentDoc.dispatchedAt || !shipmentDoc.estimatedArrival) return;
const vehicle = shipmentDoc.transportVehicle;
if (!vehicle || typeof vehicle === "number") return;
const vehicleType = typeof vehicle.type === "object" ? vehicle.type : null;
if (!vehicleType) return;
const dispatchedAt = new Date(shipmentDoc.dispatchedAt).getTime();
const estimatedArrival = new Date(shipmentDoc.estimatedArrival).getTime();
const totalDurationMs = Math.max(1, estimatedArrival - dispatchedAt);
const elapsedMs = Math.max(0, Math.min(now.getTime() - dispatchedAt, totalDurationMs));
const targetFuelConsumed = Math.min(
shipmentDoc.fuelCost,
shipmentDoc.fuelCost * (elapsedMs / totalDurationMs),
);
const fuelDelta = targetFuelConsumed - (shipmentDoc.fuelConsumed ?? 0);
if (vehicle.currentFuel < fuelDelta) {
await payload.update({
collection: "shipments",
id: shipmentDoc.id,
data: {
status: "stranded",
failureReason: "Vehicle ran out of fuel during transit.",
},
});
await payload.update({
collection: "game-vehicles",
id: vehicle.id,
data: { status: "damaged" },
});
await emitGameEvent(payload, {
type: EventTypes.ShipmentFail,
message: `Shipment "${shipmentDoc.name ?? `SHP-${shipmentDoc.id}`}" stranded: vehicle out of fuel`,
structure: docId(shipmentDoc.origin),
targetCollection: "shipments",
targetId: shipmentDoc.id,
data: { reason: "out_of_fuel", vehicleId: vehicle.id },
});
return;
}
await payload.update({
collection: "game-vehicles",
id: vehicle.id,
data: { currentFuel: Math.max(0, vehicle.currentFuel - fuelDelta) },
});
if (now.getTime() >= estimatedArrival) {
await completeShipment(payload, shipmentDoc, targetFuelConsumed, now, log);
return;
}
await payload.update({
collection: "shipments",
id: shipmentDoc.id,
data: {
fuelConsumed: targetFuelConsumed,
status: "in_transit",
},
});
}
async function completeShipment(
payload: Payload,
shipment: ShipmentDoc,
finalFuelConsumed: number,
now: Date,
log?: AdvanceLog,
): Promise<void> {
const vehicle = shipment.transportVehicle;
const destinationId = docId(shipment.destination);
const originId = docId(shipment.origin);
// Someone may have completed this shipment between the caller's fetch and
// now (concurrent page loads, the tick racing an action): re-check the
// stored status before crediting any cargo.
const fresh = (await payload
.findByID({
collection: "shipments",
id: shipment.id,
depth: 0,
overrideAccess: true,
})
.catch(() => null)) as unknown as { status?: string } | null;
if (!fresh || (fresh.status !== "dispatched" && fresh.status !== "in_transit")) return;
const bounced: { itemId: number; amount: number; resourceName: string }[] = [];
for (const cargoEntry of shipment.cargo ?? []) {
const itemRef = cargoEntry.item;
if (!itemRef || typeof itemRef === "number") continue;
const polymorphic = itemRef as { relationTo: string; value: number | { id: number } };
if (polymorphic.relationTo !== "resources") continue;
const itemId = typeof polymorphic.value === "object" ? polymorphic.value.id : polymorphic.value;
try {
const destination = await payload.findByID({
collection: "game-structures",
id: destinationId,
depth: 2,
});
const destType = typeof destination.type === "object" ? destination.type : null;
if (destType) {
const destStored = destination.storedResources ?? [];
const destVoid = (destination as GameStructure).voidStorage ?? [];
const currentStored = [...destStored, ...destVoid].reduce((sum, r) => {
const resId = typeof r.resource === "object" ? r.resource.id : r.resource;
return sum + (resId === itemId ? r.amount : 0);
}, 0);
const ruleCheck = checkStorageDeposit(destType, itemId, cargoEntry.amount, currentStored);
if (!ruleCheck.allowed) {
const resName =
(
await payload
.findByID({ collection: "resources", id: itemId, depth: 0 })
.catch(() => null)
)?.name ?? `resource #${itemId}`;
bounced.push({
itemId,
amount: cargoEntry.amount,
resourceName: resName,
});
log?.error?.(
`Shipment "${shipment.name ?? `SHP-${shipment.id}`}" delivery rejected at destination: ${storageViolationMessage(resName, ruleCheck)}`,
);
continue;
}
}
const existingResources = destination.storedResources ?? [];
const existingEntry = existingResources.find((r) => {
const resId = typeof r.resource === "object" ? r.resource.id : r.resource;
return resId === itemId;
});
if (existingEntry) {
existingEntry.amount += cargoEntry.amount;
} else {
existingResources.push({
resource: itemId,
amount: cargoEntry.amount,
gridX: 0,
gridY: existingResources.length,
rotated: false,
});
}
await payload.update({
collection: "game-structures",
id: destinationId,
data: { storedResources: existingResources },
});
} catch (error) {
log?.error?.(`Failed to transfer cargo item ${itemId}: ${errorMessage(error)}`);
}
}
await payload.update({
collection: "game-vehicles",
id: vehicle.id,
data: {
deployedAt: destinationId,
status: "idle",
},
});
if (bounced.length > 0) {
// Return rejected cargo to the origin structure
const origin = await payload
.findByID({
collection: "game-structures",
id: originId,
depth: 1,
})
.catch(() => null);
if (origin) {
const existingResources = [...(origin.storedResources ?? [])];
for (const b of bounced) {
const existingEntry = existingResources.find((r) => {
const resId = typeof r.resource === "object" ? r.resource.id : r.resource;
return resId === b.itemId;
});
if (existingEntry) {
existingEntry.amount += b.amount;
} else {
existingResources.push({
resource: b.itemId,
amount: b.amount,
gridX: 0,
gridY: existingResources.length,
rotated: false,
});
}
}
await payload.update({
collection: "game-structures",
id: originId,
data: { storedResources: existingResources },
});
}
await payload.update({
collection: "shipments",
id: shipment.id,
data: {
status: "failed",
failureReason: `Destination storage rules prevented delivery: ${bounced
.map((b) => `${b.resourceName} ×${b.amount.toLocaleString()}`)
.join(", ")}; returned to origin.`,
completedAt: new Date().toISOString(),
},
});
await emitGameEvent(payload, {
type: EventTypes.ShipmentFail,
message: `Shipment "${shipment.name ?? `SHP-${shipment.id}`}" delivery rejected by destination storage rules`,
structure: destinationId,
targetCollection: "shipments",
targetId: shipment.id,
data: {
reason: "storage_rules",
bounced: bounced.map((b) => ({
itemId: b.itemId,
amount: b.amount,
resourceName: b.resourceName,
})),
},
});
return;
}
await payload.update({
collection: "shipments",
id: shipment.id,
data: {
status: "completed",
completedAt: new Date().toISOString(),
fuelConsumed: finalFuelConsumed,
},
});
await emitGameEvent(payload, {
type: EventTypes.ShipmentComplete,
message: `Shipment "${shipment.name ?? `SHP-${shipment.id}`}" arrived at destination`,
structure: destinationId,
targetCollection: "shipments",
targetId: shipment.id,
data: { vehicleId: vehicle.id, originId, destinationId },
});
// Fire-and-forget: a failed construction start must not fail the completed shipment.
try {
await maybeStartConstruction(payload, destinationId, now);
} catch (error) {
log?.error?.(
`Construction start failed at destination "${destinationId}": ${errorMessage(error)}`,
);
}
// Notify the user who created the shipment (the closest thing to a recipient/owner).
const creatorId =
typeof shipment.createdBy === "object" && shipment.createdBy
? shipment.createdBy.id
: (shipment.createdBy as number | null | undefined);
if (creatorId != null) {
await notifyUser(payload, {
userId: creatorId,
type: "shipment:completed",
title: "Shipment completed",
message: `Shipment "${shipment.name ?? `SHP-${shipment.id}`}" arrived at its destination.`,
link: `/logistics/shipments/${shipment.id}`,
});
}
if (shipment.autoReturn) {
await createAutoReturnShipment(payload, shipment, vehicle as GameVehicle & { type: Vehicle });
}
}
async function createAutoReturnShipment(
payload: Payload,
originalShipment: ShipmentDoc,
vehicle: GameVehicle & { type: Vehicle },
): Promise<void> {
const originId =
typeof originalShipment.origin === "object"
? originalShipment.origin.id
: (originalShipment.origin as number);
const destinationId =
typeof originalShipment.destination === "object"
? originalShipment.destination.id
: (originalShipment.destination as number);
const vehicleType = typeof vehicle.type === "object" ? vehicle.type : null;
if (!vehicleType) return;
const speed =
vehicleType.maxSpeedOnRoad ?? vehicleType.maxSpeedOffRoad ?? vehicleType.maxAirspeed ?? 50;
const rate = vehicleType.fuel?.fuelConsumptionRate ?? 1;
const originalRoutePath = isPointArray(originalShipment.routePath)
? ([...originalShipment.routePath] as MapPoint[]).reverse()
: null;
const returnFuelCost = Math.ceil(originalShipment.distance * rate);
const returnDurationMs = (originalShipment.distance / speed) * 60 * 60 * 1000;
const now = new Date();
if (vehicle.currentFuel < returnFuelCost) {
await emitGameEvent(payload, {
type: EventTypes.ShipmentFail,
message: `Auto-return failed: insufficient fuel`,
structure: destinationId,
targetCollection: "game-vehicles",
targetId: vehicle.id,
data: { reason: "insufficient_fuel_for_return" },
});
return;
}
await payload.update({
collection: "game-vehicles",
id: vehicle.id,
data: {
currentFuel: vehicle.currentFuel - returnFuelCost,
status: "in_transit",
deployedAt: null,
},
});
const returnShipment = await payload.create({
collection: "shipments",
data: {
name: `Return: ${originalShipment.name ?? `SHP-${originalShipment.id}`}`,
origin: destinationId,
destination: originId,
map:
typeof originalShipment.map === "object"
? (originalShipment.map?.id ?? null)
: (originalShipment.map ?? null),
routePath: originalRoutePath,
transportVehicle: vehicle.id,
distance: originalShipment.distance,
cargo: [],
fuelCost: returnFuelCost,
fuelConsumed: 0,
status: "dispatched",
dispatchedAt: now.toISOString(),
estimatedArrival: new Date(now.getTime() + returnDurationMs).toISOString(),
autoReturn: false,
createdBy: originalShipment.createdBy,
},
});
await emitGameEvent(payload, {
type: EventTypes.ShipmentAutoReturn,
message: `Vehicle auto-returning to origin`,
structure: destinationId,
targetCollection: "shipments",
targetId: returnShipment.id,
data: { vehicleId: vehicle.id, originalShipmentId: originalShipment.id },
});
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}