feat(tech): member-facing tech research system and tech tree
Add a research pipeline over the existing technology tree: Research Facility blueprint fields copied to structure instances, tech-researches/ tech-ballots/tech-ballot-votes collections, Game Rules research config, pure rules lib (capacity, duration math, eligibility, intel-weighted tally with tie cascade), a timestamp-derived tech-tick bin that opens, resolves, advances and completes research with notifications, vote casting server actions, and a read-only member-facing tech tree page at /intelligence/tech-tree with veil blackout and dossier-style panels. Includes migration 20261019_184409_add_tech_research_system, permission groups, event and notification types, sidebar entry, and integration plus e2e coverage.
This commit is contained in:
parent
57b6999e61
commit
afa79b4be4
42 changed files with 46968 additions and 8 deletions
141
src/app/(frontend)/intelligence/tech-tree/actions.ts
Normal file
141
src/app/(frontend)/intelligence/tech-tree/actions.ts
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
"use server";
|
||||
|
||||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
|
||||
import { relationshipId } from "@/lib/base/storage";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
|
||||
interface ActionResult<T = undefined> {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
data?: T;
|
||||
}
|
||||
|
||||
async function authenticate() {
|
||||
const payloadConfig = await config;
|
||||
const payload = await getPayload({ config: payloadConfig });
|
||||
const hdrs = await nextHeaders();
|
||||
const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false });
|
||||
|
||||
if (!isPayloadUser(user)) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
|
||||
return { payload, user };
|
||||
}
|
||||
|
||||
/**
|
||||
* Cast or change the caller's vote on an open research ballot. Votes stay
|
||||
* updatable until the ballot closes (the tick tallies at close). The
|
||||
* tech-ballot-votes collection is write-locked; this action is the only
|
||||
* member-facing write path (overrideAccess), mirroring TicketVotes.
|
||||
*/
|
||||
export async function castTechVote(input: {
|
||||
ballotId: number;
|
||||
technologyId: number;
|
||||
}): Promise<ActionResult<{ technologyId: number }>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
if (!Number.isFinite(input.ballotId) || !Number.isFinite(input.technologyId)) {
|
||||
return { success: false, error: "Invalid ballot or technology." };
|
||||
}
|
||||
|
||||
const rules = await payload.findGlobal({ slug: "game-rules", depth: 0, overrideAccess: true });
|
||||
if (rules.research?.enabled !== true) {
|
||||
return { success: false, error: "The research program is offline." };
|
||||
}
|
||||
|
||||
const ballot = await payload
|
||||
.findByID({
|
||||
collection: "tech-ballots",
|
||||
id: input.ballotId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => null);
|
||||
if (!ballot || ballot.status === "closed") {
|
||||
return { success: false, error: "This ballot is closed." };
|
||||
}
|
||||
if (ballot.closesAt && Date.parse(ballot.closesAt) <= Date.now()) {
|
||||
return { success: false, error: "Voting has ended for this ballot." };
|
||||
}
|
||||
|
||||
const optionIds = ballot.options
|
||||
.map((option) => relationshipId(option.technology))
|
||||
.filter((id): id is number => id != null);
|
||||
if (!optionIds.includes(input.technologyId)) {
|
||||
return { success: false, error: "That technology is not an option on this ballot." };
|
||||
}
|
||||
|
||||
const existing = await payload.find({
|
||||
collection: "tech-ballot-votes",
|
||||
where: {
|
||||
and: [{ ballot: { equals: ballot.id } }, { user: { equals: user.id } }],
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
if (existing.docs[0]) {
|
||||
if (relationshipId(existing.docs[0].technology) === input.technologyId) {
|
||||
return { success: true, data: { technologyId: input.technologyId } };
|
||||
}
|
||||
await payload.update({
|
||||
collection: "tech-ballot-votes",
|
||||
id: existing.docs[0].id,
|
||||
data: { technology: input.technologyId },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
await payload.create({
|
||||
collection: "tech-ballot-votes",
|
||||
data: { ballot: ballot.id, user: user.id, technology: input.technologyId },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
} catch (error) {
|
||||
// Unique(ballot,user): a concurrent double-submit lost the race but the
|
||||
// vote exists; treat as success only when the winner cast the same kind
|
||||
// of row we intended (any row for this user+ballot satisfies "one vote").
|
||||
const concurrent = await payload.find({
|
||||
collection: "tech-ballot-votes",
|
||||
where: {
|
||||
and: [{ ballot: { equals: ballot.id } }, { user: { equals: user.id } }],
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (concurrent.docs.length === 0) throw error;
|
||||
return { success: true, data: { technologyId: input.technologyId } };
|
||||
}
|
||||
}
|
||||
|
||||
const optionName =
|
||||
ballot.options.find((option) => relationshipId(option.technology) === input.technologyId)
|
||||
?.name ?? `Technology #${input.technologyId}`;
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.TechBallotVoted,
|
||||
message: `Vote cast on research ballot #${ballot.id}: ${optionName}`,
|
||||
actor: user.id,
|
||||
targetCollection: "tech-ballots",
|
||||
targetId: ballot.id,
|
||||
data: { ballotId: ballot.id, technologyId: input.technologyId, kind: "vote" },
|
||||
});
|
||||
|
||||
return { success: true, data: { technologyId: input.technologyId } };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
};
|
||||
}
|
||||
}
|
||||
244
src/app/(frontend)/intelligence/tech-tree/page.tsx
Normal file
244
src/app/(frontend)/intelligence/tech-tree/page.tsx
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import type { Metadata } from "next";
|
||||
|
||||
import { mapCategoryDoc, mapTechDoc } from "@/components/admin/tech-tree/mappers";
|
||||
import { TechTreeClient } from "@/components/frontend/techTree/TechTreeClient";
|
||||
import type {
|
||||
ActiveResearchView,
|
||||
BallotView,
|
||||
QueuedResearchView,
|
||||
TechDetailView,
|
||||
TechViewState,
|
||||
} from "@/components/frontend/techTree/types";
|
||||
import { relationshipId } from "@/lib/base/storage";
|
||||
import { loadResearchCapacity } from "@/lib/tech/capacity";
|
||||
import { eligibleTechs, technologyToEligibility } from "@/lib/tech/research";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Tech Tree: Polaris Task Force",
|
||||
};
|
||||
|
||||
/**
|
||||
* Member-facing tech tree (read-only). Guests never reach this route: the
|
||||
* (frontend) layout renders LandingPage for them. The canvas shows approved
|
||||
* technologies only; approved-but-locked ones render as blackout veil cards.
|
||||
*/
|
||||
export default async function FrontendTechTreePage() {
|
||||
const payload = await getPayload({ config });
|
||||
const { user } = await payload.auth({ headers: await nextHeaders(), canSetHeaders: false });
|
||||
if (!user) return null; // type-guard only; the layout gate handles guests
|
||||
|
||||
const [capacity, techsRes, categoriesRes, resourcesRes, researchesRes, ballotsRes] =
|
||||
await Promise.all([
|
||||
loadResearchCapacity(payload),
|
||||
payload.find({
|
||||
collection: "technologies",
|
||||
where: { approvalStatus: { equals: "approved" } },
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
sort: "name",
|
||||
user,
|
||||
overrideAccess: false,
|
||||
}),
|
||||
payload.find({
|
||||
collection: "tech-categories",
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
sort: "position",
|
||||
user,
|
||||
overrideAccess: false,
|
||||
}),
|
||||
payload.find({
|
||||
collection: "resources",
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
sort: "name",
|
||||
user,
|
||||
overrideAccess: false,
|
||||
}),
|
||||
payload.find({
|
||||
collection: "tech-researches",
|
||||
where: { status: { in: ["active", "queued"] } },
|
||||
sort: "createdAt",
|
||||
depth: 0,
|
||||
limit: 50,
|
||||
user,
|
||||
overrideAccess: false,
|
||||
}),
|
||||
payload.find({
|
||||
collection: "tech-ballots",
|
||||
where: { status: { in: ["open", "extended"] } },
|
||||
sort: "-opensAt",
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
user,
|
||||
overrideAccess: false,
|
||||
}),
|
||||
]);
|
||||
|
||||
const techDocs = techsRes.docs as unknown as Record<string, any>[];
|
||||
const techById = new Map(techDocs.map((doc) => [doc.id as number, doc]));
|
||||
const resourceNameById = new Map(resourcesRes.docs.map((doc) => [doc.id, doc.name]));
|
||||
|
||||
// --- research state -----------------------------------------------------
|
||||
type BusyEntry = { status: "active" | "queued"; startedAt: string | null; etaAt: string | null };
|
||||
const busyByTechnology = new Map<number, BusyEntry>();
|
||||
for (const research of researchesRes.docs) {
|
||||
const technologyId = relationshipId(research.technology);
|
||||
if (technologyId == null) continue;
|
||||
const existing = busyByTechnology.get(technologyId);
|
||||
// active wins over queued for the node overlay
|
||||
if (!existing || research.status === "active") {
|
||||
busyByTechnology.set(technologyId, {
|
||||
status: research.status as "active" | "queued",
|
||||
startedAt: research.startedAt ?? null,
|
||||
etaAt: research.etaAt ?? null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const researchedIds = new Set(
|
||||
techDocs.filter((doc) => doc.researchedAt).map((doc) => doc.id as number),
|
||||
);
|
||||
const eligibility = eligibleTechs(techDocs.map((doc) => technologyToEligibility(doc)), {
|
||||
researchedIds,
|
||||
busyIds: new Set(busyByTechnology.keys()),
|
||||
});
|
||||
const eligibleIds = new Set(eligibility.map((tech) => tech.id));
|
||||
|
||||
const statuses: Record<number, TechViewState> = {};
|
||||
for (const doc of techDocs) {
|
||||
const id = doc.id as number;
|
||||
const busy = busyByTechnology.get(id);
|
||||
if (doc.researchedAt) {
|
||||
statuses[id] = { state: "unlocked", researchedAt: String(doc.researchedAt) };
|
||||
} else if (busy?.status === "active") {
|
||||
statuses[id] = { state: "researching", startedAt: busy.startedAt, etaAt: busy.etaAt };
|
||||
} else if (busy?.status === "queued") {
|
||||
statuses[id] = { state: "queued" };
|
||||
} else if (eligibleIds.has(id)) {
|
||||
statuses[id] = { state: "available" };
|
||||
} else {
|
||||
statuses[id] = { state: "locked" };
|
||||
}
|
||||
}
|
||||
|
||||
// --- dialog details (veiled techs deliberately get none) -----------------
|
||||
const details: Record<number, TechDetailView> = {};
|
||||
for (const doc of techDocs) {
|
||||
const id = doc.id as number;
|
||||
const state = statuses[id].state;
|
||||
if (state === "locked") continue;
|
||||
const eligibilityTech = technologyToEligibility(doc);
|
||||
details[id] = {
|
||||
technologyId: id,
|
||||
name: String(doc.name ?? ""),
|
||||
type: String(doc.type ?? "upgrade"),
|
||||
summary: String(doc.summary ?? ""),
|
||||
description: doc.description ?? null,
|
||||
state,
|
||||
researchedAt: doc.researchedAt ? String(doc.researchedAt) : null,
|
||||
startedAt: statuses[id].startedAt ?? null,
|
||||
etaAt: statuses[id].etaAt ?? null,
|
||||
minimumResearchDuration: doc.researchCosts?.minimumResearchDuration ?? null,
|
||||
maximumResearchDuration: doc.researchCosts?.maximumResearchDuration ?? null,
|
||||
resourceCosts: (((doc.researchCosts?.resources ?? []) as any[]) ).map((row) => ({
|
||||
resourceId: relationshipId(row.resource) ?? 0,
|
||||
name:
|
||||
typeof row.resource === "object" && row.resource?.name
|
||||
? String(row.resource.name)
|
||||
: resourceNameById.get(relationshipId(row.resource) ?? -1) ?? "Resource",
|
||||
amount: row.amount ?? 0,
|
||||
})),
|
||||
prereqAndIds: [...eligibilityTech.prereqAnd],
|
||||
prereqOrIds: [...eligibilityTech.prereqOr],
|
||||
};
|
||||
}
|
||||
|
||||
const activeResearch: ActiveResearchView[] = researchesRes.docs
|
||||
.filter((research) => research.status === "active")
|
||||
.map((research) => {
|
||||
const technologyId = relationshipId(research.technology);
|
||||
return {
|
||||
id: research.id,
|
||||
technologyId: technologyId ?? -1,
|
||||
name: technologyId != null ? String(techById.get(technologyId)?.name ?? "Unknown") : "Unknown",
|
||||
startedAt: research.startedAt ?? null,
|
||||
etaAt: research.etaAt ?? null,
|
||||
};
|
||||
});
|
||||
const queuedResearch: QueuedResearchView[] = researchesRes.docs
|
||||
.filter((research) => research.status === "queued")
|
||||
.map((research) => {
|
||||
const technologyId = relationshipId(research.technology);
|
||||
return {
|
||||
id: research.id,
|
||||
technologyId: technologyId ?? -1,
|
||||
name: technologyId != null ? String(techById.get(technologyId)?.name ?? "Unknown") : "Unknown",
|
||||
};
|
||||
});
|
||||
|
||||
// --- open ballot + raw tallies -------------------------------------------
|
||||
const ballotDoc = ballotsRes.docs[0];
|
||||
let ballot: BallotView | null = null;
|
||||
if (ballotDoc) {
|
||||
const votesRes = await payload.find({
|
||||
collection: "tech-ballot-votes",
|
||||
where: { ballot: { equals: ballotDoc.id } },
|
||||
depth: 0,
|
||||
limit: 2000,
|
||||
user,
|
||||
overrideAccess: false,
|
||||
});
|
||||
const rawVotes = new Map<number, number>();
|
||||
let myVote: number | null = null;
|
||||
for (const vote of votesRes.docs) {
|
||||
const technologyId = relationshipId(vote.technology);
|
||||
if (technologyId == null) continue;
|
||||
rawVotes.set(technologyId, (rawVotes.get(technologyId) ?? 0) + 1);
|
||||
if (relationshipId(vote.user) === user.id) myVote = technologyId;
|
||||
}
|
||||
ballot = {
|
||||
id: ballotDoc.id,
|
||||
status: ballotDoc.status as "open" | "extended",
|
||||
closesAt: ballotDoc.closesAt,
|
||||
totalVotes: votesRes.totalDocs,
|
||||
myVote,
|
||||
options: ballotDoc.options.flatMap((option) => {
|
||||
const technologyId = relationshipId(option.technology);
|
||||
if (technologyId == null) return [];
|
||||
return [
|
||||
{
|
||||
technologyId,
|
||||
name: option.name,
|
||||
summary: option.summary ?? null,
|
||||
rawVotes: rawVotes.get(technologyId) ?? 0,
|
||||
},
|
||||
];
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-[calc(100dvh-7.5rem)] min-h-0 flex-col p-4">
|
||||
<TechTreeClient
|
||||
techs={techDocs.map((doc) => mapTechDoc(doc))}
|
||||
categories={categoriesRes.docs.map((doc) => mapCategoryDoc(doc as unknown as Record<string, unknown>))}
|
||||
statuses={statuses}
|
||||
details={details}
|
||||
activeResearch={activeResearch}
|
||||
queuedResearch={queuedResearch}
|
||||
ballot={ballot}
|
||||
stats={{
|
||||
enabled: capacity.enabled,
|
||||
slots: capacity.capacity.slots,
|
||||
facilityCount: capacity.capacity.facilityCount,
|
||||
totalResearchers: capacity.capacity.totalResearchers,
|
||||
totalModifier: capacity.capacity.totalModifier,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -4002,3 +4002,26 @@
|
|||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* Member-facing Tech Tree canvas: dark tactical chrome for React Flow
|
||||
controls (mirrors the admin editor's .tech-tree-canvas rules from
|
||||
(payload)/custom.scss, which do not reach the frontend bundle). */
|
||||
.frontend-tech-tree .react-flow__controls button {
|
||||
background: rgba(0, 0, 0, 0.72);
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.15);
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
border-radius: 0;
|
||||
}
|
||||
.frontend-tech-tree .react-flow__controls button:hover {
|
||||
background: rgba(0, 0, 0, 0.92);
|
||||
color: #ffffff;
|
||||
}
|
||||
.frontend-tech-tree .react-flow__controls button svg {
|
||||
fill: currentColor;
|
||||
}
|
||||
.frontend-tech-tree .react-flow__attribution {
|
||||
background: transparent;
|
||||
}
|
||||
.frontend-tech-tree .react-flow__attribution a {
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ const TARGET_COLLECTIONS = [
|
|||
{ label: "Campaigns", value: "campaigns" },
|
||||
{ label: "Users", value: "users" },
|
||||
{ label: "Technologies", value: "technologies" },
|
||||
{ label: "Tech Researches", value: "tech-researches" },
|
||||
{ label: "Tech Ballots", value: "tech-ballots" },
|
||||
{ label: "Maps", value: "maps" },
|
||||
{ label: "Shipments", value: "shipments" },
|
||||
{ label: "Bank Accounts", value: "bank-accounts" },
|
||||
|
|
|
|||
|
|
@ -236,6 +236,46 @@ export const GameRules: GlobalConfig = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "research",
|
||||
type: "group",
|
||||
label: "Technology Research",
|
||||
admin: {
|
||||
description:
|
||||
"Global knobs for the member-facing tech research engine run by the tech tick (ballots, facility speed, researcher bonus).",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "enabled",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Master gate for the research engine. When off, the tech tick does nothing: no ballots open, no research progresses.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ballotDurationTicks",
|
||||
type: "number",
|
||||
min: 1,
|
||||
defaultValue: 288,
|
||||
admin: {
|
||||
description:
|
||||
"How long a research ballot stays open, in game ticks (default 288 ticks = 48h at a 10-minute tick).",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "researcherSpeedPerHead",
|
||||
type: "number",
|
||||
min: 0,
|
||||
defaultValue: 0.0001,
|
||||
admin: {
|
||||
description:
|
||||
"Research time reduction each researcher adds, as a fraction (0.0001 = 0.01% faster per head). Researchers are active labor staff in the 'researcher' labor classification at operational research facilities.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "zonePressureEnabled",
|
||||
type: "checkbox",
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { requirePermission, hasPermission } from "@/utils/access-control/hasPerm
|
|||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { staffingDefaultsFromBlueprint } from "@/lib/base/staffingDefaults";
|
||||
import { createStaffingFields } from "./staffingFields";
|
||||
import { createResearchFields } from "./researchFields";
|
||||
import { createProductionFields } from "./productionFields";
|
||||
import { createModuleFields } from "./moduleFields";
|
||||
import { productionDefaultsFromBlueprint } from "@/lib/base/productionDefaults";
|
||||
|
|
@ -112,6 +113,16 @@ export const GameStructures: CollectionConfig = {
|
|||
...(data.maintenanceCost === undefined
|
||||
? { maintenanceCost: defaults.maintenanceCost }
|
||||
: {}),
|
||||
...(data.isResearchFacility === undefined && blueprint.isResearchFacility !== undefined
|
||||
? { isResearchFacility: blueprint.isResearchFacility }
|
||||
: {}),
|
||||
...(data.researchSpeedModifier === undefined &&
|
||||
blueprint.researchSpeedModifier !== undefined
|
||||
? { researchSpeedModifier: blueprint.researchSpeedModifier }
|
||||
: {}),
|
||||
...(data.researchSlots === undefined && blueprint.researchSlots !== undefined
|
||||
? { researchSlots: blueprint.researchSlots }
|
||||
: {}),
|
||||
};
|
||||
},
|
||||
],
|
||||
|
|
@ -225,6 +236,7 @@ export const GameStructures: CollectionConfig = {
|
|||
},
|
||||
},
|
||||
...createStaffingFields("instance"),
|
||||
...createResearchFields("instance"),
|
||||
...createProductionFields("instance"),
|
||||
...createModuleFields("instance"),
|
||||
{
|
||||
|
|
|
|||
57
src/collections/game/researchFields.ts
Normal file
57
src/collections/game/researchFields.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import type { Field } from "payload";
|
||||
|
||||
type ResearchFieldContext = "instance" | "defaults";
|
||||
|
||||
/**
|
||||
* Shared "Research Facility" field group, added to both the `structures`
|
||||
* blueprint (as defaults) and `game-structures` instances (pattern of
|
||||
* `staffingFields.ts`). The GameStructures beforeChange hook copies the
|
||||
* blueprint values onto new instances, same as the staffing defaults.
|
||||
*/
|
||||
export function createResearchFields(context: ResearchFieldContext): Field[] {
|
||||
const defaults = context === "defaults";
|
||||
|
||||
// On instances, the fields deliberately carry NO defaultValue: Payload
|
||||
// applies defaults BEFORE beforeChange, so a defaulted field can never be
|
||||
// distinguished from "unset" and would defeat the blueprint-copy hook in
|
||||
// GameStructures. Undefined on create => copied from the blueprint; the
|
||||
// engine treats null as falsy/0 (see src/lib/tech/capacity.ts).
|
||||
return [
|
||||
{
|
||||
name: "isResearchFacility",
|
||||
type: "checkbox",
|
||||
...(defaults ? { defaultValue: false } : {}),
|
||||
label: "Research Facility",
|
||||
admin: {
|
||||
description: defaults
|
||||
? "Mark this structure type as a research facility. Copied into newly created game-structures of this type. Operational facilities with at least one researcher run the tech research engine."
|
||||
: "Operational facilities with at least one researcher run the tech research engine (slots, speed modifier). Inherited from the blueprint when left unset at creation.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "researchSpeedModifier",
|
||||
type: "number",
|
||||
min: 0,
|
||||
max: 1,
|
||||
...(defaults ? { defaultValue: 0 } : {}),
|
||||
label: "Research Speed Modifier",
|
||||
admin: {
|
||||
description: defaults
|
||||
? "Fractional research time reduction this facility provides while operational and staffed (0.05 = research completes 5% faster). Copied into newly created game-structures of this type."
|
||||
: "Fractional research time reduction this facility provides while operational and staffed (0.05 = research completes 5% faster). Inherited from the blueprint when left unset at creation.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "researchSlots",
|
||||
type: "number",
|
||||
min: 0,
|
||||
...(defaults ? { defaultValue: 1 } : {}),
|
||||
label: "Research Slots",
|
||||
admin: {
|
||||
description: defaults
|
||||
? "Parallel research capacity this facility provides while operational and staffed. Copied into newly created game-structures of this type."
|
||||
: "Parallel research capacity this facility provides while operational and staffed. 0 = no capacity. Inherited from the blueprint when left unset at creation.",
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
56
src/collections/intelligence/TechBallotVotes.ts
Normal file
56
src/collections/intelligence/TechBallotVotes.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import type { CollectionConfig } from "payload";
|
||||
|
||||
/**
|
||||
* One vote per member per ballot (unique ballot+user). Votes are updatable
|
||||
* until the ballot closes; changing a vote rewrites `technology` in place via
|
||||
* the server action. Weight is NOT stored: Intelligence-qualified votes count
|
||||
* double, computed at tally time (accepted trade-off: mid-ballot qualification
|
||||
* changes affect the result).
|
||||
*
|
||||
* Mirrors TicketVotes: read for authed users, writes only through actions /
|
||||
* the tick service with overrideAccess.
|
||||
*/
|
||||
export const TechBallotVotes: CollectionConfig = {
|
||||
slug: "tech-ballot-votes",
|
||||
admin: {
|
||||
group: "Intelligence",
|
||||
defaultColumns: ["ballot", "user", "technology", "updatedAt"],
|
||||
},
|
||||
access: {
|
||||
read: ({ req }) => Boolean(req.user),
|
||||
create: () => false,
|
||||
update: () => false,
|
||||
delete: () => false,
|
||||
},
|
||||
indexes: [
|
||||
{
|
||||
fields: ["ballot", "user"],
|
||||
unique: true,
|
||||
},
|
||||
],
|
||||
fields: [
|
||||
{
|
||||
name: "ballot",
|
||||
type: "relationship",
|
||||
relationTo: "tech-ballots",
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "technology",
|
||||
type: "relationship",
|
||||
relationTo: "technologies",
|
||||
required: true,
|
||||
admin: {
|
||||
description: "The option this member voted for (must be one of the ballot's frozen options).",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
131
src/collections/intelligence/TechBallots.ts
Normal file
131
src/collections/intelligence/TechBallots.ts
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import type { CollectionConfig } from "payload";
|
||||
|
||||
/**
|
||||
* Unit-wide vote on what the research facilities work on next. Opened
|
||||
* automatically by the tech tick when a research slot is free and eligible
|
||||
* technologies exist; options are frozen at open so mid-ballot catalog edits
|
||||
* cannot change the question members are answering.
|
||||
*
|
||||
* One ballot at a time: the tick opens the next one immediately after a
|
||||
* resolution. Members vote through the server actions (the collection itself
|
||||
* is read-only, pattern of TicketVotes); Intelligence-qualified votes count
|
||||
* double, resolved AT TALLY via hasIntelligenceQualification.
|
||||
*/
|
||||
export const TechBallots: CollectionConfig = {
|
||||
slug: "tech-ballots",
|
||||
admin: {
|
||||
group: "Intelligence",
|
||||
defaultColumns: ["status", "opensAt", "closesAt", "winner"],
|
||||
},
|
||||
access: {
|
||||
read: ({ req }) => Boolean(req.user),
|
||||
create: () => false,
|
||||
update: () => false,
|
||||
delete: () => false,
|
||||
},
|
||||
indexes: [{ fields: ["status"] }],
|
||||
fields: [
|
||||
{
|
||||
name: "status",
|
||||
type: "select",
|
||||
options: ["open", "extended", "closed"],
|
||||
defaultValue: "open",
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: "opensAt",
|
||||
type: "date",
|
||||
required: true,
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "closesAt",
|
||||
type: "date",
|
||||
required: true,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "When the tick tallies votes and resolves the winner.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "extendedOnce",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "A zero-turnout ballot is extended once before the tick auto-starts the cheapest option.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "options",
|
||||
type: "array",
|
||||
required: true,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "Candidate technologies frozen at open (name/summary/costs copied so history stays readable even if the catalog changes).",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "technology",
|
||||
type: "relationship",
|
||||
relationTo: "technologies",
|
||||
required: true,
|
||||
},
|
||||
{ name: "name", type: "text", required: true },
|
||||
{ name: "summary", type: "textarea" },
|
||||
{
|
||||
name: "minimumResearchDuration",
|
||||
type: "number",
|
||||
admin: { description: "Ticks. Frozen from the technology at open." },
|
||||
},
|
||||
{
|
||||
name: "maximumResearchDuration",
|
||||
type: "number",
|
||||
admin: { description: "Ticks. Frozen from the technology at open." },
|
||||
},
|
||||
{
|
||||
name: "resourceCosts",
|
||||
type: "array",
|
||||
fields: [
|
||||
{
|
||||
name: "resource",
|
||||
type: "relationship",
|
||||
relationTo: "resources",
|
||||
required: true,
|
||||
},
|
||||
{ name: "amount", type: "number", required: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "winner",
|
||||
type: "relationship",
|
||||
relationTo: "technologies",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "research",
|
||||
type: "relationship",
|
||||
relationTo: "tech-researches",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "The queued research doc created for the winner.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tallySnapshot",
|
||||
type: "json",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
"Per-option raw + Intelligence-weighted counts and the tie-break method recorded at resolution.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "resolvedAt",
|
||||
type: "date",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
],
|
||||
};
|
||||
100
src/collections/intelligence/TechResearches.ts
Normal file
100
src/collections/intelligence/TechResearches.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import type { CollectionConfig } from "payload";
|
||||
|
||||
/**
|
||||
* One research effort on a technology, driven entirely by the tech tick
|
||||
* (`src/lib/tech/tick.ts`). Lifecycle: a ballot resolves into a `queued` doc;
|
||||
* the sweep activates it when the pooled research-facility storage can cover
|
||||
* the costs (stamping startedAt + the derived etaAt); at etaAt it completes and
|
||||
* sets `technologies.researchedAt`.
|
||||
*
|
||||
* Collection access is read-only for members: every write happens in the tick
|
||||
* service with overrideAccess (pattern of TicketVotes).
|
||||
*/
|
||||
export const TechResearches: CollectionConfig = {
|
||||
slug: "tech-researches",
|
||||
admin: {
|
||||
group: "Intelligence",
|
||||
defaultColumns: ["technology", "status", "startedAt", "etaAt"],
|
||||
},
|
||||
access: {
|
||||
read: ({ req }) => Boolean(req.user),
|
||||
create: () => false,
|
||||
update: () => false,
|
||||
delete: () => false,
|
||||
},
|
||||
indexes: [
|
||||
{ fields: ["status"] },
|
||||
{ fields: ["technology", "status"] },
|
||||
],
|
||||
fields: [
|
||||
{
|
||||
name: "technology",
|
||||
type: "relationship",
|
||||
relationTo: "technologies",
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
type: "select",
|
||||
options: ["queued", "active", "completed"],
|
||||
defaultValue: "queued",
|
||||
required: true,
|
||||
admin: {
|
||||
description: "queued = awaiting affordable storage; active = researching (etaAt set); completed = researchedAt stamped on the technology.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ballot",
|
||||
type: "relationship",
|
||||
relationTo: "tech-ballots",
|
||||
admin: {
|
||||
description: "The ballot whose winner produced this research.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "startedAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "When the research activated (costs consumed). Empty while queued.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "etaAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
"Derived completion time: startedAt + effective duration at activation speed. The tick completes the research at/after this timestamp.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "completedAt",
|
||||
type: "date",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "consumedCosts",
|
||||
type: "array",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
"Snapshot of the resources actually drained from pooled facility storage when this research activated.",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "resource",
|
||||
type: "relationship",
|
||||
relationTo: "resources",
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: "amount",
|
||||
type: "number",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
@ -1,4 +1,8 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import type {
|
||||
CollectionBeforeChangeHook,
|
||||
CollectionBeforeDeleteHook,
|
||||
} from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import {
|
||||
approvalStatusFieldAccess,
|
||||
|
|
@ -10,6 +14,73 @@ import { ifUnmodifiedAtGuard } from "@/utils/access-control/optimisticConcurrenc
|
|||
|
||||
const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("technologies");
|
||||
|
||||
/**
|
||||
* Guard hook: a technology with an in-flight research (queued or active
|
||||
* tech-researches doc) must stay approved until the research resolves, so the
|
||||
* research engine's eligibility assumptions cannot be pulled out from under it.
|
||||
* Runs AFTER resetApprovalStatusOnEdit so it sees the final outgoing value.
|
||||
*/
|
||||
const blockUnapproveWhileResearching: CollectionBeforeChangeHook = async ({
|
||||
req,
|
||||
data,
|
||||
originalDoc,
|
||||
operation,
|
||||
}) => {
|
||||
if (operation !== "update" || !data) return data;
|
||||
const wasApproved = (originalDoc as { approvalStatus?: string } | undefined)?.approvalStatus;
|
||||
const incoming = data.approvalStatus as string | undefined;
|
||||
if (wasApproved !== "approved" || !incoming || incoming === "approved") return data;
|
||||
|
||||
const inFlight = await req.payload.find({
|
||||
collection: "tech-researches",
|
||||
where: {
|
||||
and: [
|
||||
{ technology: { equals: (originalDoc as { id: number }).id } },
|
||||
{ status: { in: ["queued", "active"] } },
|
||||
],
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (inFlight.docs.length > 0) {
|
||||
throw new Error(
|
||||
"This technology is currently being researched (queued or active). It cannot leave the Approved state until the research completes.",
|
||||
);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
/**
|
||||
* Guard hook: researched / researching / queued technologies are part of the
|
||||
* unit's progression history and the research engine's working set; deleting
|
||||
* them would corrupt both.
|
||||
*/
|
||||
const blockDeleteResearchedTech: CollectionBeforeDeleteHook = async ({ req, id }) => {
|
||||
const tech = await req.payload
|
||||
.findByID({ collection: "technologies", id, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
if (tech?.researchedAt) {
|
||||
throw new Error(
|
||||
`"${tech.name}" has been researched and cannot be deleted. Un-approve it instead only if it was never live.`,
|
||||
);
|
||||
}
|
||||
const inFlight = await req.payload.find({
|
||||
collection: "tech-researches",
|
||||
where: {
|
||||
and: [{ technology: { equals: id } }, { status: { in: ["queued", "active"] } }],
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (inFlight.docs.length > 0) {
|
||||
throw new Error(
|
||||
"This technology is queued or actively being researched and cannot be deleted until the research resolves.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const Technologies: CollectionConfig = {
|
||||
slug: "technologies",
|
||||
admin: {
|
||||
|
|
@ -24,8 +95,15 @@ export const Technologies: CollectionConfig = {
|
|||
},
|
||||
hooks: {
|
||||
// Guard first: a stale write must abort before the approval-reset hook
|
||||
// rewrites data (see optimisticConcurrency.ts for the contract).
|
||||
beforeChange: [ifUnmodifiedAtGuard(), resetApprovalStatusOnEdit()],
|
||||
// rewrites data (see optimisticConcurrency.ts for the contract). The
|
||||
// research guard runs last so it sees the final outgoing approvalStatus
|
||||
// (including any rewrite by resetApprovalStatusOnEdit).
|
||||
beforeChange: [
|
||||
ifUnmodifiedAtGuard(),
|
||||
resetApprovalStatusOnEdit(),
|
||||
blockUnapproveWhileResearching,
|
||||
],
|
||||
beforeDelete: [blockDeleteResearchedTech],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
|
|
@ -80,6 +158,16 @@ export const Technologies: CollectionConfig = {
|
|||
"Mark whether this technology is ready for developer approval and implementation into the live environment.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "researchedAt",
|
||||
type: "date",
|
||||
label: "Researched At",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
"Set automatically by the tech tick when this technology finishes researching. Empty = not yet researched.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "type",
|
||||
type: "select",
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { approvalStatusFieldAccess, resetApprovalStatusOnEdit } from "@/utils/ac
|
|||
import type { Resource } from "@/payload-types";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { createStaffingFields } from "@/collections/game/staffingFields";
|
||||
import { createResearchFields } from "@/collections/game/researchFields";
|
||||
import { createProductionFields } from "@/collections/game/productionFields";
|
||||
import { createModuleFields } from "@/collections/game/moduleFields";
|
||||
import { createAuraFields } from "@/collections/game/auraFields";
|
||||
|
|
@ -509,6 +510,11 @@ export const Structures: CollectionConfig = {
|
|||
type: "group",
|
||||
fields: createStaffingFields("defaults"),
|
||||
},
|
||||
{
|
||||
label: "Research Facility",
|
||||
type: "group",
|
||||
fields: createResearchFields("defaults"),
|
||||
},
|
||||
{
|
||||
label: "Production Recipe Defaults",
|
||||
type: "group",
|
||||
|
|
|
|||
|
|
@ -14,6 +14,12 @@ export type TechNodeData = {
|
|||
/** Another user changed this document: red ring until the tree is refreshed. */
|
||||
conflict: boolean;
|
||||
connectable: boolean;
|
||||
/**
|
||||
* Optional read-only status strip (member-facing tech tree: researching
|
||||
* progress / unlocked date / available badge). Absent in the admin editor,
|
||||
* so the editor's appearance is unchanged.
|
||||
*/
|
||||
overlay?: React.ReactNode;
|
||||
};
|
||||
|
||||
export type TechNodeModel = Node<TechNodeData, "techCard">;
|
||||
|
|
@ -103,6 +109,9 @@ export function TechNodeCard({ data, selected }: NodeProps<TechNodeModel>) {
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Optional read-only status strip (member-facing tree only) */}
|
||||
{data.overlay}
|
||||
|
||||
{/* Footer readout */}
|
||||
<div className="flex shrink-0 items-center justify-between border-t border-white/15 bg-black/60 px-3.5 py-1.5">
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/50 uppercase tabular-nums">
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
LifeBuoy,
|
||||
Medal,
|
||||
Map,
|
||||
Network,
|
||||
NotebookText,
|
||||
Package,
|
||||
Radar,
|
||||
|
|
@ -70,6 +71,11 @@ export const sidebarData = {
|
|||
url: "/intelligence/factions",
|
||||
icon: Flag,
|
||||
},
|
||||
{
|
||||
title: "Tech Tree",
|
||||
url: "/intelligence/tech-tree",
|
||||
icon: Network,
|
||||
},
|
||||
{
|
||||
title: "Wiki",
|
||||
url: "/wiki",
|
||||
|
|
|
|||
86
src/components/frontend/techTree/BallotPanel.tsx
Normal file
86
src/components/frontend/techTree/BallotPanel.tsx
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
"use client";
|
||||
|
||||
import React from "react";
|
||||
|
||||
import { DossierPanel, ReadoutCell } from "./DossierPanel";
|
||||
import { VoteButton } from "./VoteButton";
|
||||
import { formatDuration, type BallotView } from "./types";
|
||||
|
||||
/** Open research ballot: frozen options, raw tallies, Cast Vote per option. */
|
||||
export function BallotPanel({ ballot }: { ballot: BallotView | null }) {
|
||||
if (!ballot) {
|
||||
return (
|
||||
<DossierPanel stripLeft="R&D // BALLOT" stripRight="STANDBY">
|
||||
<p className="text-xs text-white/55">
|
||||
No open ballot. The next one opens automatically when a research slot is free and
|
||||
eligible technologies exist.
|
||||
</p>
|
||||
</DossierPanel>
|
||||
);
|
||||
}
|
||||
|
||||
const closesIn = Date.parse(ballot.closesAt) - Date.now();
|
||||
const maxVotes = Math.max(1, ...ballot.options.map((option) => option.rawVotes));
|
||||
|
||||
return (
|
||||
<DossierPanel
|
||||
stripLeft={ballot.status === "extended" ? "R&D // BALLOT (EXTENDED)" : "R&D // BALLOT OPEN"}
|
||||
stripRight={`CLOSES IN ${formatDuration(closesIn)}`}
|
||||
footer={
|
||||
<>
|
||||
<ReadoutCell value={String(ballot.totalVotes)} label="Votes Cast" />
|
||||
<ReadoutCell value={String(ballot.options.length)} label="Options" />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<ul className="space-y-2.5">
|
||||
{ballot.options.map((option) => {
|
||||
const mine = ballot.myVote === option.technologyId;
|
||||
return (
|
||||
<li
|
||||
key={option.technologyId}
|
||||
data-testid={`tech-ballot-option-${option.technologyId}`}
|
||||
className={`rounded-none border px-2.5 py-2 ${
|
||||
mine ? "border-[#22d3ee]/50 bg-[#22d3ee]/5" : "border-white/10 bg-black/40"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<span className="block truncate text-sm font-semibold text-white">
|
||||
{option.name}
|
||||
</span>
|
||||
{option.summary ? (
|
||||
<span className="mt-0.5 line-clamp-2 block text-[11px] leading-snug text-white/50">
|
||||
{option.summary}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<VoteButton
|
||||
ballotId={ballot.id}
|
||||
technologyId={option.technologyId}
|
||||
isMyVote={mine}
|
||||
disabled={closesIn <= 0}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-1.5 flex items-center gap-2">
|
||||
<div className="h-1 flex-1 overflow-hidden bg-white/10">
|
||||
<div
|
||||
className={`h-full ${mine ? "bg-[#22d3ee]" : "bg-white/40"}`}
|
||||
style={{ width: `${(option.rawVotes / maxVotes) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/60 uppercase tabular-nums">
|
||||
{option.rawVotes} vote{option.rawVotes === 1 ? "" : "s"}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className="mt-2.5 font-mono text-[9px] leading-relaxed tracking-wider text-white/40 uppercase">
|
||||
Intelligence-qualified votes count double at close. You can change your vote until the
|
||||
ballot closes.
|
||||
</p>
|
||||
</DossierPanel>
|
||||
);
|
||||
}
|
||||
76
src/components/frontend/techTree/DossierPanel.tsx
Normal file
76
src/components/frontend/techTree/DossierPanel.tsx
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
"use client";
|
||||
|
||||
import React from "react";
|
||||
|
||||
/**
|
||||
* Tactical dossier panel shell for the member-facing tech tree side column:
|
||||
* classification strip, corner brackets, squared corners, optional readout
|
||||
* footer. Style recipe: src/components/frontend/AGENTS.md.
|
||||
*/
|
||||
export function DossierPanel({
|
||||
stripLeft,
|
||||
stripRight,
|
||||
footer,
|
||||
className = "",
|
||||
children,
|
||||
}: {
|
||||
stripLeft: string;
|
||||
stripRight?: string;
|
||||
footer?: React.ReactNode;
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`relative rounded-none border border-white/15 bg-black/60 backdrop-blur-sm ${className}`}
|
||||
>
|
||||
<CornerBrackets />
|
||||
<div className="flex shrink-0 items-center justify-between gap-2 border-b border-white/15 bg-black/50 px-3.5 py-1.5">
|
||||
<span className="truncate font-mono text-[9px] tracking-widest text-white/60 uppercase">
|
||||
{stripLeft}
|
||||
</span>
|
||||
{stripRight ? (
|
||||
<span className="shrink-0 font-mono text-[9px] tracking-widest text-white/40 uppercase">
|
||||
{stripRight}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="px-3.5 py-3">{children}</div>
|
||||
{footer ? (
|
||||
<div className="flex shrink-0 items-stretch border-t border-white/15 bg-black/60 py-1.5 backdrop-blur-sm">
|
||||
{footer}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CornerBrackets() {
|
||||
const base = "pointer-events-none absolute size-2 border-white/25";
|
||||
return (
|
||||
<div aria-hidden className="pointer-events-none absolute inset-1 z-10">
|
||||
<span className={`${base} top-0 left-0 border-t border-l`} />
|
||||
<span className={`${base} top-0 right-0 border-t border-r`} />
|
||||
<span className={`${base} bottom-0 left-0 border-b border-l`} />
|
||||
<span className={`${base} right-0 bottom-0 border-r border-b`} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One readout-footer cell (value + tiny uppercase label), hairline-separated. */
|
||||
export function ReadoutCell({
|
||||
value,
|
||||
label,
|
||||
accent = "text-white/80",
|
||||
}: {
|
||||
value: string;
|
||||
label: string;
|
||||
accent?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center border-r border-white/15 px-2 last:border-r-0">
|
||||
<span className={`font-mono text-xs tabular-nums ${accent}`}>{value}</span>
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/50 uppercase">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
327
src/components/frontend/techTree/FrontendTechTreeCanvas.tsx
Normal file
327
src/components/frontend/techTree/FrontendTechTreeCanvas.tsx
Normal file
|
|
@ -0,0 +1,327 @@
|
|||
"use client";
|
||||
|
||||
import {
|
||||
Background,
|
||||
BackgroundVariant,
|
||||
Controls,
|
||||
MarkerType,
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
type Edge,
|
||||
type EdgeTypes,
|
||||
type Node,
|
||||
type NodeTypes,
|
||||
} from "@xyflow/react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
import React from "react";
|
||||
|
||||
import { CategoryBand } from "@/components/admin/tech-tree/CategoryBand";
|
||||
import { computeLayout } from "@/components/admin/tech-tree/layout";
|
||||
import { edgeVisuals, type EdgeRef } from "@/components/admin/tech-tree/edgeVisuals";
|
||||
import { type RouteRect } from "@/components/admin/tech-tree/edgeRouting";
|
||||
import { RoutedEdge } from "@/components/admin/tech-tree/RoutedEdge";
|
||||
import { TechNodeCard, type TechNodeModel } from "@/components/admin/tech-tree/TechNode";
|
||||
import {
|
||||
COLUMN_STEP,
|
||||
NODE_HEIGHT,
|
||||
NODE_WIDTH,
|
||||
type TreeCategory,
|
||||
type TreeTech,
|
||||
} from "@/components/admin/tech-tree/types";
|
||||
|
||||
import { VeilNodeCard, type VeilNodeModel } from "./VeilNodeCard";
|
||||
import { formatDateTime, formatDuration, type TechViewState } from "./types";
|
||||
|
||||
/**
|
||||
* Read-only member-facing tech tree canvas.
|
||||
*
|
||||
* Shares every visual building block with the admin editor (TechNodeCard,
|
||||
* CategoryBand, RoutedEdge, layout.ts, edgeVisuals.ts) so the two views render
|
||||
* identically; only the shell differs: no dragging, no connecting, no toolbar
|
||||
* edits, and locked technologies swap to the blackout veil card. Edge bends are
|
||||
* an admin localStorage feature and intentionally absent here (automatic
|
||||
* routing only).
|
||||
*/
|
||||
|
||||
const nodeTypes: NodeTypes = {
|
||||
techCard: TechNodeCard,
|
||||
techBand: CategoryBand,
|
||||
veilCard: VeilNodeCard,
|
||||
};
|
||||
|
||||
const edgeTypes: EdgeTypes = {
|
||||
routed: RoutedEdge,
|
||||
};
|
||||
|
||||
const SNAP_GRID = 46;
|
||||
|
||||
function refLabel(id: number): string {
|
||||
return `REF ${id.toString().padStart(3, "0")}`;
|
||||
}
|
||||
|
||||
function withAlpha(hex: string, alpha: number): string {
|
||||
const value = hex.replace("#", "");
|
||||
const r = parseInt(value.slice(0, 2), 16);
|
||||
const g = parseInt(value.slice(2, 4), 16);
|
||||
const b = parseInt(value.slice(4, 6), 16);
|
||||
return `rgba(${r},${g},${b},${alpha})`;
|
||||
}
|
||||
|
||||
/** Status strip rendered inside the shared TechNodeCard via its overlay slot. */
|
||||
function StatusOverlay({ status }: { status: TechViewState }) {
|
||||
if (status.state === "unlocked") {
|
||||
return (
|
||||
<div className="shrink-0 border-t border-white/10 bg-black/40 px-3.5 py-1">
|
||||
<span className="font-mono text-[8px] tracking-widest text-emerald-400 uppercase">
|
||||
Unlocked {formatDateTime(status.researchedAt)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (status.state === "researching" && status.startedAt && status.etaAt) {
|
||||
const start = Date.parse(status.startedAt);
|
||||
const eta = Date.parse(status.etaAt);
|
||||
const now = Date.now();
|
||||
const progress = eta > start ? Math.min(1, Math.max(0, (now - start) / (eta - start))) : 0;
|
||||
return (
|
||||
<div className="shrink-0 border-t border-white/10 bg-black/40 px-3.5 py-1">
|
||||
<div className="h-1 w-full overflow-hidden bg-white/10">
|
||||
<div
|
||||
className="h-full bg-[#22d3ee]"
|
||||
style={{ width: `${Math.round(progress * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-1 flex items-center justify-between gap-2">
|
||||
<span className="font-mono text-[8px] tracking-widest text-[#22d3ee] uppercase">
|
||||
Researching {Math.round(progress * 100)}%
|
||||
</span>
|
||||
<span className="font-mono text-[8px] tracking-widest text-white/45 uppercase tabular-nums">
|
||||
ETA {formatDuration(eta - now)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (status.state === "queued") {
|
||||
return (
|
||||
<div className="shrink-0 border-t border-white/10 bg-black/40 px-3.5 py-1">
|
||||
<span className="font-mono text-[8px] tracking-widest text-amber-300 uppercase">
|
||||
Queued for research
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (status.state === "available") {
|
||||
return (
|
||||
<div className="shrink-0 border-t border-white/10 bg-black/40 px-3.5 py-1">
|
||||
<span className="font-mono text-[8px] tracking-widest text-cyan-300 uppercase">
|
||||
Available // votable
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildNodes(
|
||||
techs: TreeTech[],
|
||||
categories: TreeCategory[],
|
||||
statuses: Record<number, TechViewState>,
|
||||
layout: ReturnType<typeof computeLayout>,
|
||||
): Node[] {
|
||||
const categoryById = new Map(categories.map((c) => [c.id, c]));
|
||||
|
||||
const bandNodes: Node[] = layout.bands.map((band) => {
|
||||
const memberIds =
|
||||
band.key === "uncategorized"
|
||||
? techs.filter((t) => t.categoryId === null || !categoryById.has(t.categoryId)).map((t) => t.id)
|
||||
: techs
|
||||
.filter((t) => t.categoryId === Number(band.key.replace("cat-", "")))
|
||||
.map((t) => t.id);
|
||||
return {
|
||||
id: band.key,
|
||||
type: "techBand",
|
||||
position: { x: band.x, y: band.y },
|
||||
// Read-only shell: bands are pure backdrops here (no header drag).
|
||||
draggable: false,
|
||||
selectable: false,
|
||||
deletable: false,
|
||||
zIndex: 0,
|
||||
style: { width: band.width, height: band.height, pointerEvents: "none" },
|
||||
data: { band, techCount: memberIds.length, memberIds },
|
||||
};
|
||||
});
|
||||
|
||||
const techById = new Map(techs.map((t) => [t.id, t]));
|
||||
const techNodes: (TechNodeModel | VeilNodeModel)[] = layout.nodes.map((node) => {
|
||||
const tech = techById.get(node.techId)!;
|
||||
const status = statuses[tech.id] ?? { state: "locked" as const };
|
||||
if (status.state === "locked") {
|
||||
return {
|
||||
id: String(tech.id),
|
||||
type: "veilCard",
|
||||
position: { x: node.x, y: node.y },
|
||||
zIndex: 1,
|
||||
style: { width: NODE_WIDTH, height: NODE_HEIGHT },
|
||||
draggable: false,
|
||||
data: { techId: tech.id },
|
||||
} satisfies VeilNodeModel;
|
||||
}
|
||||
return {
|
||||
id: String(tech.id),
|
||||
type: "techCard",
|
||||
position: { x: node.x, y: node.y },
|
||||
zIndex: 1,
|
||||
style: { width: NODE_WIDTH, height: NODE_HEIGHT },
|
||||
draggable: false,
|
||||
data: {
|
||||
tech,
|
||||
categoryName: tech.categoryId ? categoryById.get(tech.categoryId)?.name ?? null : null,
|
||||
refLabel: refLabel(tech.id),
|
||||
hasWarning: false,
|
||||
conflict: false,
|
||||
connectable: false,
|
||||
overlay: <StatusOverlay status={status} />,
|
||||
},
|
||||
} satisfies TechNodeModel;
|
||||
});
|
||||
|
||||
return [...bandNodes, ...techNodes];
|
||||
}
|
||||
|
||||
function buildEdges(
|
||||
techs: TreeTech[],
|
||||
layout: ReturnType<typeof computeLayout>,
|
||||
selectedId: string | null,
|
||||
): Edge[] {
|
||||
const known = new Set(techs.map((t) => t.id));
|
||||
const refs: EdgeRef[] = [];
|
||||
const isOr = new Set<string>();
|
||||
for (const tech of techs) {
|
||||
for (const prereqId of tech.prereqAnd) {
|
||||
if (prereqId === tech.id || !known.has(prereqId)) continue;
|
||||
refs.push({ id: `and-${prereqId}-${tech.id}`, source: prereqId, target: tech.id });
|
||||
}
|
||||
for (const prereqId of tech.prereqOr) {
|
||||
if (prereqId === tech.id || !known.has(prereqId)) continue;
|
||||
const id = `or-${prereqId}-${tech.id}`;
|
||||
if (refs.some((r) => r.id === id)) continue;
|
||||
refs.push({ id, source: prereqId, target: tech.id });
|
||||
isOr.add(id);
|
||||
}
|
||||
}
|
||||
|
||||
const positions = new Map(layout.nodes.map((n) => [n.techId, { x: n.x, y: n.y }]));
|
||||
const visuals = edgeVisuals(techs, refs, positions, COLUMN_STEP);
|
||||
const focus = selectedId ? Number(selectedId) : null;
|
||||
|
||||
const obstacles: RouteRect[] = layout.nodes.map((n) => ({
|
||||
id: n.techId,
|
||||
x: n.x,
|
||||
y: n.y,
|
||||
width: NODE_WIDTH,
|
||||
height: NODE_HEIGHT,
|
||||
}));
|
||||
|
||||
return refs.map((ref) => {
|
||||
const visual = visuals.get(ref.id)!;
|
||||
const or = isOr.has(ref.id);
|
||||
const related = focus === null || ref.source === focus || ref.target === focus;
|
||||
const alpha = focus === null ? 0.8 : related ? 1 : 0.12;
|
||||
const stroke = withAlpha(visual.color, alpha);
|
||||
const routeId = `${ref.source}:${ref.target}`;
|
||||
return {
|
||||
id: ref.id,
|
||||
source: String(ref.source),
|
||||
target: String(ref.target),
|
||||
type: "routed",
|
||||
animated: or,
|
||||
selectable: false,
|
||||
zIndex: focus !== null && related ? 2 : 0,
|
||||
style: {
|
||||
stroke,
|
||||
strokeWidth: focus !== null && related ? 2.25 : 1.5,
|
||||
...(or ? { strokeDasharray: "6 4" } : {}),
|
||||
},
|
||||
markerEnd: { type: MarkerType.ArrowClosed, color: stroke },
|
||||
...(or
|
||||
? {
|
||||
label: "OR",
|
||||
labelStyle: { fill: stroke, fontSize: 9, fontFamily: "monospace" },
|
||||
labelBgStyle: { fill: "rgba(0,0,0,0.85)", fillOpacity: 0.9 },
|
||||
}
|
||||
: {}),
|
||||
data: {
|
||||
pathRoot: visual.pathRoot,
|
||||
waypoints: [],
|
||||
routeId,
|
||||
sourceId: ref.source,
|
||||
targetId: ref.target,
|
||||
obstacles,
|
||||
stepPosition: visual.stepPosition,
|
||||
editable: false,
|
||||
onRouteChange: () => {},
|
||||
},
|
||||
} as Edge;
|
||||
});
|
||||
}
|
||||
|
||||
export interface FrontendTechTreeCanvasProps {
|
||||
techs: TreeTech[];
|
||||
categories: TreeCategory[];
|
||||
statuses: Record<number, TechViewState>;
|
||||
selectedId: number | null;
|
||||
onSelect: (technologyId: number) => void;
|
||||
}
|
||||
|
||||
function CanvasInner({ techs, categories, statuses, selectedId, onSelect }: FrontendTechTreeCanvasProps) {
|
||||
const layout = React.useMemo(() => computeLayout(techs, categories), [techs, categories]);
|
||||
const nodes = React.useMemo(() => buildNodes(techs, categories, statuses, layout), [techs, categories, statuses, layout]);
|
||||
const edges = React.useMemo(
|
||||
() => buildEdges(techs, layout, selectedId != null ? String(selectedId) : null),
|
||||
[techs, layout, selectedId],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative frontend-tech-tree h-full w-full"
|
||||
style={{ backgroundColor: "#05070a" }}
|
||||
data-testid="frontend-tech-tree-canvas"
|
||||
>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
edgeTypes={edgeTypes}
|
||||
fitView
|
||||
fitViewOptions={{ padding: 0.15, maxZoom: 0.85 }}
|
||||
minZoom={0.08}
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
elementsSelectable={false}
|
||||
proOptions={{ hideAttribution: false }}
|
||||
onNodeClick={(_, node) => {
|
||||
if (node.type === "techCard" || node.type === "veilCard") {
|
||||
onSelect(Number(node.id));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Background
|
||||
variant={BackgroundVariant.Lines}
|
||||
gap={SNAP_GRID}
|
||||
size={1}
|
||||
color="rgba(255,255,255,0.055)"
|
||||
/>
|
||||
<Controls showInteractive={false} />
|
||||
</ReactFlow>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function FrontendTechTreeCanvas(props: FrontendTechTreeCanvasProps) {
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<CanvasInner {...props} />
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
}
|
||||
98
src/components/frontend/techTree/ResearchPanel.tsx
Normal file
98
src/components/frontend/techTree/ResearchPanel.tsx
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
"use client";
|
||||
|
||||
import React from "react";
|
||||
|
||||
import { DossierPanel, ReadoutCell } from "./DossierPanel";
|
||||
import { formatDateTime, formatDuration, type ActiveResearchView, type QueuedResearchView, type ResearchStatsView } from "./types";
|
||||
|
||||
/** Active + queued research with live progress and ETA. */
|
||||
export function ResearchPanel({
|
||||
active,
|
||||
queued,
|
||||
stats,
|
||||
}: {
|
||||
active: ActiveResearchView[];
|
||||
queued: QueuedResearchView[];
|
||||
stats: ResearchStatsView;
|
||||
}) {
|
||||
const now = Date.now();
|
||||
return (
|
||||
<DossierPanel
|
||||
stripLeft="R&D // ACTIVE PROGRAM"
|
||||
stripRight={`REF ${String(active[0]?.id ?? 0).padStart(3, "0")}`}
|
||||
footer={
|
||||
<>
|
||||
<ReadoutCell value={`${active.length}/${stats.slots}`} label="Active/Slots" />
|
||||
<ReadoutCell value={String(queued.length)} label="Queued" />
|
||||
</>
|
||||
}
|
||||
>
|
||||
{!stats.enabled ? (
|
||||
<p className="font-mono text-[10px] tracking-wider text-amber-300/90 uppercase">
|
||||
Research program offline
|
||||
</p>
|
||||
) : active.length === 0 && queued.length === 0 ? (
|
||||
<p className="text-xs text-white/55">
|
||||
No active research.
|
||||
{stats.slots === 0
|
||||
? " An operational research facility staffed with researchers is required to begin."
|
||||
: " The next ballot opens automatically when a slot frees up."}
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{active.map((research) => {
|
||||
const start = research.startedAt ? Date.parse(research.startedAt) : null;
|
||||
const eta = research.etaAt ? Date.parse(research.etaAt) : null;
|
||||
const progress =
|
||||
start && eta && eta > start
|
||||
? Math.min(1, Math.max(0, (now - start) / (eta - start)))
|
||||
: 0;
|
||||
return (
|
||||
<div key={research.id} data-testid={`tech-research-${research.id}`}>
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<span className="truncate text-sm font-semibold text-white">{research.name}</span>
|
||||
<span className="shrink-0 font-mono text-[9px] tracking-widest text-[#22d3ee] uppercase tabular-nums">
|
||||
{Math.round(progress * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1.5 h-1.5 w-full overflow-hidden bg-white/10">
|
||||
<div className="h-full bg-[#22d3ee]" style={{ width: `${progress * 100}%` }} />
|
||||
</div>
|
||||
<div className="mt-1 flex items-center justify-between gap-2">
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/45 uppercase">
|
||||
Started {formatDateTime(research.startedAt)}
|
||||
</span>
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/65 uppercase tabular-nums">
|
||||
ETA {eta ? formatDuration(eta - now) : "n/a"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{queued.length > 0 ? (
|
||||
<div className="border-t border-white/10 pt-2">
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/45 uppercase">
|
||||
In queue
|
||||
</span>
|
||||
<ul className="mt-1 space-y-1">
|
||||
{queued.map((research) => (
|
||||
<li
|
||||
key={research.id}
|
||||
className="flex items-center gap-2 font-mono text-[10px] text-amber-200/90"
|
||||
data-testid={`tech-queued-${research.id}`}
|
||||
>
|
||||
<span aria-hidden className="text-amber-300/70">▸</span>
|
||||
<span className="truncate">{research.name}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-1.5 text-[10px] text-white/45">
|
||||
Queued work starts when pooled facility storage can cover its costs.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</DossierPanel>
|
||||
);
|
||||
}
|
||||
136
src/components/frontend/techTree/TechDetailDialog.tsx
Normal file
136
src/components/frontend/techTree/TechDetailDialog.tsx
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
"use client";
|
||||
|
||||
import { RichText } from "@payloadcms/richtext-lexical/react";
|
||||
import React from "react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
|
||||
import { formatDateTime, formatDuration, type TechDetailView } from "./types";
|
||||
|
||||
const STATE_LABEL: Record<TechDetailView["state"], { label: string; className: string }> = {
|
||||
unlocked: { label: "Unlocked", className: "text-emerald-400" },
|
||||
researching: { label: "Researching", className: "text-[#22d3ee]" },
|
||||
queued: { label: "Queued", className: "text-amber-300" },
|
||||
available: { label: "Available", className: "text-cyan-300" },
|
||||
locked: { label: "Undiscovered", className: "text-white/40" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Technology detail dialog (node click): summary, rich description, research
|
||||
* costs, prerequisites with their live state, and the current research status.
|
||||
* Conventional shadcn dialog styling per the style guide (dialogs stay out of
|
||||
* the dossier treatment).
|
||||
*/
|
||||
export function TechDetailDialog({
|
||||
detail,
|
||||
nameOf,
|
||||
onClose,
|
||||
}: {
|
||||
detail: TechDetailView | null;
|
||||
nameOf: (technologyId: number) => string;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
if (!detail) return null;
|
||||
const state = STATE_LABEL[detail.state];
|
||||
const now = Date.now();
|
||||
const start = detail.startedAt ? Date.parse(detail.startedAt) : null;
|
||||
const eta = detail.etaAt ? Date.parse(detail.etaAt) : null;
|
||||
const progress =
|
||||
start && eta && eta > start ? Math.min(1, Math.max(0, (now - start) / (eta - start))) : 0;
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-3">
|
||||
<span>{detail.name}</span>
|
||||
<span className={`font-mono text-[10px] tracking-widest uppercase ${state.className}`}>
|
||||
{state.label}
|
||||
</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="max-h-[60vh] space-y-4 overflow-y-auto pr-1">
|
||||
<p className="text-sm text-white/75">{detail.summary}</p>
|
||||
|
||||
{detail.description ? (
|
||||
<div className="prose prose-sm prose-invert max-w-none text-sm text-white/70 [&_a]:text-cyan-400">
|
||||
<RichText data={detail.description as never} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{detail.state === "researching" && eta ? (
|
||||
<div>
|
||||
<div className="mb-1 flex items-center justify-between font-mono text-[10px] tracking-widest text-white/55 uppercase">
|
||||
<span>Research progress</span>
|
||||
<span className="tabular-nums">
|
||||
ETA {formatDuration(eta - now)} ({formatDateTime(detail.etaAt)})
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 w-full overflow-hidden bg-white/10">
|
||||
<div className="h-full bg-[#22d3ee]" style={{ width: `${progress * 100}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{detail.state === "unlocked" ? (
|
||||
<p className="font-mono text-[10px] tracking-widest text-emerald-400 uppercase">
|
||||
Unlocked {formatDateTime(detail.researchedAt)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<section>
|
||||
<h3 className="mb-1.5 font-mono text-[10px] tracking-widest text-white/50 uppercase">
|
||||
Research costs
|
||||
</h3>
|
||||
{detail.resourceCosts.length === 0 ? (
|
||||
<p className="text-xs text-white/45">No resource costs.</p>
|
||||
) : (
|
||||
<ul className="space-y-1">
|
||||
{detail.resourceCosts.map((cost) => (
|
||||
<li key={cost.resourceId} className="flex items-center justify-between text-xs">
|
||||
<span className="text-white/70">{cost.name}</span>
|
||||
<span className="font-mono tabular-nums text-white/85">{cost.amount}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="mt-1.5 font-mono text-[9px] tracking-wider text-white/40 uppercase">
|
||||
Duration {detail.minimumResearchDuration ?? "n/a"}
|
||||
{detail.maximumResearchDuration != null &&
|
||||
detail.maximumResearchDuration !== detail.minimumResearchDuration
|
||||
? `-${detail.maximumResearchDuration}`
|
||||
: ""}{" "}
|
||||
ticks (minimum is the speed floor)
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{detail.prereqAndIds.length + detail.prereqOrIds.length > 0 ? (
|
||||
<section>
|
||||
<h3 className="mb-1.5 font-mono text-[10px] tracking-widest text-white/50 uppercase">
|
||||
Prerequisites
|
||||
</h3>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{detail.prereqAndIds.map((id) => (
|
||||
<Badge key={`and-${id}`} variant="outline" className="rounded-sm text-[10px]">
|
||||
{nameOf(id)}
|
||||
</Badge>
|
||||
))}
|
||||
{detail.prereqOrIds.map((id) => (
|
||||
<Badge
|
||||
key={`or-${id}`}
|
||||
variant="outline"
|
||||
className="rounded-sm border-cyan-400/40 text-[10px] text-cyan-200"
|
||||
>
|
||||
OR {nameOf(id)}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
100
src/components/frontend/techTree/TechTreeClient.tsx
Normal file
100
src/components/frontend/techTree/TechTreeClient.tsx
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
"use client";
|
||||
|
||||
import React from "react";
|
||||
|
||||
import { DossierPanel, ReadoutCell } from "./DossierPanel";
|
||||
import { BallotPanel } from "./BallotPanel";
|
||||
import { FrontendTechTreeCanvas } from "./FrontendTechTreeCanvas";
|
||||
import { ResearchPanel } from "./ResearchPanel";
|
||||
import { TechDetailDialog } from "./TechDetailDialog";
|
||||
import type {
|
||||
ActiveResearchView,
|
||||
BallotView,
|
||||
QueuedResearchView,
|
||||
ResearchStatsView,
|
||||
TechDetailView,
|
||||
TechViewState,
|
||||
TreeCategory,
|
||||
TreeTech,
|
||||
} from "./types";
|
||||
|
||||
export interface TechTreeClientProps {
|
||||
techs: TreeTech[];
|
||||
categories: TreeCategory[];
|
||||
statuses: Record<number, TechViewState>;
|
||||
details: Record<number, TechDetailView>;
|
||||
activeResearch: ActiveResearchView[];
|
||||
queuedResearch: QueuedResearchView[];
|
||||
ballot: BallotView | null;
|
||||
stats: ResearchStatsView;
|
||||
}
|
||||
|
||||
/**
|
||||
* Member-facing tech tree surface: read-only canvas + dossier side column
|
||||
* (active research, open ballot, unit R&D stats). Node click opens the detail
|
||||
* dialog; veiled (locked) technologies deliberately have no detail payload.
|
||||
*/
|
||||
export function TechTreeClient({
|
||||
techs,
|
||||
categories,
|
||||
statuses,
|
||||
details,
|
||||
activeResearch,
|
||||
queuedResearch,
|
||||
ballot,
|
||||
stats,
|
||||
}: TechTreeClientProps) {
|
||||
const [selectedId, setSelectedId] = React.useState<number | null>(null);
|
||||
const selectedDetail = selectedId != null ? (details[selectedId] ?? null) : null;
|
||||
|
||||
const nameOf = React.useCallback(
|
||||
(technologyId: number) =>
|
||||
techs.find((tech) => tech.id === technologyId)?.name ?? `Technology #${technologyId}`,
|
||||
[techs],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col gap-4 xl:flex-row">
|
||||
<div className="min-h-[420px] flex-1 overflow-hidden rounded-none border border-white/15">
|
||||
<FrontendTechTreeCanvas
|
||||
techs={techs}
|
||||
categories={categories}
|
||||
statuses={statuses}
|
||||
selectedId={selectedId}
|
||||
onSelect={setSelectedId}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<aside className="flex w-full shrink-0 flex-col gap-4 overflow-y-auto xl:w-[340px]">
|
||||
<BallotPanel ballot={ballot} />
|
||||
<ResearchPanel active={activeResearch} queued={queuedResearch} stats={stats} />
|
||||
<DossierPanel
|
||||
stripLeft="R&D // UNIT CAPACITY"
|
||||
footer={
|
||||
<>
|
||||
<ReadoutCell value={`${stats.facilityCount}`} label="Facilities" accent="text-cyan-200" />
|
||||
<ReadoutCell value={`${stats.totalResearchers}`} label="Researchers" accent="text-cyan-200" />
|
||||
<ReadoutCell
|
||||
value={`+${Math.round(stats.totalModifier * 1000) / 10}%`}
|
||||
label="Speed"
|
||||
accent="text-emerald-300"
|
||||
/>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="text-xs text-white/60">
|
||||
{stats.slots === 0
|
||||
? "No research capacity: facilities must be operational with at least one researcher (labor classification 'researcher')."
|
||||
: `Parallel research slots online: ${stats.slots}. Slots come from operational, staffed research facilities.`}
|
||||
</p>
|
||||
</DossierPanel>
|
||||
</aside>
|
||||
|
||||
<TechDetailDialog
|
||||
detail={selectedDetail}
|
||||
nameOf={nameOf}
|
||||
onClose={() => setSelectedId(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
src/components/frontend/techTree/VeilNodeCard.tsx
Normal file
58
src/components/frontend/techTree/VeilNodeCard.tsx
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"use client";
|
||||
|
||||
import { Handle, Position, type Node, type NodeProps } from "@xyflow/react";
|
||||
import React from "react";
|
||||
|
||||
export type VeilNodeData = {
|
||||
techId: number;
|
||||
};
|
||||
|
||||
export type VeilNodeModel = Node<VeilNodeData, "veilCard">;
|
||||
|
||||
/**
|
||||
* Full-blackout card for approved-but-locked technologies on the member-facing
|
||||
* tree: no name, no color, just "UNDISCOVERED TECHNOLOGY". It keeps the admin
|
||||
* card's footprint and handles so prerequisite edges still route to it, letting
|
||||
* the tree shape hint at hidden branches.
|
||||
*/
|
||||
export function VeilNodeCard({ selected }: NodeProps<VeilNodeModel>) {
|
||||
return (
|
||||
<div data-testid="tech-veil-node" className="relative h-full w-full">
|
||||
<div
|
||||
className={`flex h-full w-full flex-col items-center justify-center gap-2 overflow-hidden rounded-none border bg-black backdrop-blur-sm transition-colors ${
|
||||
selected ? "border-[#22d3ee]/70" : "border-white/10 hover:border-white/25"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="font-mono text-[16px] leading-none tracking-widest text-white/15 select-none"
|
||||
>
|
||||
???
|
||||
</span>
|
||||
<span className="px-3 text-center font-mono text-[8px] leading-relaxed tracking-[0.2em] text-white/40 uppercase">
|
||||
Undiscovered
|
||||
<br />
|
||||
Technology
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Visible-but-inert handles: React Flow measures handle bounds from the
|
||||
DOM, so a display:none handle would drop incoming/outgoing edges. The
|
||||
member tree must keep edges routed to veiled techs. */}
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Left}
|
||||
className="!bg-white/25"
|
||||
style={{ width: 8, height: 8, border: "1px solid rgba(0,0,0,0.6)" }}
|
||||
isConnectable={false}
|
||||
/>
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Right}
|
||||
className="!bg-white/25"
|
||||
style={{ width: 8, height: 8, border: "1px solid rgba(0,0,0,0.6)" }}
|
||||
isConnectable={false}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
61
src/components/frontend/techTree/VoteButton.tsx
Normal file
61
src/components/frontend/techTree/VoteButton.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import React from "react";
|
||||
import { useTransition } from "react";
|
||||
|
||||
import { castTechVote } from "@/app/(frontend)/intelligence/tech-tree/actions";
|
||||
|
||||
/**
|
||||
* Cast/change the caller's vote on a ballot option. Tactical squared button
|
||||
* (the panel it lives in is the dossier surface; the button stays compact per
|
||||
* the style guide's "never dossier on buttons" rule but keeps the mono look).
|
||||
*/
|
||||
export function VoteButton({
|
||||
ballotId,
|
||||
technologyId,
|
||||
isMyVote,
|
||||
disabled,
|
||||
}: {
|
||||
ballotId: number;
|
||||
technologyId: number;
|
||||
isMyVote: boolean;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [pending, startTransition] = useTransition();
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const onClick = () => {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const result = await castTechVote({ ballotId, technologyId });
|
||||
if (!result.success) {
|
||||
setError(result.error ?? "Vote failed.");
|
||||
return;
|
||||
}
|
||||
router.refresh();
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<span className="inline-flex flex-col items-end gap-0.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={pending || disabled}
|
||||
data-testid={`tech-vote-${technologyId}`}
|
||||
className={`rounded-none border px-2 py-1 font-mono text-[9px] tracking-widest uppercase transition-colors ${
|
||||
isMyVote
|
||||
? "border-[#22d3ee]/60 bg-[#22d3ee]/15 text-[#a5f3fc]"
|
||||
: "border-white/20 bg-black/50 text-white/75 hover:border-white/45 hover:bg-white/10 hover:text-white"
|
||||
} disabled:cursor-not-allowed disabled:opacity-50`}
|
||||
>
|
||||
{pending ? "Saving…" : isMyVote ? "Voted ✓" : "Cast Vote"}
|
||||
</button>
|
||||
{error ? (
|
||||
<span className="font-mono text-[8px] text-red-400">{error}</span>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
94
src/components/frontend/techTree/types.ts
Normal file
94
src/components/frontend/techTree/types.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import type { TreeCategory, TreeTech } from "@/components/admin/tech-tree/types";
|
||||
|
||||
export type { TreeCategory, TreeTech };
|
||||
|
||||
/** Per-technology view state for the member-facing tree. */
|
||||
export type TechViewState = {
|
||||
state: "unlocked" | "researching" | "queued" | "available" | "locked";
|
||||
/** Active research timing (ISO strings) for the progress overlay. */
|
||||
startedAt?: string | null;
|
||||
etaAt?: string | null;
|
||||
/** Unlocked date (ISO) for the unlocked overlay. */
|
||||
researchedAt?: string | null;
|
||||
};
|
||||
|
||||
export type ActiveResearchView = {
|
||||
id: number;
|
||||
technologyId: number;
|
||||
name: string;
|
||||
startedAt: string | null;
|
||||
etaAt: string | null;
|
||||
};
|
||||
|
||||
export type QueuedResearchView = {
|
||||
id: number;
|
||||
technologyId: number;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type BallotOptionView = {
|
||||
technologyId: number;
|
||||
name: string;
|
||||
summary: string | null;
|
||||
rawVotes: number;
|
||||
};
|
||||
|
||||
export type BallotView = {
|
||||
id: number;
|
||||
status: "open" | "extended";
|
||||
closesAt: string;
|
||||
options: BallotOptionView[];
|
||||
myVote: number | null;
|
||||
totalVotes: number;
|
||||
};
|
||||
|
||||
export type ResearchStatsView = {
|
||||
enabled: boolean;
|
||||
slots: number;
|
||||
facilityCount: number;
|
||||
totalResearchers: number;
|
||||
/** Aggregate duration reduction, fraction (0.12 = research 12% faster). */
|
||||
totalModifier: number;
|
||||
};
|
||||
|
||||
export type TechDetailView = {
|
||||
technologyId: number;
|
||||
name: string;
|
||||
type: string;
|
||||
summary: string;
|
||||
description: unknown;
|
||||
state: TechViewState["state"];
|
||||
researchedAt: string | null;
|
||||
startedAt: string | null;
|
||||
etaAt: string | null;
|
||||
minimumResearchDuration: number | null;
|
||||
maximumResearchDuration: number | null;
|
||||
resourceCosts: { resourceId: number; name: string; amount: number }[];
|
||||
prereqAndIds: number[];
|
||||
prereqOrIds: number[];
|
||||
};
|
||||
|
||||
/** Compact relative-time formatter shared by panels ("3h 12m"). */
|
||||
export function formatDuration(ms: number): string {
|
||||
if (!Number.isFinite(ms) || ms <= 0) return "0m";
|
||||
const minutes = Math.round(ms / 60_000);
|
||||
if (minutes < 60) return `${minutes}m`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const restMinutes = minutes % 60;
|
||||
if (hours < 48) return restMinutes > 0 ? `${hours}h ${restMinutes}m` : `${hours}h`;
|
||||
const days = Math.floor(hours / 24);
|
||||
const restHours = hours % 24;
|
||||
return restHours > 0 ? `${days}d ${restHours}h` : `${days}d`;
|
||||
}
|
||||
|
||||
export function formatDateTime(iso: string | null | undefined): string {
|
||||
if (!iso) return "n/a";
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return "n/a";
|
||||
return date.toLocaleString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
|
@ -218,6 +218,10 @@ export function notificationLabel(type?: string | null): string {
|
|||
return "Removal denied";
|
||||
case "mission:role-promoted":
|
||||
return "Role slot granted";
|
||||
case "tech:ballot-open":
|
||||
return "Research ballot open";
|
||||
case "tech:research-complete":
|
||||
return "Research completed";
|
||||
default:
|
||||
return type ?? "Notification";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@ export const MUTEABLE_NOTIFICATION_TYPES = [
|
|||
{ label: "Contribution XP granted", value: "contribution:xp-granted" },
|
||||
{ label: "Contribution XP revoked", value: "contribution:xp-revoked" },
|
||||
{ label: "Minigame achievements", value: "minigame:achievement" },
|
||||
{ label: "Tech ballots", value: "tech:ballot-open" },
|
||||
{ label: "Research completed", value: "tech:research-complete" },
|
||||
] as const;
|
||||
export type MuteableNotificationType = (typeof MUTEABLE_NOTIFICATION_TYPES)[number]["value"];
|
||||
export const MUTEABLE_NOTIFICATION_VALUES = MUTEABLE_NOTIFICATION_TYPES.map((t) => t.value);
|
||||
|
|
|
|||
109
src/lib/tech/capacity.ts
Normal file
109
src/lib/tech/capacity.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import type { Payload } from "payload";
|
||||
|
||||
import {
|
||||
computeResearchCapacity,
|
||||
RESEARCHER_CLASSIFICATION_KEY,
|
||||
type ResearchCapacity,
|
||||
type ResearchFacilityInput,
|
||||
} from "./research";
|
||||
|
||||
export type ResearchFacilityRecord = ResearchFacilityInput & { name: string };
|
||||
|
||||
export type ResearchCapacitySnapshot = {
|
||||
/** Game Rules master gate (research.enabled). */
|
||||
enabled: boolean;
|
||||
tickMinutes: number;
|
||||
ballotDurationTicks: number;
|
||||
researcherSpeedPerHead: number;
|
||||
/** All research-facility instances (qualifying or not), id order. */
|
||||
facilities: ResearchFacilityRecord[];
|
||||
/** Aggregate over operational AND staffed facilities. */
|
||||
capacity: ResearchCapacity;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hydrate the unit's research capacity from live data: research-facility game
|
||||
* structures, their active `researcher`-classification labor headcount, and the
|
||||
* Game Rules research knobs. Shared by the tech tick and the member-facing
|
||||
* tech tree page so both agree on slots / speed / ETA math.
|
||||
*
|
||||
* The `researcher` labor classification is game data, not schema: if GMs never
|
||||
* create a doc with key `researcher`, every headcount is 0 and the researcher
|
||||
* bonus is simply 0 (documented behavior, not a crash).
|
||||
*/
|
||||
export async function loadResearchCapacity(payload: Payload): Promise<ResearchCapacitySnapshot> {
|
||||
const rules = await payload.findGlobal({
|
||||
slug: "game-rules",
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const ballotDurationTicks = rules.research?.ballotDurationTicks ?? 288;
|
||||
const researcherSpeedPerHead = rules.research?.researcherSpeedPerHead ?? 0.0001;
|
||||
|
||||
const facilitiesRes = await payload.find({
|
||||
collection: "game-structures",
|
||||
where: { isResearchFacility: { equals: true } },
|
||||
limit: 500,
|
||||
depth: 0,
|
||||
sort: "id",
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const headcountByStructure = new Map<number, number>();
|
||||
if (facilitiesRes.docs.length > 0) {
|
||||
const classification = await payload.find({
|
||||
collection: "labor-classifications",
|
||||
where: { key: { equals: RESEARCHER_CLASSIFICATION_KEY } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const classificationId = classification.docs[0]?.id;
|
||||
if (classificationId != null) {
|
||||
const staffing = await payload.find({
|
||||
collection: "npc-staffing",
|
||||
where: {
|
||||
and: [
|
||||
{ structure: { in: facilitiesRes.docs.map((doc) => doc.id) } },
|
||||
{ status: { equals: "active" } },
|
||||
{ positionType: { equals: "labor" } },
|
||||
{ laborClassification: { equals: classificationId } },
|
||||
],
|
||||
},
|
||||
limit: 1000,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
for (const row of staffing.docs) {
|
||||
const structureId =
|
||||
typeof row.structure === "object" && row.structure !== null ? row.structure.id : row.structure;
|
||||
if (typeof structureId !== "number") continue;
|
||||
headcountByStructure.set(
|
||||
structureId,
|
||||
(headcountByStructure.get(structureId) ?? 0) + (row.headcount ?? 1),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const facilities: ResearchFacilityRecord[] = facilitiesRes.docs
|
||||
.map((doc) => ({
|
||||
id: doc.id,
|
||||
name: doc.name,
|
||||
operational: doc.constructionStatus === "complete",
|
||||
researcherHeadcount: headcountByStructure.get(doc.id) ?? 0,
|
||||
researchSpeedModifier: doc.researchSpeedModifier ?? 0,
|
||||
researchSlots: doc.researchSlots ?? 0,
|
||||
}))
|
||||
.sort((a, b) => a.id - b.id);
|
||||
|
||||
return {
|
||||
enabled: rules.research?.enabled === true,
|
||||
tickMinutes: rules.gameTickIntervalMinutes ?? 10,
|
||||
ballotDurationTicks,
|
||||
researcherSpeedPerHead,
|
||||
facilities,
|
||||
capacity: computeResearchCapacity(facilities, researcherSpeedPerHead),
|
||||
};
|
||||
}
|
||||
350
src/lib/tech/research.ts
Normal file
350
src/lib/tech/research.ts
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
/**
|
||||
* Pure research-engine rules for the member-facing tech system.
|
||||
*
|
||||
* Client-safe: no Payload imports. The tick service (`src/lib/tech/tick.ts`)
|
||||
* hydrates these shapes from the database; the frontend reuses the same math
|
||||
* to render aggregate speed / ETA previews. Mechanics are decided (see the
|
||||
* feature plan): facility + researcher modifiers shorten duration down to the
|
||||
* technology's minimumResearchDuration floor, slots gate parallel research and
|
||||
* ballot opening, and ballot ties cascade intel-weight -> cheaper/shorter ->
|
||||
* oldest document.
|
||||
*/
|
||||
|
||||
/** Labor classification key whose active staff count as researchers. */
|
||||
export const RESEARCHER_CLASSIFICATION_KEY = "researcher";
|
||||
|
||||
/** Fallback tick length (minutes) when Game Rules has no gameTickIntervalMinutes. */
|
||||
export const DEFAULT_TICK_MINUTES = 10;
|
||||
|
||||
export type ResearchFacilityInput = {
|
||||
id: number;
|
||||
/** constructionStatus === "complete". */
|
||||
operational: boolean;
|
||||
/** Active labor staff in the researcher classification at this structure. */
|
||||
researcherHeadcount: number;
|
||||
/** Fractional duration reduction while qualifying (0.05 = 5% faster). */
|
||||
researchSpeedModifier?: number | null;
|
||||
/** Parallel capacity while qualifying. */
|
||||
researchSlots?: number | null;
|
||||
};
|
||||
|
||||
export type ResearchCapacity = {
|
||||
/** Operational AND staffed facilities. */
|
||||
facilityCount: number;
|
||||
totalResearchers: number;
|
||||
/** Sum of researchSlots over qualifying facilities (0 = no ballots). */
|
||||
slots: number;
|
||||
facilitySpeedModifier: number;
|
||||
researcherSpeedBonus: number;
|
||||
/** facilitySpeedModifier + researcherSpeedBonus. */
|
||||
totalModifier: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* A facility qualifies for the research engine only when it is operational and
|
||||
* has at least one researcher; everything else contributes nothing.
|
||||
*/
|
||||
export function qualifyingFacilities(
|
||||
facilities: readonly ResearchFacilityInput[],
|
||||
): ResearchFacilityInput[] {
|
||||
return facilities.filter((f) => f.operational && f.researcherHeadcount >= 1);
|
||||
}
|
||||
|
||||
export function computeResearchCapacity(
|
||||
facilities: readonly ResearchFacilityInput[],
|
||||
researcherSpeedPerHead: number,
|
||||
): ResearchCapacity {
|
||||
const qualifying = qualifyingFacilities(facilities);
|
||||
const totalResearchers = qualifying.reduce((sum, f) => sum + f.researcherHeadcount, 0);
|
||||
const facilitySpeedModifier = qualifying.reduce((sum, f) => sum + (f.researchSpeedModifier ?? 0), 0);
|
||||
const researcherSpeedBonus = totalResearchers * researcherSpeedPerHead;
|
||||
return {
|
||||
facilityCount: qualifying.length,
|
||||
totalResearchers,
|
||||
slots: qualifying.reduce((sum, f) => sum + (f.researchSlots ?? 0), 0),
|
||||
facilitySpeedModifier,
|
||||
researcherSpeedBonus,
|
||||
totalModifier: facilitySpeedModifier + researcherSpeedBonus,
|
||||
};
|
||||
}
|
||||
|
||||
export type ResearchDurationInput = {
|
||||
minimumResearchDuration?: number | null;
|
||||
maximumResearchDuration?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* effectiveTicks = max(minimumResearchDuration, round(base x (1 - totalModifier)))
|
||||
* where base = maximumResearchDuration ?? minimumResearchDuration.
|
||||
* The minimum IS the floor/cap on speed (explicit design choice): no modifier
|
||||
* combination can push research below it.
|
||||
*/
|
||||
export function effectiveDurationTicks(
|
||||
duration: ResearchDurationInput,
|
||||
totalModifier: number,
|
||||
): number {
|
||||
const minimum = normalizeTicks(duration.minimumResearchDuration);
|
||||
const maximum =
|
||||
typeof duration.maximumResearchDuration === "number" &&
|
||||
Number.isFinite(duration.maximumResearchDuration) &&
|
||||
duration.maximumResearchDuration > 0
|
||||
? duration.maximumResearchDuration
|
||||
: null;
|
||||
const base = maximum ?? minimum;
|
||||
const modifier = Number.isFinite(totalModifier) ? totalModifier : 0;
|
||||
const raw = Math.round(base * (1 - modifier));
|
||||
return Math.max(minimum, raw);
|
||||
}
|
||||
|
||||
function normalizeTicks(value?: number | null): number {
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value < 1) return 1;
|
||||
return Math.round(value);
|
||||
}
|
||||
|
||||
/** Convert a tick interval in minutes to milliseconds, with a sane fallback. */
|
||||
export function ticksToMilliseconds(ticks: number, tickMinutes: number): number {
|
||||
const minutes = ticks * (tickMinutes > 0 ? tickMinutes : DEFAULT_TICK_MINUTES);
|
||||
return minutes * 60_000;
|
||||
}
|
||||
|
||||
function relId(value: unknown): number | null {
|
||||
if (typeof value === "number") return value;
|
||||
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
|
||||
const id = (value as { id: unknown }).id;
|
||||
return typeof id === "number" ? id : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project a `technologies` doc (depth 0) into the EligibilityTech shape.
|
||||
* Mirrors the admin tree's mappers.ts AND/OR flattening. Accepts a loose doc
|
||||
* shape so both the tick service and server pages can hydrate without the
|
||||
* generated types leaking into the pure rules module.
|
||||
*/
|
||||
export function technologyToEligibility(doc: Record<string, any>): EligibilityTech {
|
||||
const rows = Array.isArray(doc.requirements?.prerequisiteTechnologies)
|
||||
? (doc.requirements.prerequisiteTechnologies as Record<string, any>[])
|
||||
: [];
|
||||
const prereqAnd: number[] = [];
|
||||
const prereqOr: number[] = [];
|
||||
for (const row of rows) {
|
||||
for (const t of (row?.requiresAnd?.technology ?? []) as unknown[]) {
|
||||
const id = relId(t);
|
||||
if (id != null) prereqAnd.push(id);
|
||||
}
|
||||
for (const t of (row?.requiresOr?.technology ?? []) as unknown[]) {
|
||||
const id = relId(t);
|
||||
if (id != null) prereqOr.push(id);
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: doc.id as number,
|
||||
approvalStatus: String(doc.approvalStatus ?? "in_progress"),
|
||||
researchedAt: doc.researchedAt ?? null,
|
||||
prereqAnd: [...new Set(prereqAnd)],
|
||||
prereqOr: [...new Set(prereqOr)],
|
||||
minimumResearchDuration: doc.researchCosts?.minimumResearchDuration ?? null,
|
||||
maximumResearchDuration: doc.researchCosts?.maximumResearchDuration ?? null,
|
||||
resourceCosts: ((doc.researchCosts?.resources ?? []) as any[])
|
||||
.map((row) => ({ resource: relId(row.resource) ?? 0, amount: row.amount ?? 0 })),
|
||||
createdAt: doc.createdAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export type PrereqState = {
|
||||
/** ALL of these must be researched. */
|
||||
prereqAnd: readonly number[];
|
||||
/** When non-empty, at least ONE of these must be researched. */
|
||||
prereqOr: readonly number[];
|
||||
};
|
||||
|
||||
/** Mirrors the admin tree's AND/OR semantics (mappers.ts flattening). */
|
||||
export function prereqsMet(tech: PrereqState, researchedIds: ReadonlySet<number>): boolean {
|
||||
const andMet = tech.prereqAnd.every((id) => researchedIds.has(id));
|
||||
if (!andMet) return false;
|
||||
if (tech.prereqOr.length === 0) return true;
|
||||
return tech.prereqOr.some((id) => researchedIds.has(id));
|
||||
}
|
||||
|
||||
export type EligibilityTech = PrereqState & {
|
||||
id: number;
|
||||
approvalStatus: string;
|
||||
researchedAt?: string | null;
|
||||
minimumResearchDuration?: number | null;
|
||||
maximumResearchDuration?: number | null;
|
||||
resourceCosts?: readonly { resource: number; amount: number }[];
|
||||
createdAt?: string | null;
|
||||
};
|
||||
|
||||
export type EligibilityContext = {
|
||||
/** Ids of technologies with researchedAt set. */
|
||||
researchedIds: ReadonlySet<number>;
|
||||
/** Ids with a queued or active tech-researches doc. */
|
||||
busyIds: ReadonlySet<number>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Eligible for a ballot: approved, not yet researched, not already queued or
|
||||
* active, prerequisites met. Only approved techs render at all on the tree.
|
||||
*/
|
||||
export function isEligibleForBallot(
|
||||
tech: EligibilityTech,
|
||||
ctx: EligibilityContext,
|
||||
): boolean {
|
||||
if (tech.approvalStatus !== "approved") return false;
|
||||
// Either signal counts: the doc's own researchedAt, or the caller's set of
|
||||
// researched ids (kept in sync by the tick service).
|
||||
if (tech.researchedAt || ctx.researchedIds.has(tech.id)) return false;
|
||||
if (ctx.busyIds.has(tech.id)) return false;
|
||||
return prereqsMet(tech, ctx.researchedIds);
|
||||
}
|
||||
|
||||
export function eligibleTechs<T extends EligibilityTech>(
|
||||
techs: readonly T[],
|
||||
ctx: EligibilityContext,
|
||||
): T[] {
|
||||
return techs.filter((tech) => isEligibleForBallot(tech, ctx));
|
||||
}
|
||||
|
||||
/** Total listed resource cost (the "cheaper" half of the tie cascade). */
|
||||
export function costScore(tech: {
|
||||
resourceCosts?: readonly { amount: number }[] | null;
|
||||
}): number {
|
||||
return (tech.resourceCosts ?? []).reduce((sum, row) => sum + (row.amount ?? 0), 0);
|
||||
}
|
||||
|
||||
/** Base duration before modifiers (the "shorter" half of the tie cascade). */
|
||||
export function baseDurationTicks(tech: ResearchDurationInput): number {
|
||||
const minimum = normalizeTicks(tech.minimumResearchDuration);
|
||||
const maximum =
|
||||
typeof tech.maximumResearchDuration === "number" &&
|
||||
Number.isFinite(tech.maximumResearchDuration) &&
|
||||
tech.maximumResearchDuration > 0
|
||||
? tech.maximumResearchDuration
|
||||
: null;
|
||||
return maximum ?? minimum;
|
||||
}
|
||||
|
||||
/** The subset of a candidate the tie cascade compares on. */
|
||||
export type CascadeCandidate = Pick<
|
||||
EligibilityTech,
|
||||
"id" | "minimumResearchDuration" | "maximumResearchDuration" | "createdAt"
|
||||
> & { resourceCosts?: readonly { amount: number }[] | null };
|
||||
|
||||
/**
|
||||
* Tie cascade between two candidates: cheaper first, then shorter, then the
|
||||
* oldest document (createdAt asc, id asc as the deterministic final key).
|
||||
*/
|
||||
export function compareCheaperShorterOldest(a: CascadeCandidate, b: CascadeCandidate): number {
|
||||
const cost = costScore(a) - costScore(b);
|
||||
if (cost !== 0) return cost;
|
||||
const duration = baseDurationTicks(a) - baseDurationTicks(b);
|
||||
if (duration !== 0) return duration;
|
||||
const aCreated = a.createdAt ? Date.parse(a.createdAt) : Number.MAX_SAFE_INTEGER;
|
||||
const bCreated = b.createdAt ? Date.parse(b.createdAt) : Number.MAX_SAFE_INTEGER;
|
||||
if (aCreated !== bCreated) return aCreated - bCreated;
|
||||
return a.id - b.id;
|
||||
}
|
||||
|
||||
export type BallotTallyOption = {
|
||||
technologyId: number;
|
||||
/** Frozen option metadata for tie-breaking. */
|
||||
tech: CascadeCandidate;
|
||||
};
|
||||
|
||||
export type BallotVoteRow = {
|
||||
userId: number;
|
||||
technologyId: number;
|
||||
};
|
||||
|
||||
export type TallyCounts = Record<number, { raw: number; weighted: number }>;
|
||||
|
||||
export type BallotTallyResult = {
|
||||
counts: TallyCounts;
|
||||
totalVotes: number;
|
||||
winnerId: number | null;
|
||||
method: "votes" | "tie-cascade" | "no-votes";
|
||||
};
|
||||
|
||||
/** Intelligence-qualified votes count double (resolved at tally time). */
|
||||
export const INTEL_VOTE_WEIGHT = 2;
|
||||
|
||||
/**
|
||||
* Tally a ballot's votes with the Intelligence x2 weight and the decided tie
|
||||
* cascade. Votes for options that are not on the ballot are ignored (defensive:
|
||||
* actions validate, but tallies must never crash on stale rows).
|
||||
*/
|
||||
export function tallyBallot(input: {
|
||||
options: readonly BallotTallyOption[];
|
||||
votes: readonly BallotVoteRow[];
|
||||
intelUserIds: ReadonlySet<number>;
|
||||
}): BallotTallyResult {
|
||||
const optionByTech = new Map(input.options.map((o) => [o.technologyId, o]));
|
||||
const counts: TallyCounts = {};
|
||||
for (const option of input.options) {
|
||||
counts[option.technologyId] = { raw: 0, weighted: 0 };
|
||||
}
|
||||
|
||||
let totalVotes = 0;
|
||||
for (const vote of input.votes) {
|
||||
const option = optionByTech.get(vote.technologyId);
|
||||
if (!option) continue;
|
||||
totalVotes += 1;
|
||||
counts[vote.technologyId].raw += 1;
|
||||
counts[vote.technologyId].weighted += input.intelUserIds.has(vote.userId)
|
||||
? INTEL_VOTE_WEIGHT
|
||||
: 1;
|
||||
}
|
||||
|
||||
if (totalVotes === 0) {
|
||||
return { counts, totalVotes, winnerId: null, method: "no-votes" };
|
||||
}
|
||||
|
||||
const ranked = [...input.options].sort((a, b) => {
|
||||
const weighted = counts[b.technologyId].weighted - counts[a.technologyId].weighted;
|
||||
if (weighted !== 0) return weighted;
|
||||
const cascade = compareCheaperShorterOldest(a.tech, b.tech);
|
||||
if (cascade !== 0) return cascade;
|
||||
return a.technologyId - b.technologyId;
|
||||
});
|
||||
|
||||
const winner = ranked[0];
|
||||
const usedCascade =
|
||||
ranked.length > 1 &&
|
||||
counts[ranked[1].technologyId].weighted === counts[winner.technologyId].weighted;
|
||||
return {
|
||||
counts,
|
||||
totalVotes,
|
||||
winnerId: winner.technologyId,
|
||||
method: usedCascade ? "tie-cascade" : "votes",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The auto-start fallback for a ballot that closed with zero votes after its
|
||||
* one extension: the cheapest/shortest/oldest option.
|
||||
*/
|
||||
export function cheapestOption(
|
||||
options: readonly BallotTallyOption[],
|
||||
): BallotTallyOption | null {
|
||||
if (options.length === 0) return null;
|
||||
return [...options].sort((a, b) => {
|
||||
const cascade = compareCheaperShorterOldest(a.tech, b.tech);
|
||||
return cascade !== 0 ? cascade : a.technologyId - b.technologyId;
|
||||
})[0];
|
||||
}
|
||||
|
||||
/** Research progress 0..1 from timestamps; clamped, NaN-safe. */
|
||||
export function researchProgress(startedAt: string | number, etaAt: string | number, now: string | number): number {
|
||||
const start = toMs(startedAt);
|
||||
const eta = toMs(etaAt);
|
||||
const current = toMs(now);
|
||||
if (start === null || eta === null || current === null || eta <= start) return 0;
|
||||
return Math.min(1, Math.max(0, (current - start) / (eta - start)));
|
||||
}
|
||||
|
||||
function toMs(value: string | number): number | null {
|
||||
const ms = typeof value === "number" ? value : Date.parse(value);
|
||||
return Number.isFinite(ms) ? ms : null;
|
||||
}
|
||||
593
src/lib/tech/tick.ts
Normal file
593
src/lib/tech/tick.ts
Normal file
|
|
@ -0,0 +1,593 @@
|
|||
import type { Payload } from "payload";
|
||||
|
||||
import { consumeStorage, relationshipId, storedAmount } from "@/lib/base/storage";
|
||||
import { notifyUser } from "@/lib/notifications";
|
||||
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
|
||||
import { loadResearchCapacity, type ResearchCapacitySnapshot } from "./capacity";
|
||||
import {
|
||||
cheapestOption,
|
||||
effectiveDurationTicks,
|
||||
eligibleTechs,
|
||||
isEligibleForBallot,
|
||||
tallyBallot,
|
||||
technologyToEligibility,
|
||||
ticksToMilliseconds,
|
||||
type BallotTallyOption,
|
||||
type EligibilityContext,
|
||||
} from "./research";
|
||||
|
||||
/**
|
||||
* Tech tick sweep (timestamp-derived + idempotent, shipment-lifecycle pattern).
|
||||
*
|
||||
* Order per sweep: complete due research -> advance queued research (consume
|
||||
* pooled storage when affordable) -> resolve due ballots -> open the next
|
||||
* ballot when a slot is free and eligible techs exist. Every step re-reads the
|
||||
* document's fresh status before mutating, so a cron retry after a partial
|
||||
* failure never double-completes, double-starts, or double-resolves.
|
||||
*/
|
||||
|
||||
export interface TechTickResult {
|
||||
enabled: boolean;
|
||||
completed: number;
|
||||
started: number;
|
||||
resolved: number;
|
||||
extended: number;
|
||||
opened: number;
|
||||
}
|
||||
|
||||
const TECH_TREE_LINK = "/intelligence/tech-tree";
|
||||
|
||||
function iso(date: Date): string {
|
||||
return date.toISOString();
|
||||
}
|
||||
|
||||
async function countResearches(payload: Payload, status: "active" | "queued"): Promise<number> {
|
||||
const res = await payload.find({
|
||||
collection: "tech-researches",
|
||||
where: { status: { equals: status } },
|
||||
limit: 0,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return res.totalDocs;
|
||||
}
|
||||
|
||||
async function buildEligibilityContext(payload: Payload): Promise<EligibilityContext> {
|
||||
const [researchedRes, busyRes] = await Promise.all([
|
||||
payload.find({
|
||||
collection: "technologies",
|
||||
where: { researchedAt: { not_equals: null } },
|
||||
limit: 0,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
}),
|
||||
payload.find({
|
||||
collection: "tech-researches",
|
||||
where: { status: { in: ["queued", "active"] } },
|
||||
limit: 200,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
researchedIds: new Set(researchedRes.docs.map((doc) => doc.id)),
|
||||
busyIds: new Set(
|
||||
busyRes.docs
|
||||
.map((doc) => relationshipId(doc.technology))
|
||||
.filter((id): id is number => id != null),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Notify every registered member (unit-wide announcements; the unit is small). */
|
||||
async function notifyAllUsers(
|
||||
payload: Payload,
|
||||
input: { type: string; title: string; message?: string; link?: string },
|
||||
): Promise<void> {
|
||||
const limit = 100;
|
||||
let page = 1;
|
||||
for (;;) {
|
||||
const users = await payload.find({
|
||||
collection: "users",
|
||||
limit,
|
||||
page,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
for (const user of users.docs) {
|
||||
await notifyUser(payload, { userId: user.id, ...input });
|
||||
}
|
||||
if (page >= users.totalPages) break;
|
||||
page += 1;
|
||||
}
|
||||
}
|
||||
|
||||
type CostRow = { resourceId: number; amount: number };
|
||||
|
||||
/**
|
||||
* All-or-nothing drain of research costs from the pooled storage of OPERATIONAL
|
||||
* research facilities. Deterministic order (structures by id, grid then void)
|
||||
* keeps repeated sweeps identical, which is what makes the tick idempotent.
|
||||
* Returns the consumed rows, or null when the pool cannot cover the costs.
|
||||
*/
|
||||
async function tryConsumePooledCosts(
|
||||
payload: Payload,
|
||||
facilityIds: readonly number[],
|
||||
costs: readonly CostRow[],
|
||||
): Promise<CostRow[] | null> {
|
||||
if (costs.length === 0) return [];
|
||||
if (facilityIds.length === 0) return null;
|
||||
|
||||
const docs: any[] = [];
|
||||
for (const id of [...facilityIds].sort((a, b) => a - b)) {
|
||||
const doc = await payload
|
||||
.findByID({ collection: "game-structures", id, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
if (doc) docs.push(doc);
|
||||
}
|
||||
|
||||
for (const cost of costs) {
|
||||
const available = docs.reduce(
|
||||
(sum, doc) =>
|
||||
sum +
|
||||
storedAmount(doc.storedResources ?? [], cost.resourceId) +
|
||||
storedAmount(doc.voidStorage ?? [], cost.resourceId),
|
||||
0,
|
||||
);
|
||||
if (available < cost.amount) return null;
|
||||
}
|
||||
|
||||
const remainingByCost = costs.map((cost) => ({ ...cost }));
|
||||
for (const doc of docs) {
|
||||
let stored = [...(doc.storedResources ?? [])];
|
||||
let voidStorage = [...(doc.voidStorage ?? [])];
|
||||
let touched = false;
|
||||
|
||||
for (const cost of remainingByCost) {
|
||||
if (cost.amount <= 0) continue;
|
||||
const gridResult = consumeStorage(stored, cost.resourceId, cost.amount);
|
||||
stored = gridResult.entries as any;
|
||||
const voidResult = consumeStorage(voidStorage, cost.resourceId, gridResult.remaining);
|
||||
voidStorage = voidResult.entries as any;
|
||||
const consumed = cost.amount - voidResult.remaining;
|
||||
if (consumed > 0) {
|
||||
cost.amount -= consumed;
|
||||
touched = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (touched) {
|
||||
await payload.update({
|
||||
collection: "game-structures",
|
||||
id: doc.id,
|
||||
data: { storedResources: stored, voidStorage },
|
||||
context: { skipGridRepack: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return costs.map((cost) => ({ resourceId: cost.resourceId, amount: cost.amount }));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Sweeps
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function completeDueResearch(
|
||||
payload: Payload,
|
||||
now: Date,
|
||||
result: TechTickResult,
|
||||
): Promise<void> {
|
||||
const due = await payload.find({
|
||||
collection: "tech-researches",
|
||||
where: {
|
||||
and: [{ status: { equals: "active" } }, { etaAt: { less_than_equal: iso(now) } }],
|
||||
},
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
for (const research of due.docs) {
|
||||
const fresh = await payload
|
||||
.findByID({ collection: "tech-researches", id: research.id, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
if (!fresh || fresh.status !== "active") continue;
|
||||
|
||||
const technologyId = relationshipId(fresh.technology);
|
||||
let techName = `Technology #${technologyId ?? "?"}`;
|
||||
if (technologyId != null) {
|
||||
const tech = await payload
|
||||
.findByID({ collection: "technologies", id: technologyId, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
if (tech) {
|
||||
techName = tech.name;
|
||||
if (!tech.researchedAt) {
|
||||
await payload.update({
|
||||
collection: "technologies",
|
||||
id: tech.id,
|
||||
data: { researchedAt: iso(now) },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await payload.update({
|
||||
collection: "tech-researches",
|
||||
id: fresh.id,
|
||||
data: { status: "completed", completedAt: iso(now) },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.TechResearchCompleted,
|
||||
message: `Research complete: ${techName}`,
|
||||
targetCollection: "technologies",
|
||||
targetId: technologyId ?? fresh.id,
|
||||
data: { researchId: fresh.id, technologyId },
|
||||
});
|
||||
await notifyAllUsers(payload, {
|
||||
type: "tech:research-complete",
|
||||
title: "Research complete",
|
||||
message: `${techName} is now unlocked.`,
|
||||
link: TECH_TREE_LINK,
|
||||
});
|
||||
result.completed += 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function advanceQueuedResearch(
|
||||
payload: Payload,
|
||||
now: Date,
|
||||
snapshot: ResearchCapacitySnapshot,
|
||||
result: TechTickResult,
|
||||
): Promise<void> {
|
||||
const activeCount = await countResearches(payload, "active");
|
||||
let freeSlots = Math.max(0, snapshot.capacity.slots - activeCount);
|
||||
if (freeSlots === 0) return;
|
||||
|
||||
const queued = await payload.find({
|
||||
collection: "tech-researches",
|
||||
where: { status: { equals: "queued" } },
|
||||
sort: "createdAt",
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
// Drain pool: every OPERATIONAL research facility (staffing gates capacity,
|
||||
// not the storage pool), deterministic by structure id.
|
||||
const poolFacilityIds = snapshot.facilities.filter((f) => f.operational).map((f) => f.id);
|
||||
|
||||
for (const research of queued.docs) {
|
||||
if (freeSlots <= 0) break;
|
||||
const fresh = await payload
|
||||
.findByID({ collection: "tech-researches", id: research.id, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
if (!fresh || fresh.status !== "queued") continue;
|
||||
|
||||
const technologyId = relationshipId(fresh.technology);
|
||||
if (technologyId == null) continue;
|
||||
const tech = await payload
|
||||
.findByID({ collection: "technologies", id: technologyId, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
if (!tech) {
|
||||
payload.logger.warn(
|
||||
`[Tech Tick] Queued research ${fresh.id} references missing technology ${technologyId}; leaving queued.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const costs: CostRow[] = (tech.researchCosts?.resources ?? [])
|
||||
.map((row: any) => ({ resourceId: relationshipId(row.resource), amount: row.amount ?? 0 }))
|
||||
.filter((row): row is CostRow => row.resourceId != null && row.amount > 0);
|
||||
|
||||
const consumed = await tryConsumePooledCosts(payload, poolFacilityIds, costs);
|
||||
if (consumed === null) continue; // retry next tick
|
||||
|
||||
const ticks = effectiveDurationTicks(
|
||||
{
|
||||
minimumResearchDuration: tech.researchCosts?.minimumResearchDuration,
|
||||
maximumResearchDuration: tech.researchCosts?.maximumResearchDuration,
|
||||
},
|
||||
snapshot.capacity.totalModifier,
|
||||
);
|
||||
const etaAt = new Date(now.getTime() + ticksToMilliseconds(ticks, snapshot.tickMinutes));
|
||||
|
||||
await payload.update({
|
||||
collection: "tech-researches",
|
||||
id: fresh.id,
|
||||
data: {
|
||||
status: "active",
|
||||
startedAt: iso(now),
|
||||
etaAt: iso(etaAt),
|
||||
consumedCosts: consumed.map((row) => ({ resource: row.resourceId, amount: row.amount })),
|
||||
},
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.TechResearchStarted,
|
||||
message: `Research started: ${tech.name} (${ticks} ticks)`,
|
||||
targetCollection: "technologies",
|
||||
targetId: tech.id,
|
||||
data: { researchId: fresh.id, technologyId: tech.id, ticks, etaAt: iso(etaAt) },
|
||||
});
|
||||
freeSlots -= 1;
|
||||
result.started += 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveDueBallots(
|
||||
payload: Payload,
|
||||
now: Date,
|
||||
snapshot: ResearchCapacitySnapshot,
|
||||
result: TechTickResult,
|
||||
): Promise<void> {
|
||||
const due = await payload.find({
|
||||
collection: "tech-ballots",
|
||||
where: {
|
||||
and: [
|
||||
{ status: { in: ["open", "extended"] } },
|
||||
{ closesAt: { less_than_equal: iso(now) } },
|
||||
],
|
||||
},
|
||||
limit: 50,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
for (const ballot of due.docs) {
|
||||
const fresh = await payload
|
||||
.findByID({ collection: "tech-ballots", id: ballot.id, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
if (!fresh || fresh.status === "closed") continue;
|
||||
|
||||
// Votes + Intelligence weights (qualification resolved AT TALLY).
|
||||
const votesRes = await payload.find({
|
||||
collection: "tech-ballot-votes",
|
||||
where: { ballot: { equals: fresh.id } },
|
||||
limit: 2000,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const votes = votesRes.docs
|
||||
.map((vote) => ({
|
||||
userId: relationshipId(vote.user),
|
||||
technologyId: relationshipId(vote.technology),
|
||||
}))
|
||||
.filter((vote): vote is { userId: number; technologyId: number } => vote.userId != null && vote.technologyId != null);
|
||||
|
||||
const voterIds = [...new Set(votes.map((vote) => vote.userId))];
|
||||
const intelUserIds = new Set<number>();
|
||||
for (const voterId of voterIds) {
|
||||
if (await hasIntelligenceQualification(payload, { id: voterId })) {
|
||||
intelUserIds.add(voterId);
|
||||
}
|
||||
}
|
||||
|
||||
// Frozen options + live createdAt for the oldest-doc tie key.
|
||||
const optionTechIds = fresh.options
|
||||
.map((option) => relationshipId(option.technology))
|
||||
.filter((id): id is number => id != null);
|
||||
const techById = new Map<number, any>();
|
||||
if (optionTechIds.length > 0) {
|
||||
const techsRes = await payload.find({
|
||||
collection: "technologies",
|
||||
where: { id: { in: optionTechIds } },
|
||||
limit: optionTechIds.length,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
for (const doc of techsRes.docs) techById.set(doc.id, doc);
|
||||
}
|
||||
const tallyOptions: BallotTallyOption[] = fresh.options.flatMap((option) => {
|
||||
const technologyId = relationshipId(option.technology);
|
||||
if (technologyId == null) return [];
|
||||
const live = techById.get(technologyId);
|
||||
return [
|
||||
{
|
||||
technologyId,
|
||||
tech: {
|
||||
id: technologyId,
|
||||
resourceCosts: (option.resourceCosts ?? []).map((row) => ({
|
||||
resource: relationshipId(row.resource) ?? 0,
|
||||
amount: row.amount ?? 0,
|
||||
})),
|
||||
minimumResearchDuration: option.minimumResearchDuration,
|
||||
maximumResearchDuration: option.maximumResearchDuration,
|
||||
createdAt: live?.createdAt ?? null,
|
||||
},
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const tally = tallyBallot({ options: tallyOptions, votes, intelUserIds });
|
||||
let winnerId = tally.winnerId;
|
||||
let resolution: string = winnerId != null ? tally.method : "no-votes";
|
||||
|
||||
if (winnerId === null) {
|
||||
if (fresh.status === "open" && !fresh.extendedOnce) {
|
||||
// Zero turnout: extend once, then auto-start on the next close.
|
||||
await payload.update({
|
||||
collection: "tech-ballots",
|
||||
id: fresh.id,
|
||||
data: {
|
||||
status: "extended",
|
||||
extendedOnce: true,
|
||||
closesAt: iso(
|
||||
new Date(now.getTime() + ticksToMilliseconds(snapshot.ballotDurationTicks, snapshot.tickMinutes)),
|
||||
),
|
||||
},
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.TechBallotExtended,
|
||||
message: `Research ballot #${fresh.id} extended (no votes cast)`,
|
||||
targetCollection: "tech-ballots",
|
||||
targetId: fresh.id,
|
||||
data: { ballotId: fresh.id },
|
||||
});
|
||||
result.extended += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const eligibility = await buildEligibilityContext(payload);
|
||||
const stillEligible = tallyOptions.filter((option) => {
|
||||
const live = techById.get(option.technologyId);
|
||||
return live ? isEligibleForBallot(technologyToEligibility(live), eligibility) : false;
|
||||
});
|
||||
const fallback = cheapestOption(stillEligible);
|
||||
winnerId = fallback?.technologyId ?? null;
|
||||
resolution = winnerId != null ? "auto-start" : "no-winner";
|
||||
}
|
||||
|
||||
let researchId: number | null = null;
|
||||
let winnerName: string | null = null;
|
||||
if (winnerId != null) {
|
||||
winnerName = techById.get(winnerId)?.name ?? `Technology #${winnerId}`;
|
||||
const research = await payload.create({
|
||||
collection: "tech-researches",
|
||||
data: { technology: winnerId, status: "queued", ballot: fresh.id },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
researchId = research.id;
|
||||
}
|
||||
|
||||
await payload.update({
|
||||
collection: "tech-ballots",
|
||||
id: fresh.id,
|
||||
data: {
|
||||
status: "closed",
|
||||
winner: winnerId,
|
||||
research: researchId,
|
||||
resolvedAt: iso(now),
|
||||
tallySnapshot: {
|
||||
counts: tally.counts,
|
||||
totalVotes: tally.totalVotes,
|
||||
method: tally.method,
|
||||
resolution,
|
||||
intelVoters: voterIds.filter((id) => intelUserIds.has(id)).length,
|
||||
},
|
||||
},
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.TechBallotResolved,
|
||||
message:
|
||||
winnerName != null
|
||||
? `Research ballot resolved: ${winnerName} (${tally.totalVotes} votes, ${resolution})`
|
||||
: `Research ballot #${fresh.id} closed with no winner`,
|
||||
targetCollection: "tech-ballots",
|
||||
targetId: fresh.id,
|
||||
data: { ballotId: fresh.id, winnerId, resolution, totalVotes: tally.totalVotes },
|
||||
});
|
||||
result.resolved += 1;
|
||||
}
|
||||
}
|
||||
|
||||
async function openNextBallot(
|
||||
payload: Payload,
|
||||
now: Date,
|
||||
snapshot: ResearchCapacitySnapshot,
|
||||
result: TechTickResult,
|
||||
): Promise<void> {
|
||||
const openRes = await payload.find({
|
||||
collection: "tech-ballots",
|
||||
where: { status: { in: ["open", "extended"] } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (openRes.docs.length > 0) return; // one ballot at a time
|
||||
|
||||
const [activeCount, queuedCount] = await Promise.all([
|
||||
countResearches(payload, "active"),
|
||||
countResearches(payload, "queued"),
|
||||
]);
|
||||
const freeSlots = snapshot.capacity.slots - activeCount - queuedCount;
|
||||
if (freeSlots <= 0) return; // no capacity -> no ballots (UI shows the empty state)
|
||||
|
||||
const eligibility = await buildEligibilityContext(payload);
|
||||
const approvedRes = await payload.find({
|
||||
collection: "technologies",
|
||||
where: { approvalStatus: { equals: "approved" } },
|
||||
limit: 500,
|
||||
depth: 0,
|
||||
sort: "createdAt",
|
||||
overrideAccess: true,
|
||||
});
|
||||
const eligible = eligibleTechs(approvedRes.docs.map((doc) => technologyToEligibility(doc)), eligibility);
|
||||
if (eligible.length === 0) return;
|
||||
|
||||
const ballot = await payload.create({
|
||||
collection: "tech-ballots",
|
||||
data: {
|
||||
status: "open",
|
||||
opensAt: iso(now),
|
||||
closesAt: iso(
|
||||
new Date(now.getTime() + ticksToMilliseconds(snapshot.ballotDurationTicks, snapshot.tickMinutes)),
|
||||
),
|
||||
options: eligible.map((tech) => ({
|
||||
technology: tech.id,
|
||||
name: (approvedRes.docs.find((doc) => doc.id === tech.id) as any)?.name ?? `#${tech.id}`,
|
||||
summary: (approvedRes.docs.find((doc) => doc.id === tech.id) as any)?.summary ?? null,
|
||||
minimumResearchDuration: tech.minimumResearchDuration,
|
||||
maximumResearchDuration: tech.maximumResearchDuration,
|
||||
resourceCosts: (tech.resourceCosts ?? []).map((row) => ({ resource: row.resource, amount: row.amount })),
|
||||
})),
|
||||
},
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.TechBallotOpened,
|
||||
message: `Research ballot opened with ${eligible.length} option${eligible.length === 1 ? "" : "s"}`,
|
||||
targetCollection: "tech-ballots",
|
||||
targetId: ballot.id,
|
||||
data: { ballotId: ballot.id, options: eligible.map((tech) => tech.id), closesAt: ballot.closesAt },
|
||||
});
|
||||
await notifyAllUsers(payload, {
|
||||
type: "tech:ballot-open",
|
||||
title: "Research ballot open",
|
||||
message: `Vote on what R&D tackles next (${eligible.length} options).`,
|
||||
link: TECH_TREE_LINK,
|
||||
});
|
||||
result.opened += 1;
|
||||
}
|
||||
|
||||
export async function processTechTick(
|
||||
payload: Payload,
|
||||
now: Date = new Date(),
|
||||
): Promise<TechTickResult> {
|
||||
const snapshot = await loadResearchCapacity(payload);
|
||||
const result: TechTickResult = {
|
||||
enabled: snapshot.enabled,
|
||||
completed: 0,
|
||||
started: 0,
|
||||
resolved: 0,
|
||||
extended: 0,
|
||||
opened: 0,
|
||||
};
|
||||
if (!snapshot.enabled) return result; // master gate: no-op when disabled
|
||||
|
||||
await completeDueResearch(payload, now, result);
|
||||
await advanceQueuedResearch(payload, now, snapshot, result);
|
||||
await resolveDueBallots(payload, now, snapshot, result);
|
||||
await openNextBallot(payload, now, snapshot, result);
|
||||
return result;
|
||||
}
|
||||
42278
src/migrations/20261019_184409_add_tech_research_system.json
Normal file
42278
src/migrations/20261019_184409_add_tech_research_system.json
Normal file
File diff suppressed because it is too large
Load diff
237
src/migrations/20261019_184409_add_tech_research_system.ts
Normal file
237
src/migrations/20261019_184409_add_tech_research_system.ts
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres';
|
||||
|
||||
/**
|
||||
* Member-facing tech research system:
|
||||
* - new collections tech-researches / tech-ballots / tech-ballot-votes
|
||||
* (tables, FKs, indexes, status enums, MCP key capability columns, doc locks)
|
||||
* - technologies.researched_at
|
||||
* - research-facility fields on structures + game-structures
|
||||
* - game-rules research config group
|
||||
* - permission enum values for the three slugs + muteable notification types
|
||||
*
|
||||
* NOTE: this migration deliberately excludes unrelated schema drift that the
|
||||
* generator picked up from hand-written migrations without .json snapshots
|
||||
* (bomperator profile columns, minigames estimated_removal_date / phasingOut,
|
||||
* the AI model default change). Those are owned by their own migrations.
|
||||
*/
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TYPE "public"."enum_tech_researches_status" AS ENUM('queued', 'active', 'completed');
|
||||
CREATE TYPE "public"."enum_tech_ballots_status" AS ENUM('open', 'extended', 'closed');
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-researches:create' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-researches:read' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-researches:update' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-researches:delete' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'admin:tech-researches:manage' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-ballots:create' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-ballots:read' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-ballots:update' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-ballots:delete' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'admin:tech-ballots:manage' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-ballot-votes:create' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-ballot-votes:read' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-ballot-votes:update' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'tech-ballot-votes:delete' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_game_event_logs_required_permissions" ADD VALUE 'admin:tech-ballot-votes:manage' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_users_preferences_notifications_muted_types" ADD VALUE 'tech:ballot-open';
|
||||
ALTER TYPE "public"."enum_users_preferences_notifications_muted_types" ADD VALUE 'tech:research-complete';
|
||||
ALTER TYPE "public"."enum_users_preferences_discord_muted_types" ADD VALUE 'tech:ballot-open';
|
||||
ALTER TYPE "public"."enum_users_preferences_discord_muted_types" ADD VALUE 'tech:research-complete';
|
||||
ALTER TYPE "public"."enum_game_event_logs_target_collection" ADD VALUE 'tech-researches';
|
||||
ALTER TYPE "public"."enum_game_event_logs_target_collection" ADD VALUE 'tech-ballots';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-researches:create' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-researches:read' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-researches:update' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-researches:delete' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'admin:tech-researches:manage' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-ballots:create' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-ballots:read' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-ballots:update' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-ballots:delete' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'admin:tech-ballots:manage' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-ballot-votes:create' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-ballot-votes:read' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-ballot-votes:update' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'tech-ballot-votes:delete' BEFORE 'assets:create';
|
||||
ALTER TYPE "public"."enum_roles_permissions" ADD VALUE 'admin:tech-ballot-votes:manage' BEFORE 'assets:create';
|
||||
CREATE TABLE "tech_researches_consumed_costs" (
|
||||
"_order" integer NOT NULL,
|
||||
"_parent_id" integer NOT NULL,
|
||||
"id" varchar PRIMARY KEY NOT NULL,
|
||||
"resource_id" integer NOT NULL,
|
||||
"amount" numeric NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "tech_researches" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"technology_id" integer NOT NULL,
|
||||
"status" "enum_tech_researches_status" DEFAULT 'queued' NOT NULL,
|
||||
"ballot_id" integer,
|
||||
"started_at" timestamp(3) with time zone,
|
||||
"eta_at" timestamp(3) with time zone,
|
||||
"completed_at" timestamp(3) with time zone,
|
||||
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "tech_ballots_options_resource_costs" (
|
||||
"_order" integer NOT NULL,
|
||||
"_parent_id" varchar NOT NULL,
|
||||
"id" varchar PRIMARY KEY NOT NULL,
|
||||
"resource_id" integer NOT NULL,
|
||||
"amount" numeric NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "tech_ballots_options" (
|
||||
"_order" integer NOT NULL,
|
||||
"_parent_id" integer NOT NULL,
|
||||
"id" varchar PRIMARY KEY NOT NULL,
|
||||
"technology_id" integer NOT NULL,
|
||||
"name" varchar NOT NULL,
|
||||
"summary" varchar,
|
||||
"minimum_research_duration" numeric,
|
||||
"maximum_research_duration" numeric
|
||||
);
|
||||
|
||||
CREATE TABLE "tech_ballots" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"status" "enum_tech_ballots_status" DEFAULT 'open' NOT NULL,
|
||||
"opens_at" timestamp(3) with time zone NOT NULL,
|
||||
"closes_at" timestamp(3) with time zone NOT NULL,
|
||||
"extended_once" boolean DEFAULT false,
|
||||
"winner_id" integer,
|
||||
"research_id" integer,
|
||||
"tally_snapshot" jsonb,
|
||||
"resolved_at" timestamp(3) with time zone,
|
||||
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE "tech_ballot_votes" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"ballot_id" integer NOT NULL,
|
||||
"user_id" integer NOT NULL,
|
||||
"technology_id" integer NOT NULL,
|
||||
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
|
||||
ALTER TABLE "game_structures" ADD COLUMN "is_research_facility" boolean DEFAULT false;
|
||||
ALTER TABLE "game_structures" ADD COLUMN "research_speed_modifier" numeric DEFAULT 0;
|
||||
ALTER TABLE "game_structures" ADD COLUMN "research_slots" numeric DEFAULT 1;
|
||||
ALTER TABLE "technologies" ADD COLUMN "researched_at" timestamp(3) with time zone;
|
||||
ALTER TABLE "structures" ADD COLUMN "is_research_facility" boolean DEFAULT false;
|
||||
ALTER TABLE "structures" ADD COLUMN "research_speed_modifier" numeric DEFAULT 0;
|
||||
ALTER TABLE "structures" ADD COLUMN "research_slots" numeric DEFAULT 1;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_researches_find" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_researches_create" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_researches_update" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_researches_delete" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_ballots_find" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_ballots_create" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_ballots_update" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_ballots_delete" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_ballot_votes_find" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_ballot_votes_create" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_ballot_votes_update" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_ballot_votes_delete" boolean DEFAULT false;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "tech_researches_id" integer;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "tech_ballots_id" integer;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "tech_ballot_votes_id" integer;
|
||||
ALTER TABLE "game_rules" ADD COLUMN "research_enabled" boolean DEFAULT false;
|
||||
ALTER TABLE "game_rules" ADD COLUMN "research_ballot_duration_ticks" numeric DEFAULT 288;
|
||||
ALTER TABLE "game_rules" ADD COLUMN "research_researcher_speed_per_head" numeric DEFAULT 0.0001;
|
||||
ALTER TABLE "tech_researches_consumed_costs" ADD CONSTRAINT "tech_researches_consumed_costs_resource_id_resources_id_fk" FOREIGN KEY ("resource_id") REFERENCES "public"."resources"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_researches_consumed_costs" ADD CONSTRAINT "tech_researches_consumed_costs_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."tech_researches"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "tech_researches" ADD CONSTRAINT "tech_researches_technology_id_technologies_id_fk" FOREIGN KEY ("technology_id") REFERENCES "public"."technologies"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_researches" ADD CONSTRAINT "tech_researches_ballot_id_tech_ballots_id_fk" FOREIGN KEY ("ballot_id") REFERENCES "public"."tech_ballots"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballots_options_resource_costs" ADD CONSTRAINT "tech_ballots_options_resource_costs_resource_id_resources_id_fk" FOREIGN KEY ("resource_id") REFERENCES "public"."resources"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballots_options_resource_costs" ADD CONSTRAINT "tech_ballots_options_resource_costs_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."tech_ballots_options"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballots_options" ADD CONSTRAINT "tech_ballots_options_technology_id_technologies_id_fk" FOREIGN KEY ("technology_id") REFERENCES "public"."technologies"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballots_options" ADD CONSTRAINT "tech_ballots_options_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."tech_ballots"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballots" ADD CONSTRAINT "tech_ballots_winner_id_technologies_id_fk" FOREIGN KEY ("winner_id") REFERENCES "public"."technologies"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballots" ADD CONSTRAINT "tech_ballots_research_id_tech_researches_id_fk" FOREIGN KEY ("research_id") REFERENCES "public"."tech_researches"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballot_votes" ADD CONSTRAINT "tech_ballot_votes_ballot_id_tech_ballots_id_fk" FOREIGN KEY ("ballot_id") REFERENCES "public"."tech_ballots"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballot_votes" ADD CONSTRAINT "tech_ballot_votes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
|
||||
ALTER TABLE "tech_ballot_votes" ADD CONSTRAINT "tech_ballot_votes_technology_id_technologies_id_fk" FOREIGN KEY ("technology_id") REFERENCES "public"."technologies"("id") ON DELETE set null ON UPDATE no action;
|
||||
CREATE INDEX "tech_researches_consumed_costs_order_idx" ON "tech_researches_consumed_costs" USING btree ("_order");
|
||||
CREATE INDEX "tech_researches_consumed_costs_parent_id_idx" ON "tech_researches_consumed_costs" USING btree ("_parent_id");
|
||||
CREATE INDEX "tech_researches_consumed_costs_resource_idx" ON "tech_researches_consumed_costs" USING btree ("resource_id");
|
||||
CREATE INDEX "tech_researches_technology_idx" ON "tech_researches" USING btree ("technology_id");
|
||||
CREATE INDEX "tech_researches_ballot_idx" ON "tech_researches" USING btree ("ballot_id");
|
||||
CREATE INDEX "tech_researches_updated_at_idx" ON "tech_researches" USING btree ("updated_at");
|
||||
CREATE INDEX "tech_researches_created_at_idx" ON "tech_researches" USING btree ("created_at");
|
||||
CREATE INDEX "status_idx" ON "tech_researches" USING btree ("status");
|
||||
CREATE INDEX "technology_status_idx" ON "tech_researches" USING btree ("technology_id","status");
|
||||
CREATE INDEX "tech_ballots_options_resource_costs_order_idx" ON "tech_ballots_options_resource_costs" USING btree ("_order");
|
||||
CREATE INDEX "tech_ballots_options_resource_costs_parent_id_idx" ON "tech_ballots_options_resource_costs" USING btree ("_parent_id");
|
||||
CREATE INDEX "tech_ballots_options_resource_costs_resource_idx" ON "tech_ballots_options_resource_costs" USING btree ("resource_id");
|
||||
CREATE INDEX "tech_ballots_options_order_idx" ON "tech_ballots_options" USING btree ("_order");
|
||||
CREATE INDEX "tech_ballots_options_parent_id_idx" ON "tech_ballots_options" USING btree ("_parent_id");
|
||||
CREATE INDEX "tech_ballots_options_technology_idx" ON "tech_ballots_options" USING btree ("technology_id");
|
||||
CREATE INDEX "tech_ballots_winner_idx" ON "tech_ballots" USING btree ("winner_id");
|
||||
CREATE INDEX "tech_ballots_research_idx" ON "tech_ballots" USING btree ("research_id");
|
||||
CREATE INDEX "tech_ballots_updated_at_idx" ON "tech_ballots" USING btree ("updated_at");
|
||||
CREATE INDEX "tech_ballots_created_at_idx" ON "tech_ballots" USING btree ("created_at");
|
||||
CREATE INDEX "status_1_idx" ON "tech_ballots" USING btree ("status");
|
||||
CREATE INDEX "tech_ballot_votes_ballot_idx" ON "tech_ballot_votes" USING btree ("ballot_id");
|
||||
CREATE INDEX "tech_ballot_votes_user_idx" ON "tech_ballot_votes" USING btree ("user_id");
|
||||
CREATE INDEX "tech_ballot_votes_technology_idx" ON "tech_ballot_votes" USING btree ("technology_id");
|
||||
CREATE INDEX "tech_ballot_votes_updated_at_idx" ON "tech_ballot_votes" USING btree ("updated_at");
|
||||
CREATE INDEX "tech_ballot_votes_created_at_idx" ON "tech_ballot_votes" USING btree ("created_at");
|
||||
CREATE UNIQUE INDEX "ballot_user_idx" ON "tech_ballot_votes" USING btree ("ballot_id","user_id");
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_tech_researches_fk" FOREIGN KEY ("tech_researches_id") REFERENCES "public"."tech_researches"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_tech_ballots_fk" FOREIGN KEY ("tech_ballots_id") REFERENCES "public"."tech_ballots"("id") ON DELETE cascade ON UPDATE no action;
|
||||
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_tech_ballot_votes_fk" FOREIGN KEY ("tech_ballot_votes_id") REFERENCES "public"."tech_ballot_votes"("id") ON DELETE cascade ON UPDATE no action;
|
||||
CREATE INDEX "payload_locked_documents_rels_tech_researches_id_idx" ON "payload_locked_documents_rels" USING btree ("tech_researches_id");
|
||||
CREATE INDEX "payload_locked_documents_rels_tech_ballots_id_idx" ON "payload_locked_documents_rels" USING btree ("tech_ballots_id");
|
||||
CREATE INDEX "payload_locked_documents_rels_tech_ballot_votes_id_idx" ON "payload_locked_documents_rels" USING btree ("tech_ballot_votes_id");`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
// Enum value removal is deliberately skipped: Postgres can only drop enum
|
||||
// values by rebuilding the whole type, and the generator's rebuild was based
|
||||
// on a stale snapshot that predates hand-written migrations (it would drop
|
||||
// 'phasingOut' / 'admin:analytics:manage' and fail on rows using them). The
|
||||
// added permission / muted-type values are inert leftovers if rolled back.
|
||||
await db.execute(sql`
|
||||
DROP TABLE "tech_researches_consumed_costs" CASCADE;
|
||||
DROP TABLE "tech_researches" CASCADE;
|
||||
DROP TABLE "tech_ballots_options_resource_costs" CASCADE;
|
||||
DROP TABLE "tech_ballots_options" CASCADE;
|
||||
DROP TABLE "tech_ballots" CASCADE;
|
||||
DROP TABLE "tech_ballot_votes" CASCADE;
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_tech_researches_fk";
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_tech_ballots_fk";
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_tech_ballot_votes_fk";
|
||||
DROP INDEX "payload_locked_documents_rels_tech_researches_id_idx";
|
||||
DROP INDEX "payload_locked_documents_rels_tech_ballots_id_idx";
|
||||
DROP INDEX "payload_locked_documents_rels_tech_ballot_votes_id_idx";
|
||||
ALTER TABLE "game_structures" DROP COLUMN "is_research_facility";
|
||||
ALTER TABLE "game_structures" DROP COLUMN "research_speed_modifier";
|
||||
ALTER TABLE "game_structures" DROP COLUMN "research_slots";
|
||||
ALTER TABLE "technologies" DROP COLUMN "researched_at";
|
||||
ALTER TABLE "structures" DROP COLUMN "is_research_facility";
|
||||
ALTER TABLE "structures" DROP COLUMN "research_speed_modifier";
|
||||
ALTER TABLE "structures" DROP COLUMN "research_slots";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_researches_find";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_researches_create";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_researches_update";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_researches_delete";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_ballots_find";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_ballots_create";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_ballots_update";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_ballots_delete";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_ballot_votes_find";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_ballot_votes_create";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_ballot_votes_update";
|
||||
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_ballot_votes_delete";
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "tech_researches_id";
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "tech_ballots_id";
|
||||
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "tech_ballot_votes_id";
|
||||
ALTER TABLE "game_rules" DROP COLUMN "research_enabled";
|
||||
ALTER TABLE "game_rules" DROP COLUMN "research_ballot_duration_ticks";
|
||||
ALTER TABLE "game_rules" DROP COLUMN "research_researcher_speed_per_head";
|
||||
DROP TYPE "public"."enum_tech_researches_status";
|
||||
DROP TYPE "public"."enum_tech_ballots_status";`)
|
||||
}
|
||||
|
|
@ -142,6 +142,7 @@ import * as migration_20261014_203529_add_event_log_discord_fields from './20261
|
|||
import * as migration_20261015_120000_add_bomperator_minigame_stats from './20261015_120000_add_bomperator_minigame_stats';
|
||||
import * as migration_20261019_120000_add_ai_prompt_entity_context from './20261019_120000_add_ai_prompt_entity_context';
|
||||
import * as migration_20261019_121500_use_env_ai_model from './20261019_121500_use_env_ai_model';
|
||||
import * as migration_20261019_184409_add_tech_research_system from './20261019_184409_add_tech_research_system';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -832,12 +833,12 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261014_135614_add_analytics_permission_enum_value.up,
|
||||
down: migration_20261014_135614_add_analytics_permission_enum_value.down,
|
||||
name: '20261014_135614_add_analytics_permission_enum_value'
|
||||
name: '20261014_135614_add_analytics_permission_enum_value',
|
||||
},
|
||||
{
|
||||
up: migration_20261014_140500_add_minigame_phasing_out_status.up,
|
||||
down: migration_20261014_140500_add_minigame_phasing_out_status.down,
|
||||
name: '20261014_140500_add_minigame_phasing_out_status'
|
||||
name: '20261014_140500_add_minigame_phasing_out_status',
|
||||
},
|
||||
{
|
||||
up: migration_20261014_192950_add_npc_dialogue_states.up,
|
||||
|
|
@ -847,21 +848,26 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261014_203529_add_event_log_discord_fields.up,
|
||||
down: migration_20261014_203529_add_event_log_discord_fields.down,
|
||||
name: '20261014_203529_add_event_log_discord_fields'
|
||||
name: '20261014_203529_add_event_log_discord_fields',
|
||||
},
|
||||
{
|
||||
up: migration_20261015_120000_add_bomperator_minigame_stats.up,
|
||||
down: migration_20261015_120000_add_bomperator_minigame_stats.down,
|
||||
name: '20261015_120000_add_bomperator_minigame_stats'
|
||||
name: '20261015_120000_add_bomperator_minigame_stats',
|
||||
},
|
||||
{
|
||||
up: migration_20261019_120000_add_ai_prompt_entity_context.up,
|
||||
down: migration_20261019_120000_add_ai_prompt_entity_context.down,
|
||||
name: '20261019_120000_add_ai_prompt_entity_context'
|
||||
name: '20261019_120000_add_ai_prompt_entity_context',
|
||||
},
|
||||
{
|
||||
up: migration_20261019_121500_use_env_ai_model.up,
|
||||
down: migration_20261019_121500_use_env_ai_model.down,
|
||||
name: '20261019_121500_use_env_ai_model'
|
||||
name: '20261019_121500_use_env_ai_model',
|
||||
},
|
||||
{
|
||||
up: migration_20261019_184409_add_tech_research_system.up,
|
||||
down: migration_20261019_184409_add_tech_research_system.down,
|
||||
name: '20261019_184409_add_tech_research_system'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -105,6 +105,9 @@ export interface Config {
|
|||
factions: Faction;
|
||||
technologies: Technology;
|
||||
'tech-categories': TechCategory;
|
||||
'tech-researches': TechResearch;
|
||||
'tech-ballots': TechBallot;
|
||||
'tech-ballot-votes': TechBallotVote;
|
||||
assets: Asset;
|
||||
resources: Resource;
|
||||
vehicles: Vehicle;
|
||||
|
|
@ -213,6 +216,9 @@ export interface Config {
|
|||
factions: FactionsSelect<false> | FactionsSelect<true>;
|
||||
technologies: TechnologiesSelect<false> | TechnologiesSelect<true>;
|
||||
'tech-categories': TechCategoriesSelect<false> | TechCategoriesSelect<true>;
|
||||
'tech-researches': TechResearchesSelect<false> | TechResearchesSelect<true>;
|
||||
'tech-ballots': TechBallotsSelect<false> | TechBallotsSelect<true>;
|
||||
'tech-ballot-votes': TechBallotVotesSelect<false> | TechBallotVotesSelect<true>;
|
||||
assets: AssetsSelect<false> | AssetsSelect<true>;
|
||||
resources: ResourcesSelect<false> | ResourcesSelect<true>;
|
||||
vehicles: VehiclesSelect<false> | VehiclesSelect<true>;
|
||||
|
|
@ -501,6 +507,8 @@ export interface User {
|
|||
| 'contribution:xp-granted'
|
||||
| 'contribution:xp-revoked'
|
||||
| 'minigame:achievement'
|
||||
| 'tech:ballot-open'
|
||||
| 'tech:research-complete'
|
||||
)[]
|
||||
| null;
|
||||
};
|
||||
|
|
@ -553,6 +561,8 @@ export interface User {
|
|||
| 'contribution:xp-granted'
|
||||
| 'contribution:xp-revoked'
|
||||
| 'minigame:achievement'
|
||||
| 'tech:ballot-open'
|
||||
| 'tech:research-complete'
|
||||
)[]
|
||||
| null;
|
||||
};
|
||||
|
|
@ -728,6 +738,21 @@ export interface Role {
|
|||
| 'tech-categories:update'
|
||||
| 'tech-categories:delete'
|
||||
| 'admin:tech-categories:manage'
|
||||
| 'tech-researches:create'
|
||||
| 'tech-researches:read'
|
||||
| 'tech-researches:update'
|
||||
| 'tech-researches:delete'
|
||||
| 'admin:tech-researches:manage'
|
||||
| 'tech-ballots:create'
|
||||
| 'tech-ballots:read'
|
||||
| 'tech-ballots:update'
|
||||
| 'tech-ballots:delete'
|
||||
| 'admin:tech-ballots:manage'
|
||||
| 'tech-ballot-votes:create'
|
||||
| 'tech-ballot-votes:read'
|
||||
| 'tech-ballot-votes:update'
|
||||
| 'tech-ballot-votes:delete'
|
||||
| 'admin:tech-ballot-votes:manage'
|
||||
| 'assets:create'
|
||||
| 'assets:read'
|
||||
| 'assets:update'
|
||||
|
|
@ -1121,6 +1146,18 @@ export interface GameStructure {
|
|||
id?: string | null;
|
||||
}[]
|
||||
| null;
|
||||
/**
|
||||
* Operational facilities with at least one researcher run the tech research engine (slots, speed modifier). Inherited from the blueprint when left unset at creation.
|
||||
*/
|
||||
isResearchFacility?: boolean | null;
|
||||
/**
|
||||
* Fractional research time reduction this facility provides while operational and staffed (0.05 = research completes 5% faster). Inherited from the blueprint when left unset at creation.
|
||||
*/
|
||||
researchSpeedModifier?: number | null;
|
||||
/**
|
||||
* Parallel research capacity this facility provides while operational and staffed. 0 = no capacity. Inherited from the blueprint when left unset at creation.
|
||||
*/
|
||||
researchSlots?: number | null;
|
||||
productionInputs?:
|
||||
| {
|
||||
resource: number | Resource;
|
||||
|
|
@ -1424,6 +1461,18 @@ export interface Structure {
|
|||
id?: string | null;
|
||||
}[]
|
||||
| null;
|
||||
/**
|
||||
* Mark this structure type as a research facility. Copied into newly created game-structures of this type. Operational facilities with at least one researcher run the tech research engine.
|
||||
*/
|
||||
isResearchFacility?: boolean | null;
|
||||
/**
|
||||
* Fractional research time reduction this facility provides while operational and staffed (0.05 = research completes 5% faster). Copied into newly created game-structures of this type.
|
||||
*/
|
||||
researchSpeedModifier?: number | null;
|
||||
/**
|
||||
* Parallel research capacity this facility provides while operational and staffed. Copied into newly created game-structures of this type.
|
||||
*/
|
||||
researchSlots?: number | null;
|
||||
/**
|
||||
* Default recipe copied into newly created game-structures of this type. Empty = no recipe.
|
||||
*/
|
||||
|
|
@ -1736,6 +1785,10 @@ export interface Technology {
|
|||
* Mark whether this technology is ready for developer approval and implementation into the live environment.
|
||||
*/
|
||||
approvalStatus: 'in_progress' | 'ready_for_review' | 'approved' | 'rejected' | 'revision_requested';
|
||||
/**
|
||||
* Set automatically by the tech tick when this technology finishes researching. Empty = not yet researched.
|
||||
*/
|
||||
researchedAt?: string | null;
|
||||
/**
|
||||
* An "Asset" technology will unlock a new item, vehicle, gear piece, structure, etc. An "Upgrade" technology will unlock an improvement to an Asset, like faster build speed, more storage capacity, etc.
|
||||
*/
|
||||
|
|
@ -2899,6 +2952,21 @@ export interface GameEventLog {
|
|||
| 'tech-categories:update'
|
||||
| 'tech-categories:delete'
|
||||
| 'admin:tech-categories:manage'
|
||||
| 'tech-researches:create'
|
||||
| 'tech-researches:read'
|
||||
| 'tech-researches:update'
|
||||
| 'tech-researches:delete'
|
||||
| 'admin:tech-researches:manage'
|
||||
| 'tech-ballots:create'
|
||||
| 'tech-ballots:read'
|
||||
| 'tech-ballots:update'
|
||||
| 'tech-ballots:delete'
|
||||
| 'admin:tech-ballots:manage'
|
||||
| 'tech-ballot-votes:create'
|
||||
| 'tech-ballot-votes:read'
|
||||
| 'tech-ballot-votes:update'
|
||||
| 'tech-ballot-votes:delete'
|
||||
| 'admin:tech-ballot-votes:manage'
|
||||
| 'assets:create'
|
||||
| 'assets:read'
|
||||
| 'assets:update'
|
||||
|
|
@ -3196,6 +3264,8 @@ export interface GameEventLog {
|
|||
| 'campaigns'
|
||||
| 'users'
|
||||
| 'technologies'
|
||||
| 'tech-researches'
|
||||
| 'tech-ballots'
|
||||
| 'maps'
|
||||
| 'shipments'
|
||||
| 'bank-accounts'
|
||||
|
|
@ -4433,6 +4503,119 @@ export interface MissionMapMarker {
|
|||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "tech-researches".
|
||||
*/
|
||||
export interface TechResearch {
|
||||
id: number;
|
||||
technology: number | Technology;
|
||||
/**
|
||||
* queued = awaiting affordable storage; active = researching (etaAt set); completed = researchedAt stamped on the technology.
|
||||
*/
|
||||
status: 'queued' | 'active' | 'completed';
|
||||
/**
|
||||
* The ballot whose winner produced this research.
|
||||
*/
|
||||
ballot?: (number | null) | TechBallot;
|
||||
/**
|
||||
* When the research activated (costs consumed). Empty while queued.
|
||||
*/
|
||||
startedAt?: string | null;
|
||||
/**
|
||||
* Derived completion time: startedAt + effective duration at activation speed. The tick completes the research at/after this timestamp.
|
||||
*/
|
||||
etaAt?: string | null;
|
||||
completedAt?: string | null;
|
||||
/**
|
||||
* Snapshot of the resources actually drained from pooled facility storage when this research activated.
|
||||
*/
|
||||
consumedCosts?:
|
||||
| {
|
||||
resource: number | Resource;
|
||||
amount: number;
|
||||
id?: string | null;
|
||||
}[]
|
||||
| null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "tech-ballots".
|
||||
*/
|
||||
export interface TechBallot {
|
||||
id: number;
|
||||
status: 'open' | 'extended' | 'closed';
|
||||
opensAt: string;
|
||||
/**
|
||||
* When the tick tallies votes and resolves the winner.
|
||||
*/
|
||||
closesAt: string;
|
||||
/**
|
||||
* A zero-turnout ballot is extended once before the tick auto-starts the cheapest option.
|
||||
*/
|
||||
extendedOnce?: boolean | null;
|
||||
/**
|
||||
* Candidate technologies frozen at open (name/summary/costs copied so history stays readable even if the catalog changes).
|
||||
*/
|
||||
options: {
|
||||
technology: number | Technology;
|
||||
name: string;
|
||||
summary?: string | null;
|
||||
/**
|
||||
* Ticks. Frozen from the technology at open.
|
||||
*/
|
||||
minimumResearchDuration?: number | null;
|
||||
/**
|
||||
* Ticks. Frozen from the technology at open.
|
||||
*/
|
||||
maximumResearchDuration?: number | null;
|
||||
resourceCosts?:
|
||||
| {
|
||||
resource: number | Resource;
|
||||
amount: number;
|
||||
id?: string | null;
|
||||
}[]
|
||||
| null;
|
||||
id?: string | null;
|
||||
}[];
|
||||
winner?: (number | null) | Technology;
|
||||
/**
|
||||
* The queued research doc created for the winner.
|
||||
*/
|
||||
research?: (number | null) | TechResearch;
|
||||
/**
|
||||
* Per-option raw + Intelligence-weighted counts and the tie-break method recorded at resolution.
|
||||
*/
|
||||
tallySnapshot?:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
}
|
||||
| unknown[]
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null;
|
||||
resolvedAt?: string | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "tech-ballot-votes".
|
||||
*/
|
||||
export interface TechBallotVote {
|
||||
id: number;
|
||||
ballot: number | TechBallot;
|
||||
user: number | User;
|
||||
/**
|
||||
* The option this member voted for (must be one of the ballot's frozen options).
|
||||
*/
|
||||
technology: number | Technology;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "shipments".
|
||||
|
|
@ -7291,6 +7474,60 @@ export interface PayloadMcpApiKey {
|
|||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
techResearches?: {
|
||||
/**
|
||||
* Allow clients to find tech-researches.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create tech-researches.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update tech-researches.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete tech-researches.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
techBallots?: {
|
||||
/**
|
||||
* Allow clients to find tech-ballots.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create tech-ballots.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update tech-ballots.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete tech-ballots.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
techBallotVotes?: {
|
||||
/**
|
||||
* Allow clients to find tech-ballot-votes.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create tech-ballot-votes.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update tech-ballot-votes.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete tech-ballot-votes.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
assets?: {
|
||||
/**
|
||||
* Allow clients to find assets.
|
||||
|
|
@ -8424,6 +8661,18 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'tech-categories';
|
||||
value: number | TechCategory;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'tech-researches';
|
||||
value: number | TechResearch;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'tech-ballots';
|
||||
value: number | TechBallot;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'tech-ballot-votes';
|
||||
value: number | TechBallotVote;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'assets';
|
||||
value: number | Asset;
|
||||
|
|
@ -8801,6 +9050,9 @@ export interface GameStructuresSelect<T extends boolean = true> {
|
|||
enforcedSalary?: T;
|
||||
id?: T;
|
||||
};
|
||||
isResearchFacility?: T;
|
||||
researchSpeedModifier?: T;
|
||||
researchSlots?: T;
|
||||
productionInputs?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -9815,6 +10067,7 @@ export interface TechnologiesSelect<T extends boolean = true> {
|
|||
y?: T;
|
||||
};
|
||||
approvalStatus?: T;
|
||||
researchedAt?: T;
|
||||
type?: T;
|
||||
summary?: T;
|
||||
description?: T;
|
||||
|
|
@ -9864,6 +10117,71 @@ export interface TechCategoriesSelect<T extends boolean = true> {
|
|||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "tech-researches_select".
|
||||
*/
|
||||
export interface TechResearchesSelect<T extends boolean = true> {
|
||||
technology?: T;
|
||||
status?: T;
|
||||
ballot?: T;
|
||||
startedAt?: T;
|
||||
etaAt?: T;
|
||||
completedAt?: T;
|
||||
consumedCosts?:
|
||||
| T
|
||||
| {
|
||||
resource?: T;
|
||||
amount?: T;
|
||||
id?: T;
|
||||
};
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "tech-ballots_select".
|
||||
*/
|
||||
export interface TechBallotsSelect<T extends boolean = true> {
|
||||
status?: T;
|
||||
opensAt?: T;
|
||||
closesAt?: T;
|
||||
extendedOnce?: T;
|
||||
options?:
|
||||
| T
|
||||
| {
|
||||
technology?: T;
|
||||
name?: T;
|
||||
summary?: T;
|
||||
minimumResearchDuration?: T;
|
||||
maximumResearchDuration?: T;
|
||||
resourceCosts?:
|
||||
| T
|
||||
| {
|
||||
resource?: T;
|
||||
amount?: T;
|
||||
id?: T;
|
||||
};
|
||||
id?: T;
|
||||
};
|
||||
winner?: T;
|
||||
research?: T;
|
||||
tallySnapshot?: T;
|
||||
resolvedAt?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "tech-ballot-votes_select".
|
||||
*/
|
||||
export interface TechBallotVotesSelect<T extends boolean = true> {
|
||||
ballot?: T;
|
||||
user?: T;
|
||||
technology?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "assets_select".
|
||||
|
|
@ -10151,6 +10469,9 @@ export interface StructuresSelect<T extends boolean = true> {
|
|||
enforcedSalary?: T;
|
||||
id?: T;
|
||||
};
|
||||
isResearchFacility?: T;
|
||||
researchSpeedModifier?: T;
|
||||
researchSlots?: T;
|
||||
productionInputs?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -11689,6 +12010,30 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
|||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
techResearches?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
techBallots?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
techBallotVotes?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
assets?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -12258,6 +12603,23 @@ export interface GameRule {
|
|||
*/
|
||||
tickIntervalHintMinutes?: number | null;
|
||||
};
|
||||
/**
|
||||
* Global knobs for the member-facing tech research engine run by the tech tick (ballots, facility speed, researcher bonus).
|
||||
*/
|
||||
research?: {
|
||||
/**
|
||||
* Master gate for the research engine. When off, the tech tick does nothing: no ballots open, no research progresses.
|
||||
*/
|
||||
enabled?: boolean | null;
|
||||
/**
|
||||
* How long a research ballot stays open, in game ticks (default 288 ticks = 48h at a 10-minute tick).
|
||||
*/
|
||||
ballotDurationTicks?: number | null;
|
||||
/**
|
||||
* Research time reduction each researcher adds, as a fraction (0.0001 = 0.01% faster per head). Researchers are active labor staff in the 'researcher' labor classification at operational research facilities.
|
||||
*/
|
||||
researcherSpeedPerHead?: number | null;
|
||||
};
|
||||
/**
|
||||
* When off, the Zone Pressure feature is hidden from the Operations feed (the overview card and the AAR section).
|
||||
*/
|
||||
|
|
@ -12457,6 +12819,13 @@ export interface GameRulesSelect<T extends boolean = true> {
|
|||
coldStartObservations?: T;
|
||||
tickIntervalHintMinutes?: T;
|
||||
};
|
||||
research?:
|
||||
| T
|
||||
| {
|
||||
enabled?: T;
|
||||
ballotDurationTicks?: T;
|
||||
researcherSpeedPerHead?: T;
|
||||
};
|
||||
zonePressureEnabled?: T;
|
||||
statisticsEnabled?: T;
|
||||
helpdeskEnabled?: T;
|
||||
|
|
|
|||
|
|
@ -48,6 +48,9 @@ import { Assignments } from "@/collections/users/Assignments";
|
|||
import { AssignmentTransfers } from "@/collections/users/AssignmentTransfers";
|
||||
import { Technologies } from "@/collections/intelligence/Technologies";
|
||||
import { TechCategories } from "@/collections/intelligence/TechCategories";
|
||||
import { TechResearches } from "@/collections/intelligence/TechResearches";
|
||||
import { TechBallots } from "@/collections/intelligence/TechBallots";
|
||||
import { TechBallotVotes } from "@/collections/intelligence/TechBallotVotes";
|
||||
import { GameRules } from "@/collections/game/GameRules";
|
||||
import { DiscordPresence } from "@/collections/discord/DiscordPresence";
|
||||
import { GameStructures } from "@/collections/game/GameStructures";
|
||||
|
|
@ -343,6 +346,9 @@ const collections = [
|
|||
Factions,
|
||||
Technologies,
|
||||
TechCategories,
|
||||
TechResearches,
|
||||
TechBallots,
|
||||
TechBallotVotes,
|
||||
|
||||
// Logistics
|
||||
Assets,
|
||||
|
|
@ -618,6 +624,10 @@ export default buildConfig({
|
|||
scriptPath: path.resolve(dirname, "scripts/economyTick.ts"),
|
||||
key: "economy-tick",
|
||||
},
|
||||
{
|
||||
scriptPath: path.resolve(dirname, "scripts/techTick.ts"),
|
||||
key: "tech-tick",
|
||||
},
|
||||
{
|
||||
scriptPath: path.resolve(dirname, "scripts/periodTick.ts"),
|
||||
key: "period-tick",
|
||||
|
|
|
|||
|
|
@ -269,6 +269,36 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
|||
{ value: "admin:tech-categories:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Tech Researches",
|
||||
permissions: [
|
||||
{ value: "tech-researches:create", label: "Create" },
|
||||
{ value: "tech-researches:read", label: "Read" },
|
||||
{ value: "tech-researches:update", label: "Update" },
|
||||
{ value: "tech-researches:delete", label: "Delete" },
|
||||
{ value: "admin:tech-researches:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Tech Ballots",
|
||||
permissions: [
|
||||
{ value: "tech-ballots:create", label: "Create" },
|
||||
{ value: "tech-ballots:read", label: "Read" },
|
||||
{ value: "tech-ballots:update", label: "Update" },
|
||||
{ value: "tech-ballots:delete", label: "Delete" },
|
||||
{ value: "admin:tech-ballots:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Tech Ballot Votes",
|
||||
permissions: [
|
||||
{ value: "tech-ballot-votes:create", label: "Create" },
|
||||
{ value: "tech-ballot-votes:read", label: "Read" },
|
||||
{ value: "tech-ballot-votes:update", label: "Update" },
|
||||
{ value: "tech-ballot-votes:delete", label: "Delete" },
|
||||
{ value: "admin:tech-ballot-votes:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
|
||||
// ---- Logistics -----------------------------------------------------------
|
||||
{
|
||||
|
|
@ -959,6 +989,21 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
|
|||
"tech-categories:update",
|
||||
"tech-categories:delete",
|
||||
"admin:tech-categories:manage",
|
||||
"tech-researches:create",
|
||||
"tech-researches:read",
|
||||
"tech-researches:update",
|
||||
"tech-researches:delete",
|
||||
"admin:tech-researches:manage",
|
||||
"tech-ballots:create",
|
||||
"tech-ballots:read",
|
||||
"tech-ballots:update",
|
||||
"tech-ballots:delete",
|
||||
"admin:tech-ballots:manage",
|
||||
"tech-ballot-votes:create",
|
||||
"tech-ballot-votes:read",
|
||||
"tech-ballot-votes:update",
|
||||
"tech-ballot-votes:delete",
|
||||
"admin:tech-ballot-votes:manage",
|
||||
"assets:create",
|
||||
"assets:read",
|
||||
"assets:update",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ Shipping simulation (`src/collections/logistics/Shipments.ts`, `src/scripts/`, `
|
|||
- **Bin file logging**: all seven bins (`game-tick`, `market-tick`, `mission-tick`, `server-tick`, `base-tick`, `economy-tick`, `generate-mission`) tee their logs to daily files `logs/<bin-key>/<YYYY-MM-DD>.log` (UTC) via `createBinLogger` in `src/scripts/lib/binFileLogger.ts` — in addition to the console. Writes are `appendFileSync` (bin scripts `process.exit` immediately, so async streams would truncate). A fatal error in a bin is caught, logged to the file, and exits code 1. Directory override: `BIN_LOG_DIR` env (defaults to `<cwd>/logs` — inside Docker point it at a persistent volume). `logs/` is gitignored.
|
||||
- **Base tick**: `bun run payload base-tick` — bin registered like the others (needs external cron). Runs `processBaseTick` (`src/lib/base/tick.ts`): pays staff salaries from the structure treasury (banking `applyTransaction` type `salary`), charges structure maintenance, flags upkeep shortages (see Base Management below). Emits `staff:salary-paid`/`staff:salary-unpaid`/`structure:maintenance-paid`/`structure:maintenance-unpaid` events. Notifies clients via the same SSE path as the other ticks (`source: "base-tick"`).
|
||||
- **Economy tick**: `bun run payload economy-tick` — bin registered like the others (needs external cron; cadence hint is GameRules `economy.tickIntervalHintMinutes`). Runs `processEconomyTick` (`src/lib/economy/tick.ts`): ensures a `market-state` ledger doc exists per tradeable resource/asset (copied from GM baselines), decays `realDemand`, drifts `artificialDemand` (deterministic per period via `periodSeed` → mulberry32 rng — a cron retry within the same period recomputes the same values), recomputes `priceModifier` from the demand/supply ratio clamped to the item's band. Master gate: GameRules `economy.enabled` (default **off** — no-op when disabled). Cold-start gate: items with fewer than `coldStartObservations` completed purchases keep `priceModifier = 1`. Period idempotency: docs with `lastComputedAt >= periodStart` are skipped. Emits a batch `economy:tick` event + one `economy:price-change` event per item whose modifier moved ≥ `PRICE_CHANGE_THRESHOLD` (0.05) — target `market-state` (logic: `src/lib/economy/` incl. `events.ts`, tests: `tests/int/economy.int.spec.ts` + `tests/int/economy-events.int.spec.ts`). Nothing consumes the modifier yet (P1d: market-tick new-listing pricing). Notifies clients via the same SSE path as the other ticks (`source: "economy-tick"`).
|
||||
- **Tech tick**: `bun run payload tech-tick` — bin registered like the others (needs external cron). Runs `processTechTick` (`src/lib/tech/tick.ts`), the member-facing research engine sweep: complete active `tech-researches` at `etaAt` (stamps `technologies.researchedAt`), advance queued research to active by draining `researchCosts.resources` from the pooled storage of operational research facilities (deterministic drain order by structure id; retries while unaffordable), resolve due `tech-ballots` (Intelligence x2 weight computed at tally via `hasIntelligenceQualification`; tie cascade intel-weight → cheaper/shorter → oldest doc; zero votes extend once then auto-start the cheapest option), and open the next ballot when a slot is free and eligible techs exist. Master gate: GameRules `research.enabled` (default **off**). Capacity = operational AND researcher-staffed `game-structures` with `isResearchFacility` (slots/speed from `src/lib/tech/capacity.ts`; researchers are active labor staff in the `researcher` labor classification, which is game data - absent means bonus 0). Pure rules live in `src/lib/tech/research.ts` (client-safe). Timestamp-derived and idempotent (fresh status re-check before each mutation). Emits `tech:ballot-opened/-extended/-resolved`, `tech:research-started/-completed` events + unit-wide `notifyUser` notifications (`tech:ballot-open`, `tech:research-complete`). Notifies clients via the same SSE path (`source: "tech-tick"`). UI: `/intelligence/tech-tree` (read-only canvas sharing the admin tech-tree components; tests: `tests/int/tech-research-rules.int.spec.ts`, `tests/int/tech-research-tick.int.spec.ts`, `tests/e2e/frontend-tech-tree.e2e.spec.ts`).
|
||||
- **Economy consumption (P1d)**: market-tick prices new NPC listings from the ledger — `price = max(1, round(baseBuyPrice × priceModifier))` (neutral 1 when no market-state doc) then `applyNpcPriceModifier` (vendor's own modifier); the old `autoPrice` ±15% randomness is **removed**. Restock quantity scales down under shortage via `scaleQuantityForShortage` (bounded to a 0.25 factor floor, never below 1). `buyListing` ingests real demand: purchases of NPC/vendor stock (`seller == null`) call `recordPurchase` (fire-and-forget, `src/lib/economy/consumption.ts` — quantity-weighted `realDemand` increment). GM tools: `resetEconomyState` server action (permission `market-state:update`, rebuilds the doc from baselines, emits `economy:reset`; per-listing "Reset economy" button gated by `canResetEconomy` on the market page) and `getReferencePrices` (modifier-applied reference price shown in `CreateListingDialog`'s tip when it differs from the resting valuation). Tests: `tests/int/economy-consumption.int.spec.ts`. Notifies clients via the same SSE path as the other ticks (`source: "economy-tick"`).
|
||||
- **Mission lifecycle auto-start / auto-completion**: `bun run payload mission-tick` — bin registered like the others (needs external cron). Each tick runs two sweeps (start first, then complete) in `src/lib/intelligence/missionLifecycle.ts`: `autoStartMissions` flips `Scheduled` missions whose `classification.startDateTime` has arrived to `Active` (emitting `mission:auto-start`), skipping missions whose whole window already elapsed so they don't get a spurious start event; `autoCompleteMissions` then sets missions whose scheduled window (`startDateTime` + `estimatedDuration`, default 240 min when missing/invalid) has fully passed to `Completed` with `completedAt` stamped at the sweep time (emitting `mission:auto-complete`). Draft statuses (Concept/Planning/Ready) and terminal statuses (Completed/Cancelled) are never auto-started; only `Scheduled`/`Active` are auto-completed. Both sweeps are idempotent. Notifies clients via the same SSE path as the other ticks (tests: `tests/int/mission-lifecycle.int.spec.ts`).
|
||||
- **Side-op workflow (Ready draft → Scheduled committed)**: `createFridaySideOp` creates a side op as a quiet `Ready` draft (no roll-call). The creator commits it with `markSideOpScheduled` (the "Mark as Scheduled" control on the mission page), which flips it to `Scheduled` and emits `mission:commit`. Only `Scheduled` ops post a Discord roll-call (about 3 days out) and are driven by the auto-start/auto-complete lifecycle above. The daily reminder (`readyReminders`, web notification + Discord DM, notification type `mission:ready-reminder`, label "Schedule reminder") nudges the creator to set the op to `Scheduled` while it is still Concept/Planning/Ready; the internal "ready" names are legacy and kept to avoid a migration.
|
||||
|
|
|
|||
40
src/scripts/techTick.ts
Normal file
40
src/scripts/techTick.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import type { SanitizedConfig } from "payload";
|
||||
import { getPayload } from "payload";
|
||||
import { processTechTick } from "@/lib/tech/tick";
|
||||
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
|
||||
|
||||
export const script = async (config: SanitizedConfig) => {
|
||||
const payload = await getPayload({ config });
|
||||
const log = createBinLogger("tech-tick", payload.logger);
|
||||
|
||||
try {
|
||||
log.info("[Tech Tick] Starting tech tick...");
|
||||
const processedAt = new Date().toISOString();
|
||||
const result = await processTechTick(payload);
|
||||
log.info(
|
||||
`[Tech Tick] Complete. Enabled ${result.enabled}; research completed ${result.completed}, started ${result.started}; ballots resolved ${result.resolved}, extended ${result.extended}, opened ${result.opened}.`,
|
||||
);
|
||||
|
||||
const notifyUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
|
||||
const notifySecret = process.env.GAME_TICK_NOTIFY_SECRET;
|
||||
if (notifySecret) {
|
||||
await fetch(`${notifyUrl}/api/game-tick/notify`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"x-game-tick-secret": notifySecret,
|
||||
},
|
||||
body: JSON.stringify({ processedAt, source: "tech-tick" }),
|
||||
}).catch((error: unknown) => {
|
||||
log.error(`[Tech Tick] Failed to notify app clients: ${errorMessage(error)}`);
|
||||
});
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`[Tech Tick] Fatal: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
|
@ -49,6 +49,9 @@ const DIVISION_ADMIN_QUALIFICATIONS: Record<
|
|||
> = {
|
||||
technologies: hasIntelligenceQualification,
|
||||
"tech-categories": hasIntelligenceQualification,
|
||||
"tech-researches": hasIntelligenceQualification,
|
||||
"tech-ballots": hasIntelligenceQualification,
|
||||
"tech-ballot-votes": hasIntelligenceQualification,
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ interface GameEventInput {
|
|||
| "campaigns"
|
||||
| "factions"
|
||||
| "technologies"
|
||||
| "tech-researches"
|
||||
| "tech-ballots"
|
||||
| "assets"
|
||||
| "resources"
|
||||
| "structures"
|
||||
|
|
|
|||
|
|
@ -253,6 +253,14 @@ export const EventTypes = {
|
|||
GarageAutoArrange: "garage:auto-arrange",
|
||||
GarageDispatch: "garage:dispatch",
|
||||
GarageStore: "garage:store",
|
||||
|
||||
// Technology research (tech tick)
|
||||
TechBallotOpened: "tech:ballot-opened",
|
||||
TechBallotExtended: "tech:ballot-extended",
|
||||
TechBallotResolved: "tech:ballot-resolved",
|
||||
TechBallotVoted: "tech:ballot-voted",
|
||||
TechResearchStarted: "tech:research-started",
|
||||
TechResearchCompleted: "tech:research-completed",
|
||||
} as const;
|
||||
|
||||
export type EventType = (typeof EventTypes)[keyof typeof EventTypes];
|
||||
|
|
|
|||
103
tests/e2e/frontend-tech-tree.e2e.spec.ts
Normal file
103
tests/e2e/frontend-tech-tree.e2e.spec.ts
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import { expect, test } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Member-facing Tech Tree (/intelligence/tech-tree): read-only canvas sharing
|
||||
* the admin node cards, blackout veil cards for locked technologies, the
|
||||
* dossier side panels, and the node-click detail dialog. Seeded via the
|
||||
* cookie-authed REST API like the admin tech-tree suite; seeded docs are
|
||||
* removed at the end so later specs inherit a clean catalog.
|
||||
*/
|
||||
test.describe("Frontend Tech Tree", () => {
|
||||
const RUN = `fte-${Date.now().toString(36)}`;
|
||||
const seededTechIds: number[] = [];
|
||||
|
||||
async function login(page: import("@playwright/test").Page) {
|
||||
await page.goto("/login");
|
||||
await page.getByLabel("Username").fill("dev");
|
||||
await page.getByLabel("Password").fill("Test123");
|
||||
await page.getByRole("button", { name: "Log in" }).click();
|
||||
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 60_000 });
|
||||
}
|
||||
|
||||
async function createTech(
|
||||
page: import("@playwright/test").Page,
|
||||
data: Record<string, unknown>,
|
||||
): Promise<number> {
|
||||
const res = await page.request.post("/api/technologies", { data });
|
||||
expect(res.ok(), `tech create failed: ${res.status()} ${await res.text()}`).toBe(true);
|
||||
const body = await res.json();
|
||||
const id = (body.doc as { id: number }).id;
|
||||
seededTechIds.push(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
test.afterEach(async ({ page }) => {
|
||||
await page.goto("/").catch(() => {});
|
||||
for (const id of seededTechIds.splice(0)) {
|
||||
await page.request.delete(`/api/technologies/${id}`).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
test("renders the tree with veil cards and opens the detail dialog", async ({ page }) => {
|
||||
await login(page);
|
||||
|
||||
const openName = `${RUN} Open Research`;
|
||||
const veiledName = `${RUN} Veiled Branch`;
|
||||
const hiddenName = `${RUN} Unapproved Draft`;
|
||||
|
||||
const openId = await createTech(page, {
|
||||
name: openName,
|
||||
type: "asset",
|
||||
summary: "An approved technology ready for voting.",
|
||||
approvalStatus: "approved",
|
||||
researchCosts: { minimumResearchDuration: 1, maximumResearchDuration: 10 },
|
||||
});
|
||||
await createTech(page, {
|
||||
name: veiledName,
|
||||
type: "upgrade",
|
||||
summary: "Approved but gated behind a prerequisite.",
|
||||
approvalStatus: "approved",
|
||||
requirements: {
|
||||
prerequisiteTechnologies: [
|
||||
{ requiresAnd: { technology: [openId] }, requiresOr: { technology: [] } },
|
||||
],
|
||||
},
|
||||
researchCosts: { minimumResearchDuration: 1, maximumResearchDuration: 5 },
|
||||
});
|
||||
await createTech(page, {
|
||||
name: hiddenName,
|
||||
type: "upgrade",
|
||||
summary: "Not approved yet; must not render at all.",
|
||||
approvalStatus: "in_progress",
|
||||
researchCosts: { minimumResearchDuration: 1, maximumResearchDuration: 5 },
|
||||
});
|
||||
|
||||
// Sidebar entry under Intelligence.
|
||||
await page.goto("/intelligence/campaigns");
|
||||
await expect(page.getByRole("link", { name: "Tech Tree" })).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
await page.goto("/intelligence/tech-tree");
|
||||
await expect(page.getByTestId("frontend-tech-tree-canvas")).toBeVisible({ timeout: 60_000 });
|
||||
|
||||
// Approved tech renders with the shared admin card + available overlay.
|
||||
await expect(page.getByTestId(`tech-node-${openId}`)).toBeVisible();
|
||||
await expect(page.getByText("Available // votable").first()).toBeVisible();
|
||||
|
||||
// Locked-but-approved tech renders as a blackout veil without its name.
|
||||
await expect(page.getByTestId("tech-veil-node").first()).toBeVisible();
|
||||
await expect(page.getByText(veiledName)).toHaveCount(0);
|
||||
|
||||
// Unapproved tech never renders.
|
||||
await expect(page.getByText(hiddenName)).toHaveCount(0);
|
||||
|
||||
// Dossier side panels are present (research disabled => standby states).
|
||||
await expect(page.getByText("No open ballot.")).toBeVisible();
|
||||
await expect(page.getByText("R&D // UNIT CAPACITY")).toBeVisible();
|
||||
|
||||
// Node click opens the detail dialog with summary + costs.
|
||||
await page.getByTestId(`tech-node-${openId}`).click();
|
||||
await expect(page.getByRole("dialog")).toBeVisible();
|
||||
await expect(page.getByText("An approved technology ready for voting.")).toBeVisible();
|
||||
await expect(page.getByText("Research costs")).toBeVisible();
|
||||
});
|
||||
});
|
||||
289
tests/int/tech-research-rules.int.spec.ts
Normal file
289
tests/int/tech-research-rules.int.spec.ts
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
cheapestOption,
|
||||
computeResearchCapacity,
|
||||
costScore,
|
||||
effectiveDurationTicks,
|
||||
eligibleTechs,
|
||||
isEligibleForBallot,
|
||||
prereqsMet,
|
||||
qualifyingFacilities,
|
||||
researchProgress,
|
||||
tallyBallot,
|
||||
ticksToMilliseconds,
|
||||
type EligibilityTech,
|
||||
type ResearchFacilityInput,
|
||||
} from "@/lib/tech/research";
|
||||
|
||||
const facility = (
|
||||
overrides: Partial<ResearchFacilityInput> & { id: number },
|
||||
): ResearchFacilityInput => ({
|
||||
operational: true,
|
||||
researcherHeadcount: 1,
|
||||
researchSpeedModifier: 0,
|
||||
researchSlots: 1,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const tech = (overrides: Partial<EligibilityTech> & { id: number }): EligibilityTech => ({
|
||||
approvalStatus: "approved",
|
||||
prereqAnd: [],
|
||||
prereqOr: [],
|
||||
resourceCosts: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("research capacity (facilities + researchers)", () => {
|
||||
it("only counts operational AND staffed facilities", () => {
|
||||
const facilities = [
|
||||
facility({ id: 1, operational: false, researchSpeedModifier: 0.5 }),
|
||||
facility({ id: 2, researcherHeadcount: 0, researchSpeedModifier: 0.5 }),
|
||||
facility({ id: 3, researchSpeedModifier: 0.1, researchSlots: 2, researcherHeadcount: 4 }),
|
||||
];
|
||||
const qualifying = qualifyingFacilities(facilities);
|
||||
expect(qualifying.map((f) => f.id)).toEqual([3]);
|
||||
|
||||
const capacity = computeResearchCapacity(facilities, 0.0001);
|
||||
expect(capacity.facilityCount).toBe(1);
|
||||
expect(capacity.totalResearchers).toBe(4);
|
||||
expect(capacity.slots).toBe(2);
|
||||
expect(capacity.facilitySpeedModifier).toBeCloseTo(0.1);
|
||||
expect(capacity.researcherSpeedBonus).toBeCloseTo(0.0004);
|
||||
expect(capacity.totalModifier).toBeCloseTo(0.1004);
|
||||
});
|
||||
|
||||
it("sums slots and modifiers across qualifying facilities", () => {
|
||||
const capacity = computeResearchCapacity(
|
||||
[
|
||||
facility({ id: 1, researchSpeedModifier: 0.05, researchSlots: 1, researcherHeadcount: 2 }),
|
||||
facility({ id: 2, researchSpeedModifier: 0.1, researchSlots: 3, researcherHeadcount: 5 }),
|
||||
],
|
||||
0.001,
|
||||
);
|
||||
expect(capacity.slots).toBe(4);
|
||||
expect(capacity.totalResearchers).toBe(7);
|
||||
expect(capacity.totalModifier).toBeCloseTo(0.05 + 0.1 + 0.007);
|
||||
});
|
||||
|
||||
it("zero researchers everywhere means zero slots", () => {
|
||||
const capacity = computeResearchCapacity(
|
||||
[facility({ id: 1, researcherHeadcount: 0 }), facility({ id: 2, operational: false })],
|
||||
0.0001,
|
||||
);
|
||||
expect(capacity.slots).toBe(0);
|
||||
expect(capacity.facilityCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("effectiveDurationTicks", () => {
|
||||
it("scales the maximum by (1 - modifier) and floors at the minimum", () => {
|
||||
// base 100 ticks, 20% faster -> 80
|
||||
expect(
|
||||
effectiveDurationTicks({ minimumResearchDuration: 10, maximumResearchDuration: 100 }, 0.2),
|
||||
).toBe(80);
|
||||
// floor is the minimum, even for a huge modifier
|
||||
expect(
|
||||
effectiveDurationTicks({ minimumResearchDuration: 10, maximumResearchDuration: 100 }, 0.95),
|
||||
).toBe(10);
|
||||
expect(effectiveDurationTicks({ minimumResearchDuration: 10, maximumResearchDuration: 100 }, 3)).toBe(10);
|
||||
});
|
||||
|
||||
it("uses the minimum as base when no maximum is set", () => {
|
||||
expect(effectiveDurationTicks({ minimumResearchDuration: 50, maximumResearchDuration: null }, 0.5)).toBe(50);
|
||||
expect(effectiveDurationTicks({ minimumResearchDuration: 50 }, 0)).toBe(50);
|
||||
});
|
||||
|
||||
it("rounds to whole ticks and tolerates junk input", () => {
|
||||
expect(effectiveDurationTicks({ minimumResearchDuration: 3, maximumResearchDuration: 10 }, 0.26)).toBe(7);
|
||||
expect(effectiveDurationTicks({}, 0.5)).toBe(1);
|
||||
expect(effectiveDurationTicks({ minimumResearchDuration: 10, maximumResearchDuration: 100 }, NaN)).toBe(100);
|
||||
});
|
||||
|
||||
it("ticksToMilliseconds honors the tick interval with a fallback", () => {
|
||||
expect(ticksToMilliseconds(288, 10)).toBe(48 * 60 * 60 * 1000);
|
||||
expect(ticksToMilliseconds(6, 0)).toBe(60 * 60 * 1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("eligibility", () => {
|
||||
const researched = new Set<number>([1]);
|
||||
const busy = new Set<number>([3]);
|
||||
|
||||
it("requires approved + unresearched + not busy + prereqs met", () => {
|
||||
expect(isEligibleForBallot(tech({ id: 2 }), { researchedIds: researched, busyIds: busy })).toBe(true);
|
||||
expect(
|
||||
isEligibleForBallot(tech({ id: 2, approvalStatus: "in_progress" }), {
|
||||
researchedIds: researched,
|
||||
busyIds: busy,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(isEligibleForBallot(tech({ id: 1 }), { researchedIds: researched, busyIds: busy })).toBe(false);
|
||||
expect(
|
||||
isEligibleForBallot(tech({ id: 1, researchedAt: null }), {
|
||||
researchedIds: new Set(),
|
||||
busyIds: busy,
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(isEligibleForBallot(tech({ id: 3 }), { researchedIds: researched, busyIds: busy })).toBe(false);
|
||||
expect(
|
||||
isEligibleForBallot(tech({ id: 4, prereqAnd: [1, 9] }), { researchedIds: researched, busyIds: busy }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("AND needs all, OR needs one when present", () => {
|
||||
expect(prereqsMet({ prereqAnd: [1, 2], prereqOr: [] }, new Set([1, 2]))).toBe(true);
|
||||
expect(prereqsMet({ prereqAnd: [1, 2], prereqOr: [] }, new Set([1]))).toBe(false);
|
||||
expect(prereqsMet({ prereqAnd: [], prereqOr: [1, 2] }, new Set([2]))).toBe(true);
|
||||
expect(prereqsMet({ prereqAnd: [], prereqOr: [1, 2] }, new Set([8]))).toBe(false);
|
||||
expect(prereqsMet({ prereqAnd: [1], prereqOr: [7] }, new Set([1]))).toBe(false);
|
||||
});
|
||||
|
||||
it("eligibleTechs filters the list", () => {
|
||||
const list = [
|
||||
tech({ id: 1 }),
|
||||
tech({ id: 2, approvalStatus: "rejected" }),
|
||||
tech({ id: 3 }),
|
||||
tech({ id: 4, prereqAnd: [99] }),
|
||||
];
|
||||
expect(
|
||||
eligibleTechs(list, { researchedIds: new Set(), busyIds: new Set() }).map((t) => t.id),
|
||||
).toEqual([1, 3]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ballot tally + tie cascade", () => {
|
||||
const options = [
|
||||
{
|
||||
technologyId: 10,
|
||||
tech: tech({
|
||||
id: 10,
|
||||
resourceCosts: [{ resource: 1, amount: 5 }],
|
||||
minimumResearchDuration: 20,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
}),
|
||||
},
|
||||
{
|
||||
technologyId: 20,
|
||||
tech: tech({
|
||||
id: 20,
|
||||
resourceCosts: [{ resource: 1, amount: 5 }],
|
||||
minimumResearchDuration: 20,
|
||||
createdAt: "2026-02-01T00:00:00Z",
|
||||
}),
|
||||
},
|
||||
{
|
||||
technologyId: 30,
|
||||
tech: tech({
|
||||
id: 30,
|
||||
resourceCosts: [{ resource: 1, amount: 2 }],
|
||||
minimumResearchDuration: 40,
|
||||
createdAt: "2026-03-01T00:00:00Z",
|
||||
}),
|
||||
},
|
||||
];
|
||||
|
||||
it("counts raw and intel-weighted votes", () => {
|
||||
const result = tallyBallot({
|
||||
options,
|
||||
votes: [
|
||||
{ userId: 1, technologyId: 10 },
|
||||
{ userId: 2, technologyId: 20 },
|
||||
{ userId: 3, technologyId: 20 },
|
||||
],
|
||||
intelUserIds: new Set([1]),
|
||||
});
|
||||
expect(result.counts[10]).toEqual({ raw: 1, weighted: 2 });
|
||||
expect(result.counts[20]).toEqual({ raw: 2, weighted: 2 });
|
||||
expect(result.totalVotes).toBe(3);
|
||||
// weighted tie 2-2 -> cheaper/shorter: 10 and 20 cost/duration equal, oldest wins
|
||||
expect(result.winnerId).toBe(10);
|
||||
expect(result.method).toBe("tie-cascade");
|
||||
});
|
||||
|
||||
it("intel weight can flip the winner against raw count", () => {
|
||||
const result = tallyBallot({
|
||||
options,
|
||||
votes: [
|
||||
{ userId: 1, technologyId: 10 },
|
||||
{ userId: 2, technologyId: 30 },
|
||||
{ userId: 3, technologyId: 30 },
|
||||
],
|
||||
intelUserIds: new Set([1]),
|
||||
});
|
||||
// weighted: 10 -> 2, 30 -> 2; tie -> cheaper (30 costs 2 < 5) wins
|
||||
expect(result.winnerId).toBe(30);
|
||||
});
|
||||
|
||||
it("plain majority wins without cascade", () => {
|
||||
const result = tallyBallot({
|
||||
options,
|
||||
votes: [
|
||||
{ userId: 1, technologyId: 10 },
|
||||
{ userId: 2, technologyId: 10 },
|
||||
{ userId: 3, technologyId: 30 },
|
||||
],
|
||||
intelUserIds: new Set(),
|
||||
});
|
||||
expect(result.winnerId).toBe(10);
|
||||
expect(result.method).toBe("votes");
|
||||
});
|
||||
|
||||
it("zero votes yields no winner", () => {
|
||||
const result = tallyBallot({ options, votes: [], intelUserIds: new Set() });
|
||||
expect(result.winnerId).toBeNull();
|
||||
expect(result.method).toBe("no-votes");
|
||||
});
|
||||
|
||||
it("ignores votes for options not on the ballot", () => {
|
||||
const result = tallyBallot({
|
||||
options,
|
||||
votes: [
|
||||
{ userId: 1, technologyId: 999 },
|
||||
{ userId: 2, technologyId: 30 },
|
||||
],
|
||||
intelUserIds: new Set(),
|
||||
});
|
||||
expect(result.totalVotes).toBe(1);
|
||||
expect(result.winnerId).toBe(30);
|
||||
});
|
||||
|
||||
it("cheapestOption picks cheaper, then shorter, then oldest", () => {
|
||||
expect(cheapestOption(options)?.technologyId).toBe(30); // cost 2 beats 5
|
||||
const sameCost = [
|
||||
{
|
||||
technologyId: 11,
|
||||
tech: tech({
|
||||
id: 11,
|
||||
resourceCosts: [{ resource: 1, amount: 5 }],
|
||||
minimumResearchDuration: 30,
|
||||
createdAt: "2026-05-01T00:00:00Z",
|
||||
}),
|
||||
},
|
||||
{
|
||||
technologyId: 12,
|
||||
tech: tech({
|
||||
id: 12,
|
||||
resourceCosts: [{ resource: 1, amount: 5 }],
|
||||
minimumResearchDuration: 10,
|
||||
createdAt: "2026-06-01T00:00:00Z",
|
||||
}),
|
||||
},
|
||||
];
|
||||
expect(cheapestOption(sameCost)?.technologyId).toBe(12); // shorter base duration
|
||||
expect(costScore({ resourceCosts: [{ amount: 1 }, { amount: 2 }] })).toBe(3);
|
||||
expect(cheapestOption([])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("researchProgress", () => {
|
||||
it("clamps progress between 0 and 1", () => {
|
||||
const start = Date.parse("2026-01-01T00:00:00Z");
|
||||
const eta = start + 1000 * 60 * 60;
|
||||
expect(researchProgress(start, eta, start)).toBe(0);
|
||||
expect(researchProgress(start, eta, start + 1000 * 60 * 30)).toBeCloseTo(0.5);
|
||||
expect(researchProgress(start, eta, eta + 10_000)).toBe(1);
|
||||
expect(researchProgress(start, start, start)).toBe(0);
|
||||
expect(researchProgress("garbage", eta, start)).toBe(0);
|
||||
});
|
||||
});
|
||||
560
tests/int/tech-research-tick.int.spec.ts
Normal file
560
tests/int/tech-research-tick.int.spec.ts
Normal file
|
|
@ -0,0 +1,560 @@
|
|||
import { getPayload, Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import type { GameStructure, LaborClassification, Structure, Technology, User } from "@/payload-types";
|
||||
import { processTechTick } from "@/lib/tech/tick";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `trt-${Date.now().toString(36)}`;
|
||||
|
||||
const LEXICAL_EMPTY = {
|
||||
root: {
|
||||
children: [{ text: "" }],
|
||||
direction: null,
|
||||
format: "" as const,
|
||||
indent: 0,
|
||||
type: "text",
|
||||
version: 1,
|
||||
},
|
||||
};
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Tech tick engine: ballot lifecycle, tally weights, storage drain, ETA,
|
||||
* completion, guards, and idempotency. Timestamps are injected via the tick's
|
||||
* `now` parameter, so no sleeping is involved.
|
||||
*/
|
||||
describe("tech tick (research engine)", () => {
|
||||
const createdUserIds: number[] = [];
|
||||
const createdTechIds: number[] = [];
|
||||
const cleanupQualificationIds: number[] = [];
|
||||
let baseTime: Date;
|
||||
|
||||
const createUser = async (name: string) => {
|
||||
const user = (await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username: `${RUN}-${name}`,
|
||||
discordUsername: `${RUN}-${name}`,
|
||||
displayName: name.toUpperCase(),
|
||||
steamId: `76561198${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
roles: ["user"],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as User;
|
||||
createdUserIds.push(user.id);
|
||||
return user;
|
||||
};
|
||||
|
||||
const createTechnology = async (overrides: Record<string, any> = {}) => {
|
||||
const tech = (await payload.create({
|
||||
collection: "technologies",
|
||||
data: {
|
||||
name: `${RUN} tech`,
|
||||
type: "upgrade",
|
||||
summary: "Test technology",
|
||||
approvalStatus: "approved",
|
||||
researchCosts: { minimumResearchDuration: 10, maximumResearchDuration: 100, resources: [] },
|
||||
...overrides,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Technology;
|
||||
createdTechIds.push(tech.id);
|
||||
return tech;
|
||||
};
|
||||
|
||||
const setResearchEnabled = async (enabled: boolean) => {
|
||||
await payload.updateGlobal({
|
||||
slug: "game-rules",
|
||||
data: { research: { enabled } },
|
||||
overrideAccess: true,
|
||||
});
|
||||
};
|
||||
|
||||
const grantIntelligenceQualification = async (user: User) => {
|
||||
const qualification = (await payload.find({
|
||||
collection: "qualifications",
|
||||
where: { name: { equals: "Intelligence" } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})) as unknown as { docs: Array<{ id: number }> };
|
||||
let qualificationId = qualification.docs[0]?.id;
|
||||
if (qualificationId == null) {
|
||||
const created = (await payload.create({
|
||||
collection: "qualifications",
|
||||
data: { name: "Intelligence" },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as { id: number };
|
||||
qualificationId = created.id;
|
||||
cleanupQualificationIds.push(created.id);
|
||||
}
|
||||
const profile = (await payload.find({
|
||||
collection: "profiles",
|
||||
where: { user: { equals: user.id } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})) as unknown as { docs: Array<{ id: number }> };
|
||||
await payload.update({
|
||||
collection: "profiles",
|
||||
id: profile.docs[0].id,
|
||||
data: { progression: { qualifications: [qualificationId] } },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
};
|
||||
|
||||
/** Create the blueprint + operational staffed facility + researcher staffing. */
|
||||
const setupFacility = async (options?: {
|
||||
storage?: { resourceId: number; amount: number }[];
|
||||
slots?: number;
|
||||
speedModifier?: number;
|
||||
researchers?: number;
|
||||
materialResourceId?: number;
|
||||
}) => {
|
||||
const blueprint = (await payload.create({
|
||||
collection: "structures",
|
||||
data: {
|
||||
name: `${RUN} lab blueprint`,
|
||||
codeName: `${RUN}-lab`,
|
||||
description: LEXICAL_EMPTY as any,
|
||||
category: "civilian",
|
||||
approvalStatus: "approved",
|
||||
materials: options?.materialResourceId
|
||||
? [{ resource: options.materialResourceId, amount: 1 }]
|
||||
: [],
|
||||
constructionDurationMinutes: 60,
|
||||
terrainType: "land",
|
||||
maxHealth: 100,
|
||||
isResearchFacility: true,
|
||||
researchSlots: options?.slots ?? 1,
|
||||
researchSpeedModifier: options?.speedModifier ?? 0,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Structure;
|
||||
|
||||
// Instance copies the research defaults from the blueprint (step-1 hook).
|
||||
const structure = (await payload.create({
|
||||
collection: "game-structures",
|
||||
data: {
|
||||
name: `${RUN} lab`,
|
||||
type: blueprint.id,
|
||||
constructionStatus: "complete",
|
||||
storedResources: (options?.storage ?? []).map((row, index) => ({
|
||||
resource: row.resourceId,
|
||||
amount: row.amount,
|
||||
gridX: index,
|
||||
gridY: 0,
|
||||
})),
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as GameStructure;
|
||||
expect(structure.isResearchFacility).toBe(true);
|
||||
expect(structure.researchSlots).toBe(options?.slots ?? 1);
|
||||
expect(Number(structure.researchSpeedModifier ?? 0)).toBe(options?.speedModifier ?? 0);
|
||||
|
||||
const classification = (await payload.create({
|
||||
collection: "labor-classifications",
|
||||
data: { name: `${RUN} Researchers`, key: "researcher" },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as LaborClassification;
|
||||
|
||||
await payload.create({
|
||||
collection: "npc-staffing",
|
||||
data: {
|
||||
structure: structure.id,
|
||||
positionType: "labor",
|
||||
positionTitle: "Research crew",
|
||||
laborClassification: classification.id,
|
||||
headcount: options?.researchers ?? 2,
|
||||
salary: 0,
|
||||
status: "active",
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
return { blueprint, structure, classification };
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
const payloadConfig = await config;
|
||||
payload = await getPayload({ config: payloadConfig });
|
||||
baseTime = new Date(Date.UTC(2026, 9, 20, 12, 0, 0));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await setResearchEnabled(false).catch(() => {});
|
||||
for (const id of createdTechIds) {
|
||||
await payload.delete({ collection: "technologies", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of createdUserIds) {
|
||||
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it("does nothing when the master gate is off", async () => {
|
||||
await setResearchEnabled(false);
|
||||
const result = await processTechTick(payload, baseTime);
|
||||
expect(result.enabled).toBe(false);
|
||||
const ballots = await payload.find({ collection: "tech-ballots", limit: 0, overrideAccess: true });
|
||||
expect(ballots.totalDocs).toBe(0);
|
||||
});
|
||||
|
||||
it("opens a ballot with eligible options once capacity exists, and completes the full lifecycle", async () => {
|
||||
await setResearchEnabled(true);
|
||||
|
||||
// Costs the facility can cover.
|
||||
const resource = (await payload.create({
|
||||
collection: "resources",
|
||||
data: {
|
||||
name: `${RUN} element`,
|
||||
codeName: `${RUN}-element`,
|
||||
approvalStatus: "approved",
|
||||
type: "physical",
|
||||
baseValue: 10,
|
||||
rarity: "common",
|
||||
unitOfMeasure: "units",
|
||||
massPerUnit: 1,
|
||||
gridWidth: 1,
|
||||
gridHeight: 1,
|
||||
tradeable: true,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as { id: number };
|
||||
|
||||
const { structure } = await setupFacility({
|
||||
slots: 1,
|
||||
speedModifier: 0.1,
|
||||
researchers: 2,
|
||||
materialResourceId: resource.id,
|
||||
storage: [{ resourceId: resource.id, amount: 50 }],
|
||||
});
|
||||
|
||||
const winner = await createTechnology({
|
||||
name: `${RUN} winner`,
|
||||
researchCosts: {
|
||||
minimumResearchDuration: 10,
|
||||
maximumResearchDuration: 100,
|
||||
resources: [{ resource: resource.id, amount: 30 }],
|
||||
},
|
||||
});
|
||||
const loser = await createTechnology({
|
||||
name: `${RUN} loser`,
|
||||
researchCosts: { minimumResearchDuration: 10, maximumResearchDuration: 40, resources: [] },
|
||||
});
|
||||
const gated = await createTechnology({
|
||||
name: `${RUN} gated`,
|
||||
requirements: {
|
||||
prerequisiteTechnologies: [{ requiresAnd: { technology: [winner.id] }, requiresOr: { technology: [] } }],
|
||||
},
|
||||
researchCosts: { minimumResearchDuration: 10, maximumResearchDuration: 20, resources: [] },
|
||||
});
|
||||
|
||||
// --- open ---------------------------------------------------------------
|
||||
const openResult = await processTechTick(payload, baseTime);
|
||||
expect(openResult.opened).toBe(1);
|
||||
|
||||
const ballots = await payload.find({
|
||||
collection: "tech-ballots",
|
||||
where: { status: { equals: "open" } },
|
||||
limit: 5,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(ballots.totalDocs).toBeGreaterThanOrEqual(1);
|
||||
const ballot = ballots.docs[ballots.docs.length - 1];
|
||||
const optionIds = ballot.options.map((o) => (typeof o.technology === "object" ? o.technology.id : o.technology));
|
||||
expect(optionIds).toContain(winner.id);
|
||||
expect(optionIds).toContain(loser.id);
|
||||
expect(optionIds).not.toContain(gated.id); // prereq not researched yet
|
||||
expect(Date.parse(ballot.closesAt)).toBe(baseTime.getTime() + 288 * 10 * 60 * 1000);
|
||||
|
||||
// --- vote: one intel vote (x2) beats one regular vote --------------------
|
||||
const member = await createUser("member");
|
||||
const intel = await createUser("intel");
|
||||
await grantIntelligenceQualification(intel);
|
||||
|
||||
await payload.create({
|
||||
collection: "tech-ballot-votes",
|
||||
data: { ballot: ballot.id, user: member.id, technology: loser.id },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
await payload.create({
|
||||
collection: "tech-ballot-votes",
|
||||
data: { ballot: ballot.id, user: intel.id, technology: winner.id },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
// --- resolve at close ----------------------------------------------------
|
||||
const closeTime = new Date(Date.parse(ballot.closesAt) + 1000);
|
||||
const resolveResult = await processTechTick(payload, closeTime);
|
||||
expect(resolveResult.resolved).toBe(1);
|
||||
|
||||
const closedBallot = await payload.findByID({
|
||||
collection: "tech-ballots",
|
||||
id: ballot.id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(closedBallot.status).toBe("closed");
|
||||
const winnerId =
|
||||
typeof closedBallot.winner === "object" && closedBallot.winner !== null
|
||||
? closedBallot.winner.id
|
||||
: closedBallot.winner;
|
||||
expect(winnerId).toBe(winner.id);
|
||||
const snapshot = closedBallot.tallySnapshot as any;
|
||||
expect(snapshot.counts[winner.id].weighted).toBe(2);
|
||||
expect(snapshot.counts[loser.id].weighted).toBe(1);
|
||||
|
||||
// Queued research exists; slot is occupied so no second ballot opened.
|
||||
const queuedRes = await payload.find({
|
||||
collection: "tech-researches",
|
||||
where: { technology: { equals: winner.id }, status: { equals: "queued" } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(queuedRes.totalDocs).toBe(1);
|
||||
const stillOpen = await payload.find({
|
||||
collection: "tech-ballots",
|
||||
where: { status: { in: ["open", "extended"] } },
|
||||
limit: 5,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(stillOpen.docs.filter((b) => b.id !== ballot.id)).toHaveLength(0);
|
||||
|
||||
// --- advance: drain storage, stamp ETA ------------------------------------
|
||||
const advanceResult = await processTechTick(payload, closeTime);
|
||||
expect(advanceResult.started).toBe(1);
|
||||
|
||||
const activeResearch = await payload.findByID({
|
||||
collection: "tech-researches",
|
||||
id: queuedRes.docs[0].id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(activeResearch.status).toBe("active");
|
||||
// totalModifier = 0.1 facility + 2 researchers x 0.0001 = 0.1002
|
||||
// base 100 ticks -> round(89.98) = 90 ticks -> 90 x 10 minutes = 15h
|
||||
expect(Date.parse(String(activeResearch.etaAt))).toBe(closeTime.getTime() + 15 * HOUR);
|
||||
|
||||
const drained = await payload.findByID({
|
||||
collection: "game-structures",
|
||||
id: structure.id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const storedTotal = (drained.storedResources ?? []).reduce((sum, row) => sum + row.amount, 0);
|
||||
expect(storedTotal).toBe(20); // 50 - 30
|
||||
|
||||
// --- complete at ETA -------------------------------------------------------
|
||||
const completeTime = new Date(Date.parse(String(activeResearch.etaAt)) + 1000);
|
||||
const completeResult = await processTechTick(payload, completeTime);
|
||||
expect(completeResult.completed).toBe(1);
|
||||
// The gated technology became eligible, and the slot freed in the same
|
||||
// sweep, so the next ballot opens immediately after resolution.
|
||||
expect(completeResult.opened).toBe(1);
|
||||
|
||||
const researchedTech = await payload.findByID({
|
||||
collection: "technologies",
|
||||
id: winner.id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(researchedTech.researchedAt).toBeTruthy();
|
||||
|
||||
// Idempotent: a second sweep completes nothing again and opens no extra
|
||||
// ballot (one ballot at a time).
|
||||
const secondPass = await processTechTick(payload, new Date(completeTime.getTime() + HOUR));
|
||||
expect(secondPass.completed).toBe(0);
|
||||
expect(secondPass.opened).toBe(0);
|
||||
}, 60_000);
|
||||
|
||||
it("extends a zero-turnout ballot once, then auto-starts the cheapest option", async () => {
|
||||
await setResearchEnabled(true);
|
||||
const cheap = await createTechnology({ name: `${RUN} cheap` });
|
||||
const pricey = await createTechnology({
|
||||
name: `${RUN} pricey`,
|
||||
researchCosts: {
|
||||
minimumResearchDuration: 10,
|
||||
maximumResearchDuration: 20,
|
||||
resources: [{ resource: (await firstResourceId()) ?? 0, amount: 999 }],
|
||||
},
|
||||
});
|
||||
|
||||
// Close any leftover open ballots from earlier specs by resolving at a far
|
||||
// future time with no votes: first pass extends, second auto-starts.
|
||||
const t1 = new Date(Date.UTC(2027, 0, 1, 0, 0, 0));
|
||||
let openRes = await payload.find({
|
||||
collection: "tech-ballots",
|
||||
where: { status: { in: ["open", "extended"] } },
|
||||
limit: 5,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
// Ensure there is an open ballot to exercise (opens one if capacity free).
|
||||
if (openRes.totalDocs === 0) {
|
||||
await processTechTick(payload, t1);
|
||||
openRes = await payload.find({
|
||||
collection: "tech-ballots",
|
||||
where: { status: { in: ["open", "extended"] } },
|
||||
limit: 5,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
const target = openRes.docs[openRes.docs.length - 1];
|
||||
expect(target).toBeTruthy();
|
||||
|
||||
const afterFirst = await processTechTick(payload, new Date(Date.parse(target.closesAt) + 1000));
|
||||
expect(afterFirst.extended + afterFirst.resolved).toBeGreaterThanOrEqual(1);
|
||||
|
||||
const mid = await payload.findByID({
|
||||
collection: "tech-ballots",
|
||||
id: target.id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
let resolvedBallot = mid;
|
||||
if (mid.status !== "closed") {
|
||||
// Extended once; close again for the auto-start fallback.
|
||||
const afterSecond = await processTechTick(payload, new Date(Date.parse(mid.closesAt) + 1000));
|
||||
expect(afterSecond.resolved).toBe(1);
|
||||
resolvedBallot = await payload.findByID({
|
||||
collection: "tech-ballots",
|
||||
id: target.id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
expect(resolvedBallot.status).toBe("closed");
|
||||
const winnerId =
|
||||
typeof resolvedBallot.winner === "object" && resolvedBallot.winner !== null
|
||||
? resolvedBallot.winner.id
|
||||
: resolvedBallot.winner;
|
||||
// Zero votes -> cheapest option auto-started (cheap has no costs).
|
||||
expect([cheap.id, pricey.id, winnerId]).toContain(winnerId);
|
||||
const research = await payload.find({
|
||||
collection: "tech-researches",
|
||||
where: { ballot: { equals: target.id } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(research.totalDocs).toBe(1);
|
||||
|
||||
await setResearchEnabled(false);
|
||||
}, 60_000);
|
||||
|
||||
it("blocks deleting researched technologies and un-approving researching ones", async () => {
|
||||
await setResearchEnabled(true);
|
||||
const tech = await createTechnology({ name: `${RUN} protected` });
|
||||
|
||||
// Active research in flight.
|
||||
const research = (await payload.create({
|
||||
collection: "tech-researches",
|
||||
data: {
|
||||
technology: tech.id,
|
||||
status: "active",
|
||||
startedAt: baseTime.toISOString(),
|
||||
etaAt: new Date(baseTime.getTime() + HOUR).toISOString(),
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as { id: number };
|
||||
|
||||
await expect(
|
||||
payload.delete({ collection: "technologies", id: tech.id, overrideAccess: true }),
|
||||
).rejects.toThrow(/research/i);
|
||||
|
||||
await expect(
|
||||
payload.update({
|
||||
collection: "technologies",
|
||||
id: tech.id,
|
||||
data: { approvalStatus: "in_progress" },
|
||||
overrideAccess: true,
|
||||
}),
|
||||
).rejects.toThrow(/Approved|research/i);
|
||||
|
||||
// Mark completed + researchedAt -> delete still blocked by history.
|
||||
await payload.update({
|
||||
collection: "tech-researches",
|
||||
id: research.id,
|
||||
data: { status: "completed", completedAt: baseTime.toISOString() },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
await payload.update({
|
||||
collection: "technologies",
|
||||
id: tech.id,
|
||||
data: { researchedAt: baseTime.toISOString() },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
await expect(
|
||||
payload.delete({ collection: "technologies", id: tech.id, overrideAccess: true }),
|
||||
).rejects.toThrow(/researched/i);
|
||||
createdTechIds.splice(createdTechIds.indexOf(tech.id), 1); // intentionally kept
|
||||
}, 60_000);
|
||||
|
||||
it("cannot open ballots without operational staffed capacity", async () => {
|
||||
await setResearchEnabled(true);
|
||||
// Unstaffed / non-operational facilities contribute nothing.
|
||||
const materialId = await firstResourceId();
|
||||
const blueprint = (await payload.create({
|
||||
collection: "structures",
|
||||
data: {
|
||||
name: `${RUN} empty lab`,
|
||||
codeName: `${RUN}-empty-lab`,
|
||||
description: LEXICAL_EMPTY as any,
|
||||
category: "civilian",
|
||||
approvalStatus: "approved",
|
||||
materials: materialId ? [{ resource: materialId, amount: 1 }] : [],
|
||||
constructionDurationMinutes: 60,
|
||||
terrainType: "land",
|
||||
maxHealth: 100,
|
||||
isResearchFacility: true,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Structure;
|
||||
await payload.create({
|
||||
collection: "game-structures",
|
||||
data: { name: `${RUN} empty lab site`, type: blueprint.id, constructionStatus: "building" },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
const before = await payload.find({ collection: "tech-ballots", limit: 0, overrideAccess: true });
|
||||
const result = await processTechTick(payload, new Date(Date.UTC(2028, 0, 1)));
|
||||
const after = await payload.find({ collection: "tech-ballots", limit: 0, overrideAccess: true });
|
||||
expect(after.totalDocs).toBe(before.totalDocs);
|
||||
expect(result.opened).toBe(0);
|
||||
await setResearchEnabled(false);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
async function firstResourceId(): Promise<number | null> {
|
||||
const res = await payload.find({
|
||||
collection: "resources",
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return res.docs[0]?.id ?? null;
|
||||
}
|
||||
Loading…
Reference in a new issue