Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 6 additions & 4 deletions README.md

Large diffs are not rendered by default.

131 changes: 131 additions & 0 deletions backend/__tests__/catalogue_into_items.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});
33 changes: 30 additions & 3 deletions backend/sockets/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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);
Expand All @@ -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 } }
: {};
})(),
});
};

Expand Down Expand Up @@ -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 }));
});
});
});
Expand Down
79 changes: 79 additions & 0 deletions backend/systemBuilder/itemsFromCatalogue.js
Original file line number Diff line number Diff line change
@@ -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 };
Loading
Loading