V1.25.0: the DM approves a level, each player takes their own

- "Level up..." beside Rest approves a level for any of the party at once;
  with XP tracked, those who have the XP start ticked
- Each player is told with a notice and picks for themselves in the checklist:
  class (multiclass), subclass, Boon, spells within the level's allowance,
  the weapon upgrade; a waiting level shows on the sheet and campaign page
- The DM sees who still has picks to make, and can finish or take back any
- Hit points on a level up can be rolled (campaign setting): by the site, or
  at the table and typed in with physical dice
- Toasts: notices that slide in over any page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 08:30:31 +02:00
co-authored by Claude Opus 5.5
parent 86ef106969
commit c3f2b0dfa7
24 changed files with 782 additions and 66 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "backend",
"version": "1.24.0",
"version": "1.25.0",
"private": true,
"type": "commonjs",
"main": "src/index.js",
@@ -0,0 +1,5 @@
-- Level-ups the DM approves for players to take, and rolled HP on a level up.
-- AlterTable
ALTER TABLE "characters" ADD COLUMN "hpRollAdjust" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN "levelUpsPending" INTEGER NOT NULL DEFAULT 0;
+7
View File
@@ -357,6 +357,13 @@ model Character {
// until the class reaches the level it chooses at.
subclass String?
level Int @default(1)
// Levels the DM has approved that the character has not yet taken: each is
// one level-up checklist waiting for its picks. The player resolves them
// (or the DM does), one at a time.
levelUpsPending Int @default(0)
// Where the campaign rolls HP on a level up: how far the rolls so far are
// from the average they replace, in all (a 2 on a d8 is -3). Added to max HP.
hpRollAdjust Int @default(0)
xp Int @default(0)
motivation String?
+6 -1
View File
@@ -325,6 +325,7 @@ function computeCharacterSheet(character, skillProficiencies = [], saveProficien
speedOverride = null,
spellSlotsUsed = [],
hitDiceUsed = 0,
hpRollAdjust = 0,
} = character;
const rolled = { STR: strScore, DEX: dexScore, CON: conScore, INT: intScore, WIS: wisScore, CHA: chaScore };
@@ -389,7 +390,11 @@ function computeCharacterSheet(character, skillProficiencies = [], saveProficien
initiative: initiative(abilities.DEX.modifier) + fromGear('INITIATIVE'),
speed: Math.max(0, effectiveSpeed(species, speedOverride) + fromGear('SPEED')),
hp: {
max: Math.max(1, (multi ? multiclass.multiclassHpMax(classes, abilities.CON.modifier) : hpMax(level, hitDieSize, abilities.CON.modifier)) + fromGear('MAX_HP')),
// hpRollAdjust: how far HP rolled on level-ups is from the average counted here.
max: Math.max(
1,
(multi ? multiclass.multiclassHpMax(classes, abilities.CON.modifier) : hpMax(level, hitDieSize, abilities.CON.modifier)) + (Number(hpRollAdjust) || 0) + fromGear('MAX_HP')
),
},
hitDice: multi ? multiclass.multiclassHitDice(classes, hitDiceUsed) : hitDiceState(characterClass, level, hitDiceUsed),
saves,
@@ -3694,3 +3694,97 @@ describe('multiclassing', () => {
expect(res.body.paths.map((p) => p.key)).toContain('SORLOCK');
});
});
describe('approved level-ups', () => {
itIfDb('the DM approves for many at once; each player then takes their own level, once', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('approve');
const ariaId = await buildAs(campaign.id, playerAuth, 'Aria', 'FIGHTER', 1);
const boId = await buildAs(campaign.id, dmAuth, 'Bo', 'WIZARD', 1);
const approve = (auth, body) => request(app).post(`/campaigns/${campaign.id}/level-up`).set(auth).send(body);
const levelUp = (id, auth, body = {}) => request(app).post(`/characters/${id}/level-up`).set(auth).send(body);
// Not the player's to take until it is approved, and not theirs to approve.
expect((await request(app).get(`/characters/${ariaId}/level-up`).set(playerAuth)).status).toBe(403);
expect((await levelUp(ariaId, playerAuth)).status).toBe(403);
expect((await approve(playerAuth, { characterIds: [ariaId] })).status).toBe(403);
const approved = await approve(dmAuth, { characterIds: [ariaId, boId] });
expect(approved.status).toBe(200);
expect(approved.body.results.map((r) => [r.name, r.levelUpsPending, r.skipped])).toEqual([['Aria', 1, null], ['Bo', 1, null]]);
const listed = (await request(app).get(`/campaigns/${campaign.id}/characters`).set(playerAuth)).body.characters;
expect(listed.find((c) => c.id === ariaId).levelUpsPending).toBe(1);
// The player sees the plan and takes the level; a second try has nothing approved.
const plan = await request(app).get(`/characters/${ariaId}/level-up`).set(playerAuth);
expect(plan.status).toBe(200);
expect(plan.body.plan).toMatchObject({ toLevel: 2, hp: { method: 'AVERAGE', die: 10, average: 6 } });
const taken = await levelUp(ariaId, playerAuth);
expect(taken.status).toBe(200);
expect(taken.body.character).toMatchObject({ level: 2, levelUpsPending: 0 });
expect(taken.body.hpRolled).toBeNull();
expect((await levelUp(ariaId, playerAuth)).status).toBe(403);
// Bo is the DM's own character; another player cannot take that level.
expect((await levelUp(boId, playerAuth)).status).toBe(403);
// An approval can be taken back, and stops at the top level.
const revoked = await approve(dmAuth, { characterIds: [boId, ariaId], revoke: true });
expect(revoked.body.results.find((r) => r.name === 'Bo')).toMatchObject({ levelUpsPending: 0, skipped: null });
expect(revoked.body.results.find((r) => r.name === 'Aria').skipped).toMatch(/no level up waiting/);
await prisma.character.update({ where: { id: boId }, data: { level: 20 } });
expect((await approve(dmAuth, { characterIds: [boId] })).body.results[0].skipped).toMatch(/level 20/);
});
itIfDb('an approved level is no longer shown as due', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('approvedue');
const id = await buildAs(campaign.id, playerAuth, 'Aria', 'FIGHTER', 1);
await request(app).patch(`/characters/${id}`).set(dmAuth).send({ xp: 300 });
const read = async () => (await request(app).get(`/characters/${id}`).set(playerAuth)).body.character;
expect((await read()).xpProgress.levelUpDue).toBe(true);
await request(app).post(`/campaigns/${campaign.id}/level-up`).set(dmAuth).send({ characterIds: [id] });
expect(await read()).toMatchObject({ levelUpsPending: 1, xpProgress: { levelUpDue: false } });
});
itIfDb('where the campaign rolls hit points, the die is rolled here or typed in from the table', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('hproll');
const id = await buildAs(campaign.id, playerAuth, 'Aria', 'FIGHTER', 1);
await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ hpOnLevelUp: 'ROLL', diceMode: 'PHYSICAL' });
const before = (await request(app).get(`/characters/${id}`).set(dmAuth)).body.character.sheet.hp.max;
const levelUp = (body) => request(app).post(`/characters/${id}/level-up`).set(dmAuth).send(body);
expect((await request(app).get(`/characters/${id}/level-up`).set(dmAuth)).body.plan.hp).toEqual({ method: 'ROLL', die: 10, average: 6, physical: true });
expect((await levelUp({})).status).toBe(400); // the roll has to be entered
expect((await levelUp({ hpRoll: 11 })).status).toBe(400); // not on a d10
const low = await levelUp({ hpRoll: 2 });
expect(low.body.hpRolled).toBe(2);
// +2 from the die and +2 Constitution (CON 14), where the average would have given 6 + 2.
expect(low.body.character.sheet.hp.max).toBe(before + 2 + 2);
// Digital dice: the server rolls, and the sheet follows whatever came up.
await request(app).patch(`/campaigns/${campaign.id}`).set(dmAuth).send({ diceMode: 'DIGITAL' });
const rolled = await levelUp({ hpRoll: 10, subclass: 'CHAMPION' }); // a typed value is ignored
expect(rolled.body.hpRolled).toBeGreaterThanOrEqual(1);
expect(rolled.body.hpRolled).toBeLessThanOrEqual(10);
expect(rolled.body.character.sheet.hp.max).toBe(before + 4 + rolled.body.hpRolled + 2);
});
});
describe('a player picking spells on a level up', () => {
itIfDb('is offered the campaign spells they can cast, and held to the level’s allowance', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('playerspells');
const id = await buildAs(campaign.id, playerAuth, 'Mira', 'WIZARD', 1);
const spell = async (name, level) => (await request(app).post(`/campaigns/${campaign.id}/spells`).set(dmAuth).send({ name, level })).body.spell.id;
const [a, b, c, high] = [await spell('Alarm', 1), await spell('Shield', 1), await spell('Sleep', 1), await spell('Fireball', 3)];
await request(app).post(`/campaigns/${campaign.id}/level-up`).set(dmAuth).send({ characterIds: [id] });
const plan = (await request(app).get(`/characters/${id}/level-up`).set(playerAuth)).body.plan;
expect(plan.spells).toMatchObject({ newSpells: 2, maxSpellLevel: 1 });
expect(plan.spellOptions.map((s) => s.name)).toEqual(['Alarm', 'Shield', 'Sleep']); // not Fireball: too high
const levelUp = (spellIds) => request(app).post(`/characters/${id}/level-up`).set(playerAuth).send({ subclass: 'EVOCATION', spellIds });
expect((await levelUp([a, b, c])).status).toBe(400); // one too many
expect((await levelUp([a, high])).status).toBe(400); // out of reach
const done = await levelUp([a, b]);
expect(done.status).toBe(200);
expect(done.body.character.spells.map((s) => s.spell.name).sort()).toEqual(['Alarm', 'Shield']);
});
});
+59 -1
View File
@@ -255,6 +255,7 @@ function characterSummary(character, subclasses = true) {
characterClass: character.characterClass,
subclassName: subclasses ? subclassName(character.characterClass, character.subclass) : null,
level: character.level,
levelUpsPending: character.levelUpsPending,
// Every class it has levels in; one entry unless it has multiclassed.
classes: classLevels(character).map((entry) => ({
characterClass: entry.characterClass,
@@ -262,7 +263,8 @@ function characterSummary(character, subclasses = true) {
subclassName: subclasses ? subclassName(entry.characterClass, entry.subclass) : null,
})),
xp: character.xp,
xpProgress: xpProgress(character.xp, character.level),
// A level already approved is no longer due.
xpProgress: xpProgress(character.xp, Math.min(MAX_LEVEL, character.level + character.levelUpsPending)),
buildStage: character.buildStage,
currentHp: character.currentHp,
tempHp: character.tempHp,
@@ -369,6 +371,62 @@ router.post('/:id/characters', requireCampaignMember(), async (req, res, next) =
}
});
// ---------------------------------------------------------------------------
// Level-ups — the DM approves a level for any of the party at once. Each
// approval is a checklist waiting (Character.levelUpsPending): the
// character's player is told and makes their own picks (POST
// /characters/:id/level-up), so five players levelling together do not queue
// for the DM. A character with no player is the DM's to finish.
// ---------------------------------------------------------------------------
const approveLevelUpSchema = z.object({
characterIds: z.array(z.string()).min(1).max(200),
// Takes an approval back (one not yet used) instead of giving one.
revoke: z.boolean().default(false),
});
router.post('/:id/level-up', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = approveLevelUpSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { revoke } = parsed.data;
const ids = [...new Set(parsed.data.characterIds)];
const characters = await prisma.character.findMany({
where: { id: { in: ids }, campaignId: req.campaign.id, buildStage: 'COMPLETE' },
orderBy: { createdAt: 'asc' },
});
if (characters.length !== ids.length) return res.status(400).json({ error: 'Pick finished characters from this campaign.' });
const results = characters.map((character) => {
const who = { characterId: character.id, name: character.name, userId: character.userId, level: character.level };
if (revoke) {
return character.levelUpsPending > 0
? { ...who, levelUpsPending: character.levelUpsPending - 1, skipped: null }
: { ...who, levelUpsPending: 0, skipped: `${character.name} has no level up waiting.` };
}
if (character.level + character.levelUpsPending >= MAX_LEVEL) {
return { ...who, levelUpsPending: character.levelUpsPending, skipped: `${character.name} is already at (or approved up to) level ${MAX_LEVEL}.` };
}
return { ...who, levelUpsPending: character.levelUpsPending + 1, skipped: null };
});
const changed = results.filter((result) => !result.skipped);
await prisma.$transaction(
changed.map((result) => prisma.character.update({ where: { id: result.characterId }, data: { levelUpsPending: result.levelUpsPending } }))
);
const io = req.app.get('io');
for (const { characterId, userId } of changed) {
io.to(`campaign:${req.campaign.id}`).emit('character:updated', { characterId });
// Tells the character's player there is a level to take (ids only).
if (!revoke) io.to(`campaign:${req.campaign.id}`).emit('character:level-up-granted', { characterId, userId });
}
res.json({ revoke, results });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Rests — the DM rests any of the party at once (utils/rest.js)
// ---------------------------------------------------------------------------
+65 -8
View File
@@ -8,6 +8,7 @@ const {
computeCharacterSheet,
computeWeaponStats,
getClassSaveProficiencies,
getClassHitDieSize,
getClassSpellcastingAbility,
scaledDamageDice,
canUseGear,
@@ -65,7 +66,7 @@ async function loadFullCharacter(id) {
spells: { include: { spell: true } },
currentLocation: true,
classLevels: true,
campaign: { select: { subclassesEnabled: true, multiclassEnabled: true, diceMode: true } },
campaign: { select: { subclassesEnabled: true, multiclassEnabled: true, diceMode: true, hpOnLevelUp: true } },
},
});
}
@@ -103,6 +104,8 @@ function serializeCharacter(character, isOwner, isDM = true) {
// 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) => ({
@@ -112,7 +115,8 @@ function serializeCharacter(character, isOwner, isDM = true) {
subclassName: subclasses ? subclassName(entry.characterClass, entry.subclass) : null,
})),
xp: character.xp,
xpProgress: xpProgress(character.xp, character.level),
// 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: {
@@ -549,11 +553,14 @@ router.post('/:id/resources', requireCharacterAccess({ write: true }), async (re
// and the free weapon upgrade.
// ---------------------------------------------------------------------------
// Answers the request and returns false when this character cannot be levelled up.
// 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) refusal = [403, 'Only the DM can level a character up.'];
else if (character.buildStage !== 'COMPLETE') refusal = [400, 'Character build is not finished yet.'];
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;
@@ -586,6 +593,19 @@ function planFor(req, res, character, toClass) {
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) => {
@@ -596,7 +616,17 @@ router.get('/:id/level-up', requireCharacterAccess(), async (req, res, next) =>
if (!planned) return;
const { plan, sheet } = planned;
const after = sheetOf({ ...withLevelIn(character, plan.characterClass), spellSlotsUsed: [] });
res.json({ plan: { ...plan, maxHp: { from: sheet.hp.max, to: after.hp.max }, spellSlots: after.spellSlots } });
// 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);
}
@@ -607,6 +637,7 @@ const levelUpSchema = z.object({
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
});
@@ -635,6 +666,14 @@ router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req
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;
@@ -648,7 +687,21 @@ router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req
return res.status(400).json({ error: err.message });
}
const armorBonus = clamp(character.armorBonus + gained.armorBonus, -30, 30);
const maxHp = sheetOf({ ...withLevelIn(character, plan.characterClass, newSubclass || undefined), armorBonus }).hp.max;
// 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) {
@@ -670,6 +723,9 @@ router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req
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,
@@ -683,7 +739,8 @@ router.post('/:id/level-up', requireCharacterAccess({ write: true }), async (req
const full = await loadFullCharacter(character.id);
emitCharacterUpdated(req);
res.json({ character: serializeCharacter(full, req.isOwner) });
// 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);
}