From 743777e7d908d6e25fced0916429412672cdf569 Mon Sep 17 00:00:00 2001 From: Developer Date: Sun, 22 Nov 2026 01:35:58 -0600 Subject: [PATCH 1/2] feat: the server notes who changed a gear line from its item and when, worked out from what was stored on every inventory write (player, GM on a player's sheet, GM on an NPC's), never from what the sheet sends --- CHANGELOG.md | 1 + README.md | 4 +- .../system_builder_unique_lines.test.js | 166 ++++++++++++++++++ backend/routes/sheets.js | 8 +- backend/sockets/index.js | 6 +- backend/systemBuilder/uniqueLines.js | 86 +++++++++ 6 files changed, 268 insertions(+), 3 deletions(-) create mode 100644 backend/__tests__/system_builder_unique_lines.test.js create mode 100644 backend/systemBuilder/uniqueLines.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 7443e2e1..c403effe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -928,6 +928,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Under the hood +- **Who changed a gear line from its item, and when.** When a line named like one of a system's items is given a value of its own in a column (the Cutlass made 2d8), the server now notes who changed it and when: the player from their sheet, or the GM on a player's or an NPC's. It is worked out from what was saved before, never taken from the sheet, kept while the value stays, and dropped when it is put back to the item's. The sheet shows this as UNIQUE next. - **A stress test for the shops.** 200 items and a 1500-line catalogue, saved, sent to players, bought from with a 100-line cart and sold to with 300 lines at once, each within a time limit; and a 1000-line shelf opened, filtered and sorted in a real browser. - **Condition rolls asked of the player, or the GM for an NPC, on the server (8a9a2).** A condition's EACH TURN set to be rolled by the player is now asked of them when it fires (and of the GM for an NPC), said in the dice log, and kept until rolled, even across a reload. Rolled, it does what the table's roll would and the log says who rolled it ("rolled by KES", "rolled by the GM"). Only that player or the GM may roll a player's, and only the GM an NPC's; two clicks roll it once. An ask goes when its condition comes off, when a newer turn asks again, or when the fight ends. Where a token is in two fights, the log names the scene. The ROLL buttons on the sheet and the tracker come with 8a9c. - **Conditions on initiative turns, on the server (8a9a).** A condition can now do up to three things on initiative turns: at the start or end of its turn, or of the round, it rolls DAMAGE, HEAL, a save that takes it off (ROLL TO END), or a roll for the log. Damage and healing change the token's HP on their own unless the GM chooses to apply them by hand, and every roll is a line in the dice log saying whose, what, when, who rolled it and what it did. A condition can also end AT THE END OF ITS NEXT TURN. NEXT fires them in the agreed order (the turn ending, the round ending, the countdown, the round starting, the next turn starting), a new BEGIN starts round 1, and the table can switch them off. The builder's boxes, the tracker's BEGIN button, the GAME tab's switch and asking a player to roll come in the next pieces. diff --git a/README.md b/README.md index 4a4b4f30..dbfdeef8 100644 --- a/README.md +++ b/README.md @@ -433,7 +433,7 @@ CITY_NET/ │ ├── sockets/ │ │ ├── tokenControl.js # Who may move a token, in one place because two move handlers ask it. An admin always may; the owner may; a friendly NPC may name players, or open to everyone. Only friendly NPCs can carry a grant, enforced here rather than by the caller, so one that reaches an enemy row through an import or a restore is inert — and anything unreadable in the column means nobody, since a malformed grant must never open a token up │ │ ├── choices.js # Picking on a custom system's sheet (7a3a): choicesAction ({ kind: pick | drop | level | use }) for the caller's own character, or the player the GM names; systemBuilder/picking.js says what may be done, this stores it through the sheet queue, works the numbers out again and tells every screen; a refusal goes back to the one who asked, in words. recoverySpend ({ pool, count }, R2a) spends recovery dice with a roll (sheets/recover.js), and kind recovery ticks them off; where the system leaves spending to the GM, a player is refused while the GM has it closed. restTake ({ rest }, R3a): a player rests their own character from their sheet where rests are finished on each sheet; the GM anyone's, always. ROLL FOR IT (7a5b2): { kind: 'roll', list, from } rolled on the secure dice, a dice-log line for everyone and the roll thrown in the tray; kits going ONLY IF not met worked out with the rest (7c4b); what an option gives, stored on it (7c4e); itemAction, wearing and attuning an item, the token following (7e3a); an install's limit read on the sheet as it is now (7e4a); spendAction, XP spent and the GM settling it (7f2a2); improveAction, an IMPROVE BY USE mark by hand (7f3a1); countAction (8a4a), a gear line's COUNT spent by its button or filled by RELOAD, answered by ack alone with the lines to ask between or why not (8a4b: said on the line that asked); FIRE and RELOAD worked out as any save is (8a5d1) -│ │ ├── index.js # All Socket.IO event handlers. Every write to a character sheet goes through sheets/mutate.js: rolls, damage, death saves, stabilisation, spell effort and vehicle hulls all touch sheets their owner is very likely looking at, and anything relative is worked out inside the write so two of them landing together both count. Sheet rolls and sheet attacks can come from an NPC's sheet (rollSheetOf): the GM's for any NPC, a player's for a friendly NPC the GM gave them, the log naming the NPC. requestTokenConditions answers a token's conditions with rounds left and modifiers to whoever may change them, and which conditions to anyone else A custom system's stat rolled as IMPROVE BY USE's MARKED BY says is marked (7f3a1).; requestSheetRoll also rolls a line of gear's DAMAGE or DICE (8a3b, { gear: { line, column } }); a band's condition following every sheet write (8a5d1); a battle map floor's start positions, SAVE and LOAD, the GM's alone: a save with no list refused rather than thrown, a player's token made once however many places are saved (8a9c2) +│ │ ├── index.js # All Socket.IO event handlers. Every write to a character sheet goes through sheets/mutate.js: rolls, damage, death saves, stabilisation, spell effort and vehicle hulls all touch sheets their owner is very likely looking at, and anything relative is worked out inside the write so two of them landing together both count. Sheet rolls and sheet attacks can come from an NPC's sheet (rollSheetOf): the GM's for any NPC, a player's for a friendly NPC the GM gave them, the log naming the NPC. requestTokenConditions answers a token's conditions with rounds left and modifiers to whoever may change them, and which conditions to anyone else A custom system's stat rolled as IMPROVE BY USE's MARKED BY says is marked (7f3a1).; requestSheetRoll also rolls a line of gear's DAMAGE or DICE (8a3b, { gear: { line, column } }); a band's condition following every sheet write (8a5d1); a battle map floor's start positions, SAVE and LOAD, the GM's alone: a save with no list refused rather than thrown, a player's token made once however many places are saved (8a9c2); an inventory written by updateSheetField keeps which lines are their item made unique, by whom and when (G5a) │ │ ├── initiativeOrder.js # Where a combatant stands in the initiative order, so a drag stands when later rolls are sorted in: a hidden place only where its roll doesn't already put it (keepDrag, worked out from the roll every time, never from an earlier place, and every place no longer needed let go), a late joiner kept at the bottom (atBottom), Shadowrun's pass taking the place down with the roll (lowered); the roll stays the one shown │ │ ├── sceneQueue.js # One scene's initiative changes one after another (found by 8i2's journey on CI): inTurn(key, work) runs work(done) once the one before has said done; other scenes never wait; work that throws or never says done lets the next go after 5 s │ │ ├── turnAsks.js # A condition's EACH TURN rolled by the player, or the GM for an NPC (8a9a2): requestTurnAsks (every ask for the GM, a player's own for them) and turnRoll, answered by ack @@ -482,6 +482,7 @@ CITY_NET/ │ │ ├── healthLevels.js # MAX HEALTH: PER LEVEL (7d5a): level 1 the full die, each level after what it kept or the average, EACH LEVEL ADDS read now, never less than 1 a level; the token's base; REROLL ALL, KEEP HIGHER, a level's gain kept outright (7d5c); ROLL TO BEAT, a pool or a die per level against the maximum, a gain of 0 kept (7d5d); each level saying how it was kept (rolled, set, cleared), level 1 set by the GM, a level averaging its own die (7d7b1); an uploaded sheet's maximum the base for its levels, and a whole upload's health (7d7c) │ │ ├── items.js # A system's items (7e2a): slots each character has so many of, items whose features need carrying, wearing or wearing in a slot, checked; at the table (7e3a): carried by a readied or stowed gear line of its name, WEAR and TAKE OFF, ATTUNE with a slot free or the GM's anyway, END, the GM's count for one character, what works; GIVE.EXE's list of them, each with what it needs and its words (itemsGivable, 7e3b); INSTALLS (7e4a): each costing against a stat or formula, ADDING TO it up to a limit or TAKING FROM it down to one, an item needing one with a COST; INSTALL with room or the GM's anyway, REMOVE, the line kept in the gear wherever it is, the cost one of its modifiers (overlaid, never written in), each install's cost, value and limit for the sheet; checks the item types and each item's type and values (8a1); encumbrance beside them, and an install's WEIGHS (8a5a); an item's PRICE and IN SHOPS, checked, one IN SHOPS needing a price (8a7a3a) │ │ ├── itemTypes.js # Item types (8a1; approved mockup item-types, 2026-11-14): each type's columns, NUMBER (a unit), TEXT, DAMAGE, DICE, COUNT (a button, a rest that refills it, the items it reloads from) and PICK ONE (its words), checked; GEAR, WEIGHT and PRICE, where a system makes none; an item's values checked against its type's columns; the types as the sheet is shown them; a line of gear's type, values and counts, from the item it is named like or its own; linesOf, the gear read as the sheet stores it, shared with gearRolls, gearCounts and encumbrance; SOLD AT (8a7a2), the kinds of shop a type's lines are sold at, the General Store where unsaid, and the type shelves a kind of building sells (typeShelvesAt); an item's price (its own, else its type's PRICE column) and whether it is IN SHOPS, one saved before the switch by whether it has a price (8a7a3a); a type's band on the sheet, EQUIPPED, USABLE or PACK, PACK where unsaid (bandOf, G1) +│ │ ├── uniqueLines.js # UNIQUE, the server's half (G5a; decided 2026-11-20): a gear line named like an item, of its type, with a column of its own that isn't the item's, is that item made unique; who changed each such column and when (`changed: { damage: { by, gm?, at } }`) worked out on every inventory write from what was stored, never from what the sheet sends; kept as it was, the writer's when changed, gone when put back │ │ ├── encumbrance.js # Encumbrance (8a5a; approved mockup item-types, 2026-11-14, decision 7; shown, never enforced): COUNTED BY a NUMBER column, one of each times how many over the lines READIED or STOWED, an installed item only where its install WEIGHS; CAN CARRY a formula among the others (@capacity), what is carried read as @carried; bands as words at a share of it; the checks; each band and the word past them saying WHAT IT MEANS and naming an optional condition (8a5d1), the band as the sheet is told it; BAND_KEY, and CARRYING given CAN CARRY as the band reads it (8a5e1); the bands, the word past them and the condition's name given to the sheet for CARRYING on GEAR (8a6a) │ │ ├── wornSums.js # What is worn, summed by column (8a5b; approved mockup item-types, 2026-11-14, decision 6): each NUMBER column of a system's own types read as @type_column, the worn items of that type together (@armor_defense), each worn item once as its line has it; no name a stat's, formula's or level's │ │ ├── itemsImport.js # A system's items from a file (8aL3a; approved mockup items-layout, 2026-11-14): a section per type by its id or name, each column by its name or id, needs, cost where the system has an install, words, and [features]; read against the draft, matched by name, never deleting; one there under another type made it, keeping the values both have; each mistake skipped by its line, the rest going in; nothing saved. In a game with types of its own, PRICE (an item's own, where its type has no column holding it) and IN SHOPS, yes or no (8a7a3b2) @@ -632,6 +633,7 @@ CITY_NET/ │ ├── system_builder_items_worn.test.js # Items at the table (7e3a): carried, WEAR and TAKE OFF, ATTUNE and END, the GM's anyway and own count, taken off still attuned, a working item's bonuses (named by it), has() and uses, what the sheet is told; over the socket, the token following; the render copy's items and slots, and a pick's features read as before (7e3b); GIVE.EXE listing them for the GM only, giving one as a stowed line that is then worn, more joining it, the notice, one not had refused │ ├── system_builder_items_installed.test.js # Installed items (7e4a): the checks, INSTALL and REMOVE within and past the limit (ADDS TO and TAKES FROM), the GM's anyway, the cost on its stat and a formula named by the item, has(), the line gone or kept stashed, what the sheet is told, the system file, no shop buying one, over the socket │ ├── system_builder_item_types.test.js # Item types (8a1): the list, each type and column checked, each kind's own parts, each item's type and values, what the sheet is shown, a line of gear's columns from its item or its own, the system file and back unchanged +│ ├── system_builder_unique_lines.test.js # UNIQUE on the server (G5a): which columns are unique (read loosely, none for a thing made by hand or of another type), the writer's when changed, kept as it was, gone put back, never what the sheet sends, the line found where lines moved, as stored; kept by the player's socket, the GM on a player's sheet and on an NPC's; a built-in system's written as sent │ ├── system_builder_ranks.test.js # Ranks with names (7f1a): the lists and the stats held as them checked, a ranked stat's worth at its step (the ends holding, a formula reading it, one read after it, a loop said), a bonus moving the step, the system file, a sheet saved working it out; the rank picker on the sheet a browser draws, an NPC's, and the import by name or step (7f1c1) │ ├── system_builder_ranks_start.test.js # Ranks making a character and levelling up (7f1c2): a ranked stat asked with its ranks and AT START, never locked as a number placed; a player's rank past AT START refused over the socket, one field or a batch, the GM's kept; an INCREASE raising a rank to its top and never stopped by a number's cap │ ├── system_builder_spend_xp.test.js # SPEND XP's price list (7f2a1): every check, the list told to the sheet by name and with the template, a stat's price from @old and @new to UP TO, a rank's to its top, an option's on the sheet as it reads, never one held or not met; the system file carrying it, a new version naming it; XP given, uploaded and on the form where it is spent diff --git a/backend/__tests__/system_builder_unique_lines.test.js b/backend/__tests__/system_builder_unique_lines.test.js new file mode 100644 index 00000000..20dfc29a --- /dev/null +++ b/backend/__tests__/system_builder_unique_lines.test.js @@ -0,0 +1,166 @@ +/** + * UNIQUE, the server's half (G5a; decided 2026-11-20, the user: "mark it as Unique so the GM can see changes at a glance"). + * A gear line named like one of the system's items, a column of its own that isn't the item's: the item made unique. Who + * changed each such column and when is kept on the line, worked out from what was stored on every inventory write: by the + * player's own socket, by the GM on a player's sheet, by the GM on an NPC's. Never taken from what the sheet sends. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import jwt from 'jsonwebtoken'; +import { createRequire } from 'module'; +import { makeTestDb, get, run } from './helpers/testDb.js'; +import { drain, until } from './helpers/until.js'; + +process.env.JWT_SECRET = 'test-secret'; +const require_ = createRequire(import.meta.url); +const { withChanges, uniqueColumns } = require_('../systemBuilder/uniqueLines'); +const runtime = require_('../systemBuilder/runtime'); +const socketsFactory = require_('../sockets/index.js'); + +const GM = jwt.sign({ id: 1, username: 'gm', role: 'admin', isTemporary: false }, 'test-secret'); +const gm = { Authorization: `Bearer ${GM}` }; + +const BLADES = { + format: 1, name: 'Bladeworks', core: { health: { model: 'pool' } }, + stats: [{ id: 'abilities', label: 'ABILITIES', stats: [{ id: 'might', label: 'Might' }] }], + items: { + types: [ + { id: 'weapons', label: 'WEAPONS', one: 'Weapon', columns: [{ id: 'damage', label: 'DAMAGE', kind: 'damage' }, { id: 'range', label: 'RANGE', kind: 'text' }, { id: 'weight', label: 'WEIGHT', kind: 'number' }] }, + { id: 'gear', label: 'GEAR', one: 'Gear', columns: [{ id: 'weight', label: 'WEIGHT', kind: 'number' }] }, + ], + list: [{ id: 'cutlass', label: 'Cutlass', type: 'weapons', values: { damage: '1d8 + @might', range: 'melee', weight: 3 } }], + }, +}; +const line = (name, more = {}) => ({ name, qty: 1, enc: '', bundled: false, carry: 'stowed', location: '', ...more }); +const AT = '2026-11-22T10:00:00.000Z'; +const LATER = '2026-11-23T09:30:00.000Z'; + +describe('which columns are unique', () => { + it('a value of its own that isn\'t its item\'s; read loosely; none for a line of no item, or of another type', () => { + expect(uniqueColumns(BLADES, line('Cutlass', { values: { damage: '2d8 + @might', weight: 3 } }))).toEqual(['damage']); + // 3 and "3", and spaces around, are the item's own. + expect(uniqueColumns(BLADES, line(' cutlass ', { values: { weight: '3', range: ' melee ' } }))).toEqual([]); + // A column the item hasn't filled, filled by the line: unique. + expect(uniqueColumns({ ...BLADES, items: { ...BLADES.items, list: [{ id: 'cutlass', label: 'Cutlass', type: 'weapons', values: {} }] } }, line('Cutlass', { values: { range: '2 m' } }))).toEqual(['range']); + // Blank is nothing of its own. + expect(uniqueColumns(BLADES, line('Cutlass', { values: { damage: ' ' } }))).toEqual([]); + // A stick made by hand is no item; a Cutlass made GEAR by hand is a thing of its own, not the item. + expect(uniqueColumns(BLADES, line('A stick', { type: 'weapons', values: { damage: '1d4' } }))).toEqual([]); + expect(uniqueColumns(BLADES, line('Cutlass', { type: 'gear', values: { weight: 9 } }))).toEqual([]); + expect(uniqueColumns(BLADES, line('Cutlass', { type: 'weapons', values: { weight: 9 } }))).toEqual(['weight']); + }); +}); + +describe('who changed it, and when', () => { + const kes = { by: 'kes' }; + + it('a column changed: the writer\'s, when; left as it was: kept; put back to the item\'s or cleared: gone', () => { + const first = withChanges(BLADES, '[]', [line('Cutlass', { values: { damage: '2d8 + @might' } })], kes, AT); + expect(first[0].changed).toEqual({ damage: { by: 'kes', at: AT } }); + // The GM changes RANGE later; DAMAGE as it was keeps Kes's. + const second = withChanges(BLADES, first, [line('Cutlass', { values: { damage: '2d8 + @might', range: '2 m' } })], { by: 'gm', gm: true }, LATER); + expect(second[0].changed).toEqual({ damage: { by: 'kes', at: AT }, range: { by: 'gm', gm: true, at: LATER } }); + // DAMAGE changed again: the writer's, now. + const third = withChanges(BLADES, second, [line('Cutlass', { values: { damage: '3d8', range: '2 m' } })], kes, LATER); + expect(third[0].changed.damage).toEqual({ by: 'kes', at: LATER }); + // THE ITEM'S: DAMAGE back to the item's, RANGE cleared: nothing changed, no `changed` at all. + const back = withChanges(BLADES, third, [line('Cutlass', { values: { damage: '1d8 + @might' } })], kes, LATER); + expect(back[0]).toEqual(line('Cutlass', { values: { damage: '1d8 + @might' } })); + }); + + it('never what the sheet sends: a record made up is dropped, one left off is kept', () => { + const stored = [line('Cutlass', { values: { damage: '2d8' }, changed: { damage: { by: 'kes', at: AT } } })]; + const forged = withChanges(BLADES, stored, [line('Cutlass', { values: { damage: '2d8', range: '2 m' }, changed: { damage: { by: 'someone', at: 'x' } } })], { by: 'mo' }, LATER); + expect(forged[0].changed).toEqual({ damage: { by: 'kes', at: AT }, range: { by: 'mo', at: LATER } }); + // A line of no item says nothing changed, whatever it is sent with. + expect(withChanges(BLADES, '[]', [line('Rope', { changed: { weight: { by: 'x', at: 'y' } } })], kes, AT)[0]).toEqual(line('Rope')); + }); + + it('the line it was: in its place, or found by name and type where lines moved; a new one is the writer\'s', () => { + const stored = [line('Rope'), line('Cutlass', { values: { damage: '2d8' }, changed: { damage: { by: 'kes', at: AT } } })]; + // The Rope removed: the Cutlass moved up a place, still the same, keeping Kes's. + expect(withChanges(BLADES, stored, [line('Cutlass', { values: { damage: '2d8' } })], { by: 'mo' }, LATER)[0].changed).toEqual({ damage: { by: 'kes', at: AT } }); + // A second Cutlass made 2d8 too: the first keeps its record, the new one is the writer's. + const two = withChanges(BLADES, stored, [line('Rope'), line('Cutlass', { values: { damage: '2d8' } }), line('Cutlass', { values: { damage: '2d8' } })], { by: 'mo' }, LATER); + expect(two.map((l) => l.changed)).toEqual([undefined, { damage: { by: 'kes', at: AT } }, { damage: { by: 'mo', at: LATER } }]); + }); + + it('as stored: a JSON string back as one; as given with no definition or lines that can\'t be read', () => { + const out = withChanges(BLADES, '[]', JSON.stringify([line('Cutlass', { values: { damage: '2d8' } })]), kes, AT); + expect(JSON.parse(out)[0].changed).toEqual({ damage: { by: 'kes', at: AT } }); + expect(withChanges(null, '[]', '[{"name":"Cutlass"}]', kes, AT)).toBe('[{"name":"Cutlass"}]'); + expect(withChanges(BLADES, '[]', 'not json', kes, AT)).toBe('not json'); + // What was stored unreadable: every unique column is the writer's. + expect(withChanges(BLADES, '{bad', [line('Cutlass', { values: { damage: '2d8' } })], kes, AT)[0].changed).toEqual({ damage: { by: 'kes', at: AT } }); + }); +}); + +describe('kept by every write of the inventory', () => { + let db; + let app; + let id; + + beforeEach(async () => { + db = await makeTestDb(); + await run(db, "INSERT INTO global_settings (key, value) VALUES ('game_system', 'cities_without_number')"); + const io = { emit: () => {}, to: () => ({ emit: () => {} }) }; + app = express(); + app.use(express.json({ limit: '2mb' })); + app.use('/api/systems', require_('../routes/systems.js')(db)); + app.use('/api/sheets', require_('../routes/sheets.js')(db, io)); + id = (await request(app).post('/api/systems').set(gm).send({ definition: BLADES })).body.id; + await new Promise((resolve) => runtime.load(db, resolve)); + await request(app).post(`/api/systems/${id}/publish`).set(gm); + await request(app).put('/api/sheets/system').set(gm).send({ system: id }); + await run(db, 'INSERT INTO character_sheets (username, system, data, is_npc) VALUES (?, ?, ?, 0)', ['kes', id, JSON.stringify({ name: 'Kes', might: 2 })]); + vi.spyOn(console, 'log').mockImplementation(() => {}); + }); + afterEach(() => vi.restoreAllMocks()); + + const connectAs = async (userName, { admin = false } = {}) => { + let connect; + socketsFactory({ on: (e, cb) => { if (e === 'connection') connect = cb; }, emit: () => {}, to: () => ({ emit: () => {} }) }, + db, { elevatedUsers: new Set(), emitUpdate: vi.fn(), recordAction: vi.fn() }); + const handlers = {}; + connect({ id: `ul-${Math.random()}`, on: (e, fn) => { handlers[e] = fn; }, emit: () => {}, broadcast: { emit: () => {} }, use: () => {}, join: () => {}, disconnect: () => {} }); + handlers.identify(admin ? { userName, isAdmin: true, token: GM } : userName); + await drain(db); + return handlers; + }; + const linesOf = async (where = "username = 'kes'") => JSON.parse(JSON.parse((await get(db, `SELECT data FROM character_sheets WHERE ${where}`)).data).inventory || '[]'); + + it('the player\'s own: theirs; the GM on their sheet then: the GM\'s, the player\'s kept', async () => { + const kes = await connectAs('kes'); + kes.updateSheetField({ fieldId: 'inventory', value: JSON.stringify([line('Cutlass', { values: { damage: '2d8 + @might' } })]) }); + await until(async () => (await linesOf())[0]?.changed?.damage?.by === 'kes', { label: 'Kes\'s' }); + const [mine] = await linesOf(); + expect(mine.changed.damage.gm).toBeUndefined(); + expect(Date.parse(mine.changed.damage.at)).not.toBeNaN(); + // The GM, on Kes's sheet, gives it a RANGE; the sheet sends no `changed`, as it never does. + const res = await request(app).put('/api/sheets/user/kes').set(gm) + .send({ fields: { inventory: JSON.stringify([line('Cutlass', { values: { damage: '2d8 + @might', range: '2 m' } })]) } }); + expect(res.status).toBe(200); + const [after] = await linesOf(); + expect(after.changed).toEqual({ damage: mine.changed.damage, range: { by: 'gm', gm: true, at: expect.any(String) } }); + }); + + it('a built-in system\'s inventory is written as sent', async () => { + await request(app).put('/api/sheets/system').set(gm).send({ system: 'generic' }); + await run(db, 'INSERT INTO character_sheets (username, system, data, is_npc) VALUES (?, ?, ?, 0)', ['mo', 'generic', JSON.stringify({ name: 'Mo' })]); + const mo = await connectAs('mo'); + const sent = JSON.stringify([line('Cutlass', { values: { damage: '2d8' }, changed: { damage: { by: 'x', at: 'y' } } })]); + mo.updateSheetField({ fieldId: 'inventory', value: sent }); + await until(async () => JSON.parse((await get(db, "SELECT data FROM character_sheets WHERE username = 'mo'")).data).inventory === sent, { label: 'as sent' }); + }); + + it('an NPC\'s: the GM\'s', async () => { + const made = await request(app).post('/api/sheets/npcs').set(gm).send({ data: { name: 'Bosun' }, npc_label: 'Bosun' }); + expect(made.status).toBeLessThan(300); + const npc = (await get(db, 'SELECT id FROM character_sheets WHERE is_npc = 1')).id; + const res = await request(app).put(`/api/sheets/npcs/${npc}`).set(gm).send({ fields: { inventory: JSON.stringify([line('Cutlass', { values: { weight: 5 } })]) } }); + expect(res.status).toBe(200); + expect((await linesOf(`id = ${npc}`))[0].changed).toEqual({ weight: { by: 'gm', gm: true, at: expect.any(String) } }); + }); +}); diff --git a/backend/routes/sheets.js b/backend/routes/sheets.js index 158541d4..7d94fbe5 100644 --- a/backend/routes/sheets.js +++ b/backend/routes/sheets.js @@ -32,6 +32,7 @@ const { jsonTemplate, withImportedPicks } = require('../systemBuilder/sheetImpor const { HEALTH_BASE_KEY } = require('../systemBuilder/levels'); const { withUploadedHealth } = require('../systemBuilder/healthLevels'); const { inventoryAdded } = require('../sheets/inventoryImport'); +const { withChanges } = require('../systemBuilder/uniqueLines'); // Admin-facing character sheet routes. Player self-service (open/edit own // sheet, quick-sheet lookups) goes through socket events, matching how the @@ -213,6 +214,8 @@ module.exports = (db, io) => { const next = { ...current, ...patch }; Object.keys(patch).forEach((f) => applyDerived(system, next, f)); const definition = customSystems.definitionOf(system); + // The GM changing a line from its item (G5a): noted as theirs. + if (!upload && patch.inventory !== undefined) next.inventory = withChanges(definition, current.inventory, patch.inventory, { by: req.user.username, gm: true }); if (!definition || !upload) return next; // As a player's upload is (sockets/index.js): their picks whole, and adding to the inventory. if (current.inventory !== undefined) next.inventory = inventoryAdded(current.inventory, patch.inventory); @@ -523,7 +526,10 @@ module.exports = (db, io) => { let data = row.data; let mergedData = null; if (cleanFields) { - const merged = { ...JSON.parse(row.data || '{}'), ...cleanFields }; + const stored = JSON.parse(row.data || '{}'); + const merged = { ...stored, ...cleanFields }; + // An NPC's line changed from its item (G5a): the GM's. + if (cleanFields.inventory !== undefined) merged.inventory = withChanges(customSystems.definitionOf(row.system), stored.inventory, cleanFields.inventory, { by: req.user.username, gm: true }); Object.keys(cleanFields).forEach((f) => applyDerived(row.system, merged, f)); data = JSON.stringify(merged); mergedData = merged; diff --git a/backend/sockets/index.js b/backend/sockets/index.js index 36b379d0..4e515d4e 100644 --- a/backend/sockets/index.js +++ b/backend/sockets/index.js @@ -15,6 +15,7 @@ const cyberware = require('../sheets/cyberware'); const { ownToken } = require('../sheets/ownToken'); const sheetRolls = require('../sheets/rolls'); const { rollGear, readGearDice } = require('../systemBuilder/gearRolls'); +const { withChanges } = require('../systemBuilder/uniqueLines'); const rollEngine = require('../sheets/rollEngine'); const sheetAttack = require('../sheets/attack'); const cyberEffects = require('../sheets/cyberwareEffects'); @@ -1419,7 +1420,10 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { if (!isAdminSocket(socket) && (lockedWhileCreating(customSystems.definitionOf(system), data).has(payload.fieldId) || lockedByLevels(customSystems.definitionOf(system), data).has(payload.fieldId))) return undefined; // A rank past where a new character may start (7f1c2): the GM's to give. if (!isAdminSocket(socket) && pastStart(customSystems.definitionOf(system), data, payload.fieldId, payload.value)) return undefined; - data[payload.fieldId] = payload.value; + // The inventory: which lines are their item made unique, and by whom and when (G5a), from what was stored. + data[payload.fieldId] = payload.fieldId === 'inventory' + ? withChanges(customSystems.definitionOf(system), data.inventory, payload.value, { by: info.userName, gm: isAdminSocket(socket) }) + : payload.value; // If the changed field is a max, clamp the paired current field. const curField = sheetTemplates.getMaxPairs(system)[payload.fieldId]; if (curField && data[curField] !== undefined) { diff --git a/backend/systemBuilder/uniqueLines.js b/backend/systemBuilder/uniqueLines.js new file mode 100644 index 00000000..4b335e97 --- /dev/null +++ b/backend/systemBuilder/uniqueLines.js @@ -0,0 +1,86 @@ +// UNIQUE (G5a; decided 2026-11-20, the user: "mark it as Unique so the GM can see changes at a glance"; approved mockup +// docs/mockups/sheet-gear-layout.html, "changing one line"). A gear line named like one of the system's items, of that +// item's type, takes the item's values; a column it fills with a value of its own that isn't the item's makes it that item +// made unique (the Cutlass made 2d8 to level with the player). +// +// The server keeps who changed each such column and when, on the line: `changed: { damage: { by: 'kes', at: ISO } }`, with +// `gm: true` where it was the GM. Worked out on every write of the inventory from what was stored before, never from what +// the sheet sends: a column the write left as it was keeps its record, one changed gets the writer's, one put back to the +// item's (THE ITEM'S, or cleared) loses it. A line made unique by no one (bought from a catalogue with values of its own) +// is still unique, with no one named. +// +// Pure; the sheet writes call it (sockets updateSheetField, the GM's PUT /api/sheets/user/:username and /npcs/:id). + +const { typesOf, typeNamed } = require('./itemTypes'); + +const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v); +const list = (v) => (Array.isArray(v) ? v : []); +const key = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : ''); +/** A value as given, read loosely: 2 and "2" are one, spaces around don't count. */ +const same = (a, b) => a !== undefined && b !== undefined && String(a).trim() === String(b).trim(); +const filled = (v) => v !== undefined && v !== null && String(v).trim() !== ''; + +/** Gear lines as stored (a JSON string or a list), or null where they can't be read. */ +const parse = (v) => { + if (typeof v === 'string') { try { const rows = JSON.parse(v); return Array.isArray(rows) ? rows : null; } catch { return null; } } + return Array.isArray(v) ? v : null; +}; + +/** The system's item a line is, with the line's type, where the line is named like it and of its type; else null. */ +const itemOf = (definition, line) => { + const name = key(line && line.name); + if (!name || !isPlainObject(definition) || !isPlainObject(definition.items)) return null; + const item = list(definition.items.list).find((i) => isPlainObject(i) && key(i.label) === name); + if (!item) return null; + const itemType = typeNamed(definition, item.type); + const type = typesOf(definition).find((t) => t.id === line.type) || itemType; + return type.id === itemType.id ? { item, type } : null; +}; + +/** The columns a line fills with a value of its own that isn't its item's, by id, in the type's order. */ +const uniqueColumns = (definition, line) => { + const of = isPlainObject(line) ? itemOf(definition, line) : null; + if (!of) return []; + const own = isPlainObject(line.values) ? line.values : {}; + const given = isPlainObject(of.item.values) ? of.item.values : {}; + return of.type.columns.filter((c) => filled(own[c.id]) && !same(own[c.id], given[c.id])).map((c) => c.id); +}; + +/** + * The lines `after` as they are to be stored, each with `changed` worked out against `before` (what was stored): `who` is + * { by: username, gm }. In the form given (a JSON string stays one); as given where the system has no definition or the + * lines can't be read. + */ +const withChanges = (definition, before, after, who, at = new Date().toISOString()) => { + if (!isPlainObject(definition)) return after; + const next = parse(after); + if (!next) return after; + const prev = parse(before) || []; + const stamp = { by: who && typeof who.by === 'string' ? who.by : '', ...(who && who.gm ? { gm: true } : {}), at }; + // The line each was before: the one in its place where it has the same name, else the first unclaimed of its name. Its + // type needn't match: a line made another type than its item's is no longer the item, so has no unique columns anyway. + const claimed = new Set(); + const fits = (p, line) => isPlainObject(p) && key(p.name) === key(line.name); + const wasOf = (line, i) => { + const j = !claimed.has(i) && fits(prev[i], line) ? i : prev.findIndex((p, n) => !claimed.has(n) && fits(p, line)); + if (j < 0) return null; + claimed.add(j); + return prev[j]; + }; + const out = next.map((line, i) => { + if (!isPlainObject(line)) return line; + // What the sheet says was changed is never taken: worked out here alone. + const { changed: _sent, ...rest } = line; + const was = wasOf(rest, i); + const kept = was && isPlainObject(was.changed) ? was.changed : {}; + const wasOwn = was && isPlainObject(was.values) ? was.values : {}; + const changed = {}; + for (const id of uniqueColumns(definition, rest)) { + if (was && same(rest.values[id], wasOwn[id])) { if (isPlainObject(kept[id])) changed[id] = kept[id]; } else changed[id] = stamp; + } + return Object.keys(changed).length ? { ...rest, changed } : rest; + }); + return typeof after === 'string' ? JSON.stringify(out) : out; +}; + +module.exports = { withChanges, uniqueColumns, itemOf }; From b69d97c66e0d1111d7d5700918e270dc9b56ff1c Mon Sep 17 00:00:00 2001 From: Developer Date: Sun, 22 Nov 2026 02:02:03 -0600 Subject: [PATCH 2/2] test: sheet-item-types expects the Pistol's saved line to say who made its RANGE its own, and when (G5a) --- e2e/README.md | 2 +- e2e/tests/sheet-item-types.spec.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/e2e/README.md b/e2e/README.md index dde9f103..e107ca25 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -205,7 +205,7 @@ kept; the job itself stops at 30 (`timeout-minutes`), for a hang outside the tes | `tests/sheet-ranks.spec.ts` | A rank on the sheet (7f1c1): a player with Level 3 sees Athletics as a picker of UNTRAINED, TRAINED and EXPERT, picks EXPERT, its worth = 7 shows beside it, the formula Climb reading it shows 8, and the server keeps the step 2 with Athletics 7 and Climb 8 | | `tests/sheet-ranks-start.spec.ts` | Ranks making a character (7f1c2): a player in NEW CHARACTER types Grit, finds Lore under RANKS with UP TO TRAINED TO START and EXPERT off, picks TRAINED, and the server keeps the step 1 with Lore worth 2 | | `tests/sheet-worn-items.spec.ts` | Items at the table (7e3b): two GEAR lines named like items get WEAR and ATTUNE; the ring worn does nothing yet, attuned it is WORKING, ATTUNED 1 OF 1, CON 14 → 16; the cloak worn with no slot free says so and can't attune; the GM, on the player's sheet, ATTUNES it ANYWAY (2 OF 1) and gives them 2 of their own; END frees the ring's slot and its +2 goes; the cloak taken off stays attuned and does nothing. A second test: the GM's GIVE.EXE lists the ring under ITEMS with NEEDS ATTUNED and its words, gives it to the player as a stowed gear line, the player is told and WEARS it; TERMINATE_SESSION closes GIVE.EXE while the session is still ending; and (2026-11-22) no ATTUNED bar on GEAR until the Ring's line is there | -| `tests/sheet-item-types.spec.ts` | The GEAR tab as a table per item type (8a3a): a player's sheet with WEAPONS and GEAR tables, each empty with its +; + WEAPON made A stick with DAMAGE 1d4 and GRADE HEAVY; a second line named Pistol showing 2d6 + @might faint, its RANGE typed over to 50 m; + GEAR made Rope at 10 lb; saved as made, each in its table after a reload; since 8a3b the stick's DAMAGE rolled with ROLL, "rolled A stick DAMAGE 1d4" in the dice tray's history; and (8a3c1) as compact lines: a line made by hand opened under ✎, DONE showing its words with ROLL, the Pistol's RANGE read as words after the reload, and no box on the GEAR tab scrolling sideways in SHEET.EXE; and (8a3c2) the Pistol's DAMAGE under ✎ said ON THIS CHARACTER: 2d6 + Might (12): 14 to 24, @strength flagged as not the system's, eˣ INSERT putting in @might; and (G2) in bands: PACK says "Nothing here." with no WEAPONS group before anything is carried, and things are added from the row of + at the top; and (G3) the Pistol's card opened by a click on its name | +| `tests/sheet-item-types.spec.ts` | The GEAR tab as a table per item type (8a3a): a player's sheet with WEAPONS and GEAR tables, each empty with its +; + WEAPON made A stick with DAMAGE 1d4 and GRADE HEAVY; a second line named Pistol showing 2d6 + @might faint, its RANGE typed over to 50 m; + GEAR made Rope at 10 lb; saved as made, each in its table after a reload; since 8a3b the stick's DAMAGE rolled with ROLL, "rolled A stick DAMAGE 1d4" in the dice tray's history; and (8a3c1) as compact lines: a line made by hand opened under ✎, DONE showing its words with ROLL, the Pistol's RANGE read as words after the reload, and no box on the GEAR tab scrolling sideways in SHEET.EXE; and (8a3c2) the Pistol's DAMAGE under ✎ said ON THIS CHARACTER: 2d6 + Might (12): 14 to 24, @strength flagged as not the system's, eˣ INSERT putting in @might; and (G2) in bands: PACK says "Nothing here." with no WEAPONS group before anything is carried, and things are added from the row of + at the top; and (G3) the Pistol's card opened by a click on its name; and (G5a) the Pistol, its RANGE its own, saved with who changed it and when | | `tests/sheet-gear-bands.spec.ts` | The GEAR tab in bands (G2): a game with WEAPONS EQUIPPED, POTIONS USABLE and GEAR unsaid; a player adds a Sword, a Draught and a Rope from the row of + at the top, each in its band and counted (EQUIPPED · 1, USABLE · 1, PACK · 1, STASH · 0 closed), saved as made; the Sword moved to the stash goes to STASH, which opens and says WEAPONS, EQUIPPED left at 0; USABLE closed by its head, and on the next visit USABLE is still closed and PACK open; and (G3) one line a thing: the Draught's HEALS blank, so FILL IN, which opens its card at that box, ready to type; 2d4 typed, DONE, the line says HEALS 2d4 and FILL IN is gone, saved; a Cloak, GEAR, made by hand sits in PACK, WEAR puts it in EQUIPPED (EQUIPPED · 1), taken off it is back in PACK; with EQUIPPED closed, WEAR lights its head (▸ EQUIPPED · 1), opened it is plain again; and (G4) FIND: 2d4 shows the Draught in USABLE, closed, opened while it shows (PACK · 0), lantern says nothing matches, cleared USABLE is closed again | | `tests/sheet-gear-counts.spec.ts` | A gear line's COUNT at the table (8a4): a player's Pistol at AMMO 2 / 6 spends one with FIRE; RELOAD, with Pistol Rounds and AP Rounds both carried, asks which and takes all 3 AP Rounds, their line gone; RELOAD again takes 2 of the Pistol Rounds alone, full, RELOAD held; the Wand's CHARGES, with no RELOAD, filled by a SHORT REST from the sheet | | `tests/sheet-standalone-tab.spec.ts` | The sheet in a new tab is the window (8s1a): a player makes two gear lines in SHEET.EXE, opens the tab with ⧉ (a `.crt-container`, so in the theme), WEARs the boots there and SHEET.EXE says WORKING too, and rolls the club's DAMAGE from the tab, said on it once the dice land; since 8s1b the roll from the tab opens DICE_TRAY.EXE in the main app's window; and (8s1c) a character being made: the flow left, SHEET.EXE says CREATING · CONTINUE, the tab says it too and opens NEW_CHARACTER.EXE on itself; and (8s1d) Cash on the tab opens BANK.EXE in the main window and the tab says so, then with the main window closed the tab says to open it; and (G2) gear added from the row of + at the top of GEAR | diff --git a/e2e/tests/sheet-item-types.spec.ts b/e2e/tests/sheet-item-types.spec.ts index bab20d40..5b075767 100644 --- a/e2e/tests/sheet-item-types.spec.ts +++ b/e2e/tests/sheet-item-types.spec.ts @@ -75,7 +75,8 @@ test('GEAR as a table per type: a stick made by hand and its DAMAGE rolled, the const line = (name: string, more: object) => ({ name, qty: 1, enc: '', bundled: false, carry: 'stowed', location: '', ...more }); await expect.poll(async () => JSON.parse(String((await sheetOf()).inventory ?? '[]')), { timeout: 15_000 }).toEqual([ line('A stick', { type: 'weapons', values: { damage: '1d4', grade: 'HEAVY' } }), - line('Pistol', { type: 'weapons', values: { range: '50 m' } }), + // Its RANGE its own, not the item's 30 m: the Pistol made unique, the server noting who and when (G5a). + line('Pistol', { type: 'weapons', values: { range: '50 m' }, changed: { range: { by: player.username, at: expect.any(String) } } }), line('Rope', { type: 'gear', values: { weight: 10 } }), ]);