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:
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCampaignMember, requireDM } = require('../middleware/campaignAccess');
|
||||
const { generateInviteCode } = require('../utils/inviteCode');
|
||||
const { computeCharacterSheet } = require('../game/calculations');
|
||||
const { computeCharacterSheet, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { WEAPON_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -167,6 +167,7 @@ function characterSummary(character) {
|
||||
buildStage: character.buildStage,
|
||||
currentHp: character.currentHp,
|
||||
tempHp: character.tempHp,
|
||||
gold: character.gold,
|
||||
maxHp: character.buildStage === 'COMPLETE' ? sheet.hp.max : null,
|
||||
armorClass: character.buildStage === 'COMPLETE' ? sheet.armorClass : null,
|
||||
currentLocationId: character.currentLocationId,
|
||||
@@ -210,6 +211,7 @@ router.post('/:id/characters', requireCampaignMember(), async (req, res, next) =
|
||||
targetUserId = parsed.data.userId;
|
||||
}
|
||||
|
||||
const startingGold = req.campaign.startingGold;
|
||||
const character = await prisma.character.create({
|
||||
data: {
|
||||
campaignId: req.campaign.id,
|
||||
@@ -217,7 +219,13 @@ router.post('/:id/characters', requireCampaignMember(), async (req, res, next) =
|
||||
createdById: req.user.id,
|
||||
name: parsed.data.name,
|
||||
buildStage: 'ROLLING_SPECIES',
|
||||
gold: req.campaign.startingGold,
|
||||
gold: startingGold,
|
||||
goldTransactions: {
|
||||
create:
|
||||
startingGold > 0
|
||||
? [{ amount: startingGold, balanceAfter: startingGold, reason: 'Starting gold', createdById: req.user.id }]
|
||||
: [],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -249,8 +257,35 @@ const weaponSchema = z.object({
|
||||
properties: z.array(z.string()).default([]),
|
||||
rangeNormal: z.number().int().positive().optional().nullable(),
|
||||
rangeLong: z.number().int().positive().optional().nullable(),
|
||||
damageScaling: z.number().int().min(1).max(MAX_DAMAGE_SCALING).optional(),
|
||||
minLevel: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
isStartingOption: z.boolean().optional(),
|
||||
});
|
||||
|
||||
// Raising a pool entry's starting level lifts every held copy that is now
|
||||
// below it. A lifted copy comes off, since its holder may no longer be high
|
||||
// enough level to use it.
|
||||
async function liftHeldCopies(heldModel, poolKey, poolId, minLevel) {
|
||||
if (minLevel === undefined) return;
|
||||
await prisma[heldModel].updateMany({
|
||||
where: { [poolKey]: poolId, level: { lt: minLevel } },
|
||||
data: { level: minLevel, equipped: false },
|
||||
});
|
||||
}
|
||||
|
||||
// Pool entries are addressed by their own id, so every edit/delete is scoped
|
||||
// to the campaign in the URL — a DM of one campaign can't reach into another.
|
||||
// Returns the updated row, or null if it isn't in this campaign.
|
||||
async function updatePoolEntry(model, id, campaignId, data) {
|
||||
const { count } = await prisma[model].updateMany({ where: { id, campaignId }, data });
|
||||
return count === 0 ? null : prisma[model].findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
async function deletePoolEntry(model, id, campaignId) {
|
||||
const { count } = await prisma[model].deleteMany({ where: { id, campaignId } });
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
router.post('/:id/weapons', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = weaponSchema.safeParse(req.body);
|
||||
@@ -266,10 +301,9 @@ router.patch('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), asy
|
||||
try {
|
||||
const parsed = weaponSchema.partial().safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const weapon = await prisma.weapon.update({
|
||||
where: { id: req.params.weaponId },
|
||||
data: parsed.data,
|
||||
});
|
||||
const weapon = await updatePoolEntry('weapon', req.params.weaponId, req.campaign.id, parsed.data);
|
||||
if (!weapon) return res.status(404).json({ error: 'Weapon not found in this campaign' });
|
||||
await liftHeldCopies('characterWeapon', 'weaponId', weapon.id, parsed.data.minLevel);
|
||||
res.json({ weapon });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -278,7 +312,9 @@ router.patch('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), asy
|
||||
|
||||
router.delete('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.weapon.delete({ where: { id: req.params.weaponId } });
|
||||
if (!(await deletePoolEntry('weapon', req.params.weaponId, req.campaign.id))) {
|
||||
return res.status(404).json({ error: 'Weapon not found in this campaign' });
|
||||
}
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -306,6 +342,8 @@ const spellSchema = z.object({
|
||||
range: z.string().max(60).optional().nullable(),
|
||||
duration: z.string().max(60).optional().nullable(),
|
||||
description: z.string().max(4000).optional().nullable(),
|
||||
damageDice: z.string().max(20).optional().nullable(),
|
||||
isStartingOption: z.boolean().optional(),
|
||||
});
|
||||
|
||||
router.post('/:id/spells', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
@@ -319,11 +357,92 @@ router.post('/:id/spells', requireCampaignMember(), requireDM(), async (req, res
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/spells/:spellId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = spellSchema.partial().safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const spell = await updatePoolEntry('spell', req.params.spellId, req.campaign.id, parsed.data);
|
||||
if (!spell) return res.status(404).json({ error: 'Spell not found in this campaign' });
|
||||
res.json({ spell });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/spells/:spellId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
if (!(await deletePoolEntry('spell', req.params.spellId, req.campaign.id))) {
|
||||
return res.status(404).json({ error: 'Spell not found in this campaign' });
|
||||
}
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Monsters (DM only, campaign-scoped)
|
||||
// Items (campaign-level pool; DM manages and hands them out to characters)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/monsters', requireCampaignMember(), async (req, res, next) => {
|
||||
router.get('/:id/items', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const items = await prisma.item.findMany({ where: { campaignId: req.campaign.id }, orderBy: { name: 'asc' } });
|
||||
res.json({ items });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const itemSchema = z.object({
|
||||
name: z.string().min(1).max(120),
|
||||
description: z.string().max(2000).optional().nullable(),
|
||||
damageDice: z.string().max(20).optional().nullable(),
|
||||
damageScaling: z.number().int().min(1).max(MAX_DAMAGE_SCALING).optional(),
|
||||
minLevel: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
isStartingOption: z.boolean().optional(),
|
||||
});
|
||||
|
||||
router.post('/:id/items', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = itemSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const item = await prisma.item.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/items/:itemId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = itemSchema.partial().safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const item = await updatePoolEntry('item', req.params.itemId, req.campaign.id, parsed.data);
|
||||
if (!item) return res.status(404).json({ error: 'Item not found in this campaign' });
|
||||
await liftHeldCopies('inventoryItem', 'itemId', item.id, parsed.data.minLevel);
|
||||
res.json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/items/:itemId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
if (!(await deletePoolEntry('item', req.params.itemId, req.campaign.id))) {
|
||||
return res.status(404).json({ error: 'Item not found in this campaign' });
|
||||
}
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Monsters (DM only, campaign-scoped — stat blocks are the DM's; players see
|
||||
// a monster only as a name and a health bar in an encounter)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/monsters', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const monsters = await prisma.monster.findMany({ where: { campaignId: req.campaign.id }, orderBy: { name: 'asc' } });
|
||||
res.json({ monsters });
|
||||
@@ -365,7 +484,8 @@ router.patch('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), a
|
||||
try {
|
||||
const parsed = monsterSchema.partial().safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const monster = await prisma.monster.update({ where: { id: req.params.monsterId }, data: parsed.data });
|
||||
const monster = await updatePoolEntry('monster', req.params.monsterId, req.campaign.id, parsed.data);
|
||||
if (!monster) return res.status(404).json({ error: 'Monster not found in this campaign' });
|
||||
res.json({ monster });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -374,7 +494,9 @@ router.patch('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), a
|
||||
|
||||
router.delete('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.monster.delete({ where: { id: req.params.monsterId } });
|
||||
if (!(await deletePoolEntry('monster', req.params.monsterId, req.campaign.id))) {
|
||||
return res.status(404).json({ error: 'Monster not found in this campaign' });
|
||||
}
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -387,27 +509,99 @@ router.delete('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(),
|
||||
|
||||
router.get('/:id/encounters', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const isDM = req.membership.role === 'DM';
|
||||
const encounters = await prisma.encounter.findMany({
|
||||
where: { campaignId: req.campaign.id },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
res.json({ encounters });
|
||||
// dmNotes never leaves the server for a player.
|
||||
res.json({ encounters: isDM ? encounters : encounters.map(({ dmNotes, ...encounter }) => encounter) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const createEncounterSchema = z.object({
|
||||
name: z.string().min(1).max(120),
|
||||
mode: z.enum(['BATTLE', 'QUEST']).optional(),
|
||||
description: z.string().max(4000).optional().nullable(),
|
||||
});
|
||||
|
||||
router.post('/:id/encounters', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ name: z.string().min(1).max(120) }).safeParse(req.body);
|
||||
const parsed = createEncounterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const encounter = await prisma.encounter.create({ data: { campaignId: req.campaign.id, name: parsed.data.name } });
|
||||
const encounter = await prisma.encounter.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ encounter });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// NPCs (DM only — players meet them through encounters, without the DM's
|
||||
// notes or stats)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/npcs', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const npcs = await prisma.npc.findMany({ where: { campaignId: req.campaign.id }, orderBy: { name: 'asc' } });
|
||||
res.json({ npcs });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const npcSchema = z.object({
|
||||
name: z.string().min(1).max(80),
|
||||
role: z.string().max(80).optional().nullable(),
|
||||
disposition: z.enum(['FRIENDLY', 'NEUTRAL', 'HOSTILE']).optional(),
|
||||
description: z.string().max(2000).optional().nullable(),
|
||||
dmNotes: z.string().max(4000).optional().nullable(),
|
||||
ac: z.number().int().min(0).optional().nullable(),
|
||||
maxHp: z.number().int().min(1).optional().nullable(),
|
||||
attackBonus: z.number().int().optional().nullable(),
|
||||
damageDice: z.string().max(20).optional().nullable(),
|
||||
});
|
||||
|
||||
router.post('/:id/npcs', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = npcSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const npc = await prisma.npc.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ npc });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/npcs/:npcId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = npcSchema.partial().safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const npc = await updatePoolEntry('npc', req.params.npcId, req.campaign.id, parsed.data);
|
||||
if (!npc) return res.status(404).json({ error: 'NPC not found in this campaign' });
|
||||
res.json({ npc });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/npcs/:npcId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const npc = await prisma.npc.findFirst({ where: { id: req.params.npcId, campaignId: req.campaign.id } });
|
||||
if (!npc) return res.status(404).json({ error: 'NPC not found in this campaign' });
|
||||
// An NPC that no longer exists leaves the scenes it was in.
|
||||
await prisma.$transaction([
|
||||
prisma.encounterParticipant.deleteMany({ where: { npcId: npc.id } }),
|
||||
prisma.npc.delete({ where: { id: npc.id } }),
|
||||
]);
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Notes
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -462,7 +656,8 @@ router.patch('/:id/locations/:locationId', requireCampaignMember(), requireDM(),
|
||||
try {
|
||||
const parsed = locationSchema.partial().safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const location = await prisma.location.update({ where: { id: req.params.locationId }, data: parsed.data });
|
||||
const location = await updatePoolEntry('location', req.params.locationId, req.campaign.id, parsed.data);
|
||||
if (!location) return res.status(404).json({ error: 'Location not found in this campaign' });
|
||||
res.json({ location });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -471,7 +666,9 @@ router.patch('/:id/locations/:locationId', requireCampaignMember(), requireDM(),
|
||||
|
||||
router.delete('/:id/locations/:locationId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.location.delete({ where: { id: req.params.locationId } });
|
||||
if (!(await deletePoolEntry('location', req.params.locationId, req.campaign.id))) {
|
||||
return res.status(404).json({ error: 'Location not found in this campaign' });
|
||||
}
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
|
||||
@@ -3,23 +3,33 @@ const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCharacterAccess } = require('../middleware/characterAccess');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
const {
|
||||
computeCharacterSheet,
|
||||
computeWeaponStats,
|
||||
getClassSaveProficiencies,
|
||||
getClassSpellcastingAbility,
|
||||
scaledDamageDice,
|
||||
canUseGear,
|
||||
MAX_GEAR_LEVEL,
|
||||
ABILITIES,
|
||||
} = require('../game/calculations');
|
||||
const {
|
||||
rollDie,
|
||||
rollAbilityScore,
|
||||
abilityScoreFromDice,
|
||||
speciesChoicesForRoll,
|
||||
classChoicesForRoll,
|
||||
autoSelectSkills,
|
||||
validateManualRoll,
|
||||
MOTIVATION_TABLE,
|
||||
validatePicks,
|
||||
composeFromPicks,
|
||||
validateTalents,
|
||||
composeSpecialAbilities,
|
||||
} = require('../game/buildFlow');
|
||||
const characterOptions = require('../game/data/characterOptions');
|
||||
const { SKILLS } = require('../game/data/skills');
|
||||
const { InsufficientGoldError, adjustGold, giveGear } = require('../utils/grants');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -31,7 +41,7 @@ async function loadFullCharacter(id) {
|
||||
include: {
|
||||
skillProficiencies: true,
|
||||
saveProficiencies: true,
|
||||
inventoryItems: true,
|
||||
inventoryItems: { include: { item: true } },
|
||||
weapons: { include: { weapon: true } },
|
||||
spells: { include: { spell: true } },
|
||||
currentLocation: true,
|
||||
@@ -79,13 +89,40 @@ function serializeCharacter(character, isOwner) {
|
||||
buildState: character.buildStage === 'COMPLETE' ? null : character.buildState,
|
||||
skillProficiencies: character.skillProficiencies,
|
||||
saveProficiencies: character.saveProficiencies,
|
||||
inventoryItems: character.inventoryItems,
|
||||
weapons: character.weapons,
|
||||
spells: character.spells,
|
||||
// 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: character.inventoryItems.map((ii) => ({
|
||||
...ii,
|
||||
scaledDamageDice: ii.item.damageDice
|
||||
? scaledDamageDice(ii.item.damageDice, ii.level, ii.item.damageScaling, ii.item.minLevel)
|
||||
: null,
|
||||
usable: canUseGear(character.level, ii.level),
|
||||
})),
|
||||
weapons: character.weapons.map((cw) => ({
|
||||
...cw,
|
||||
scaledDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel),
|
||||
usable: canUseGear(character.level, cw.level),
|
||||
})),
|
||||
spells: character.spells.map((cs) => ({ ...cs, usable: canUseGear(character.level, cs.spell.level) })),
|
||||
sheet: character.buildStage === 'COMPLETE' ? sheet : null,
|
||||
};
|
||||
}
|
||||
|
||||
// The lists the builder's story steps are made of. Static, and the same for
|
||||
// everyone; the page fetches them rather than keeping a second copy.
|
||||
router.get('/build/options', (req, res) => {
|
||||
const { MOTIVATIONS, SPECIES_TRAITS, CLASS_FEATURES, TALENTS, TALENT_PICKS, BACKGROUND_GROUPS, APPEARANCE_GROUPS } = characterOptions;
|
||||
res.json({
|
||||
motivations: MOTIVATIONS,
|
||||
speciesTraits: SPECIES_TRAITS,
|
||||
classFeatures: CLASS_FEATURES,
|
||||
talents: TALENTS,
|
||||
talentPicks: TALENT_PICKS,
|
||||
background: BACKGROUND_GROUPS,
|
||||
appearance: APPEARANCE_GROUPS,
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
@@ -106,16 +143,39 @@ const patchCharacterSchema = z.object({
|
||||
appearance: z.string().max(4000).nullable().optional(),
|
||||
privateNotes: z.string().max(4000).nullable().optional(),
|
||||
currentLocationId: z.string().nullable().optional(),
|
||||
gold: z.number().int().min(0).optional(),
|
||||
level: z.number().int().min(1).max(20).optional(),
|
||||
xp: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
// Progression and placement are the DM's call, and so is rewriting what the
|
||||
// builder composed (special abilities, background, appearance): a player
|
||||
// picks those from lists and cannot type their own. 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).
|
||||
const DM_ONLY_PATCH_FIELDS = ['level', 'xp', 'currentLocationId', 'speedOverride', 'specialAbilities', 'background', 'appearance'];
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
if (req.body && req.body.gold !== undefined) {
|
||||
return res.status(400).json({ error: 'Gold 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 level, XP, speed, location, special abilities, background or appearance.' });
|
||||
}
|
||||
|
||||
// Current HP stays within 0..max, including when a level change moves max.
|
||||
if (req.character.buildStage === 'COMPLETE' && (parsed.data.currentHp !== undefined || parsed.data.level !== undefined)) {
|
||||
const maxHp = computeCharacterSheet({ ...req.character, ...parsed.data }).hp.max;
|
||||
parsed.data.currentHp = clamp(parsed.data.currentHp ?? req.character.currentHp, 0, maxHp);
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -131,6 +191,16 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({ where: { id: req.character.id }, data: parsed.data });
|
||||
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 },
|
||||
});
|
||||
}
|
||||
const full = await loadFullCharacter(updated.id);
|
||||
|
||||
// Broadcast payload never includes privateNotes — a socket room has
|
||||
@@ -153,6 +223,154 @@ router.delete('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Copy to another campaign
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Weapons, spells and items are per-campaign rows, so a copied character's gear
|
||||
// is re-pointed at the target campaign's entry of the same name
|
||||
// (case-insensitive), creating that entry from the source row when the target
|
||||
// doesn't have one. A created entry is never a starting option — that stays
|
||||
// the target DM's decision.
|
||||
// Returns source id -> the target pool row.
|
||||
async function mapPoolByName(tx, model, sourceRows, targetCampaignId) {
|
||||
const existing = await tx[model].findMany({ where: { campaignId: targetCampaignId } });
|
||||
const byName = new Map(existing.map((row) => [row.name.toLowerCase(), row]));
|
||||
const idMap = new Map();
|
||||
for (const { id, campaignId, createdAt, ...fields } of sourceRows) {
|
||||
const key = fields.name.toLowerCase();
|
||||
if (!byName.has(key)) {
|
||||
const created = await tx[model].create({
|
||||
data: { ...fields, isStartingOption: false, campaignId: targetCampaignId },
|
||||
});
|
||||
byName.set(key, created);
|
||||
}
|
||||
idMap.set(id, byName.get(key));
|
||||
}
|
||||
return idMap;
|
||||
}
|
||||
|
||||
// The copy is an independent character owned by whoever made it: the original
|
||||
// is untouched and the two never sync. Campaign-bound state (location, notes,
|
||||
// encounter entries) stays behind, and the copy arrives at full HP.
|
||||
router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ targetCampaignId: z.string().min(1) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { targetCampaignId } = parsed.data;
|
||||
|
||||
if (!req.isDM && !req.isOwner) {
|
||||
return res.status(403).json({ error: 'You can only copy your own character' });
|
||||
}
|
||||
if (req.character.buildStage !== 'COMPLETE') {
|
||||
return res.status(400).json({ error: 'Finish building this character before copying it.' });
|
||||
}
|
||||
if (targetCampaignId === req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'Pick a different campaign to copy this character into.' });
|
||||
}
|
||||
const targetMembership = await loadCampaignMembership(req.user.id, targetCampaignId);
|
||||
if (!targetMembership) return res.status(403).json({ error: 'Not a member of the target campaign' });
|
||||
|
||||
const source = await loadFullCharacter(req.character.id);
|
||||
const sheet = computeCharacterSheet(source, source.skillProficiencies, source.saveProficiencies);
|
||||
|
||||
const copyId = await prisma.$transaction(async (tx) => {
|
||||
const targetWeapons = await mapPoolByName(tx, 'weapon', source.weapons.map((cw) => cw.weapon), targetCampaignId);
|
||||
const targetSpells = await mapPoolByName(tx, 'spell', source.spells.map((cs) => cs.spell), targetCampaignId);
|
||||
const targetItems = await mapPoolByName(tx, 'item', source.inventoryItems.map((ii) => ii.item), targetCampaignId);
|
||||
|
||||
// Two source entries that differ only by case land on one target row.
|
||||
const items = new Map();
|
||||
for (const ii of source.inventoryItems) {
|
||||
const target = targetItems.get(ii.itemId);
|
||||
const itemId = target.id;
|
||||
const prev = items.get(itemId);
|
||||
items.set(itemId, {
|
||||
itemId,
|
||||
quantity: (prev ? prev.quantity : 0) + ii.quantity,
|
||||
equipped: Boolean(prev && prev.equipped) || ii.equipped,
|
||||
// The target campaign's entry may start at a higher level than the source's.
|
||||
level: Math.max(prev ? prev.level : 1, ii.level, target.minLevel),
|
||||
});
|
||||
}
|
||||
const weapons = new Map();
|
||||
for (const cw of source.weapons) {
|
||||
const target = targetWeapons.get(cw.weaponId);
|
||||
const weaponId = target.id;
|
||||
const prev = weapons.get(weaponId);
|
||||
weapons.set(weaponId, {
|
||||
weaponId,
|
||||
quantity: (prev ? prev.quantity : 0) + cw.quantity,
|
||||
equipped: Boolean(prev && prev.equipped) || cw.equipped,
|
||||
level: Math.max(prev ? prev.level : 1, cw.level, target.minLevel),
|
||||
});
|
||||
}
|
||||
const spells = new Map();
|
||||
for (const cs of source.spells) {
|
||||
const spellId = targetSpells.get(cs.spellId).id;
|
||||
const prev = spells.get(spellId);
|
||||
spells.set(spellId, { spellId, prepared: Boolean(prev && prev.prepared) || cs.prepared });
|
||||
}
|
||||
|
||||
const created = await tx.character.create({
|
||||
data: {
|
||||
campaignId: targetCampaignId,
|
||||
userId: req.user.id,
|
||||
createdById: req.user.id,
|
||||
name: source.name,
|
||||
species: source.species,
|
||||
characterClass: source.characterClass,
|
||||
level: source.level,
|
||||
xp: source.xp,
|
||||
motivation: source.motivation,
|
||||
strScore: source.strScore,
|
||||
dexScore: source.dexScore,
|
||||
conScore: source.conScore,
|
||||
intScore: source.intScore,
|
||||
wisScore: source.wisScore,
|
||||
chaScore: source.chaScore,
|
||||
halfElfBonusAbility1: source.halfElfBonusAbility1,
|
||||
halfElfBonusAbility2: source.halfElfBonusAbility2,
|
||||
currentHp: sheet.hp.max,
|
||||
armorBonus: source.armorBonus,
|
||||
speedOverride: source.speedOverride,
|
||||
specialAbilities: source.specialAbilities,
|
||||
gold: source.gold,
|
||||
background: source.background,
|
||||
appearance: source.appearance,
|
||||
// Same privacy boundary as serializeCharacter: a DM copying a
|
||||
// player's character never carries the player's private notes along.
|
||||
privateNotes: req.isOwner ? source.privateNotes : null,
|
||||
diceMode: source.diceMode,
|
||||
buildStage: 'COMPLETE',
|
||||
skillProficiencies: {
|
||||
create: source.skillProficiencies.map(({ skill, proficient, expertise }) => ({ skill, proficient, expertise })),
|
||||
},
|
||||
saveProficiencies: {
|
||||
create: source.saveProficiencies.map(({ ability, proficient }) => ({ ability, proficient })),
|
||||
},
|
||||
inventoryItems: { create: [...items.values()] },
|
||||
goldTransactions: {
|
||||
create:
|
||||
source.gold > 0
|
||||
? [{ amount: source.gold, balanceAfter: source.gold, 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', { character: serializeCharacter(full, false) });
|
||||
res.status(201).json({ character: serializeCharacter(full, true) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Roll-Your-Character build flow — docs/ROLL_YOUR_CHARACTER.md
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -212,12 +430,15 @@ router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (r
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
|
||||
try {
|
||||
// Every die is rolled once. Going back to a step shows the roll that was
|
||||
// already made; it never hands out a fresh one.
|
||||
if (stage === 'ROLLING_SPECIES') {
|
||||
if (buildState.speciesRoll) {
|
||||
return res.status(400).json({ error: 'Species die already rolled for this character — choose from what it offered.' });
|
||||
}
|
||||
const roll = resolveSingleRoll(character, req.body, 6);
|
||||
buildState.speciesRoll = roll;
|
||||
buildState.speciesChoices = speciesChoicesForRoll(roll);
|
||||
delete buildState.species;
|
||||
delete buildState.halfElfBonusAbilities;
|
||||
} else if (stage === 'ROLLING_CLASS') {
|
||||
const alreadyRolled = buildState.classChoices && buildState.classChoices.type !== 'reroll';
|
||||
if (alreadyRolled) {
|
||||
@@ -227,10 +448,6 @@ router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (r
|
||||
buildState.classRoll = roll;
|
||||
buildState.classChoices = classChoicesForRoll(roll);
|
||||
delete buildState.characterClass;
|
||||
} else if (stage === 'ROLLING_MOTIVATION') {
|
||||
const roll = resolveSingleRoll(character, req.body, 6);
|
||||
buildState.motivationRoll = roll;
|
||||
buildState.motivationText = MOTIVATION_TABLE[roll];
|
||||
} else if (stage === 'ASSIGNING_SCORES') {
|
||||
if (buildState.abilityRolls) {
|
||||
return res.status(400).json({ error: 'Ability scores were already rolled for this character.' });
|
||||
@@ -258,7 +475,9 @@ const chooseSchemas = {
|
||||
halfElfBonusAbilities: z.array(z.enum(HALF_ELF_ELIGIBLE_ABILITIES)).length(2).optional(),
|
||||
}),
|
||||
ROLLING_CLASS: z.object({ characterClass: z.string() }),
|
||||
ROLLING_MOTIVATION: z.object({ motivation: z.string().max(500).optional() }),
|
||||
// Motivation is story only, so it is simply picked from the list (the stage
|
||||
// keeps its old name from when it was a die roll).
|
||||
ROLLING_MOTIVATION: z.object({ motivation: z.number().int() }),
|
||||
ASSIGNING_SCORES: z.object({
|
||||
assignments: z.object({
|
||||
STR: z.number().int().min(0).max(5),
|
||||
@@ -283,18 +502,35 @@ const chooseSchemas = {
|
||||
)
|
||||
.optional(),
|
||||
}),
|
||||
CHOOSING_ABILITIES: z.object({ talents: z.array(z.string()) }),
|
||||
CHOOSING_BACKGROUND: z.object({ picks: z.record(z.array(z.string())) }),
|
||||
CHOOSING_APPEARANCE: z.object({ picks: z.record(z.array(z.string())) }),
|
||||
CHOOSING_EQUIPMENT: z.object({
|
||||
weaponIds: z.array(z.string()).default([]),
|
||||
itemIds: z.array(z.string()).default([]),
|
||||
spellIds: z.array(z.string()).default([]),
|
||||
}),
|
||||
};
|
||||
|
||||
// Every id must be a distinct entry in this campaign's pool that the DM has
|
||||
// marked as a starting option. `reach` narrows that to entries a character of
|
||||
// this level can already use (gear by its starting level, spells by their level).
|
||||
async function allStartingOptions(model, ids, campaignId, reach) {
|
||||
if (new Set(ids).size !== ids.length) return false;
|
||||
if (ids.length === 0) return true;
|
||||
const count = await prisma[model].count({ where: { id: { in: ids }, campaignId, isStartingOption: true, ...reach } });
|
||||
return count === ids.length;
|
||||
}
|
||||
|
||||
const STAGE_ORDER = [
|
||||
'ROLLING_SPECIES',
|
||||
'ROLLING_CLASS',
|
||||
'ROLLING_MOTIVATION',
|
||||
'ASSIGNING_SCORES',
|
||||
'ASSIGNING_PROFICIENCIES',
|
||||
'CHOOSING_ABILITIES',
|
||||
'CHOOSING_BACKGROUND',
|
||||
'CHOOSING_APPEARANCE',
|
||||
'CHOOSING_EQUIPMENT',
|
||||
'COMPLETE',
|
||||
];
|
||||
@@ -351,8 +587,10 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
buildState.motivationText = null;
|
||||
}
|
||||
} else if (stage === 'ROLLING_MOTIVATION') {
|
||||
if (!buildState.motivationRoll) return res.status(400).json({ error: 'Roll for motivation first.' });
|
||||
if (parsed.data.motivation) buildState.motivationText = parsed.data.motivation;
|
||||
const motivation = characterOptions.MOTIVATIONS.find((m) => m.key === parsed.data.motivation);
|
||||
if (!motivation) return res.status(400).json({ error: 'Pick a motivation from the list.' });
|
||||
buildState.motivationChoice = motivation.key;
|
||||
buildState.motivationText = motivation.label;
|
||||
} else if (stage === 'ASSIGNING_SCORES') {
|
||||
if (!buildState.abilityRolls) return res.status(400).json({ error: 'Roll ability scores first.' });
|
||||
const { assignments } = parsed.data;
|
||||
@@ -364,20 +602,41 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
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.
|
||||
buildState.skillProficiencies = autoSelectSkills(buildState.characterClass);
|
||||
// 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, spellIds } = parsed.data;
|
||||
const { weaponIds, itemIds, spellIds } = parsed.data;
|
||||
const maxItems = req.campaign.startingItemCount;
|
||||
const maxSpells = req.campaign.startingSpellCount;
|
||||
if (weaponIds.length > maxItems) {
|
||||
return res.status(400).json({ error: `This campaign allows at most ${maxItems} starting item(s).` });
|
||||
// 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) {
|
||||
@@ -386,7 +645,18 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
if (spellIds.length > maxSpells) {
|
||||
return res.status(400).json({ error: `This campaign allows at most ${maxSpells} starting spell(s).` });
|
||||
}
|
||||
buildState.equipment = { weaponIds, spellIds };
|
||||
// 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
|
||||
}
|
||||
|
||||
@@ -400,6 +670,40 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
}
|
||||
});
|
||||
|
||||
// Steps back to the previous step so its choice can be changed. Dice are
|
||||
// never re-rolled: the earlier step comes back with the same roll, the same
|
||||
// options and the previous pick still in place. The only thing dropped is the
|
||||
// equipment selection, which is re-confirmed on the way forward (a change of
|
||||
// class can change which starting spells are allowed).
|
||||
router.post('/:id/build/back', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
const stage = character.buildStage;
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
|
||||
let backTo;
|
||||
if (stage === 'CHOOSING_EQUIPMENT' && buildState.equipment) {
|
||||
backTo = 'CHOOSING_EQUIPMENT'; // from the finalize prompt back to picking equipment
|
||||
} else {
|
||||
const idx = STAGE_ORDER.indexOf(stage);
|
||||
if (idx <= 0 || stage === 'COMPLETE') {
|
||||
return res.status(400).json({ error: 'There is no earlier step to go back to.' });
|
||||
}
|
||||
backTo = STAGE_ORDER[idx - 1];
|
||||
if (backTo === 'ROLLING_MOTIVATION' && req.campaign.skipMotivationRoll) backTo = 'ROLLING_CLASS';
|
||||
}
|
||||
delete buildState.equipment;
|
||||
|
||||
const updated = await prisma.character.update({
|
||||
where: { id: character.id },
|
||||
data: { buildState, buildStage: backTo },
|
||||
});
|
||||
res.json({ buildStage: updated.buildStage, buildState: updated.buildState });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
@@ -430,6 +734,11 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
|
||||
species: bs.species,
|
||||
characterClass: bs.characterClass,
|
||||
motivation: bs.motivationText || null,
|
||||
// Composed here, from the picks, so the text can only ever say what
|
||||
// the lists allow.
|
||||
specialAbilities: composeSpecialAbilities(bs.species, bs.characterClass, bs.talents || []),
|
||||
background: bs.backgroundPicks ? composeFromPicks(characterOptions.BACKGROUND_GROUPS, bs.backgroundPicks) : null,
|
||||
appearance: bs.appearancePicks ? composeFromPicks(characterOptions.APPEARANCE_GROUPS, bs.appearancePicks) : null,
|
||||
strScore: rolledScores.STR,
|
||||
dexScore: rolledScores.DEX,
|
||||
conScore: rolledScores.CON,
|
||||
@@ -453,6 +762,9 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
|
||||
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 })),
|
||||
},
|
||||
@@ -488,14 +800,17 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
}
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
|
||||
const weapons = character.weapons.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
weaponId: cw.weaponId,
|
||||
name: cw.weapon.name,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true),
|
||||
}));
|
||||
const weapons = character.weapons
|
||||
.filter((cw) => canUseGear(character.level, cw.level))
|
||||
.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
weaponId: cw.weaponId,
|
||||
name: cw.weapon.name,
|
||||
level: cw.level,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level),
|
||||
}));
|
||||
|
||||
res.json({
|
||||
quickStats: {
|
||||
@@ -518,137 +833,267 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Weapons assigned to this character
|
||||
// Money tracker — the gold balance only ever changes through this ledger
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/weapons', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
const GOLD_TRANSACTION_INCLUDE = { createdBy: { select: { displayName: true } } };
|
||||
|
||||
router.get('/:id/gold', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ weaponId: z.string(), quantity: z.number().int().min(1).default(1) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const weapon = await prisma.weapon.findUnique({ where: { id: parsed.data.weaponId } });
|
||||
if (!weapon || weapon.campaignId !== req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'That weapon is not part of this campaign.' });
|
||||
}
|
||||
|
||||
const characterWeapon = await prisma.characterWeapon.upsert({
|
||||
where: { characterId_weaponId: { characterId: req.character.id, weaponId: parsed.data.weaponId } },
|
||||
create: { characterId: req.character.id, weaponId: parsed.data.weaponId, quantity: parsed.data.quantity },
|
||||
update: { quantity: { increment: parsed.data.quantity } },
|
||||
include: { weapon: true },
|
||||
const transactions = await prisma.goldTransaction.findMany({
|
||||
where: { characterId: req.character.id },
|
||||
include: GOLD_TRANSACTION_INCLUDE,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
});
|
||||
res.status(201).json({ characterWeapon });
|
||||
res.json({ gold: req.character.gold, transactions });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/weapons/:weaponId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({ quantity: z.number().int().min(0).optional(), equipped: z.boolean().optional() })
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const characterWeapon = await prisma.characterWeapon.update({
|
||||
where: { characterId_weaponId: { characterId: req.character.id, weaponId: req.params.weaponId } },
|
||||
data: parsed.data,
|
||||
include: { weapon: true },
|
||||
});
|
||||
res.json({ characterWeapon });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Inventory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/inventory', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
// amount is signed: positive = gained, negative = spent. The owning player
|
||||
// and the DM can both record entries; each one is stamped with who made it.
|
||||
router.post('/:id/gold', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({
|
||||
name: z.string().min(1).max(120),
|
||||
description: z.string().max(2000).optional().nullable(),
|
||||
quantity: z.number().int().min(1).default(1),
|
||||
equipped: z.boolean().default(false),
|
||||
amount: z.number().int().refine((n) => n !== 0, 'Amount cannot be zero'),
|
||||
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, reason } = parsed.data;
|
||||
|
||||
const item = await prisma.inventoryItem.create({ data: { ...parsed.data, characterId: req.character.id } });
|
||||
res.status(201).json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/inventory/:itemId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
quantity: z.number().int().min(0).optional(),
|
||||
equipped: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const item = await prisma.inventoryItem.update({ where: { id: req.params.itemId }, data: parsed.data });
|
||||
res.json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/inventory/:itemId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.inventoryItem.delete({ where: { id: req.params.itemId } });
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spells known by this character
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/spells', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ spellId: z.string(), prepared: z.boolean().default(false) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const spell = await prisma.spell.findUnique({ where: { id: parsed.data.spellId } });
|
||||
if (!spell || spell.campaignId !== req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'That spell is not part of this campaign.' });
|
||||
let transaction;
|
||||
try {
|
||||
// Throwing inside the transaction rolls the balance change back.
|
||||
transaction = await prisma.$transaction((tx) =>
|
||||
adjustGold(tx, { characterId: req.character.id, amount, reason, userId: req.user.id, include: GOLD_TRANSACTION_INCLUDE })
|
||||
);
|
||||
} catch (err) {
|
||||
if (!(err instanceof InsufficientGoldError)) throw err;
|
||||
return res.status(400).json({ error: `Not enough gold — the balance is ${req.character.gold}.` });
|
||||
}
|
||||
|
||||
const characterSpell = await prisma.characterSpell.upsert({
|
||||
where: { characterId_spellId: { characterId: req.character.id, spellId: parsed.data.spellId } },
|
||||
create: { characterId: req.character.id, spellId: parsed.data.spellId, prepared: parsed.data.prepared },
|
||||
update: { prepared: parsed.data.prepared },
|
||||
include: { spell: true },
|
||||
});
|
||||
res.status(201).json({ characterSpell });
|
||||
emitCharacterUpdated(req);
|
||||
res.status(201).json({ gold: transaction.balanceAfter, transaction });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/spells/:spellId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ prepared: z.boolean() }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const characterSpell = await prisma.characterSpell.update({
|
||||
where: { characterId_spellId: { characterId: req.character.id, spellId: req.params.spellId } },
|
||||
data: parsed.data,
|
||||
include: { spell: true },
|
||||
});
|
||||
res.json({ characterSpell });
|
||||
function requireDmForGear(req, res) {
|
||||
if (req.isDM) return true;
|
||||
res.status(403).json({ error: 'Only the DM can give, remove, re-count or level up gear.' });
|
||||
return false;
|
||||
}
|
||||
|
||||
function emitCharacterUpdated(req) {
|
||||
req.app.get('io').to(`campaign:${req.character.campaignId}`).emit('character:updated', { characterId: req.character.id });
|
||||
}
|
||||
|
||||
// One set of routes per kind of gear. `key` is the pool-entry id column on the
|
||||
// join row (also the route param), `flag` the boolean the owner may toggle.
|
||||
// A held weapon or item (`ownLevel`) has a quantity and its own level; a spell
|
||||
// has neither, and the level a character needs is the spell's classic level.
|
||||
const GEAR = [
|
||||
{ path: 'weapons', pool: 'weapon', held: 'characterWeapon', key: 'weaponId', flag: 'equipped', ownLevel: true, label: 'weapon' },
|
||||
{ path: 'inventory', pool: 'item', held: 'inventoryItem', key: 'itemId', flag: 'equipped', ownLevel: true, label: 'item' },
|
||||
{ path: 'spells', pool: 'spell', held: 'characterSpell', key: 'spellId', flag: 'prepared', ownLevel: false, label: 'spell' },
|
||||
];
|
||||
|
||||
const gearLevelSchema = z.number().int().min(1).max(MAX_GEAR_LEVEL);
|
||||
|
||||
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)) });
|
||||
}
|
||||
|
||||
// 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,
|
||||
});
|
||||
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
|
||||
}
|
||||
|
||||
const row = await prisma[gear.held].update({ where: whereHeld(req), data, include });
|
||||
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}.` });
|
||||
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) }),
|
||||
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') {
|
||||
await adjustGold(tx, { characterId: giver.id, amount: -give.amount, reason: `Gave to ${recipient.name}`, userId: req.user.id });
|
||||
await adjustGold(tx, { characterId: recipient.id, amount: give.amount, reason: `Received from ${giver.name}`, userId: req.user.id });
|
||||
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: `Not enough gold — ${giver.name} has ${giver.gold}.` });
|
||||
}
|
||||
if (err instanceof GiveError) return res.status(400).json({ error: err.message });
|
||||
throw err;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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