diff --git a/CHANGELOG.md b/CHANGELOG.md index 945db293..ed7e14b3 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 +- **What a shop buys, on the server.** Each kind of shop, the app's and a game's own, can buy WHAT IT SELLS (as every shop always has) or ANYTHING: a Fence or a pawn shop takes every priced thing at its building's buyback rate, and the shop window's SELL list offers it all. Carried by the system file. The builder's BUYS setting comes with the game's own shops on FEATURES. - **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. diff --git a/README.md b/README.md index caedca11..47e61980 100644 --- a/README.md +++ b/README.md @@ -433,7 +433,7 @@ CITY_NET/ │ ├── sockets/ │ │ ├── tokenControl.js # Who may move a token, in one place because two move handlers ask it. An admin always may; the owner may; a friendly NPC may name players, or open to everyone. Only friendly NPCs can carry a grant, enforced here rather than by the caller, so one that reaches an enemy row through an import or a restore is inert — and anything unreadable in the column means nobody, since a malformed grant must never open a token up │ │ ├── choices.js # Picking on a custom system's sheet (7a3a): choicesAction ({ kind: pick | drop | level | use }) for the caller's own character, or the player the GM names; systemBuilder/picking.js says what may be done, this stores it through the sheet queue, works the numbers out again and tells every screen; a refusal goes back to the one who asked, in words. recoverySpend ({ pool, count }, R2a) spends recovery dice with a roll (sheets/recover.js), and kind recovery ticks them off; where the system leaves spending to the GM, a player is refused while the GM has it closed. restTake ({ rest }, R3a): a player rests their own character from their sheet where rests are finished on each sheet; the GM anyone's, always. ROLL FOR IT (7a5b2): { kind: 'roll', list, from } rolled on the secure dice, a dice-log line for everyone and the roll thrown in the tray; kits going ONLY IF not met worked out with the rest (7c4b); what an option gives, stored on it (7c4e); itemAction, wearing and attuning an item, the token following (7e3a); an install's limit read on the sheet as it is now (7e4a); spendAction, XP spent and the GM settling it (7f2a2); improveAction, an IMPROVE BY USE mark by hand (7f3a1); countAction (8a4a), a gear line's COUNT spent by its button or filled by RELOAD, answered by ack alone with the lines to ask between or why not (8a4b: said on the line that asked); FIRE and RELOAD worked out as any save is (8a5d1) -│ │ ├── index.js # All Socket.IO event handlers. Every write to a character sheet goes through sheets/mutate.js: rolls, damage, death saves, stabilisation, spell effort and vehicle hulls all touch sheets their owner is very likely looking at, and anything relative is worked out inside the write so two of them landing together both count. Sheet rolls and sheet attacks can come from an NPC's sheet (rollSheetOf): the GM's for any NPC, a player's for a friendly NPC the GM gave them, the log naming the NPC. requestTokenConditions answers a token's conditions with rounds left and modifiers to whoever may change them, and which conditions to anyone else A custom system's stat rolled as IMPROVE BY USE's MARKED BY says is marked (7f3a1).; requestSheetRoll also rolls a line of gear's DAMAGE or DICE (8a3b, { gear: { line, column } }); a band's condition following every sheet write (8a5d1); a battle map floor's start positions, SAVE and LOAD, the GM's alone: a save with no list refused rather than thrown, a player's token made once however many places are saved (8a9c2); an inventory written by updateSheetField keeps which lines are their item made unique, by whom and when (G5a); with PLAYERS CHANGE GEAR off, a player's inventory keeps its columns as stored (G6a) +│ │ ├── index.js # All Socket.IO event handlers. Every write to a character sheet goes through sheets/mutate.js: rolls, damage, death saves, stabilisation, spell effort and vehicle hulls all touch sheets their owner is very likely looking at, and anything relative is worked out inside the write so two of them landing together both count. Sheet rolls and sheet attacks can come from an NPC's sheet (rollSheetOf): the GM's for any NPC, a player's for a friendly NPC the GM gave them, the log naming the NPC. requestTokenConditions answers a token's conditions with rounds left and modifiers to whoever may change them, and which conditions to anyone else A custom system's stat rolled as IMPROVE BY USE's MARKED BY says is marked (7f3a1).; requestSheetRoll also rolls a line of gear's DAMAGE or DICE (8a3b, { gear: { line, column } }); a band's condition following every sheet write (8a5d1); a battle map floor's start positions, SAVE and LOAD, the GM's alone: a save with no list refused rather than thrown, a player's token made once however many places are saved (8a9c2); an inventory written by updateSheetField keeps which lines are their item made unique, by whom and when (G5a); with PLAYERS CHANGE GEAR off, a player's inventory keeps its columns as stored (G6a); checkout sells back to what a shop buys, ANYTHING taking every priced thing (8a7b1b) │ │ ├── initiativeOrder.js # Where a combatant stands in the initiative order, so a drag stands when later rolls are sorted in: a hidden place only where its roll doesn't already put it (keepDrag, worked out from the roll every time, never from an earlier place, and every place no longer needed let go), a late joiner kept at the bottom (atBottom), Shadowrun's pass taking the place down with the roll (lowered); the roll stays the one shown │ │ ├── sceneQueue.js # One scene's initiative changes one after another (found by 8i2's journey on CI): inTurn(key, work) runs work(done) once the one before has said done; other scenes never wait; work that throws or never says done lets the next go after 5 s │ │ ├── turnAsks.js # A condition's EACH TURN rolled by the player, or the GM for an NPC (8a9a2): requestTurnAsks (every ask for the GM, a player's own for them) and turnRoll, answered by ack @@ -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; 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 +│ │ ├── 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; what a shop BUYS (8a7b1b): WHAT IT SELLS or ANYTHING, on the app's shops and the game's own, checked (a bar buys nothing), buysOf, sent to the browser where it buys anything │ │ ├── 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); SOLD AT may tick the game's own shops (8a7b1a) +│ │ ├── 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); boughtAt, the shelves a shop buys back from: what it sells, or under ANYTHING every shelf the game prices (8a7b1b) │ │ ├── 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 @@ -650,6 +650,7 @@ CITY_NET/ │ ├── 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_shop_buys.test.js # What a shop BUYS (8a7b1b): WHAT IT SELLS or ANYTHING checked (a bar buys nothing), read, sent to the browser, carried by the system file; the shelves bought back from; a Fence on ANYTHING buying a draught it never sells at the building's rate, a General Store on ANYTHING too, not on WHAT IT SELLS │ ├── 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 @@ -882,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) +│ │ │ ├── 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) │ │ │ ├── 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() @@ -1201,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) +│ │ │ ├── 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) │ │ │ └── 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) @@ -1387,6 +1388,7 @@ CITY_NET/ │ │ │ ├── quickRolls.test.ts # What QUICK ACTIONS can roll, read off the real templates, so a roll added to or taken off a sheet shows up here │ │ │ ├── catalogueSchema.test.ts # An uploaded catalogue's columns derived from each system's own template, so the downloaded example can't drift │ │ │ ├── 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 │ │ │ ├── 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 diff --git a/backend/__tests__/system_builder_own_shops.test.js b/backend/__tests__/system_builder_own_shops.test.js index 8613b058..f14e9266 100644 --- a/backend/__tests__/system_builder_own_shops.test.js +++ b/backend/__tests__/system_builder_own_shops.test.js @@ -49,7 +49,7 @@ describe('checked', () => { 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(problemsOf([{ id: 'fence', name: 'Fence', sells: ['gear'] }])).toEqual([{ where: 'buildings shop 1, sells', message: 'Only "id", "name", "on" and "buys" 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' }]); diff --git a/backend/__tests__/system_builder_shop_buys.test.js b/backend/__tests__/system_builder_shop_buys.test.js new file mode 100644 index 00000000..079ff0ae --- /dev/null +++ b/backend/__tests__/system_builder_shop_buys.test.js @@ -0,0 +1,140 @@ +/** + * What a shop BUYS (8a7b1b; the user, 2026-11-21: "shops like pawns or fences that will buy anything"; drawn in the approved + * mockup docs/mockups/types-in-shops.html, section 4). WHAT IT SELLS, as every shop always has, or ANYTHING: every priced + * thing the game has, at the building's BUYBACK rate. Set on the app's shops and the game's own alike. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { createRequire } from 'module'; +import { makeTestDb, get, run } from './helpers/testDb.js'; +import { untilValue, drain } from './helpers/until.js'; + +const require_ = createRequire(import.meta.url); +const { checkDefinition } = require_('../systemBuilder/definition'); +const { buysOf, ownShops, ownBuildings, BUYS } = require_('../systemBuilder/buildings'); +const { boughtAt } = 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 = (buildings) => ({ + format: 1, name: 'Herbal', core: { health: { model: 'pool' } }, + stats: [{ id: 'abilities', label: 'ABILITIES', stats: [{ id: 'might', label: 'Might' }] }], + buildings, + items: { types: [{ ...POTIONS, sold_at: ['apothecary'] }], list: [{ id: 'draught', label: 'Healing Draught', type: 'potions', values: { heals: '2d4' }, price: 40 }] }, +}); +const SHOPS = [{ id: 'apothecary', name: 'Apothecary' }, { id: 'fence', name: 'Fence', buys: 'anything' }]; +const problemsOf = (buildings) => checkDefinition({ format: 1, name: 'A', buildings }).problems; + +describe('checked', () => { + it('WHAT IT SELLS or ANYTHING, on the app\'s shops and the game\'s own', () => { + expect(BUYS).toEqual(['sells', 'anything']); + expect(problemsOf({ types: { general_store: { buys: 'anything' }, gun_shop: { buys: 'sells' } }, shops: SHOPS })).toEqual([]); + }); + + it('names whatever it can\'t take; a building that is no shop buys nothing', () => { + const word = 'WHAT IT SELLS ("sells") or ANYTHING ("anything")'; + expect(problemsOf({ types: { general_store: { buys: 'all' } } })).toEqual([{ where: 'buildings types general_store, buys', message: word }]); + expect(problemsOf({ shops: [{ id: 'fence', name: 'Fence', buys: true }] })).toEqual([{ where: 'buildings shop 1, buys', message: word }]); + expect(problemsOf({ types: { bar: { buys: 'anything' } } })).toEqual([{ where: 'buildings types bar, buys', message: 'Only "name" and "on" are set here' }]); + expect(problemsOf({ types: { general_store: { sells: ['gear'] } } })).toEqual([{ where: 'buildings types general_store, sells', message: 'Only "name", "on" and "buys" are set here' }]); + expect(problemsOf({ shops: [{ id: 'fence', name: 'Fence', sells: ['gear'] }] })).toEqual([{ where: 'buildings shop 1, sells', message: 'Only "id", "name", "on" and "buys" are set here' }]); + }); +}); + +describe('read', () => { + const def = HERBAL({ types: { general_store: { buys: 'anything' }, gun_shop: { buys: 'sells' }, bar: { buys: 'anything' } }, shops: SHOPS }); + + it('ANYTHING where it says so; else, and in every built-in game, what it sells', () => { + expect(buysOf(def, 'general_store')).toBe('anything'); + expect(buysOf(def, 'fence')).toBe('anything'); + expect(buysOf(def, 'gun_shop')).toBe('sells'); + expect(buysOf(def, 'apothecary')).toBe('sells'); + expect(buysOf(def, 'bar')).toBe('sells'); + expect(buysOf(null, 'general_store')).toBe('sells'); + }); + + it('sent to the browser: on a shop that buys anything, and the game\'s own shop that does', () => { + expect(ownBuildings(def).types).toEqual({ general_store: { buys: 'anything' } }); + expect(ownShops(def)).toEqual([{ id: 'apothecary', name: 'Apothecary', on: true }, { id: 'fence', name: 'Fence', on: true, buys: 'anything' }]); + }); + + it('the shelves it buys back from: what it sells, or every shelf the game prices', () => { + expect(boughtAt(def, 'apothecary', ['type:potions'], ['gear', 'weapons'])).toEqual(['type:potions']); + expect(boughtAt(def, 'fence', [], ['gear', 'weapons'])).toEqual(['gear', 'weapons', 'type:potions']); + expect(boughtAt(def, 'general_store', ['gear'], ['gear', 'weapons'])).toEqual(['gear', 'weapons', 'type:potions']); + // A game with no types of its own: the app's shelves only. + expect(boughtAt({ buildings: { types: { general_store: { buys: 'anything' } } } }, 'general_store', ['gear'], ['gear', 'weapons'])).toEqual(['gear', 'weapons']); + }); + + it('carried by the system file, exported and read back unchanged', () => { + const read = citysys.readFile(JSON.stringify(citysys.buildFile({ definition: def, version: 1, origin: 'sys_herbalherbalherba' }))); + expect(read.file.definition.buildings).toEqual(def.buildings); + }); +}); + +describe('sold back 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 stall = async (type) => (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: `sb-${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 sell = async (who, locationId) => { + who.emitted.length = 0; + who.handlers.checkoutShop({ locationId, buys: [], sells: [{ catalogue: 'type:potions', id: 'item:draught', qty: 1 }] }); + return (await untilValue(() => [...who.emitted].reverse().find((e) => e.event === 'shopCheckout'), Boolean, { label: 'shopCheckout' })).data; + }; + const balance = async () => (await get(db, 'SELECT balance FROM bank_accounts WHERE username = ?', ['kes'])).balance; + const SHEET = JSON.stringify({ inventory: JSON.stringify([{ name: 'Healing Draught', qty: 1, carry: 'stowed', type: 'potions', values: { heals: '2d4' } }]) }); + + 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 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, SHEET]); + }); + + it('a Fence that buys anything takes the draught it never sells, at the building\'s rate, off the sheet', async () => { + await install(HERBAL({ shops: SHOPS })); + const fence = await stall('fence'); + await run(db, 'UPDATE locations SET buyback_pct = 50 WHERE id = ?', [fence]); + const kes = await boot('kes'); + expect(await sell(kes, fence)).toMatchObject({ ok: true, payout: 20 }); + expect(await balance()).toBe(120); + const sheet = JSON.parse((await get(db, 'SELECT data FROM character_sheets WHERE username = ?', ['kes'])).data); + expect(JSON.parse(sheet.inventory)).toEqual([]); + }); + + it('a General Store set to ANYTHING takes it; on WHAT IT SELLS, and as a Fence that doesn\'t, it is not sold', async () => { + await install(HERBAL({ types: { general_store: { buys: 'anything' } }, shops: [{ id: 'fence', name: 'Fence' }] })); + const goods = await stall('general_store'); + const fence = await stall('fence'); + const kes = await boot('kes'); + expect(await sell(kes, fence)).toMatchObject({ ok: false, reason: 'not_sold' }); + // The app's 45% of its 40. + expect(await sell(kes, goods)).toMatchObject({ ok: true, payout: 18 }); + await run(db, 'UPDATE character_sheets SET data = ? WHERE username = ?', [SHEET, 'kes']); + await install(HERBAL({ types: { general_store: { buys: 'sells' } } })); + expect(await sell(kes, goods)).toMatchObject({ ok: false, reason: 'not_sold' }); + }); +}); diff --git a/backend/sockets/index.js b/backend/sockets/index.js index d8b80b91..107714de 100644 --- a/backend/sockets/index.js +++ b/backend/sockets/index.js @@ -48,7 +48,7 @@ const vehicleSystems = require('../sheets/vehicleSystems'); const ram = require('../sheets/ram'); const enemyVehicles = require('../sheets/enemyVehicles'); const buildingTypes = require('../buildingTypes'); -const { typesOf, ownTypes, typeShelvesAt } = require('../systemBuilder/itemTypes'); +const { typesOf, ownTypes, typeShelvesAt, boughtAt } = require('../systemBuilder/itemTypes'); const { namesOf } = require('../systemBuilder/choices'); // The merged catalogue: what the app ships with, plus whatever a GM uploaded. const shopPrices = require('../shops/catalogueStore'); @@ -2380,7 +2380,10 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { ...buildingTypes.shelvedCatalogues(loc.building_type).filter((c) => customSystems.buildingIn(system, 'catalogues', c)), ...(definition ? typeShelvesAt(definition, loc.building_type) : []), ]; - if (!catalogues.length) return refuse('not_sold'); + // What it buys back (8a7b1b): what it sells, or with BUYS ANYTHING every shelf this game prices. + const bought = boughtAt(definition, loc.building_type, catalogues, + buildingTypes.CATALOGUES.filter((c) => c.shelved && customSystems.buildingIn(system, 'catalogues', c.id)).map((c) => c.id)); + if (!catalogues.length && !bought.length) return refuse('not_sold'); db.all( 'SELECT key, value FROM global_settings WHERE key IN (?, ?)', @@ -2405,7 +2408,7 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { let sheetData; try { sheetData = JSON.parse(sheetRow.data || '{}'); } catch { return refuse('no_sheet'); } sale = shopSell.planSale({ - data: sheetData, items: sells, catalogues, + data: sheetData, items: sells, catalogues: bought, locationPct: loc.buyback_pct, globalPct, system, }); if (!sale.ok) return refuse(sale.reason, { itemId: sale.itemId }); diff --git a/backend/systemBuilder/buildings.js b/backend/systemBuilder/buildings.js index 68a38e33..ee97504c 100644 --- a/backend/systemBuilder/buildings.js +++ b/backend/systemBuilder/buildings.js @@ -24,6 +24,12 @@ // 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 }] } +// +// What a shop BUYS (8a7b1b; the user, 2026-11-21: "shops like pawns or fences that will buy anything"): WHAT IT SELLS, as +// every shop always has, or ANYTHING, every priced thing this game has, at the building's BUYBACK rate. Set on the app's +// shops and the game's own alike, unset meaning WHAT IT SELLS: +// +// buildings: { types: { general_store: { buys: 'anything' } }, shops: [{ id: 'fence', name: 'Fence', buys: 'anything' }] } const { BUILDING_TYPES, CATALOGUES, shelvedCatalogues, isShop } = require('../buildingTypes'); const { partOn } = require('./parts'); @@ -36,7 +42,10 @@ const NAME_LIMIT = 40; 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 SHOP_KEYS = ['id', 'name', 'on', 'buys']; +/** What a shop buys back (8a7b1b): what it sells, or anything with a price. */ +const BUYS = ['sells', 'anything']; +const BUYS_MESSAGE = 'WHAT IT SELLS ("sells") or ANYTHING ("anything")'; const KINDS = { types: new Set(BUILDING_TYPES.map((t) => t.id)), @@ -61,10 +70,13 @@ const checkBuildings = (buildings, problems, currencyIds = []) => { const where = `buildings ${kind} ${id}`; if (!ids.has(id)) { problems.push({ where, message: kind === 'types' ? 'Not a building type of the app' : 'Not a shop catalogue of the app' }); continue; } if (!isPlainObject(setting)) { problems.push({ where, message: 'Must say a name, on, or both' }); continue; } - const keys = kind === 'catalogues' ? ['name', 'on', 'currency'] : ['name', 'on']; + // A shop also says what it BUYS (8a7b1b); a bar buys nothing. + const shop = kind === 'types' && isShop(id); + const keys = kind === 'catalogues' ? ['name', 'on', 'currency'] : shop ? ['name', 'on', 'buys'] : ['name', 'on']; for (const key of Object.keys(setting)) { - if (!keys.includes(key)) problems.push({ where: `${where}, ${key}`, message: kind === 'catalogues' ? 'Only "name", "on" and "currency" are set here' : 'Only "name" and "on" are set here' }); + if (!keys.includes(key)) problems.push({ where: `${where}, ${key}`, message: kind === 'catalogues' ? 'Only "name", "on" and "currency" are set here' : shop ? 'Only "name", "on" and "buys" are set here' : 'Only "name" and "on" are set here' }); } + if (shop && setting.buys !== undefined && !BUYS.includes(setting.buys)) problems.push({ where: `${where}, buys`, message: BUYS_MESSAGE }); if (kind === 'catalogues' && setting.currency !== undefined) { if (!currencyIds.length) problems.push({ where: `${where}, currency`, message: 'This system has no currencies of its own' }); else if (!currencyIds.includes(setting.currency)) problems.push({ where: `${where}, currency`, message: "Not one of this system's currencies" }); @@ -86,7 +98,7 @@ const checkShops = (shops, problems) => { 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' }); + for (const key of Object.keys(shop)) if (!SHOP_KEYS.includes(key)) problems.push({ where: `${where}, ${key}`, message: 'Only "id", "name", "on" and "buys" 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}` }); @@ -94,16 +106,17 @@ const checkShops = (shops, problems) => { 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' }); + if (shop.buys !== undefined && !BUYS.includes(shop.buys)) problems.push({ where: `${where}, buys`, message: BUYS_MESSAGE }); }); }; -/** The game's own kinds of shop (8a7b), those well formed, in its order: { id, name, on }. None for a game with none. */ +/** The game's own kinds of shop (8a7b), those well formed, in its order: { id, name, on }, and buys: 'anything' where it says so. 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 })); + .map((s) => ({ id: s.id, name: s.name.trim().slice(0, NAME_LIMIT), on: s.on !== false, ...(s.buys === 'anything' ? { buys: 'anything' } : {}) })); }; /** The game's own kind of shop by id (8a7b), or null where it has none of that id. */ @@ -118,6 +131,13 @@ const settingOf = (definition, kind, id) => { return isPlainObject(setting) ? setting : null; }; +/** What a kind of shop buys back in this game (8a7b1b): 'anything' where it says so, else 'sells', what it sells. Every built-in game's shops buy what they sell. */ +const buysOf = (definition, id) => { + const own = ownShopOf(definition, id); + const setting = own || (isShop(id) ? settingOf(definition, 'types', id) : null); + return setting && setting.buys === 'anything' ? 'anything' : 'sells'; +}; + /** * The catalogues that belong to a part of the app (parts.js): a system without vehicles sells * none of the garage's stock (3b4), and one without cyberware none of the ripperdoc's (3b5). @@ -179,7 +199,9 @@ const ownBuildings = (definition) => { const on = buildingOn(definition, kind, id); const own = kind === 'catalogues' ? (settingOf(definition, kind, id) || {}).currency : undefined; const currency = own !== undefined && catalogueCurrency(definition, id) === own ? own : undefined; - if (name || !on || currency) out[kind][id] = { ...(name ? { name } : {}), ...(on ? {} : { on: false }), ...(currency ? { currency } : {}) }; + // And a shop's BUYS where it buys anything (8a7b1b). + const buys = kind === 'types' && buysOf(definition, id) === 'anything' ? 'anything' : undefined; + if (name || !on || currency || buys) out[kind][id] = { ...(name ? { name } : {}), ...(on ? {} : { on: false }), ...(currency ? { currency } : {}), ...(buys ? { buys } : {}) }; } } // And the game's own shops (8a7b), each as it is, for SOLD AT and the BUILDING TYPE list: only where it makes some. @@ -187,4 +209,4 @@ const ownBuildings = (definition) => { return shops.length ? { ...out, shops } : out; }; -module.exports = { checkBuildings, buildingOn, buildingName, catalogueCurrency, ownBuildings, ownShops, ownShopOf, shopKindsOf, NAME_LIMIT, SHOPS_MOST }; +module.exports = { checkBuildings, buildingOn, buildingName, catalogueCurrency, ownBuildings, ownShops, ownShopOf, shopKindsOf, buysOf, BUYS, NAME_LIMIT, SHOPS_MOST }; diff --git a/backend/systemBuilder/itemTypes.js b/backend/systemBuilder/itemTypes.js index 75a8d965..91f07101 100644 --- a/backend/systemBuilder/itemTypes.js +++ b/backend/systemBuilder/itemTypes.js @@ -26,7 +26,7 @@ const { boxProblem } = require('./tierRolls'); const { BUILDING_TYPES } = require('../buildingTypes'); -const { shopKindsOf } = require('./buildings'); +const { shopKindsOf, buysOf } = require('./buildings'); const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v); const list = (v) => (Array.isArray(v) ? v : []); @@ -85,6 +85,13 @@ const soldAt = (type, definition) => { const typeShelvesAt = (definition, buildingType) => (ownTypes(definition) ? typesOf(definition).filter((t) => soldAt(t, definition).includes(buildingType)).map((t) => `type:${t.id}`) : []); +/** + * The shelves a kind of shop buys back from (8a7b1b): those it sells (`sold`), or, where it BUYS ANYTHING, every shelf this + * game prices: the app's catalogues it has on (`onCatalogues`) and each of its own types'. + */ +const boughtAt = (definition, buildingType, sold, onCatalogues) => (buysOf(definition, buildingType) === 'anything' + ? [...new Set([...sold, ...onCatalogues, ...(ownTypes(definition) ? typesOf(definition).map((t) => `type:${t.id}`) : [])])] : sold); + /** 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]; }; @@ -263,4 +270,4 @@ const lineColumns = (definition, line, items, names) => { return { type: type.id, ...(item ? { item: item.id } : {}), values, counts }; }; -module.exports = { BANDS, DEFAULT_BAND, bandOf, PRICE_COLUMN, MOST_PRICE, isPrice, itemPrice, inShops, KINDS, LIMITS, GEAR, NAME, SHOP_TYPES, DEFAULT_SOLD_AT, soldAt, typeShelvesAt, linesOf, typesOf, ownTypes, typeNamed, valueProblem, checkTypes, checkItemType, typesShown, itemValues, lineColumns }; +module.exports = { BANDS, DEFAULT_BAND, bandOf, PRICE_COLUMN, MOST_PRICE, isPrice, itemPrice, inShops, KINDS, LIMITS, GEAR, NAME, SHOP_TYPES, DEFAULT_SOLD_AT, soldAt, typeShelvesAt, boughtAt, linesOf, typesOf, ownTypes, typeNamed, valueProblem, checkTypes, checkItemType, typesShown, itemValues, lineColumns }; diff --git a/e2e/COVERAGE.md b/e2e/COVERAGE.md index 780e362b..529d1105 100644 --- a/e2e/COVERAGE.md +++ b/e2e/COVERAGE.md @@ -35,6 +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; set in the builder in 8a7b | `shop_typed_lines`, `typedShelves` | `shop-typed-lines` (unsaid: the General Store) | **AT THE TABLE** unsaid; a kind of shop picked waits for 8a7b's box | +| 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`, `system_builder_shop_buys`, `shopBuys`, `ShopWindow` | | **GAP** until the builder sets them: + NEW SHOP in 8a7b2, BUYS and the BUILDING TYPE list in 8a7b3, each with its journey | | 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/frontend/src/components/ShopWindow.tsx b/frontend/src/components/ShopWindow.tsx index b4ae2f43..7d0e9533 100644 --- a/frontend/src/components/ShopWindow.tsx +++ b/frontend/src/components/ShopWindow.tsx @@ -1,7 +1,7 @@ import React, { useDeferredValue, useEffect, useState } from 'react'; import { TerminalWindow } from './TerminalWindow'; import { - buildingTypeById, shelvedIn, catalogueById, typeLabel, catalogueLabel, itemTypeOfShelf, type ShopStock, + buildingTypeById, shelvedIn, boughtIn, catalogueById, typeLabel, catalogueLabel, itemTypeOfShelf, type ShopStock, } from '../data/buildingTypes'; import { SETTLE_BALANCE, SETTLE_DEBT, refusalText, buybackValue, @@ -496,7 +496,8 @@ export function ShopWindow({ // A custom system's items installed (7e4c) stay on the sheet, never sold: the server refuses them too. const installed = sheet ? installedNames(customTemplate(system)?.items, itemsWorkedOn(sheet.data as Record)) : new Set(); const owned = sheet ? ownedItems(sheet.data as Record, system).filter((l) => !installed.has(l.label.trim().toLowerCase())) : []; - const sellable = sellableAt(owned, catalogues); + // What it buys back (8a7b1b): what it sells, or with BUYS ANYTHING every priced thing. + const sellable = sellableAt(owned, boughtIn(buildingType, system, catalogues)); const sellQuery = sellFilter.trim().toLowerCase(); /** The sell list as shown: narrowed by its filter. Totals still count the whole list. */ const shownSellable = sellQuery ? sellable.filter((l) => l.label.toLowerCase().includes(sellQuery)) : sellable; diff --git a/frontend/src/components/__tests__/ShopWindow.test.tsx b/frontend/src/components/__tests__/ShopWindow.test.tsx index e2b8ad74..c4a1bf19 100644 --- a/frontend/src/components/__tests__/ShopWindow.test.tsx +++ b/frontend/src/components/__tests__/ShopWindow.test.tsx @@ -2215,6 +2215,38 @@ describe('the shop\'s refusals', () => { }); }); +// ─── What a shop buys (8a7b1b) ────────────────────────────────────────────────── +describe('a shop that buys anything (8a7b1b)', () => { + const PAWN = 'sys_baba0baba0baba0b'; + const SHEET = { system: PAWN, data: { inventory: JSON.stringify([{ name: 'Rope', qty: 1, carry: 'stowed' }, { name: 'Zip Gun', qty: 1, carry: 'stowed' }]) } }; + const game = (buys?: 'anything') => registerCustomTemplate({ + id: PAWN, name: 'Pawn', parts: {}, derived: [], sheet: { sections: [] }, words: {}, + buildings: { types: buys ? { general_store: { buys } } : {} }, + }); + + beforeEach(() => { + clearCustomTemplates(); + loadUploaded({ gear: [{ id: 'rope', name: 'Rope', price: 100, fields: {} }], weapons: [{ id: 'zip_gun', name: 'Zip Gun', price: 200, fields: {} }] }); + sheetState.sheet = SHEET; + }); + afterEach(() => { clearCustomTemplates(); clearUploaded(); }); + + it('offers to buy back a gun at the General Store, priced at its rate; one on WHAT IT SELLS, only its gear', async () => { + game('anything'); + const { unmount } = show('general_store', 'Pawn', PAWN); + await openFolder('SELL'); + expect(screen.getByRole('button', { name: 'Add Zip Gun to the cart' })).toBeInTheDocument(); + expect(within(screen.getByText('Zip Gun').closest('tr')!).getByText('90cr')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Add Rope to the cart' })).toBeInTheDocument(); + unmount(); + game(); + show('general_store', 'Goods', PAWN); + await openFolder('SELL'); + expect(screen.getByRole('button', { name: 'Add Rope to the cart' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Add Zip Gun to the cart' })).toBeNull(); + }); +}); + // ─── A shelf of an item type (8a7a2) ──────────────────────────────────────────── describe('a shelf of an item type (8a7a2)', () => { const TYPED = 'sys_dddddddddddddddd'; diff --git a/frontend/src/data/buildingTypes.ts b/frontend/src/data/buildingTypes.ts index f8036378..94451754 100644 --- a/frontend/src/data/buildingTypes.ts +++ b/frontend/src/data/buildingTypes.ts @@ -194,6 +194,23 @@ export const shelvedIn = ( ...ownItemTypes(system).filter((t) => (t.sold_at ?? []).includes(String(id ?? ''))).map((t) => `type:${t.id}` as ShopStock), ]; +/** 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; + const key = String(id ?? ''); + return (buildings?.shops?.find((s) => s.id === key) ?? buildings?.types?.[key])?.buys === 'anything' ? 'anything' : 'sells'; +}; + +/** + * The shelves a shop of this type buys back from (8a7b1b): what it sells (`sold`), or where it BUYS ANYTHING every shelf + * this game prices, the app's it has on and each of its own types'. The server takes the same list (itemTypes.js boughtAt). + */ +export const boughtIn = (id: string | null | undefined, system: string | null | undefined, sold: ShopStock[]): ShopStock[] => + (buysIn(system, id) === 'anything' + ? [...new Set([...sold, ...CATALOGUES.filter((c) => c.shelved && catalogueOn(system, c.id)).map((c) => c.id), + ...ownItemTypes(system).map((t) => `type:${t.id}` as ShopStock)])] + : sold); + /** A custom system's own item types, as its render copy says them (8a7a2); none for a built-in game. */ export const ownItemTypes = (system: string | null | undefined) => customTemplate(String(system ?? ''))?.items?.types ?? []; diff --git a/frontend/src/sheets/__tests__/shopBuys.test.ts b/frontend/src/sheets/__tests__/shopBuys.test.ts new file mode 100644 index 00000000..a6e7d77e --- /dev/null +++ b/frontend/src/sheets/__tests__/shopBuys.test.ts @@ -0,0 +1,44 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { buysIn, boughtIn, shelvedIn, type ShopStock } from '../../data/buildingTypes'; +import { registerCustomTemplate, clearCustomTemplates } from '../customTemplates'; + +// What a shop BUYS (8a7b1b): what it sells, or ANYTHING, every shelf the game prices; the server takes the same list +// (backend systemBuilder/itemTypes.js boughtAt). + +const SYS = 'sys_baba0baba0baba0b'; +const POTIONS = { id: 'potions', label: 'POTIONS', one: 'Potion', sold_at: ['apothecary'], columns: [] }; + +beforeEach(() => { + clearCustomTemplates(); + registerCustomTemplate({ + id: SYS, name: 'Pawn', parts: {}, derived: [], sheet: { sections: [] }, words: {}, + buildings: { types: { general_store: { buys: 'anything' } }, catalogues: { vehicles: { on: false } }, + shops: [{ id: 'apothecary', name: 'Apothecary', on: true }, { id: 'fence', name: 'Fence', on: true, buys: 'anything' }] }, + items: { slots: [], list: [], types: [POTIONS] }, + } as never); +}); +afterEach(() => clearCustomTemplates()); + +describe('what a shop buys', () => { + it('ANYTHING where the game says so, on the app\'s shops and its own; else, and in a built-in game, what it sells', () => { + expect(buysIn(SYS, 'general_store')).toBe('anything'); + expect(buysIn(SYS, 'fence')).toBe('anything'); + expect(buysIn(SYS, 'gun_shop')).toBe('sells'); + expect(buysIn(SYS, 'apothecary')).toBe('sells'); + expect(buysIn('cities_without_number', 'general_store')).toBe('sells'); + }); + + it('the shelves it buys back from: what it sells, or every shelf the game has on and each of its types\'', () => { + const sold = shelvedIn('gun_shop', SYS); + expect(boughtIn('gun_shop', SYS, sold)).toEqual(sold); + const all = boughtIn('general_store', SYS, ['gear' as ShopStock]); + expect(all).toEqual(expect.arrayContaining(['gear', 'weapons', 'armor', 'pharmaceuticals', 'cyberware', 'type:potions'])); + // A catalogue turned off, or one no shop shelves, is bought nowhere. + expect(all).not.toContain('vehicles'); + expect(all).not.toContain('cyber_mods'); + expect(new Set(all).size).toBe(all.length); + // The game's own Fence, selling nothing, buys the same. + expect([...boughtIn('fence', SYS, [])].sort()).toEqual([...all].sort()); + expect(boughtIn('general_store', 'cities_without_number', ['gear' as ShopStock])).toEqual(['gear']); + }); +}); diff --git a/frontend/src/sheets/customTemplates.ts b/frontend/src/sheets/customTemplates.ts index d277b8b1..3bf587ad 100644 --- a/frontend/src/sheets/customTemplates.ts +++ b/frontend/src/sheets/customTemplates.ts @@ -38,9 +38,12 @@ export interface CustomRenderSheet { /** A system's own names for the app's building types and catalogues, and which it turned off. */ export interface CustomBuildings { - types?: Record; + /** A shop may buy ANYTHING (8a7b1b, backend systemBuilder/buildings.js buysOf); unset, what it sells. */ + types?: Record; /** A catalogue may name the currency it is priced in (sheets/currencies.ts catalogueCurrencyFor). */ catalogues?: Record; + /** The game's own kinds of shop (8a7b), where it makes some. */ + shops?: { id: string; name: string; on: boolean; buys?: 'anything' }[]; } export interface CustomRender { diff --git a/frontend/src/sheets/types.ts b/frontend/src/sheets/types.ts index fc4a43bf..43f8f27d 100644 --- a/frontend/src/sheets/types.ts +++ b/frontend/src/sheets/types.ts @@ -286,7 +286,7 @@ export interface SheetTemplate { parts?: Record; /** The building types and shop catalogues a custom system renamed or turned off * (data/buildingTypes.ts reads them). Absent on the built-in systems. */ - buildings?: { types?: Record; catalogues?: Record }; + buildings?: import('./customTemplates').CustomBuildings; /** A custom system's currencies, the first the main one (sheets/currencies.ts reads them). * Absent on the built-in systems, which keep the app's single money. */ currencies?: import('./currencies').Currency[];