- Free roam no longer adds the whole party: the DM adds who is there - A spell with no slot of its level or higher left cannot be declared; it takes the lowest slot left at or above its level. Cantrips take none - In a battle in progress a player changes the weapon in hand only as the battle begins or on their own turn after their attack has landed - Spells are listed cantrips first, then by level, with the level shown Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1933 lines
95 KiB
JavaScript
1933 lines
95 KiB
JavaScript
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,
|
|
getClassHitDieSize,
|
|
getClassSpellcastingAbility,
|
|
scaledDamageDice,
|
|
canUseGear,
|
|
spellSlotState,
|
|
xpProgress,
|
|
MAX_GEAR_LEVEL,
|
|
MAX_LEVEL,
|
|
MAX_SLOT_LEVEL,
|
|
ABILITIES,
|
|
} = require('../game/calculations');
|
|
const { LevelUpError, advance, advanceIn, levelUpPlan, switchSubclass, subclassByDefault } = require('../game/levelUp');
|
|
const { classLevels, withLevelIn } = require('../game/multiclass');
|
|
const { CLASSES } = require('../game/data/classes');
|
|
const { resourceTally, MAX_EXHAUSTION } = require('../game/classResources');
|
|
const { SUBCLASS_LEVEL, SUBCLASSES, subclassesOf, findSubclass, subclassName, newerVersionOf, subclassSummary } = require('../game/data/subclasses');
|
|
const {
|
|
rollDie,
|
|
rollAbilityScore,
|
|
abilityScoreFromDice,
|
|
speciesChoicesForRoll,
|
|
classChoicesForRoll,
|
|
SPECIES_ROLL_DIE,
|
|
CLASS_ROLL_DIE,
|
|
autoSelectSkills,
|
|
validateManualRoll,
|
|
validatePicks,
|
|
composeFromPicks,
|
|
validateTalents,
|
|
composeSpecialAbilities,
|
|
STANDARD_ARRAY,
|
|
POINT_BUY_BUDGET,
|
|
pointBuyCost,
|
|
effectiveDiceMode,
|
|
} = require('../game/buildFlow');
|
|
const characterOptions = require('../game/data/characterOptions');
|
|
const { speciesBonusProblem } = require('../game/data/species');
|
|
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, sheetOf, settleHp, bySpellLevel } = require('../utils/sheet');
|
|
const { inTurnOrder, weaponSwapOpen } = require('../game/combat');
|
|
const { isFallen } = require('../utils/actions');
|
|
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,
|
|
classLevels: true,
|
|
campaign: { select: { subclassesEnabled: true, multiclassEnabled: true, diceMode: true, hpOnLevelUp: true } },
|
|
},
|
|
});
|
|
}
|
|
|
|
// Whether a character's campaign uses subclasses. Takes a character loaded
|
|
// with its campaign (loadFullCharacter).
|
|
const usesSubclasses = (character) => !character.campaign || character.campaign.subclassesEnabled;
|
|
|
|
// 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);
|
|
// With subclasses switched off for the campaign, none is named or offered.
|
|
const subclasses = usesSubclasses(character);
|
|
return {
|
|
id: character.id,
|
|
campaignId: character.campaignId,
|
|
userId: character.userId,
|
|
createdById: character.createdById,
|
|
name: character.name,
|
|
species: character.species,
|
|
characterClass: character.characterClass,
|
|
subclass: subclasses ? character.subclass : null,
|
|
subclassName: subclasses ? subclassName(character.characterClass, character.subclass) : null,
|
|
// What the class can choose from, and the level it chooses at.
|
|
subclassLevel: subclasses ? (SUBCLASS_LEVEL[character.characterClass] ?? null) : null,
|
|
subclassOptions: subclasses ? subclassesOf(character.characterClass).map(subclassSummary) : [],
|
|
// The 2024 subclass that updates the one the character follows, if any.
|
|
subclassUpgrade: subclasses && newerVersionOf(character.characterClass, character.subclass) ? subclassSummary(newerVersionOf(character.characterClass, character.subclass)) : null,
|
|
level: character.level,
|
|
// Levels the DM has approved that are still to be taken (their picks made).
|
|
levelUpsPending: character.levelUpsPending,
|
|
// Every class the character has levels in, the first first; one entry
|
|
// unless they have multiclassed.
|
|
classes: classLevels(character).map((entry) => ({
|
|
characterClass: entry.characterClass,
|
|
level: entry.level,
|
|
subclass: subclasses ? entry.subclass : null,
|
|
subclassName: subclasses ? subclassName(entry.characterClass, entry.subclass) : null,
|
|
})),
|
|
xp: character.xp,
|
|
// A level already approved is no longer due.
|
|
xpProgress: xpProgress(character.xp, Math.min(MAX_LEVEL, character.level + character.levelUpsPending)),
|
|
motivation: character.motivation,
|
|
speciesBonusChoices: character.speciesBonusChoices || {},
|
|
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),
|
|
inspiration: character.inspiration,
|
|
exhaustion: character.exhaustion,
|
|
conditions: character.conditions,
|
|
armorBonus: character.armorBonus,
|
|
specialAbilities: character.specialAbilities,
|
|
background: character.background,
|
|
appearance: character.appearance,
|
|
privateNotes: isOwner ? character.privateNotes : undefined,
|
|
// The dice this character rolls with, and whether that is theirs to choose
|
|
// (the campaign leaves it to each character) or the campaign's.
|
|
diceMode: effectiveDiceMode(character.campaign, character),
|
|
diceModeChoosable: !character.campaign || character.campaign.diceMode === 'BOTH',
|
|
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) => {
|
|
// What this character rolls with it: to hit, and on top of its dice.
|
|
const { attackBonus, damageBonus } = computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level);
|
|
return {
|
|
...cw,
|
|
scaledDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel),
|
|
attackBonus,
|
|
damageBonus,
|
|
usable: canUseGear(character.level, cw.level),
|
|
};
|
|
}),
|
|
spells: [...character.spells].sort(bySpellLevel).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,
|
|
// Each class's subclasses, as the builder's subclass step lists them, and
|
|
// the level each class gets its subclass's first gifts at.
|
|
subclasses: Object.fromEntries(Object.entries(SUBCLASSES).map(([cls, list]) => [cls, list.map(subclassSummary)])),
|
|
subclassLevels: SUBCLASS_LEVEL,
|
|
});
|
|
});
|
|
|
|
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(MAX_LEVEL).optional(),
|
|
subclass: z.string().max(40).nullable().optional(), // a key from game/data/subclasses.js; null clears it
|
|
xp: z.number().int().min(0).max(10000000).optional(),
|
|
hitDiceUsed: z.number().int().min(0).max(MAX_LEVEL).optional(),
|
|
inspiration: z.boolean().optional(),
|
|
exhaustion: z.number().int().min(0).max(MAX_EXHAUSTION).optional(),
|
|
conditions: z.array(z.string().trim().min(1).max(40)).max(20).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. Hit
|
|
// Dice are spent on a rest, which the DM runs. Exhaustion and conditions are
|
|
// the DM's to give and take away. Inspiration is the DM's to give; the player
|
|
// may spend it (checked below).
|
|
const DM_ONLY_PATCH_FIELDS = ['currentHp', 'tempHp', 'level', 'subclass', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance', 'hitDiceUsed', 'exhaustion', 'conditions'];
|
|
|
|
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, Hit Dice, level, subclass, XP, speed, armor bonus, location, exhaustion, conditions, special abilities, background or appearance.' });
|
|
}
|
|
if (!req.isDM && parsed.data.inspiration === true) {
|
|
return res.status(403).json({ error: 'Only the DM can give inspiration. You can spend it.' });
|
|
}
|
|
if (parsed.data.conditions) parsed.data.conditions = [...new Set(parsed.data.conditions)];
|
|
|
|
const newLevel = parsed.data.level ?? req.character.level;
|
|
if (parsed.data.level !== undefined || parsed.data.hitDiceUsed !== undefined) {
|
|
// A character has one Hit Die per level, so none can be spent beyond that.
|
|
parsed.data.hitDiceUsed = Math.min(parsed.data.hitDiceUsed ?? req.character.hitDiceUsed, newLevel);
|
|
}
|
|
if (newLevel !== req.character.level) {
|
|
// Spent slots of a level the character no longer has are forgotten.
|
|
const slots = spellSlotState(req.character.characterClass, newLevel, req.character.spellSlotsUsed);
|
|
const tally = [];
|
|
for (const slot of slots ? slots.levels : []) tally[slot.level - 1] = slot.used;
|
|
parsed.data.spellSlotsUsed = Array.from(tally, (used) => used || 0);
|
|
}
|
|
const characterClass = req.character.characterClass;
|
|
const askedSubclass = parsed.data.subclass; // before a level change may take one by default
|
|
let abilities = parsed.data.specialAbilities === undefined ? req.character.specialAbilities : null;
|
|
const writesAbilities = req.character.buildStage === 'COMPLETE' && parsed.data.specialAbilities === undefined;
|
|
if (writesAbilities && newLevel > req.character.level) {
|
|
// Setting a higher level by hand still writes down what the class and
|
|
// subclass give on the way there. A Boon, and a subclass not yet picked,
|
|
// are left as a line saying one is owed: picking them is part of
|
|
// levelling up properly (POST /:id/level-up).
|
|
let key = req.character.subclass;
|
|
for (let level = req.character.level + 1; level <= newLevel; level++) {
|
|
// With subclasses switched off, the class's first one is taken at the
|
|
// level it would have been chosen.
|
|
const taken = req.campaign.subclassesEnabled ? null : subclassByDefault(characterClass, level, key);
|
|
abilities = advance(abilities, characterClass, level, undefined, taken ? { key: taken, chosen: true } : { key }).specialAbilities;
|
|
if (taken) key = taken;
|
|
}
|
|
parsed.data.specialAbilities = abilities;
|
|
if (key !== req.character.subclass && askedSubclass === undefined) parsed.data.subclass = key;
|
|
}
|
|
if (askedSubclass !== undefined && askedSubclass !== req.character.subclass) {
|
|
if (!req.campaign.subclassesEnabled) return res.status(400).json({ error: 'Subclasses are switched off for this campaign.' });
|
|
const picked = askedSubclass;
|
|
if (picked !== null) {
|
|
if (!findSubclass(characterClass, picked)) return res.status(400).json({ error: 'That is not a subclass of this character\'s class.' });
|
|
// A path can be set before the class reaches it, as the builder does;
|
|
// its lines are written as the levels come.
|
|
}
|
|
// The old subclass's lines come off the sheet and the new one's go on.
|
|
if (writesAbilities) parsed.data.specialAbilities = switchSubclass(abilities, characterClass, newLevel, req.character.subclass, picked);
|
|
}
|
|
|
|
// 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);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Spell slots — the slot tracker. How many slots there are comes from class
|
|
// and level (game/calculations.js); the character row keeps how many are spent.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const ORDINALS = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th'];
|
|
const slotLevelSchema = z.number().int().min(1).max(MAX_SLOT_LEVEL);
|
|
|
|
const spellSlotSchema = z.discriminatedUnion('action', [
|
|
// Casting a spell: one slot of that level is spent.
|
|
z.object({ action: z.literal('use'), level: slotLevelSchema }),
|
|
// The DM setting how many of a level are spent: giving one back, or fixing a mistake.
|
|
z.object({ action: z.literal('set'), level: slotLevelSchema, used: z.number().int().min(0).max(9) }),
|
|
// The DM giving every slot back.
|
|
z.object({ action: z.literal('restore') }),
|
|
]);
|
|
|
|
// The owning player spends their own slots, one at a time. Getting one back
|
|
// is the DM's: by hand here, or for everyone with a rest
|
|
// (POST /campaigns/:id/rest).
|
|
router.post('/:id/spell-slots', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
|
try {
|
|
const parsed = spellSlotSchema.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;
|
|
if (input.action !== 'use' && !req.isDM) {
|
|
return res.status(403).json({ error: 'Only the DM can give a spell slot back.' });
|
|
}
|
|
// By the sheet, so that a casting subclass and a multiclass count.
|
|
const slots = sheetOf(await loadFullCharacter(character.id)).spellSlots;
|
|
if (!slots) return res.status(400).json({ error: `${character.name} has no spell slots.` });
|
|
|
|
// The stored tally, squared up with what the class has at this level.
|
|
const used = Array.from({ length: slots.levels[slots.levels.length - 1].level }, (_, i) => {
|
|
const slot = slots.levels.find((s) => s.level === i + 1);
|
|
return slot ? slot.used : 0;
|
|
});
|
|
if (input.action === 'restore') {
|
|
used.fill(0);
|
|
} else {
|
|
const slot = slots.levels.find((s) => s.level === input.level);
|
|
if (!slot) return res.status(400).json({ error: `${character.name} has no ${ORDINALS[input.level - 1]}-level spell slots.` });
|
|
if (input.action === 'use') {
|
|
if (slot.remaining === 0) {
|
|
return res.status(400).json({
|
|
error: `${character.name} has no ${ORDINALS[input.level - 1]}-level spell slots left. They come back on a ${slots.restoresOn === 'SHORT' ? 'short or long' : 'long'} rest.`,
|
|
});
|
|
}
|
|
used[input.level - 1] = slot.used + 1;
|
|
} else {
|
|
used[input.level - 1] = Math.min(input.used, slot.max);
|
|
}
|
|
}
|
|
|
|
await prisma.character.update({ where: { id: character.id }, data: { spellSlotsUsed: used } });
|
|
const full = await loadFullCharacter(character.id);
|
|
emitCharacterUpdated(req);
|
|
res.json({ character: serializeCharacter(full, req.isOwner) });
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Class counters — Rage, Ki, Channel Divinity and the like. Which a character
|
|
// has, and how many, comes from class, subclass and level
|
|
// (game/classResources.js); the character row keeps how many are spent.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const resourceKey = z.string().min(1).max(40);
|
|
|
|
const resourceSchema = z.discriminatedUnion('action', [
|
|
// Using it: one is spent, or `amount` from a pool (Lay on Hands, Ki).
|
|
z.object({ action: z.literal('use'), key: resourceKey, amount: z.number().int().min(1).max(999).default(1) }),
|
|
// The DM setting how many are spent: giving some back, or fixing a mistake.
|
|
z.object({ action: z.literal('set'), key: resourceKey, used: z.number().int().min(0).max(999) }),
|
|
// The DM giving every counter back.
|
|
z.object({ action: z.literal('restore') }),
|
|
]);
|
|
|
|
// The owning player spends their own. Getting any back is the DM's: by hand
|
|
// here, or for everyone with a rest (POST /campaigns/:id/rest).
|
|
router.post('/:id/resources', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
|
try {
|
|
const parsed = resourceSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
|
if (req.character.buildStage !== 'COMPLETE') return res.status(400).json({ error: 'Character build is not finished yet.' });
|
|
const input = parsed.data;
|
|
if (input.action !== 'use' && !req.isDM) return res.status(403).json({ error: 'Only the DM can give a use back.' });
|
|
|
|
const character = await loadFullCharacter(req.character.id);
|
|
const resources = sheetOf(character).resources;
|
|
if (input.action === 'restore') {
|
|
for (const resource of resources) resource.used = 0;
|
|
} else {
|
|
const resource = resources.find((r) => r.key === input.key);
|
|
if (!resource) return res.status(400).json({ error: `${character.name} has no such counter.` });
|
|
if (input.action === 'use') {
|
|
if (input.amount > resource.remaining) {
|
|
const back = resource.restoresOn === 'SHORT' ? 'short or long' : 'long';
|
|
return res.status(400).json({
|
|
error:
|
|
resource.remaining === 0
|
|
? `${character.name} has no ${resource.name} left. It comes back on a ${back} rest.`
|
|
: `${character.name} has only ${resource.remaining} ${resource.name} left.`,
|
|
});
|
|
}
|
|
resource.used += input.amount;
|
|
} else {
|
|
resource.used = Math.min(input.used, resource.max);
|
|
}
|
|
}
|
|
|
|
await prisma.character.update({ where: { id: character.id }, data: { resourcesUsed: resourceTally(resources) } });
|
|
const full = await loadFullCharacter(character.id);
|
|
emitCharacterUpdated(req);
|
|
res.json({ character: serializeCharacter(full, req.isOwner) });
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Levelling up — one level at a time, with the checklist that goes with it
|
|
// (game/levelUp.js): the new level, full HP, the class's new special
|
|
// abilities, a Boon where the level grants one, new spells, fresh spell slots
|
|
// and the free weapon upgrade.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Answers the request and returns false when this character cannot be levelled
|
|
// up. The DM always can; the character's own player can once the DM has
|
|
// approved a level for them (levelUpsPending).
|
|
function canLevelUp(req, res, character) {
|
|
let refusal = null;
|
|
if (!req.isDM && !(req.isOwner && character.levelUpsPending > 0)) {
|
|
refusal = [403, req.isOwner ? 'Your DM has not approved a level up yet.' : 'Only the DM can level a character up.'];
|
|
} else if (character.buildStage !== 'COMPLETE') refusal = [400, 'Character build is not finished yet.'];
|
|
else if (character.level >= MAX_LEVEL) refusal = [400, `${character.name} is already level ${MAX_LEVEL}, the highest there is.`];
|
|
if (refusal) res.status(refusal[0]).json({ error: refusal[1] });
|
|
return !refusal;
|
|
}
|
|
|
|
// The plan for a character's next level in `toClass` (their first class when
|
|
// not given). Answers the request and returns null when the class can't take
|
|
// it: another class needs the campaign to allow multiclassing, and the
|
|
// character to meet both classes' requirements.
|
|
function planFor(req, res, character, toClass) {
|
|
const sheet = sheetOf(character);
|
|
const scores = Object.fromEntries(Object.entries(sheet.abilities).map(([ability, detail]) => [ability, detail.final]));
|
|
const multiclass = Boolean(character.campaign && character.campaign.multiclassEnabled);
|
|
if (toClass && !CLASSES[toClass]) {
|
|
res.status(400).json({ error: 'That is not a class.' });
|
|
return null;
|
|
}
|
|
const plan = levelUpPlan(character, { subclasses: usesSubclasses(character), multiclass, toClass, scores });
|
|
if (plan.characterClass !== character.characterClass && !classLevels(character).some((e) => e.characterClass === plan.characterClass)) {
|
|
if (!multiclass) {
|
|
res.status(400).json({ error: 'This campaign does not allow multiclassing.' });
|
|
return null;
|
|
}
|
|
const option = plan.classChoice.options.find((o) => o.characterClass === plan.characterClass);
|
|
if (!option.eligible) {
|
|
res.status(400).json({ error: option.problems.join(' ') });
|
|
return null;
|
|
}
|
|
}
|
|
return { plan, sheet };
|
|
}
|
|
|
|
// How the level's hit points are come by: the campaign's method, the die of
|
|
// the class taking the level, the average it would count, and whether the
|
|
// die is rolled at the table (physical dice) and typed in.
|
|
function hpGain(character, plan) {
|
|
const die = getClassHitDieSize(plan.characterClass);
|
|
return {
|
|
method: (character.campaign && character.campaign.hpOnLevelUp) || 'AVERAGE',
|
|
die,
|
|
average: Math.floor(die / 2) + 1,
|
|
physical: effectiveDiceMode(character.campaign, character) === 'PHYSICAL',
|
|
};
|
|
}
|
|
|
|
// What the next level brings, for the DM to look over before saying yes.
|
|
// `?class=` asks about a level in another class (multiclassing).
|
|
router.get('/:id/level-up', requireCharacterAccess(), async (req, res, next) => {
|
|
try {
|
|
const character = await loadFullCharacter(req.character.id);
|
|
if (!canLevelUp(req, res, character)) return;
|
|
const planned = planFor(req, res, character, typeof req.query.class === 'string' ? req.query.class : null);
|
|
if (!planned) return;
|
|
const { plan, sheet } = planned;
|
|
const after = sheetOf({ ...withLevelIn(character, plan.characterClass), spellSlotsUsed: [] });
|
|
// The spells that could be granted now: the campaign's, of a level the
|
|
// class can cast, that the character does not know. Sent with the plan
|
|
// because a player otherwise sees only the spells they hold.
|
|
const spellOptions = plan.spells
|
|
? await prisma.spell.findMany({
|
|
where: { campaignId: character.campaignId, level: { lte: plan.spells.maxSpellLevel }, id: { notIn: character.spells.map((held) => held.spellId) } },
|
|
select: { id: true, name: true, level: true, school: true, description: true },
|
|
orderBy: [{ level: 'asc' }, { name: 'asc' }],
|
|
})
|
|
: [];
|
|
res.json({ plan: { ...plan, maxHp: { from: sheet.hp.max, to: after.hp.max }, hp: hpGain(character, plan), spellSlots: after.spellSlots, spellOptions } });
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
});
|
|
|
|
const levelUpSchema = z.object({
|
|
characterClass: z.enum(Object.keys(CLASSES)).optional(), // the class taking the level; the first one when left out
|
|
subclass: z.string().optional(), // which subclass, at the level the class chooses one
|
|
boon: z.string().optional(), // which Boon, at a level that grants one
|
|
weaponId: z.string().nullable().optional(), // the weapon that gets the free upgrade
|
|
hpRoll: z.number().int().min(1).max(12).optional(), // the hit die rolled at the table, where HP is rolled with physical dice
|
|
spellIds: z.array(z.string()).max(50).default([]), // spells newly granted
|
|
});
|
|
|
|
router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
|
try {
|
|
const parsed = levelUpSchema.safeParse(req.body);
|
|
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
|
const { subclass, boon, weaponId, spellIds } = parsed.data;
|
|
const character = await loadFullCharacter(req.character.id);
|
|
if (!canLevelUp(req, res, character)) return;
|
|
|
|
const planned = planFor(req, res, character, parsed.data.characterClass || null);
|
|
if (!planned) return;
|
|
const { plan } = planned;
|
|
if (plan.subclass && !subclass) return res.status(400).json({ error: `Level ${plan.toLevel} needs a subclass: pick one.` });
|
|
if (!plan.subclass && subclass) return res.status(400).json({ error: `There is no subclass to pick at level ${plan.toLevel}.` });
|
|
if (subclass && !plan.subclass.options.some((option) => option.key === subclass)) {
|
|
return res.status(400).json({ error: 'That is not a subclass of this character\'s class.' });
|
|
}
|
|
if (plan.boon && !boon) return res.status(400).json({ error: `Level ${plan.toLevel} grants a Boon: pick one.` });
|
|
if (!plan.boon && boon) return res.status(400).json({ error: `Level ${plan.toLevel} does not grant a Boon.` });
|
|
if (weaponId && !plan.weapons.some((w) => w.weaponId === weaponId)) {
|
|
return res.status(400).json({ error: 'That weapon cannot take the free upgrade: it has to be one this character holds, of standard growth, below their new level.' });
|
|
}
|
|
const spellsFound = await prisma.spell.count({ where: { id: { in: spellIds }, campaignId: character.campaignId } });
|
|
if (new Set(spellIds).size !== spellIds.length || spellsFound !== spellIds.length) {
|
|
return res.status(400).json({ error: "Pick the new spells from this campaign's spell list, each once." });
|
|
}
|
|
// The DM grants what they like; a player picks within what the level allows.
|
|
if (!req.isDM && spellIds.length > 0) {
|
|
const allowed = plan.spells ? plan.spells.newSpells + plan.spells.newCantrips : 0;
|
|
const inReach = plan.spells ? await prisma.spell.count({ where: { id: { in: spellIds }, level: { lte: plan.spells.maxSpellLevel } } }) : 0;
|
|
if (spellIds.length > allowed || inReach !== spellIds.length) {
|
|
return res.status(400).json({ error: allowed > 0 ? `This level allows ${allowed} new spell${allowed === 1 ? '' : 's'}, of a level you can cast.` : 'This level grants no new spell.' });
|
|
}
|
|
}
|
|
|
|
// The subclass picked, or the one taken for them where the campaign has no choosing.
|
|
const newSubclass = subclass || plan.subclassTaken || null;
|
|
const first = plan.characterClass === character.characterClass;
|
|
const heldSubclass = (classLevels(character).find((e) => e.characterClass === plan.characterClass) || {}).subclass || null;
|
|
let gained;
|
|
try {
|
|
gained = advanceIn(character.specialAbilities, plan, boon, newSubclass ? { key: newSubclass, chosen: true } : { key: heldSubclass });
|
|
} catch (err) {
|
|
if (!(err instanceof LevelUpError)) throw err;
|
|
return res.status(400).json({ error: err.message });
|
|
}
|
|
const armorBonus = clamp(character.armorBonus + gained.armorBonus, -30, 30);
|
|
// Rolled hit points: the die is rolled here, or typed in from the table.
|
|
const hp = hpGain(character, plan);
|
|
let hpRolled = null;
|
|
if (hp.method === 'ROLL') {
|
|
if (hp.physical) {
|
|
if (!validateManualRoll(hp.die, parsed.data.hpRoll)) {
|
|
return res.status(400).json({ error: `Roll a d${hp.die} for hit points and enter what it shows (1 to ${hp.die}).` });
|
|
}
|
|
hpRolled = parsed.data.hpRoll;
|
|
} else {
|
|
hpRolled = rollDie(hp.die);
|
|
}
|
|
}
|
|
const hpRollAdjust = character.hpRollAdjust + (hpRolled == null ? 0 : hpRolled - hp.average);
|
|
const maxHp = sheetOf({ ...withLevelIn(character, plan.characterClass, newSubclass || undefined), armorBonus, hpRollAdjust }).hp.max;
|
|
|
|
await prisma.$transaction(async (tx) => {
|
|
if (weaponId) {
|
|
await tx.characterWeapon.update({
|
|
where: { characterId_weaponId: { characterId: character.id, weaponId } },
|
|
data: { level: { increment: 1 } },
|
|
});
|
|
}
|
|
await tx.characterSpell.createMany({ data: spellIds.map((spellId) => ({ characterId: character.id, spellId })), skipDuplicates: true });
|
|
// A level in another class goes on that class's row.
|
|
if (!first) {
|
|
await tx.characterClassLevel.upsert({
|
|
where: { characterId_characterClass: { characterId: character.id, characterClass: plan.characterClass } },
|
|
create: { characterId: character.id, characterClass: plan.characterClass, level: 1, subclass: newSubclass },
|
|
update: { level: plan.classLevel, ...(newSubclass ? { subclass: newSubclass } : {}) },
|
|
});
|
|
}
|
|
await tx.character.update({
|
|
where: { id: character.id },
|
|
data: {
|
|
level: plan.toLevel,
|
|
hpRollAdjust,
|
|
// An approved level is now taken.
|
|
levelUpsPending: Math.max(0, character.levelUpsPending - 1),
|
|
...(first && newSubclass ? { subclass: newSubclass } : {}),
|
|
specialAbilities: gained.specialAbilities,
|
|
armorBonus,
|
|
tempHp: Math.max(character.tempHp, gained.tempHp),
|
|
spellSlotsUsed: [],
|
|
// The new maximum, and healed to it. Levelling does not raise the dead.
|
|
...(lifeState(character) === 'DEAD' ? {} : { currentHp: maxHp, ...NO_DEATH_SAVES }),
|
|
},
|
|
});
|
|
});
|
|
|
|
const full = await loadFullCharacter(character.id);
|
|
emitCharacterUpdated(req);
|
|
// hpRolled: what the hit die showed, where HP is rolled (null otherwise).
|
|
res.json({ character: serializeCharacter(full, req.isOwner, req.isDM), hpRolled });
|
|
} 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,
|
|
subclass: source.subclass,
|
|
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,
|
|
speciesBonusChoices: source.speciesBonusChoices,
|
|
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',
|
|
classLevels: {
|
|
create: (source.classLevels || []).map(({ characterClass, level, subclass }) => ({ characterClass, level, subclass })),
|
|
},
|
|
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 (effectiveDiceMode(character.campaign, character) !== '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) {
|
|
// The standard array is not rolled at all: the same six scores for everyone.
|
|
if (character.campaign.abilityScoreMethod === 'STANDARD_ARRAY') {
|
|
return STANDARD_ARRAY.map((total) => ({ dice: [], dropped: null, total }));
|
|
}
|
|
if (effectiveDiceMode(character.campaign, character) !== '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() });
|
|
|
|
if (req.campaign.diceMode !== 'BOTH') {
|
|
return res.status(400).json({ error: `This campaign plays with ${req.campaign.diceMode === 'PHYSICAL' ? 'physical' : 'digital'} dice only.` });
|
|
}
|
|
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, SPECIES_ROLL_DIE);
|
|
buildState.speciesRoll = roll;
|
|
buildState.speciesChoices = speciesChoicesForRoll(roll);
|
|
} else if (stage === 'ROLLING_CLASS') {
|
|
// A 7 may be rerolled once (a build from before kept a bare "reroll").
|
|
const previous = buildState.classChoices;
|
|
const mayReroll = previous && (previous.canReroll || previous.type === 'reroll');
|
|
if (previous && !mayReroll) {
|
|
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, CLASS_ROLL_DIE);
|
|
buildState.classRoll = roll;
|
|
buildState.classChoices = classChoicesForRoll(roll, { rerolled: Boolean(mayReroll) });
|
|
delete buildState.characterClass;
|
|
} else if (stage === 'CHOOSING_SUBCLASS') {
|
|
// A die with a face per subclass suggests one; the player still picks freely.
|
|
if (buildState.subclassRoll) {
|
|
return res.status(400).json({ error: 'The subclass die was already rolled — pick from the list.' });
|
|
}
|
|
const options = subclassesOf(buildState.characterClass);
|
|
const roll = resolveSingleRoll(character, req.body, options.length);
|
|
buildState.subclassRoll = roll;
|
|
buildState.subclassSuggestion = options[roll - 1].key;
|
|
} else if (stage === 'ASSIGNING_SCORES') {
|
|
if (buildState.abilityRolls) {
|
|
return res.status(400).json({ error: 'Ability scores were already rolled for this character.' });
|
|
}
|
|
if (req.campaign.abilityScoreMethod === 'POINT_BUY') {
|
|
return res.status(400).json({ error: 'This campaign uses point buy: nothing is rolled, the scores are bought.' });
|
|
}
|
|
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 chooseSchemas = {
|
|
// `bonusChoices` are the species' flexible bonuses, { ability: amount }.
|
|
// `halfElfBonusAbilities` is the older way to give a Half-Elf's two +1s.
|
|
ROLLING_SPECIES: z.object({
|
|
species: z.string(),
|
|
bonusChoices: z.partialRecord(z.enum(ABILITIES), z.number().int().min(0).max(2)).optional(),
|
|
halfElfBonusAbilities: z.array(z.enum(ABILITIES)).length(2).optional(),
|
|
}),
|
|
ROLLING_CLASS: z.object({ characterClass: z.string() }),
|
|
// null: decide later, at the level the class chooses.
|
|
CHOOSING_SUBCLASS: z.object({ subclass: z.string().nullable() }),
|
|
// 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() }),
|
|
// Rolled scores (and the standard array) are assigned by index; point buy
|
|
// sends the six scores themselves.
|
|
ASSIGNING_SCORES: z.object({
|
|
pointBuy: z.record(z.enum(ABILITIES), z.number().int().min(8).max(15)).optional(),
|
|
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),
|
|
})
|
|
.optional(),
|
|
}),
|
|
// 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.string(), z.array(z.string())) }),
|
|
CHOOSING_APPEARANCE: z.object({ picks: z.record(z.string(), 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',
|
|
'CHOOSING_SUBCLASS',
|
|
'ROLLING_MOTIVATION',
|
|
'ASSIGNING_SCORES',
|
|
'ASSIGNING_PROFICIENCIES',
|
|
'CHOOSING_ABILITIES',
|
|
'CHOOSING_BACKGROUND',
|
|
'CHOOSING_APPEARANCE',
|
|
'CHOOSING_EQUIPMENT',
|
|
'COMPLETE',
|
|
];
|
|
|
|
// Steps a campaign can leave out: the subclass (without subclasses) and the
|
|
// motivation (when it skips it).
|
|
function stageSkipped(stage, campaign) {
|
|
if (stage === 'CHOOSING_SUBCLASS') return !campaign.subclassesEnabled;
|
|
if (stage === 'ROLLING_MOTIVATION') return campaign.skipMotivationRoll;
|
|
return false;
|
|
}
|
|
|
|
// The next (or, with step -1, the previous) step this campaign uses.
|
|
function nextStage(current, campaign, step = 1) {
|
|
let idx = STAGE_ORDER.indexOf(current) + step;
|
|
while (campaign && STAGE_ORDER[idx] && stageSkipped(STAGE_ORDER[idx], campaign)) idx += step;
|
|
return STAGE_ORDER[idx];
|
|
}
|
|
|
|
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, req.campaign);
|
|
|
|
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.` });
|
|
}
|
|
let bonusChoices = parsed.data.bonusChoices || {};
|
|
if (halfElfBonusAbilities) {
|
|
if (new Set(halfElfBonusAbilities).size !== 2) {
|
|
return res.status(400).json({ error: 'The two Half-Elf bonus abilities must be different.' });
|
|
}
|
|
bonusChoices = Object.fromEntries(halfElfBonusAbilities.map((ability) => [ability, 1]));
|
|
}
|
|
bonusChoices = Object.fromEntries(Object.entries(bonusChoices).filter(([, amount]) => amount));
|
|
const problem = speciesBonusProblem(species, bonusChoices);
|
|
if (problem) return res.status(400).json({ error: problem });
|
|
delete buildState.halfElfBonusAbilities;
|
|
buildState.speciesBonusChoices = bonusChoices;
|
|
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.` });
|
|
}
|
|
// A subclass picked for another class goes with it.
|
|
if (buildState.characterClass !== characterClass) {
|
|
delete buildState.subclass;
|
|
delete buildState.subclassRoll;
|
|
delete buildState.subclassSuggestion;
|
|
}
|
|
buildState.characterClass = characterClass;
|
|
if (req.campaign.skipMotivationRoll) buildState.motivationText = null;
|
|
} else if (stage === 'CHOOSING_SUBCLASS') {
|
|
const { subclass } = parsed.data;
|
|
if (subclass !== null && !findSubclass(buildState.characterClass, subclass)) {
|
|
return res.status(400).json({ error: 'That is not a subclass of this class.' });
|
|
}
|
|
buildState.subclass = subclass;
|
|
} 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') {
|
|
let { assignments } = parsed.data;
|
|
if (req.campaign.abilityScoreMethod === 'POINT_BUY') {
|
|
const scores = parsed.data.pointBuy;
|
|
if (!scores || ABILITIES.some((ability) => scores[ability] === undefined)) {
|
|
return res.status(400).json({ error: 'Buy a score for each of the six abilities.' });
|
|
}
|
|
const cost = pointBuyCost(scores);
|
|
if (cost === null || cost > POINT_BUY_BUDGET) {
|
|
return res.status(400).json({ error: `Those scores cost ${cost} points; you have ${POINT_BUY_BUDGET}.` });
|
|
}
|
|
// Kept the way rolled scores are, each assigned to its own ability.
|
|
buildState.abilityRolls = ABILITIES.map((ability) => ({ dice: [], dropped: null, total: scores[ability] }));
|
|
buildState.pointBuy = scores;
|
|
assignments = Object.fromEntries(ABILITIES.map((ability, i) => [ability, i]));
|
|
}
|
|
if (!buildState.abilityRolls) return res.status(400).json({ error: 'Roll ability scores first.' });
|
|
if (!assignments) return res.status(400).json({ error: 'Assign each score to an ability.' });
|
|
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 = nextStage(stage, req.campaign, -1);
|
|
}
|
|
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;
|
|
}
|
|
|
|
// A build begun before chosen bonuses were general kept a Half-Elf's two picks on their own.
|
|
const speciesBonusChoices =
|
|
bs.speciesBonusChoices || Object.fromEntries((bs.halfElfBonusAbilities || []).map((ability) => [ability, 1]));
|
|
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,
|
|
// Chosen now, its gifts still come at the level the class chooses at.
|
|
subclass: req.campaign.subclassesEnabled && findSubclass(bs.characterClass, bs.subclass) ? bs.subclass : null,
|
|
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,
|
|
speciesBonusChoices,
|
|
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].sort(bySpellLevel).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,
|
|
subclassName: usesSubclasses(character) ? subclassName(character.characterClass, character.subclass) : null,
|
|
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,
|
|
spellSlots: sheet.spellSlots,
|
|
hitDice: sheet.hitDice,
|
|
resources: sheet.resources,
|
|
inspiration: character.inspiration,
|
|
exhaustion: character.exhaustion,
|
|
conditions: character.conditions,
|
|
passivePerception: sheet.passivePerception,
|
|
passiveInvestigation: sheet.passiveInvestigation,
|
|
passiveInsight: sheet.passiveInsight,
|
|
abilities: sheet.abilities,
|
|
saves: sheet.saves,
|
|
skills: sheet.skills,
|
|
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;
|
|
}
|
|
|
|
// A weapon is not swapped in the middle of a fight. For a character in a
|
|
// battle that is under way, the weapon in hand changes only as the battle
|
|
// begins (before anyone has made a move) or on their own turn once their
|
|
// attack has landed, before the turn passes (game/combat.js, weaponSwapOpen).
|
|
// Returns what to tell the player when it is not one of those moments. The
|
|
// DM is not held to it: they referee, and put mistakes right.
|
|
async function weaponSwapWait(character) {
|
|
const rows = await prisma.encounterParticipant.findMany({
|
|
where: { characterId: character.id, encounter: { status: 'ACTIVE', mode: 'BATTLE', archivedAt: null } },
|
|
include: { encounter: true },
|
|
});
|
|
for (const row of rows) {
|
|
const { encounter } = row;
|
|
const participants = await prisma.encounterParticipant.findMany({
|
|
where: { encounterId: encounter.id },
|
|
include: { character: { select: { currentHp: true, deathSaveFailures: true, stable: true } } },
|
|
});
|
|
const first = inTurnOrder(participants).find((p) => !isFallen(p));
|
|
// What has landed, and whether an attack somebody declared is still being
|
|
// resolved (one the server lined up for a monster is not a move yet).
|
|
const actions = await prisma.encounterAction.findMany({
|
|
where: { encounterId: encounter.id, status: { in: ['APPLIED', 'PENDING'] } },
|
|
select: { round: true, actorParticipantId: true, status: true, auto: true },
|
|
});
|
|
const applied = actions.filter((a) => a.status === 'APPLIED');
|
|
const open = weaponSwapOpen({
|
|
round: encounter.currentRound,
|
|
activeId: encounter.activeParticipantId,
|
|
firstId: first ? first.id : null,
|
|
participantId: row.id,
|
|
applied,
|
|
declared: actions.some((a) => a.status === 'PENDING' && !a.auto),
|
|
});
|
|
if (!open) {
|
|
return `${character.name} is in a battle (${encounter.name}). A weapon can be changed as the battle begins, before anyone has made a move, or on ${character.name}'s own turn once their attack has landed. The DM can change it at any time.`;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
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 });
|
|
}
|
|
// Drawing or putting away a weapon in a battle waits for the right moment.
|
|
if (gear.pool === 'weapon' && !req.isDM && parsed.data.equipped !== undefined && parsed.data.equipped !== existing.equipped) {
|
|
const wait = await weaponSwapWait(req.character);
|
|
if (wait) return res.status(400).json({ error: wait });
|
|
}
|
|
|
|
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;
|