diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f53013c..7352b65c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -105,6 +105,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added +- **Publishing tidies the shop catalogue.** When you publish a system, any catalogue line that is now exactly one of your items, same name, price and columns, is taken out of the file, since the item sells itself. That includes lines that ADD NEW LINES TO ITEMS turned into items. The builder's publish message says how many. Lines naming an item kept out of the shops stay, so they sell again if you switch it back on. - **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. diff --git a/README.md b/README.md index 9f577775..46538810 100644 --- a/README.md +++ b/README.md @@ -363,7 +363,7 @@ CITY_NET/ │ │ ├── fonts.js # Font file upload/list/delete (.ttf .otf .woff .woff2); served as static under /uploads/fonts/ │ │ ├── me.js # The signed-in person's own settings, GET and PUT /api/me/settings (6c4b3a): anyone signed in, player or GM, reads and changes only their own, a known setting at a time │ │ ├── player.js # Player auth (register, login, forgot, reset, registration status poll); the GM's RESET makes a temporary password from the secure random source, in letters and digits read aloud without mix-ups -│ │ ├── systems.js # Custom game systems: list, create (from a name, a whole definition, or a copy of a built-in example or genre starter), read, save a draft, preview what publishing would change (publishPreview.js), publish, rename, duplicate, delete (a hide, refused for the running system); export a published system as a .citysys file, preview a file, install it as new, an update or a second copy; upload a currency or condition icon (PNG, WebP or SVG, 0.25MB, stored by content hash, one route for both) and set or clear a currency's icon in the draft and running copy alike; the builder's previews, which change nothing (a draft's values from its sample, its sheet as drawn, an NPC tier rolled for a level, health tried on a pretend token); the examples and starters, listed and opened; a built-in game's own conditions replaced (PUT /table-conditions/:system); a draft's rest tried on a made-up character (POST /try-rest). Main admin only, reading included, except the two public reads every player needs: a published system's render copy, and the conditions a system offers (GET /conditions/:system, modifiers left out for anyone but the GM). GET and PUT /tour: whether the builder's first-time tour has been seen, one setting in global_settings. PUT /:id/house-rules: the GM or a granted editor switches a running system's house rules, any number at once, the game taking them straight away and every browser told. POST /test-dice: the DICE tab's TEST, a handful of a draft's own die thrown by the table's engine; test-roll: TEST ROLL, one of a draft's rolls made for its sample character by the table's own engine on the secure dice, under the draft's conditions asked for, changing and logging nothing; preview-values reads a ranked stat's sample as its step (7f1b); POST /import-items reads a file of items against a draft (8aL3a), changing nothing +│ │ ├── systems.js # Custom game systems: list, create (from a name, a whole definition, or a copy of a built-in example or genre starter), read, save a draft, preview what publishing would change (publishPreview.js), publish, rename, duplicate, delete (a hide, refused for the running system); export a published system as a .citysys file, preview a file, install it as new, an update or a second copy; upload a currency or condition icon (PNG, WebP or SVG, 0.25MB, stored by content hash, one route for both) and set or clear a currency's icon in the draft and running copy alike; the builder's previews, which change nothing (a draft's values from its sample, its sheet as drawn, an NPC tier rolled for a level, health tried on a pretend token); the examples and starters, listed and opened; a built-in game's own conditions replaced (PUT /table-conditions/:system); a draft's rest tried on a made-up character (POST /try-rest). Main admin only, reading included, except the two public reads every player needs: a published system's render copy, and the conditions a system offers (GET /conditions/:system, modifiers left out for anyone but the GM). GET and PUT /tour: whether the builder's first-time tour has been seen, one setting in global_settings. PUT /:id/house-rules: the GM or a granted editor switches a running system's house rules, any number at once, the game taking them straight away and every browser told. POST /test-dice: the DICE tab's TEST, a handful of a draft's own die thrown by the table's engine; test-roll: TEST ROLL, one of a draft's rolls made for its sample character by the table's own engine on the secure dice, under the draft's conditions asked for, changing and logging nothing; preview-values reads a ranked stat's sample as its step (7f1b); POST /import-items reads a file of items against a draft (8aL3a), changing nothing; PUBLISH takes out the catalogue lines now exactly one of the system's items and says how many (dropped), the running game's shops told (8a7a4b) │ │ └── sheets.js # Character sheets — admin sheet access, NPC library, portraits, LUCK/Edge reset & grant, CWN's long rest (System Strain down 1), a custom system's rests listed and called or previewed (GET /rests, POST /rest, GM and granted editors), import preview; a friendly NPC's sheet, read-only, for the player the GM gave it to (GET /npcs/controlled/:location_id). The table-wide resets scan to decide who is affected and then work out each value as that sheet is written, rather than writing back a scan that has already gone stale; the GM's GET /user/:username carries the player's token for the vitals box (8s3d2) │ ├── dice/ │ │ └── systemDice.js # Built-in dice manifest keyed by game system (ids namespaced `builtin:`); lives in code, not the DB, so app updates change definitions with no migration and nothing is mutable through the API @@ -423,7 +423,7 @@ CITY_NET/ │ │ ├── catalogueParse.js # Reads a catalogue a GM pasted or uploaded: CSV, TSV or JSON, real RFC-4180 quoting, per-line problems rather than exceptions. The only reader - the preview is a round trip to it; a section per item type (8a7a1): [GUNS], [gun] or [MELEE WEAPONS] is lines of the system's own type, a type winning over a shelf of its name, each column read as it holds (numbers, PICK ONE's own word) and checked as the builder checks an item's, a row that doesn't fit left out and said, blanks kept and noted once a row; a section that is neither a type nor a shelf said, its rows not saved │ │ ├── catalogueStore.js # Uploaded catalogues in memory, added on top of the built-in ones, never replacing them. Holds one system at a time, and consults the built-in book only when that system is CWN - every other game's shops carry only what their GM uploaded. Requires nothing, so priceOf stays synchronous and the lot stays importable from a frontend test │ │ ├── ownItems.js # The game's own items on the shelves (8a7a3a; decided 2026-11-21): each priced and IN SHOPS a line of its type's catalogue, its values and words as fields; the names of those turned off. Pure, worked out once per definition. A catalogue file held against them (againstItems, 8a7a3c1): an exact copy of an item left out, one kept out of the shops left out, one of an item's name overruling it, and how many sell themselves besides; the items turned off with a price, bought back by a shop of their type (8a7a3c2). The running game's own items (8a7a3a, ownItems.js, set by the sockets) sit under the uploaded lines: a line uploaded with an item's name wins, an item turned off keeps a line of its name off the shelves -│ │ └── catalogueDb.js # The only piece that knows uploaded catalogues live in SQLite. A save replaces one catalogue wholesale, in a transaction, a hundred rows a statement (8n3: a 1500-line save took a round trip a row) +│ │ └── catalogueDb.js # The only piece that knows uploaded catalogues live in SQLite. A save replaces one catalogue wholesale, in a transaction, a hundred rows a statement (8n3: a 1500-line save took a round trip a row); on a publish, a system's lines now exactly one of its items taken out (dropItemCopies, 8a7a4b), lines naming an item kept out of the shops kept │ ├── tokens/ │ │ ├── conditions.js # A token's conditions as stored ([{ id, left }]): read safely, checked against what the running system offers (one twice, an unknown one, rounds out of 1 to 99 refused by name; one that ends after rounds starting at its own), shown to everyone without the rounds left, a hidden one (a house rule off) kept as it was, and counted down a round at a time for a combat's tokens (tickCombat), coming off at none; `started` kept for one ending AT THE END OF ITS NEXT TURN, through an edit too (8a9a) │ │ ├── poolHealth.js # One pool of hit points changed by an amount (8a9a): TEMP first, never below 0 nor past MAX; the HEALTH route and a condition's EACH TURN alike @@ -606,7 +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 +│ ├── 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; PUBLISH takes out the lines now exactly an item, keeps a new line and one naming an item kept out, tells the running game's shops (8a7a4b) │ ├── 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 @@ -1241,7 +1241,7 @@ CITY_NET/ │ │ │ ├── modTargets.ts # What a modifier may point at, read off the sheet template rather than listed: the template already knows this system's stats and skills. Stats are found through the skills, since each names the stat it keys off — which works unchanged on CWN, whose skills key off a modifier field. Maximums and derived fields are excluded, both being values a modifier could never hold │ │ │ ├── systemsApi.ts # The builder's requests to the server (routes/systems.js), each answering ok with a value or the server's own words for what went wrong; whether the tour has been seen, and marking it; a running system's house rules switched; testDice for the DICE tab's TEST; tableDice for COPY FROM THE TABLE'S DICE; importItems (8aL3b) │ │ │ ├── systemsLibrary.ts # What MY SYSTEMS says about each system: its badges, version, facts, what an install offers (BRING IT BACK or START FRESH for one deleted here), and the messages after a rename, duplicate, delete or install -│ │ │ ├── builderSession.ts # The builder's saving as rules: autosave after a pause, SAVE now, whether leaving needs asking, what PUBLISH says, and its pages (HOUSE RULES between RESTS and TRY IT); ITEMS on the rail, after CHOICES (7e2b) +│ │ │ ├── builderSession.ts # The builder's saving as rules: autosave after a pause, SAVE now, whether leaving needs asking, what PUBLISH says, and its pages (HOUSE RULES between RESTS and TRY IT); ITEMS on the rail, after CHOICES (7e2b); the publish sentence says how many catalogue lines it took out (8a7a4b) │ │ │ ├── setup.ts # SETUP as logic: the health models, advancement, dice and distance it offers, each model's starting shape, and the answers read from and written to a definition │ │ │ ├── wordsFeatures.ts # WORDS and PARTS as logic: terms and their forms, parts and what turning one off greys, building types, catalogues and currencies written back to a definition; a part's house rule (ONLY WITH), kept when the part is switched │ │ │ ├── dice.ts # The DICE tab as logic (6c2a): a system's own dice and symbols read and written back, three presets (dF, GOOD / GREAT / BAD, a d6 with a word), a die renamed, colored, its faces counted and each face a number and up to six symbols, symbols cancelling as a pair (old partners let go) and counting as another one step at a time (alsoChoices), removed off every face; COPY FROM THE TABLE'S DICE (numbers stay numbers, words become symbols); a face as the log writes it; a symbol's look set (withSymbolLook, a mark always kept for the log) and the pad's drawing a square at a time (withSquare, drawnAt, drawnSquares); more faces on a die numbered 1, 2, 3 carry its numbering on (6c3) diff --git a/backend/__tests__/catalogue_into_items.test.js b/backend/__tests__/catalogue_into_items.test.js index a5fb69e1..bd246efd 100644 --- a/backend/__tests__/catalogue_into_items.test.js +++ b/backend/__tests__/catalogue_into_items.test.js @@ -10,6 +10,8 @@ import { createRequire } from 'module'; import jwt from 'jsonwebtoken'; import { makeTestDb, get, run } from './helpers/testDb.js'; import { untilValue, drain } from './helpers/until.js'; +import express from 'express'; +import request from 'supertest'; process.env.JWT_SECRET = 'test-secret'; const require_ = createRequire(import.meta.url); @@ -20,6 +22,8 @@ const { checkDefinition } = require_('../systemBuilder/definition'); const store = require_('../shops/catalogueStore'); const runtime = require_('../systemBuilder/runtime'); const socketsFactory = (await import('../sockets/index.js')).default; +const systemsRoute = require_('../routes/systems.js'); +const catalogueDb = require_('../shops/catalogueDb'); 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' }] }; @@ -129,3 +133,63 @@ describe('at the table', () => { expect((await copies()).draft.items.list).toHaveLength(3); }); }); + +describe('on PUBLISH, the lines now exactly an item taken out of the file (8a7a4b)', () => { + const ID = 'sys_a74b0000a74b0000'; + const GM = jwt.sign({ id: 1, username: 'gm', role: 'admin', isTemporary: false }, 'test-secret'); + const RINGED = { ...DEF, items: { ...DEF.items, list: [...DEF.items.list, { id: 'ring', label: 'Ring of Might', type: 'gear', price: 5000, in_shops: false }] } }; + let db; + let app; + let emitted; + const lines = async () => (await new Promise((resolve, reject) => db.all('SELECT catalogue, name FROM shop_catalogues WHERE system = ? ORDER BY name', [ID], (e, r) => (e ? reject(e) : resolve(r))))); + const publish = () => request(app).post(`/api/systems/${ID}/publish`).set({ Authorization: `Bearer ${GM}` }).send({}); + + 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(RINGED); + 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)); + // The file: the Pistol exactly as the item is, the Hand Cannon no item yet, the Ring kept out of the shops. + await new Promise((resolve, reject) => catalogueDb.replaceCatalogues(db, ID, parse('[WEAPONS]\nname, price, damage\nPistol, 200, 2d6\nHand Cannon, 900, 3d6\n[gear]\nname, price\nRing of Might, 10\n', RINGED), (e) => (e ? reject(e) : resolve()))); + emitted = []; + app = express(); + app.use(express.json()); + app.use('/api/systems', systemsRoute(db, { emit: (event, data) => emitted.push({ event, data }) })); + }); + + it('the exact copy out, said by how many; a new line, and one naming an item kept out of the shops, kept', async () => { + const res = await publish(); + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(res.body.dropped).toBe(1); + expect(await lines()).toEqual([{ catalogue: 'type:weapons', name: 'Hand Cannon' }, { catalogue: 'type:gear', name: 'Ring of Might' }]); + // Again: nothing more to take out, nothing said. + const again = await publish(); + expect(again.body).not.toHaveProperty('dropped'); + expect(await lines()).toHaveLength(2); + }); + + it('a line made an item by ADD NEW LINES TO ITEMS leaves the file once that version is published', async () => { + const into = itemsFromLines(RINGED, parse('[WEAPONS]\nname, price, damage\nHand Cannon, 900, 3d6\n')); + const draft = { ...RINGED, items: { ...RINGED.items, list: [...RINGED.items.list, ...into.items] } }; + await run(db, 'UPDATE custom_systems SET draft = ? WHERE id = ?', [JSON.stringify(draft), ID]); + expect((await publish()).body.dropped).toBe(2); + expect(await lines()).toEqual([{ catalogue: 'type:gear', name: 'Ring of Might' }]); + }); + + it('the running game\'s shops told, their store reloaded without the copies; another game\'s shops left alone', async () => { + await new Promise((resolve) => catalogueDb.refresh(db, ID, resolve)); + expect(store.uploadedIn('type:weapons').map((e) => e.name).sort()).toEqual(['Hand Cannon', 'Pistol']); + await publish(); + expect(store.uploadedIn('type:weapons').map((e) => e.name)).toEqual(['Hand Cannon']); + expect(emitted).toContainEqual({ event: 'cataloguesChanged', data: { system: ID } }); + // Not the running game: its lines still go, but no shop is told. + store.clear(); + emitted.length = 0; + await run(db, "INSERT INTO shop_catalogues (system, catalogue, id, name, price, fields) VALUES (?, 'type:weapons', 'pistol', 'Pistol', 200, ?)", [ID, JSON.stringify({ damage: '2d6', price: 200 })]); + expect((await publish()).body.dropped).toBe(1); + expect(emitted.map((e) => e.event)).not.toContain('cataloguesChanged'); + }); +}); diff --git a/backend/__tests__/shop_items_on_sale.test.js b/backend/__tests__/shop_items_on_sale.test.js index b73a3675..0d7d56dc 100644 --- a/backend/__tests__/shop_items_on_sale.test.js +++ b/backend/__tests__/shop_items_on_sale.test.js @@ -166,6 +166,8 @@ describe('a catalogue file held against them (8a7a3c1)', () => { ]); expect(held.overrules).toEqual([{ line: 8, catalogue: 'type:armor', name: 'Leather Jacket', from: 50, to: 75 }]); expect(held.onSale).toBe(2); + // The exact copy, by its line's id, for a publish to take out (8a7a4b). + expect(held.copies).toEqual([{ catalogue: 'type:weapons', id: 'pistol' }]); }); it('a column apart, the price the same: it overrules the item\'s columns; a game without types of its own, nothing held', () => { @@ -173,7 +175,7 @@ describe('a catalogue file held against them (8a7a3c1)', () => { expect(held.overrules).toEqual([{ line: 3, catalogue: 'type:weapons', name: 'Pistol', from: 200, to: 200 }]); expect(held.leftOut).toEqual([]); const sections = { gear: [{ id: 'rope', name: 'Rope', price: 1, fields: {} }] }; - expect(againstItems(sections, { ...DEF, items: { list: DEF.items.list } })).toEqual({ sections, leftOut: [], overrules: [], onSale: 0 }); + expect(againstItems(sections, { ...DEF, items: { list: DEF.items.list } })).toEqual({ sections, leftOut: [], overrules: [], onSale: 0, copies: [] }); }); }); diff --git a/backend/routes/systems.js b/backend/routes/systems.js index f6aa44ca..72103fbc 100644 --- a/backend/routes/systems.js +++ b/backend/routes/systems.js @@ -12,6 +12,8 @@ const { zipBody: readZipBody } = require('../middleware/jsonBody'); const { previewPublish } = require('../systemBuilder/publishPreview'); const { buildCustomTemplate } = require('../sheets/pdfTemplate'); const runtime = require('../systemBuilder/runtime'); +const catalogueDb = require('../shops/catalogueDb'); +const shopPrices = require('../shops/catalogueStore'); const { checkDefinition, NEW_SYSTEM_SEEN } = require('../systemBuilder/definition'); const { previewDerived } = require('../systemBuilder/derived'); const { rankedOf } = require('../systemBuilder/ranks'); @@ -221,12 +223,21 @@ module.exports = (db, io = null) => { router.post('/:id/publish', gm, (req, res) => { store.publishSystem(db, req.params.id, (err, done) => { if (err) return answer(res, err); - runtime.refresh(db, req.params.id, () => syncAllTokenMax(db, req.params.id, (moved) => { - // A new version may change what a feature adds to the token's maximum (7a5a3, tokenMax.js). - if (io && moved) io.emit('dataUpdated', { isRhombusOnly: true }); - if (io) io.emit('customSystemChanged', { id: req.params.id }); - answer(res, null, done); - })); + runtime.refresh(db, req.params.id, () => { + // Its catalogue lines now exactly one of its items taken out (8a7a4b), the items selling themselves; the running + // game's shops told, so their shelves come again without the copies. + catalogueDb.dropItemCopies(db, req.params.id, runtime.definitionOf(req.params.id), (dErr, dropped) => { + const reloaded = () => syncAllTokenMax(db, req.params.id, (moved) => { + // A new version may change what a feature adds to the token's maximum (7a5a3, tokenMax.js). + if (io && moved) io.emit('dataUpdated', { isRhombusOnly: true }); + if (io) io.emit('customSystemChanged', { id: req.params.id }); + answer(res, null, { ...done, ...(!dErr && dropped ? { dropped } : {}) }); + }); + if (dErr || !dropped) return reloaded(); + if (shopPrices.systemLoaded() !== req.params.id) return reloaded(); + catalogueDb.refresh(db, req.params.id, () => { if (io) io.emit('cataloguesChanged', { system: req.params.id }); reloaded(); }); + }); + }); }); }); diff --git a/backend/shops/catalogueDb.js b/backend/shops/catalogueDb.js index 7b4c98a2..a935ac45 100644 --- a/backend/shops/catalogueDb.js +++ b/backend/shops/catalogueDb.js @@ -6,6 +6,7 @@ // database, and it is the only piece a frontend test must never reach. const store = require('./catalogueStore'); +const { againstItems } = require('./ownItems'); /** Rows out of the table, as the store wants them: catalogue -> entries. */ const shape = (rows) => { @@ -113,4 +114,29 @@ const clearCatalogue = (db, system, catalogue, cb) => (err) => cb(err || null), ); -module.exports = { read, refresh, replaceCatalogues, clearCatalogue, shape }; +/** + * A system's catalogue lines that are now exactly one of its items taken out of the file (8a7a4b; decided 2026-11-21, mockup + * types-in-shops.html, question 12): called when the system is published, so a line ADD NEW LINES TO ITEMS made an item, or + * any line the GM's items now match in name, price and every column, isn't kept twice. Lines naming an item kept out of the + * shops stay: turned back on, it is sold from them again. cb(err, how many were taken out). + */ +const dropItemCopies = (db, system, definition, cb) => { + read(db, system, (err, sections) => { + if (err) return cb(err); + const { copies } = againstItems(sections, definition); + if (!copies.length) return cb(null, 0); + const drop = async () => { + await q(db, 'BEGIN IMMEDIATE'); + try { + for (const { catalogue, id } of copies) await q(db, 'DELETE FROM shop_catalogues WHERE system = ? AND catalogue = ? AND id = ?', [system, catalogue, id]); + await q(db, 'COMMIT'); + } catch (e) { + await q(db, 'ROLLBACK').catch(() => {}); + throw e; + } + }; + drop().then(() => cb(null, copies.length), cb); + }); +}; + +module.exports = { read, refresh, replaceCatalogues, clearCatalogue, shape, dropItemCopies }; diff --git a/backend/shops/ownItems.js b/backend/shops/ownItems.js index 32f46f7d..0ac39704 100644 --- a/backend/shops/ownItems.js +++ b/backend/shops/ownItems.js @@ -62,12 +62,14 @@ const sameFields = (a, b) => { * A catalogue file's lines held against the game's own items (8a7a3c1; decided 2026-11-21, mockup types-in-shops.html, * questions 9 and 15): a line that is exactly an item IN SHOPS (its name, price and every column) is left out, the item * selling itself, so nothing is kept twice; a line naming an item turned off is left out, the shops never selling it; a line - * of an item's name otherwise overrules it, said. { sections to save, leftOut, overrules, onSale: the items on sale besides }. + * of an item's name otherwise overrules it, said. { sections to save, leftOut, overrules, onSale: the items on sale besides, + * copies: each exact copy's { catalogue, id }, which a publish takes out of the file (8a7a4b) }. */ const againstItems = (sections, definition) => { const stock = ownStock(definition); const leftOut = []; const overrules = []; + const copies = []; const kept = {}; for (const [catalogue, entries] of Object.entries(sections || {})) { const items = stock.catalogues[catalogue] || []; @@ -79,6 +81,7 @@ const againstItems = (sections, definition) => { if (!item) return true; if (item.price === e.price && sameFields(item.fields, e.fields)) { leftOut.push({ ...at, message: `already on ITEMS at ${item.price}, the same in every column: left out, as it sells itself` }); + copies.push({ catalogue, id: e.id }); return false; } overrules.push({ ...at, from: item.price, to: e.price }); @@ -86,7 +89,7 @@ const againstItems = (sections, definition) => { }); } const onSale = Object.values(stock.catalogues).reduce((n, list) => n + list.length, 0); - return { sections: kept, leftOut, overrules, onSale }; + return { sections: kept, leftOut, overrules, onSale, copies }; }; module.exports = { ITEM_PREFIX, ownStock, againstItems }; diff --git a/e2e/COVERAGE.md b/e2e/COVERAGE.md index 22169b36..9419335d 100644 --- a/e2e/COVERAGE.md +++ b/e2e/COVERAGE.md @@ -37,7 +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** | +| ADD NEW LINES TO ITEMS | a catalogue's new lines made items in the draft (8a7a4a), off to start; on PUBLISH the lines now exactly an item leave the file (8a7a4b) | `catalogue_into_items`, `CatalogueWindow`, `catalogueItems`, `BuilderScreen` | `catalogue-and-items` (the Hand Cannon into the draft, then out of the file once published) | **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 ceec6aee..e2fd6aa5 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. 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-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; published (8a7a4b), the Hand Cannon's line leaves the file (dropped 1) and DOWNLOAD CURRENT has it only behind a #. | | `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 c037df8d..9e5c58bc 100644 --- a/e2e/tests/catalogue-and-items.spec.ts +++ b/e2e/tests/catalogue-and-items.spec.ts @@ -7,7 +7,8 @@ import { signInAsGm, gmToken, runningSystem, openGameSystem, asGm } from './help // 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 #. 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. +// an item of WEAPONS in the builder's draft, priced 900, the running game untouched until a publish; published (8a7a4b), its +// catalogue line, now exactly the item, leaves the file and the item sells itself. const SYSTEM = (name: string) => ({ format: 1, name, core: { health: { model: 'pool' } }, @@ -75,4 +76,13 @@ test('a catalogue held against the game\'s items: one overruling, an exact copy expect(now).toMatch(/^Hand Cannon\s*, 900\s*, 3d6/m); expect(now).toMatch(/^# Cutlass\s*, 120\s*, 1d8/m); expect(now).not.toMatch(/Ring of Might/); + + // Published: the Hand Cannon's line, now exactly the item, taken out of the file, said by how many; the item sells itself. + const published = await asGm(request, gm, 'post', `/api/systems/${id}/publish`); + expect(published.dropped).toBe(1); + const [after] = await Promise.all([page.waitForEvent('download'), page.getByRole('button', { name: 'DOWNLOAD CURRENT', exact: true }).click()]); + const then = await readFile(await after.path(), 'utf8'); + expect(then).toMatch(/^# Hand Cannon\s*, 900\s*, 3d6/m); + expect(then).not.toMatch(/^Hand Cannon/m); + expect(then).toMatch(/^Pistol\s*, 260\s*, 2d6/m); }); diff --git a/frontend/src/components/BuilderScreen.tsx b/frontend/src/components/BuilderScreen.tsx index 3915a3fa..18504677 100644 --- a/frontend/src/components/BuilderScreen.tsx +++ b/frontend/src/components/BuilderScreen.tsx @@ -395,7 +395,7 @@ export function BuilderScreen({ token, systemId, startPage = 'setup', running, o } setPreview(null); setPage(back); - setStatus({ text: publishedMessage(r.value.version, running === systemId) }); + setStatus({ text: publishedMessage(r.value.version, running === systemId, r.value.dropped ?? 0) }); await load(); window.dispatchEvent(new Event(SYSTEMS_CHANGED_EVENT)); }; diff --git a/frontend/src/sheets/__tests__/builderSession.test.ts b/frontend/src/sheets/__tests__/builderSession.test.ts index 679dfb90..cc7635f5 100644 --- a/frontend/src/sheets/__tests__/builderSession.test.ts +++ b/frontend/src/sheets/__tests__/builderSession.test.ts @@ -202,6 +202,10 @@ describe('what it says', () => { expect(publishBlocked([PROBLEM, PROBLEM])).toBe('Fix these 2 problems before publishing.'); expect(publishedMessage(4, true)).toBe('Published v4. The game runs it from now on.'); expect(publishedMessage(1, false)).toBe('Published v1. It\'s ready to pick in the game-system picker.'); + // Catalogue lines now exactly one of its items taken out of the file (8a7a4b). + expect(publishedMessage(4, true, 1)).toBe('Published v4. The game runs it from now on. 1 catalogue line taken out: it\'s an item now and sells itself.'); + expect(publishedMessage(4, true, 3)).toBe('Published v4. The game runs it from now on. 3 catalogue lines taken out: they\'re items now and sell themselves.'); + expect(publishedMessage(4, true, 0)).toBe('Published v4. The game runs it from now on.'); }); it('the sidebar\'s pages, in order, each saying what it is for', () => { diff --git a/frontend/src/sheets/builderSession.ts b/frontend/src/sheets/builderSession.ts index c0cb0741..e71ea26f 100644 --- a/frontend/src/sheets/builderSession.ts +++ b/frontend/src/sheets/builderSession.ts @@ -134,8 +134,10 @@ export const publishBlocked = (problems: Problem[]): string | null => (problems.length === 0 ? null : `Fix ${problems.length === 1 ? 'this problem' : `these ${problems.length} problems`} before publishing.`); /** The line after PUBLISH. `running` says whether the game runs this system now. */ -export const publishedMessage = (version: number, running: boolean): string => - (running ? `Published v${version}. The game runs it from now on.` : `Published v${version}. It's ready to pick in the game-system picker.`); +export const publishedMessage = (version: number, running: boolean, dropped = 0): string => + (running ? `Published v${version}. The game runs it from now on.` : `Published v${version}. It's ready to pick in the game-system picker.`) + // Catalogue lines now exactly one of its items taken out of the file (8a7a4b). + + (dropped === 1 ? " 1 catalogue line taken out: it's an item now and sells itself." : dropped > 1 ? ` ${dropped} catalogue lines taken out: they're items now and sell themselves.` : ''); // ─── The sidebar ──────────────────────────────────────────────────────────── diff --git a/frontend/src/sheets/systemsApi.ts b/frontend/src/sheets/systemsApi.ts index 60371910..8558327d 100644 --- a/frontend/src/sheets/systemsApi.ts +++ b/frontend/src/sheets/systemsApi.ts @@ -220,7 +220,7 @@ export const systemsApi = (token: string, fetcher: typeof fetch = fetch) => { */ publishPreview: (systemId: string) => call(fetcher, token, `${id(systemId)}/publish-preview`), /** Make the stored draft what the game runs; refused, with `problems`, while it has any. */ - publish: (systemId: string) => call<{ version: number }>(fetcher, token, `${id(systemId)}/publish`, 'POST', {}), + publish: (systemId: string) => call<{ version: number; dropped?: number }>(fetcher, token, `${id(systemId)}/publish`, 'POST', {}), create: (name: string) => call<{ id: string }>(fetcher, token, '/api/systems', 'POST', { name }), /** * The built-in examples (4d1) or the genre starters (4d3) to copy: what each is called and