diff --git a/CHANGELOG.md b/CHANGELOG.md index fd01ce0a..2f53013c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -105,6 +105,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added +- **Catalogue lines can become items.** In SHOP_CATALOGUES, PREVIEW now offers ADD NEW LINES TO ITEMS, off to start. Switched on, it lists what it will add and how many items your system will hold. SAVE then makes each line that isn't one of your items yet into an item: of its section's type (a shelf's lines go to your DEFAULT type), with its columns, price and words, in the shops. They go into the builder's draft and are kept once you publish; until then the catalogue line sells them. If the builder is open, it takes them in, so its next save keeps them. - **One-of-a-kind items sell back.** An item kept out of the shops is never on a shelf, but a player can still sell one to a shop that sells its type, at the item's own price times that shop's buyback rate. A ring sells at an Armorer, never at a Gun Shop. - **The shop catalogue knows your items.** In a game whose items sell themselves, PREVIEW in SHOP_CATALOGUES now says how many of your items are also on sale, and which lines in your file overrule one ("Pistol: overrules the item, 200 → 260 in the shops"). A line that's exactly one of your items, same price and columns, is left out, since the item already sells itself. So is a line naming an item kept out of the shops. The preview says why for each line, and SAVE leaves out the same lines. - **PRICE and IN SHOPS in the ITEMS page's files.** In a game with item types of its own, DOWNLOAD EXAMPLE and DOWNLOAD THIS LIST have a price column (for a type without a PRICE column of its own) and an in shops column, yes or no. IMPORT reads them: write - to clear one, and a price or a yes/no that isn't one is skipped and named by its line. A list downloaded and imported back changes nothing. diff --git a/README.md b/README.md index d6b03681..9f577775 100644 --- a/README.md +++ b/README.md @@ -485,6 +485,7 @@ CITY_NET/ │ │ ├── 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) +│ │ ├── itemsFromCatalogue.js # A shop catalogue's new lines made items of the system (8a7a4a, ADD NEW LINES TO ITEMS): each line not an item already, of its section's type (a shelf's of the DEFAULT type), its columns, price, IN SHOPS and words; past 200 items or a name too long, said. Pure │ │ ├── gearRolls.js # A line of gear's DAMAGE or DICE rolled (8a3b; approved mockup item-types, 2026-11-14): the line's own dice, else its item's, read against the sheet as rolls read it, rolled with the server's dice, in the log's words ("Wren rolled Longsword DAMAGE 1d8 + @might_mod [5 + 2 = 7]"); readGearDice (8a3c2), a line's dice as typed read as ROLL would on this character without rolling: the least and most, each name with its value, or what is wrong, and the system's names │ │ ├── gearCounts.js # A gear line's COUNT (8a4a; approved mockup item-types, 2026-11-14, decision 5): one spent by the button its column names (FIRE, USE), RELOAD from a carried line of an item the column names taking from its quantity (asked which when several are carried, the line gone when used up), and a rest's refills; the gear written back as the sheet had it │ │ ├── ranks.js # A system's ranks (7f1a): shared lists of named ranks, lowest first, each worth a number or a formula; a stat held as one keeps its step in _rank and is its step's worth (derived.js, kind rank); the checks (a list there is, the highest at the start, no range of its own, its step field free), what a sheet's formulas compile with, a rank's name at a step; a sheet with each ranked stat as its rank picker, a select on its step naming the stat whose worth shows (withRankFields, 7f1c1) @@ -605,6 +606,7 @@ CITY_NET/ │ ├── shop_sell.test.js # Selling a basket: a payout the client cannot talk up, the item really leaving the sheet, and nothing emptied when a basket fails part way │ ├── shop_buy_sockets.test.js # Buying through the socket as a cart of one, the old buy handler's cases moved across whole │ ├── shop_sell_sockets.test.js # Selling through the socket as a cart with nothing to buy, the old sell handler's cases moved across whole +│ ├── catalogue_into_items.test.js # ADD NEW LINES TO ITEMS (8a7a4a): new lines made items of their type, a shelf's of the DEFAULT, one already an item or named twice once, ids apart, too long or past 200 said; the preview says what it adds, the save writes the draft only │ ├── shop_items_on_sale.test.js # The game's own items on the shelves (8a7a3a): a price, its own or its type's PRICE column's; IN SHOPS, one saved before it by its price; checked and carried by the system file; the lines they make; under the uploads in the store (a line of an item's name wins, one turned off never sold); bought, sold back at the BUYBACK rate, not again in GIVE's type folders; a catalogue file held against them, its preview and its save (8a7a3c1) │ ├── shop_stress.test.js # The shops under load (8n3): 200 items and a 1500-line catalogue previewed and saved, every catalogue sent to a player (its size said), a 100-line cart checked out and 300 lines sold back at once, each in time and each answer right │ ├── shop_typed_lines.test.js # Lines of an item type sold and given (8a7a2): SOLD AT, the General Store unsaid, checked and carried by the system file; a typed line placed and stacked only onto the same thing untouched; bought at a shop that sells the type and refused at one that doesn't, sold back at exactly the app's 45%, given from GIVE @@ -891,7 +893,7 @@ CITY_NET/ │ │ │ ├── BuildingPreview.tsx # The corner picture: the GM's photo, else the building's own parts turning as a wireframe in its own small canvas, else the CITY_NET badge. The color is read from the theme's CSS variable where it sits - the info windows render outside the ThemeContext provider, so the context alone drew every theme in classic green │ │ │ ├── BuildingExtrasEditor.tsx # The photo and GM notes in the admin edit view. Nothing saves on its own: UPDATE_DATA_POINT commits them after the building saves, and a 200 with nothing in it - an old server not yet restarted - is reported rather than called saved │ │ │ ├── CityNetIcon.tsx # The CITY_NET badge from assets/citynet-logo.svg in the theme's colors, for anywhere that needs a picture and has none -│ │ │ ├── CatalogueWindow.tsx # Where a GM adds to what shops sell: download an example or the current list, paste or upload, preview, save. SAVE only ever stores text that was previewed, and the preview is the server's own parser, so it cannot show something different from what gets stored; a custom system's items (7e3c): DOWNLOAD ITEMS, and the preview naming the lines that are items and those only nearly named as one; a type's section by its name in the preview, its problems and the save (GUNS ×2), a line's blank columns noted as kept (8a7a1); ALSO ON SALE FROM ITEMS, each line overruling an item and how, each left out and why (8a7a3c1) +│ │ │ ├── CatalogueWindow.tsx # Where a GM adds to what shops sell: download an example or the current list, paste or upload, preview, save. SAVE only ever stores text that was previewed, and the preview is the server's own parser, so it cannot show something different from what gets stored; a custom system's items (7e3c): DOWNLOAD ITEMS, and the preview naming the lines that are items and those only nearly named as one; a type's section by its name in the preview, its problems and the save (GUNS ×2), a line's blank columns noted as kept (8a7a1); ALSO ON SALE FROM ITEMS, each line overruling an item and how, each left out and why (8a7a3c1); ADD NEW LINES TO ITEMS under the preview (8a7a4a), off to start: what it adds and how many ITEMS will hold, the save saying what was added and handing it to an open builder │ │ │ ├── EmptyShopSteps.tsx # What a GM is told when a shop has nothing on any shelf, which outside CWN is every new one: the steps to stock it, a button straight to SHOP_CATALOGUES, and the header line for that shop's section in this game. Shown where the building type is set and to an admin opening the shop. A game's own item types by their sections' names and columns ([WEAPONS], 8a7a2) │ │ │ ├── CyberwareSection.tsx # What the GEAR tab shows: a count, the humanity cost, and the way in. Says when pieces are still unplaced, because an import lands everything unfiled and nothing else would mention it │ │ │ ├── ImportPreviewWindow.tsx # What an import would do, in its own window: what was recognised, what the source never held, what a custom system's importer left and why (worked out, GM-only, not one of the choices), and which of your fields a replace would clear. The window is the confirmation — applying replaces the sheet @@ -900,7 +902,7 @@ CITY_NET/ │ │ │ ├── VehicleBadgeButton.tsx # The car badge on the sheet and token menu — inline SVG so it takes the theme; inert on someone else's token rather than hidden │ │ │ ├── vehicleArt.tsx # Ten top-down wireframes, one per book vehicle. Stroke-only and currentColor, matching how the city itself is drawn │ │ │ ├── TvPortrait.tsx # Reusable glitchy TV/CRT portrait effect (chromatic fringe, scanlines, rollband); optional shadow silhouette -│ │ │ ├── BuilderScreen.tsx # The system builder: takes over the whole window, the map's icon rail down the left (MY SYSTEMS, the pages, SAVE, PUBLISH (from v2 on showing what the new version changes first, PublishPreviewPage), EXIT TO MAP), the open page under a bar naming it and over a status line. Autosaves the draft and warns on leaving only when saving failed. Opens a built-in example or genre starter read-only: every page locked but for tabs and things opening out, TRY IT usable, COPY TO CHANGE IT. HELP on the rail above SAVE, open with or without a system, keeping its topic while the GM goes to a page and back. The first-time tour once the server says it hasn't been seen (remembered when finished or skipped, played again from HELP), lighting each place on the rail held open. Its pages are left-aligned, not centred as #root is +│ │ │ ├── BuilderScreen.tsx # The system builder: takes over the whole window, the map's icon rail down the left (MY SYSTEMS, the pages, SAVE, PUBLISH (from v2 on showing what the new version changes first, PublishPreviewPage), EXIT TO MAP), the open page under a bar naming it and over a status line. Autosaves the draft and warns on leaving only when saving failed. Opens a built-in example or genre starter read-only: every page locked but for tabs and things opening out, TRY IT usable, COPY TO CHANGE IT. HELP on the rail above SAVE, open with or without a system, keeping its topic while the GM goes to a page and back. The first-time tour once the server says it hasn't been seen (remembered when finished or skipped, played again from HELP), lighting each place on the rail held open. Its pages are left-aligned, not centred as #root is; a catalogue's new items taken into the draft as edited, so autosave keeps them (8a7a4a) │ │ │ ├── BuilderTour.tsx # The builder's first-time tour box: a step's number, title and words, beside the rail button it points at (centered for the welcome, kept on the screen, its arrow at the button), BACK, NEXT or DONE with the keyboard's focus, and SKIP THE TOUR or Escape; the place it points at scrolled into view first, the rail being taller than a small window, and the box kept on the screen by its height as drawn │ │ │ ├── MySystemsPage.tsx # MY SYSTEMS: every system as a line item opening out in place (OPEN, RENAME, DUPLICATE, EXPORT, DELETE), + NEW and INSTALL A FILE, all without leaving the builder; EXPORT on a system with uploaded images opens a line to send them or not (ticked: a zip of it and them; unticked: the .citysys without) │ │ │ ├── SystemsPanels.tsx # MY SYSTEMS' parts: + NEW (blank, or a copy of a built-in example or genre starter from their cards, with LOOK FIRST), INSTALL A FILE with its preview, and the badges; INSTALL takes a .zip of a system and its images too, sent to the server as it is @@ -1008,7 +1010,7 @@ CITY_NET/ │ │ │ ├── VehicleBadgeButton.test.tsx # Reads as an action on your own and a statement on someone else's; themed rather than a fixed colour │ │ │ ├── SheetRenderer.vehicles.test.tsx # Collapsing repeated entries — one empty vehicle at rest, filled ones visible on reload, whitespace not counting as data │ │ │ ├── Sidebar.test.tsx # The dice menu's two headings, only the table's dice editable, a bad die in the danger color, an own die rolled by its id, no fixed colors left -│ │ │ ├── BuilderScreen.test.tsx # The builder taking over the window, every page reached from the rail and saved like any other change, SAVE and PUBLISH, leaving with or without unsaved work, MY SYSTEMS; looking at a built-in example or genre starter locked (tabs and opening out still working, TRY IT usable) and COPY TO CHANGE IT; HOUSE RULES after RESTS with GO TO to where a thing under a rule lives; HELP above SAVE with or without a system, GO TO and back to the same topic, unlocked while looking and opening another example; the tour lighting each place down the rail held open, BACK, SKIP and Escape, remembered once ended, kept away once seen or when the server can't say, and played again from HELP +│ │ │ ├── BuilderScreen.test.tsx # The builder taking over the window, every page reached from the rail and saved like any other change, SAVE and PUBLISH, leaving with or without unsaved work, MY SYSTEMS; looking at a built-in example or genre starter locked (tabs and opening out still working, TRY IT usable) and COPY TO CHANGE IT; HOUSE RULES after RESTS with GO TO to where a thing under a rule lives; HELP above SAVE with or without a system, GO TO and back to the same topic, unlocked while looking and opening another example; the tour lighting each place down the rail held open, BACK, SKIP and Escape, remembered once ended, kept away once seen or when the server can't say, and played again from HELP; a catalogue's new items taken in while open, another system's left alone (8a7a4a) │ │ │ ├── BuilderTour.test.tsx # Where the tour box sits (the welcome centered, beside the button, never off the screen, the arrow at the button), what it says at a step, BACK only after the first, DONE on the last, and Escape skipping it without going further; a place off the screen scrolled into view │ │ │ ├── MySystemsPage.test.tsx # Line items opening out in place, RENAME refused where typed, DUPLICATE, EXPORT, DELETE, INSTALL A FILE; + NEW blank, from a built-in example's or genre starter's card, and LOOK FIRST │ │ │ ├── SetupPage.test.tsx # Five questions on one page, each saved as answered, the name refused like RENAME, and the warning when characters already play the system; a "?" beside every setting the help has words for, the fields still named by their words @@ -1289,7 +1291,7 @@ CITY_NET/ │ │ │ ├── gearTypes.ts # The GEAR tab's tables as logic (8a3a): the types from the render copy, what fits each column, a line's type (its own, its item's, the first) and its cells (its own value over its item's, the item's only on a line of its type), the tables in the system's order, a value typed, a new line of a type; mirrors the server's lineColumns; shownCells and cellWords, what a compact line shows (8a3c1); countOf, a COUNT left as the server counts it, and "4 / 6" in words (8a4b) │ │ │ ├── gearDice.ts # A gear line's DAMAGE or DICE in words (8a3c2): ON THIS CHARACTER with each name's value and the range, or what is wrong; the eˣ shapes and INSERT at the cursor │ │ │ ├── rollTotal.ts # A roll line's final total, found for the dice history to bold: after the last = in its first [ ], or the lone number; never what follows a · -│ │ │ ├── catalogueItems.ts # A system's items in the shops' catalogues (7e3c): the preview's lines read against the items (named as one, landing as gear or not; nearly named, the closest said), the shelf a starter file uses (the gear's, or the first landing as gear), and the starter file itself, prices left blank; with types of its own, DOWNLOAD ITEMS puts each item in its type's section with its columns, and a type's section counts as gear in the preview (8a7a1) +│ │ │ ├── catalogueItems.ts # A system's items in the shops' catalogues (7e3c): the preview's lines read against the items (named as one, landing as gear or not; nearly named, the closest said), the shelf a starter file uses (the gear's, or the first landing as gear), and the starter file itself, prices left blank; with types of its own, DOWNLOAD ITEMS puts each item in its type's section with its columns, and a type's section counts as gear in the preview (8a7a1); ITEMS_ADDED_EVENT and withAddedItems, a catalogue's new items merged into a draft by id (8a7a4a) │ │ │ ├── choicesImport.ts # IMPORT as logic (choices import 2): DOWNLOAD EXAMPLE made from the system (its @names, its rests by name, a level column only for a levelled list, made-up rows) and DOWNLOAD THIS LIST (cells quoted as a spreadsheet would, rests by name where the reader finds them so, a # note for what a feature does beyond words and uses), a previewed list put into the draft, a line to select, and changes in the page's words. A levelled list's files have a die column, the example's d10 and d6 and the list's own (R1a); a list with a table's, a roll column (7a5b); gives and money columns, what an option gives read back unchanged (7c4e) │ │ │ ├── itemsImport.ts # The ITEMS tab's IMPORT as logic (8aL3b): DOWNLOAD EXAMPLE made from the system (a section per type with its own columns, needs in its words, cost only with an install, made-up rows fitting each column), DOWNLOAD THIS LIST, a preview put in place, each change in words; held to the server's reader; each section's price and in shops columns, IN SHOPS written only where an item says it, so the list reads back unchanged (8a7a3b2) │ │ │ ├── formulaBox.ts # The formula box as logic (formula box 1): a formula in words (+2 for each level, needs Strength 13 or more), its sample line, INSERT's groups (no formulas for an amount), and the SHAPES with why one can't be used yet and what each writes (a name at the cursor is statsRules.ts' insertToken). Formula box 2: ADD (+ your rolled stat's modifier), AGAINST (against 13, against your rolled stat) and a rest's amount (1d8 + CON modifier, sample 3 to 10); THIS ROLL in INSERT, no levels or tables for a rest; the shapes THE STAT ROLLED, ITS MODIFIER, DICE, DICE AND A STAT. Formula box 3: a STATS & RULES formula said as a value with no sign (2 for each level, your Strength), formulaTexts (each formula, or a condition's three parts, keyed id:box) and isMistake. has() in words, and INSERT's CHOICES group: each option and feature as has(name) (7b); AT LEAST in words: at least 19, at least your Con (7e1b); a cost (7f2b), reading the stat raised, and an option's price, said as what it costs; IMPROVE BY USE's boxes, dice and @this (7f3a2); INSERT's GEAR, @carried, @capacity and what is worn by column, wherever the gear is read (8a5c); a condition's TIMES, SET TO and AT MOST as kinds of box, read as formulas, the sample said its way (8a5e2) diff --git a/backend/__tests__/catalogue_into_items.test.js b/backend/__tests__/catalogue_into_items.test.js new file mode 100644 index 00000000..a5fb69e1 --- /dev/null +++ b/backend/__tests__/catalogue_into_items.test.js @@ -0,0 +1,131 @@ +/** + * A shop catalogue's new lines made items of the system (8a7a4a; decided 2026-11-21, mockup docs/mockups/types-in-shops.html, + * questions 10 to 13): ADD NEW LINES TO ITEMS, off to start, adds each line that isn't an item already to the builder's draft + * (of its section's type, a shelf's of the DEFAULT type), its columns, price, IN SHOPS and words; past 200 items, said. The + * preview says what it would add; the save adds it to the draft only, the running game untouched until a publish. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { createRequire } from 'module'; +import jwt from 'jsonwebtoken'; +import { makeTestDb, get, run } from './helpers/testDb.js'; +import { untilValue, drain } from './helpers/until.js'; + +process.env.JWT_SECRET = 'test-secret'; +const require_ = createRequire(import.meta.url); +const { itemsFromLines } = require_('../systemBuilder/itemsFromCatalogue'); +const { parseCatalogue } = require_('../shops/catalogueParse'); +const { typesOf } = require_('../systemBuilder/itemTypes'); +const { checkDefinition } = require_('../systemBuilder/definition'); +const store = require_('../shops/catalogueStore'); +const runtime = require_('../systemBuilder/runtime'); +const socketsFactory = (await import('../sockets/index.js')).default; + +const WEAPONS = { id: 'weapons', label: 'WEAPONS', one: 'Weapon', columns: [{ id: 'damage', label: 'DAMAGE', kind: 'damage' }, { id: 'ammo', label: 'AMMO', kind: 'count' }, { id: 'price', label: 'PRICE', kind: 'number' }] }; +const GEAR = { id: 'gear', label: 'GEAR', one: 'Gear', columns: [{ id: 'weight', label: 'WEIGHT', kind: 'number' }] }; +const DEF = { + format: 1, name: 'Intofall', core: { health: { model: 'pool' } }, + stats: [{ id: 'abilities', label: 'ABILITIES', stats: [{ id: 'might', label: 'Might' }] }], + items: { types: [GEAR, WEAPONS], list: [{ id: 'pistol', label: 'Pistol', type: 'weapons', values: { damage: '2d6', price: 200 } }] }, +}; +const parse = (text, def = DEF) => parseCatalogue(text, { types: typesOf(def), names: { known: () => true, refused: (n) => n } }).sections; +const FILE = '[WEAPONS]\nname, price, damage, ammo, description\nPistol, 260, 2d6, 6\nHand Cannon, 900, 3d6, 5, "Loud, very."\n[weapon_mods]\nname, price\nScope, 2\n'; + +describe('the lines made items', () => { + it('each new line an item of its type, a shelf\'s of the DEFAULT type; one already an item not added', () => { + const out = itemsFromLines(DEF, parse(FILE)); + expect(out.items).toEqual([ + { id: 'hand_cannon', label: 'Hand Cannon', type: 'weapons', values: { damage: '3d6', ammo: 5, price: 900 }, in_shops: true, description: 'Loud, very.' }, + { id: 'scope', label: 'Scope', type: 'gear', price: 2, in_shops: true }, + ]); + expect(out.added).toEqual([ + { line: 4, catalogue: 'type:weapons', name: 'Hand Cannon', type: 'WEAPONS' }, + { line: 7, catalogue: 'weapon_mods', name: 'Scope', type: 'GEAR' }, + ]); + expect(out.skipped).toEqual([]); + // Sound as items, as the builder checks them. + expect(checkDefinition({ ...DEF, items: { ...DEF.items, list: [...DEF.items.list, ...out.items] } }).problems).toEqual([]); + }); + + it('an id apart from what the system already names; a name too long, and past 200 items, said and not added', () => { + const named = { ...DEF, items: { ...DEF.items, list: [...DEF.items.list, { id: 'hand_cannon', label: 'Old Cannon', type: 'weapons' }] } }; + expect(itemsFromLines(named, parse(FILE)).items[0].id).toBe('hand_cannon_2'); + const long = itemsFromLines(DEF, parse(`[gear]\nname, price\n${'X'.repeat(41)}, 1\n`)); + expect(long.skipped).toEqual([{ line: 3, catalogue: 'type:gear', name: 'X'.repeat(41), message: 'an item\'s name is 40 characters at most: not added' }]); + const full = { ...DEF, items: { ...DEF.items, list: Array.from({ length: 199 }, (_, i) => ({ id: `i${i}`, label: `I${i}` })) } }; + const one = itemsFromLines(full, parse(FILE)); + expect(one.items.map((i) => i.label)).toEqual(['Pistol']); + expect(one.skipped.map((s) => s.name)).toEqual(['Hand Cannon', 'Scope']); + expect(one.skipped[0].message).toBe('ITEMS holds 200, the most a system can: not added'); + }); + + it('a name in the file twice made one item, from its first line', () => { + const twice = itemsFromLines(DEF, parse('[WEAPONS]\nname, price, damage\nScope, 30, 1d4\n[weapon_mods]\nname, price\nScope, 2\n')); + expect(twice.items).toEqual([{ id: 'scope', label: 'Scope', type: 'weapons', values: { damage: '1d4', price: 30 }, in_shops: true }]); + }); + + it('a value that doesn\'t fit its column left out; a game without types of its own: nothing', () => { + const odd = itemsFromLines(DEF, { 'type:weapons': [{ name: 'Odd', price: 5, fields: { damage: 'lots', ammo: 3 }, line: 2 }] }); + expect(odd.items[0].values).toEqual({ ammo: 3, price: 5 }); + expect(itemsFromLines({ ...DEF, items: { list: [] } }, parse('[gear]\nname, price\nRope, 2\n', { ...DEF, items: { list: [] } }))).toEqual({ items: [], added: [], skipped: [] }); + }); +}); + +describe('at the table', () => { + const ID = 'sys_a74a0000a74a0000'; + let db; + const boot = async (who, admin) => { + const emitted = []; + let connect; + const io = { on: (e, cb) => { if (e === 'connection') connect = cb; }, emit: (event, data) => emitted.push({ event, data }), to: () => ({ emit: () => {} }) }; + socketsFactory(io, db, { elevatedUsers: new Set(), emitUpdate: vi.fn(), recordAction: vi.fn() }); + const handlers = {}; + connect({ id: `s-${who}-${Math.random()}`, on: (e, fn) => { handlers[e] = fn; }, emit: (event, data) => emitted.push({ event, data }), broadcast: { emit: () => {} }, use: () => {}, join: () => {} }); + handlers.identify(admin ? { userName: who, isAdmin: true, token: jwt.sign({ id: 1, username: who, role: 'admin', isTemporary: false }, 'test-secret') } : who); + await drain(db); + return { handlers, emitted }; + }; + const last = (emitted, event) => untilValue(() => [...emitted].reverse().find((e) => e.event === event), Boolean, { label: event }); + const copies = async () => { const row = await get(db, 'SELECT draft, published FROM custom_systems WHERE id = ?', [ID]); return { draft: JSON.parse(row.draft), published: JSON.parse(row.published) }; }; + + beforeEach(async () => { + store.clear(); + db = await makeTestDb(); + await run(db, `CREATE TABLE IF NOT EXISTS shop_catalogues (system TEXT NOT NULL, catalogue TEXT NOT NULL, id TEXT NOT NULL, + name TEXT NOT NULL, price REAL NOT NULL DEFAULT 0, fields TEXT NOT NULL DEFAULT '{}', PRIMARY KEY (system, catalogue, id))`); + const def = JSON.stringify(DEF); + await run(db, 'INSERT INTO custom_systems (id, name, draft, published, version) VALUES (?, ?, ?, ?, 1)', [ID, 'Intofall', def, def]); + await new Promise((resolve) => runtime.load(db, resolve)); + await run(db, "INSERT INTO global_settings (key, value) VALUES ('game_system', ?)", [ID]); + }); + + it('the preview says what ADD NEW LINES TO ITEMS would add, with each price, and how many the draft holds', async () => { + const gm = await boot('gm', true); + gm.handlers.previewCatalogue({ text: FILE }); + expect((await last(gm.emitted, 'cataloguePreview')).data.toItems).toEqual({ + added: [{ line: 4, catalogue: 'type:weapons', name: 'Hand Cannon', type: 'WEAPONS', price: 900 }, { line: 7, catalogue: 'weapon_mods', name: 'Scope', type: 'GEAR', price: 2 }], + skipped: [], have: 1, most: 200, + }); + }); + + it('saved with it off: the draft as it was; on: the new lines items in the draft only, said back with them', async () => { + const gm = await boot('gm', true); + gm.handlers.saveCatalogue({ text: FILE }); + expect((await last(gm.emitted, 'catalogueSaved')).data).not.toHaveProperty('toItems'); + expect((await copies()).draft.items.list.map((i) => i.label)).toEqual(['Pistol']); + gm.emitted.length = 0; + gm.handlers.saveCatalogue({ text: FILE, toItems: true }); + const saved = (await last(gm.emitted, 'catalogueSaved')).data; + expect(saved.toItems).toMatchObject({ ok: true, added: [{ name: 'Hand Cannon' }, { name: 'Scope' }], skipped: [] }); + expect(saved.toItems.items.map((i) => i.id)).toEqual(['hand_cannon', 'scope']); + const { draft, published } = await copies(); + expect(draft.items.list.map((i) => i.label)).toEqual(['Pistol', 'Hand Cannon', 'Scope']); + // The running game untouched until a publish. + expect(published.items.list.map((i) => i.label)).toEqual(['Pistol']); + // Saved again: already items, nothing added twice. + gm.emitted.length = 0; + gm.handlers.saveCatalogue({ text: FILE, toItems: true }); + expect((await last(gm.emitted, 'catalogueSaved')).data.toItems).toMatchObject({ ok: true, added: [], items: [] }); + expect((await copies()).draft.items.list).toHaveLength(3); + }); +}); diff --git a/backend/sockets/index.js b/backend/sockets/index.js index 1003ad5c..36b379d0 100644 --- a/backend/sockets/index.js +++ b/backend/sockets/index.js @@ -52,6 +52,9 @@ const { namesOf } = require('../systemBuilder/choices'); // The merged catalogue: what the app ships with, plus whatever a GM uploaded. const shopPrices = require('../shops/catalogueStore'); const { ownStock, againstItems } = require('../shops/ownItems'); +const { itemsFromLines } = require('../systemBuilder/itemsFromCatalogue'); +const systemsStore = require('../systemBuilder/store'); +const { itemsOf, LIMITS: ITEM_LIMITS } = require('../systemBuilder/items'); // And the running game's own items, priced and IN SHOPS (8a7a3a), under the uploaded lines. shopPrices.setOwnSource((system) => ownStock(customSystems.definitionOf(system))); const catalogueDb = require('../shops/catalogueDb'); @@ -2488,10 +2491,14 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { socket.on('previewCatalogue', (data) => { const info = userSockets.get(socket.id); if (!info || !info.isAdmin) return; - getGameSystem((sysErr, system) => previewCatalogue(data, sysErr ? {} : catalogueOptions(system), sysErr ? null : customSystems.definitionOf(system))); + getGameSystem((sysErr, system) => { + if (sysErr) return previewCatalogue(data, {}, null, null); + // The draft, where ADD NEW LINES TO ITEMS would put them (8a7a4a); none for a built-in game. + systemsStore.getSystem(db, system, (dErr, sys) => previewCatalogue(data, catalogueOptions(system), customSystems.definitionOf(system), dErr || !sys ? null : sys.draft)); + }); }); - const previewCatalogue = (data, options, definition) => { + const previewCatalogue = (data, options, definition, draft) => { const read = catalogueParse.parseCatalogue(data && data.text, options); // Held against the game's own items (8a7a3c1): exact copies and items kept out of the shops left out, as the save does. const held = againstItems(read.sections, definition); @@ -2515,6 +2522,13 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { notes: parsed.notes, summary, ...(held.onSale || held.leftOut.length || held.overrules.length ? { items: { onSale: held.onSale, overrules: held.overrules, leftOut: held.leftOut } } : {}), + // What ADD NEW LINES TO ITEMS would add to the draft (8a7a4a), and how many it holds. + ...(() => { + const into = itemsFromLines(draft, held.sections); + return into.added.length || into.skipped.length + ? { toItems: { added: into.added.map(({ line, catalogue, name, type }) => ({ line, catalogue, name, type, price: (held.sections[catalogue] || []).find((e) => e.name === name)?.price })), skipped: into.skipped, have: itemsOf(draft).length, most: ITEM_LIMITS.items } } + : {}; + })(), }); }; @@ -2545,10 +2559,23 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { catalogueDb.refresh(db, system, () => { io.emit('cataloguesChanged', { system }); const typeLabel = new Map(ownTypesIn(system).map((t) => [`type:${t.id}`, String(t.label || t.id).toUpperCase()])); - socket.emit('catalogueSaved', { + const answer = (toItems) => socket.emit('catalogueSaved', { ok: true, saved: wanted.map((c) => ({ catalogue: c, count: parsed.sections[c].length, ...(typeLabel.has(c) ? { label: typeLabel.get(c) } : {}) })), problems: parsed.problems, + ...(toItems ? { toItems } : {}), + }); + // ADD NEW LINES TO ITEMS (8a7a4a): the new lines made items in the builder's draft, live once published. + if (!(data && data.toItems === true)) return answer(null); + systemsStore.getSystem(db, system, (dErr, sys) => { + if (dErr || !sys) return answer({ ok: false, reason: 'no_draft', added: [], items: [] }); + const into = itemsFromLines(sys.draft, parsed.sections); + if (!into.items.length) return answer({ ok: true, added: [], skipped: into.skipped, items: [] }); + const items = { ...(sys.draft.items || {}) }; + items.list = [...(Array.isArray(items.list) ? items.list : []), ...into.items]; + systemsStore.saveDraft(db, system, { ...sys.draft, items }, (sErr) => answer(sErr + ? { ok: false, reason: 'write', added: [], items: [] } + : { ok: true, added: into.added, skipped: into.skipped, items: into.items })); }); }); }); diff --git a/backend/systemBuilder/itemsFromCatalogue.js b/backend/systemBuilder/itemsFromCatalogue.js new file mode 100644 index 00000000..36f199d1 --- /dev/null +++ b/backend/systemBuilder/itemsFromCatalogue.js @@ -0,0 +1,79 @@ +// A shop catalogue's new lines made items of the system (8a7a4a; decided 2026-11-21, mockup docs/mockups/types-in-shops.html, +// questions 10 to 13): with ADD NEW LINES TO ITEMS switched on in the catalogue's preview, each line that isn't one of the +// system's items already becomes one, in the builder's DRAFT (live when the GM publishes; the file's line sells it until +// then): of its section's type, a shelf's lines of the DEFAULT type (the first); its columns' values where they fit, its +// price (in the type's PRICE column where it has one, else its own), IN SHOPS, its words as its words. Past the most a +// system holds, the rest aren't added, each said. +// +// Pure: a definition and the file's sections to the items to add, what is said about each, and nothing changed. + +const { LIMITS: CHOICE_LIMITS, choicesOf, namesOf } = require('./choices'); +const { LIMITS, itemsOf } = require('./items'); +const { typesOf, ownTypes, valueProblem, PRICE_COLUMN, isPrice } = require('./itemTypes'); +const { idFrom } = require('./choicesImport'); +const { normaliseName } = require('../shops/prices'); + +const list = (v) => (Array.isArray(v) ? v : []); +const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v); +/** Dice read whatever names they read: the builder checks them, as it does any item's. */ +const ANY_NAME = { known: () => true, refused: (n) => `@${n}` }; + +/** + * { items: the items to add, added: [{ line, catalogue, name, type }], skipped: [{ line, catalogue, name, message }] } for the + * lines of `sections` (a catalogue as parsed, catalogue -> entries) against `definition`. Nothing for a system without types + * of its own, whose items no shop sells by themselves. + */ +const itemsFromLines = (definition, sections) => { + const out = { items: [], added: [], skipped: [] }; + if (!definition || !ownTypes(definition)) return out; + const types = typesOf(definition); + const existing = itemsOf(definition); + const named = new Set(existing.map((i) => normaliseName(i.label))); + // The names an item's id could clash with: options, features and items share one set, and formulas read names. + const taken = new Set(); + for (const c of choicesOf(definition)) { + taken.add(c.id); + for (const o of list(c.options).filter(isPlainObject)) { taken.add(o.id); for (const f of list(o.features).filter(isPlainObject)) taken.add(f.id); } + } + for (const i of existing) { taken.add(i.id); for (const f of list(i.features).filter(isPlainObject)) taken.add(f.id); } + for (const n of namesOf(definition).keys()) taken.add(n); + let room = LIMITS.items - existing.length; + + for (const [catalogue, entries] of Object.entries(sections || {})) { + const type = String(catalogue).startsWith('type:') ? types.find((t) => `type:${t.id}` === catalogue) : types[0]; + if (!type) continue; + for (const e of list(entries)) { + const name = String((e && e.name) || '').trim(); + const at = { line: (e && e.line) || 0, catalogue, name }; + // One already: the file's line overrules it, as the preview says; never a second. + if (!name || named.has(normaliseName(name))) continue; + if (name.length > CHOICE_LIMITS.label) { out.skipped.push({ ...at, message: `an item's name is ${CHOICE_LIMITS.label} characters at most: not added` }); continue; } + if (room <= 0) { out.skipped.push({ ...at, message: `ITEMS holds ${LIMITS.items}, the most a system can: not added` }); continue; } + const fields = isPlainObject(e.fields) ? e.fields : {}; + const values = {}; + for (const column of type.columns) { + const value = fields[column.id]; + if (value === undefined || value === '' || column.id === PRICE_COLUMN) continue; + if (!valueProblem(column, value, ANY_NAME)) values[column.id] = value; + } + const pricedByColumn = type.columns.some((c) => c.id === PRICE_COLUMN && c.kind === 'number'); + const price = isPrice(e.price) ? e.price : undefined; + if (pricedByColumn && price !== undefined) values[PRICE_COLUMN] = price; + const words = typeof fields.description === 'string' ? fields.description.trim().slice(0, CHOICE_LIMITS.description) : ''; + const item = { + id: idFrom(name, taken), label: name, type: type.id, + ...(Object.keys(values).length ? { values } : {}), + ...(!pricedByColumn && price !== undefined ? { price } : {}), + in_shops: price !== undefined, + ...(words ? { description: words } : {}), + }; + named.add(normaliseName(name)); + room -= 1; + out.items.push(item); + out.added.push({ ...at, type: String(type.label || type.id).toUpperCase() }); + } + } + return out; +}; + +module.exports = { itemsFromLines }; diff --git a/e2e/COVERAGE.md b/e2e/COVERAGE.md index 06e77c10..22169b36 100644 --- a/e2e/COVERAGE.md +++ b/e2e/COVERAGE.md @@ -37,6 +37,7 @@ panel), so a control that looks fine but does nothing is caught for all of them. | An item type's SOLD AT | the kinds of shop that sell its lines (8a7a2), the General Store where unsaid; set in the builder in 8a7b | `shop_typed_lines`, `typedShelves` | `shop-typed-lines` (unsaid: the General Store) | **AT THE TABLE** unsaid; a kind of shop picked waits for 8a7b's box | | An item's PRICE and IN SHOPS | priced and IN SHOPS, it sells itself at its type's shops (8a7a3a); off, never sold, not even from a file, but bought back at its price by a shop of its type (8a7a3c2); a type's PRICE column read as its price; set on ITEMS under TYPE, NOT SOLD in the list, a new item's price asked for (8a7a3b1); in the ITEMS import and downloads, price and in shops columns (8a7a3b2) | `shop_items_on_sale`, `itemPrice`, `ItemsPage`, `system_builder_items_import`, `itemsImport` | `shop-items-on-sale` (a type's PRICE column; a ring turned off; sold back from the window at 50%), `builder-item-price` (set by clicks), `builder-items-import` (imported priced and IN SHOPS) | **AT THE TABLE** | | A catalogue file held against the game's items | an exact copy of an item left out, an item kept out of the shops left out, one of an item's name overruling it, ALSO ON SALE FROM ITEMS (8a7a3c1) | `shop_items_on_sale`, `CatalogueWindow` | `catalogue-and-items` | **AT THE TABLE** | +| ADD NEW LINES TO ITEMS | a catalogue's new lines made items in the draft (8a7a4a), off to start | `catalogue_into_items`, `CatalogueWindow`, `catalogueItems`, `BuilderScreen` | `catalogue-and-items` (the Hand Cannon into the draft) | **AT THE TABLE** | | Building types and catalogues renamed or off | | `buildings` | | **GAP** | | Currencies | several, decimals, a catalogue's currency, the cart per currency, PAYROLL | `currencies`, `currency_icons`, `catalogue_currency`, `bank_currencies`, `shop_checkout_currencies` | | **GAP** | | The bank's celebrations | on / off | `bank` | | **GAP** | diff --git a/e2e/README.md b/e2e/README.md index 1689439c..ceec6aee 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -219,7 +219,7 @@ kept; the job itself stops at 30 (`timeout-minutes`), for a hang outside the tes | `tests/shop-stress.spec.ts` | The shop under load in a real browser (8n3, the user asked for a 1000+ item stress test). A GUNS shelf of 1000 lines saved from SHOP_CATALOGUES; the player opens it (200 rows and SHOWING 200 OF 1000), scrolls to the end for 200 more, filters it key by key to Gun 99 (11 rows, found past the first page), clears it and sorts by PRICE both ways (Gun 0 and Gun 999 at the top in turn). Each step under 5 s; on a desk each took under half a second, and the times are logged. | | `tests/shop-items-on-sale.spec.ts` | The game's own items at the table (8a7a3a), found by the user testing 8a7a2. A game whose WEAPONS type has a PRICE column, its Pistol priced 200 and a Ring of Might kept out of the shops, and no catalogue saved: the player's General Store has the Pistol on its WEAPONS shelf at 200 with its damage, never the ring, and no empty-shop steps; bought through the cart, it lands on the gear as a Weapon with its damage; sold back from the window at the store's 50% (8a7a3c2), 900 left and off the sheet. Run once without the window's fix, it fails at that balance. | | `tests/shop-typed-lines.spec.ts` | Lines of an item type at the table (8a7a2). A game with a GUNS type (DAMAGE, AMMO) and no SOLD AT, so sold at the General Store: the GM saves a [GUNS] catalogue with a Pistol and pays the player 1000; the player's General Store has a GUNS tab saying GOES INTO YOUR GEAR AS A GUN, sortable by DAMAGE and AMMO; the Pistol bought through the cart lands on the sheet as a Gun with its damage and ammo, and one given from GIVE.EXE stacks onto it. | -| `tests/catalogue-and-items.spec.ts` | A catalogue file held against the game's own items (8a7a3c1). WEAPONS selling a Pistol at 200 and a Cutlass at 120 by themselves, a Ring of Might kept out of the shops: a file with the Pistol at 260, the Cutlass exactly as it is, the Ring and a Hand Cannon previews as WEAPONS ×2, ALSO ON SALE FROM ITEMS: 2 (1 overruled by this file), the Pistol overruling 200 → 260, the Cutlass and the Ring left out and why; saved as WEAPONS ×2, DOWNLOAD CURRENT has the Pistol at 260, the Hand Cannon and the game's Cutlass behind a #, no Ring. | +| `tests/catalogue-and-items.spec.ts` | A catalogue file held against the game's own items (8a7a3c1). WEAPONS selling a Pistol at 200 and a Cutlass at 120 by themselves, a Ring of Might kept out of the shops: a file with the Pistol at 260, the Cutlass exactly as it is, the Ring and a Hand Cannon previews as WEAPONS ×2, ALSO ON SALE FROM ITEMS: 2 (1 overruled by this file), the Pistol overruling 200 → 260, the Cutlass and the Ring left out and why; saved as WEAPONS ×2, DOWNLOAD CURRENT has the Pistol at 260, the Hand Cannon and the game's Cutlass behind a #, no Ring. With ADD NEW LINES TO ITEMS switched on (8a7a4a, off to start), the Hand Cannon becomes an item of WEAPONS at 900 in the builder's draft (ITEMS 3 OF 200 → 4), said on SAVE, the published system untouched. | | `tests/catalogue-types.spec.ts` | A catalogue section per item type (8a7a1). In a game with a GUNS type (DAMAGE, AMMO, GRADE), DOWNLOAD EXAMPLE has a [GUNS] section in those columns; a file with a good pistol, a Hand Cannon whose AMMO is "six" and a Blank Gun with columns left blank previews as 2 ROWS READ · 1 PROBLEM, GUNS ×2, the cannon said by its line and the blanks noted as kept; SAVE says GUNS ×2; DOWNLOAD CURRENT has the pistol and the blank gun with their columns, never the cannon | | `tests/shop-items-catalogue.spec.ts` | Items in the shops (7e3c): CATALOGUES.EXE's DOWNLOAD ITEMS gives the ring on the gear's shelf, its price blank; with a price filled in and a line named Ring of Migt, the preview names RING OF MIGHT as an item and the other as nearly it; saved, GIVE.EXE lists the ring from the gear's catalogue at 500 beside the system's ITEMS | | `tests/sheet-level-up.spec.ts` | Going up a level (7d2b): XP reaches the next level and LEVEL UP READY blinks, opening LEVEL_UP.EXE (7d3a), where the player picks which of two classes goes up, leaves and comes back to it where they were, sees what the new level unlocks and FINISHES. In the window (7d3b) a Path Soldier 2 opens is picked, FINISH waiting for it, and then a class not held yet is taken up at level 1; what's past it carries over, with no + on a class, and LEVEL_DOWN brings READY back. With milestone there's no XP anywhere: the GM's LEVEL_UP gives a level, the rail blinks, the player takes it, and a stat called level can't be typed. An uploaded sheet brings its XP under the game's word, and one with none keeps what they have (7d2c). FILL IT IN FOR THEM (7d7a): the GM, on a player's sheet at level 1 with no XP, opens LEVEL_UP.EXE for them, adds a Path they don't meet, and finishes with nothing rolled: Soldier 2, the Path under its feature, health at its average | diff --git a/e2e/tests/catalogue-and-items.spec.ts b/e2e/tests/catalogue-and-items.spec.ts index ba14825e..c037df8d 100644 --- a/e2e/tests/catalogue-and-items.spec.ts +++ b/e2e/tests/catalogue-and-items.spec.ts @@ -1,12 +1,13 @@ import { test, expect } from '@playwright/test'; import { readFile } from 'fs/promises'; -import { signInAsGm, gmToken, runningSystem, openGameSystem } from './helpers'; +import { signInAsGm, gmToken, runningSystem, openGameSystem, asGm } from './helpers'; // A catalogue file held against the game's own items (8a7a3c1; mockup docs/mockups/types-in-shops.html, answered 2026-11-21). // A game whose WEAPONS sell themselves (a Pistol at 200, a Cutlass at 120) and a Ring of Might kept out of the shops: a file // with the Pistol at 260, the Cutlass exactly as it is, the Ring and a Hand Cannon previews as WEAPONS ×2, ALSO ON SALE FROM // ITEMS: 2 (1 overruled), the Pistol overruling 200 → 260, the Cutlass and the Ring left out and why; saved, DOWNLOAD CURRENT -// has the file's two lines and the game's items behind a #. +// has the file's two lines and the game's items behind a #. With ADD NEW LINES TO ITEMS on (8a7a4a), the Hand Cannon becomes +// an item of WEAPONS in the builder's draft, priced 900, the running game untouched until a publish. const SYSTEM = (name: string) => ({ format: 1, name, core: { health: { model: 'pool' } }, @@ -28,7 +29,7 @@ test('a catalogue held against the game\'s items: one overruling, an exact copy test.setTimeout(120_000); const again = info.retry ? `_${info.retry + 1}` : ''; const gm = await gmToken(request); - await runningSystem(request, gm, SYSTEM(`Itemfile${again}`)); + const id = await runningSystem(request, gm, SYSTEM(`Itemfile${again}`)); await page.setViewportSize({ width: 1280, height: 800 }); await signInAsGm(page); @@ -53,8 +54,19 @@ test('a catalogue held against the game\'s items: one overruling, an exact copy 'LINE 5 [WEAPONS] Ring of Might: kept out of the shops on ITEMS (IN SHOPS is off), so never sold: left out', ]); + // ADD NEW LINES TO ITEMS: off to start; on, the Hand Cannon to be an item (the Pistol is one already). + const into = page.getByTestId('catalogue-to-items'); + const toggle = into.getByRole('switch', { name: /ADD NEW LINES TO ITEMS/ }); + await expect(toggle).toHaveAttribute('aria-checked', 'false'); + await toggle.click(); + await expect(into.getByText('Hand Cannon becomes an item of WEAPONS, 900')).toBeVisible(); + await expect(into.getByText(/^ITEMS · 3 OF 200 → 4 OF 200/)).toBeVisible(); + await page.getByRole('button', { name: 'SAVE', exact: true }).click(); - await expect(page.getByText('Saved: WEAPONS ×2. The shops have it now.')).toBeVisible({ timeout: 15_000 }); + await expect(page.getByText("Saved: WEAPONS ×2. The shops have it now. Hand Cannon added to ITEMS in the builder's draft: PUBLISH the system to keep it.")).toBeVisible({ timeout: 15_000 }); + const system = await asGm(request, gm, 'get', `/api/systems/${id}`); + expect(system.draft.items.list.find((i: { label: string }) => i.label === 'Hand Cannon')).toEqual({ id: 'hand_cannon', label: 'Hand Cannon', type: 'weapons', values: { damage: '3d6', price: 900 }, in_shops: true }); + expect(system.published.items.list.map((i: { label: string }) => i.label)).toEqual(['Pistol', 'Cutlass', 'Ring of Might']); // On sale now: the file's two lines, and the game's own Cutlass behind a # (the Pistol's line stands in for its item). const [current] = await Promise.all([page.waitForEvent('download'), page.getByRole('button', { name: 'DOWNLOAD CURRENT', exact: true }).click()]); diff --git a/frontend/src/components/BuilderScreen.tsx b/frontend/src/components/BuilderScreen.tsx index b28d42f7..3915a3fa 100644 --- a/frontend/src/components/BuilderScreen.tsx +++ b/frontend/src/components/BuilderScreen.tsx @@ -6,6 +6,7 @@ import { BUILDER_PAGES, type Autosave, type BuilderPage, } from '../sheets/builderSession'; import { SYSTEMS_CHANGED_EVENT } from '../sheets/systemsLibrary'; +import { ITEMS_ADDED_EVENT, withAddedItems, type ItemsAdded } from '../sheets/catalogueItems'; import { MySystemsPage } from './MySystemsPage'; import { SetupPage } from './SetupPage'; import { WordsPage } from './WordsPage'; @@ -293,6 +294,26 @@ export function BuilderScreen({ token, systemId, startPage = 'setup', running, o return () => { live = false; }; }, [api, looking, example]); + // A catalogue's new lines made items in this system's draft (8a7a4a): taken into the draft as edited here, so the next + // autosave keeps them rather than saving over them. Only items it hasn't already, by id; nothing else it has changes. + const draftNow = useRef(null); + useEffect(() => { draftNow.current = definition; }, [definition]); + useEffect(() => { + if (!systemId) return undefined; + const takeIn = (e: Event) => { + const said = (e as CustomEvent).detail; + const now = draftNow.current; + if (!said || said.systemId !== systemId || !now) return; + const next = withAddedItems(now, said.items); + if (next === now) return; + draftNow.current = next; + setDefinition(next); + autosave.current?.edit(next); + }; + window.addEventListener(ITEMS_ADDED_EVENT, takeIn); + return () => window.removeEventListener(ITEMS_ADDED_EVENT, takeIn); + }, [systemId]); + /** A page changed the system: shown at once, saved once editing pauses (builderSession). */ const edit = (next: Definition) => { // Nothing on a locked page can call this, but an example never changes whatever does. diff --git a/frontend/src/components/CatalogueWindow.tsx b/frontend/src/components/CatalogueWindow.tsx index 61b15130..ab18dbd9 100644 --- a/frontend/src/components/CatalogueWindow.tsx +++ b/frontend/src/components/CatalogueWindow.tsx @@ -4,7 +4,8 @@ import { exampleFor, currentFor, type StoredEntry } from '../sheets/catalogueSch import { catalogueLabel, type ShopStock } from '../data/buildingTypes'; import { downloadText } from '../utils/downloadText'; import { customTemplate } from '../sheets/customTemplates'; -import { itemsInPreview, itemsCatalogue, type PreviewRow } from '../sheets/catalogueItems'; +import { itemsInPreview, itemsCatalogue, ITEMS_ADDED_EVENT, type PreviewRow, type ItemsAdded } from '../sheets/catalogueItems'; +import { ToggleSwitch } from './ToggleSwitch'; // Where a GM adds to what the shops sell. // @@ -36,7 +37,9 @@ interface Summary { catalogue: string; count: number; overrides: string[]; label /** `notes` (8a7a1): what a type's line left blank, nothing wrong. */ /** The file held against the game's own items (8a7a3c1): how many sell themselves, lines overruling one, lines left out. */ interface AgainstItems { onSale: number; overrules: (Omit & { from: number; to: number })[]; leftOut: Problem[] } -interface Preview { problems: Problem[]; notes?: Problem[]; summary: Summary[]; format: string | null; sections?: Record; items?: AgainstItems } +/** What ADD NEW LINES TO ITEMS would add to the draft (8a7a4a), and how many items it holds. */ +interface ToItems { added: (Omit & { type: string; price?: number })[]; skipped: Problem[]; have: number; most: number } +interface Preview { problems: Problem[]; notes?: Problem[]; summary: Summary[]; format: string | null; sections?: Record; items?: AgainstItems; toItems?: ToItems } /** * Socket.io refuses a message over a megabyte by default, and says nothing useful when it @@ -57,6 +60,8 @@ export function CatalogueWindow({ pos, setPos, onClose, socket, system }: Props) const [previewedText, setPreviewedText] = useState(null); const [busy, setBusy] = useState<'preview' | 'save' | 'current' | null>(null); const [message, setMessage] = useState<{ tone: 'ok' | 'bad'; text: string } | null>(null); + /** ADD NEW LINES TO ITEMS (8a7a4a): off to start, afresh with each preview. */ + const [toItems, setToItems] = useState(false); const fileRef = useRef(null); /** Set when this window asked for the current catalogues, so their arrival means "download". */ const awaitingCurrent = useRef(false); @@ -67,16 +72,24 @@ export function CatalogueWindow({ pos, setPos, onClose, socket, system }: Props) const onPreview = (res: Preview) => { setBusy(null); setPreview(res); + setToItems(false); }; - const onSaved = (res: { ok: boolean; reason?: string; saved?: { catalogue: string; count: number; label?: string }[] }) => { + const onSaved = (res: { ok: boolean; reason?: string; saved?: { catalogue: string; count: number; label?: string }[]; toItems?: { ok: boolean; added: { name: string }[]; items: Record[] } }) => { setBusy(null); if (!res.ok) { setMessage({ tone: 'bad', text: res.reason === 'empty' ? 'Nothing in that could be saved.' : 'The save did not go through. Nothing was changed.' }); return; } const parts = (res.saved ?? []).map((s) => `${s.label ?? catalogueLabel(s.catalogue as ShopStock, system)} ×${s.count}`); - setMessage({ tone: 'ok', text: `Saved: ${parts.join(', ')}. The shops have it now.` }); + // The lines made items in the draft (8a7a4a): said, and handed to a builder open on this system. + const into = res.toItems; + const added = into?.ok ? into.added.length : 0; + const items = !into ? '' : !into.ok ? ' The new lines could not be added to ITEMS.' + : added === 1 ? ` ${into.added[0].name} added to ITEMS in the builder's draft: PUBLISH the system to keep it.` + : added ? ` ${added} lines added to ITEMS in the builder's draft: PUBLISH the system to keep them.` : ''; + if (into?.ok && into.items.length) window.dispatchEvent(new CustomEvent(ITEMS_ADDED_EVENT, { detail: { systemId: system, items: into.items } })); + setMessage({ tone: into && !into.ok ? 'bad' : 'ok', text: `Saved: ${parts.join(', ')}. The shops have it now.${items}` }); setPreview(null); setPreviewedText(null); }; @@ -128,7 +141,7 @@ export function CatalogueWindow({ pos, setPos, onClose, socket, system }: Props) if (!canSave) return; setMessage(null); setBusy('save'); - socket.emit('saveCatalogue', { text }); + socket.emit('saveCatalogue', { text, ...(toItems && preview?.toItems?.added.length ? { toItems: true } : {}) }); }; const pickFile = (file: File | undefined) => { @@ -354,6 +367,31 @@ export function CatalogueWindow({ pos, setPos, onClose, socket, system }: Props) )} )} + {/* ADD NEW LINES TO ITEMS (8a7a4a; mockup types-in-shops.html, section 7): off to start; on, what it adds. Under the + scrolling preview, so the switch that changes what SAVE does is always in sight. */} + {preview && preview.toItems && preview.toItems.added.length > 0 && (() => { + const into = preview.toItems; + const shown = into.added.slice(0, 8); + return ( +
+ + {toItems && <> + {shown.map((a, i) => ( +
+ {a.name} becomes an item of {a.type}{a.price !== undefined ? `, ${a.price}` : ''} +
+ ))} + {into.added.length > shown.length &&
and {into.added.length - shown.length} more
} +
+ ITEMS · {into.have} OF {into.most} → {into.have + into.added.length} OF {into.most} · in the builder's draft, live once you PUBLISH +
+ } + {toItems && into.skipped.map((p, i) => ( +
{p.line > 0 ? `LINE ${p.line}` : 'FILE'} {p.name}: {p.message}
+ ))} +
+ ); + })()} ); diff --git a/frontend/src/components/__tests__/BuilderScreen.test.tsx b/frontend/src/components/__tests__/BuilderScreen.test.tsx index b01e1790..e744f2f1 100644 --- a/frontend/src/components/__tests__/BuilderScreen.test.tsx +++ b/frontend/src/components/__tests__/BuilderScreen.test.tsx @@ -1056,4 +1056,15 @@ describe('HOUSE RULES (4j3b)', () => { await userEvent.click(within(sidebar()).getByLabelText('SAVE')); await waitFor(() => expect(drafts.at(-1)).toMatchObject({ house_rules: [{ id: 'magic', name: 'MAGIC' }, { id: 'new_rule', name: 'NEW RULE' }] })); }); -}); \ No newline at end of file +}); + +describe('a catalogue\'s new items, while the builder is open (8a7a4a)', () => { + it('taken into the draft as edited here, so the next save keeps them; another system\'s left alone', async () => { + open({ startPage: 'setup' }); + await ready(); + act(() => { window.dispatchEvent(new CustomEvent('city:catalogue-items-added', { detail: { systemId: 'sys_ffffffffffffffff', items: [{ id: 'nope', label: 'Nope' }] } })); }); + act(() => { window.dispatchEvent(new CustomEvent('city:catalogue-items-added', { detail: { systemId: HEARTH, items: [{ id: 'hand_cannon', label: 'Hand Cannon' }] } })); }); + await userEvent.click(within(sidebar()).getByLabelText('SAVE')); + await waitFor(() => expect(drafts.at(-1)).toEqual({ format: 1, name: 'Hearth', items: { list: [{ id: 'hand_cannon', label: 'Hand Cannon' }] } })); + }); +}); diff --git a/frontend/src/components/__tests__/CatalogueWindow.test.tsx b/frontend/src/components/__tests__/CatalogueWindow.test.tsx index 90bd834e..e01bfcb5 100644 --- a/frontend/src/components/__tests__/CatalogueWindow.test.tsx +++ b/frontend/src/components/__tests__/CatalogueWindow.test.tsx @@ -10,7 +10,7 @@ import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, act, fireEvent } from '@testing-library/react'; +import { render, screen, act, fireEvent, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { CatalogueWindow } from '../CatalogueWindow'; import { registerCustomTemplate, clearCustomTemplates } from '../../sheets/customTemplates'; @@ -357,3 +357,64 @@ describe('the file held against the game\'s own items (8a7a3c1)', () => { expect(screen.queryByTestId('catalogue-overrules')).toBeNull(); }); }); + +describe('ADD NEW LINES TO ITEMS (8a7a4a)', () => { + const TO_ITEMS = { + added: [{ line: 4, catalogue: 'type:guns', name: 'Hand Cannon', type: 'GUNS', price: 900 }, { line: 5, catalogue: 'type:guns', name: 'Derringer', type: 'GUNS', price: 90 }], + skipped: [{ line: 6, catalogue: 'type:guns', name: 'Overflow', message: 'ITEMS holds 200, the most a system can: not added' }], + have: 12, most: 200, + }; + const previewWith = (toItems?: object) => reply('cataloguePreview', { + format: 'delimited', summary: [{ catalogue: 'type:guns', count: 3, overrides: [], label: 'GUNS' }], problems: [], ...(toItems ? { toItems } : {}), + }); + + it('off to start; on, what it adds and how many ITEMS will hold; saved with it said, and handed to an open builder', async () => { + show(); + type('[GUNS]\nname, price\nHand Cannon, 900'); + await userEvent.click(button('PREVIEW')); + previewWith(TO_ITEMS); + const panel = within(screen.getByTestId('catalogue-to-items')); + const toggle = panel.getByRole('switch', { name: /ADD NEW LINES TO ITEMS/ }); + expect(toggle.getAttribute('aria-checked')).toBe('false'); + expect(panel.queryByText(/becomes an item/)).toBeNull(); + await userEvent.click(toggle); + expect(panel.getByText('Hand Cannon becomes an item of GUNS, 900')).toBeInTheDocument(); + expect(panel.getByText('Derringer becomes an item of GUNS, 90')).toBeInTheDocument(); + expect(panel.getByText(/^ITEMS · 12 OF 200 → 14 OF 200/)).toBeInTheDocument(); + expect(panel.getByText('LINE 6 Overflow: ITEMS holds 200, the most a system can: not added')).toBeInTheDocument(); + const heard = vi.fn(); + window.addEventListener('city:catalogue-items-added', heard); + await userEvent.click(button('SAVE')); + expect(sent.at(-1)).toEqual({ event: 'saveCatalogue', data: { text: '[GUNS]\nname, price\nHand Cannon, 900', toItems: true } }); + reply('catalogueSaved', { ok: true, saved: [{ catalogue: 'type:guns', count: 3, label: 'GUNS' }], toItems: { ok: true, added: [{ name: 'Hand Cannon' }, { name: 'Derringer' }], items: [{ id: 'hand_cannon' }, { id: 'derringer' }] } }); + expect(screen.getByText("Saved: GUNS ×3. The shops have it now. 2 lines added to ITEMS in the builder's draft: PUBLISH the system to keep them.")).toBeInTheDocument(); + expect(heard).toHaveBeenCalledOnce(); + expect((heard.mock.calls[0][0] as CustomEvent).detail).toEqual({ systemId: 'cities_without_number', items: [{ id: 'hand_cannon' }, { id: 'derringer' }] }); + window.removeEventListener('city:catalogue-items-added', heard); + }); + + it('left off, saved without it; nothing new to add, no switch; one added, said by name', async () => { + show(); + type('[GUNS]\nname, price\nHand Cannon, 900'); + await userEvent.click(button('PREVIEW')); + previewWith(TO_ITEMS); + await userEvent.click(button('SAVE')); + expect(sent.at(-1)).toEqual({ event: 'saveCatalogue', data: { text: '[GUNS]\nname, price\nHand Cannon, 900' } }); + reply('catalogueSaved', { ok: true, saved: [{ catalogue: 'type:guns', count: 1, label: 'GUNS' }], toItems: { ok: true, added: [{ name: 'Hand Cannon' }], items: [{ id: 'hand_cannon' }] } }); + expect(screen.getByText("Saved: GUNS ×1. The shops have it now. Hand Cannon added to ITEMS in the builder's draft: PUBLISH the system to keep it.")).toBeInTheDocument(); + await userEvent.click(button('PREVIEW')); + previewWith(); + expect(screen.queryByTestId('catalogue-to-items')).toBeNull(); + }); + + it('off again with each fresh preview, whatever it was before', async () => { + show(); + type('[GUNS]\nname, price\nHand Cannon, 900'); + await userEvent.click(button('PREVIEW')); + previewWith(TO_ITEMS); + await userEvent.click(within(screen.getByTestId('catalogue-to-items')).getByRole('switch', { name: /ADD NEW LINES TO ITEMS/ })); + await userEvent.click(button('PREVIEW')); + previewWith(TO_ITEMS); + expect(within(screen.getByTestId('catalogue-to-items')).getByRole('switch', { name: /ADD NEW LINES TO ITEMS/ }).getAttribute('aria-checked')).toBe('false'); + }); +}); diff --git a/frontend/src/sheets/__tests__/catalogueItems.test.ts b/frontend/src/sheets/__tests__/catalogueItems.test.ts index 32857ada..d4fbe187 100644 --- a/frontend/src/sheets/__tests__/catalogueItems.test.ts +++ b/frontend/src/sheets/__tests__/catalogueItems.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, afterEach } from 'vitest'; -import { distance, itemsInPreview, itemsShelf, itemsCatalogue, landsAsGear } from '../catalogueItems'; +import { distance, itemsInPreview, itemsShelf, itemsCatalogue, landsAsGear, withAddedItems } from '../catalogueItems'; import { registerCustomTemplate, clearCustomTemplates } from '../customTemplates'; import type { ItemsShown } from '../gearItems'; @@ -95,3 +95,14 @@ describe('a starter catalogue of the items', () => { expect(itemsCatalogue(HEARTH, { slots: [], list: [{ id: 'b', label: ' ', needs: 'worn', features: [] }] })).toBeNull(); }); }); + +describe('a catalogue\'s new items merged into a draft (8a7a4a)', () => { + const DRAFT = { format: 1, name: 'X', items: { types: [{ id: 'gear', label: 'GEAR' }], list: [{ id: 'rope', label: 'Rope' }] } } as never; + it('each one whose id it hasn\'t, at the end; the rest of the draft as it was; none new, the same draft', () => { + const next = withAddedItems(DRAFT, [{ id: 'rope', label: 'Other Rope' }, { id: 'scope', label: 'Scope' }]) as { items: { types: unknown[]; list: unknown[] } }; + expect(next.items.list).toEqual([{ id: 'rope', label: 'Rope' }, { id: 'scope', label: 'Scope' }]); + expect(next.items.types).toEqual([{ id: 'gear', label: 'GEAR' }]); + expect(withAddedItems(DRAFT, [{ id: 'rope', label: 'Rope' }])).toBe(DRAFT); + expect((withAddedItems({ format: 1, name: 'Y' } as never, [{ id: 'a', label: 'A' }]) as { items: { list: unknown[] } }).items.list).toEqual([{ id: 'a', label: 'A' }]); + }); +}); diff --git a/frontend/src/sheets/catalogueItems.ts b/frontend/src/sheets/catalogueItems.ts index 144f4555..c317060a 100644 --- a/frontend/src/sheets/catalogueItems.ts +++ b/frontend/src/sheets/catalogueItems.ts @@ -10,6 +10,7 @@ import type { ShopStock } from '../data/buildingTypes'; import { CATALOGUES, catalogueOn } from '../data/buildingTypes'; import { columnsFor, writeCatalogueFile, ownTypesOf } from './catalogueSchema'; import type { ItemsShown } from './gearItems'; +import type { Definition } from './systemsApi'; /** A row as the preview sends it back (backend shops/catalogueParse.js). */ export interface PreviewRow { name: string; line?: number } @@ -116,3 +117,19 @@ export const itemsCatalogue = (system: string, items: ItemsShown | undefined): s ], ); }; + +/** + * Said in the page when a catalogue's new lines were made items in a system's draft (8a7a4a, ADD NEW LINES TO ITEMS), so a + * builder open on that system takes them in before its next autosave, rather than saving over them. + */ +export const ITEMS_ADDED_EVENT = 'city:catalogue-items-added'; +export interface ItemsAdded { systemId: string; items: Record[] } + +/** A draft with a catalogue's new items at the end of its list: each one whose id it hasn't already, the rest as they are. */ +export const withAddedItems = (def: Definition, items: Record[]): Definition => { + const part = (def.items && typeof def.items === 'object' && !Array.isArray(def.items) ? def.items : {}) as Record; + const list = Array.isArray(part.list) ? part.list as Record[] : []; + const have = new Set(list.map((i) => i && i.id)); + const fresh = (items ?? []).filter((i) => i && typeof i.id === 'string' && !have.has(i.id)); + return fresh.length ? { ...def, items: { ...part, list: [...list, ...fresh] } } : def; +};