1
0
Fork 0

Compare commits

...

4 commits

Author SHA1 Message Date
429d2028d0 v0.16.4 - add unlimited arsenal stock, fix the claimed op notice 2026-11-20 20:14:55 -05:00
86b1c9ae61 docs: add v0.16.4 changelog entry 2026-11-20 20:13:18 -05:00
b90247a288 fix(bot): rewrite the Friday notice in the claimed state
The claim path appended a credit line to the invitation, so a claimed notice
still said the slot was open, that nobody had picked it up, and that Jason
would host if nobody did.

- renderClaimedNotice(): the whole body for the claimed state, role ping
  dropped since there is nothing left to ask for
- compare the live message against the rendered body each poll, so a message
  left contradictory by an older build heals on the next tick
- a cancelled claim still restores the full invitation, ping included
- cover both bodies and the claim parser in the notice integration test
2026-11-20 20:11:53 -05:00
5418d6563e feat(lockers): seed and unlimited-stock sync for limited arsenal 2026-11-20 19:52:15 -05:00
15 changed files with 46692 additions and 49 deletions

View file

@ -1,5 +1,21 @@
# Changelog
# v0.16.4
Arsenal stock can now be unlimited, and the Friday op notice stops contradicting itself once someone claims the slot.
### Features
- **Unlimited arsenal stock.** Lockers and base stock can mark an item as unlimited, so it can be taken any number of times without the count going down. Useful for arsenals where a category of gear should never run out.
- **Arsenal stock survives a dropped connection.** While the server is not talking to the site, the game keeps its own copy of each locker's contents, so a mission restart no longer empties lockers that were stocked. The first time an instance links, the site takes the stock the game already holds instead of starting blank.
### Fixes
- **Friday op notice.** Once a community host claims the Friday slot, the Discord notice now reads as claimed throughout. It no longer says the slot is still open or that Jason will host it if nobody does, and the Community Zeus ping is dropped, since there is nothing left to ask for.
- Various bug fixes and improvements.
---
# v0.16.3
Relations and ratings read the right way round now, and the weekly Discord op notice shows the correct day.

View file

@ -46,13 +46,15 @@ serverTime]`, payload defaults to `[]`).
| Type | Payload | Meaning |
|---|---|---|
| `locker.sync` | `[instanceRef, [[itemClass, count], ...]]` | Full stock snapshot for one instance after a committed change. |
| `locker.seed` | `[instanceRef, [[itemClass, count], ...]]` | Create-only first-bind seed. Applied only when the web has no document (personal) or no `storedAssets` yet (structure); never overwrites existing web state. |
| `locker.request` | `[instanceRef]` | The game asks the web to push current state for this instance (mission start, player connect, availability refresh). |
`locker.sync` snapshot rules:
- TOP-LEVEL stock only: `[itemClass, count]` pairs, one per class, counts are
integers >= 0. Classes with count 0 MAY be included (explicit depletion) or
omitted (treated as unknown/absent, not as zero — see merge rules).
- TOP-LEVEL stock only: `[itemClass, count]` pairs, one per class. Counts are
integers >= 0, or `-1` for an Antistasi-style **unlimited** entry. Classes
with count 0 MAY be included (explicit depletion) or omitted (treated as
unknown/absent, not as zero — see merge rules).
- Emitted after every committed stock mutation (take settlement, deposit,
Zeus/Eden edit, `locker.apply` application) while the bridge is enabled.
- Dedup is web-side by `eventId`; retried flushes never double-apply.
@ -70,9 +72,10 @@ serverTime]`, payload defaults to `[]`).
Unknown slug is logged and skipped.
- Merge per entry by `asset.className`:
- Existing web entry whose class appears in the snapshot → `quantity` set to
the snapshot count. **All web-managed metadata is preserved**: `gridX`,
`gridY`, `rotated`, and the `equipment` group (attachments, skin,
customName) are never touched by the merge.
the snapshot count (or `1` with `unlimited = true` for `-1`). **All
web-managed metadata is preserved**: `gridX`, `gridY`, `rotated`, and the
`equipment` group (attachments, skin, customName) are never touched by the
merge.
- Snapshot class with no web entry → create the entry (asset resolved by
`className`; unknown classes are skipped with a warning) and **auto-place**
it in the next free grid cell (row-major scan, unrotated). Equipment left
@ -88,6 +91,11 @@ serverTime]`, payload defaults to `[]`).
- Enqueue exactly one `locker.apply` command for the requesting server with
the web's current full snapshot for that instanceRef. Unknown/unlinked
instanceRefs enqueue nothing.
- **No-wipe rule**: a linked Steam ID with no `locker-storages` document, and
an unknown structure slug, are both "unknown" → nothing is enqueued. An
empty snapshot is only sent for a document that actually exists and is empty.
The game therefore keeps its local `profileNamespace` stock until the web
has a real snapshot to apply.
## Command envelope and schemas
@ -96,7 +104,7 @@ and `fn_executeCommand` destructures), stored in `arma-commands`.
| Type | Payload | Effect |
|---|---|---|
| `locker.apply` | `[instanceRef, [[itemClass, count], ...]]` | Server replaces the instance's stock wholesale with the given pairs, pushes availability to clients, and acks. |
| `locker.apply` | `[instanceRef, [[itemClass, count], ...]]` | Server replaces the instance's stock wholesale with the given pairs, pushes availability to clients, and acks. `-1` means unlimited. |
- The web enqueues `locker.apply` when: (a) a member/admin edits locker items
or structure `storedAssets` in the UI (afterChange hook), or (b) a
@ -118,12 +126,19 @@ and `fn_executeCommand` destructures), stored in `arma-commands`.
- Web event processors never throw: malformed payloads are logged and skipped;
one bad event never aborts the batch or rolls back raw-event ingestion.
- Duplicate eventIds are deduped (counted as duplicates, no double-apply).
- Bridge disabled/unreachable: the mod keeps full session-local stock; queued
`locker.sync` events flush when the bridge returns (queue cap drops oldest,
per existing bridge behavior).
- Game store is volatile per mission (like crate registry): on mission start
the mod emits `locker.request` for every bound structure instance and per
connecting player, and the web replies with `locker.apply`.
- Bridge disabled/unreachable: the mod keeps its local stock AND persists it
to `profileNamespace` (per world, key `twwk_arsenal_store_<world>`, written by
a debounced saver and at mission end). The store survives mission restarts on
the same server with the bridge off. Queued `locker.sync` events flush when
the bridge returns (queue cap drops oldest, per existing bridge behavior).
- On mission start the mod loads the local store first, then emits
`locker.request` for every bound structure instance and per connecting
player; the web replies with `locker.apply` only when it has a document to
apply (no-wipe rule).
- New storage instances seed once: `cargo` turns the bound crate's Eden cargo
into stock and clears the crate; `custom` parses `class:count` pairs;
`none` starts empty. Personal lockers always start empty (per player) and
are created on first access.
## Security
@ -135,10 +150,19 @@ and `fn_executeCommand` destructures), stored in `arma-commands`.
## Mod-side behavior (TWWK `twwk_arsenal`)
- Server store: `instanceRef → (className → count)` in missionNamespace.
- Availability: a class is in the ACE Arsenal virtual-item set iff count > 0
- Server store: `instanceRef → (className → count)` in missionNamespace, backed
by the per-world `profileNamespace` store. `-1` is unlimited.
- Module binding: the Eden/Zeus "Limited Arsenal Storage" module binds the crate
it is placed on (or synced to) — `attachedTo` → `synchronizedObjects` → a
downward ray through the module → nearest object within 2.5 m. Eden applies
its Attributes at mission start; Zeus opens the bind window on placement and
on double-click.
- Availability: a class is in the ACE Arsenal virtual-item set iff count != 0
(shared instances: global `addVirtualItems`/`removeVirtualItems`; personal:
targeted per-player local set).
targeted per-player local set). Zero-stock classes are hidden.
- Count display: `[xN]` / `[∞]` in the left list's right column, a "Storage"
stat in the item panel, and a "Stock (high to low)" sort. Unlimited sorts
above finite stacks.
- Settlement: client snapshots gear on `ace_arsenal_displayOpened`, diffs on
`ace_arsenal_displayClosed`, server validates/clamps and commits; live
over-take into containers is clamped per `ace_arsenal_cargoChanged`.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.16.3",
"version": "0.16.4",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -99,7 +99,7 @@ Once a mission is evaluable (`Completed`, or `Scheduled`/`Active` past its start
## Feature flow: Friday open-slot notice
At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in `src/lib/intelligence/fridayOpsNotice.ts`; catch-up until ET midnight, a fully missed Wednesday skips to next week), if no non-cancelled mission starts on that week's upcoming Friday, `fridayOpsNotice` posts once in #side-ops pinging the Community Zeus role: the slot is open, hosting is welcome, and if nobody picks it up the slot stays empty or Jason hosts it himself. The slot window is Friday 00:00–23:59:59.999 **America/New_York** computed from the Eastern calendar date, never the server clock (the UTC deploy container once treated Wed 8 PM ET as Thursday and missed Friday-evening ops entirely); when it is already Friday Eastern, that day itself is the slot, so the dedup token stays stable from Wednesday through the op day and late claims still credit. When a non-superuser creator later claims the slot (`getFridayClaimant`, earliest-created mission wins; superuser/staff-created missions never claim), the notice is edited to append "This slot was claimed by \<user\>. Thank you for hosting for our community!"; if that op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a between-polls claim swap re-credits the new claimant). Role: `DISCORD_COMMUNITY_ZEUS_ROLE_ID` or resolved by name in the guild; channel: `DISCORD_SIDE_OPS_CHANNEL_ID`. Dedup without DB state: the message embeds a stable per-Friday Eastern date label (e.g. `January 15, 2027`) and the service scans recent channel messages for it (claim idempotency via a marker in the message content). Never use Discord's `<t:epoch:D>` for this date: it renders in each viewer's timezone, so an epoch at Friday 00:00 Eastern displayed as Thursday for members in Central/Mountain/Pacific/Hawaii. Notices still carrying the old `<t:epoch:D>` token are matched and rewritten in place to the Eastern label. Drafts (Concept) count as the slot being taken.
At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in `src/lib/intelligence/fridayOpsNotice.ts`; catch-up until ET midnight, a fully missed Wednesday skips to next week), if no non-cancelled mission starts on that week's upcoming Friday, `fridayOpsNotice` posts once in #side-ops pinging the Community Zeus role: the slot is open, hosting is welcome, and if nobody picks it up the slot stays empty or Jason hosts it himself. The slot window is Friday 00:00–23:59:59.999 **America/New_York** computed from the Eastern calendar date, never the server clock (the UTC deploy container once treated Wed 8 PM ET as Thursday and missed Friday-evening ops entirely); when it is already Friday Eastern, that day itself is the slot, so the dedup token stays stable from Wednesday through the op day and late claims still credit. When a non-superuser creator later claims the slot (`getFridayClaimant`, earliest-created mission wins; superuser/staff-created missions never claim), the notice is rewritten to the claimed state: the invitation and its role ping are replaced with "The Friday op slot (<date>) is taken." plus "This slot was claimed by \<user\>. Thank you for hosting for our community!" (leaving the invitation in place would contradict the credit line). If that op is later cancelled or deleted, the claim line is stripped and the whole invitation, role ping included, is restored (a between-polls claim swap re-credits the new claimant; the service compares the rendered body each poll, so a message left in a contradictory state by an older build heals itself). Role: `DISCORD_COMMUNITY_ZEUS_ROLE_ID` or resolved by name in the guild; channel: `DISCORD_SIDE_OPS_CHANNEL_ID`. Dedup without DB state: the message embeds a stable per-Friday Eastern date label (e.g. `January 15, 2027`) and the service scans recent channel messages for it (claim idempotency via a marker in the message content). Never use Discord's `<t:epoch:D>` for this date: it renders in each viewer's timezone, so an epoch at Friday 00:00 Eastern displayed as Thursday for members in Central/Mountain/Pacific/Hawaii. Notices still carrying the old `<t:epoch:D>` token are matched and rewritten in place to the Eastern label. Drafts (Concept) count as the slot being taken.
## Feature flow: assignment transfers

View file

@ -21,12 +21,13 @@ import {
* scheduled for that week's Friday yet, post once in #side-ops pinging the
* Community Zeus role, offering the slot.
*
* When a non-superuser (a community zeus) later claims the slot, the notice
* is edited to credit them instead; if that claim op is later cancelled (or
* deleted), the notice reverts to the open-slot state. Dedup needs no DB
* state: the notice embeds a stable per-Friday Eastern date label and the
* service scans recent channel messages for it (and for the claim line)
* before posting or editing, so bot restarts never double-post or re-credit.
* When a non-superuser (a community zeus) later claims the slot, the notice is
* rewritten to the claimed state (the invitation and its role ping replaced by
* the credit line); if that claim op is later cancelled (or deleted), the
* notice reverts to the open-slot invitation. Dedup needs no DB state: the
* notice embeds a stable per-Friday Eastern date label and the service scans
* recent channel messages for it before posting or editing, so bot restarts
* never double-post or re-credit.
*/
const MESSAGE_SCAN_LIMIT = 100;
@ -72,7 +73,19 @@ const CLAIM_MARKER = "This slot was claimed by";
const CLAIM_LINE_PATTERN =
/\n\nThis slot was claimed by (.+)\. Thank you for hosting for our community!$/;
const creditedNameOf = (content: string): string | null =>
/**
* The same notice once a community zeus has claimed the slot. The invitation
* above is replaced rather than kept: "the slot is still open ... if nobody
* picks it up" directly contradicts the credit line under it, so the whole
* body is rewritten to the claimed state (and the role ping dropped, since
* there is nothing left to ask for).
*/
export const renderClaimedNotice = (userName: string, now = new Date()): string =>
`The Friday op slot (${fridayDateLabel(now)}) is taken.\n\n` +
`${CLAIM_MARKER} ${userName}. Thank you for hosting for our community!`;
/** The credited host, when the message body is in the claimed state. */
export const claimedByName = (content: string): string | null =>
content.match(CLAIM_LINE_PATTERN)?.[1] ?? null;
/**
@ -128,34 +141,37 @@ const processNotice = async (
return "posted";
}
// A notice posted before the Eastern label existed still carries the old
// `<t:epoch:D>` token (which reads as Thursday west of Eastern). Upgrade it
// in place so the visible date is correct for everyone.
let content = notice.content;
if (!content.includes(token) && content.includes(legacyToken)) {
content = content.replace(legacyToken, token);
await notice.edit(content);
// Once a host has claimed the slot the message must read as claimed end to
// end. Comparing against the rendered body instead of appending a line also
// heals a message an older build left with the invitation still in it.
if (claim) {
const desired = renderClaimedNotice(claim.userName, now);
if (notice.content === desired) return "idle";
await notice.edit(desired);
payload.logger.info(
`[Bot] Friday open-slot notice for ${token}: upgraded the legacy date token to the Eastern label.`,
`[Bot] Friday open-slot notice for ${token} claimed by ${claim.userName}; notice rewritten to the claimed state.`,
);
return "edited";
}
const credited = creditedNameOf(content);
if (!claim) {
if (!credited) return "idle";
await notice.edit(content.replace(CLAIM_LINE_PATTERN, ""));
// The claim went away (op cancelled or deleted): restore the full invitation,
// including the role ping, so the slot reads as open again.
const credited = claimedByName(notice.content);
if (credited) {
const zeusRoleId = await resolveZeusRoleId(client);
await notice.edit(renderNotice(zeusRoleId, now));
payload.logger.info(
`[Bot] Friday open-slot notice for ${token}: claim by ${credited} was cancelled; notice reverted to the open-slot state.`,
);
return "edited";
}
if (credited !== claim.userName) {
const base = credited ? content.replace(CLAIM_LINE_PATTERN, "") : content;
await notice.edit(
`${base}\n\n${CLAIM_MARKER} ${claim.userName}. Thank you for hosting for our community!`,
);
// Open and unclaimed: the only repair left is the legacy Discord timestamp
// token, which reads as Thursday for viewers west of Eastern.
if (!notice.content.includes(token) && notice.content.includes(legacyToken)) {
await notice.edit(notice.content.replace(legacyToken, token));
payload.logger.info(
`[Bot] Friday open-slot notice for ${token} claimed by ${claim.userName}; notice updated.`,
`[Bot] Friday open-slot notice for ${token}: upgraded the legacy date token to the Eastern label.`,
);
return "edited";
}

View file

@ -476,6 +476,15 @@ export const GameStructures: CollectionConfig = {
min: 0,
defaultValue: 1,
},
{
name: "unlimited",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Antistasi-style unlimited stock: the game may take this entry without decrementing. The quantity field is kept at 1 for display.",
},
},
{
name: "gridX",
type: "number",

View file

@ -80,6 +80,15 @@ export const LockerStorages: CollectionConfig = {
min: 0,
defaultValue: 1,
},
{
name: "unlimited",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Antistasi-style unlimited stock: the game may take this entry without decrementing. The quantity field is kept at 1 for display.",
},
},
{
name: "gridX",
type: "number",

View file

@ -66,7 +66,10 @@ export function parseStockSnapshot(value: unknown): LockerStockLine[] | null {
const count = entry[1];
if (typeof className !== "string" || className.length === 0 || className.length > 200) continue;
if (typeof count !== "number" || !Number.isFinite(count)) continue;
lines.push({ className, count: Math.max(0, Math.round(count)) });
// -1 is the Antistasi-style unlimited entry; any other negative is clamped
// to -1 so a malformed sender cannot create arbitrary negative stock.
const rounded = Math.round(count);
lines.push({ className, count: rounded < 0 ? -1 : rounded });
}
return lines;
}
@ -167,7 +170,12 @@ export async function stockPairsFromItems(
const assetId = relId(row.asset);
const className = assetId != null ? classById.get(assetId) : undefined;
const quantity = typeof row.quantity === "number" ? Math.round(row.quantity) : 0;
if (!className || quantity < 1) continue;
if (!className) continue;
if (row.unlimited === true) {
pairs.push([className, -1]);
continue;
}
if (quantity < 1) continue;
pairs.push([className, quantity]);
}
return pairs;
@ -202,9 +210,11 @@ export function mergeStockIntoItems(
}, -1) + 1;
for (const line of snapshot) {
const unlimited = line.count < 0;
const quantity = unlimited ? 1 : line.count;
const hit = indexByClassName.get(line.className);
if (hit !== undefined) {
merged[hit] = { ...merged[hit], quantity: line.count };
merged[hit] = { ...merged[hit], quantity, unlimited };
continue;
}
const assetId = assetIdByClassName.get(line.className);
@ -214,7 +224,8 @@ export function mergeStockIntoItems(
}
const row: ExistingItemRow = {
asset: assetId,
quantity: line.count,
quantity,
unlimited,
gridX: 0,
gridY: nextY,
rotated: false,
@ -329,6 +340,16 @@ export async function processLockerEvent(
return;
}
if (raw.type === "locker.seed") {
const snapshot = parseStockSnapshot(raw.payload[1]);
if (!snapshot) {
payload.logger.warn(`[LockerSync] Event ${raw.eventId} has a malformed seed snapshot; skipping`);
return;
}
await applySeedToInstance(payload, ref, refString, snapshot, raw.eventId, req);
return;
}
if (raw.type === "locker.request") {
const stock = await currentStockForInstance(payload, ref);
if (stock === null) {
@ -436,6 +457,98 @@ async function applySnapshotToInstance(
});
}
/**
* Create-only seed: fills an EMPTY instance from the game's first-bind stock.
* An instance with existing items is left untouched so a seed event can never
* overwrite a web-managed document. Never echoes a locker.apply command.
*/
async function applySeedToInstance(
payload: Payload,
ref: LockerInstanceRef,
refString: string,
snapshot: LockerStockLine[],
eventId: string,
req?: PayloadRequest,
): Promise<void> {
const assetIds = await findAssetIdsByClassName(
payload,
snapshot.map((line) => line.className),
);
markSyncOrigin(req);
if (ref.kind === "personal") {
const userId = await findUserIdBySteamId(payload, ref.steamId);
if (!userId) {
payload.logger.info(
`[LockerSync] Seed for unlinked Steam ID ${ref.steamId}; session-only stock, event ${eventId} skipped`,
);
return;
}
const lockers = await payload.find({
collection: "locker-storages",
where: { ownerUser: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
req,
});
const items = mergeStockIntoItems([], snapshot, assetIds, (m) => payload.logger.warn(m));
const existingLocker = lockers.docs[0];
if (existingLocker) {
const existingItems = (existingLocker as { items?: unknown }).items;
if (Array.isArray(existingItems) && existingItems.length > 0) {
payload.logger.info(`[LockerSync] Seed for non-empty ${refString}; ignored`);
return;
}
await payload.update({
collection: "locker-storages",
id: existingLocker.id,
data: { items: items as never },
overrideAccess: true,
depth: 0,
req,
});
return;
}
await payload.create({
collection: "locker-storages",
data: { name: "Personal Locker", ownerUser: userId, items: items as never },
overrideAccess: true,
depth: 0,
req,
});
return;
}
const structures = await payload.find({
collection: "game-structures",
where: { storageSlug: { equals: ref.slug } },
limit: 1,
depth: 0,
overrideAccess: true,
req,
});
const structure = structures.docs[0];
if (!structure) {
payload.logger.warn(`[LockerSync] Seed for unknown structure "${ref.slug}"; event ${eventId} skipped`);
return;
}
const existing = (structure as { storedAssets?: unknown }).storedAssets;
if (Array.isArray(existing) && existing.length > 0) {
payload.logger.info(`[LockerSync] Seed for non-empty ${refString}; ignored`);
return;
}
const items = mergeStockIntoItems([], snapshot, assetIds, (m) => payload.logger.warn(m));
await payload.update({
collection: "game-structures",
id: structure.id,
data: { storedAssets: items as never },
overrideAccess: true,
depth: 0,
req,
});
}
/**
* The web's current stock for an instance as [className, count] pairs.
* Null when the instance cannot be resolved (unknown slug / unlinked user);
@ -456,7 +569,10 @@ async function currentStockForInstance(
overrideAccess: true,
});
const locker = lockers.docs[0];
if (!locker) return [];
// No locker document = the web has never seen this locker. Enqueueing an
// empty snapshot would wipe the game's local stock, so return null: the
// game keeps its profileNamespace stock until it syncs a real snapshot.
if (!locker) return null;
return stockPairsFromItems(payload, (locker as { items?: unknown }).items);
}
const structures = await payload.find({

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_structures_stored_assets" ADD COLUMN "unlimited" boolean DEFAULT false;
ALTER TABLE "locker_storages_items" ADD COLUMN "unlimited" boolean DEFAULT false;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_structures_stored_assets" DROP COLUMN "unlimited";
ALTER TABLE "locker_storages_items" DROP COLUMN "unlimited";`)
}

View file

@ -161,6 +161,7 @@ import * as migration_20261117_212337_add_faction_discovered_field from './20261
import * as migration_20261118_143000_add_wiki_pages_draft_and_created_by from './20261118_143000_add_wiki_pages_draft_and_created_by';
import * as migration_20261118_184813_add_faction_relation_entries from './20261118_184813_add_faction_relation_entries';
import * as migration_20261118_184851_drop_factions_relationships_array from './20261118_184851_drop_factions_relationships_array';
import * as migration_20261120_234950_add_locker_unlimited from './20261120_234950_add_locker_unlimited';
export const migrations = [
{
@ -976,6 +977,11 @@ export const migrations = [
{
up: migration_20261118_184851_drop_factions_relationships_array.up,
down: migration_20261118_184851_drop_factions_relationships_array.down,
name: '20261118_184851_drop_factions_relationships_array'
name: '20261118_184851_drop_factions_relationships_array',
},
{
up: migration_20261120_234950_add_locker_unlimited.up,
down: migration_20261120_234950_add_locker_unlimited.down,
name: '20261120_234950_add_locker_unlimited'
},
];

View file

@ -2151,6 +2151,7 @@ export const game_structures_stored_assets = pgTable(
onDelete: "set null",
}),
quantity: numeric("quantity", { mode: "number" }).notNull().default(1),
unlimited: boolean("unlimited").default(false),
gridX: numeric("grid_x", { mode: "number" }).notNull().default(0),
gridY: numeric("grid_y", { mode: "number" }).notNull().default(0),
rotated: boolean("rotated").default(false),
@ -6769,6 +6770,7 @@ export const locker_storages_items = pgTable(
onDelete: "set null",
}),
quantity: numeric("quantity", { mode: "number" }).notNull().default(1),
unlimited: boolean("unlimited").default(false),
gridX: numeric("grid_x", { mode: "number" }).notNull().default(0),
gridY: numeric("grid_y", { mode: "number" }).notNull().default(0),
rotated: boolean("rotated").default(false),

View file

@ -1302,6 +1302,10 @@ export interface GameStructure {
| {
asset: number | Asset;
quantity: number;
/**
* Antistasi-style unlimited stock: the game may take this entry without decrementing. The quantity field is kept at 1 for display.
*/
unlimited?: boolean | null;
/**
* Column position in the storage grid (0-indexed).
*/
@ -5461,6 +5465,10 @@ export interface LockerStorage {
| {
asset: number | Asset;
quantity: number;
/**
* Antistasi-style unlimited stock: the game may take this entry without decrementing. The quantity field is kept at 1 for display.
*/
unlimited?: boolean | null;
/**
* Column position in the locker grid (0-indexed).
*/
@ -9949,6 +9957,7 @@ export interface GameStructuresSelect<T extends boolean = true> {
| {
asset?: T;
quantity?: T;
unlimited?: T;
gridX?: T;
gridY?: T;
rotated?: T;
@ -11782,6 +11791,7 @@ export interface LockerStoragesSelect<T extends boolean = true> {
| {
asset?: T;
quantity?: T;
unlimited?: T;
gridX?: T;
gridY?: T;
rotated?: T;

View file

@ -34,6 +34,7 @@ let assetBId: number;
let resourceId: number;
let blueprintId: number;
let structureId: number;
let seedStructureId: number;
let lockerId: number;
let serverId: number;
// Highest arma-commands id when this file starts (set in beforeAll). Rows at or
@ -177,6 +178,19 @@ describe("Arma locker sync", () => {
});
structureId = structure.id;
const seedStructure = await payload.create({
collection: "game-structures",
data: {
name: `${RUN} Seed Storage`,
type: blueprintId,
constructionStatus: "complete",
storageSlug: `${RUN}-seed`,
} as never,
overrideAccess: true,
depth: 0,
});
seedStructureId = seedStructure.id;
// Isolate from arma-commands rows left by earlier spec files (foreign online
// servers change locker fan-out and pollute the total-count assertions).
const latest = await payload.find({
@ -200,6 +214,9 @@ describe("Arma locker sync", () => {
if (structureId) {
await payload.delete({ collection: "game-structures", id: structureId, overrideAccess: true }).catch(() => {});
}
if (seedStructureId) {
await payload.delete({ collection: "game-structures", id: seedStructureId, overrideAccess: true }).catch(() => {});
}
if (blueprintId) {
await payload.delete({ collection: "structures", id: blueprintId, overrideAccess: true }).catch(() => {});
}
@ -264,6 +281,18 @@ describe("Arma locker sync", () => {
{ className: CLASS_B, count: 2 },
]);
});
it("keeps -1 as unlimited and clamps other negatives to -1", () => {
expect(
parseStockSnapshot([
[CLASS_A, -1],
[CLASS_B, -17],
]),
).toEqual([
{ className: CLASS_A, count: -1 },
{ className: CLASS_B, count: -1 },
]);
});
});
describe("mergeStockIntoItems", () => {
@ -291,6 +320,18 @@ describe("Arma locker sync", () => {
expect(merged[1]).toMatchObject({ className: "other_class", quantity: 1 });
expect(merged[2]).toMatchObject({ asset: 2, quantity: 10, gridX: 0, gridY: 5, rotated: false });
});
it("stores unlimited entries as quantity 1 + unlimited flag, preserving grid metadata", () => {
const existing = [
{ asset: 1, quantity: 2, gridX: 3, gridY: 4, rotated: true, className: CLASS_A },
];
const merged = mergeStockIntoItems(
existing,
[{ className: CLASS_A, count: -1 }],
new Map([[CLASS_A, 1]]),
);
expect(merged[0]).toMatchObject({ quantity: 1, unlimited: true, gridX: 3, gridY: 4, rotated: true });
});
});
describe("locker.sync (personal)", () => {
@ -406,6 +447,28 @@ describe("Arma locker sync", () => {
processLockerEvent(payload, lockerEvent("locker.sync", [`structure:${RUN}-missing`, [[CLASS_A, 4]]], 1)),
).resolves.toBeUndefined();
});
it("seeds an empty structure once and never overwrites it", async () => {
const ref = `structure:${RUN}-seed`;
await processLockerEvent(payload, lockerEvent("locker.seed", [ref, [[CLASS_A, 3]]], 1));
let doc = (await payload.findByID({
collection: "game-structures",
id: seedStructureId,
depth: 0,
overrideAccess: true,
})) as unknown as { storedAssets: Record<string, unknown>[] };
expect(doc.storedAssets).toHaveLength(1);
expect(doc.storedAssets[0]).toMatchObject({ asset: assetAId, quantity: 3 });
await processLockerEvent(payload, lockerEvent("locker.seed", [ref, [[CLASS_A, 99]]], 1));
doc = (await payload.findByID({
collection: "game-structures",
id: seedStructureId,
depth: 0,
overrideAccess: true,
})) as unknown as { storedAssets: Record<string, unknown>[] };
expect(doc.storedAssets[0]).toMatchObject({ quantity: 3 });
});
});
describe("locker.request + locker.apply enqueue", () => {

View file

@ -342,3 +342,53 @@ describe("Friday open-slot notice", () => {
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toBeNull();
});
});
/**
* Message copy for the notice, exercised through the bot service that sends it.
* The service validates its env at import, so give it dummies (nothing here
* connects to Discord: the render helpers are pure).
*/
describe("Friday open-slot notice copy", () => {
process.env.DISCORD_TOKEN ||= "notice-copy-test-token";
process.env.DISCORD_GUILD_ID ||= "123456789012345678";
process.env.APP_URL ||= "https://example.test";
const loadService = () => import("@/bot/services/fridayOpsNotice");
it("invites a host, with the role ping, while the slot is open", async () => {
const { renderNotice } = await loadService();
const body = renderNotice("987654321098765432", WEDNESDAY);
expect(body.startsWith("<@&987654321098765432> ")).toBe(true);
expect(body).toContain("is still open");
expect(body).toContain(fridayDateLabel(WEDNESDAY));
expect(body).toContain(`${process.env.APP_URL?.trim()}/intelligence/missions/calendar`);
expect(body).not.toContain("is taken");
});
it("drops the invitation and the role ping once the slot is claimed", async () => {
const { claimedByName, renderClaimedNotice } = await loadService();
const body = renderClaimedNotice("J. Goad", WEDNESDAY);
// The credit line on its own is not enough: the invitation left above it
// ("still open ... if nobody picks it up") reads as the opposite claim.
expect(body).toContain("is taken");
expect(body).not.toContain("still open");
expect(body).not.toContain("schedule one");
expect(body).not.toContain("<@&");
expect(body).toContain(fridayDateLabel(WEDNESDAY));
expect(body).toContain(
"This slot was claimed by J. Goad. Thank you for hosting for our community!",
);
expect(claimedByName(body)).toBe("J. Goad");
});
it("reads an open notice as unclaimed and round-trips a claimed one", async () => {
const { claimedByName, renderClaimedNotice, renderNotice } = await loadService();
expect(claimedByName(renderNotice(null, WEDNESDAY))).toBeNull();
// Comparing rendered bodies is how the service decides to heal a message,
// so the claim parser must accept exactly what the renderer writes.
expect(claimedByName(renderClaimedNotice("Z. LAMPERT", FRIDAY))).toBe("Z. LAMPERT");
});
});