const express = require('express'); const { z } = require('zod'); const prisma = require('../db'); const { requireAuth } = require('../middleware/auth'); const { requireCharacterAccess } = require('../middleware/characterAccess'); const { loadCampaignMembership } = require('../middleware/campaignAccess'); const { computeCharacterSheet, computeWeaponStats, getClassSaveProficiencies, getClassSpellcastingAbility, scaledDamageDice, canUseGear, MAX_GEAR_LEVEL, ABILITIES, } = require('../game/calculations'); const { rollDie, rollAbilityScore, abilityScoreFromDice, speciesChoicesForRoll, classChoicesForRoll, autoSelectSkills, validateManualRoll, validatePicks, composeFromPicks, validateTalents, composeSpecialAbilities, } = require('../game/buildFlow'); const characterOptions = require('../game/data/characterOptions'); const { SKILLS } = require('../game/data/skills'); const { CURRENCIES, COINS, COIN_VALUE, COIN_COLUMN, InsufficientGoldError, adjustGold, spendCoins, worthInGold, giveGear } = require('../utils/grants'); const { recordVisits } = require('../utils/locations'); const { SHEET_INCLUDE, settleHp } = require('../utils/sheet'); const { absorbDamage, NO_DEATH_SAVES, lifeState, deathSaveInfo, settleDeathSaves, changeHp, rollDeathSave } = require('../utils/hp'); const router = express.Router(); router.use(requireAuth); async function loadFullCharacter(id) { return prisma.character.findUnique({ where: { id }, include: { skillProficiencies: true, saveProficiencies: true, inventoryItems: { include: { item: true } }, weapons: { include: { weapon: true } }, spells: { include: { spell: true } }, currentLocation: true, }, }); } // privateNotes is a real privacy boundary, not a UI hide — it's only ever // included in the payload for the character's own owning player. // // Another player (neither the owner nor the DM) gets the sheet the party can // see across the table — who the character is, HP, AC, abilities, what they // fight with — but not what is in their pack, their purse, or where they are. // `isDM` defaults to true because every caller but the plain read is a write // route, which only the owner or the DM can reach. function serializeCharacter(character, isOwner, isDM = true) { const restricted = !isOwner && !isDM; const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies); return { id: character.id, campaignId: character.campaignId, userId: character.userId, createdById: character.createdById, name: character.name, species: character.species, characterClass: character.characterClass, level: character.level, xp: character.xp, motivation: character.motivation, halfElfBonusAbility1: character.halfElfBonusAbility1, halfElfBonusAbility2: character.halfElfBonusAbility2, rolledScores: { STR: character.strScore, DEX: character.dexScore, CON: character.conScore, INT: character.intScore, WIS: character.wisScore, CHA: character.chaScore, }, currentHp: character.currentHp, tempHp: character.tempHp, deathSaves: deathSaveInfo(character), armorBonus: character.armorBonus, specialAbilities: character.specialAbilities, background: character.background, appearance: character.appearance, privateNotes: isOwner ? character.privateNotes : undefined, diceMode: character.diceMode, currentLocationId: restricted ? null : character.currentLocationId, currentLocation: restricted ? null : character.currentLocation || null, gold: restricted ? null : character.gold, silver: restricted ? null : character.silver, copper: restricted ? null : character.copper, cash: restricted ? null : character.cash, restricted, buildStage: character.buildStage, buildState: character.buildStage === 'COMPLETE' ? null : character.buildState, skillProficiencies: character.skillProficiencies, saveProficiencies: character.saveProficiencies, // Each held entry carries what its level works out to: the dice at that // level, and whether this character is high enough level to use it. inventoryItems: (restricted ? [] : character.inventoryItems).map((ii) => ({ ...ii, scaledDamageDice: ii.item.damageDice ? scaledDamageDice(ii.item.damageDice, ii.level, ii.item.damageScaling, ii.item.minLevel) : null, usable: canUseGear(character.level, ii.level), })), weapons: character.weapons.map((cw) => ({ ...cw, scaledDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel), usable: canUseGear(character.level, cw.level), })), spells: character.spells.map((cs) => ({ ...cs, usable: canUseGear(character.level, cs.spell.level) })), sheet: character.buildStage === 'COMPLETE' ? sheet : null, }; } // The lists the builder's story steps are made of. Static, and the same for // everyone; the page fetches them rather than keeping a second copy. router.get('/build/options', (req, res) => { const { MOTIVATIONS, SPECIES_TRAITS, CLASS_FEATURES, TALENTS, TALENT_PICKS, BACKGROUND_GROUPS, APPEARANCE_GROUPS } = characterOptions; res.json({ motivations: MOTIVATIONS, speciesTraits: SPECIES_TRAITS, classFeatures: CLASS_FEATURES, talents: TALENTS, talentPicks: TALENT_PICKS, background: BACKGROUND_GROUPS, appearance: APPEARANCE_GROUPS, }); }); router.get('/:id', requireCharacterAccess(), async (req, res, next) => { try { const character = await loadFullCharacter(req.character.id); res.json({ character: serializeCharacter(character, req.isOwner, req.isDM) }); } catch (err) { next(err); } }); const patchCharacterSchema = z.object({ name: z.string().min(1).max(80).optional(), currentHp: z.number().int().optional(), tempHp: z.number().int().min(0).max(9999).optional(), armorBonus: z.number().int().min(-30).max(30).optional(), speedOverride: z.number().int().min(0).nullable().optional(), specialAbilities: z.string().max(4000).nullable().optional(), background: z.string().max(4000).nullable().optional(), appearance: z.string().max(4000).nullable().optional(), privateNotes: z.string().max(4000).nullable().optional(), currentLocationId: z.string().nullable().optional(), level: z.number().int().min(1).max(20).optional(), xp: z.number().int().min(0).optional(), }); // Progression and placement are the DM's call, and so is rewriting what the // builder composed (special abilities, background, appearance): a player // picks those from lists and cannot type their own. So are HP and temp HP: // a player cannot heal or hurt their own character. The owning player can // edit the rest of their own sheet. Gold is not patchable at all — it only // moves through the ledger (POST /:id/gold). The armor bonus is the DM's // adjustment on top of what equipped gear gives, so it is the DM's too. const DM_ONLY_PATCH_FIELDS = ['currentHp', 'tempHp', 'level', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance']; function clamp(value, min, max) { return Math.min(Math.max(value, min), max); } router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, next) => { try { if (req.body && Object.values(COIN_COLUMN).some((coin) => req.body[coin] !== undefined)) { return res.status(400).json({ error: 'Gold, silver, copper and cash changes go through the money tracker.' }); } const parsed = patchCharacterSchema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); if (!req.isDM && DM_ONLY_PATCH_FIELDS.some((field) => parsed.data[field] !== undefined)) { return res.status(403).json({ error: 'Only the DM can change HP, temp HP, level, XP, speed, armor bonus, location, special abilities, background or appearance.' }); } // Damage is soaked by temp HP before it reaches real HP — unless this // same request sets temp HP outright. const settingHp = parsed.data.currentHp !== undefined; const settingTempHp = parsed.data.tempHp !== undefined; if (req.character.buildStage === 'COMPLETE' && (settingHp || parsed.data.level !== undefined)) { // Current HP stays within 0..max, including when a level change moves max. const geared = await prisma.character.findUnique({ where: { id: req.character.id }, include: SHEET_INCLUDE }); const maxHp = computeCharacterSheet({ ...geared, ...parsed.data }, geared.skillProficiencies, geared.saveProficiencies).hp.max; if (!settingHp) { parsed.data.currentHp = clamp(req.character.currentHp, 0, maxHp); } else { if (lifeState(req.character) === 'DEAD' && parsed.data.currentHp > 0) { return res.status(400).json({ error: `${req.character.name} is dead. The DM has to revive them before they can be healed.` }); } // Reaching 0, being hit while there, and being healed back up all // move the death saves along with the HP. const { tempHp, ...after } = changeHp(settingTempHp ? { ...req.character, tempHp: 0 } : req.character, parsed.data.currentHp, maxHp); Object.assign(parsed.data, after, settingTempHp ? {} : { tempHp }); } } else if (settingHp && !settingTempHp) { const after = absorbDamage(req.character.currentHp, req.character.tempHp, parsed.data.currentHp); parsed.data.currentHp = after.currentHp; if (after.tempHp !== req.character.tempHp) parsed.data.tempHp = after.tempHp; } // privateNotes is for the owning player only — a DM editing someone // else's character (or another player, though write access already // blocks that) should never be able to set it through this route. if (parsed.data.privateNotes !== undefined && !req.isOwner) { return res.status(403).json({ error: 'Only the owning player can edit private notes.' }); } if (parsed.data.currentLocationId) { const location = await prisma.location.findUnique({ where: { id: parsed.data.currentLocationId } }); if (!location || location.campaignId !== req.character.campaignId) { return res.status(400).json({ error: 'That location is not part of this campaign.' }); } } const updated = await prisma.character.update({ where: { id: req.character.id }, data: parsed.data }); if (parsed.data.currentLocationId) await recordVisits(prisma, [updated.id], parsed.data.currentLocationId); if (updated.level < req.character.level) { // Dropping a level can put equipped gear and prepared spells out of reach. const tooHigh = { characterId: updated.id, level: { gt: updated.level } }; await prisma.characterWeapon.updateMany({ where: tooHigh, data: { equipped: false } }); await prisma.inventoryItem.updateMany({ where: tooHigh, data: { equipped: false } }); await prisma.characterSpell.updateMany({ where: { characterId: updated.id, spell: { level: { gt: updated.level } } }, data: { prepared: false }, }); // Gear that came off may have been holding the maximum HP up. await settleHp(prisma, [updated.id]); } const full = await loadFullCharacter(updated.id); // Broadcast payload never includes privateNotes — a socket room has // every campaign member in it, not just the owner. Only the direct HTTP // response (below) is allowed to include it. req.app.get('io').to(`campaign:${updated.campaignId}`).emit('character:updated', { characterId: full.id }); res.json({ character: serializeCharacter(full, req.isOwner) }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // Death saves — what happens to a character at 0 HP (utils/hp.js) // --------------------------------------------------------------------------- const deathSaveTally = z.number().int().min(0).max(3); const deathSaveRoll = z.number().int().min(1, 'A death save is a d20: 1 to 20').max(20, 'A death save is a d20: 1 to 20'); const deathSaveSchema = z.discriminatedUnion('action', [ // What the d20 showed; the server works out what it means. z.object({ action: z.literal('roll'), roll: deathSaveRoll }), // Steadied by someone else: a Medicine check, a healer's kit, a spell. z.object({ action: z.literal('stabilize') }), // The DM setting the tallies by hand: a critical hit's second failure, or // undoing a mistake. z.object({ action: z.literal('set'), successes: deathSaveTally, failures: deathSaveTally }), // The DM bringing back the dead, at 1 HP. z.object({ action: z.literal('revive') }), ]); // The owning player rolls their own death saves and can be steadied; setting // the tallies by hand and raising the dead are the DM's. router.post('/:id/death-saves', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const parsed = deathSaveSchema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const { character } = req; if (character.buildStage !== 'COMPLETE') return res.status(400).json({ error: 'Character build is not finished yet.' }); const input = parsed.data; const state = lifeState(character); if ((input.action === 'set' || input.action === 'revive') && !req.isDM) { return res.status(403).json({ error: 'Only the DM can do that.' }); } let data; if (input.action === 'roll' || input.action === 'stabilize') { if (state !== 'DYING') return res.status(400).json({ error: `${character.name} is not dying, so there is no death save to make.` }); data = input.action === 'roll' ? rollDeathSave(character, input.roll) : { ...NO_DEATH_SAVES, stable: true }; } else if (input.action === 'set') { if (state === 'UP') return res.status(400).json({ error: `${character.name} is not at 0 HP.` }); data = settleDeathSaves(input.successes, input.failures); } else { if (state !== 'DEAD') return res.status(400).json({ error: `${character.name} is not dead.` }); data = { currentHp: 1, ...NO_DEATH_SAVES }; } await prisma.character.update({ where: { id: character.id }, data }); const full = await loadFullCharacter(character.id); req.app.get('io').to(`campaign:${full.campaignId}`).emit('character:updated', { characterId: full.id }); res.json({ character: serializeCharacter(full, req.isOwner) }); } catch (err) { next(err); } }); router.delete('/:id', requireCharacterAccess(), async (req, res, next) => { try { if (!req.isDM) return res.status(403).json({ error: 'DM only' }); await prisma.character.delete({ where: { id: req.character.id } }); res.status(204).end(); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // Copy to another campaign // --------------------------------------------------------------------------- // Weapons, spells and items are per-campaign rows, so a copied character's gear // is re-pointed at the target campaign's entry of the same name // (case-insensitive), creating that entry from the source row when the target // doesn't have one. A created entry is never a starting option — that stays // the target DM's decision. // Returns source id -> the target pool row. async function mapPoolByName(tx, model, sourceRows, targetCampaignId) { const existing = await tx[model].findMany({ where: { campaignId: targetCampaignId } }); const byName = new Map(existing.map((row) => [row.name.toLowerCase(), row])); const idMap = new Map(); for (const { id, campaignId, createdAt, ...fields } of sourceRows) { const key = fields.name.toLowerCase(); if (!byName.has(key)) { const created = await tx[model].create({ data: { ...fields, isStartingOption: false, campaignId: targetCampaignId }, }); byName.set(key, created); } idMap.set(id, byName.get(key)); } return idMap; } // The copy is an independent character owned by whoever made it: the original // is untouched and the two never sync. Campaign-bound state (location, notes, // encounter entries) stays behind, and the copy arrives at full HP. router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => { try { const parsed = z.object({ targetCampaignId: z.string().min(1) }).safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const { targetCampaignId } = parsed.data; if (!req.isDM && !req.isOwner) { return res.status(403).json({ error: 'You can only copy your own character' }); } if (req.character.buildStage !== 'COMPLETE') { return res.status(400).json({ error: 'Finish building this character before copying it.' }); } if (targetCampaignId === req.character.campaignId) { return res.status(400).json({ error: 'Pick a different campaign to copy this character into.' }); } const targetMembership = await loadCampaignMembership(req.user.id, targetCampaignId); if (!targetMembership) return res.status(403).json({ error: 'Not a member of the target campaign' }); const source = await loadFullCharacter(req.character.id); const sheet = computeCharacterSheet(source, source.skillProficiencies, source.saveProficiencies); const copyId = await prisma.$transaction(async (tx) => { const targetWeapons = await mapPoolByName(tx, 'weapon', source.weapons.map((cw) => cw.weapon), targetCampaignId); const targetSpells = await mapPoolByName(tx, 'spell', source.spells.map((cs) => cs.spell), targetCampaignId); const targetItems = await mapPoolByName(tx, 'item', source.inventoryItems.map((ii) => ii.item), targetCampaignId); // Two source entries that differ only by case land on one target row. const items = new Map(); for (const ii of source.inventoryItems) { const target = targetItems.get(ii.itemId); const itemId = target.id; const prev = items.get(itemId); items.set(itemId, { itemId, quantity: (prev ? prev.quantity : 0) + ii.quantity, equipped: Boolean(prev && prev.equipped) || ii.equipped, // The target campaign's entry may start at a higher level than the source's. level: Math.max(prev ? prev.level : 1, ii.level, target.minLevel), }); } const weapons = new Map(); for (const cw of source.weapons) { const target = targetWeapons.get(cw.weaponId); const weaponId = target.id; const prev = weapons.get(weaponId); weapons.set(weaponId, { weaponId, quantity: (prev ? prev.quantity : 0) + cw.quantity, equipped: Boolean(prev && prev.equipped) || cw.equipped, level: Math.max(prev ? prev.level : 1, cw.level, target.minLevel), }); } const spells = new Map(); for (const cs of source.spells) { const spellId = targetSpells.get(cs.spellId).id; const prev = spells.get(spellId); spells.set(spellId, { spellId, prepared: Boolean(prev && prev.prepared) || cs.prepared }); } const created = await tx.character.create({ data: { campaignId: targetCampaignId, userId: req.user.id, createdById: req.user.id, name: source.name, species: source.species, characterClass: source.characterClass, level: source.level, xp: source.xp, motivation: source.motivation, strScore: source.strScore, dexScore: source.dexScore, conScore: source.conScore, intScore: source.intScore, wisScore: source.wisScore, chaScore: source.chaScore, halfElfBonusAbility1: source.halfElfBonusAbility1, halfElfBonusAbility2: source.halfElfBonusAbility2, currentHp: sheet.hp.max, armorBonus: source.armorBonus, speedOverride: source.speedOverride, specialAbilities: source.specialAbilities, gold: source.gold, silver: source.silver, copper: source.copper, cash: source.cash, background: source.background, appearance: source.appearance, // Same privacy boundary as serializeCharacter: a DM copying a // player's character never carries the player's private notes along. privateNotes: req.isOwner ? source.privateNotes : null, diceMode: source.diceMode, buildStage: 'COMPLETE', skillProficiencies: { create: source.skillProficiencies.map(({ skill, proficient, expertise }) => ({ skill, proficient, expertise })), }, saveProficiencies: { create: source.saveProficiencies.map(({ ability, proficient }) => ({ ability, proficient })), }, inventoryItems: { create: [...items.values()] }, goldTransactions: { create: CURRENCIES.filter((currency) => source[COIN_COLUMN[currency]] > 0).map((currency) => ({ currency, amount: source[COIN_COLUMN[currency]], balanceAfter: source[COIN_COLUMN[currency]], reason: 'Carried over from another campaign', createdById: req.user.id, })), }, weapons: { create: [...weapons.values()] }, spells: { create: [...spells.values()] }, }, }); return created.id; }); const full = await loadFullCharacter(copyId); req.app.get('io').to(`campaign:${targetCampaignId}`).emit('character:created', { characterId: full.id }); res.status(201).json({ character: serializeCharacter(full, true) }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // Roll-Your-Character build flow — docs/ROLL_YOUR_CHARACTER.md // --------------------------------------------------------------------------- // Digital mode rolls server-side (crypto.randomInt) as before. Physical mode // requires the value(s) the roller typed in from their real dice — this // helper validates them against the step's real die range/count and throws // a user-facing error string on failure, otherwise returns the value(s) in // the exact same shape the digital path would have produced. function resolveSingleRoll(character, body, sides) { if (character.diceMode !== 'PHYSICAL') return rollDie(sides); const value = Number(body?.value); if (!validateManualRoll(sides, value)) { throw new Error(`Enter the d${sides} you rolled — a whole number from 1 to ${sides}.`); } return value; } function resolveAbilityRolls(character, body) { if (character.diceMode !== 'PHYSICAL') { return Array.from({ length: 6 }, () => rollAbilityScore()); } const sets = body?.abilitySets; if (!Array.isArray(sets) || sets.length !== 6) { throw new Error('Enter all six 4d6 sets you rolled at the table.'); } return sets.map((dice, i) => { if (!Array.isArray(dice) || dice.length !== 4 || !dice.every((d) => validateManualRoll(6, d))) { throw new Error(`Ability set ${i + 1}: enter four d6 results, each a whole number from 1 to 6.`); } return abilityScoreFromDice(dice); }); } router.patch('/:id/build/dice-mode', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const character = req.character; const parsed = z.object({ diceMode: z.enum(['DIGITAL', 'PHYSICAL']) }).safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const alreadyRolling = character.buildStage !== 'ROLLING_SPECIES' || Boolean((character.buildState || {}).speciesRoll); if (alreadyRolling) { return res.status(400).json({ error: 'Dice mode can only be chosen before the first roll of the build.' }); } const updated = await prisma.character.update({ where: { id: character.id }, data: { diceMode: parsed.data.diceMode } }); res.json({ diceMode: updated.diceMode }); } catch (err) { next(err); } }); router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const character = req.character; const stage = character.buildStage; const buildState = { ...(character.buildState || {}) }; try { // Every die is rolled once. Going back to a step shows the roll that was // already made; it never hands out a fresh one. if (stage === 'ROLLING_SPECIES') { if (buildState.speciesRoll) { return res.status(400).json({ error: 'Species die already rolled for this character — choose from what it offered.' }); } const roll = resolveSingleRoll(character, req.body, 6); buildState.speciesRoll = roll; buildState.speciesChoices = speciesChoicesForRoll(roll); } else if (stage === 'ROLLING_CLASS') { const alreadyRolled = buildState.classChoices && buildState.classChoices.type !== 'reroll'; if (alreadyRolled) { return res.status(400).json({ error: 'Class die already rolled for this character — submit a choice, or reroll if the current roll allows it.' }); } const roll = resolveSingleRoll(character, req.body, 8); buildState.classRoll = roll; buildState.classChoices = classChoicesForRoll(roll); delete buildState.characterClass; } else if (stage === 'ASSIGNING_SCORES') { if (buildState.abilityRolls) { return res.status(400).json({ error: 'Ability scores were already rolled for this character.' }); } buildState.abilityRolls = resolveAbilityRolls(character, req.body); } else { return res.status(400).json({ error: `No die roll is required at the "${stage}" step.` }); } } catch (rollErr) { return res.status(400).json({ error: rollErr.message }); } const updated = await prisma.character.update({ where: { id: character.id }, data: { buildState } }); res.json({ buildStage: updated.buildStage, buildState: updated.buildState }); } catch (err) { next(err); } }); const HALF_ELF_ELIGIBLE_ABILITIES = ABILITIES.filter((a) => a !== 'CHA'); const chooseSchemas = { ROLLING_SPECIES: z.object({ species: z.string(), halfElfBonusAbilities: z.array(z.enum(HALF_ELF_ELIGIBLE_ABILITIES)).length(2).optional(), }), ROLLING_CLASS: z.object({ characterClass: z.string() }), // Motivation is story only, so it is simply picked from the list (the stage // keeps its old name from when it was a die roll). ROLLING_MOTIVATION: z.object({ motivation: z.number().int() }), ASSIGNING_SCORES: z.object({ assignments: z.object({ STR: z.number().int().min(0).max(5), DEX: z.number().int().min(0).max(5), CON: z.number().int().min(0).max(5), INT: z.number().int().min(0).max(5), WIS: z.number().int().min(0).max(5), CHA: z.number().int().min(0).max(5), }), }), // Skill proficiencies are now auto-generated (see autoSelectSkills, applied // when this stage is entered from ASSIGNING_SCORES below) — this payload is // an optional DM correction, not the normal path. ASSIGNING_PROFICIENCIES: z.object({ skillProficiencies: z .array( z.object({ skill: z.enum(Object.keys(SKILLS)), proficient: z.boolean().default(true), expertise: z.boolean().default(false), }) ) .optional(), }), CHOOSING_ABILITIES: z.object({ talents: z.array(z.string()) }), CHOOSING_BACKGROUND: z.object({ picks: z.record(z.array(z.string())) }), CHOOSING_APPEARANCE: z.object({ picks: z.record(z.array(z.string())) }), CHOOSING_EQUIPMENT: z.object({ weaponIds: z.array(z.string()).default([]), itemIds: z.array(z.string()).default([]), spellIds: z.array(z.string()).default([]), }), }; // Every id must be a distinct entry in this campaign's pool that the DM has // marked as a starting option. `reach` narrows that to entries a character of // this level can already use (gear by its starting level, spells by their level). async function allStartingOptions(model, ids, campaignId, reach) { if (new Set(ids).size !== ids.length) return false; if (ids.length === 0) return true; const count = await prisma[model].count({ where: { id: { in: ids }, campaignId, isStartingOption: true, ...reach } }); return count === ids.length; } const STAGE_ORDER = [ 'ROLLING_SPECIES', 'ROLLING_CLASS', 'ROLLING_MOTIVATION', 'ASSIGNING_SCORES', 'ASSIGNING_PROFICIENCIES', 'CHOOSING_ABILITIES', 'CHOOSING_BACKGROUND', 'CHOOSING_APPEARANCE', 'CHOOSING_EQUIPMENT', 'COMPLETE', ]; function nextStage(current) { const idx = STAGE_ORDER.indexOf(current); return STAGE_ORDER[idx + 1]; } router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const character = req.character; const stage = character.buildStage; const schema = chooseSchemas[stage]; if (!schema) return res.status(400).json({ error: `No choice is expected at the "${stage}" step.` }); const parsed = schema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const buildState = { ...(character.buildState || {}) }; let advanceTo = nextStage(stage); if (stage === 'ROLLING_SPECIES') { const choices = buildState.speciesChoices; if (!choices) return res.status(400).json({ error: 'Roll for species before choosing one.' }); const { species, halfElfBonusAbilities } = parsed.data; if (choices.type !== 'wildcard' && !choices.options.includes(species)) { return res.status(400).json({ error: `${species} was not offered by this roll.` }); } if (species === 'HALF_ELF') { if (!halfElfBonusAbilities) { return res.status(400).json({ error: 'Half-Elf requires choosing two abilities (other than CHA) for the +1/+1 bonus.' }); } if (new Set(halfElfBonusAbilities).size !== 2) { return res.status(400).json({ error: 'The two Half-Elf bonus abilities must be different.' }); } buildState.halfElfBonusAbilities = halfElfBonusAbilities; } else { delete buildState.halfElfBonusAbilities; } buildState.species = species; } else if (stage === 'ROLLING_CLASS') { const choices = buildState.classChoices; if (!choices || choices.type === 'reroll') { return res.status(400).json({ error: 'Roll for class before choosing one.' }); } const { characterClass } = parsed.data; if (choices.type !== 'wildcard' && !choices.options.includes(characterClass)) { return res.status(400).json({ error: `${characterClass} was not offered by this roll.` }); } buildState.characterClass = characterClass; if (req.campaign.skipMotivationRoll) { advanceTo = 'ASSIGNING_SCORES'; buildState.motivationText = null; } } else if (stage === 'ROLLING_MOTIVATION') { const motivation = characterOptions.MOTIVATIONS.find((m) => m.key === parsed.data.motivation); if (!motivation) return res.status(400).json({ error: 'Pick a motivation from the list.' }); buildState.motivationChoice = motivation.key; buildState.motivationText = motivation.label; } else if (stage === 'ASSIGNING_SCORES') { if (!buildState.abilityRolls) return res.status(400).json({ error: 'Roll ability scores first.' }); const { assignments } = parsed.data; const usedIndexes = Object.values(assignments); const uniqueIndexes = new Set(usedIndexes); if (uniqueIndexes.size !== 6 || Math.max(...usedIndexes) > 5) { return res.status(400).json({ error: 'Each of the 6 rolled scores must be assigned to exactly one ability.' }); } buildState.abilityAssignments = assignments; // Skill proficiencies are auto-generated per the class's SRD "choose N" // rule the moment ability scores are locked in, so the next step has // something to show immediately rather than an empty picker. They are // generated once per class and remembered: stepping back and forward // again (or switching class and switching back) never re-rolls them. const cls = buildState.characterClass; if (buildState.skillsForClass !== cls) { buildState.autoSkills = { ...(buildState.autoSkills || {}) }; buildState.autoSkills[cls] = buildState.autoSkills[cls] || autoSelectSkills(cls); buildState.skillProficiencies = buildState.autoSkills[cls]; buildState.skillsForClass = cls; } } else if (stage === 'ASSIGNING_PROFICIENCIES') { // Optional DM override of the auto-generated picks; if omitted, the // auto-generated set from the previous step stands as-is. if (parsed.data.skillProficiencies) { buildState.skillProficiencies = parsed.data.skillProficiencies; } } else if (stage === 'CHOOSING_ABILITIES') { const problem = validateTalents(parsed.data.talents); if (problem) return res.status(400).json({ error: problem }); buildState.talents = parsed.data.talents; } else if (stage === 'CHOOSING_BACKGROUND' || stage === 'CHOOSING_APPEARANCE') { const isBackground = stage === 'CHOOSING_BACKGROUND'; const groups = isBackground ? characterOptions.BACKGROUND_GROUPS : characterOptions.APPEARANCE_GROUPS; const problem = validatePicks(groups, parsed.data.picks); if (problem) return res.status(400).json({ error: problem }); // Keep only the groups that exist, so nothing else rides along in the build state. const picks = Object.fromEntries(groups.map((g) => [g.key, parsed.data.picks[g.key] || []])); buildState[isBackground ? 'backgroundPicks' : 'appearancePicks'] = picks; } else if (stage === 'CHOOSING_EQUIPMENT') { const { weaponIds, itemIds, spellIds } = parsed.data; const maxItems = req.campaign.startingItemCount; const maxSpells = req.campaign.startingSpellCount; // Weapons and items share the one "starting items" allowance. if (weaponIds.length + itemIds.length > maxItems) { return res.status(400).json({ error: `This campaign allows at most ${maxItems} starting item(s), weapons included.` }); } const hasSpellcasting = Boolean(getClassSpellcastingAbility(buildState.characterClass)); if (spellIds.length > 0 && !hasSpellcasting) { return res.status(400).json({ error: 'This class has no spellcasting ability — it cannot pick starting spells.' }); } if (spellIds.length > maxSpells) { return res.status(400).json({ error: `This campaign allows at most ${maxSpells} starting spell(s).` }); } // A new character can only start with what it can already use. const gearInReach = { minLevel: { lte: character.level } }; const allOffered = (await allStartingOptions('weapon', weaponIds, req.campaign.id, gearInReach)) && (await allStartingOptions('item', itemIds, req.campaign.id, gearInReach)) && (await allStartingOptions('spell', spellIds, req.campaign.id, { level: { lte: character.level } })); if (!allOffered) { return res.status(400).json({ error: `Pick only from the starting options the DM has made available for a level ${character.level} character.`, }); } buildState.equipment = { weaponIds, itemIds, spellIds }; advanceTo = 'CHOOSING_EQUIPMENT'; // stay here; POST /build/finalize completes the character } const updated = await prisma.character.update({ where: { id: character.id }, data: { buildState, buildStage: advanceTo }, }); res.json({ buildStage: updated.buildStage, buildState: updated.buildState }); } catch (err) { next(err); } }); // Steps back to the previous step so its choice can be changed. Dice are // never re-rolled: the earlier step comes back with the same roll, the same // options and the previous pick still in place. The only thing dropped is the // equipment selection, which is re-confirmed on the way forward (a change of // class can change which starting spells are allowed). router.post('/:id/build/back', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const character = req.character; const stage = character.buildStage; const buildState = { ...(character.buildState || {}) }; let backTo; if (stage === 'CHOOSING_EQUIPMENT' && buildState.equipment) { backTo = 'CHOOSING_EQUIPMENT'; // from the finalize prompt back to picking equipment } else { const idx = STAGE_ORDER.indexOf(stage); if (idx <= 0 || stage === 'COMPLETE') { return res.status(400).json({ error: 'There is no earlier step to go back to.' }); } backTo = STAGE_ORDER[idx - 1]; if (backTo === 'ROLLING_MOTIVATION' && req.campaign.skipMotivationRoll) backTo = 'ROLLING_CLASS'; } delete buildState.equipment; const updated = await prisma.character.update({ where: { id: character.id }, data: { buildState, buildStage: backTo }, }); res.json({ buildStage: updated.buildStage, buildState: updated.buildState }); } catch (err) { next(err); } }); router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const character = req.character; if (character.buildStage !== 'CHOOSING_EQUIPMENT') { return res.status(400).json({ error: `Character isn't ready to finalize (currently at "${character.buildStage}").` }); } const bs = character.buildState || {}; if (!bs.species || !bs.characterClass || !bs.abilityAssignments || !bs.equipment) { return res.status(400).json({ error: 'Build is incomplete — species, class, ability assignments, and equipment are all required.' }); } const rolledScores = {}; for (const ability of ABILITIES) { const rollIndex = bs.abilityAssignments[ability]; rolledScores[ability] = bs.abilityRolls[rollIndex].total; } const [halfElfBonusAbility1, halfElfBonusAbility2] = bs.halfElfBonusAbilities || [null, null]; const saveProfs = getClassSaveProficiencies(bs.characterClass); const result = await prisma.$transaction(async (tx) => { await tx.characterSkillProficiency.deleteMany({ where: { characterId: character.id } }); await tx.characterSaveProficiency.deleteMany({ where: { characterId: character.id } }); const updated = await tx.character.update({ where: { id: character.id }, data: { species: bs.species, characterClass: bs.characterClass, motivation: bs.motivationText || null, // Composed here, from the picks, so the text can only ever say what // the lists allow. specialAbilities: composeSpecialAbilities(bs.species, bs.characterClass, bs.talents || []), background: bs.backgroundPicks ? composeFromPicks(characterOptions.BACKGROUND_GROUPS, bs.backgroundPicks) : null, appearance: bs.appearancePicks ? composeFromPicks(characterOptions.APPEARANCE_GROUPS, bs.appearancePicks) : null, strScore: rolledScores.STR, dexScore: rolledScores.DEX, conScore: rolledScores.CON, intScore: rolledScores.INT, wisScore: rolledScores.WIS, chaScore: rolledScores.CHA, halfElfBonusAbility1, halfElfBonusAbility2, buildStage: 'COMPLETE', buildState: null, skillProficiencies: { create: (bs.skillProficiencies || []).map((sp) => ({ skill: sp.skill, proficient: sp.proficient !== false, expertise: Boolean(sp.expertise), })), }, saveProficiencies: { create: ABILITIES.map((ability) => ({ ability, proficient: saveProfs.includes(ability) })), }, weapons: { create: (bs.equipment.weaponIds || []).map((weaponId) => ({ weaponId, quantity: 1, equipped: false })), }, inventoryItems: { create: (bs.equipment.itemIds || []).map((itemId) => ({ itemId, quantity: 1, equipped: false })), }, spells: { create: (bs.equipment.spellIds || []).map((spellId) => ({ spellId, prepared: false })), }, }, include: { skillProficiencies: true, saveProficiencies: true }, }); const sheet = computeCharacterSheet(updated, updated.skillProficiencies, updated.saveProficiencies); const finalized = await tx.character.update({ where: { id: character.id }, data: { currentHp: sheet.hp.max }, }); return finalized; }); const full = await loadFullCharacter(result.id); req.app.get('io').to(`campaign:${result.campaignId}`).emit('character:created', { characterId: full.id }); res.json({ character: serializeCharacter(full, req.isOwner) }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // Quick Stats — combat-context panel (docs/GAME_RULES_REFERENCE.md) // --------------------------------------------------------------------------- router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next) => { try { const character = await loadFullCharacter(req.character.id); if (character.buildStage !== 'COMPLETE') { return res.status(400).json({ error: 'Character build is not finished yet.' }); } const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies); // The pack, the spell list and the purse are the owner's and the DM's to // see, as on the sheet; anyone else gets what is visible across the table. const restricted = !req.isOwner && !req.isDM; const effectsOf = (entry) => ({ effects: Array.isArray(entry.effects) ? entry.effects : [], effectNote: entry.effectNote || null }); // Everything held is listed, usable or not: `usable` says whether the // character is high enough level for it. const weapons = character.weapons.map((cw) => ({ characterWeaponId: cw.id, weaponId: cw.weaponId, name: cw.weapon.name, level: cw.level, equipped: cw.equipped, quantity: cw.quantity, usable: canUseGear(character.level, cw.level), ...effectsOf(cw.weapon), ...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level), })); const inventory = character.inventoryItems.map((ii) => ({ inventoryItemId: ii.id, itemId: ii.itemId, name: ii.item.name, description: ii.item.description, level: ii.level, equipped: ii.equipped, quantity: ii.quantity, usable: canUseGear(character.level, ii.level), damageDice: ii.item.damageDice ? scaledDamageDice(ii.item.damageDice, ii.level, ii.item.damageScaling, ii.item.minLevel) : null, ...effectsOf(ii.item), })); const spells = character.spells.map((cs) => ({ characterSpellId: cs.id, name: cs.spell.name, level: cs.spell.level, damageDice: cs.spell.damageDice, description: cs.spell.description, prepared: cs.prepared, usable: canUseGear(character.level, cs.spell.level), })); res.json({ quickStats: { id: character.id, name: character.name, level: character.level, species: character.species, characterClass: character.characterClass, currentHp: character.currentHp, maxHp: sheet.hp.max, tempHp: character.tempHp, deathSaves: deathSaveInfo(character), armorClass: sheet.armorClass, initiative: sheet.initiative, speed: sheet.speed, proficiencyBonus: sheet.proficiencyBonus, spellcasting: sheet.spellcasting, passivePerception: sheet.passivePerception, abilities: sheet.abilities, specialAbilities: character.specialAbilities, // What equipped gear is adding and taking away, and what else it does. gear: sheet.gear, weapons, restricted, inventory: restricted ? [] : inventory, spells: restricted ? [] : spells, purse: restricted ? null : { gold: character.gold, silver: character.silver, copper: character.copper, cash: character.cash }, }, }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // Money tracker — the gold balance only ever changes through this ledger // --------------------------------------------------------------------------- const GOLD_TRANSACTION_INCLUDE = { createdBy: { select: { displayName: true } } }; // Which coin an amount is in; gold when none is given. const currencySchema = z.enum(CURRENCIES).default('GOLD'); function coinName(currency) { return currency.toLowerCase(); } const PURSE_SELECT = { gold: true, silver: true, copper: true, cash: true }; // For a payment the whole purse can't cover. Cash stands apart from the coins. function notEnoughMoney(character, amount, currency) { if (currency === 'CASH') return `Not enough cash — ${character.name} has $${character.cash}, which doesn't cover $${amount}.`; return `Not enough money — ${character.name} has ${character.gold} gold, ${character.silver} silver and ${character.copper} copper (worth ${worthInGold(character)} gold), which doesn't cover ${amount} ${coinName(currency)}.`; } router.get('/:id/gold', requireCharacterAccess(), async (req, res, next) => { try { if (!req.isDM && !req.isOwner) return res.status(403).json({ error: "Only the character's player and the DM can see its money" }); const transactions = await prisma.goldTransaction.findMany({ where: { characterId: req.character.id }, include: GOLD_TRANSACTION_INCLUDE, orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], }); res.json({ gold: req.character.gold, silver: req.character.silver, copper: req.character.copper, cash: req.character.cash, transactions }); } catch (err) { next(err); } }); // amount is signed: positive = gained, negative = spent. Only the DM records // entries here — a player cannot add money to their own purse or write it // off; theirs moves by giving, buying and exchanging. Each entry is stamped // with who made it. A spend is paid from the whole purse: if there aren't enough of the coin // named, bigger coins are broken (or smaller ones counted out) to cover it. // Cash is only ever paid in cash. router.post('/:id/gold', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const parsed = z .object({ amount: z.number().int().min(-1000000).max(1000000).refine((n) => n !== 0, 'Amount cannot be zero'), currency: currencySchema, reason: z.string().trim().max(200).optional().nullable(), }) .safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const { amount, currency, reason } = parsed.data; if (!req.isDM) return res.status(403).json({ error: 'Only the DM can record a gain or a spend.' }); let transactions; try { // Throwing inside the transaction rolls the balance change back. transactions = await prisma.$transaction(async (tx) => { const entry = { characterId: req.character.id, currency, reason, userId: req.user.id, include: GOLD_TRANSACTION_INCLUDE }; return amount > 0 ? [await adjustGold(tx, { ...entry, amount })] : spendCoins(tx, { ...entry, amount: -amount }); }); } catch (err) { if (!(err instanceof InsufficientGoldError)) throw err; return res.status(400).json({ error: notEnoughMoney(req.character, -amount, currency) }); } emitCharacterUpdated(req); const purse = await prisma.character.findUnique({ where: { id: req.character.id }, select: PURSE_SELECT }); res.status(201).json({ ...purse, transaction: transactions[0], transactions }); } catch (err) { next(err); } }); // Changes coins of one kind into another at their fixed worth (1 gold = 10 // silver = 100 copper). `amount` is how many `from` coins to hand over; it has // to come to a whole number of `to` coins. Both sides go on the ledger. Unlike // a spend, this moves exactly the coins named: no change is made. Cash has no // worth in coins, so it can't be exchanged. router.post('/:id/gold/exchange', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const parsed = z .object({ from: z.enum(COINS), to: z.enum(COINS), amount: z.number().int().min(1).max(1000000) }) .refine((data) => data.from !== data.to, { message: 'Pick two different coins' }) .safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const { from, to, amount } = parsed.data; const worth = amount * COIN_VALUE[from]; if (worth % COIN_VALUE[to] !== 0) { const step = COIN_VALUE[to] / COIN_VALUE[from]; return res.status(400).json({ error: `${amount} ${coinName(from)} doesn't make a whole number of ${coinName(to)} — exchange in multiples of ${step}.` }); } const received = worth / COIN_VALUE[to]; try { await prisma.$transaction(async (tx) => { const base = { characterId: req.character.id, userId: req.user.id }; await adjustGold(tx, { ...base, currency: from, amount: -amount, reason: `Exchanged for ${received} ${coinName(to)}` }); await adjustGold(tx, { ...base, currency: to, amount: received, reason: `Exchanged from ${amount} ${coinName(from)}` }); }); } catch (err) { if (!(err instanceof InsufficientGoldError)) throw err; return res.status(400).json({ error: `Not enough ${coinName(from)} — the balance is ${req.character[COIN_COLUMN[from]]}.` }); } emitCharacterUpdated(req); const character = await loadFullCharacter(req.character.id); res.status(201).json({ character: serializeCharacter(character, req.isOwner, req.isDM), received }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // Gear held by this character — weapons, items and spells all come from the // campaign's DM-managed pools. Only the DM hands them out, changes quantities // or levels, or takes them away; the owning player can toggle equipped / // prepared — but only on gear the character is high enough level to use. // --------------------------------------------------------------------------- function requireDmForGear(req, res) { if (req.isDM) return true; res.status(403).json({ error: 'Only the DM can give, remove, re-count or level up gear.' }); return false; } function emitCharacterUpdated(req) { req.app.get('io').to(`campaign:${req.character.campaignId}`).emit('character:updated', { characterId: req.character.id }); } // One set of routes per kind of gear. `key` is the pool-entry id column on the // join row (also the route param), `flag` the boolean the owner may toggle. // A held weapon or item (`ownLevel`) has a quantity and its own level; a spell // has neither, and the level a character needs is the spell's classic level. const GEAR = [ { path: 'weapons', pool: 'weapon', held: 'characterWeapon', key: 'weaponId', flag: 'equipped', ownLevel: true, label: 'weapon' }, { path: 'inventory', pool: 'item', held: 'inventoryItem', key: 'itemId', flag: 'equipped', ownLevel: true, label: 'item' }, { path: 'spells', pool: 'spell', held: 'characterSpell', key: 'spellId', flag: 'prepared', ownLevel: false, label: 'spell' }, ]; const gearLevelSchema = z.number().int().min(1).max(MAX_GEAR_LEVEL); // A character can only have so much equipped at once (campaign settings: // weapons and items together, and weapons alone). Returns why `adding` — a // weapon or an item, not yet counted — cannot go on as well, or null if it // can. `exceptPoolId` is the pool entry being equipped, in case it already is. async function equipBlocked(req, kind, exceptPoolId) { const { maxEquipped, maxEquippedWeapons } = req.campaign; const where = { characterId: req.character.id, equipped: true }; const [weapons, items] = await Promise.all([ prisma.characterWeapon.findMany({ where: { ...where, ...(kind === 'weapon' ? { weaponId: { not: exceptPoolId } } : {}) }, include: { weapon: true } }), prisma.inventoryItem.findMany({ where: { ...where, ...(kind === 'item' ? { itemId: { not: exceptPoolId } } : {}) }, include: { item: true } }), ]); const names = (rows, key) => rows.map((row) => row[key].name).join(', '); if (kind === 'weapon' && weapons.length >= maxEquippedWeapons) { if (maxEquippedWeapons === 0) return 'Nobody can equip a weapon in this campaign.'; return `${req.character.name} already has ${names(weapons, 'weapon')} equipped, and can hold ${maxEquippedWeapons === 1 ? 'one weapon' : `${maxEquippedWeapons} weapons`} at a time. Unequip it first.`; } if (weapons.length + items.length >= maxEquipped) { const on = [names(weapons, 'weapon'), names(items, 'item')].filter(Boolean).join(', '); return `${req.character.name} already has ${maxEquipped === 1 ? 'something' : `${maxEquipped} things`} equipped (${on}). Unequip one first.`; } return null; } for (const gear of GEAR) { const uniqueKey = `characterId_${gear.key}`; const whereHeld = (req) => ({ [uniqueKey]: { characterId: req.character.id, [gear.key]: req.params.poolId } }); const include = { [gear.pool]: true }; const requiredLevel = (row, poolEntry) => (gear.ownLevel ? row.level : poolEntry.level); const tooHighMessage = (level) => `Requires character level ${level} to ${gear.flag === 'prepared' ? 'prepare' : 'equip'} this ${gear.label}.`; const belowStartMessage = (entry) => `${entry.name} starts at level ${entry.minLevel} and can't go below it.`; const assignSchema = z.object({ [gear.key]: z.string(), ...(gear.ownLevel ? { quantity: z.number().int().min(1).default(1), level: gearLevelSchema.optional() } : {}), [gear.flag]: z.boolean().default(false), }); router.post(`/:id/${gear.path}`, requireCharacterAccess({ write: true }), async (req, res, next) => { try { if (!requireDmForGear(req, res)) return; const parsed = assignSchema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const poolId = parsed.data[gear.key]; const entry = await prisma[gear.pool].findUnique({ where: { id: poolId } }); if (!entry || entry.campaignId !== req.character.campaignId) { return res.status(400).json({ error: `That ${gear.label} is not part of this campaign.` }); } if (gear.ownLevel) { // Given at the entry's starting level unless the DM picks a higher one. parsed.data.level = parsed.data.level ?? entry.minLevel; if (parsed.data.level < entry.minLevel) return res.status(400).json({ error: belowStartMessage(entry) }); } if (parsed.data[gear.flag] && !canUseGear(req.character.level, requiredLevel(parsed.data, entry))) { return res.status(400).json({ error: tooHighMessage(requiredLevel(parsed.data, entry)) }); } if (gear.ownLevel && parsed.data.equipped) { const blocked = await equipBlocked(req, gear.pool, poolId); if (blocked) return res.status(400).json({ error: blocked }); } // Giving something the character already holds adds to the stack (the // stack keeps the level it has). const row = await prisma[gear.held].upsert({ where: { [uniqueKey]: { characterId: req.character.id, [gear.key]: poolId } }, create: { characterId: req.character.id, ...parsed.data }, update: gear.ownLevel ? { quantity: { increment: parsed.data.quantity } } : { [gear.flag]: parsed.data[gear.flag] }, include, }); if (gear.ownLevel) await settleHp(prisma, [req.character.id]); emitCharacterUpdated(req); res.status(201).json({ [gear.held]: row }); } catch (err) { next(err); } }); const patchSchema = z.object({ ...(gear.ownLevel ? { quantity: z.number().int().min(1).optional(), level: gearLevelSchema.optional() } : {}), [gear.flag]: z.boolean().optional(), }); router.patch(`/:id/${gear.path}/:poolId`, requireCharacterAccess({ write: true }), async (req, res, next) => { try { const parsed = patchSchema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const dmOnlyChange = parsed.data.quantity !== undefined || parsed.data.level !== undefined; if (dmOnlyChange && !requireDmForGear(req, res)) return; const existing = await prisma[gear.held].findUnique({ where: whereHeld(req), include }); if (!existing) return res.status(404).json({ error: `This character doesn't have that ${gear.label}.` }); const data = { ...parsed.data }; if (data.level !== undefined && data.level < existing[gear.pool].minLevel) { return res.status(400).json({ error: belowStartMessage(existing[gear.pool]) }); } const needed = requiredLevel({ ...existing, ...data }, existing[gear.pool]); if (!canUseGear(req.character.level, needed)) { if (data[gear.flag]) return res.status(400).json({ error: tooHighMessage(needed) }); data[gear.flag] = false; // levelled past its holder: it comes off } if (gear.ownLevel && data.equipped && !existing.equipped) { const blocked = await equipBlocked(req, gear.pool, req.params.poolId); if (blocked) return res.status(400).json({ error: blocked }); } const row = await prisma[gear.held].update({ where: whereHeld(req), data, include }); if (gear.ownLevel) await settleHp(prisma, [req.character.id]); emitCharacterUpdated(req); res.json({ [gear.held]: row }); } catch (err) { next(err); } }); router.delete(`/:id/${gear.path}/:poolId`, requireCharacterAccess({ write: true }), async (req, res, next) => { try { if (!requireDmForGear(req, res)) return; const { count } = await prisma[gear.held].deleteMany({ where: { characterId: req.character.id, [gear.key]: req.params.poolId }, }); if (count === 0) return res.status(404).json({ error: `This character doesn't have that ${gear.label}.` }); if (gear.ownLevel) await settleHp(prisma, [req.character.id]); emitCharacterUpdated(req); res.status(204).end(); } catch (err) { next(err); } }); } // --------------------------------------------------------------------------- // Giving to another character — a player (or the DM) hands something this // character holds to another character in the same campaign. It always moves: // whatever is given leaves the giver. That keeps the DM in control of how much // gear, gold and magic exists, while letting the party share it out. // --------------------------------------------------------------------------- const giveSchema = z.discriminatedUnion('kind', [ z.object({ kind: z.literal('gold'), toCharacterId: z.string(), amount: z.number().int().min(1), currency: z.enum(CURRENCIES).default('GOLD') }), z.object({ kind: z.literal('weapon'), toCharacterId: z.string(), id: z.string(), quantity: z.number().int().min(1).default(1) }), z.object({ kind: z.literal('item'), toCharacterId: z.string(), id: z.string(), quantity: z.number().int().min(1).default(1) }), z.object({ kind: z.literal('spell'), toCharacterId: z.string(), id: z.string() }), ]); class GiveError extends Error {} router.post('/:id/give', requireCharacterAccess({ write: true }), async (req, res, next) => { try { const parsed = giveSchema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() }); const give = parsed.data; const giver = req.character; const recipient = await prisma.character.findUnique({ where: { id: give.toCharacterId } }); if (!recipient || recipient.campaignId !== giver.campaignId) { return res.status(400).json({ error: 'That character is not part of this campaign.' }); } if (recipient.id === giver.id) return res.status(400).json({ error: 'Pick a different character to give it to.' }); if (giver.buildStage !== 'COMPLETE' || recipient.buildStage !== 'COMPLETE') { return res.status(400).json({ error: 'Both characters must be finished before they can trade.' }); } try { await prisma.$transaction(async (tx) => { if (give.kind === 'gold') { // The giver pays from their whole purse, with change; the recipient gets the coins named. const coins = { amount: give.amount, currency: give.currency, userId: req.user.id }; await spendCoins(tx, { ...coins, characterId: giver.id, reason: `Gave to ${recipient.name}` }); await adjustGold(tx, { ...coins, characterId: recipient.id, reason: `Received from ${giver.name}` }); return; } if (give.kind === 'spell') { const key = { characterId_spellId: { characterId: giver.id, spellId: give.id } }; const known = await tx.characterSpell.findUnique({ where: key, include: { spell: true } }); if (!known) throw new GiveError(`${giver.name} doesn't know that spell.`); const already = await tx.characterSpell.findUnique({ where: { characterId_spellId: { characterId: recipient.id, spellId: give.id } }, }); if (already) throw new GiveError(`${recipient.name} already knows ${known.spell.name}.`); await tx.characterSpell.delete({ where: key }); await tx.characterSpell.create({ data: { characterId: recipient.id, spellId: give.id } }); return; } // Weapons and items: take from the giver's stack, add to the // recipient's. A new stack arrives at the giver's level, unequipped; an // existing one just grows and keeps its own level. const model = give.kind === 'weapon' ? 'characterWeapon' : 'inventoryItem'; const poolKey = `${give.kind}Id`; const key = { [`characterId_${poolKey}`]: { characterId: giver.id, [poolKey]: give.id } }; const held = await tx[model].findUnique({ where: key, include: { [give.kind]: true } }); if (!held) throw new GiveError(`${giver.name} doesn't have that ${give.kind}.`); if (give.quantity > held.quantity) { throw new GiveError(`${giver.name} only has ${held.quantity} of ${held[give.kind].name}.`); } if (give.quantity === held.quantity) await tx[model].delete({ where: key }); else await tx[model].update({ where: key, data: { quantity: { decrement: give.quantity } } }); await giveGear(tx, give.kind, { characterId: recipient.id, entry: held[give.kind], quantity: give.quantity, level: held.level }); }); } catch (err) { if (err instanceof InsufficientGoldError) { return res.status(400).json({ error: notEnoughMoney(giver, give.amount, give.currency || 'GOLD') }); } if (err instanceof GiveError) return res.status(400).json({ error: err.message }); throw err; } // What was handed over may have been equipped, and holding the giver's maximum HP up. await settleHp(prisma, [giver.id]); const io = req.app.get('io'); for (const characterId of [giver.id, recipient.id]) { io.to(`campaign:${giver.campaignId}`).emit('character:updated', { characterId }); } const full = await loadFullCharacter(giver.id); res.json({ character: serializeCharacter(full, req.isOwner) }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // Notes about this character // --------------------------------------------------------------------------- router.get('/:id/notes', requireCharacterAccess(), async (req, res, next) => { try { const notes = await prisma.note.findMany({ where: { characterId: req.character.id, ...(req.isDM ? {} : { OR: [{ visibility: 'SHARED' }, { authorId: req.user.id }] }), }, include: { author: { select: { displayName: true } } }, orderBy: { createdAt: 'desc' }, }); res.json({ notes }); } catch (err) { next(err); } }); module.exports = router;