diff --git a/CHANGELOG.md b/CHANGELOG.md index b2e96a57..f5f8a27c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Fixed +- **Selling back typed gear from the shop window.** A line of one of your item types, or one of your own items, could be bought but not sold back: the shop window didn't recognize it, and the sale was refused. It now sells back at the shop's buyback rate, and a new browser test sells one and checks the money. - **A catalogue section that names nothing is now said.** A section like `[rocks]`, which is neither a shelf nor one of your item types, used to be saved quietly where no shop would ever sell it. The preview now says so, listing your types, and its lines are not saved. - **The bank's windows now follow the theme.** BANK.EXE, PAYROLL.EXE and the GM's BANK_ADMIN.EXE drew in the classic green and grey whatever theme was picked; their boxes, numbers, chart and celebrations now take the theme's colors. - **The bank's boxes have names a screen reader can say.** PAYROLL.EXE's amount and each player's tick box, BANK_ADMIN.EXE's Balance and Debt, and the amount you withdraw or borrow are now named, and clicking a player's name in PAYROLL.EXE ticks them. @@ -104,6 +105,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added +- **One-of-a-kind items sell back.** An item kept out of the shops is never on a shelf, but a player can still sell one to a shop that sells its type, at the item's own price times that shop's buyback rate. A ring sells at an Armorer, never at a Gun Shop. - **The shop catalogue knows your items.** In a game whose items sell themselves, PREVIEW in SHOP_CATALOGUES now says how many of your items are also on sale, and which lines in your file overrule one ("Pistol: overrules the item, 200 → 260 in the shops"). A line that's exactly one of your items, same price and columns, is left out, since the item already sells itself. So is a line naming an item kept out of the shops. The preview says why for each line, and SAVE leaves out the same lines. - **PRICE and IN SHOPS in the ITEMS page's files.** In a game with item types of its own, DOWNLOAD EXAMPLE and DOWNLOAD THIS LIST have a price column (for a type without a PRICE column of its own) and an in shops column, yes or no. IMPORT reads them: write - to clear one, and a price or a yes/no that isn't one is skipped and named by its line. A list downloaded and imported back changes nothing. - **PRICE and IN SHOPS on the ITEMS page.** In a game with item types of its own, every item has a PRICE under its TYPE. If the type has a PRICE column, that column is shown there, once. Beside it, IN SHOPS says whether the shops sell the item: switched off, it's never sold and is tagged NOT SOLD in the list, for a one-of-a-kind ring or a quest item. A new item starts IN SHOPS and asks for its price until it has one. Moving an item to another type keeps its price. A PRICE column in the ITEMS import and downloads comes next. diff --git a/README.md b/README.md index fd9042c1..bee17537 100644 --- a/README.md +++ b/README.md @@ -416,13 +416,13 @@ CITY_NET/ │ │ ├── bookPlacement.js # Where a CWN book item lands, on the server, for GIVE ITEM: the twin of the shop's own sheets/bookPlacement.ts (a carried weapon row Stowed, a vehicle row from its stat block with the * / ** note, cyberware unplaced, inventory lines with Encumbrance, a dose stacked by any of its names), for a book row or a GM's upload shaped as one (asBookRow) │ │ ├── bookItems.js # The CWN book's items as the server needs them to place one: weapon and vehicle stat blocks, cyberware details, armor and gear Encumbrance. Generated from the frontend's book files, not retyped, and held to them by serverBookPlacement.test.ts │ │ ├── give.js # What a GM can give, for GIVE ITEM: everything the running game's shops could sell, free (the CWN book's items on CWN, the GM's uploads everywhere, only on shelves the game has on), and where a gift lands, the book's way on a CWN book shelf and the uploaded way elsewhere, so many of it all or none; every one of a custom system's item types too (8a7a2), sold anywhere or not, a gift landing as a line of its type; the game's own items aren't listed again under their type (8a7a3a), GIVE's ITEMS folder has them all -│ │ ├── sell.js # Prices a sell basket and builds the sheet patch. A row is emptied of exactly the fields that system's template draws for it (sheetSlots), so a vehicle takes its mounts and fittings with it and a Cyberpunk RED gun its ROF. Refuses without a known system rather than guessing CWN; a basket that fails part way empties nothing; refuses a custom system's installed line (7e4a, reason installed) +│ │ ├── sell.js # Prices a sell basket and builds the sheet patch. A row is emptied of exactly the fields that system's template draws for it (sheetSlots), so a vehicle takes its mounts and fittings with it and a Cyberpunk RED gun its ROF. Refuses without a known system rather than guessing CWN; a basket that fails part way empties nothing; refuses a custom system's installed line (7e4a, reason installed); priced as a shop buys back (sellPriceOf), so a one-of-a-kind item kept out of the shops pays its own price at the shop's rate (8a7a3c2) │ │ ├── checkout.js # A shop cart, settled as one: prices from the server, the sale through sell.js, the account moved once by the difference, and nothing moved unless every line is good. Refuses a total that changed since the player was shown it │ │ ├── sheetSlots.js # Where each system keeps weapons and vehicles: row counts and every field a row owns, nested mounts included. The server's templates carry no field ids, so this is a copy of what the frontend reads out of its templates, compared entry for entry by a test │ │ ├── availability.js # Whether a system has shops: a sheet the shops know (a built-in, or any published custom system, whose purchases are inventory lines), with shops and the bank both on │ │ ├── catalogueParse.js # Reads a catalogue a GM pasted or uploaded: CSV, TSV or JSON, real RFC-4180 quoting, per-line problems rather than exceptions. The only reader - the preview is a round trip to it; a section per item type (8a7a1): [GUNS], [gun] or [MELEE WEAPONS] is lines of the system's own type, a type winning over a shelf of its name, each column read as it holds (numbers, PICK ONE's own word) and checked as the builder checks an item's, a row that doesn't fit left out and said, blanks kept and noted once a row; a section that is neither a type nor a shelf said, its rows not saved │ │ ├── catalogueStore.js # Uploaded catalogues in memory, added on top of the built-in ones, never replacing them. Holds one system at a time, and consults the built-in book only when that system is CWN - every other game's shops carry only what their GM uploaded. Requires nothing, so priceOf stays synchronous and the lot stays importable from a frontend test -│ │ ├── ownItems.js # The game's own items on the shelves (8a7a3a; decided 2026-11-21): each priced and IN SHOPS a line of its type's catalogue, its values and words as fields; the names of those turned off. Pure, worked out once per definition. A catalogue file held against them (againstItems, 8a7a3c1): an exact copy of an item left out, one kept out of the shops left out, one of an item's name overruling it, and how many sell themselves besides. The running game's own items (8a7a3a, ownItems.js, set by the sockets) sit under the uploaded lines: a line uploaded with an item's name wins, an item turned off keeps a line of its name off the shelves +│ │ ├── ownItems.js # The game's own items on the shelves (8a7a3a; decided 2026-11-21): each priced and IN SHOPS a line of its type's catalogue, its values and words as fields; the names of those turned off. Pure, worked out once per definition. A catalogue file held against them (againstItems, 8a7a3c1): an exact copy of an item left out, one kept out of the shops left out, one of an item's name overruling it, and how many sell themselves besides; the items turned off with a price, bought back by a shop of their type (8a7a3c2). The running game's own items (8a7a3a, ownItems.js, set by the sockets) sit under the uploaded lines: a line uploaded with an item's name wins, an item turned off keeps a line of its name off the shelves │ │ └── catalogueDb.js # The only piece that knows uploaded catalogues live in SQLite. A save replaces one catalogue wholesale, in a transaction │ ├── tokens/ │ │ ├── conditions.js # A token's conditions as stored ([{ id, left }]): read safely, checked against what the running system offers (one twice, an unknown one, rounds out of 1 to 99 refused by name; one that ends after rounds starting at its own), shown to everyone without the rounds left, a hidden one (a house rule off) kept as it was, and counted down a round at a time for a combat's tokens (tickCombat), coming off at none; `started` kept for one ending AT THE END OF ITS NEXT TURN, through an edit too (8a9a) @@ -606,7 +606,7 @@ CITY_NET/ │ ├── shop_buy_sockets.test.js # Buying through the socket as a cart of one, the old buy handler's cases moved across whole │ ├── shop_sell_sockets.test.js # Selling through the socket as a cart with nothing to buy, the old sell handler's cases moved across whole │ ├── shop_items_on_sale.test.js # The game's own items on the shelves (8a7a3a): a price, its own or its type's PRICE column's; IN SHOPS, one saved before it by its price; checked and carried by the system file; the lines they make; under the uploads in the store (a line of an item's name wins, one turned off never sold); bought, sold back at the BUYBACK rate, not again in GIVE's type folders; a catalogue file held against them, its preview and its save (8a7a3c1) -│ ├── shop_typed_lines.test.js # Lines of an item type sold and given (8a7a2): SOLD AT, the General Store unsaid, checked and carried by the system file; a typed line placed and stacked only onto the same thing untouched; bought at a shop that sells the type and refused at one that doesn't, sold back, given from GIVE +│ ├── shop_typed_lines.test.js # Lines of an item type sold and given (8a7a2): SOLD AT, the General Store unsaid, checked and carried by the system file; a typed line placed and stacked only onto the same thing untouched; bought at a shop that sells the type and refused at one that doesn't, sold back at exactly the app's 45%, given from GIVE │ ├── shop_catalogue_types.test.js # A catalogue section per item type (8a7a1): by name, one or id in any case, spaces, columns by name; a value that doesn't fit said in the builder's words; blanks one note; a type over a shelf of its name; JSON; a section that is neither said; through the sockets, the preview by the type's name, saved under it, sent to players │ ├── shop_catalogue_parse.test.js # Reading a GM's catalogue: commas inside names, semicolons from a European Excel, a byte-order mark, a price with its symbol; problems per line, never a throw │ ├── shop_catalogue_store.test.js # Uploaded catalogues added to the built-in ones, never replacing them @@ -1220,9 +1220,9 @@ CITY_NET/ │ │ │ ├── cwnWeaponPresets.ts # 32 weapons from the book with their real damage, trauma, shock and Encumbrance; the footnote markers are stripped off the damage and kept as a note │ │ │ ├── cwnArmorPresets.ts # The armor table (p53): 14 pieces in three groups. Accessories add to AC where armor sets it. Obsolete Tech is kept as a constant, not a row, because its penalties are rolled after the sale │ │ │ ├── cwnGearPresets.ts # Common Operator Gear (p50), 27 items. The Enc column's ~ and * are kept as a note beside a numeric Enc, so the encumbrance sum never has to parse a symbol -│ │ │ ├── ownedItems.ts # What a character owns, from inventory rows, weapon slots and stash, cyberware and vehicle slots, reading the rows that system's sheet has. Consults the CWN book only on CWN. Mirrored from backend/shops/owned.js and run against it on every system. Boxed chrome is listed before installed, so selling one of two sells the spare +│ │ │ ├── ownedItems.ts # What a character owns, from inventory rows, weapon slots and stash, cyberware and vehicle slots, reading the rows that system's sheet has. Consults the CWN book only on CWN. Mirrored from backend/shops/owned.js and run against it on every system. Boxed chrome is listed before installed, so selling one of two sells the spare. A line is found on the game's type shelves too, and an item kept out of the shops is priced as a shop buys it back (8a7a3c2) │ │ │ ├── catalogueSchema.ts # The shape of an uploaded catalogue, read out of each system's own sheet template rather than written down - so the example a GM downloads cannot drift. Also writes the 'download current' file, with the built-in rows behind a #; a section per item type first in a custom system with types of its own (8a7a1): its name as heading where it reads back (else its id), its columns after name and price, a sample line behind a # in EXAMPLE, its lines in CURRENT, the game's own items behind a # there so uploading it back repeats none (8a7a3a) -│ │ │ ├── uploadedCatalogues.ts # What the GM uploaded, as the window sees it, so shelves and the SELL tab can show what the server would sell; uploadedOf, the server's catalogues as a shop keeps them, the uploaded entries and the game's own items on a type's shelf (8n1, 8a7a3a) +│ │ │ ├── uploadedCatalogues.ts # What the GM uploaded, as the window sees it, so shelves and the SELL tab can show what the server would sell; uploadedOf, the server's catalogues as a shop keeps them, the uploaded entries and the game's own items on a type's shelf (8n1, 8a7a3a); what a shop buys back of the items kept out of the shops (loadBuyback, 8a7a3c2) │ │ │ ├── sheetSlots.ts # Where each system's sheet keeps weapons and vehicles, read out of the templates: rows are the highest numbered name field, fields are everything row 1 declares. The source the server's copy is checked against │ │ │ ├── quickRolls.ts # What QUICK ACTIONS can roll, read off the sheet template: fields with a roll outside a skills section as buttons, skills grouped for the picker, house-rule-hidden tabs left out │ │ │ ├── shopPlacement.ts # Where a bought uploaded item lands on any system's sheet: the first free row of its group with only the fields that row has, a new unplaced cyberware row where the sheet draws that table, or an inventory line. Pure, and run twice - to refuse before paying, and again when the receipt arrives. A type's shelf (8a7a2): a line of the type with its columns as values, as the server places it @@ -1378,7 +1378,7 @@ CITY_NET/ │ │ │ ├── distance.test.ts # The ruler in each unit: meters and yards converted from feet, squares and hexes counted, zones with no number, feet where none was given │ │ │ ├── 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 +│ │ │ ├── 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) │ │ │ ├── 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 @@ -1557,7 +1557,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-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 +│ ├── 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-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 │ ├── sheet-level-up.spec.ts # Going up a level (7d2b): XP reaches it and the player goes up, one class of two, the rest carrying over; milestone's level given by the GM and taken by the player; LEVEL_DOWN; an uploaded sheet bringing its XP (7d2c); LEVEL_UP.EXE: which class, left and come back to, what it unlocks, FINISH (7d3a); a pick the new level opens, then a new class (7d3b) │ ├── sheet-level-record.spec.ts # What each level gained (7d7b2): the GM clears a past roll, the player rolls it again, the maximum follows; the GM sets one; an uploaded HP MAX the base, one line, cleared by the GM (7d7c) diff --git a/backend/__tests__/shop_items_on_sale.test.js b/backend/__tests__/shop_items_on_sale.test.js index bedc7d44..b73a3675 100644 --- a/backend/__tests__/shop_items_on_sale.test.js +++ b/backend/__tests__/shop_items_on_sale.test.js @@ -92,6 +92,8 @@ describe('the lines they make', () => { 'type:armor': [{ id: 'item:jacket', name: 'Leather Jacket', price: 50, fields: { defense: 2 } }], }); expect([...stock.off]).toEqual(['ring of might', 'rope']); + // Turned off with a price: bought back by a shop of its type, never on a shelf (8a7a3c2); the Rope, with none, not. + expect(stock.buyback).toEqual({ 'type:armor': [{ id: 'item:ring', name: 'Ring of Might', price: 5000 }] }); // Worked out once for a definition. expect(ownStock(DEF)).toBe(stock); }); @@ -139,7 +141,13 @@ describe('in the store, under the uploads', () => { expect(store.priceOf('type:armor', 'ring_of_might')).toBeNull(); expect(store.labelOf('type:armor', 'ring_of_might')).toBeNull(); expect(store.fieldsOf('type:armor', 'ring_of_might')).toEqual({}); - expect(store.findByName('Ring of Might')).toBeNull(); + // Found by name only as the item it is, to sell back at its own price, never to buy (8a7a3c2). + expect(store.findByName('Ring of Might')).toEqual({ catalogue: 'type:armor', id: 'item:ring' }); + expect(store.priceOf('type:armor', 'item:ring')).toBeNull(); + expect(store.sellPriceOf('type:armor', 'item:ring')).toBe(5000); + expect(store.labelOf('type:armor', 'item:ring')).toBe('Ring of Might'); + expect(store.sellPriceOf('type:armor', 'ring_of_might')).toBeNull(); + expect(store.sellPriceOf('type:armor', 'item:jacket')).toBe(50); // Still uploaded, for the GM's file. expect(store.uploadedIn('type:armor').map((e) => e.name)).toEqual(['Ring of Might']); }); @@ -233,6 +241,26 @@ describe('at the table', () => { expect(await balance()).toBe(1100); }); + it('a one-of-a-kind item kept out of the shops: sold back where its type is sold, at its price and the shop\'s rate; never at another (8a7a3c2)', async () => { + await run(db, 'UPDATE character_sheets SET data = ? WHERE username = ?', [JSON.stringify({ inventory: JSON.stringify([{ name: 'Ring of Might', qty: 1, enc: '', bundled: false, carry: 'stowed', location: '', type: 'armor' }]) }), 'kes']); + const kes = await boot('kes', false); + // Not at the General Store, which sells no ARMOR: no ring at a gun shop. + expect(await checkout(kes, goods, { buys: [], sells: [{ catalogue: 'type:armor', id: 'item:ring', qty: 1 }] })).toMatchObject({ ok: false, reason: 'not_sold' }); + kes.emitted.length = 0; + // Nor bought, anywhere. + expect(await checkout(kes, arms, { buys: [{ catalogue: 'type:armor', itemId: 'item:ring', qty: 1 }] })).toMatchObject({ ok: false }); + kes.emitted.length = 0; + // At the Armorer, at the app's 45%: 5000 → 2250. + expect(await checkout(kes, arms, { buys: [], sells: [{ catalogue: 'type:armor', id: 'item:ring', qty: 1 }] })).toMatchObject({ ok: true, payout: 2250 }); + expect(await balance()).toBe(3250); + }); + + it('the window is told what a shop buys back with the catalogues (8a7a3c2)', async () => { + const kes = await boot('kes', false); + kes.handlers.requestCatalogues(); + expect((await last(kes.emitted, 'catalogues')).data.buyback).toEqual({ 'type:armor': [{ id: 'item:ring', name: 'Ring of Might', price: 5000 }] }); + }); + it('a line uploaded with its name wins: one Pistol, at the file\'s price', async () => { const gm = await boot('gm', true); gm.handlers.saveCatalogue({ text: '[WEAPONS]\nname, price, damage\nPistol, 260, 2d6\n' }); diff --git a/backend/__tests__/shop_typed_lines.test.js b/backend/__tests__/shop_typed_lines.test.js index 03c1a29c..703a6691 100644 --- a/backend/__tests__/shop_typed_lines.test.js +++ b/backend/__tests__/shop_typed_lines.test.js @@ -177,7 +177,9 @@ describe('at the table', () => { const out = await checkout(kes, store_, { buys: [], sells: [{ catalogue: 'type:guns', id: 'pistol', qty: 1 }] }); expect(out).toMatchObject({ ok: true }); expect(await inventoryOf('kes')).toEqual([]); - expect((await get(db, 'SELECT balance FROM bank_accounts WHERE username = ?', ['kes'])).balance).toBeGreaterThan(1000); + // Exactly the app's 45% of its 250 (8a7a3c2; it said only "more than 1000"). + expect(out).toMatchObject({ payout: 112 }); + expect((await get(db, 'SELECT balance FROM bank_accounts WHERE username = ?', ['kes'])).balance).toBe(1112); }); it('GIVE: every type offered, sold anywhere or not; given, a line of its type with its values', async () => { diff --git a/backend/shops/catalogueStore.js b/backend/shops/catalogueStore.js index 96e6ce8b..9df57c4c 100644 --- a/backend/shops/catalogueStore.js +++ b/backend/shops/catalogueStore.js @@ -45,7 +45,7 @@ const bookApplies = () => loadedSystem === BOOK_SYSTEM; * so a published change sells at once. Under the uploaded lines, as they are over the book: a line uploaded with an item's * name is the GM's latest word and wins; an item turned off keeps a line of its name off the shelves. */ -const NO_OWN = { catalogues: {}, off: new Set() }; +const NO_OWN = { catalogues: {}, off: new Set(), buyback: {} }; let ownSource = () => NO_OWN; const setOwnSource = (fn) => { ownSource = typeof fn === 'function' ? fn : () => NO_OWN; }; /** Whatever is set, so a test that sets its own can put it back. */ @@ -95,6 +95,9 @@ const ownIn = (catalogue) => { return (own().catalogues[String(catalogue || '')] || []).filter((e) => !named.has(builtIn.normaliseName(e.name))); }; +/** The game's items kept out of the shops, by id, that a shop of their type buys back (8a7a3c2): never sold, never priced to buy. */ +const buybackOf = (catalogue, itemId) => ((own().buyback || {})[String(catalogue || '')] || []).find((e) => e.id === String(itemId || '')); + /** One entry a shop sells, uploaded or the game's own, by id; undefined for neither (the book is asked apart). */ const sold = (catalogue, itemId) => { const mine = (uploaded[String(catalogue || '')] || {})[String(itemId || '')]; @@ -119,10 +122,23 @@ const priceOf = (catalogue, itemId) => { return bookApplies() ? builtIn.priceOf(catalogue, itemId) : null; }; -/** What a catalogue entry is called. Uploaded first, then the book. */ +/** + * What a shop pays for one, before its rate (8a7a3c2): what it sells it for, else an item kept out of the shops at its own + * price, as one-of-a-kind things still sell back. Null for neither. + */ +const sellPriceOf = (catalogue, itemId) => { + const price = priceOf(catalogue, itemId); + if (price !== null) return price; + const kept = buybackOf(catalogue, itemId); + return kept ? kept.price : null; +}; + +/** What a catalogue entry is called. Uploaded first, then the book; an item kept out of the shops by its own name. */ const labelOf = (catalogue, itemId) => { const mine = sold(catalogue, itemId); if (mine) return mine.entry ? mine.entry.name : null; + const kept = buybackOf(catalogue, itemId); + if (kept) return kept.name; return bookApplies() ? builtIn.labelOf(catalogue, itemId) : null; }; @@ -159,6 +175,12 @@ const findByName = (name) => { if (builtIn.normaliseName(entry.name) === wanted) return { catalogue, id: entry.id }; } } + // And one kept out of the shops (8a7a3c2), to sell back where its type is sold. + for (const [catalogue, entries] of Object.entries(own().buyback || {})) { + for (const entry of entries) { + if (builtIn.normaliseName(entry.name) === wanted) return { catalogue, id: entry.id }; + } + } return null; }; @@ -191,6 +213,6 @@ const overridesIn = (catalogue, entries) => { module.exports = { BOOK_SYSTEM, bookApplies, setOwnSource, ownSourceNow, load, clear, systemLoaded, uploadedIn, hasUploads, entriesIn, overridesIn, - priceOf, labelOf, fieldsOf, findByName, + priceOf, sellPriceOf, labelOf, fieldsOf, findByName, normaliseName: builtIn.normaliseName, }; diff --git a/backend/shops/ownItems.js b/backend/shops/ownItems.js index b61e6689..32f46f7d 100644 --- a/backend/shops/ownItems.js +++ b/backend/shops/ownItems.js @@ -13,33 +13,41 @@ const { normaliseName } = require('./prices'); /** An item's line id: apart from an uploaded line's (a slug of its name), so the two never share one. */ const ITEM_PREFIX = 'item:'; -const NONE = Object.freeze({ catalogues: Object.freeze({}), off: new Set() }); +const NONE = Object.freeze({ catalogues: Object.freeze({}), off: new Set(), buyback: Object.freeze({}) }); /** Dice read whatever names they read: the builder checked them. */ const ANY_NAME = { known: () => true, refused: (n) => `@${n}` }; const cache = new WeakMap(); /** - * { catalogues: { 'type:': [{ id, name, price, fields }] }, off: Set of names }: each item IN SHOPS with a price, a line - * of its type, its columns' values and its words as its fields, as an uploaded typed line has them; and the names of those - * turned off. Nothing for a system without types of its own, whose shops have no type shelves. + * { catalogues: { 'type:': [{ id, name, price, fields }] }, off: Set of names, buyback: { 'type:': [...] } }: each item + * IN SHOPS with a price, a line of its type, its columns' values and its words as its fields, as an uploaded typed line has + * them; the names of those turned off; and those turned off with a price, which no shelf shows but a shop of their type buys + * back at its rate (8a7a3c2; the user: "a unique item should still be sellable for its set price"). Nothing for a system + * without types of its own, whose shops have no type shelves. */ const ownStock = (definition) => { if (!definition || typeof definition !== 'object' || !ownTypes(definition)) return NONE; if (cache.has(definition)) return cache.get(definition); const catalogues = {}; const off = new Set(); + const buyback = {}; for (const item of itemsOf(definition)) { const name = typeof item.label === 'string' ? item.label.trim() : ''; if (!name || typeof item.id !== 'string') continue; - if (!inShops(definition, item)) { off.add(normaliseName(name)); continue; } const price = itemPrice(definition, item); + const shelf = `type:${typeNamed(definition, item.type).id}`; + if (!inShops(definition, item)) { + off.add(normaliseName(name)); + if (isPrice(price)) (buyback[shelf] ||= []).push({ id: ITEM_PREFIX + item.id, name, price }); + continue; + } if (!isPrice(price)) continue; const description = typeof item.description === 'string' ? item.description.trim() : ''; const fields = { ...itemValues(definition, item, ANY_NAME), ...(description ? { description } : {}) }; - (catalogues[`type:${typeNamed(definition, item.type).id}`] ||= []).push({ id: ITEM_PREFIX + item.id, name, price, fields }); + (catalogues[shelf] ||= []).push({ id: ITEM_PREFIX + item.id, name, price, fields }); } - const out = { catalogues, off }; + const out = { catalogues, off, buyback }; cache.set(definition, out); return out; }; diff --git a/backend/shops/owned.js b/backend/shops/owned.js index 9137487a..0807b04f 100644 --- a/backend/shops/owned.js +++ b/backend/shops/owned.js @@ -89,7 +89,7 @@ const tally = (into, name, source, extra) => { id: hit ? hit.id : null, label: hit ? prices.labelOf(hit.catalogue, hit.id) : label, // What one is worth on a shelf. Null for anything no catalogue carries. - unitPrice: hit ? prices.priceOf(hit.catalogue, hit.id) : null, + unitPrice: hit ? prices.sellPriceOf(hit.catalogue, hit.id) : null, qty: 0, /** Every place one of these is sitting, so a sale knows what to empty. */ at: [], diff --git a/backend/shops/sell.js b/backend/shops/sell.js index fc9cc167..93181a27 100644 --- a/backend/shops/sell.js +++ b/backend/shops/sell.js @@ -155,7 +155,8 @@ const planSale = ({ data, items, catalogues, locationPct, globalPct, system }) = takenSoFar.set(key, already + want); // Priced from the book table on this side, never from anything the client sent. - const unit = catalogue && id ? prices.priceOf(catalogue, id) : null; + // One-of-a-kind items too (8a7a3c2): kept out of the shops, bought back at their own price. + const unit = catalogue && id ? prices.sellPriceOf(catalogue, id) : null; const each = buyback.buybackValue(unit, pct); payout += each * want; sold.push({ catalogue, id, label: line.label, qty: want, each }); diff --git a/backend/sockets/index.js b/backend/sockets/index.js index dac16a9a..1003ad5c 100644 --- a/backend/sockets/index.js +++ b/backend/sockets/index.js @@ -2569,7 +2569,8 @@ module.exports = (io, db, { elevatedUsers, emitUpdate, recordAction }) => { for (const c of buildingTypes.CATALOGUES) out[c.id] = shopPrices.entriesIn(c.id); // Each of the game's own item types too (8a7a1), its lines with their columns, for DOWNLOAD CURRENT and the shops. for (const t of ownTypesIn(system)) out[`type:${t.id}`] = shopPrices.entriesIn(`type:${t.id}`); - socket.emit('catalogues', { entries: out }); + // And the game's items kept out of the shops, which no shelf shows but a shop of their type buys back (8a7a3c2). + socket.emit('catalogues', { entries: out, buyback: ownStock(customSystems.definitionOf(system)).buyback }); }); }; diff --git a/e2e/COVERAGE.md b/e2e/COVERAGE.md index eb3f4513..94aa3c4a 100644 --- a/e2e/COVERAGE.md +++ b/e2e/COVERAGE.md @@ -34,7 +34,7 @@ panel), so a control that looks fine but does nothing is caught for all of them. | GIVE ITEM and shop catalogues | a catalogue typed in, an item given with a note | `shops_give`, `shop_catalogue_*` | `player-journey`, `shop-cart-items` (a catalogue saved while a player is online, bought by them through the cart, 8n1), `shop-cart` (CWN's book: bought and sold back, 8n1), `give-item` (a ring and two ropes given, on the sheet as bought ones are, in GIVEN, 8n2) | **AT THE TABLE** | | 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** | | An item type's SOLD AT | the kinds of shop that sell its lines (8a7a2), the General Store where unsaid; set in the builder in 8a7b | `shop_typed_lines`, `typedShelves` | `shop-typed-lines` (unsaid: the General Store) | **AT THE TABLE** unsaid; a kind of shop picked waits for 8a7b's box | -| An item's PRICE and IN SHOPS | priced and IN SHOPS, it sells itself at its type's shops (8a7a3a); off, never sold, not even from a file; 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), `builder-item-price` (set by clicks), `builder-items-import` (imported priced and IN SHOPS) | **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** | | A catalogue file held against the game's items | an exact copy of an item left out, an item kept out of the shops left out, one of an item's name overruling it, ALSO ON SALE FROM ITEMS (8a7a3c1) | `shop_items_on_sale`, `CatalogueWindow` | `catalogue-and-items` | **AT THE TABLE** | | Building types and catalogues renamed or off | | `buildings` | | **GAP** | | Currencies | several, decimals, a catalogue's currency, the cart per currency, PAYROLL | `currencies`, `currency_icons`, `catalogue_currency`, `bank_currencies`, `shop_checkout_currencies` | | **GAP** | diff --git a/e2e/README.md b/e2e/README.md index c474610b..c36341f5 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -216,7 +216,7 @@ kept; the job itself stops at 30 (`timeout-minutes`), for a hang outside the tes | `tests/give-item.spec.ts` | GIVE.EXE at the table, a safety net before 8a7 (8n2). A custom system's catalogue from DOWNLOAD ITEMS, its ring priced and a rope added; the player opens their sheet once; the GM gives the ring, then two ropes: found in ITEMS, the player ticked in TO, GIVE 2 × ROPE TO 1. Free, and on the sheet as bought ones are, the ring known as the item it is; GIVEN lists both | | `tests/shop-cart.spec.ts` | The shop at the table, a safety net before 8a7 (8n1). Cities Without Number's Gun Shop from the book: the GM pays the player 1,000 from PAYROLL.EXE in the GAME tab's BANK, the player opens the shop from QUICK_ACCESS, its header says 1,000cr; a Light Pistol into the cart and CHECK OUT, 800cr and the pistol on the sheet; SELL, the pistol into the cart and CHECK OUT, 890cr (45% back) and the pistol gone | | `tests/shop-cart-items.spec.ts` | A custom system's General Store at the table (8n1). The GM starts a catalogue from DOWNLOAD ITEMS, the ring priced at 500 and a rope at 5, and saves it while the player is online (this found the player's shops empty: fixed); pays the player 1,000; the player's store has both lines, both bought through the cart, the receipt saying 505 paid and 495 left; both in the inventory, the ring known as the item it is, to WEAR and ATTUNE | -| `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. | +| `tests/shop-items-on-sale.spec.ts` | The game's own items at the table (8a7a3a), found by the user testing 8a7a2. A game whose WEAPONS type has a PRICE column, its Pistol priced 200 and a Ring of Might kept out of the shops, and no catalogue saved: the player's General Store has the Pistol on its WEAPONS shelf at 200 with its damage, never the ring, and no empty-shop steps; bought through the cart, it lands on the gear as a Weapon with its damage; sold back from the window at the store's 50% (8a7a3c2), 900 left and off the sheet. Run once without the window's fix, it fails at that balance. | | `tests/shop-typed-lines.spec.ts` | Lines of an item type at the table (8a7a2). A game with a GUNS type (DAMAGE, AMMO) and no SOLD AT, so sold at the General Store: the GM saves a [GUNS] catalogue with a Pistol and pays the player 1000; the player's General Store has a GUNS tab saying GOES INTO YOUR GEAR AS A GUN, sortable by DAMAGE and AMMO; the Pistol bought through the cart lands on the sheet as a Gun with its damage and ammo, and one given from GIVE.EXE stacks onto it. | | `tests/catalogue-and-items.spec.ts` | A catalogue file held against the game's own items (8a7a3c1). WEAPONS selling a Pistol at 200 and a Cutlass at 120 by themselves, a Ring of Might kept out of the shops: a file with the Pistol at 260, the Cutlass exactly as it is, the Ring and a Hand Cannon previews as WEAPONS ×2, ALSO ON SALE FROM ITEMS: 2 (1 overruled by this file), the Pistol overruling 200 → 260, the Cutlass and the Ring left out and why; saved as WEAPONS ×2, DOWNLOAD CURRENT has the Pistol at 260, the Hand Cannon and the game's Cutlass behind a #, no Ring. | | `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 | diff --git a/e2e/tests/shop-items-on-sale.spec.ts b/e2e/tests/shop-items-on-sale.spec.ts index bb1e38d3..817383a8 100644 --- a/e2e/tests/shop-items-on-sale.spec.ts +++ b/e2e/tests/shop-items-on-sale.spec.ts @@ -5,7 +5,8 @@ import { playerToken, sheetOf, payPlayer } from './shops'; // The game's own items on the shelves (8a7a3a; mockup docs/mockups/types-in-shops.html, decided 2026-11-21). Found by the user // testing 8a7a2: a Pistol priced on the ITEMS page never reached a shop. A game whose WEAPONS type has a PRICE column, its // Pistol priced 200 and a Ring of Might kept out of the shops; no catalogue saved at all. The player's General Store sells the -// Pistol on its WEAPONS shelf, never the ring; bought, it lands on the gear as a Weapon with its damage. +// Pistol on its WEAPONS shelf, never the ring; bought, it lands on the gear as a Weapon with its damage; sold back from the +// window at the store's own 50% (8a7a3c2: the window never found a typed line to sell), 100 back and off the sheet. const SYSTEM = (name: string) => ({ format: 1, name, core: { health: { model: 'pool' } }, @@ -32,7 +33,8 @@ test('a Pistol priced on ITEMS sells itself at the General Store, no catalogue s await playerToken(request, gm, player.username); const shop = `ITEMSALE_GOODS${again}`; const made = await asGm(request, gm, 'post', '/api/locations', { name: shop, description: '', shape: 'box', x: 10, y: 0, z: 10, width: 2, height: 2, depth: 2 }); - const typed = await request.patch(`/api/locations/${made.data[0].id}/building-type`, { data: { building_type: 'general_store' }, headers: { Authorization: `Bearer ${gm}` } }); + // A store that buys back at 50%, so the sale is a round 100. + const typed = await request.patch(`/api/locations/${made.data[0].id}/building-type`, { data: { building_type: 'general_store', buyback_pct: 50 }, headers: { Authorization: `Bearer ${gm}` } }); expect(typed.ok(), await typed.text()).toBe(true); // The player, with a sheet opened once. @@ -73,5 +75,16 @@ test('a Pistol priced on ITEMS sells itself at the General Store, no catalogue s return (JSON.parse(typeof inventory === 'string' ? inventory : '[]') as { name: string; qty: number; type?: string; values?: Record }[]) .map(({ name, qty, type, values }) => ({ name, qty, type, damage: values?.damage })); }, { timeout: 15_000 }).toEqual([{ name: 'Pistol', qty: 1, type: 'weapons', damage: '2d6' }]); + + // Sold back from the window: the store's 50% of 200, and off the sheet. + await window.getByRole('tab', { name: 'SELL' }).click(); + await window.getByRole('button', { name: 'Add Pistol to the cart' }).click(); + await window.getByRole('tab', { name: 'CART' }).click(); + await window.getByRole('button', { name: 'CHECK OUT' }).click(); + await expect(window.getByRole('tabpanel')).toContainText('BALANCE 900cr', { timeout: 15_000 }); + await expect.poll(async () => { + const inventory = (await sheetOf(request, gm, player.username)).inventory; + return (JSON.parse(typeof inventory === 'string' ? inventory : '[]') as { name: string }[]).map((l) => l.name); + }, { timeout: 15_000 }).toEqual([]); await context.close(); }); diff --git a/frontend/src/hooks/__tests__/useSocket.catalogues.test.ts b/frontend/src/hooks/__tests__/useSocket.catalogues.test.ts index b43f56ba..2bfff99c 100644 --- a/frontend/src/hooks/__tests__/useSocket.catalogues.test.ts +++ b/frontend/src/hooks/__tests__/useSocket.catalogues.test.ts @@ -15,7 +15,7 @@ const fakeSocket = { vi.mock('socket.io-client', () => ({ io: () => fakeSocket })); const { useSocket } = await import('../useSocket'); -const { uploadedIn, uploadedRevision, clearUploaded, uploadedOf } = await import('../../sheets/uploadedCatalogues'); +const { uploadedIn, uploadedRevision, clearUploaded, uploadedOf, buybackIn } = await import('../../sheets/uploadedCatalogues'); afterEach(() => { cleanup(); clearUploaded(); fakeSocket.emit.mockClear(); for (const k of Object.keys(listeners)) delete listeners[k]; }); @@ -42,6 +42,14 @@ describe('the shops\' catalogues', () => { expect(uploadedRevision()).toBeGreaterThan(before); }); + it('with what a shop buys back of the game\'s items kept out of the shops (8a7a3c2)', () => { + mount(); + send('catalogues', { entries: {}, buyback: { 'type:guns': [{ id: 'item:ring', name: 'Ring of Might', price: 5000 }] } }); + expect(buybackIn('type:guns')).toEqual([{ id: 'item:ring', name: 'Ring of Might', price: 5000, fields: {} }]); + send('catalogues', { entries: {} }); + expect(buybackIn('type:guns')).toEqual([]); + }); + it('what draws the shops draws again when they come', () => { let renders = 0; renderHook(() => { diff --git a/frontend/src/hooks/useSocket.ts b/frontend/src/hooks/useSocket.ts index 6f062e41..cf66d903 100644 --- a/frontend/src/hooks/useSocket.ts +++ b/frontend/src/hooks/useSocket.ts @@ -1,5 +1,5 @@ import { useState, useEffect, useRef, useCallback } from 'react'; -import { loadUploaded, uploadedOf } from '../sheets/uploadedCatalogues'; +import { loadUploaded, uploadedOf, loadBuyback } from '../sheets/uploadedCatalogues'; import { io } from 'socket.io-client'; import type { ActiveUser, ChatMessage, BattleMapSessionData, BattleMapPosition, @@ -117,8 +117,10 @@ export function useSocket({ // they were missed, and a player found every custom system's shop empty). Listened for from the socket's first moment: // the server sends them on identify, and again whenever asked, as a GM's save or a new game says to. const askCatalogues = () => newSocket.emit('requestCatalogues'); - newSocket.on('catalogues', (payload: Parameters[0]) => { + newSocket.on('catalogues', (payload: Parameters[0] & { buyback?: Parameters[0] }) => { loadUploaded(uploadedOf(payload)); + // What a shop buys back of the game's items kept out of the shops (8a7a3c2). + loadBuyback(payload?.buyback); // The shops redraw with them: App, which draws them, re-renders on this. setCatalogueRevision((n) => n + 1); }); diff --git a/frontend/src/sheets/__tests__/typedShelves.test.ts b/frontend/src/sheets/__tests__/typedShelves.test.ts index 618cbbc2..feba4d63 100644 --- a/frontend/src/sheets/__tests__/typedShelves.test.ts +++ b/frontend/src/sheets/__tests__/typedShelves.test.ts @@ -3,7 +3,8 @@ import { createRequire } from 'module'; import { shelvedIn, catalogueLabel, itemTypeOfShelf, ownItemTypes, typeNamedLike, type ShopStock } from '../../data/buildingTypes'; import { placeUploaded, destinationOf } from '../shopPlacement'; import { registerCustomTemplate, clearCustomTemplates } from '../customTemplates'; -import type { UploadedEntry } from '../uploadedCatalogues'; +import { loadUploaded, loadBuyback, clearUploaded, type UploadedEntry } from '../uploadedCatalogues'; +import { ownedItems, sellableAt } from '../ownedItems'; // A shelf of an item type (8a7a2; mockup docs/mockups/item-types-in-shops.html): sold at the kinds of shop its SOLD AT says // (the server's, in the render copy), named as the type, and a line bought from it a line of the type with its columns as @@ -21,7 +22,7 @@ beforeEach(() => { clearCustomTemplates(); registerCustomTemplate({ id: SYS, name: 'Typed', parts: {}, derived: [], sheet: { sections: [] }, words: {}, items: { slots: [], list: [], types: [GUNS, POTIONS] } } as never); }); -afterEach(() => clearCustomTemplates()); +afterEach(() => { clearCustomTemplates(); clearUploaded(); }); describe('a type\'s shelf', () => { it('at each kind of shop it is sold at, after the shop\'s own; at none for a type sold nowhere', () => { @@ -98,3 +99,29 @@ describe('a line bought from it', () => { } }); }); + +describe('sold back from the window (8a7a3c2)', () => { + // A line of the type, bought from its shelf or one of the game's items; and the game's ring kept out of the shops. + const sheet = { inventory: JSON.stringify([ + { name: 'Pistol', qty: 1, carry: 'stowed', type: 'guns', values: { damage: '2d6', ammo: 6 } }, + { name: 'Ring of Might', qty: 1, carry: 'stowed', type: 'guns' }, + { name: 'Lucky Rock', qty: 1, carry: 'stowed' }, + ]) }; + const line = (lines: ReturnType, label: string) => lines.find((l) => l.label === label); + + it('a typed line found on its type\'s shelf, priced as the shop sells it, sellable where the type is sold', () => { + loadUploaded({ 'type:guns': [{ ...PISTOL, id: 'item:pistol' }] } as never); + const lines = ownedItems(sheet, SYS); + expect(line(lines, 'Pistol')).toMatchObject({ catalogue: 'type:guns', id: 'item:pistol', unitPrice: 250 }); + expect(sellableAt(lines, ['type:guns' as ShopStock]).map((l) => l.label)).toContain('Pistol'); + expect(sellableAt(lines, ['gear' as ShopStock]).map((l) => l.label)).not.toContain('Pistol'); + }); + + it('one kept out of the shops: priced at its own to sell back, only where its type is sold; something unknown, none', () => { + loadBuyback({ 'type:guns': [{ id: 'item:ring', name: 'Ring of Might', price: 5000 }] }); + const lines = ownedItems(sheet, SYS); + expect(line(lines, 'Ring of Might')).toMatchObject({ catalogue: 'type:guns', id: 'item:ring', unitPrice: 5000 }); + expect(sellableAt(lines, ['weapons' as ShopStock]).map((l) => l.label)).not.toContain('Ring of Might'); + expect(line(lines, 'Lucky Rock')).toMatchObject({ catalogue: null, unitPrice: null }); + }); +}); diff --git a/frontend/src/sheets/ownedItems.ts b/frontend/src/sheets/ownedItems.ts index 62836149..b5744c6b 100644 --- a/frontend/src/sheets/ownedItems.ts +++ b/frontend/src/sheets/ownedItems.ts @@ -24,7 +24,7 @@ import { VEHICLE_WEAPONS } from './vehicleWeapons'; import { slotsOf } from './sheetSlots'; import type { ShopStock } from '../data/buildingTypes'; import { CATALOGUES as CATALOGUE_LIST } from '../data/buildingTypes'; -import { uploadedIn, uploadedEntry } from './uploadedCatalogues'; +import { uploadedIn, uploadedEntry, uploadedCatalogues, buybackIn, buybackEntry, buybackCatalogues } from './uploadedCatalogues'; /** * The system the built-in book belongs to, and the one a caller gets by not saying. @@ -127,9 +127,18 @@ export const findByName = ( const wanted = normaliseName(name); if (!wanted) return null; - for (const { id: catalogue } of CATALOGUE_LIST) { - for (const entry of uploadedIn(catalogue)) { - if (normaliseName(entry.name) === wanted) return { catalogue, id: entry.id }; + // The shelves, then the game's type shelves (8a7a3c2: they were never looked in, so a typed line or an item bought from + // one couldn't be sold back from the window), as the server finds them. + const shelves = [...CATALOGUE_LIST.map((c) => c.id as string), ...uploadedCatalogues().filter((c) => c.startsWith('type:'))]; + for (const catalogue of shelves) { + for (const entry of uploadedIn(catalogue as ShopStock)) { + if (normaliseName(entry.name) === wanted) return { catalogue: catalogue as ShopStock, id: entry.id }; + } + } + // And one kept out of the shops, which a shop of its type buys back. + for (const catalogue of buybackCatalogues()) { + for (const entry of buybackIn(catalogue)) { + if (normaliseName(entry.name) === wanted) return { catalogue: catalogue as ShopStock, id: entry.id }; } } return null; @@ -143,7 +152,7 @@ export const findByName = ( export const priceOf = ( catalogue: ShopStock, id: string, system: string = BOOK_SYSTEM, ): number | null => { - const mine = uploadedEntry(catalogue, id); + const mine = uploadedEntry(catalogue, id) ?? buybackEntry(catalogue, id); if (mine) return Number.isFinite(mine.price) ? mine.price : null; return system === BOOK_SYSTEM ? (BY_ID.get(`${catalogue}/${id}`)?.price ?? null) : null; }; @@ -151,7 +160,7 @@ export const priceOf = ( export const labelOf = ( catalogue: ShopStock, id: string, system: string = BOOK_SYSTEM, ): string | null => { - const mine = uploadedEntry(catalogue, id); + const mine = uploadedEntry(catalogue, id) ?? buybackEntry(catalogue, id); if (mine) return mine.name; return system === BOOK_SYSTEM ? (BY_ID.get(`${catalogue}/${id}`)?.label ?? null) : null; }; diff --git a/frontend/src/sheets/uploadedCatalogues.ts b/frontend/src/sheets/uploadedCatalogues.ts index d8053e8c..72036f4c 100644 --- a/frontend/src/sheets/uploadedCatalogues.ts +++ b/frontend/src/sheets/uploadedCatalogues.ts @@ -53,7 +53,7 @@ export const loadUploaded = ( revision += 1; }; -export const clearUploaded = (): void => { uploaded = {}; revision += 1; }; +export const clearUploaded = (): void => { uploaded = {}; buyback = {}; revision += 1; }; /** Changes whenever the catalogues do, so a component can depend on it. */ export const uploadedRevision = (): number => revision; @@ -66,6 +66,24 @@ export const uploadedEntry = ( catalogue: ShopStock, id: string, ): UploadedEntry | undefined => uploaded[catalogue]?.[id]; +/** Every catalogue holding uploaded lines or the game's own items, the type shelves (`type:`) among them (8a7a3c2). */ +export const uploadedCatalogues = (): string[] => Object.keys(uploaded); + +/** + * The game's items kept out of the shops (8a7a3c2), as the server sends them: on no shelf, but a shop of their type buys one + * back at its own price. catalogue -> id -> entry. + */ +let buyback: Record> = {}; +/** What the server says a shop buys back, replacing what was held. */ +export const loadBuyback = (sections: Record | null | undefined): void => { + buyback = Object.fromEntries(Object.entries(sections ?? {}).map(([catalogue, entries]) => [catalogue, + Object.fromEntries((entries ?? []).filter((e) => e && e.id).map((e) => [e.id, { id: e.id, name: String(e.name ?? ''), price: Number(e.price) || 0, fields: {} }]))])); + revision += 1; +}; +export const buybackIn = (catalogue: string): UploadedEntry[] => Object.values(buyback[catalogue] ?? {}); +export const buybackEntry = (catalogue: string, id: string): UploadedEntry | undefined => buyback[catalogue]?.[id]; +export const buybackCatalogues = (): string[] => Object.keys(buyback); + /** Whether anything at all has been uploaded, for deciding whether to say so. */ export const anyUploaded = (): boolean => Object.values(uploaded).some((table) => Object.keys(table ?? {}).length > 0);