V1.1.0: gear levels, encounter overhaul, guided builder, trading, docs
Characters - Builder: pick-then-Next on every step with live preview, Back button, plain-language help throughout, and "Suggest for me" for ability scores - Motivation is picked from a list; new steps for special abilities, background and appearance, all composed from fixed lists and DM-only to edit afterwards - Copy a character to another campaign - Characters can give gold, weapons, items and spells to each other - Money tracker: gold only changes through a logged ledger - Fixes: level/XP/location are DM-only, HP stays within 0..max, physical dice ability rolls, every die is rolled once Gear - DM-managed item pool; weapons, items and spells are handed out by the DM - Starting-option flag per pool entry - Gear levels 1-9 per held copy with a damage ladder, growth rate and starting level; spells gated by spell level with a fixed damage value - Spell library carries default damage; damage is picked from a list Encounters - Battle and NPC quest modes, turn tracking, scene description, DM notes - NPCs, richer combatant cards, conditions from a list - Rewards (gold, weapons, items) lined up and awarded, with gold splitting - Character HP is shared between the sheet and the encounter - Monster stat blocks and NPC secrets are never sent to players Other - Dice roller on every page - Docs for characters, weapons, spells, items, encounters, monsters and NPCs, with full lists generated from the data (npm run docs:lists) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,7 +3,8 @@ const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
const { computeCharacterSheet, computeWeaponStats } = require('../game/calculations');
|
||||
const { computeCharacterSheet, computeWeaponStats, canUseGear, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { adjustGold, giveGear } = require('../utils/grants');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -26,30 +27,72 @@ async function requireEncounterAccess(req, res, next) {
|
||||
}
|
||||
}
|
||||
|
||||
// Every campaign member looking at an encounter can see a character
|
||||
// combatant's equipped weapons and known spells (attack/damage bonus, save
|
||||
// DC) — not just HP/AC — so the party can plan around each other mid-fight,
|
||||
// not only the DM. Uses the same calculation-engine functions the
|
||||
// quick-stats panel already uses, never re-deriving the formulas.
|
||||
function characterCombatInfo(character) {
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
const weapons = character.weapons.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
name: cw.weapon.name,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true),
|
||||
}));
|
||||
const spells = character.spells.map((cs) => ({
|
||||
characterSpellId: cs.id,
|
||||
name: cs.spell.name,
|
||||
level: cs.spell.level,
|
||||
prepared: cs.prepared,
|
||||
}));
|
||||
return { armorClass: sheet.armorClass, weapons, spells, spellcasting: sheet.spellcasting };
|
||||
function requireDM(req, res, next) {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
return next();
|
||||
}
|
||||
|
||||
async function serializeEncounter(encounterId) {
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
// Highest initiative first; ties keep the order combatants were added in.
|
||||
function inTurnOrder(participants) {
|
||||
return [...participants].sort((a, b) => b.initiative - a.initiative || (a.id < b.id ? -1 : 1));
|
||||
}
|
||||
|
||||
// What every campaign member sees about a character in an encounter: the
|
||||
// sheet's headline numbers plus the weapons and spells it can actually use —
|
||||
// so the party can plan around each other mid-fight, not only the DM. Uses the
|
||||
// same calculation-engine functions as the sheet, never re-deriving formulas.
|
||||
function characterCombatInfo(character) {
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
// Gear and spells above the character's level are held but can't be used,
|
||||
// so they stay out of the fight.
|
||||
const weapons = character.weapons
|
||||
.filter((cw) => canUseGear(character.level, cw.level))
|
||||
.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
name: cw.weapon.name,
|
||||
level: cw.level,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level),
|
||||
}));
|
||||
const spells = character.spells
|
||||
.filter((cs) => canUseGear(character.level, cs.spell.level))
|
||||
.map((cs) => ({
|
||||
characterSpellId: cs.id,
|
||||
name: cs.spell.name,
|
||||
level: cs.spell.level,
|
||||
description: cs.spell.description,
|
||||
damageDice: cs.spell.damageDice,
|
||||
prepared: cs.prepared,
|
||||
}));
|
||||
return {
|
||||
level: character.level,
|
||||
species: character.species,
|
||||
characterClass: character.characterClass,
|
||||
armorClass: sheet.armorClass,
|
||||
maxHp: sheet.hp.max,
|
||||
tempHp: character.tempHp,
|
||||
speed: sheet.speed,
|
||||
initiativeBonus: sheet.initiative,
|
||||
passivePerception: sheet.passivePerception,
|
||||
proficiencyBonus: sheet.proficiencyBonus,
|
||||
abilities: sheet.abilities,
|
||||
saves: sheet.saves,
|
||||
specialAbilities: character.specialAbilities,
|
||||
weapons,
|
||||
spells,
|
||||
spellcasting: sheet.spellcasting,
|
||||
};
|
||||
}
|
||||
|
||||
// The DM gets everything. Players get the scene as their characters see it:
|
||||
// no DM notes, no monster stat blocks, no NPC secrets or stats, and only the
|
||||
// rewards that have actually been handed out.
|
||||
async function serializeEncounter(encounterId, isDM) {
|
||||
const encounter = await prisma.encounter.findUnique({
|
||||
where: { id: encounterId },
|
||||
include: {
|
||||
@@ -63,69 +106,132 @@ async function serializeEncounter(encounterId) {
|
||||
spells: { include: { spell: true } },
|
||||
},
|
||||
},
|
||||
monster: { select: { id: true, name: true } },
|
||||
monster: true,
|
||||
npc: true,
|
||||
},
|
||||
orderBy: { initiative: 'desc' },
|
||||
},
|
||||
rewards: { include: { weapon: true, item: true }, orderBy: { createdAt: 'asc' } },
|
||||
},
|
||||
});
|
||||
if (!encounter) return encounter;
|
||||
|
||||
encounter.participants = encounter.participants.map((p) => {
|
||||
if (!p.character) return p;
|
||||
return {
|
||||
...p,
|
||||
character: { id: p.character.id, name: p.character.name },
|
||||
characterCombatInfo: characterCombatInfo(p.character),
|
||||
};
|
||||
const participants = inTurnOrder(encounter.participants).map((p) => {
|
||||
const { character, monster, npc, ...row } = p;
|
||||
const out = { ...row, kind: npc || p.npcId ? 'NPC' : p.isMonster ? 'MONSTER' : 'CHARACTER' };
|
||||
if (character) {
|
||||
// A character combatant's HP is the character's own HP, not a
|
||||
// per-encounter copy, so the tracker and the sheet can never disagree.
|
||||
const { maxHp, ...combatInfo } = characterCombatInfo(character);
|
||||
out.currentHp = character.currentHp;
|
||||
out.maxHp = maxHp;
|
||||
out.character = { id: character.id, name: character.name };
|
||||
out.characterCombatInfo = combatInfo;
|
||||
}
|
||||
if (monster) out.monster = isDM ? monster : { id: monster.id, name: monster.name };
|
||||
if (npc) {
|
||||
const { dmNotes, ac, maxHp, attackBonus, damageDice, campaignId, createdAt, ...publicNpc } = npc;
|
||||
out.npc = isDM ? { ...publicNpc, dmNotes, ac, maxHp, attackBonus, damageDice } : publicNpc;
|
||||
}
|
||||
return out;
|
||||
});
|
||||
return encounter;
|
||||
|
||||
const { dmNotes, rewards, ...scene } = encounter;
|
||||
return {
|
||||
...scene,
|
||||
...(isDM ? { dmNotes } : {}),
|
||||
participants,
|
||||
rewards: isDM ? rewards : rewards.filter((r) => r.awardedAt),
|
||||
};
|
||||
}
|
||||
|
||||
// Every open tab refetches its own view of the encounter (the payload differs
|
||||
// between the DM and players, so it is never pushed over the shared room).
|
||||
function emitEncounterUpdated(req) {
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:participant-updated', { encounterId: req.encounter.id });
|
||||
}
|
||||
|
||||
function emitCharacterUpdated(req, characterId) {
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('character:updated', { characterId });
|
||||
}
|
||||
|
||||
async function respondWithEncounter(req, res, status = 200, extra = {}) {
|
||||
const encounter = await serializeEncounter(req.encounter.id, req.isDM);
|
||||
emitEncounterUpdated(req);
|
||||
res.status(status).json({ ...extra, encounter });
|
||||
}
|
||||
|
||||
router.get('/:id', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
const encounter = await serializeEncounter(req.encounter.id);
|
||||
res.json({ encounter });
|
||||
res.json({ encounter: await serializeEncounter(req.encounter.id, req.isDM) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const patchEncounterSchema = z.object({
|
||||
status: z.enum(['PLANNING', 'ACTIVE', 'COMPLETE']).optional(),
|
||||
mode: z.enum(['BATTLE', 'QUEST']).optional(),
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
description: z.string().max(4000).nullable().optional(),
|
||||
dmNotes: z.string().max(4000).nullable().optional(),
|
||||
});
|
||||
|
||||
router.patch('/:id', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = patchEncounterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const data = { ...parsed.data };
|
||||
|
||||
// Starting a battle puts the first combatant in the initiative order on turn.
|
||||
const mode = data.mode ?? req.encounter.mode;
|
||||
if (data.status === 'ACTIVE' && mode === 'BATTLE' && !req.encounter.activeParticipantId) {
|
||||
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id } });
|
||||
data.activeParticipantId = inTurnOrder(participants)[0]?.id ?? null;
|
||||
}
|
||||
|
||||
await prisma.encounter.update({ where: { id: req.encounter.id }, data });
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combatants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const participantSchema = z
|
||||
.object({
|
||||
characterId: z.string().optional(),
|
||||
monsterId: z.string().optional(),
|
||||
npcId: z.string().optional(),
|
||||
displayName: z.string().min(1).max(80).optional(),
|
||||
initiative: z.number().int().default(0),
|
||||
})
|
||||
.refine((data) => Boolean(data.characterId) !== Boolean(data.monsterId), {
|
||||
message: 'Provide exactly one of characterId or monsterId',
|
||||
.refine((data) => [data.characterId, data.monsterId, data.npcId].filter(Boolean).length === 1, {
|
||||
message: 'Provide exactly one of characterId, monsterId or npcId',
|
||||
});
|
||||
|
||||
router.post('/:id/participants', requireEncounterAccess, async (req, res, next) => {
|
||||
router.post('/:id/participants', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
const parsed = participantSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { characterId, monsterId, displayName, initiative } = parsed.data;
|
||||
const { characterId, monsterId, npcId, displayName, initiative } = parsed.data;
|
||||
|
||||
let currentHp, maxHp, resolvedName, isMonster;
|
||||
let currentHp, maxHp, resolvedName;
|
||||
|
||||
if (characterId) {
|
||||
const character = await prisma.character.findUnique({ where: { id: characterId } });
|
||||
if (!character || character.campaignId !== req.encounter.campaignId) {
|
||||
return res.status(400).json({ error: 'That character is not part of this campaign.' });
|
||||
}
|
||||
const full = await prisma.character.findUnique({
|
||||
const character = await prisma.character.findUnique({
|
||||
where: { id: characterId },
|
||||
include: { skillProficiencies: true, saveProficiencies: true },
|
||||
});
|
||||
const sheet = computeCharacterSheet(full, full.skillProficiencies, full.saveProficiencies);
|
||||
if (!character || character.campaignId !== req.encounter.campaignId) {
|
||||
return res.status(400).json({ error: 'That character is not part of this campaign.' });
|
||||
}
|
||||
currentHp = character.currentHp;
|
||||
maxHp = sheet.hp.max;
|
||||
maxHp = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies).hp.max;
|
||||
resolvedName = displayName || character.name;
|
||||
isMonster = false;
|
||||
} else {
|
||||
} else if (monsterId) {
|
||||
const monster = await prisma.monster.findUnique({ where: { id: monsterId } });
|
||||
if (!monster || monster.campaignId !== req.encounter.campaignId) {
|
||||
return res.status(400).json({ error: 'That monster is not part of this campaign.' });
|
||||
@@ -133,7 +239,15 @@ router.post('/:id/participants', requireEncounterAccess, async (req, res, next)
|
||||
currentHp = monster.maxHp;
|
||||
maxHp = monster.maxHp;
|
||||
resolvedName = displayName || monster.name;
|
||||
isMonster = true;
|
||||
} else {
|
||||
const npc = await prisma.npc.findUnique({ where: { id: npcId } });
|
||||
if (!npc || npc.campaignId !== req.encounter.campaignId) {
|
||||
return res.status(400).json({ error: 'That NPC is not part of this campaign.' });
|
||||
}
|
||||
// An NPC with no combat stats takes part with no hit points to track.
|
||||
currentHp = npc.maxHp ?? 0;
|
||||
maxHp = npc.maxHp ?? 0;
|
||||
resolvedName = displayName || npc.name;
|
||||
}
|
||||
|
||||
const participant = await prisma.encounterParticipant.create({
|
||||
@@ -141,17 +255,16 @@ router.post('/:id/participants', requireEncounterAccess, async (req, res, next)
|
||||
encounterId: req.encounter.id,
|
||||
characterId: characterId || null,
|
||||
monsterId: monsterId || null,
|
||||
npcId: npcId || null,
|
||||
displayName: resolvedName,
|
||||
initiative,
|
||||
currentHp,
|
||||
maxHp,
|
||||
isMonster,
|
||||
isMonster: Boolean(monsterId),
|
||||
},
|
||||
});
|
||||
|
||||
const encounter = await serializeEncounter(req.encounter.id);
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:participant-updated', { encounter });
|
||||
res.status(201).json({ participant, encounter });
|
||||
await respondWithEncounter(req, res, 201, { participant });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -161,65 +274,242 @@ const updateParticipantSchema = z.object({
|
||||
currentHp: z.number().int().optional(),
|
||||
maxHp: z.number().int().min(1).optional(),
|
||||
initiative: z.number().int().optional(),
|
||||
conditions: z.array(z.string()).optional(),
|
||||
conditions: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
|
||||
displayName: z.string().min(1).max(80).optional(),
|
||||
});
|
||||
|
||||
router.patch('/:id/participants/:participantId', requireEncounterAccess, async (req, res, next) => {
|
||||
router.patch('/:id/participants/:participantId', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
const parsed = updateParticipantSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const participant = await prisma.encounterParticipant.update({
|
||||
const existing = await prisma.encounterParticipant.findUnique({
|
||||
where: { id: req.params.participantId },
|
||||
data: parsed.data,
|
||||
include: { character: { include: { skillProficiencies: true, saveProficiencies: true } } },
|
||||
});
|
||||
if (!existing || existing.encounterId !== req.encounter.id) {
|
||||
return res.status(404).json({ error: 'Combatant not found in this encounter' });
|
||||
}
|
||||
|
||||
const encounter = await serializeEncounter(req.encounter.id);
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:participant-updated', { encounter });
|
||||
res.json({ participant, encounter });
|
||||
const data = { ...parsed.data };
|
||||
if (existing.character) {
|
||||
// Max HP comes from the sheet, and damage/healing lands on the character.
|
||||
const { character } = existing;
|
||||
const maxHp = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies).hp.max;
|
||||
data.maxHp = maxHp;
|
||||
if (data.currentHp !== undefined) {
|
||||
data.currentHp = clamp(data.currentHp, 0, maxHp);
|
||||
await prisma.character.update({ where: { id: character.id }, data: { currentHp: data.currentHp } });
|
||||
emitCharacterUpdated(req, character.id);
|
||||
}
|
||||
} else if (data.currentHp !== undefined) {
|
||||
data.currentHp = clamp(data.currentHp, 0, data.maxHp ?? existing.maxHp);
|
||||
} else if (data.maxHp !== undefined) {
|
||||
data.currentHp = Math.min(existing.currentHp, data.maxHp);
|
||||
}
|
||||
|
||||
const participant = await prisma.encounterParticipant.update({ where: { id: existing.id }, data });
|
||||
await respondWithEncounter(req, res, 200, { participant });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/participants/:participantId', requireEncounterAccess, async (req, res, next) => {
|
||||
router.delete('/:id/participants/:participantId', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id } });
|
||||
const order = inTurnOrder(participants);
|
||||
const index = order.findIndex((p) => p.id === req.params.participantId);
|
||||
if (index === -1) return res.status(404).json({ error: 'Combatant not found in this encounter' });
|
||||
|
||||
// Removing whoever is on turn passes the turn to the next combatant.
|
||||
if (req.encounter.activeParticipantId === req.params.participantId) {
|
||||
const next = order.length > 1 ? order[(index + 1) % order.length] : null;
|
||||
await prisma.encounter.update({ where: { id: req.encounter.id }, data: { activeParticipantId: next ? next.id : null } });
|
||||
}
|
||||
await prisma.encounterParticipant.delete({ where: { id: req.params.participantId } });
|
||||
const encounter = await serializeEncounter(req.encounter.id);
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:participant-updated', { encounter });
|
||||
res.json({ encounter });
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/advance-round', requireEncounterAccess, async (req, res, next) => {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Turns and rounds
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Passes the turn down the initiative order; going past the last combatant
|
||||
// starts the next round.
|
||||
router.post('/:id/next-turn', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id } });
|
||||
const order = inTurnOrder(participants);
|
||||
if (order.length === 0) return res.status(400).json({ error: 'Add combatants before taking turns.' });
|
||||
|
||||
const index = order.findIndex((p) => p.id === req.encounter.activeParticipantId);
|
||||
const wrapped = index === order.length - 1;
|
||||
await prisma.encounter.update({
|
||||
where: { id: req.encounter.id },
|
||||
data: {
|
||||
status: 'ACTIVE',
|
||||
activeParticipantId: order[wrapped || index === -1 ? 0 : index + 1].id,
|
||||
...(wrapped ? { currentRound: { increment: 1 } } : {}),
|
||||
},
|
||||
});
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/advance-round', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const participants = await prisma.encounterParticipant.findMany({ where: { encounterId: req.encounter.id } });
|
||||
const updated = await prisma.encounter.update({
|
||||
where: { id: req.encounter.id },
|
||||
data: { currentRound: { increment: 1 }, status: 'ACTIVE' },
|
||||
data: {
|
||||
currentRound: { increment: 1 },
|
||||
status: 'ACTIVE',
|
||||
// A new round starts back at the top of the initiative order.
|
||||
...(req.encounter.mode === 'BATTLE' ? { activeParticipantId: inTurnOrder(participants)[0]?.id ?? null } : {}),
|
||||
},
|
||||
});
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:round-advanced', {
|
||||
encounterId: updated.id,
|
||||
currentRound: updated.currentRound,
|
||||
});
|
||||
res.json({ encounter: updated });
|
||||
res.json({ encounter: await serializeEncounter(updated.id, req.isDM) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id', requireEncounterAccess, async (req, res, next) => {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rewards — loot the DM lines up, then hands to a character
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const rewardSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('GOLD'), gold: z.number().int().min(1), note: z.string().trim().max(200).optional().nullable() }),
|
||||
z.object({
|
||||
type: z.literal('WEAPON'),
|
||||
weaponId: z.string(),
|
||||
quantity: z.number().int().min(1).default(1),
|
||||
level: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
note: z.string().trim().max(200).optional().nullable(),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal('ITEM'),
|
||||
itemId: z.string(),
|
||||
quantity: z.number().int().min(1).default(1),
|
||||
level: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
note: z.string().trim().max(200).optional().nullable(),
|
||||
}),
|
||||
]);
|
||||
|
||||
router.post('/:id/rewards', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
const parsed = z.object({ status: z.enum(['PLANNING', 'ACTIVE', 'COMPLETE']).optional(), name: z.string().min(1).max(120).optional() }).safeParse(req.body);
|
||||
const parsed = rewardSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const updated = await prisma.encounter.update({ where: { id: req.encounter.id }, data: parsed.data });
|
||||
res.json({ encounter: updated });
|
||||
const data = { ...parsed.data, note: parsed.data.note || null };
|
||||
|
||||
if (data.type !== 'GOLD') {
|
||||
const pool = data.type === 'WEAPON' ? 'weapon' : 'item';
|
||||
const entry = await prisma[pool].findUnique({ where: { id: data[`${pool}Id`] } });
|
||||
if (!entry || entry.campaignId !== req.encounter.campaignId) {
|
||||
return res.status(400).json({ error: `That ${pool} is not part of this campaign.` });
|
||||
}
|
||||
data.level = data.level ?? entry.minLevel;
|
||||
if (data.level < entry.minLevel) {
|
||||
return res.status(400).json({ error: `${entry.name} starts at level ${entry.minLevel} and can't go below it.` });
|
||||
}
|
||||
}
|
||||
|
||||
const reward = await prisma.encounterReward.create({ data: { ...data, encounterId: req.encounter.id } });
|
||||
await respondWithEncounter(req, res, 201, { reward });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// Removing a reward only takes it off the list — anything already handed out
|
||||
// stays with the character.
|
||||
router.delete('/:id/rewards/:rewardId', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const { count } = await prisma.encounterReward.deleteMany({
|
||||
where: { id: req.params.rewardId, encounterId: req.encounter.id },
|
||||
});
|
||||
if (count === 0) return res.status(404).json({ error: 'Reward not found in this encounter' });
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const awardSchema = z.union([z.object({ characterId: z.string() }), z.object({ split: z.literal(true) })]);
|
||||
|
||||
// Hands a reward over, once. `characterId` gives all of it to one character;
|
||||
// `split` (gold only) shares it evenly between the characters in the
|
||||
// encounter, any remainder going one gold each down the initiative order.
|
||||
router.post('/:id/rewards/:rewardId/award', requireEncounterAccess, requireDM, async (req, res, next) => {
|
||||
try {
|
||||
const parsed = awardSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const reward = await prisma.encounterReward.findUnique({
|
||||
where: { id: req.params.rewardId },
|
||||
include: { weapon: true, item: true },
|
||||
});
|
||||
if (!reward || reward.encounterId !== req.encounter.id) {
|
||||
return res.status(404).json({ error: 'Reward not found in this encounter' });
|
||||
}
|
||||
if (reward.awardedAt) return res.status(400).json({ error: `Already awarded to ${reward.awardedTo}.` });
|
||||
|
||||
let recipients;
|
||||
if (parsed.data.split) {
|
||||
if (reward.type !== 'GOLD') return res.status(400).json({ error: 'Only gold can be split.' });
|
||||
const participants = await prisma.encounterParticipant.findMany({
|
||||
where: { encounterId: req.encounter.id, characterId: { not: null } },
|
||||
include: { character: true },
|
||||
});
|
||||
recipients = inTurnOrder(participants).map((p) => p.character);
|
||||
if (recipients.length === 0) return res.status(400).json({ error: 'There are no characters in this encounter to split it between.' });
|
||||
} else {
|
||||
const character = await prisma.character.findUnique({ where: { id: parsed.data.characterId } });
|
||||
if (!character || character.campaignId !== req.encounter.campaignId) {
|
||||
return res.status(400).json({ error: 'That character is not part of this campaign.' });
|
||||
}
|
||||
recipients = [character];
|
||||
}
|
||||
|
||||
const reason = `Reward: ${req.encounter.name}`;
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// Claim the reward first so two clicks can't hand it out twice.
|
||||
const claimed = await tx.encounterReward.updateMany({
|
||||
where: { id: reward.id, awardedAt: null },
|
||||
data: { awardedAt: new Date(), awardedTo: recipients.map((c) => c.name).join(', ') },
|
||||
});
|
||||
if (claimed.count === 0) return;
|
||||
|
||||
if (reward.type === 'GOLD') {
|
||||
const share = Math.floor(reward.gold / recipients.length);
|
||||
const remainder = reward.gold % recipients.length;
|
||||
for (const [i, character] of recipients.entries()) {
|
||||
const amount = share + (i < remainder ? 1 : 0);
|
||||
if (amount > 0) await adjustGold(tx, { characterId: character.id, amount, reason, userId: req.user.id });
|
||||
}
|
||||
} else {
|
||||
const kind = reward.type === 'WEAPON' ? 'weapon' : 'item';
|
||||
await giveGear(tx, kind, {
|
||||
characterId: recipients[0].id,
|
||||
entry: reward[kind],
|
||||
quantity: reward.quantity,
|
||||
level: reward.level,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
for (const character of recipients) emitCharacterUpdated(req, character.id);
|
||||
await respondWithEncounter(req, res);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user