// The two ways a character's belongings change: coins through the ledger, and // gear from the campaign pools. Shared by the character sheet routes and by // encounter rewards so both follow the same rules. Every function takes a // Prisma client or transaction client as `db`. // The coins, and what each is worth counted in copper: silver is 0.1 gold and // copper is 0.01 gold, so 1 gold = 10 silver = 100 copper and 1 silver = 10 // copper. Whole numbers keep exchanges exact. const COINS = ['GOLD', 'SILVER', 'COPPER']; const COIN_VALUE = { GOLD: 100, SILVER: 10, COPPER: 1 }; // Everything a purse can hold: the coins, plus cash ($) — modern money for // crossover worlds. Cash has no worth in coins, so it is never exchanged for // them and never used to make change. const CURRENCIES = [...COINS, 'CASH']; // Each currency is its own column on the character. const COIN_COLUMN = { GOLD: 'gold', SILVER: 'silver', COPPER: 'copper', CASH: 'cash' }; class InsufficientGoldError extends Error {} // amount is signed: positive = gained, negative = spent, in `currency` coins. // Writes the ledger row and returns it; throws InsufficientGoldError if that // coin's balance would go below 0 (inside a transaction, that rolls the whole // thing back). This moves exactly the coins named and nothing else; to pay a // price out of whatever coins the purse holds, use spendCoins. async function adjustGold(db, { characterId, amount, currency = 'GOLD', reason, userId, include }) { const column = COIN_COLUMN[currency]; // The atomic increment is the balance check: two spends racing each other // can't both pass a stale read. const updated = await db.character.update({ where: { id: characterId }, data: { [column]: { increment: amount } } }); if (updated[column] < 0) throw new InsufficientGoldError(); return db.goldTransaction.create({ data: { characterId, currency, amount, balanceAfter: updated[column], reason: reason || null, createdById: userId }, include, }); } // Works out which coins leave (and come back as change) when a purse pays // `amount` coins of `currency`. Returns the change to each balance, e.g. // { GOLD: -1, SILVER: 7, COPPER: 0 } for 3 silver paid from a purse with only // gold in it — or null if the whole purse isn't worth that much. // 1. Coins of the kind asked for go first. // 2. Any shortfall is met by breaking the nearest bigger coin; the change // comes back in as few coins as possible. // 3. Only if there are no bigger coins left are smaller ones counted out. function planPayment(purse, currency, amount) { const worth = (coin) => COIN_VALUE[coin]; const delta = { GOLD: 0, SILVER: 0, COPPER: 0 }; const left = (coin) => purse[coin] + delta[coin]; let owed = amount * worth(currency); if (COINS.reduce((sum, coin) => sum + purse[coin] * worth(coin), 0) < owed) return null; const pay = (coin, count) => { delta[coin] -= count; owed -= count * worth(coin); }; pay(currency, Math.min(purse[currency], amount)); const bigger = COINS.filter((coin) => worth(coin) > worth(currency)).reverse(); // nearest first for (const coin of bigger) { if (owed <= 0) break; pay(coin, Math.min(left(coin), Math.ceil(owed / worth(coin)))); // Overpaid: hand the difference back, biggest coins first. let change = -owed; for (const small of COINS.filter((c) => worth(c) < worth(coin))) { if (change <= 0) break; const count = Math.floor(change / worth(small)); delta[small] += count; change -= count * worth(small); } if (owed < 0) owed = 0; } for (const coin of COINS.filter((c) => worth(c) < worth(currency))) { if (owed <= 0) break; pay(coin, Math.min(left(coin), Math.floor(owed / worth(coin)))); } return delta; } // Pays `amount` coins of `currency` out of a character's purse, making change // as needed (see planPayment). Every coin that moved gets its own ledger row; // the rows are returned, the one in `currency` first when there is one. Throws // InsufficientGoldError if the purse as a whole can't cover it. Cash is paid in // cash alone: coins don't cover it, and it doesn't cover coins. async function spendCoins(db, { characterId, amount, currency = 'GOLD', reason, userId, include }) { if (!COINS.includes(currency)) return [await adjustGold(db, { characterId, amount: -amount, currency, reason, userId, include })]; const character = await db.character.findUnique({ where: { id: characterId }, select: { gold: true, silver: true, copper: true } }); const purse = { GOLD: character.gold, SILVER: character.silver, COPPER: character.copper }; const delta = planPayment(purse, currency, amount); if (!delta) throw new InsufficientGoldError(); const moved = COINS.filter((coin) => delta[coin] !== 0).sort((a, b) => (b === currency) - (a === currency)); const madeChange = moved.some((coin) => coin !== currency); const label = reason || 'Spent'; const rows = []; for (const coin of moved) { rows.push( await adjustGold(db, { characterId, amount: delta[coin], currency: coin, // Says what the payment was when the coins that moved aren't the ones asked for. reason: madeChange ? `${label} (paid ${amount} ${currency.toLowerCase()}, with change)` : reason, userId, include, }) ); } return rows; } // A purse's coins as one figure in gold, for messages: 265 copper-worth -> 2.65. function worthInGold(character) { const copper = COINS.reduce((sum, coin) => sum + character[COIN_COLUMN[coin]] * COIN_VALUE[coin], 0); return copper / COIN_VALUE.GOLD; } const HELD = { weapon: { model: 'characterWeapon', key: 'weaponId' }, item: { model: 'inventoryItem', key: 'itemId' }, }; // Gives `quantity` of a pool weapon/item to a character. Something they // already hold stacks (and keeps the level the stack has); otherwise it // arrives at `level`, never below the entry's starting level. async function giveGear(db, kind, { characterId, entry, quantity = 1, level, equipped = false }) { const { model, key } = HELD[kind]; return db[model].upsert({ where: { [`characterId_${key}`]: { characterId, [key]: entry.id } }, create: { characterId, [key]: entry.id, quantity, equipped, level: Math.max(level ?? entry.minLevel, entry.minLevel) }, update: { quantity: { increment: quantity } }, include: { [kind]: true }, }); } module.exports = { CURRENCIES, COINS, COIN_VALUE, COIN_COLUMN, InsufficientGoldError, adjustGold, planPayment, spendCoins, worthInGold, giveGear };