diff --git a/CHANGELOG.md b/CHANGELOG.md index d0b414a5..d2332af4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -106,6 +106,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added +- **A game's own shops on the map.** BUILDING TYPE now lists the shops your game made (an Apothecary, a Fence) first, under THIS GAME'S SHOPS, then the app's under SHOPS and its other buildings under OTHER BUILDINGS, in every game. A building set to one gets a SHOP button, its window named as the game names it and selling the item types SOLD AT it. A shop that sells nothing but buys anything opens on SELL, and its BUY folder says it only buys. A building keeps another game's own shop when it is saved again. - **SOLD AT on an item type, and + NEW SHOP.** On the builder's ITEMS page, each type now shows the game's shops as buttons, by what this game calls them: tick the kinds of shop that sell its lines, or none to have it only given. Type a name into + NEW SHOP (an Apothecary, a Fence) to make a kind of shop of your game's own, shown dashed and ticked. A type from a preset starts at its shop: WEAPON the Gun Shop, ARMOR the Armorer, CONSUMABLE the Clinic, GEAR the General Store; SPELL is sold nowhere, with a Magic Shop ready to ADD. - **PLAYERS CHANGE GEAR.** A new switch on the GAME tab's house rules, on to start, for systems with their own item types. Switched off, only the GM changes the columns of a player's gear (a weapon's DAMAGE, a potion's HEALS): the player's card shows them but can't change them, and says "ONLY THE GM CHANGES THESE AT THIS TABLE". Players still name, count, move, add and remove their things, and the GM can always change anything. - **UNIQUE on GEAR.** A thing changed from the item it is named after (the Cutlass made 2d8) now says UNIQUE on its line; hover it for the item's own value and who changed it, and when (a player by name, or the GM). In its card, each column made its own says UNIQUE with the item's value beside it and a THE ITEM'S button to put it back. Type unique in FIND to list them. SHEET.EXE and the sheet's own tab are the same. diff --git a/README.md b/README.md index 1da9f598..a3b1f893 100644 --- a/README.md +++ b/README.md @@ -350,7 +350,7 @@ CITY_NET/ │ │ └── rateLimit.js # A sliding per-caller ceiling, for the one open route that spends our outbound requests on an anonymous caller's say-so. Bounded in memory, since the key is whoever is asking; evicts the least recently seen, so it forgives rather than blocks │ ├── routes/ │ │ ├── admin.js # Admin-only REST endpoints; undo covers locations, roads, signs; POST /update preflights and returns 409 naming what is missing, GET /update/status reports phase and a stable failure code and nothing anyone said to us — it is unauthenticated by necessity, so the compose output that used to ride along on it now stays in the log file, POST /check-update offers only genuine upgrades from the deployment's own channel; GET and PUT /update/channel read and switch it (primary admin; refused during an update, and with the line to set by hand where the app cannot), GET naming on a dev build the copy going back would use, POST /update/revert going back to stable (dev builds only, the steps by hand where it cannot); POST /water marks generated water so a regenerate can clear its own river without touching a lake the GM drew; APPLY CONDITION MODIFIERS working every player's sheet out again (8a5e1); BAND CONDITIONS switched runs every sheet through the band hook at once (8a6b) -│ │ ├── locations.js # Location CRUD; JOIN→CUSTOM classification upserts roots + child parts to custom_structure_library; serves GET /custom-library (CUSTOM-only); GET / includes sheet_data for the GM's NPC initiative rolls, and withholds it (and a silhouetted NPC's portrait) from everyone else via sheets/npcPrivacy.js; POST /purge-region clears one region's generated content in a single transaction, keeping GM-named structures, tokens, battle-map content and hand-drawn water; who may change a token, its health or its injuries is tokens/tokenAccess.js; PUT /:id/conditions sets a token's conditions (tokens/conditions.js) by the same rule, keeping those a house rule switched off hides as they were, and the public list hides their rounds left from everyone but the GM; a player's conditions put on or taken off working their sheet out again (8a5e1) +│ │ ├── locations.js # Location CRUD; JOIN→CUSTOM classification upserts roots + child parts to custom_structure_library; serves GET /custom-library (CUSTOM-only); GET / includes sheet_data for the GM's NPC initiative rolls, and withholds it (and a silhouetted NPC's portrait) from everyone else via sheets/npcPrivacy.js; POST /purge-region clears one region's generated content in a single transaction, keeping GM-named structures, tokens, battle-map content and hand-drawn water; who may change a token, its health or its injuries is tokens/tokenAccess.js; PUT /:id/conditions sets a token's conditions (tokens/conditions.js) by the same rule, keeping those a house rule switched off hides as they were, and the public list hides their rounds left from everyone but the GM; a player's conditions put on or taken off working their sheet out again (8a5e1); a building keeps a type the running game doesn't know (another game's own shop) when saved again, a new unknown one refused (8a7b3a) │ │ ├── battle_maps.js # Battle map upload and management. Streams to a temporary file and hashes in chunks rather than buffering, so a 250MB animated map costs disk rather than RAM, then renames to the content hash — the same map on a dozen locations is one file. Sweeps partial uploads left by a process that died mid-transfer, since those are the one case the handler's own cleanup cannot reach. Accepts what the scene can actually draw, stills and loops alike, since a format the renderer cannot decode uploads perfectly and then shows nothing │ │ ├── buildingDetails.js # A building's photo and the GM's notes, mounted under /api/locations/:id. Photo upload and remove, and the notes both ways, are main-admin only - a player granted editing rights holds a token that passes `authenticate` and is refused here. The notes never join the public location list │ │ ├── maps.js # Saved map snapshots (locations, districts, roads, overpasses, water bodies); preserves only rhombus tokens on load/clear; records active_map_name in global_settings so exports can name their files @@ -796,7 +796,7 @@ CITY_NET/ │ │ │ ├── bootSounds.test.ts # No audio at all being harmless, since there are no speakers to check the rest by │ │ │ └── useAmbientHum.test.tsx # One hum per session: easing in once, the slider and mute adjusting it in place, and a start the browser holds back not taken for a start │ │ ├── components/ -│ │ │ ├── AdminPanel.tsx # GM dashboard — CITY / EXPORT / GAME / PLAYERS tabs (GAME has GIVE_ITEM beside PAY_PLAYERS, and SHOP_CATALOGUES wherever there are shops or GIVE ITEM); CITY_GENERATOR delegates to cityGen/ and exposes LAYOUT, DRAG_RECT/DRAW_AREA bounds, OVERPASS_DENSITY, WATER, PARK_PONDS, an optional SEED and REGENERATE; CUSTOM type integrates into NEXT_STYLE cycle using cross-map custom_structure_library; data-driven HouseRulesPanel for CP:R, CWN, and SR6; SR6 Edge replenishment (reset all / give 1 to player); a built-in game's own CONDITIONS for the main admin (TableConditionsPanel); a custom game's RESTS for the GM and editors (GameRestsPanel), with the NPCs on the map being viewed; a custom game's own house rules beside the shared ones in HOUSE RULES, one APPLY for all, following the game when it changes. The GAME tab's RESTS and BANK are folders of its own (R2b, GameFolder.tsx), RESTS out of TTRPG_SYSTEM, a line before what the GM hands out; AWARD_EXPERIENCE where XP is spent (7f2c2); AdminPanel itself only picks the battle map's panel or the city's (CityAdminPanel), two components so their hooks never mix; HOUSE RULES offers a custom system's SHOW ENCUMBRANCE, BAND CONDITIONS and APPLY CONDITION MODIFIERS where it has what each switches (8a6b) +│ │ │ ├── AdminPanel.tsx # GM dashboard — CITY / EXPORT / GAME / PLAYERS tabs (GAME has GIVE_ITEM beside PAY_PLAYERS, and SHOP_CATALOGUES wherever there are shops or GIVE ITEM); CITY_GENERATOR delegates to cityGen/ and exposes LAYOUT, DRAG_RECT/DRAW_AREA bounds, OVERPASS_DENSITY, WATER, PARK_PONDS, an optional SEED and REGENERATE; CUSTOM type integrates into NEXT_STYLE cycle using cross-map custom_structure_library; data-driven HouseRulesPanel for CP:R, CWN, and SR6; SR6 Edge replenishment (reset all / give 1 to player); a built-in game's own CONDITIONS for the main admin (TableConditionsPanel); a custom game's RESTS for the GM and editors (GameRestsPanel), with the NPCs on the map being viewed; a custom game's own house rules beside the shared ones in HOUSE RULES, one APPLY for all, following the game when it changes. The GAME tab's RESTS and BANK are folders of its own (R2b, GameFolder.tsx), RESTS out of TTRPG_SYSTEM, a line before what the GM hands out; AWARD_EXPERIENCE where XP is spent (7f2c2); AdminPanel itself only picks the battle map's panel or the city's (CityAdminPanel), two components so their hooks never mix; HOUSE RULES offers a custom system's SHOW ENCUMBRANCE, BAND CONDITIONS and APPLY CONDITION MODIFIERS where it has what each switches (8a6b); BUILDING TYPE grouped as FEATURES groups them: the game's own shops first under THIS GAME'S SHOPS, then SHOPS and OTHER BUILDINGS, and shows a type the game hasn't got as it is so saving keeps it (8a7b3a) │ │ │ ├── SystemPicker.tsx # GAME tab's system picker: a searchable dropdown, BUILT-IN then YOUR SYSTEMS, portalled into the theme, asking before it switches the game for everyone │ │ │ ├── systemPickerRules.ts # The picker's rules on their own: grouping and order, search, arrow-key movement, what the button says │ │ │ ├── InventorySection.tsx # The inventory table, on every system. Its own file because SheetRenderer is long enough, and generic: which rows carry an extra button, and what pressing it does, is supplied from outside - so a drug offers CONSUME and a skillplug offers LOAD without either knowing about the other A custom system's items (7e3b): the slot counters over it, and WEAR and ATTUNE under a line of an item's name (GearItemLine); an installed item's line locked, named and in place, until REMOVE (7e4c); a custom system with item types gets a table per type instead (8a3a, GearTypeTables.tsx); tells GEAR's bands which lines are worn, attuned or installed, from what the server worked out (G3); only the slot and install counters something on the sheet uses, 8px apart from FIND on a typed GEAR tab; columnsLocked on to GEAR (G6b) @@ -883,7 +883,7 @@ CITY_NET/ │ │ │ ├── SheetRenderer.tsx # Template-driven sheet renderer (any game system); sections may declare groupSize to collapse repeated entries, rowHidden to drop a row of one, and fields may declare presetFill (one select writing a whole stat block, as one save), fullWidth, startsRow or the tag_list type (an add/remove list stored as JSON) — only entries holding data render, plus one blank and a reveal button, so what you filled in comes back after a reload without anything storing that it should; MORTALLY WOUNDED / FRAIL banners, ability_list layout (dynamic add/remove rows with attr dropdown, cost, die, roll), hidden-tab gating; a ranked stat's picker with its worth beside it, starting at the lowest (7f1c1); a SPEND XP section where the sheet has one (7f2c1); IMPROVE BY USE's mark beside each stat that improves (7f3b); the conditions on the token said under a number they change, a stat's box and a skill's line, a typed stat's changed value the big number, clicked to edit what is typed (8a5e3); CARRYING (CarryingBlock) at the top of the tab a custom system's INVENTORY is on (8a6a) │ │ │ ├── ImportSheetDialog.tsx # Sheet import — fillable PDF, a Companion code (Cyberpunk only), or pasted JSON / stat block, plus a download of the blank form that upload expects; for a custom system the blank PDF and its JSON template side by side and UPLOAD JSON FILE; its boxes in the theme's colors, drawn inside the theme │ │ │ ├── CyberwareWindow.tsx # The body diagram and the table. Wires are measured from the live layout, since panels grow as chrome is added and where a wire starts is only knowable once laid out. Portalled to the body — rendered in place it inherits the character sheet's bounds and half the diagram is clipped away -│ │ │ ├── ShopWindow.tsx # A building that trades, on the terminal layout: BUY, SELL and CART folders, the building in the corner. One shelf tab per catalogue the shop sells, with the filter above the list. CWN shelves come from the book with CWN's own placement rules; every other system's are what the GM uploaded, placed through shopPlacement. + CART on either list fills the cart; CHECK OUT settles it on the server in one go, then places what was bought one at a time and shows a receipt. A checkout nobody answers gives up after 15 seconds. In a custom system's currencies, every price is in its catalogue's currency and the cart totals, asks and receipts per currency; never offers to buy an item installed (7e4c). A shelf of an item type (8a7a2) is named as the type and shows the type's own columns, and a line bought from it lands as one of the type. A long shelf drawn 200 rows at a time, more on scrolling or SHOW MORE, and filtered a step behind the typing (8n3: a 1000-line shelf took 400 ms to sort in Chromium); the SELL list is what the shop buys, everything priced under ANYTHING (8a7b1b) +│ │ │ ├── ShopWindow.tsx # A building that trades, on the terminal layout: BUY, SELL and CART folders, the building in the corner. One shelf tab per catalogue the shop sells, with the filter above the list. CWN shelves come from the book with CWN's own placement rules; every other system's are what the GM uploaded, placed through shopPlacement. + CART on either list fills the cart; CHECK OUT settles it on the server in one go, then places what was bought one at a time and shows a receipt. A checkout nobody answers gives up after 15 seconds. In a custom system's currencies, every price is in its catalogue's currency and the cart totals, asks and receipts per currency; never offers to buy an item installed (7e4c). A shelf of an item type (8a7a2) is named as the type and shows the type's own columns, and a line bought from it lands as one of the type. A long shelf drawn 200 rows at a time, more on scrolling or SHOW MORE, and filtered a step behind the typing (8n3: a 1000-line shelf took 400 ms to sort in Chromium); the SELL list is what the shop buys, everything priced under ANYTHING (8a7b1b); the game's own shops by their names, a shop that only buys opening on SELL with its BUY folder saying so (8a7b3a) │ │ │ ├── shopCart.ts # The cart's arithmetic, pure: one line per thing bought (with a count), one per thing sold, totals both ways and the net, the sell half grouped as the server takes it, and what the character would carry afterwards. What the player is shown - the server works the money out again. In a custom system's currencies, one total per currency with its shortfall and the ways it may be covered │ │ │ ├── TerminalWindow.tsx # The shared terminal layout: the picture and folders down the left, the open folder on the right, buttons along the bottom. Folders switch by click or the arrow keys, and one can blink for attention; the panel is as tall as what it holds, or in 'list' mode keeps its top still while a table scrolls under it. What goes in the folders is the caller's │ │ │ ├── TokenWindow.tsx # A token's window on TerminalWindow: INFO (headed with the player's name, their public handle and role first), HEALTH, QUICK ACTIONS on your own token, GM NOTES for the main admin on NPCs. Health panels and the GM's defense and initiative sections come in as slots; which ones a viewer gets is tokenView() @@ -891,7 +891,7 @@ CITY_NET/ │ │ │ ├── buildingActions.ts # The same for the building window's buttons │ │ │ ├── QuickActions.tsx # Your own token's QUICK ACTIONS: your AC or DV, a button per save or stat, and a skill picker, each rolled through the sheet's own roll path │ │ │ ├── GmNotes.tsx # The GM NOTES folder, shared by buildings and NPC tokens; fetched with the main admin's token only -│ │ │ ├── BuildingWindow.tsx # A building's info window as a terminal: folders down the left (INFO, RESIDENTS, and GM NOTES for the main admin only), the open one's text on the right, the building in the corner. Up and down arrows or a click switch folders; the caller hands over the buttons that apply. Reads exactly the fields the old window did +│ │ │ ├── BuildingWindow.tsx # A building's info window as a terminal: folders down the left (INFO, RESIDENTS, and GM NOTES for the main admin only), the open one's text on the right, the building in the corner. Up and down arrows or a click switch folders; the caller hands over the buttons that apply. Reads exactly the fields the old window did; one of the game's own shops by its name (8a7b3a) │ │ │ ├── BracketPortrait.tsx # The sheet's targeting-bracket portrait frame, with its upload: on the sheet's head and NEW_CHARACTER.EXE's WHO THEY ARE │ │ │ ├── BuyNumbers.tsx # A point buy in NEW_CHARACTER.EXE (7c3d): the points left, each stat's number, what it cost and what the next costs, a button either way │ │ │ ├── BuildingPreview.tsx # The corner picture: the GM's photo, else the building's own parts turning as a wireframe in its own small canvas, else the CITY_NET badge. The color is read from the theme's CSS variable where it sits - the info windows render outside the ThemeContext provider, so the context alone drew every theme in classic green @@ -1202,7 +1202,7 @@ CITY_NET/ │ │ │ ├── useSocket.conditions.test.ts # The server saying conditions changed (a built-in game's own, or a published system) telling every window that shows them │ │ │ └── useSocket.pendingRequests.test.ts # Pending edit-request state; regression for stale requests on newly-promoted temp admins │ │ ├── data/ -│ │ │ ├── buildingTypes.ts # What a building is for and which catalogues it sells, mirrored from the server, plus which systems have shops, GIVE ITEM (giveAvailable) and the catalogue upload (cataloguesAvailable: shops or GIVE ITEM) (every one with a sheet, held equal to the server's gate by a test) and what each game calls a storefront - same ids everywhere, so a Ripperdoc becomes a Street Doc when the system changes rather than disappearing. A custom system's item types are shelves too (`type:`, 8a7a2), at the kinds of shop their SOLD AT says (shelvedIn, itemTypeOfShelf), named as the type; a shop's own shelf a type is named like (a GEAR type, the gear shelf) left off while nothing is on it (typeNamedLike); buysIn and boughtIn, what a shop buys back, the server's list (8a7b1b) +│ │ │ ├── buildingTypes.ts # What a building is for and which catalogues it sells, mirrored from the server, plus which systems have shops, GIVE ITEM (giveAvailable) and the catalogue upload (cataloguesAvailable: shops or GIVE ITEM) (every one with a sheet, held equal to the server's gate by a test) and what each game calls a storefront - same ids everywhere, so a Ripperdoc becomes a Street Doc when the system changes rather than disappearing. A custom system's item types are shelves too (`type:`, 8a7a2), at the kinds of shop their SOLD AT says (shelvedIn, itemTypeOfShelf), named as the type; a shop's own shelf a type is named like (a GEAR type, the gear shelf) left off while nothing is on it (typeNamedLike); buysIn and boughtIn, what a shop buys back, the server's list (8a7b1b); the game's own shops from the render copy (ownShopsIn, ownShopIn, buildingTypeIn), shops while on, by their names, onlyBuysIn (8a7b3a) │ │ │ └── shopRules.ts # The overdraft house rule, the buy-back rate and how it resolves, and the words for every refusal (refusalText, in a custom system's own words for shops, money and characters). Mirrored from backend/shops and compared against it value for value, since the window quoting one price and the server paying another is the failure worth fearing; a sale refused for an installed item (7e4a) │ │ ├── sheets/ │ │ │ ├── types.ts # Sheet template type system (fields, sections, header, death saves, NPC tiers, a custom system's house rules as running) @@ -1391,6 +1391,7 @@ CITY_NET/ │ │ │ ├── typedShelves.test.ts # A type's shelf (8a7a2): at the kinds of shop its SOLD AT says, named as the type, where a line lands said; a line bought from it typed, stacked only onto the same thing untouched, exactly as the server places it; sold back from the window, found on its type's shelf, an item kept out of the shops priced at its own (8a7a3c2) │ │ │ ├── shopBuys.test.ts # What a shop BUYS (8a7b1b): ANYTHING on the app's shops and the game's own, every shelf the game has on and each of its types' bought back, not one turned off; a built-in game as ever │ │ │ ├── gameShops.test.ts # SOLD AT and + NEW SHOP (8a7b2): the shops named as the game names them, ticks in order, a shop made from a name or found by it, blank and past 20 refused, the words, each preset's shop; FEATURES keeping BUYS +│ │ │ ├── ownShopsTable.test.ts # The game's own shops at the table (8a7b3a): read from the render copy, building types of the game by their names, shops while on, their shelves the types SOLD AT them, one that sells nothing and buys anything only buying │ │ │ ├── itemPrice.test.ts # An item's PRICE and IN SHOPS on the ITEMS page (8a7a3b1): in its type's PRICE column or its own, IN SHOPS and a price needed, held to the server's itemPrice and inShops on the same items; changed, and kept on a change of type │ │ │ ├── catalogueTypes.test.ts # A type in a file (8a7a1): its heading and columns, only a custom system's own; EXAMPLE, CURRENT and ITEMS each back through the server's reader with every column; a type's section as gear in the preview │ │ │ ├── catalogueRoundTrip.test.ts # The example the app hands out surviving being handed back to the server's parser @@ -1572,6 +1573,7 @@ CITY_NET/ │ ├── catalogue-types.spec.ts # A catalogue section per item type (8a7a1): [GUNS] in DOWNLOAD EXAMPLE, a file with a good gun, a bad AMMO and blanks previewed as GUNS ×2 with the problem and the note, saved, both guns back in DOWNLOAD CURRENT with their columns │ ├── catalogue-and-items.spec.ts # A catalogue held against the game's items (8a7a3c1): the Pistol overruling 200 → 260, an exact Cutlass and a ring kept out of the shops left out, ALSO ON SALE FROM ITEMS; saved, the game's Cutlass behind a # in DOWNLOAD CURRENT │ ├── shop-typed-lines.spec.ts # Lines of an item type at the table (8a7a2): a [GUNS] catalogue saved, the General Store's GUNS shelf in the type's columns, a Pistol bought and landing as a Gun with its damage and ammo, another given from GIVE.EXE stacked onto it +│ ├── shop-own-kinds.spec.ts # The game's own shops at the table (8a7b3a): the GM picks Apothecary under THIS GAME'S SHOPS, first in BUILDING TYPE; a draught bought there; a Fence that only buys opens on SELL, says so on BUY, and takes the draught back at 45% │ ├── shop-items-on-sale.spec.ts # The game's own items at the table (8a7a3a): a Pistol priced on ITEMS, no catalogue saved, on the General Store's WEAPONS shelf at 200 and a ring kept out of the shops not; bought, a Weapon on the gear with its damage; sold back from the window at the store's 50%, 900 left and off the sheet (8a7a3c2) │ ├── shop-stress.spec.ts # A 1000-line shelf in the browser (8n3): saved, opened 200 at a time, scrolled for more, filtered as typed and sorted both ways, each in time, the times logged │ ├── shop-items-catalogue.spec.ts # Items in the shops (7e3c): DOWNLOAD ITEMS, a price filled in, the preview naming the ring and a near miss, saved, on sale in GIVE.EXE's catalogue diff --git a/backend/__tests__/system_builder_own_shops.test.js b/backend/__tests__/system_builder_own_shops.test.js index f14e9266..6ec22c87 100644 --- a/backend/__tests__/system_builder_own_shops.test.js +++ b/backend/__tests__/system_builder_own_shops.test.js @@ -164,6 +164,16 @@ describe('at the table', () => { expect((await give(id, 'tavern')).status).toBe(400); }); + it('a building keeps another game\'s own shop when saved again (8a7b3a); a new unknown one is still refused', async () => { + const id = await stall('apothecary'); + await install({ ...HERBAL([]), items: { types: [{ ...POTIONS, sold_at: [] }], list: [] } }); + 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, 'tavern')).status).toBe(400); + expect((await give(id, '')).status).toBe(200); + expect((await give(id, 'apothecary')).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'); diff --git a/backend/routes/locations.js b/backend/routes/locations.js index 7730145b..d0e7e25a 100644 --- a/backend/routes/locations.js +++ b/backend/routes/locations.js @@ -177,11 +177,6 @@ module.exports = (db, io, { emitUpdate, recordAction }) => { */ router.patch('/:id/building-type', authenticate, (req, res) => withShopSystem(res, (system) => { 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. - // 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; /** @@ -198,6 +193,13 @@ module.exports = (db, io, { emitUpdate, recordAction }) => { db.get('SELECT id, building_type FROM locations WHERE id = ?', [req.params.id], (err, row) => { if (err) return res.status(500).json({ error: err.message }); if (!row) return res.status(404).json({ error: 'Not found' }); + // 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: the app's types, + // or one of the running game's own shops (8a7b). One the building already has (another + // game's own shop, 8a7b3a) is kept, as saving the building sends it again. + if (next !== null && next !== row.building_type && !isValidType(next) && !ownShopOf(customSystems.definitionOf(system), next)) { + return res.status(400).json({ error: 'Unknown building type' }); + } // A type this game turned off is not one a building can be given here. One already given // keeps it, unused, for when the type is turned back on - and saving the building again // (the editor sends its type on every save) is not giving it anything new. diff --git a/e2e/COVERAGE.md b/e2e/COVERAGE.md index 4526dc26..91061f54 100644 --- a/e2e/COVERAGE.md +++ b/e2e/COVERAGE.md @@ -35,7 +35,7 @@ panel), so a control that looks fine but does nothing is caught for all of them. | Shop catalogues by item type | a section per item type (8a7a1), its columns checked, blanks kept | `shop_catalogue_types`, `catalogueTypes` | `catalogue-types`, `shop-typed-lines` (bought at the General Store and given, landing typed, 8a7a2) | **AT THE TABLE** | | The shops under load | 1000+ lines on a shelf, 200 items, a full cart, a long gear list (8n3); a long shelf drawn 200 rows at a time | `shop_stress`, `ShopWindow` | `shop-stress` | **AT THE TABLE** | | An item type's SOLD AT | the kinds of shop that sell its lines (8a7a2), the General Store where unsaid; ticked in the builder (8a7b2), each preset at its shop | `shop_typed_lines`, `typedShelves`, `gameShops`, `ItemsPage` | `shop-typed-lines` (unsaid: the General Store), `builder-sold-at` (ticked by clicks: a Pistol bought at a Gun Shop) | **AT THE TABLE** | -| The game's own shops, and what a shop BUYS | an Apothecary or a Fence of the game's own (8a7b1a), on or off; a shop's BUYS, WHAT IT SELLS or ANYTHING, every priced thing at the building's BUYBACK rate (8a7b1b) | `system_builder_own_shops`, `gameShops`, `system_builder_shop_buys`, `shopBuys`, `ShopWindow` | `builder-sold-at` (an Apothecary made by + NEW SHOP, saved) | **GAP** at the table until a building can be one: BUYS and the BUILDING TYPE list in 8a7b3, each with its journey | +| The game's own shops, and what a shop BUYS | an Apothecary or a Fence of the game's own (8a7b1a), on or off; a shop's BUYS, WHAT IT SELLS or ANYTHING, every priced thing at the building's BUYBACK rate (8a7b1b) | `system_builder_own_shops`, `gameShops`, `system_builder_shop_buys`, `shopBuys`, `ownShopsTable`, `AdminPanel`, `ShopWindow` | `builder-sold-at` (an Apothecary made by + NEW SHOP, saved), `shop-own-kinds` (an Apothecary picked in BUILDING TYPE selling its draught; a Fence on ANYTHING opening on SELL and taking it back) | **AT THE TABLE**; set from FEATURES (rename, off, BUYS, DELETE) in 8a7b3b | | An item type's ON THE SHEET band | EQUIPPED, USABLE or PACK (G1), PACK where unsaid; the sheet's GEAR tab in those bands plus STASH, closed to start, a band's head closing it, remembered (G2); a thing worn, attuned or installed in EQUIPPED whatever its type, a closed band something lands in lit until opened (G3) | `system_builder_item_types`, `itemTypes`, `ItemsPage`, `gearBands`, `GearTypeTables` | `builder-item-types` (the WEAPON preset EQUIPPED), `sheet-gear-bands` (a Sword, a Draught and a Rope in EQUIPPED, USABLE and PACK; the Sword stashed into STASH; USABLE kept closed; a Cloak of GEAR worn into a closed EQUIPPED, its head lit, taken off back into PACK) | **AT THE TABLE** | | PLAYERS CHANGE GEAR | the GAME tab's switch, on to start, offered where a system makes its own item types (G6a, G6b): off, a player's gear columns are the GM's | `players_change_gear` setting, `switches.gear`, `uniqueLines.keepColumns`, `GearTypeTables` | `sheet-players-change-gear` (off: DAMAGE read only and said; the GM changes it, UNIQUE by the GM; on: the player changes it) | **AT THE TABLE** | | 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** | diff --git a/e2e/README.md b/e2e/README.md index 9f119e3d..813ceb22 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -222,6 +222,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/shop-own-kinds.spec.ts` | The game's own shops at the table (8a7b3a). A game with an Apothecary selling its POTIONS and a Fence that sells nothing and BUYS anything. The GM picks a building out in QUICK_ACCESS, EDITs it and finds both first in BUILDING TYPE, under THIS GAME'S SHOPS, picks Apothecary (its buy-back rate box appears) and saves; paid 100, the player's Apothecary window is headed APOTHECARY and sells the Healing Draught (60 left); the Fence's window opens on SELL with the draught there, its BUY folder says THIS SHOP ONLY BUYS, and the draught sells back at 45% of 40 (78). | | `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 #; EDIT CURRENT (8a7a5) asks before replacing the box's text, then fills it with what is on sale. | | `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 | diff --git a/e2e/tests/shop-own-kinds.spec.ts b/e2e/tests/shop-own-kinds.spec.ts new file mode 100644 index 00000000..7f748c24 --- /dev/null +++ b/e2e/tests/shop-own-kinds.spec.ts @@ -0,0 +1,89 @@ +import { test, expect } from '@playwright/test'; +import { signInAsGm, signInAsPlayer, gmToken, asGm, runningSystem, approvedPlayer } from './helpers'; +import { playerToken, payPlayer } from './shops'; + +// The game's own shops at the table (8a7b3a; approved mockup docs/mockups/types-in-shops.html, sections 3 and 4). A game with +// an Apothecary selling its POTIONS and a Fence that sells nothing and BUYS anything. The GM makes a building an Apothecary +// from BUILDING TYPE, under THIS GAME'S SHOPS; the player buys a Healing Draught there, then takes it to the Fence, whose +// window opens on SELL, its BUY folder saying it only buys, and sells it back at the app's 45%. + +const SYSTEM = (name: string) => ({ + format: 1, name, core: { health: { model: 'pool' } }, + stats: [{ id: 'abilities', label: 'ABILITIES', stats: [{ id: 'might', label: 'Might' }] }], + buildings: { shops: [{ id: 'apothecary', name: 'Apothecary' }, { id: 'fence', name: 'Fence', buys: 'anything' }] }, + items: { + types: [{ id: 'potions', label: 'POTIONS', one: 'Potion', sold_at: ['apothecary'], columns: [{ id: 'heals', label: 'HEALS', kind: 'dice' }] }], + list: [{ id: 'draught', label: 'Healing Draught', type: 'potions', values: { heals: '2d4' }, price: 40, in_shops: true }], + }, +}); + +test('the game\'s own shops: an Apothecary picked under THIS GAME\'S SHOPS sells a draught; a Fence that only buys takes it back (8a7b3a)', async ({ page, browser, request }, info) => { + test.setTimeout(180_000); + const again = info.retry ? `_${info.retry + 1}` : ''; + const gm = await gmToken(request); + await runningSystem(request, gm, SYSTEM(`Herbfall${again}`)); + const player = { username: `e2e_herbfall${again}`, password: 'e2e-player-password' }; + await approvedPlayer(request, gm, player); + await playerToken(request, gm, player.username); + const shop = `HERBFALL_MOSS${again}`; + const fence = `HERBFALL_DOOR${again}`; + await asGm(request, gm, 'post', '/api/locations', { name: shop, description: '', shape: 'box', x: 12, y: 0, z: 12, width: 2, height: 2, depth: 2 }); + const door = await asGm(request, gm, 'post', '/api/locations', { name: fence, description: '', shape: 'box', x: 16, y: 0, z: 12, width: 2, height: 2, depth: 2 }); + const typed = await request.patch(`/api/locations/${door.data[0].id}/building-type`, { data: { building_type: 'fence' }, headers: { Authorization: `Bearer ${gm}` } }); + expect(typed.ok(), await typed.text()).toBe(true); + + // The player, online and with a sheet opened once. + const context = await browser.newContext({ baseURL: info.project.use.baseURL, viewport: { width: 1280, height: 800 } }); + const mine = await context.newPage(); + await signInAsPlayer(mine, player); + await mine.getByRole('button', { name: 'CHARACTER_CONTROLS', exact: true }).click(); + await mine.getByRole('button', { name: 'CHARACTER_SHEET', exact: true }).click(); + await expect(mine.getByRole('group', { name: 'Vitals' })).toBeVisible({ timeout: 15_000 }); + await mine.keyboard.press('Escape'); + + // The GM: the building picked out, EDIT, BUILDING TYPE has the game's own under THIS GAME'S SHOPS; Apothecary, saved. + await page.setViewportSize({ width: 1280, height: 800 }); + await signInAsGm(page); + await page.getByRole('button', { name: 'QUICK_ACCESS', exact: true }).click(); + const gmList = page.locator('.quick-access-panel'); + await gmList.getByText(/DEFINED_STRUCTURES/).click(); + await gmList.getByText(shop, { exact: true }).click(); + await page.locator('.selection-panel').getByRole('button', { name: 'EDIT', exact: true }).click(); + const picker = page.getByLabel('Building type'); + await expect(picker.locator('optgroup').first()).toHaveAttribute('label', 'THIS GAME\'S SHOPS'); + await expect(picker.locator('optgroup[label="THIS GAME\'S SHOPS"] option')).toHaveText(['Apothecary', 'Fence']); + await picker.selectOption('apothecary'); + await expect(page.getByLabel('Buy-back rate for this shop')).toBeVisible(); + await page.getByRole('button', { name: 'UPDATE_DATA_POINT', exact: true }).click(); + await expect(page.getByText('CHANGES_SAVED', { exact: true })).toBeVisible({ timeout: 15_000 }); + await page.getByRole('button', { name: 'ACKNOWLEDGE', exact: true }).click(); + await expect.poll(async () => (await asGm(request, gm, 'get', '/api/locations')).find((l: { name: string }) => l.name === shop)?.building_type, { timeout: 15_000 }).toBe('apothecary'); + await payPlayer(page, player.username, 100); + + // The Apothecary: named as the game names it, its POTIONS on sale; a draught bought. + await mine.getByRole('button', { name: 'QUICK_ACCESS', exact: true }).click(); + const list = mine.locator('.quick-access-panel'); + await list.getByText(/DEFINED_STRUCTURES/).click(); + await list.getByText(shop, { exact: true }).click(); + await mine.getByRole('button', { name: 'SHOP', exact: true }).click(); + const moss = mine.locator('.win95-window', { has: mine.getByText(`SHOP.EXE · ${shop}`, { exact: true }) }); + await expect(moss.getByText(/^APOTHECARY · 1 LINE/)).toBeVisible({ timeout: 15_000 }); + await moss.getByRole('button', { name: 'Add Healing Draught to the cart' }).click(); + await moss.getByRole('tab', { name: 'CART' }).click(); + await moss.getByRole('button', { name: 'CHECK OUT' }).click(); + await expect(moss.getByRole('tabpanel')).toContainText('BALANCE 60cr', { timeout: 15_000 }); + await mine.keyboard.press('Escape'); + + // The Fence: open on SELL, the draught there; BUY says it only buys; sold back at 45% of 40. + await list.getByText(fence, { exact: true }).click(); + await mine.getByRole('button', { name: 'SHOP', exact: true }).click(); + const back = mine.locator('.win95-window', { has: mine.getByText(`SHOP.EXE · ${fence}`, { exact: true }) }); + await expect(back.getByRole('tab', { name: 'SELL' })).toHaveAttribute('aria-selected', 'true', { timeout: 15_000 }); + await back.getByRole('button', { name: 'Add Healing Draught to the cart' }).click({ timeout: 15_000 }); + await back.getByRole('tab', { name: 'BUY' }).click(); + await expect(back.getByTestId('shop-sells-nothing')).toHaveText('THIS SHOP ONLY BUYS: it sells nothing, and takes anything with a price. Open SELL.'); + await back.getByRole('tab', { name: 'CART' }).click(); + await back.getByRole('button', { name: 'CHECK OUT' }).click(); + await expect(back.getByRole('tabpanel')).toContainText('BALANCE 78cr', { timeout: 15_000 }); + await context.close(); +}); diff --git a/frontend/src/components/AdminPanel.tsx b/frontend/src/components/AdminPanel.tsx index e55c52b4..c91ca0a7 100644 --- a/frontend/src/components/AdminPanel.tsx +++ b/frontend/src/components/AdminPanel.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react'; -import { BUILDING_TYPES, shopsAvailable, cataloguesAvailable, giveAvailable, isShopIn, typeLabel, typeOn } from '../data/buildingTypes'; +import { BUILDING_TYPES, shopsAvailable, cataloguesAvailable, giveAvailable, isShopIn, typeLabel, typeOn, ownShopsIn, buildingTypeIn } from '../data/buildingTypes'; import { EmptyShopSteps } from './EmptyShopSteps'; import { SystemPicker } from './SystemPicker'; import type { PickerSystem } from './systemPickerRules'; @@ -1947,12 +1947,29 @@ function CityAdminPanel({ style={{width: '100%'}} > - {/* The types this game has, by its names. One it turned off stays - listed only on a building that already has it, so the box can - show it and saving keeps it (the server allows that one). */} - {BUILDING_TYPES.filter((t) => typeOn(globalSettings['game_system'], t.id) || t.id === editData.building_type).map((t) => ( - - ))} + {/* + Grouped as FEATURES groups them (8a7b3a; the user, 2026-11-22: "should we add more headers ... should we + also put the This Game Only at the top?"): the game's own shops first, made to be put on the map, then + the app's shops, then its other buildings, each by this game's name; the header says which are shops. + One turned off stays listed only on a building that already has it, so the box can show it and saving + keeps it (the server allows that one). + */} + {[ + { label: 'THIS GAME\'S SHOPS', rows: ownShopsIn(globalSettings['game_system']).map((s) => ({ id: s.id })) }, + { label: 'SHOPS', rows: BUILDING_TYPES.filter((t) => t.shop) }, + { label: 'OTHER BUILDINGS', rows: BUILDING_TYPES.filter((t) => !t.shop) }, + ].map((g) => ({ ...g, rows: g.rows.filter((t) => typeOn(globalSettings['game_system'], t.id) || t.id === editData.building_type) })) + .filter((g) => g.rows.length).map((g) => ( + + {g.rows.map((t) => ( + + ))} + + ))} + {/* A type this game hasn't got at all (another game's own shop): shown as it is, so saving keeps it. */} + {editData.building_type && !buildingTypeIn(globalSettings['game_system'], editData.building_type) && ( + + )} {/* diff --git a/frontend/src/components/BuildingWindow.tsx b/frontend/src/components/BuildingWindow.tsx index 313c2df5..55b5c052 100644 --- a/frontend/src/components/BuildingWindow.tsx +++ b/frontend/src/components/BuildingWindow.tsx @@ -1,6 +1,6 @@ import { TerminalWindow, TERMINAL_PREVIEW, useFolder, type TerminalAction, type TerminalFolder } from './TerminalWindow'; import { BuildingPreview } from './BuildingPreview'; -import { buildingTypeById, typeLabel, typeOn } from '../data/buildingTypes'; +import { buildingTypeIn, typeLabel, typeOn } from '../data/buildingTypes'; import { GmNotes } from './GmNotes'; import { useWords } from '../sheets/words'; @@ -52,7 +52,8 @@ export function BuildingWindow({ // Opening another building starts at its INFO, not wherever the last one was left. const [open, setOpen] = useFolder(folders, location?.id); - const type = buildingTypeById(location?.building_type); + // The app's types, or one of the game's own shops (8a7b3a). + const type = buildingTypeIn(gameSystem, location?.building_type); return ( ('buy'); + // A shop that sells nothing and buys anything opens on SELL (8a7b3a). + const [tab, setTab] = useState(() => (onlyBuysIn(system, buildingType) ? 'sell' : 'buy')); const [filter, setFilter] = useState(''); // A custom system's own words for the shop, money, the GM and characters; today's text otherwise. const word = useWords(system); @@ -418,7 +419,8 @@ export function ShopWindow({ */ const [kinds, setKinds] = useState({ ranged: false, melee: false }); - const type = buildingTypeById(buildingType); + // The app's types, or one of the game's own shops (8a7b3a). + const type = buildingTypeIn(system, buildingType); // Without the catalogues this game turned off. // A shelf a type is named like only while lines are on it (8a7a2). const catalogues = shelvedIn(buildingType, system, (c) => uploadedIn(c).length > 0); @@ -1755,13 +1757,16 @@ export function ShopWindow({ {!shelf ? ( -
- NO CATALOGUE FOR THIS {SHOP} YET. - {/* Named, so the answer to "why is this empty" is on the screen. */} - {type?.sells.length - ? ` The book has ${type.sells.map((s) => catalogueLabel(s, system)).join(' and ')} for this +
+ {/* One that buys anything says so (8a7b3a); one of the game's own selling nothing yet, why. */} + {buysIn(system, buildingType) === 'anything' + ? `THIS ${SHOP} ONLY BUYS: it sells nothing, and takes anything with a price. Open SELL.` + : <>NO CATALOGUE FOR THIS {SHOP} YET. + {/* Named, so the answer to "why is this empty" is on the screen. */} + {type?.sells.length + ? ` The book has ${type.sells.map((s) => catalogueLabel(s, system)).join(' and ')} for this storefront, but nothing here can put it on a shelf yet.` - : ' This building type does not trade.'} + : ownShopIn(system, buildingType) ? ' No item type is sold here yet.' : ' This building type does not trade.'}}
) : ( <> diff --git a/frontend/src/components/__tests__/AdminPanel.test.tsx b/frontend/src/components/__tests__/AdminPanel.test.tsx index 3edcb2f8..d8034550 100644 --- a/frontend/src/components/__tests__/AdminPanel.test.tsx +++ b/frontend/src/components/__tests__/AdminPanel.test.tsx @@ -1,6 +1,6 @@ import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor } from '@testing-library/react'; +import { render, screen, waitFor, cleanup } from '@testing-library/react'; import * as THREE from 'three'; import userEvent from '@testing-library/user-event'; @@ -1196,16 +1196,22 @@ describe('the building type control', () => { ); }; + /** Each header of the BUILDING TYPE box with what is under it (8a7b3a). */ + const groups = () => [...screen.getByLabelText('Building type').querySelectorAll('optgroup')] + .map((g) => [g.label, ...[...g.querySelectorAll('option')].map((o) => o.textContent)]); + it('offers the types under Cities Without Number', () => { editView(); expect(screen.getByLabelText('Building type')).toBeInTheDocument(); - expect(screen.getByRole('option', { name: /Ripperdoc \(shop\)/ })).toBeInTheDocument(); + expect(screen.getByRole('option', { name: 'Ripperdoc' })).toBeInTheDocument(); }); - it('marks which types trade, so the SHOP button is not a surprise', () => { + it('says which types trade under SHOPS, the rest under OTHER BUILDINGS, so the SHOP button is not a surprise', () => { editView(); - expect(screen.getByRole('option', { name: 'Bar' })).toBeInTheDocument(); - expect(screen.queryByRole('option', { name: 'Bar (shop)' })).not.toBeInTheDocument(); + expect(groups()).toEqual([ + ['SHOPS', 'Ripperdoc', 'Gun Shop', 'Clinic', 'Garage', 'Armorer', 'General Store'], + ['OTHER BUILDINGS', 'Bar', 'Corporate', 'Residence', 'Industrial'], + ]); }); describe('under a custom system that renamed or turned off types (3b3b2)', () => { @@ -1221,7 +1227,7 @@ describe('the building type control', () => { it('offers the types it kept, by its names', () => { editView({ globalSettings: { game_system: HEARTH } }); - expect(options()).toContain('Temple (shop)'); + expect(options()).toContain('Temple'); expect(options().some((o) => o?.startsWith('Gun Shop'))).toBe(false); expect(options()).toHaveLength(10 - 1); }); @@ -1241,11 +1247,44 @@ describe('the building type control', () => { }); }); + describe('the game\'s own shops (8a7b3a)', () => { + const HERBAL = 'sys_bbbbbbbbbbbbbbbb'; + beforeEach(() => { + clearCustomTemplates(); + registerCustomTemplate({ id: HERBAL, name: 'Herbal', parts: {}, derived: [], sheet: { sections: [] }, words: {}, + buildings: { shops: [{ id: 'apothecary', name: 'Apothecary', on: true }, { id: 'fence', name: 'Fence', on: false }] } } as never); + }); + afterEach(() => clearCustomTemplates()); + it('first, under THIS GAME\'S SHOPS, made to be put on the map; one turned off left out; a shop, with its rate', () => { + editView({ globalSettings: { game_system: HERBAL }, editData: { building_type: 'apothecary' } }); + expect(groups().map((g) => g[0])).toEqual(['THIS GAME\'S SHOPS', 'SHOPS', 'OTHER BUILDINGS']); + expect(groups()[0]).toEqual(['THIS GAME\'S SHOPS', 'Apothecary']); + expect((screen.getByLabelText('Building type') as HTMLSelectElement).value).toBe('apothecary'); + expect(screen.getByLabelText('Buy-back rate for this shop')).toBeInTheDocument(); + }); + + it('one turned off, or another game\'s, still shown on a building that has it, so saving keeps it; no shop', () => { + editView({ globalSettings: { game_system: HERBAL }, editData: { building_type: 'fence' } }); + expect(groups()[0]).toEqual(['THIS GAME\'S SHOPS', 'Apothecary', 'Fence (not in this game)']); + expect(screen.queryByLabelText('Buy-back rate for this shop')).toBeNull(); + cleanup(); + editView({ globalSettings: { game_system: HERBAL }, editData: { building_type: 'tavern' } }); + expect((screen.getByLabelText('Building type') as HTMLSelectElement).value).toBe('tavern'); + expect(screen.getByRole('option', { name: 'tavern (not in this game)' })).toBeInTheDocument(); + }); + + it('none in a game that makes none', () => { + editView({ globalSettings: { game_system: 'cyberpunk_red' } }); + expect(groups().map((g) => g[0])).toEqual(['SHOPS', 'OTHER BUILDINGS']); + expect(screen.queryByRole('option', { name: /not in this game/ })).toBeNull(); + }); + }); + it('is there under every system, named the way that game names them', () => { editView({ globalSettings: { game_system: 'shadowrun_6e' } }); expect(screen.getByLabelText('Building type')).toBeInTheDocument(); - expect(screen.getByRole('option', { name: 'Street Doc (shop)' })).toBeInTheDocument(); - expect(screen.queryByRole('option', { name: 'Ripperdoc (shop)' })).not.toBeInTheDocument(); + expect(screen.getByRole('option', { name: 'Street Doc' })).toBeInTheDocument(); + expect(screen.queryByRole('option', { name: 'Ripperdoc' })).not.toBeInTheDocument(); }); it('tells the GM how to stock a shop that has nothing to sell', async () => { diff --git a/frontend/src/components/__tests__/ShopWindow.test.tsx b/frontend/src/components/__tests__/ShopWindow.test.tsx index c4a1bf19..7f62dcf8 100644 --- a/frontend/src/components/__tests__/ShopWindow.test.tsx +++ b/frontend/src/components/__tests__/ShopWindow.test.tsx @@ -2215,6 +2215,44 @@ describe('the shop\'s refusals', () => { }); }); +// ─── The game's own shops (8a7b3a) ────────────────────────────────────────────── +describe('a shop of the game\'s own (8a7b3a)', () => { + const HERBAL = 'sys_beef0beef0beef0b'; + const POTIONS = { id: 'potions', label: 'POTIONS', one: 'Potion', sold_at: ['apothecary'], columns: [] }; + + beforeEach(() => { + clearCustomTemplates(); + registerCustomTemplate({ + id: HERBAL, name: 'Herbal', parts: {}, derived: [], sheet: { sections: [] }, words: {}, + buildings: { shops: [{ id: 'apothecary', name: 'Apothecary', on: true }, { id: 'fence', name: 'Fence', on: true, buys: 'anything' }, { id: 'stall', name: 'Stall', on: true }] }, + items: { slots: [], list: [], types: [POTIONS] }, + } as never); + loadUploaded({ 'type:potions': [{ id: 'item:draught', name: 'Healing Draught', price: 40, fields: {} }], gear: [{ id: 'rope', name: 'Rope', price: 100, fields: {} }] } as never); + sheetState.sheet = { system: HERBAL, data: { inventory: JSON.stringify([{ name: 'Rope', qty: 1, carry: 'stowed' }]) } }; + }); + afterEach(() => { clearCustomTemplates(); clearUploaded(); }); + + it('named as the game names it, selling the types SOLD AT it, on BUY', () => { + show('apothecary', 'Moss & Root', HERBAL); + expect(screen.getByText(/^APOTHECARY · 1 LINE/)).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Add Healing Draught to the cart' })).toBeInTheDocument(); + expect(screen.getByRole('tab', { name: 'BUY' })).toHaveAttribute('aria-selected', 'true'); + }); + + it('one that sells nothing and buys anything opens on SELL, its BUY folder saying it only buys', async () => { + show('fence', 'Back Door', HERBAL); + expect(screen.getByRole('tab', { name: 'SELL' })).toHaveAttribute('aria-selected', 'true'); + expect(screen.getByRole('button', { name: 'Add Rope to the cart' })).toBeInTheDocument(); + await openFolder('BUY'); + expect(screen.getByTestId('shop-sells-nothing')).toHaveTextContent('THIS SHOP ONLY BUYS: it sells nothing, and takes anything with a price. Open SELL.'); + }); + + it('one selling nothing yet, and buying what it sells, says no type is sold there yet', () => { + show('stall', 'Corner', HERBAL); + expect(screen.getByTestId('shop-sells-nothing')).toHaveTextContent('NO CATALOGUE FOR THIS SHOP YET. No item type is sold here yet.'); + }); +}); + // ─── What a shop buys (8a7b1b) ────────────────────────────────────────────────── describe('a shop that buys anything (8a7b1b)', () => { const PAWN = 'sys_baba0baba0baba0b'; diff --git a/frontend/src/data/buildingTypes.ts b/frontend/src/data/buildingTypes.ts index 94451754..e826f3f3 100644 --- a/frontend/src/data/buildingTypes.ts +++ b/frontend/src/data/buildingTypes.ts @@ -168,17 +168,39 @@ const BOOK_SYSTEM = 'cities_without_number'; const customSetting = (system: string | null | undefined, kind: 'types' | 'catalogues', id: string | null | undefined) => (isCustomSystem(system) ? customTemplate(system)?.buildings?.[kind]?.[String(id ?? '')] : undefined); -/** Whether this game has a building type: every one, unless a custom system turned it off. */ -export const typeOn = (system: string | null | undefined, id: string | null | undefined): boolean => - customSetting(system, 'types', id)?.on !== false; +/** + * The running game's own kinds of shop (8a7b1a; approved mockup types-in-shops.html), as its render copy says them: an + * Apothecary or a Fence the GM made. None for a built-in game or one that makes none. + */ +export const ownShopsIn = (system: string | null | undefined) => + customTemplate(String(system ?? ''))?.buildings?.shops ?? []; + +/** One of the running game's own kinds of shop by id, or undefined. */ +export const ownShopIn = (system: string | null | undefined, id: string | null | undefined) => + ownShopsIn(system).find((s) => s.id === String(id ?? '')); + +/** + * A building type in this game (8a7b3a): the app's, or one of the game's own shops, drawn as a shop selling nothing of the + * app's (its shelves are the types SOLD AT it). Undefined for an id neither has. + */ +export const buildingTypeIn = (system: string | null | undefined, id: string | null | undefined): BuildingType | undefined => { + const own = ownShopIn(system, id); + return own ? { id: own.id, label: own.name, shop: true, sells: [] } : buildingTypeById(id); +}; + +/** Whether this game has a building type: every one of the app's unless a custom system turned it off; its own, as each says. */ +export const typeOn = (system: string | null | undefined, id: string | null | undefined): boolean => { + const own = ownShopIn(system, id); + return own ? own.on !== false : customSetting(system, 'types', id)?.on !== false; +}; /** Whether this game has a shop catalogue: every one, unless a custom system turned it off. */ export const catalogueOn = (system: string | null | undefined, id: ShopStock): boolean => customSetting(system, 'catalogues', id)?.on !== false; -/** Whether a building of this type is a shop in this game. */ +/** Whether a building of this type is a shop in this game: one of the app's it has, or one of its own that is on (8a7b3a). */ export const isShopIn = (system: string | null | undefined, id: string | null | undefined): boolean => - isShop(id) && typeOn(system, id); + (isShop(id) || !!ownShopIn(system, id)) && typeOn(system, id); /** * The catalogues a shop of this type puts on its shelves in this game. A shelf one of the game's own item types is named @@ -194,6 +216,10 @@ export const shelvedIn = ( ...ownItemTypes(system).filter((t) => (t.sold_at ?? []).includes(String(id ?? ''))).map((t) => `type:${t.id}` as ShopStock), ]; +/** A shop that sells nothing and buys anything (8a7b3a): its window opens on SELL, its BUY folder saying so. */ +export const onlyBuysIn = (system: string | null | undefined, id: string | null | undefined): boolean => + buysIn(system, id) === 'anything' && shelvedIn(id, system).length === 0; + /** What a shop of this type buys back in this game (8a7b1b): ANYTHING where a custom system says so, else what it sells. */ export const buysIn = (system: string | null | undefined, id: string | null | undefined): 'sells' | 'anything' => { const buildings = customTemplate(String(system ?? ''))?.buildings; @@ -230,7 +256,8 @@ export const itemTypeOfShelf = (system: string | null | undefined, id: string) = /** A building type's name in this game. Blank for an id that is not on the list. */ export const typeLabel = (id: string | null | undefined, system: string | null | undefined): string => - customSetting(system, 'types', id)?.name ?? TYPE_NAMES[String(system ?? '')]?.[String(id ?? '')] ?? buildingTypeById(id)?.label ?? ''; + // One of the game's own shops (8a7b3a): its name, the only one it has. + ownShopIn(system, id)?.name ?? customSetting(system, 'types', id)?.name ?? TYPE_NAMES[String(system ?? '')]?.[String(id ?? '')] ?? buildingTypeById(id)?.label ?? ''; /** A catalogue's name in this game, for a shelf tab or a section of the catalogue file. */ export const catalogueLabel = (id: ShopStock, system: string | null | undefined): string => { diff --git a/frontend/src/sheets/__tests__/ownShopsTable.test.ts b/frontend/src/sheets/__tests__/ownShopsTable.test.ts new file mode 100644 index 00000000..bda101ec --- /dev/null +++ b/frontend/src/sheets/__tests__/ownShopsTable.test.ts @@ -0,0 +1,51 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ownShopsIn, ownShopIn, buildingTypeIn, typeOn, isShopIn, typeLabel, onlyBuysIn, shelvedIn } from '../../data/buildingTypes'; +import { registerCustomTemplate, clearCustomTemplates } from '../customTemplates'; + +// The game's own shops at the table (8a7b3a; approved mockup docs/mockups/types-in-shops.html): building types of the game, +// by their names, shops while on, selling the types SOLD AT them; one that sells nothing and buys anything only buys. + +const SYS = 'sys_cafe0cafe0cafe0c'; +const POTIONS = { id: 'potions', label: 'POTIONS', one: 'Potion', sold_at: ['apothecary'], columns: [] }; + +beforeEach(() => { + clearCustomTemplates(); + registerCustomTemplate({ + id: SYS, name: 'Herbal', parts: {}, derived: [], sheet: { sections: [] }, words: {}, + buildings: { types: { general_store: { buys: 'anything' } }, shops: [{ id: 'apothecary', name: 'Apothecary', on: true }, { id: 'fence', name: 'Fence', on: true, buys: 'anything' }, { id: 'shrine', name: 'Shrine', on: false }] }, + items: { slots: [], list: [], types: [POTIONS] }, + } as never); +}); +afterEach(() => clearCustomTemplates()); + +describe('the game\'s own shops', () => { + it('read from its render copy; none in a built-in game', () => { + expect(ownShopsIn(SYS).map((s) => s.id)).toEqual(['apothecary', 'fence', 'shrine']); + expect(ownShopIn(SYS, 'fence')?.name).toBe('Fence'); + expect(ownShopIn(SYS, 'tavern')).toBeUndefined(); + expect(ownShopsIn('cities_without_number')).toEqual([]); + }); + + it('a building type of the game: a shop selling none of the app\'s, by its name; on as it says', () => { + expect(buildingTypeIn(SYS, 'apothecary')).toEqual({ id: 'apothecary', label: 'Apothecary', shop: true, sells: [] }); + expect(buildingTypeIn(SYS, 'gun_shop')?.label).toBe('Gun Shop'); + expect(buildingTypeIn(SYS, 'tavern')).toBeUndefined(); + expect(buildingTypeIn('cyberpunk_red', 'apothecary')).toBeUndefined(); + expect(typeLabel('apothecary', SYS)).toBe('Apothecary'); + expect(typeOn(SYS, 'apothecary')).toBe(true); + expect(typeOn(SYS, 'shrine')).toBe(false); + expect(isShopIn(SYS, 'apothecary')).toBe(true); + expect(isShopIn(SYS, 'shrine')).toBe(false); + expect(isShopIn('cyberpunk_red', 'apothecary')).toBe(false); + expect(isShopIn(SYS, 'bar')).toBe(false); + }); + + it('its shelves the types SOLD AT it; one selling nothing that buys anything only buys', () => { + expect(shelvedIn('apothecary', SYS)).toEqual(['type:potions']); + expect(onlyBuysIn(SYS, 'fence')).toBe(true); + expect(onlyBuysIn(SYS, 'apothecary')).toBe(false); + expect(onlyBuysIn(SYS, 'shrine')).toBe(false); + // Buying anything while it sells its gear: not only buying. + expect(onlyBuysIn(SYS, 'general_store')).toBe(false); + }); +});