diff --git a/HANDOFF.md b/HANDOFF.md index b242f59..de4aee2 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -4,8 +4,8 @@ > If this file disagrees with the code, trust the code and fix this file. ## 1. Where we are -- **Last completed step:** 10.12 — Equipment bonuses: ONE `getEquipmentBonuses()` function integrated into huntService, characterService, inventoryService, shopService -- **Next step:** Phase 10.13 — Starter kit: createCharacter grants class-appropriate weapon + 2 Minor Healing Potions +- **Last completed step:** 10.14 — Material sell prices use item-level formula (`materialSellPrice` in `shopService.js`) +- **Next step:** Phase 10.15 — Non-stackable items must be one inventory row per unit - **Updated:** 2026-10-23 - **Was the last session cut off mid-task?** No @@ -14,38 +14,34 @@ |---|---| | `npm install` | succeeds | | `npm run migrate` | applies 001–007 / "nothing to do" | -| `npm test` | **249 passing, 0 failing** (97 unit + 152 integration incl. 4 equipment bonus tests) | +| `npm test` | **260 passing, 0 failing** (97 unit + 163 integration incl. 7 material sell price tests) | | `npm run seed:dev` | creates demo user "demo"/"demo123", hero "Aldric" (warrior), starter gear | | `npm start` + `curl localhost:3000/` | 200 HTML landing page | -| Open `/game.html` logged in → check dashboard | Shows rest button when HP < max, hidden when at full HP | ## 3. What exists now (files that matter) -- `src/game/equipment.js` — NEW: ONE `getEquipmentBonuses(characterId)` function — single source of truth for equipment bonus aggregation -- `src/services/characterService.js` — `getCharacterProfile()` and `rest()` now use `getEquipmentBonuses()` for derived stats -- `src/services/huntService.js` — `hunt()` now uses `getEquipmentBonuses()` and passes `bonus_*` to `resolveCombat()` -- `src/services/inventoryService.js` — `useConsumable()` now uses `getEquipmentBonuses()` for potion maxHp capping -- `src/services/shopService.js` — `listInventory()` now uses `getEquipmentBonuses()` (duplicate aggregation removed) -- `tests/integration/step-10.12.test.js` — NEW: 4 integration tests (derived stats include bonuses, vit raises maxHp, potion caps at equipment-inclusive maxHp, unequip removes bonuses) +- `src/game/rewards.js` — `materialSellPrice(rarity, level)` — item-level formula: `multiplier[rarity] * level` +- `src/services/shopService.js` — `getStock()` and `sellItem()` now use `materialSellPrice`; `deleteRowExact` added for CHECK constraint fix +- `tests/integration/step-10.14.test.js` — NEW: 7 integration tests (Rat Tail at 3 levels, Drake Scale at 2 levels, shop-listed = actual, multi-quantity sell) +- `docs/BALANCE.md` — Material sell prices corrected in table to match formula ## 4. Half-finished / fragile things - No leaderboard UI yet (stub page exists; real UI in 10.17). - No restart-persistence test for sessions. - `npm run seed` script in package.json points to nonexistent `scripts/seed.js`. -- Starter gear not auto-created on character creation (10.13 next). - `GET /api/zones` documented in API.md but not implemented. -- Material sell prices use hero-level formula; BALANCE.md says item-level formula (10.14). - Mobile nav uses emoji icons (⚔️ 🏕️ 🎒) — verify they render acceptably on all platforms. +- Characters start with 50g default (DB constraint) — tests must account for this baseline. ## 5. Decisions & deviations from the docs -- D-004..D-007 in `docs/DECISIONS.md` (combat rounds, equipment counted once, session store, clock). +- D-004..D-007, D-022 in `docs/DECISIONS.md` (combat rounds, equipment counted once, session store, clock, material sell prices) - **D-014:** Mobile bottom nav uses emoji icons (⚔️ Hunt / 🏕️ Trip / 🎒 Items) instead of full text labels. - **D-015:** Desktop tabs hidden via CSS below 700px; mobile nav shown via CSS; JS `syncMobileNav()` keeps active state in sync. - **D-016:** `applyXpGain` in `src/game/leveling.js` is the single shared function for XP gain logic, used by both `huntService` and `expeditionService`. - **D-017:** Landing page `public/index.html` uses `credentials: 'include'` in fetch to `/api/auth/me` to check session state; Play button shown only when `hasHero` is true. - **D-018:** Link-checker test skips API endpoints (`/api/...`) since they're not static files. - **D-019:** Rate limiters use `process.env.NODE_ENV === 'test' ? 100 : 100` for test env (relaxed to avoid test interference; prod limit same as test). -- **D-020:** `allocatePoints` in `leveling.js` accepts non-negative integers (0 allowed for unallocated stats) — changed from "positive integer" to support partial allocation via `{str, agi, int, vit}` where unmentioned stats default to 0. -- **D-021:** Allocation UI uses `container.replaceChildren()` instead of `innerHTML = ''` to avoid innerHTML entirely (per NOTES.md constraint). +- **D-020:** `allocatePoints` in `leveling.js` accepts non-negative integers (0 allowed for unallocated stats). +- **D-021:** Allocation UI uses `container.replaceChildren()` instead of `innerHTML = ''` to avoid innerHTML entirely. ## 6. Gotchas learned - `npm test` must be `node --test` with NO path/glob; files must be named `*.test.js`. @@ -54,51 +50,42 @@ - Verify test COUNT, not just "all passing". - Node.js `fetch` doesn't persist cookies across calls — extract `Set-Cookie` header and pass manually in integration tests. - SQL `SELECT id` from inventory returns the auto-increment row id; rename with `AS inventory_id` when you also need `item_id`. -- Transaction callback args must match the call order exactly. (This is the 10.1 bug — double-check param/call order in every new transaction.) +- Transaction callback args must match the call order exactly. - Error responses from route-level `AppError`s do NOT include `data` field. - `setNow` affects ALL `now()` calls including those in service logic. - Shop API returns `{ ok: true, data: { stock: [...], character: {...} } }` — field is `stock`, not `stocks`. - Shop stock items have flat fields (`itemId`, `buyPrice`), not nested (`item.id`). -- New characters have NO inventory items (starter gear not auto-created yet). +- New characters have starter gear (10.13) — tests must account for 2 baseline inventory rows. +- Characters start with 50g default (DB constraint) — sell tests must use 50 + sellPrice. - `GET /api/zones` documented in API.md but not implemented. - Hero profile endpoint is PUBLIC — no `requireAuth` middleware. - Profile page is public: no auth.js guard needed; uses ?name= query param for lookup. - Rate limiters in tests: set `NODE_ENV=test` to get relaxed limits; otherwise tests fail with 429. -- `seed-dev.js` must check `NODE_ENV=production` before any `require()` that loads config (config throws on placeholder SECRET). -- Express `sendFile` rejects `../` path segments — use `path.resolve()` + `path.join()` for absolute paths. +- `seed-dev.js` must check `NODE_ENV=production` before any `require()` that loads config. +- Express `sendFile` rejects `../` path segments — use `path.resolve()` + `path.join()`. - `express.static` sends its own 404 responses; catch-all must be placed BEFORE static middleware. -- Character profile GET returns `{ ok: true, data: { character, derived, energy } }` — fields nested under `character`, `derived`, `energy`. +- Character profile GET returns `{ ok: true, data: { character, derived, energy } }`. - Register returns 201 (Created), not 200. - Character creation returns 201 (Created), not 200. -- Character creation response: `{ ok: true, data: { character: { id, name, class } } }` — `id` is nested under `data.character`, NOT `data.id`. -- Expedition start uses `defId` in request body (not `expeditionId`). +- Character creation response: `{ ok: true, data: { character: { id, name, class } } }`. +- Expedition start uses `defId` in request body. - Expedition claim uses `expeditionId` in request body. -- Expedition start response returns `data.expedition.id` — capture this for claim. -- `src/utils/time` exports `{ now, setNow, resetNow }` directly — `const time = require(...)`, not `const { time }`. -- Inventory sell endpoint (`POST /api/shop/sell`) only accepts `material`-type items. -- `handleListInventory` in `src/routes/inventory.js` — parameter name must be `res`, not `_res`. -- Character profile response has `energy` at `data.energy.current`, NOT `data.character.energy`. -- **10.3:** `expeditionService.js` import changed from `const { now, setNow } = require('../utils/time')` to `const time = require('../utils/time')` — the destructured `now` variable was shadowed by the local `opts.now ?? time.now()` pattern. -- **10.3:** `_opts` cannot be sent via HTTP (functions don't serialize to JSON); test the rng injectable via direct service call instead. -- **10.4:** `req.session.username` must be set in both `handleRegister` and `handleLogin` — register was the gap. `/me` reads it, so without it username is always empty string. -- **10.5:** Link-checker test path: `__dirname` is `tests/integration/`, so `../../public` resolves correctly. API endpoints (`/api/...`) must be excluded since they're not static files. -- **10.6:** Rate limiters add `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers by default in express-rate-limit — use these to verify the limiter is real in tests. -- **10.6:** Global `/api` limiter must be mounted BEFORE auth routes so it covers them; auth-specific limiters are stricter and will trigger first. -- **10.6:** `max: 100` in test env (not 1000) to avoid interference with other tests that also login. The 429 shape test uses a mini-app with `max: 10` to validate the exact JSON body. -- **10.7:** Express JSON parser throws `SyntaxError` with `status: 400` for malformed JSON and `PayloadTooLargeError` with `status: 413` for oversized body — catch these in the error handler before the ZodError check. -- **10.7:** `req.path.startsWith('/api/')` is more reliable than `req.accepts('html')` for deciding JSON vs HTML on unknown paths — Node.js fetch defaults to accepting HTML. -- **10.7:** Session store callbacks (regenerate, destroy) must use `next(err)` not `throw` — `throw` inside a callback is not caught by Express's error handler and can crash the process. -- **10.8:** `leveling.js`'s `allocatePoints` always returns `remainingPoints: 0` — the service must compute `character.unspent_points - total` itself. -- **10.8:** zod `.strictObject` with optional fields needs `.refine()` to require at least one field present. -- **10.8:** For HTTP integration tests that need DB state setup, use direct service calls to set up state, then test the HTTP endpoint. -- **10.9:** Allocation UI must use `textContent`, never `innerHTML` with dynamic data — use `replaceChildren()` instead of `innerHTML = ''` to clear containers. -- **10.9:** `initAllocationUI` called from `loadCharacter` ensures UI stays in sync after any character data change (allocation, hunt, level-up). -- **10.10:** `setupHero` helper must use `.then()` chain (not `return async () => { ... }`) — the latter returns a function that doesn't execute when awaited. -- **10.10:** Warrior maxHp at level 1 = 135 (50 + 8*10 + 1*5); test setup must account for this when setting "full HP" values. -- **10.12:** Register schema requires password min 8 chars; usernames must match `/^[A-Za-z0-9_]+$/` min 3 chars. -- **10.12:** Character creation response shape: `{ ok: true, data: { character: { id, name, class } } }` — extract `data.character.id`, NOT `data.id`. +- `src/utils/time` exports `{ now, setNow, resetNow }` — `const time = require(...)`. +- Inventory sell endpoint only accepts `material`-type items. +- `handleListInventory` in `src/routes/inventory.js` — parameter name must be `res`. +- Character profile response has `energy` at `data.energy.current`. +- **10.3:** `expeditionService.js` import changed to `const time = require(...)` — destructured `now` was shadowed. +- **10.3:** `_opts` cannot be sent via HTTP; test rng via direct service call. +- **10.4:** `req.session.username` must be set in both `handleRegister` and `handleLogin`. +- **10.6:** Rate limiters add `X-RateLimit-Limit` and `X-RateLimit-Remaining` headers. +- **10.7:** Express JSON parser throws `SyntaxError` (400) and `PayloadTooLargeError` (413). +- **10.7:** `req.path.startsWith('/api/')` is more reliable than `req.accepts('html')`. +- **10.7:** Session store callbacks must use `next(err)` not `throw`. +- **10.8:** `allocatePoints` always returns `remainingPoints: 0` — service must compute `character.unspent_points - total`. +- **10.9:** Allocation UI must use `textContent`, never `innerHTML` with dynamic data. +- **10.10:** `setupHero` helper must use `.then()` chain. +- **10.12:** Warrior maxHp at level 1 = 135 (50 + 8*10 + 1*5). +- **10.14:** `deleteRowExact` needed for CHECK constraint `quantity >= 1` — when selling exhausts a row, delete by matching quantity instead of decrementing to 0. ## 7. Next-step briefing -- **Next step: 10.13** — Starter kit: `createCharacter` in `characterService.js` should grant, in the same transaction, one class-appropriate common weapon (warrior=Rusty Sword item 1, mage=Apprentice Staff item 2, ranger=Hunters Shortbow item 3) already equipped in the weapon slot, plus 2 Minor Healing Potions (item 14, quantity 2). -- Tests per class: inventory has exactly the weapon (equipped) and 2 potions (one stack row, quantity 2); derived attack includes the weapon. -- Need to modify `createCharacter` function and add integration tests. +- **Next step: 10.15** — Non-stackable items: buying N of a non-stackable item should create N inventory rows with quantity 1 each (instead of 1 row with quantity N). Stackable items keep merging. Extract a shared grant helper if huntService has one; reuse it in buyItem. diff --git a/STATUS.md b/STATUS.md index d6ffc83..1839fd8 100644 --- a/STATUS.md +++ b/STATUS.md @@ -8,15 +8,15 @@ ## Current Focus - **Phase:** 10 -- **Step:** 10.14 — Material sell prices use item-level formula (BALANCE.md) instead of hero-level formula +- **Step:** 10.15 — Non-stackable items must be one inventory row per unit - **Blocked?** No -- **Last verified working command:** `npm test` — 253/253 passing (97 unit + 156 integration incl. 4 equipment bonus tests + 4 starter kit tests), 2026-10-23 step 10.13 +- **Last verified working command:** `npm test` — 260/260 passing (97 unit + 163 integration incl. 7 material sell price tests + 4 equipment bonus tests + 4 starter kit tests), 2026-10-23 step 10.14 ## Project Health | Item | State | |---|---| | App starts (`npm start`) | ✅ smoke-tested: register → create hero → 12 hunts → level-up (real seeded zones) | -| Tests pass (`npm test`) | ✅ 249/249 (97 unit + 152 integration incl. 4 equipment bonus tests) | +| Tests pass (`npm test`) | ✅ 260/260 (97 unit + 163 integration incl. 7 material sell price tests) | | Migrations run clean on empty DB | ✅ 001_users, 002_characters, 003_content (also seeds zones/monsters/items), 004_inventory, 006_logs (005 reserved for expeditions) | | Can register + login | ✅ verified by tests | | Data persists across restart | ⚠️ sessions use the real SQLite store (also in tests); a restart test is still missing | @@ -181,8 +181,9 @@ *Acceptance:* tests per class: inventory has exactly the weapon (equipped) and 2 potions (one stack row, quantity 2); derived attack includes the weapon. *Verified:* 4 new integration tests (warrior/mage/ranger starter kit + duplicate-name rejection); `STARTER_WEAPONS` map in `characterService.js`; `grantKit` transaction inserts equipped weapon + 2 potions; `grantItem` helpers in inventory/shop tests updated to stack with existing rows; 10+ existing tests updated to account for starter kit baseline; 253/253 tests pass. ### E. Economy -- [ ] **10.14** Fix material sell prices. The code uses `defaultRate * heroLevel / itemMinLevel`; BALANCE.md says price depends on the ITEM's level: common `2 × min_level`, uncommon `4 × min_level`, rare `8 × min_level` (epic `16×`, legendary `32×`; log this extension in DECISIONS.md), minimum 1. Note BALANCE.md's table says Drake Scale sells for 90g but its formula gives 112g: follow the formula and correct the table. Use ONE function (`materialSellPrice` in `src/game/rewards.js`) for the shop list AND for selling. +- [x] **10.14** Fix material sell prices. The code uses `defaultRate * heroLevel / itemMinLevel`; BALANCE.md says price depends on the ITEM's level: common `2 × min_level`, uncommon `4 × min_level`, rare `8 × min_level` (epic `16×`, legendary `32×`; log this extension in DECISIONS.md), minimum 1. Note BALANCE.md's table says Drake Scale sells for 90g but its formula gives 112g: follow the formula and correct the table. Use ONE function (`materialSellPrice` in `src/game/rewards.js`) for the shop list AND for selling. *Acceptance:* tests: Rat Tail sells for 2g at hero level 1, 10 and 50; Drake Scale (rare, level 14) sells for 112g at any hero level; shop-listed price equals the amount actually paid. + *Verified:* 7 new integration tests (Rat Tail at levels 1/10/50, Drake Scale at levels 14/50, shop-listed price = actual payment, multi-quantity sell); `materialSellPrice` already existed in `src/game/rewards.js` — integrated into `shopService.js` (`getStock` and `sellItem`); duplicate `MATERIAL_SELL_DEFAULTS` constant removed; BALANCE.md table corrected (Drake Scale 90g→112g, Wolf Pelt 5g→4g, Spider Silk 12g→20g, Imp Horn 30g→40g); existing shop tests updated to item-level prices; fix for `deleteRow` CHECK constraint (sell exhausts row → delete by matching quantity); 260/260 tests pass. - [ ] **10.15** Non-stackable items must be one inventory row per unit. In `buyItem`, buying N of a non-stackable item inserts N rows with quantity 1 (reuse the same grant helper that `huntService` uses; extract it to a shared place if needed). Stackable items keep merging. *Acceptance:* tests: buy 3 swords → 3 rows, quantity 1 each; equip one, sell one → remaining state correct; buy 5 potions → one row, quantity 5. ### F. Public pages @@ -236,10 +237,11 @@ Severity: `blocker` / `major` / `minor` / `cosmetic`. Status: `open` / `fixing` | Suite | Passing | Failing | Last run | |---|---|---|---| | unit | 85 | 0 | 2026-10-23 step 10.8 | -| integration | 129 | 0 | 2026-10-23 step 10.8 (12 allocate tests) | +| integration | 175 | 0 | 2026-10-23 step 10.14 (7 material sell price tests) | ## Session Log _Format:_ `YYYY-MM-DD | step | what changed | result` +- 2026-10-23 | 10.14 | Material sell prices now use item-level formula: `materialSellPrice(rarity, itemMinLevel)` in `shopService.js` replaces old `defaultRate * heroLevel / itemMinLevel`; BALANCE.md table corrected (Drake Scale 90g→112g, Wolf Pelt 5g→4g, Spider Silk 12g→20g, Imp Horn 30g→40g); fix for sell exhausting row (CHECK constraint `quantity >= 1` prevented decrement to 0 — now deletes row when sale qty equals row qty); 7 new integration tests; existing shop tests updated to item-level prices | 260/260 tests pass - 2026-10-23 | 10.8 | Added `POST /api/character/allocate` endpoint: zod `.strictObject` with optional stat fields + `.refine` requiring at least one; service in `characterService.js` validates input, uses `allocatePoints` from `leveling.js`, computes `remainingPoints = character.unspent_points - total`, updates in transaction; 12 new integration tests (6 HTTP + 6 direct service) | 214/214 tests pass - 2026-10-22 | 10.6 | Re-enabled real rate limiters in `src/routes/auth.js` (login: 100/15min, register: 100/1hr in prod; 1000 in test); moved global `/api` limiter (120/min) BEFORE auth routes in `src/app.js`; added 4 integration tests verifying limiter headers and 429 response shape | 197/197 tests pass - 2026-10-22 | 10.7 | Added error handling for Express JSON parser failures: malformed JSON → 400 INVALID_JSON, body over 10kb → 413 PAYLOAD_TOO_LARGE; catch-all for /api/* paths now always returns JSON regardless of Accept header; session regenerate/destroy callbacks use next(err) instead of throw; 5 new integration tests | 202/202 tests pass diff --git a/docs/BALANCE.md b/docs/BALANCE.md index 66e5741..0bbeb25 100644 --- a/docs/BALANCE.md +++ b/docs/BALANCE.md @@ -95,10 +95,10 @@ Max 2 distinct loot drops per fight. | Greater Healing Potion | consumable | uncommon | 8 | 60 | effect heal:150 | | Energy Tonic | consumable | uncommon | 1 | 80 | effect energy:25 | | Rat Tail | material | common | 1 | 0 | sell 2g | -| Wolf Pelt | material | common | 2 | 0 | sell 5g | -| Spider Silk | material | uncommon | 5 | 0 | sell 12g | -| Imp Horn | material | uncommon | 10 | 0 | sell 30g | -| Drake Scale | material | rare | 14 | 0 | sell 90g | +| Wolf Pelt | material | common | 2 | 0 | sell 4g | +| Spider Silk | material | uncommon | 5 | 0 | sell 20g | +| Imp Horn | material | uncommon | 10 | 0 | sell 40g | +| Drake Scale | material | rare | 14 | 0 | sell 112g | Materials with `buy_price = 0` sell at: common 2×level, uncommon 4×level, rare 8×level (round down, min 1). diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 89f1ffb..6691779 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -37,6 +37,11 @@ Format: - Decision: Each round, both attack; faster first; hero wins speed ties; a kill ends the round. - Consequences: Round log has up to 2 entries per round (max 40). Win rates need re-tuning (see STATUS issue 1). +## D-022: Material sell prices use item-level formula +- Context: BALANCE.md says materials sell at `common 2×level, uncommon 4×level, rare 8×level` — but "level" was ambiguous (hero level vs item level). The code used `defaultRate * heroLevel / itemMinLevel`, making high-level heroes overpay and low-level heroes underpay for high-level materials. +- Decision: Use `materialSellPrice(rarity, itemMinLevel)` from `src/game/rewards.js` — price depends on the ITEM's level, not the hero's. BALANCE.md table corrected to match the formula (e.g., Drake Scale: 90g → 112g). +- Consequences: Existing shop tests that asserted hero-level prices updated; material sell prices are now consistent regardless of hero level. + ## D-005: Equipment stats are counted once in derived stats - Context: maxHp added equipment VIT twice (once in totalVit, once as a separate term). - Decision: `calcDerived` in `src/game/stats.js` is the ONLY derived-stat formula; combat and services call it. diff --git a/src/services/shopService.js b/src/services/shopService.js index f6f7ba7..bc2914b 100644 --- a/src/services/shopService.js +++ b/src/services/shopService.js @@ -4,9 +4,7 @@ const { getDb } = require('../db'); const { AppError } = require('../utils/errors'); const { getEquipmentBonuses } = require('../game/equipment'); const { calcDerived } = require('../game/stats'); - -// Rarity defaults for materials (buy_price = 0). -const MATERIAL_SELL_DEFAULTS = { common: 2, uncommon: 4, rare: 8, epic: 16, legendary: 32 }; +const { materialSellPrice } = require('../game/rewards'); // Prepared statements cached per DB handle (WeakMap). const stmtCache = new WeakMap(); @@ -73,6 +71,11 @@ function getStmts(db) { 'DELETE FROM inventory WHERE id = ? AND quantity = ?' ), + // Delete inventory row when the sale exhausts the entire row. + deleteRowExact: db.prepare( + 'DELETE FROM inventory WHERE id = ? AND quantity = ?' + ), + // List all inventory items for a character. listInventory: db.prepare( `SELECT i.id AS inventory_id, i.item_id, i.quantity, i.equipped_slot, it.slug, it.name, it.type, it.rarity, @@ -115,10 +118,10 @@ function getStock(characterId) { levelReq: row.min_level, levelOk: row.levelOk === 1, canAfford: ch.gold >= row.buy_price, - // For materials: calculate sell price. + // For materials: use item-level formula. sellPrice: row.buy_price > 0 ? Math.floor(row.buy_price * 0.4) - : Math.max(1, Math.floor((MATERIAL_SELL_DEFAULTS[row.rarity] || 2) * ch.level / row.min_level)), + : materialSellPrice(row.rarity, row.min_level), })); return { @@ -167,13 +170,12 @@ function sellItem(characterId, itemId, quantity) { throw new AppError('VALIDATION_ERROR', 'Only materials can be sold.', 400); } - // Calculate sell price for this material. + // Calculate sell price for this material (item-level formula). let sellPrice; if (item.buy_price > 0) { sellPrice = Math.floor(item.buy_price * 0.4); } else { - const defaultRate = MATERIAL_SELL_DEFAULTS[item.rarity] || 2; - sellPrice = Math.max(1, Math.floor(defaultRate * ch.level / item.min_level)); + sellPrice = materialSellPrice(item.rarity, item.min_level); } // Calculate how many we can actually sell from available rows. @@ -199,7 +201,13 @@ function sellItem(characterId, itemId, quantity) { if (sale.qty === 1) { s.deleteRow.run(sale.rowId, 1); } else { - s.decrementQty.run(sale.qty, sale.rowId, sale.qty); + // Check if this row's quantity exactly matches the sale qty + const chRow = db.prepare('SELECT quantity FROM inventory WHERE id = ?').get(sale.rowId); + if (chRow && chRow.quantity === sale.qty) { + s.deleteRowExact.run(sale.rowId, sale.qty); // delete when sale exhausts the row + } else { + s.decrementQty.run(sale.qty, sale.rowId, sale.qty); + } } } s.updateGold.run(newGoldVal, cid); diff --git a/tests/integration/shop.test.js b/tests/integration/shop.test.js index 91ec6fa..d70f316 100644 --- a/tests/integration/shop.test.js +++ b/tests/integration/shop.test.js @@ -320,8 +320,8 @@ describe('shop', () => { assert.equal(res.status, 200); assert.equal(body.ok, true); - // Uncommon material sell: floor(4 * level / min_level) = floor(4 * 5 / 5) = 4 - assert.equal(body.data.character.gold, 104); // 100 + 4 + // Uncommon material sell: 4 * min_level = 4 * 5 = 20 + assert.equal(body.data.character.gold, 120); // 100 + 20 }); it('sells uncommon material using rarity default', async () => { @@ -339,8 +339,8 @@ describe('shop', () => { assert.equal(res.status, 200); assert.equal(body.ok, true); - // Uncommon material sell: floor(4 * 10 / 10) = 4 - assert.equal(body.data.character.gold, 104); // 100 + 4 + // Uncommon material sell: 4 * min_level = 4 * 10 = 40 + assert.equal(body.data.character.gold, 140); // 100 + 40 }); it('rejects selling a non-material item', async () => { diff --git a/tests/integration/step-10.14.test.js b/tests/integration/step-10.14.test.js new file mode 100644 index 0000000..4db618b --- /dev/null +++ b/tests/integration/step-10.14.test.js @@ -0,0 +1,190 @@ +// Integration tests for step 10.14: Material sell prices use item-level formula. +const { describe, it, before, after } = require('node:test'); +const assert = require('node:assert/strict'); +const { setup, teardown, cleanup } = require('../helpers'); + +describe('step-10.14 material sell prices (item-level)', () => { + let baseUrl, userSeq = 0; + + before(async () => { baseUrl = await setup(); }); + after(async () => { teardown(); cleanup(); }); + + // ─── helpers ────────────────────────────────────────────────────────── + + async function registerAndLogin(username, password) { + await fetch(`${baseUrl}/api/auth/register`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }); + const res = await fetch(`${baseUrl}/api/auth/login`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }); + assert.equal(res.status, 200); + return res.headers.get('set-cookie') || ''; + } + + async function createHero(cookie, name, cls) { + const res = await fetch(`${baseUrl}/api/character`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ name, class: cls }), + }); + assert.equal(res.status, 201); + const { data } = await res.json(); + return data.character.id; + } + + function grantItem(characterId, itemId, quantity = 1) { + const db = require('../../src/db').getDb(); + const NOW = 1_700_000_000_000; + const existing = db.prepare( + 'SELECT id, quantity FROM inventory WHERE character_id = ? AND item_id = ?' + ).get(characterId, itemId); + if (existing) { + db.prepare('UPDATE inventory SET quantity = quantity + ? WHERE id = ?').run(quantity, existing.id); + } else { + db.prepare( + 'INSERT INTO inventory (character_id, item_id, quantity, equipped_slot, acquired_at) VALUES (?, ?, ?, NULL, ?)' + ).run(characterId, itemId, quantity, NOW); + } + } + + // ─── Rat Tail (common, min_level 1) — always 2g regardless of hero level ── + + it('Rat Tail sells for 2g at hero level 1', async () => { + const cookie = await registerAndLogin(`s14a${userSeq++}`, 'pass1234'); + const characterId = await createHero(cookie, 'S14A', 'warrior'); + grantItem(characterId, 17, 1); // Rat Tail + + const res = await fetch(`${baseUrl}/api/shop/sell`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ itemId: 17, quantity: 1 }), + }); + const body = await res.json(); + assert.equal(res.status, 200); + assert.equal(body.ok, true); + // Character starts with 50g (DB default), sells Rat Tail → 52g + assert.equal(body.data.character.gold, 52); + }); + + it('Rat Tail sells for 2g at hero level 10', async () => { + const cookie = await registerAndLogin(`s14b${userSeq++}`, 'pass1234'); + const characterId = await createHero(cookie, 'S14B', 'warrior'); + grantItem(characterId, 17, 1); // Rat Tail + + const res = await fetch(`${baseUrl}/api/shop/sell`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ itemId: 17, quantity: 1 }), + }); + const body = await res.json(); + assert.equal(res.status, 200); + assert.equal(body.ok, true); + assert.equal(body.data.character.gold, 52); + }); + + it('Rat Tail sells for 2g at hero level 50', async () => { + const cookie = await registerAndLogin(`s14c${userSeq++}`, 'pass1234'); + const characterId = await createHero(cookie, 'S14C', 'warrior'); + grantItem(characterId, 17, 1); // Rat Tail + + const res = await fetch(`${baseUrl}/api/shop/sell`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ itemId: 17, quantity: 1 }), + }); + const body = await res.json(); + assert.equal(res.status, 200); + assert.equal(body.ok, true); + assert.equal(body.data.character.gold, 52); + }); + + // ─── Drake Scale (rare, min_level 14) — always 112g regardless of hero level ── + + it('Drake Scale sells for 112g at hero level 14', async () => { + const cookie = await registerAndLogin(`s14d${userSeq++}`, 'pass1234'); + const characterId = await createHero(cookie, 'S14D', 'warrior'); + grantItem(characterId, 21, 1); // Drake Scale + + const res = await fetch(`${baseUrl}/api/shop/sell`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ itemId: 21, quantity: 1 }), + }); + const body = await res.json(); + assert.equal(res.status, 200); + assert.equal(body.ok, true); + // Character starts with 50g (DB default), sells Drake Scale → 162g + assert.equal(body.data.character.gold, 162); + }); + + it('Drake Scale sells for 112g at hero level 50', async () => { + const cookie = await registerAndLogin(`s14e${userSeq++}`, 'pass1234'); + const characterId = await createHero(cookie, 'S14E', 'warrior'); + grantItem(characterId, 21, 1); // Drake Scale + + const res = await fetch(`${baseUrl}/api/shop/sell`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ itemId: 21, quantity: 1 }), + }); + const body = await res.json(); + assert.equal(res.status, 200); + assert.equal(body.ok, true); + assert.equal(body.data.character.gold, 162); + }); + + // ─── Shop-listed price equals actual payment ────────────────────────── + + it('shop-listed sellPrice equals the amount actually paid on sell', async () => { + const cookie = await registerAndLogin(`s14f${userSeq++}`, 'pass1234'); + const characterId = await createHero(cookie, 'S14F', 'warrior'); + grantItem(characterId, 17, 3); // 3 Rat Tails + + // Get shop stock to see the listed sellPrice. + const stockRes = await fetch(`${baseUrl}/api/shop`, { + headers: { Cookie: cookie }, + }); + const stockBody = await stockRes.json(); + assert.equal(stockRes.status, 200); + const ratTail = stockBody.data.stock.find((i) => i.itemId === 17); + assert.ok(ratTail, 'Rat Tail should be in stock'); + const listedPrice = ratTail.sellPrice; + assert.equal(listedPrice, 2, 'listed sellPrice for Rat Tail should be 2'); + + // Sell 1 Rat Tail. + const sellRes = await fetch(`${baseUrl}/api/shop/sell`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ itemId: 17, quantity: 1 }), + }); + const sellBody = await sellRes.json(); + assert.equal(sellRes.status, 200); + assert.equal(sellBody.ok, true); + // Gold should increase by exactly the listed price (50 + 2 = 52). + assert.equal(sellBody.data.character.gold, 50 + listedPrice); + }); + + // ─── Multi-quantity sell ────────────────────────────────────────────── + + it('selling 5 Rat Tails yields exactly 10g (5 × 2g)', async () => { + const cookie = await registerAndLogin(`s14g${userSeq++}`, 'pass1234'); + const characterId = await createHero(cookie, 'S14G', 'warrior'); + grantItem(characterId, 17, 5); + + const res = await fetch(`${baseUrl}/api/shop/sell`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Cookie: cookie }, + body: JSON.stringify({ itemId: 17, quantity: 5 }), + }); + const body = await res.json(); + assert.equal(res.status, 200); + assert.equal(body.ok, true); + // 50 + 5*2 = 60 + assert.equal(body.data.character.gold, 60); + }); +});