diff --git a/CHANGELOG.md b/CHANGELOG.md index 0da2f523..945db293 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -931,6 +931,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Under the hood +- **A game's own kinds of shop, on the server.** A system can now make shops of its own (an Apothecary, a Fence), each with a name and on or off, carried by the system file. An item type's SOLD AT can tick them, a building can be one, and it sells the types that tick it at their prices. Off, or in a game that doesn't make it, a building set to it is no shop. The builder's SOLD AT, + NEW SHOP and the BUILDING TYPE list come next. - **PLAYERS CHANGE GEAR, on the server.** A table setting (on to start) for systems with their own item types: switched off, the server keeps every column of a player's gear lines as it was saved, and a thing a player adds comes without column values, while their names, counts and where they carry things still change. The GM can always change them. The GAME tab's switch and the sheet's side come next. - **Who changed a gear line from its item, and when.** When a line named like one of a system's items is given a value of its own in a column (the Cutlass made 2d8), the server now notes who changed it and when: the player from their sheet, or the GM on a player's or an NPC's. It is worked out from what was saved before, never taken from the sheet, kept while the value stays, and dropped when it is put back to the item's. The sheet shows this as UNIQUE next. - **A stress test for the shops.** 200 items and a 1500-line catalogue, saved, sent to players, bought from with a 100-line cart and sold to with 300 lines at once, each within a time limit; and a 1000-line shelf opened, filtered and sorted in a real browser. diff --git a/README.md b/README.md index 7c68071e..caedca11 100644 --- a/README.md +++ b/README.md @@ -447,7 +447,7 @@ CITY_NET/ │ │ ├── sheet.js # A custom system's character sheet as data (tabs, header, sections of text/number/textarea/select fields with visibility, combat sensitivity, who edits it (the owner, or only the GM), max pairs and token/bank links) and its checks, a section able to wait on a house rule; a starter sheet for a system that has none. A section laid out 'choices' is the CHOICES block, drawn by the sheet itself; the starter sheet has one on its CHARACTER tab (listed first, the sheet opening on STATS: `opens`) after IDENTITY when the system has lists, named for the one list or CHOICES (7a3b1). A rests section (R3b): the starter sheet's RESTS, after CHOICES, when rests are finished on each sheet or there are recovery dice; a SPEND XP section, its own layout, on the starter sheet's CHARACTER where XP is spent (7f2c1) │ │ ├── terms.js # The glossary: the 13 terms a system may rename, their neutral defaults (for the builder), and ownWords, only the terms a system renamed (for the running game) │ │ ├── parts.js # The parts of the app a system can turn off (bank, shops, GIVE ITEM, vehicles...) and partOn(definition, part); nothing required, so the checks, the starter sheet and the runtime all use it -│ │ ├── buildings.js # A system's own names for the app's building types and shop catalogues, and which it turned off (never new ones); the section's checks, buildingOn / buildingName, and the render copy's part +│ │ ├── buildings.js # A system's own names for the app's building types and shop catalogues, and which it turned off (never new ones); the section's checks, buildingOn / buildingName, and the render copy's part; and the game's own kinds of shop (8a7b1a): buildings.shops, each an id and a name, perhaps off, checked (an id the app's types haven't got, each once, at most 20), ownShops, ownShopOf, shopKindsOf, a building type of the game on as it says and by its name, sent to the browser only where it makes some │ │ ├── currencies.js # A system's own money: the currencies section's checks, the shaped list (the first the main one; debt and negative off unless on), and an amount written with coins (12 gp 3 sp 4 cp), a symbol and decimals ($4.34, 1.234,56 €, ¥1,234), mirrored in frontend/src/sheets/currencies.ts; each currency's icon, one of CURRENCY_ICON's five or an uploaded /uploads/currency_icons file │ │ ├── bank.js # A system's bank settings: whether the bank window's celebrations run (off unless a custom system turns them on; built-ins keep them) and its own whale threshold in the main currency │ │ ├── core.js # A custom system's setup answers: the health model (one pool, two tracks, damage types, harm levels, wound count, hit locations, none) with its settings, advancement styles, common dice and distance unit, and their checks; the health part of the starter sheet each model gives (no answer = the one-pool starter every system had); the distance unit sent to the browser (feet where none was given) @@ -481,7 +481,7 @@ CITY_NET/ │ │ ├── healthFormula.js # MAX HEALTH: A FORMULA (7d4): what the formula comes to for a sheet, read as a derived value is (stats, formulas, levels), whole and never below 0; any formula of the sheet's worked out the same way (7d5a); @capacity readable (8a5a) │ │ ├── healthLevels.js # MAX HEALTH: PER LEVEL (7d5a): level 1 the full die, each level after what it kept or the average, EACH LEVEL ADDS read now, never less than 1 a level; the token's base; REROLL ALL, KEEP HIGHER, a level's gain kept outright (7d5c); ROLL TO BEAT, a pool or a die per level against the maximum, a gain of 0 kept (7d5d); each level saying how it was kept (rolled, set, cleared), level 1 set by the GM, a level averaging its own die (7d7b1); an uploaded sheet's maximum the base for its levels, and a whole upload's health (7d7c) │ │ ├── items.js # A system's items (7e2a): slots each character has so many of, items whose features need carrying, wearing or wearing in a slot, checked; at the table (7e3a): carried by a readied or stowed gear line of its name, WEAR and TAKE OFF, ATTUNE with a slot free or the GM's anyway, END, the GM's count for one character, what works; GIVE.EXE's list of them, each with what it needs and its words (itemsGivable, 7e3b); INSTALLS (7e4a): each costing against a stat or formula, ADDING TO it up to a limit or TAKING FROM it down to one, an item needing one with a COST; INSTALL with room or the GM's anyway, REMOVE, the line kept in the gear wherever it is, the cost one of its modifiers (overlaid, never written in), each install's cost, value and limit for the sheet; checks the item types and each item's type and values (8a1); encumbrance beside them, and an install's WEIGHS (8a5a); an item's PRICE and IN SHOPS, checked, one IN SHOPS needing a price (8a7a3a) -│ │ ├── itemTypes.js # Item types (8a1; approved mockup item-types, 2026-11-14): each type's columns, NUMBER (a unit), TEXT, DAMAGE, DICE, COUNT (a button, a rest that refills it, the items it reloads from) and PICK ONE (its words), checked; GEAR, WEIGHT and PRICE, where a system makes none; an item's values checked against its type's columns; the types as the sheet is shown them; a line of gear's type, values and counts, from the item it is named like or its own; linesOf, the gear read as the sheet stores it, shared with gearRolls, gearCounts and encumbrance; SOLD AT (8a7a2), the kinds of shop a type's lines are sold at, the General Store where unsaid, and the type shelves a kind of building sells (typeShelvesAt); an item's price (its own, else its type's PRICE column) and whether it is IN SHOPS, one saved before the switch by whether it has a price (8a7a3a); a type's band on the sheet, EQUIPPED, USABLE or PACK, PACK where unsaid (bandOf, G1) +│ │ ├── itemTypes.js # Item types (8a1; approved mockup item-types, 2026-11-14): each type's columns, NUMBER (a unit), TEXT, DAMAGE, DICE, COUNT (a button, a rest that refills it, the items it reloads from) and PICK ONE (its words), checked; GEAR, WEIGHT and PRICE, where a system makes none; an item's values checked against its type's columns; the types as the sheet is shown them; a line of gear's type, values and counts, from the item it is named like or its own; linesOf, the gear read as the sheet stores it, shared with gearRolls, gearCounts and encumbrance; SOLD AT (8a7a2), the kinds of shop a type's lines are sold at, the General Store where unsaid, and the type shelves a kind of building sells (typeShelvesAt); an item's price (its own, else its type's PRICE column) and whether it is IN SHOPS, one saved before the switch by whether it has a price (8a7a3a); a type's band on the sheet, EQUIPPED, USABLE or PACK, PACK where unsaid (bandOf, G1); SOLD AT may tick the game's own shops (8a7b1a) │ │ ├── uniqueLines.js # UNIQUE, the server's half (G5a; decided 2026-11-20): a gear line named like an item, of its type, with a column of its own that isn't the item's, is that item made unique; who changed each such column and when (`changed: { damage: { by, gm?, at } }`) worked out on every inventory write from what was stored, never from what the sheet sends; kept as it was, the writer's when changed, gone when put back; PLAYERS CHANGE GEAR (G6a): with the table's players_change_gear '0', keepColumns keeps a player's lines' column values as stored and a new line's none (pairLines finds the line each was) │ │ ├── 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 @@ -649,6 +649,7 @@ CITY_NET/ │ ├── system_builder_parts_money.test.js # The bank turned off: no money handler moves anything, no balance is told, checkout refuses with no_bank, bank-linked sheet fields (and a section left empty) leave the sheet; every account kept, back with the bank; the bank unchanged where it is on │ ├── system_builder_parts_shops.test.js # Shops under custom systems: open unless shops or the bank is off; building types, checkout (no_shops) and inventory sales follow; built-ins unchanged │ ├── system_builder_buildings.test.js # Building types and catalogues renamed or off: the section's checks, the render copy, the routes (only kept types, by the system's names; an off type cannot be given) and checkout (off type no shop, off catalogue not sold), back when turned on; built-ins unchanged +│ ├── system_builder_own_shops.test.js # The game's own shops (8a7b1a): checked, read, a building type of the game, SOLD AT ticking them and checked against the game, carried by the system file; listed for buildings after the app's, given to a building (not off, not unknown), selling the types that tick it, no shop off or in another game │ ├── system_builder_parts_vehicles.test.js # Vehicles turned off: the garage and its three catalogues off (even if asked for by name), told to the browser, back with vehicles on; built-ins and seating unchanged │ ├── system_builder_parts_cyberware.test.js # Cyberware turned off: the ripperdoc and its three catalogues off (even if asked for by name), with vehicles off the garage too, back with cyberware on; a custom sheet cannot have a cyberware table; built-ins unchanged │ ├── system_builder_parts_initiative.test.js # Initiative turned off: no tracker started (asked of the running game, not the message), no roll or NPC-side roll into its combat, ending still allowed; built-ins and a custom system that kept it unchanged diff --git a/backend/__tests__/system_builder_hostile_files.test.js b/backend/__tests__/system_builder_hostile_files.test.js index aeea2df5..fe2540a6 100644 --- a/backend/__tests__/system_builder_hostile_files.test.js +++ b/backend/__tests__/system_builder_hostile_files.test.js @@ -112,9 +112,9 @@ describe('the buildings section', () => { it('refuses a kind it does not have, whatever it is called', () => { const def = JSON.parse('{"format":1,"name":"X","buildings":{"constructor":{},"__proto__":{"a":1},"toString":{}}}'); expect(problemsOf(def)).toEqual([ - 'buildings constructor: Only "types" and "catalogues" are set here', - 'buildings __proto__: Only "types" and "catalogues" are set here', - 'buildings toString: Only "types" and "catalogues" are set here', + 'buildings constructor: Only "types", "catalogues" and "shops" are set here', + 'buildings __proto__: Only "types", "catalogues" and "shops" are set here', + 'buildings toString: Only "types", "catalogues" and "shops" are set here', ]); }); }); diff --git a/backend/__tests__/system_builder_own_shops.test.js b/backend/__tests__/system_builder_own_shops.test.js new file mode 100644 index 00000000..8613b058 --- /dev/null +++ b/backend/__tests__/system_builder_own_shops.test.js @@ -0,0 +1,185 @@ +/** + * The game's own kinds of shop (8a7b1a; approved mockup docs/mockups/types-in-shops.html, 2026-11-21, the user: "in Item Type + * we have a section to add what store sells this item ... then add that store to the building Type list"). A GM makes an + * Apothecary: checked, carried by the system file, ticked by a type's SOLD AT, listed for buildings after the app's own, and a + * building set to it sells the types that tick it. Off, or in another game, it is no shop. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import jwt from 'jsonwebtoken'; +import { createRequire } from 'module'; +import { makeTestDb, get, run } from './helpers/testDb.js'; +import { untilValue, drain } from './helpers/until.js'; +import locationsRouteFactory from '../routes/locations.js'; + +process.env.JWT_SECRET = 'test-secret'; +const ADMIN = jwt.sign({ id: 1, username: 'gm', role: 'admin', isTemporary: false }, 'test-secret'); +const require_ = createRequire(import.meta.url); +const { checkDefinition } = require_('../systemBuilder/definition'); +const { ownShops, ownShopOf, shopKindsOf, buildingOn, buildingName, ownBuildings, SHOPS_MOST } = require_('../systemBuilder/buildings'); +const { soldAt, typeShelvesAt, typesShown } = require_('../systemBuilder/itemTypes'); +const citysys = require_('../systemBuilder/citysys'); +const store = require_('../shops/catalogueStore'); +const runtime = require_('../systemBuilder/runtime'); +const socketsFactory = (await import('../sockets/index.js')).default; + +const POTIONS = { id: 'potions', label: 'POTIONS', one: 'Potion', columns: [{ id: 'heals', label: 'HEALS', kind: 'dice' }] }; +const HERBAL = (shops = [{ id: 'apothecary', name: 'Apothecary' }], soldAtList = ['apothecary']) => ({ + format: 1, name: 'Herbal', core: { health: { model: 'pool' } }, + stats: [{ id: 'abilities', label: 'ABILITIES', stats: [{ id: 'might', label: 'Might' }] }], + buildings: { shops }, + items: { types: [{ ...POTIONS, sold_at: soldAtList }], list: [{ id: 'draught', label: 'Healing Draught', type: 'potions', values: { heals: '2d4' }, price: 40 }] }, +}); +const problemsOf = (shops) => checkDefinition({ format: 1, name: 'A', buildings: { shops } }).problems; + +describe('checked', () => { + it('a list of shops, each an id and a name, perhaps off', () => { + expect(problemsOf([{ id: 'apothecary', name: 'Apothecary' }, { id: 'fence', name: 'Fence', on: false }])).toEqual([]); + expect(problemsOf([])).toEqual([]); + }); + + it('names whatever it can\'t take', () => { + expect(problemsOf({})).toEqual([{ where: 'buildings shops', message: 'A list of the shops this game makes' }]); + expect(problemsOf(['apothecary'])).toEqual([{ where: 'buildings shop 1', message: 'Must say an id and a name' }]); + expect(problemsOf([{ id: 'Apothecary!', name: 'A' }])).toEqual([{ where: 'buildings shop 1, id', message: 'Lowercase letters, digits and _, starting with a letter' }]); + expect(problemsOf([{ id: 'gun_shop', name: 'Guns' }])).toEqual([{ where: 'buildings shop 1, id', message: 'The app has a building type called gun_shop: call it something else' }]); + expect(problemsOf([{ id: 'fence', name: 'Fence' }, { id: 'fence', name: 'Fence too' }])).toEqual([{ where: 'buildings shop 2, id', message: 'Two shops called fence' }]); + expect(problemsOf([{ id: 'fence', name: ' ' }])).toEqual([{ where: 'buildings shop 1, name', message: 'Must be some text' }]); + expect(problemsOf([{ id: 'fence', name: 'x'.repeat(41) }])).toEqual([{ where: 'buildings shop 1, name', message: 'At most 40 characters' }]); + expect(problemsOf([{ id: 'fence', name: 'Fence', on: 'no' }])).toEqual([{ where: 'buildings shop 1, on', message: 'Must be true or false' }]); + expect(problemsOf([{ id: 'fence', name: 'Fence', sells: ['gear'] }])).toEqual([{ where: 'buildings shop 1, sells', message: 'Only "id", "name" and "on" are set here' }]); + expect(SHOPS_MOST).toBe(20); + const many = Array.from({ length: 21 }, (_, n) => ({ id: `shop_${n}`, name: `Shop ${n}` })); + expect(problemsOf(many)).toEqual([{ where: 'buildings shops', message: 'At most 20 shops of its own' }]); + }); +}); + +describe('the game\'s own shops, read', () => { + const def = HERBAL([{ id: 'apothecary', name: ' Apothecary ' }, { id: 'fence', name: 'Fence', on: false }, { id: 'gun_shop', name: 'Clash' }, 'junk']); + + it('those well formed, trimmed, on unless said off; by id; every kind of shop the game has', () => { + expect(ownShops(def)).toEqual([{ id: 'apothecary', name: 'Apothecary', on: true }, { id: 'fence', name: 'Fence', on: false }]); + expect(ownShopOf(def, 'fence')).toEqual({ id: 'fence', name: 'Fence', on: false }); + expect(ownShopOf(def, 'tavern')).toBeNull(); + expect(ownShops({ name: 'A' })).toEqual([]); + expect(shopKindsOf(def).slice(-2)).toEqual(['apothecary', 'fence']); + expect(shopKindsOf(def)).toContain('general_store'); + }); + + it('a building type of the game: on as it says, by its name; sent to the browser only where it has some', () => { + expect(buildingOn(def, 'types', 'apothecary')).toBe(true); + expect(buildingOn(def, 'types', 'fence')).toBe(false); + expect(buildingName(def, 'types', 'apothecary')).toBe('Apothecary'); + expect(ownBuildings(def).shops).toEqual(ownShops(def)); + expect(ownBuildings({ name: 'A' })).not.toHaveProperty('shops'); + }); +}); + +describe('SOLD AT the game\'s own shops', () => { + it('ticked where the game makes it; not where the game is not said, nor in another game; the shelf of its building', () => { + const def = HERBAL(); + const type = def.items.types[0]; + expect(soldAt(type, def)).toEqual(['apothecary']); + // Told nothing of the game, only the app's shops count. + expect(soldAt(type)).toEqual([]); + expect(soldAt(type, HERBAL([]))).toEqual([]); + expect(typeShelvesAt(def, 'apothecary')).toEqual(['type:potions']); + expect(typeShelvesAt(def, 'general_store')).toEqual([]); + expect(typesShown(def)[0].sold_at).toEqual(['apothecary']); + }); + + it('checked against the game\'s own: one it makes is fine, one it doesn\'t is said', () => { + const soldProblems = (def) => checkDefinition(def).problems.filter((p) => /sold_at/.test(p.where)); + expect(soldProblems(HERBAL())).toEqual([]); + expect(soldProblems(HERBAL([]))).toEqual([{ where: 'type potions, sold_at 1', message: 'No kind of shop is called apothecary' }]); + }); + + it('carried by the system file, exported and read back unchanged', () => { + const definition = HERBAL([{ id: 'apothecary', name: 'Apothecary' }, { id: 'fence', name: 'Fence', on: false }]); + const read = citysys.readFile(JSON.stringify(citysys.buildFile({ definition, version: 1, origin: 'sys_herbalherbalherba' }))); + expect(read.problems, JSON.stringify(read.problems)).toEqual([]); + expect(read.file.definition.buildings.shops).toEqual(definition.buildings.shops); + expect(read.file.definition.items.types[0].sold_at).toEqual(['apothecary']); + }); +}); + +describe('at the table', () => { + const ID = 'sys_herbalherbalherba'; + let db; + const install = async (definition) => { + const text = JSON.stringify(definition); + await run(db, 'DELETE FROM custom_systems WHERE id = ?', [ID]); + await run(db, 'INSERT INTO custom_systems (id, name, draft, published, version) VALUES (?, ?, ?, ?, 1)', [ID, 'Herbal', text, text]); + await new Promise((resolve) => runtime.load(db, resolve)); + }; + const app = () => { + const a = express(); + a.use(express.json()); + a.use('/api/locations', locationsRouteFactory(db, { emit: () => {} }, { emitUpdate: () => {}, recordAction: () => {} })); + return a; + }; + const give = (id, type) => request(app()).patch(`/api/locations/${id}/building-type`).set('Authorization', `Bearer ${ADMIN}`).send({ building_type: type }); + const stall = async (type = null) => (await run(db, "INSERT INTO locations (name, x, y, z, shape, building_type) VALUES ('Stall', 0, 0, 0, 'box', ?)", [type])).lastID; + const boot = async (who) => { + const emitted = []; + let connect; + socketsFactory({ on: (e, cb) => { if (e === 'connection') connect = cb; }, emit: (event, data) => emitted.push({ event, data }), to: () => ({ emit: () => {} }) }, + db, { elevatedUsers: new Set(), emitUpdate: vi.fn(), recordAction: vi.fn() }); + const handlers = {}; + connect({ id: `os-${who}-${Math.random()}`, on: (e, fn) => { handlers[e] = fn; }, emit: (event, data) => emitted.push({ event, data }), broadcast: { emit: () => {} }, use: () => {}, join: () => {} }); + handlers.identify(who); + await drain(db); + return { handlers, emitted }; + }; + const checkout = async (who, locationId, more) => { + who.handlers.checkoutShop({ locationId, ...more }); + return (await untilValue(() => [...who.emitted].reverse().find((e) => e.event === 'shopCheckout'), Boolean, { label: 'shopCheckout' })).data; + }; + + 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))`); + await install(HERBAL([{ id: 'apothecary', name: 'Apothecary' }, { id: 'fence', name: 'Fence', on: false }])); + await run(db, "INSERT INTO global_settings (key, value) VALUES ('game_system', ?)", [ID]); + await run(db, 'INSERT INTO bank_accounts (username, system, balance, debt) VALUES (?, ?, 100, 0)', ['kes', ID]); + await run(db, 'INSERT INTO character_sheets (username, system, data, is_npc) VALUES (?, ?, ?, 0)', ['kes', ID, JSON.stringify({ inventory: '[]' })]); + }); + + it('listed for buildings after the app\'s, marked its own, an off one left out', async () => { + const listed = (await request(app()).get('/api/locations/building-types')).body; + expect(listed.slice(-1)).toEqual([{ id: 'apothecary', label: 'Apothecary', shop: true, sells: [], own: true }]); + expect(listed.some((t) => t.id === 'fence')).toBe(false); + expect(listed.findIndex((t) => t.id === 'general_store')).toBeLessThan(listed.findIndex((t) => t.id === 'apothecary')); + }); + + it('a building can be one; not one turned off, nor one no game makes', async () => { + const id = await stall(); + expect((await give(id, 'apothecary')).status).toBe(200); + expect((await get(db, 'SELECT building_type FROM locations WHERE id = ?', [id])).building_type).toBe('apothecary'); + expect((await give(id, 'fence')).status).toBe(409); + expect((await give(id, 'tavern')).status).toBe(400); + }); + + it('sells the types that tick it, at their price; the General Store doesn\'t; off, or in another game, it is no shop', async () => { + const shop = await stall('apothecary'); + const goods = await stall('general_store'); + const kes = await boot('kes'); + const buy = { buys: [{ catalogue: 'type:potions', itemId: 'item:draught', qty: 1 }] }; + expect(await checkout(kes, shop, buy)).toMatchObject({ ok: true, buys: [{ catalogue: 'type:potions', itemId: 'item:draught', qty: 1, price: 40 }] }); + expect((await get(db, 'SELECT balance FROM bank_accounts WHERE username = ?', ['kes'])).balance).toBe(60); + kes.emitted.length = 0; + expect(await checkout(kes, goods, buy)).toMatchObject({ ok: false, reason: 'not_sold' }); + // Turned off: the building keeps its type, but is no shop. + await install(HERBAL([{ id: 'apothecary', name: 'Apothecary', on: false }])); + kes.emitted.length = 0; + expect(await checkout(kes, shop, buy)).toMatchObject({ ok: false, reason: 'no_shop' }); + // Another game, which makes no Apothecary: nothing sold there. + await install({ ...HERBAL([]), items: { types: [{ ...POTIONS, sold_at: [] }], list: [] } }); + kes.emitted.length = 0; + expect((await checkout(kes, shop, buy)).ok).toBe(false); + }); +}); diff --git a/backend/routes/locations.js b/backend/routes/locations.js index 980ce099..7730145b 100644 --- a/backend/routes/locations.js +++ b/backend/routes/locations.js @@ -8,6 +8,7 @@ const { DEFAULT_SYSTEM, applyDerived } = require('../sheets/templates'); const customSystems = require('../systemBuilder/runtime'); const { applyHealthAction } = require('../systemBuilder/health'); const { BUILDING_TYPES, isValidType } = require('../buildingTypes'); +const { ownShops, ownShopOf } = require('../systemBuilder/buildings'); const { readPct } = require('../shops/buyback'); const { shopsOpen } = require('../shops/availability'); const { selectByIds, deleteByIds } = require('../bulk'); @@ -159,9 +160,13 @@ module.exports = (db, io, { emitUpdate, recordAction }) => { * game has, by its own names (a custom system can rename and turn off types, buildings.js). */ router.get('/building-types', (req, res) => - withShopSystem(res, (system) => res.json(BUILDING_TYPES - .filter((t) => customSystems.buildingIn(system, 'types', t.id)) - .map((t) => ({ ...t, label: customSystems.buildingNameIn(system, 'types', t.id) || t.label }))))); + withShopSystem(res, (system) => res.json([ + ...BUILDING_TYPES + .filter((t) => customSystems.buildingIn(system, 'types', t.id)) + .map((t) => ({ ...t, label: customSystems.buildingNameIn(system, 'types', t.id) || t.label })), + // The game's own shops (8a7b), after the app's, marked as its own; selling only the types that tick them. + ...ownShops(customSystems.definitionOf(system)).filter((s) => s.on).map((s) => ({ id: s.id, label: s.name, shop: true, sells: [], own: true })), + ]))); /** * What a building is for. @@ -174,7 +179,8 @@ module.exports = (db, io, { emitUpdate, recordAction }) => { const { building_type, buyback_pct } = req.body; // A value nobody recognises would put a SHOP button on a building that cannot sell // anything, so it is refused rather than stored and puzzled over later. - if (!isValidType(building_type)) return res.status(400).json({ error: 'Unknown building type' }); + // The app's types, or one of the running game's own shops (8a7b). + if (!isValidType(building_type) && !ownShopOf(customSystems.definitionOf(system), building_type)) return res.status(400).json({ error: 'Unknown building type' }); const next = building_type === '' || building_type === undefined ? null : building_type; diff --git a/backend/systemBuilder/buildings.js b/backend/systemBuilder/buildings.js index 933c661a..68a38e33 100644 --- a/backend/systemBuilder/buildings.js +++ b/backend/systemBuilder/buildings.js @@ -17,6 +17,13 @@ // // Its own module, needing only the vocabulary, so the definition checks and the running game // can both use it without a circle. +// +// The game's own kinds of shop (8a7b; approved mockup docs/mockups/types-in-shops.html, 2026-11-21, the user: "in Item Type we +// have a section to add what store sells this item ... then add that store to the building Type list"): a GM makes an +// Apothecary or a Fence, named as they like, which an item type's SOLD AT can tick and a building can be. It sells only the +// types that tick it, in the General Store's look. Another game hasn't got it: a building set to it is no shop there. +// +// buildings: { shops: [{ id: 'apothecary', name: 'Apothecary' }, { id: 'fence', name: 'Fence', on: false }] } const { BUILDING_TYPES, CATALOGUES, shelvedCatalogues, isShop } = require('../buildingTypes'); const { partOn } = require('./parts'); @@ -25,6 +32,11 @@ const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v); /** The longest name a system may give a type or catalogue: the same as one glossary word. */ const NAME_LIMIT = 40; +/** The most shops of its own a game makes. */ +const SHOPS_MOST = 20; +/** A shop's id: made from its name when made, fixed after, as items' and types' are. */ +const SHOP_ID = /^[a-z][a-z0-9_]{0,63}$/; +const SHOP_KEYS = ['id', 'name', 'on']; const KINDS = { types: new Set(BUILDING_TYPES.map((t) => t.id)), @@ -39,9 +51,11 @@ const checkBuildings = (buildings, problems, currencyIds = []) => { if (buildings === undefined) return; if (!isPlainObject(buildings)) { problems.push({ where: 'buildings', message: 'Must be a set of types and catalogues' }); return; } for (const [kind, entries] of Object.entries(buildings)) { + // The game's own kinds of shop (8a7b): a list of its own. + if (kind === 'shops') { checkShops(entries, problems); continue; } // Own keys only: a file's "constructor" or "__proto__" is a kind like any other, and refused. const ids = Object.prototype.hasOwnProperty.call(KINDS, kind) ? KINDS[kind] : null; - if (!ids) { problems.push({ where: `buildings ${kind}`, message: 'Only "types" and "catalogues" are set here' }); continue; } + if (!ids) { problems.push({ where: `buildings ${kind}`, message: 'Only "types", "catalogues" and "shops" are set here' }); continue; } if (!isPlainObject(entries)) { problems.push({ where: `buildings ${kind}`, message: 'Must be a set of ids' }); continue; } for (const [id, setting] of Object.entries(entries)) { const where = `buildings ${kind} ${id}`; @@ -64,6 +78,40 @@ const checkBuildings = (buildings, problems, currencyIds = []) => { } }; +/** Problems with the game's own kinds of shop (8a7b), pushed onto `problems`. */ +const checkShops = (shops, problems) => { + if (!Array.isArray(shops)) { problems.push({ where: 'buildings shops', message: 'A list of the shops this game makes' }); return; } + if (shops.length > SHOPS_MOST) problems.push({ where: 'buildings shops', message: `At most ${SHOPS_MOST} shops of its own` }); + const seen = new Set(); + shops.forEach((shop, n) => { + const where = `buildings shop ${n + 1}`; + if (!isPlainObject(shop)) { problems.push({ where, message: 'Must say an id and a name' }); return; } + for (const key of Object.keys(shop)) if (!SHOP_KEYS.includes(key)) problems.push({ where: `${where}, ${key}`, message: 'Only "id", "name" and "on" are set here' }); + if (typeof shop.id !== 'string' || !SHOP_ID.test(shop.id)) problems.push({ where: `${where}, id`, message: 'Lowercase letters, digits and _, starting with a letter' }); + else if (KINDS.types.has(shop.id)) problems.push({ where: `${where}, id`, message: `The app has a building type called ${shop.id}: call it something else` }); + else if (seen.has(shop.id)) problems.push({ where: `${where}, id`, message: `Two shops called ${shop.id}` }); + else seen.add(shop.id); + if (typeof shop.name !== 'string' || !shop.name.trim()) problems.push({ where: `${where}, name`, message: 'Must be some text' }); + else if (shop.name.trim().length > NAME_LIMIT) problems.push({ where: `${where}, name`, message: `At most ${NAME_LIMIT} characters` }); + if (shop.on !== undefined && typeof shop.on !== 'boolean') problems.push({ where: `${where}, on`, message: 'Must be true or false' }); + }); +}; + +/** The game's own kinds of shop (8a7b), those well formed, in its order: { id, name, on }. None for a game with none. */ +const ownShops = (definition) => { + const list = definition && isPlainObject(definition.buildings) && Array.isArray(definition.buildings.shops) ? definition.buildings.shops : []; + const seen = new Set(); + return list.filter((s) => isPlainObject(s) && typeof s.id === 'string' && SHOP_ID.test(s.id) && !KINDS.types.has(s.id) + && typeof s.name === 'string' && s.name.trim() && !seen.has(s.id) && seen.add(s.id)) + .map((s) => ({ id: s.id, name: s.name.trim().slice(0, NAME_LIMIT), on: s.on !== false })); +}; + +/** The game's own kind of shop by id (8a7b), or null where it has none of that id. */ +const ownShopOf = (definition, id) => ownShops(definition).find((s) => s.id === String(id || '')) || null; + +/** Every kind of shop this game has the ids of (8a7b): the app's, and its own. What SOLD AT may tick. */ +const shopKindsOf = (definition) => [...BUILDING_TYPES.filter((t) => t.shop).map((t) => t.id), ...ownShops(definition).map((s) => s.id)]; + const settingOf = (definition, kind, id) => { const section = definition && isPlainObject(definition.buildings) ? definition.buildings[kind] : undefined; const setting = isPlainObject(section) ? section[String(id || '')] : undefined; @@ -89,6 +137,9 @@ const catalogueOn = (definition, id) => (settingOf(definition, 'catalogues', id) */ const buildingOn = (definition, kind, id) => { if (kind === 'catalogues') return catalogueOn(definition, id); + // One of the game's own shops (8a7b): on unless it says off. + const own = ownShopOf(definition, id); + if (own) return own.on; if ((settingOf(definition, 'types', id) || {}).on === false) return false; const shelves = isShop(id) ? shelvedCatalogues(id) : []; return !shelves.length || shelves.some((c) => catalogueOn(definition, c)); @@ -108,6 +159,9 @@ const catalogueCurrency = (definition, id) => { /** The system's own name for a type or catalogue, or null where it kept the app's. */ const buildingName = (definition, kind, id) => { + // One of the game's own shops (8a7b): its name, the only one it has. + const own = kind === 'types' ? ownShopOf(definition, id) : null; + if (own) return own.name; const name = (settingOf(definition, kind, id) || {}).name; return typeof name === 'string' && name.trim() ? name.trim() : null; }; @@ -128,7 +182,9 @@ const ownBuildings = (definition) => { if (name || !on || currency) out[kind][id] = { ...(name ? { name } : {}), ...(on ? {} : { on: false }), ...(currency ? { currency } : {}) }; } } - return out; + // And the game's own shops (8a7b), each as it is, for SOLD AT and the BUILDING TYPE list: only where it makes some. + const shops = ownShops(definition); + return shops.length ? { ...out, shops } : out; }; -module.exports = { checkBuildings, buildingOn, buildingName, catalogueCurrency, ownBuildings, NAME_LIMIT }; +module.exports = { checkBuildings, buildingOn, buildingName, catalogueCurrency, ownBuildings, ownShops, ownShopOf, shopKindsOf, NAME_LIMIT, SHOPS_MOST }; diff --git a/backend/systemBuilder/itemTypes.js b/backend/systemBuilder/itemTypes.js index 0b603ee6..75a8d965 100644 --- a/backend/systemBuilder/itemTypes.js +++ b/backend/systemBuilder/itemTypes.js @@ -26,6 +26,7 @@ const { boxProblem } = require('./tierRolls'); const { BUILDING_TYPES } = require('../buildingTypes'); +const { shopKindsOf } = require('./buildings'); const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v); const list = (v) => (Array.isArray(v) ? v : []); @@ -74,11 +75,15 @@ const SHOP_TYPES = BUILDING_TYPES.filter((t) => t.shop).map((t) => t.id); const DEFAULT_SOLD_AT = ['general_store']; /** The kinds of shop a type's lines are sold at (8a7a2; decided 2026-11-20): what it says, else the General Store. */ -const soldAt = (type) => (Array.isArray(type && type.sold_at) ? type.sold_at.filter((id) => SHOP_TYPES.includes(id)) : DEFAULT_SOLD_AT); +// The game's own shops (8a7b) count where the definition is given: they are its alone; told no game, the app's six. +const soldAt = (type, definition) => { + const kinds = shopKindsOf(definition); + return Array.isArray(type && type.sold_at) ? type.sold_at.filter((id) => kinds.includes(id)) : DEFAULT_SOLD_AT; +}; /** The shelves of the system's own types a kind of building sells (8a7a2): `type:` for each sold at it. None without types of its own. */ const typeShelvesAt = (definition, buildingType) => (ownTypes(definition) - ? typesOf(definition).filter((t) => soldAt(t).includes(buildingType)).map((t) => `type:${t.id}`) : []); + ? typesOf(definition).filter((t) => soldAt(t, definition).includes(buildingType)).map((t) => `type:${t.id}`) : []); /** The type an item or a line is: the one it names, or the first. */ const typeNamed = (definition, id) => { const types = typesOf(definition); return types.find((t) => t.id === id) || types[0]; }; @@ -124,7 +129,7 @@ const checkTypes = (definition, problems, { text, keys, labelMost, itemIds = new if (t.sold_at !== undefined) { if (!Array.isArray(t.sold_at)) problems.push({ where: `${where}, sold_at`, message: 'A list of the kinds of shop that sell it' }); else t.sold_at.forEach((id, n) => { - if (!SHOP_TYPES.includes(id)) problems.push({ where: `${where}, sold_at ${n + 1}`, message: `No kind of shop is called ${String(id)}` }); + if (!shopKindsOf(definition).includes(id)) problems.push({ where: `${where}, sold_at ${n + 1}`, message: `No kind of shop is called ${String(id)}` }); else if (t.sold_at.indexOf(id) !== n) problems.push({ where: `${where}, sold_at ${n + 1}`, message: 'Said twice' }); }); } @@ -184,7 +189,7 @@ const typesShown = (definition, items = []) => { return typesOf(definition).map((t) => ({ id: t.id, label: t.label || t.id, one: t.one || t.label || t.id, // The kinds of shop that sell it, the General Store where unsaid (8a7a2): the shop window's shelves follow it. - sold_at: soldAt(t), + sold_at: soldAt(t, definition), // Its band on the GEAR tab (G1), PACK where unsaid. on_sheet: bandOf(t), columns: t.columns.map((c) => ({