Files
the-sunken-reach/backend/src/routes/campaigns.routes.js
T
joshuaandClaude Opus 5.5 0ddf9846a2 V1.12.1: each library entry goes into a campaign once
- A weapon, item, spell or monster from the library can be added to a
  campaign once. Adding it again is refused: "Longsword is already in
  this campaign."
- The library list leaves out what the campaign already has, so what is
  left is what can still be added. When nothing is left it says so.
- An entry counts as added while the campaign has one by that name,
  whatever its capitals. Rename or delete the campaign's copy and the
  library offers it again. This also covers what a world's seed put in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:09:23 +02:00

1036 lines
43 KiB
JavaScript

const express = require('express');
const { z } = require('zod');
const prisma = require('../db');
const { requireAuth } = require('../middleware/auth');
const { requireCampaignMember, requireDM } = require('../middleware/campaignAccess');
const { generateInviteCode } = require('../utils/inviteCode');
const { computeCharacterSheet, GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('../game/calculations');
const { SHEET_INCLUDE, settleHp } = require('../utils/sheet');
const { WEAPON_LIBRARY, ITEM_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
const { visitedLocationIds } = require('../utils/locations');
const { deathSaveInfo } = require('../utils/hp');
const { CURRENCIES } = require('../utils/grants');
const { findSeed, normalizeCode, CODE_LENGTH } = require('../seeds');
const { createCampaignFromSeed } = require('../seeds/createCampaign');
const router = express.Router();
router.use(requireAuth);
function campaignSummary(campaign, role) {
return {
id: campaign.id,
name: campaign.name,
description: campaign.description,
// The invite code is the DM's to hand out.
inviteCode: role === 'DM' ? campaign.inviteCode : undefined,
startingGold: campaign.startingGold,
startingItemCount: campaign.startingItemCount,
startingSpellCount: campaign.startingSpellCount,
skipMotivationRoll: campaign.skipMotivationRoll,
showMonsterHp: campaign.showMonsterHp,
areaAttackAcPenalty: campaign.areaAttackAcPenalty,
maxEquipped: campaign.maxEquipped,
maxEquippedWeapons: campaign.maxEquippedWeapons,
ownerId: campaign.ownerId,
archivedAt: campaign.archivedAt,
role,
createdAt: campaign.createdAt,
};
}
// GET /campaigns — campaigns I'm a DM or player in
router.get('/', async (req, res, next) => {
try {
const memberships = await prisma.campaignMember.findMany({
where: { userId: req.user.id },
include: { campaign: true },
orderBy: { joinedAt: 'desc' },
});
res.json({ campaigns: memberships.map((m) => campaignSummary(m.campaign, m.role)) });
} catch (err) {
next(err);
}
});
const createCampaignSchema = z.object({
name: z.string().min(1).max(120),
description: z.string().max(2000).optional().nullable(),
startingGold: z.number().int().min(0).max(1000000).optional(),
startingItemCount: z.number().int().min(0).max(50).optional(),
startingSpellCount: z.number().int().min(0).max(50).optional(),
skipMotivationRoll: z.boolean().optional(),
showMonsterHp: z.boolean().optional(),
areaAttackAcPenalty: z.number().int().min(0).max(10).optional(),
// How many weapons and items a character can have equipped together, and
// how many of those can be weapons. Lowering them takes nothing off anyone:
// they are checked when something is put on.
maxEquipped: z.number().int().min(1).max(20).optional(),
maxEquippedWeapons: z.number().int().min(0).max(20).optional(),
});
// POST /campaigns — create, creator becomes DM/owner
router.post('/', async (req, res, next) => {
try {
const parsed = createCampaignSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
let inviteCode = generateInviteCode();
// Extremely unlikely to collide, but guard anyway.
for (let i = 0; i < 5; i++) {
const clash = await prisma.campaign.findUnique({ where: { inviteCode } });
if (!clash) break;
inviteCode = generateInviteCode();
}
const campaign = await prisma.campaign.create({
data: {
...parsed.data,
inviteCode,
ownerId: req.user.id,
members: { create: { userId: req.user.id, role: 'DM' } },
},
});
res.status(201).json({ campaign: campaignSummary(campaign, 'DM') });
} catch (err) {
next(err);
}
});
// POST /campaigns/from-seed — a ready-made world (a file in /backend/seeds)
// as a new campaign, by its code. As with a blank campaign, whoever creates
// it is its DM and owner; the same code can be used again for another copy.
router.post('/from-seed', async (req, res, next) => {
try {
const parsed = z.object({ code: z.string().max(40) }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (normalizeCode(parsed.data.code).length !== CODE_LENGTH) {
return res.status(400).json({ error: `A world code is ${CODE_LENGTH} letters or numbers` });
}
const seed = findSeed(parsed.data.code);
if (!seed) return res.status(404).json({ error: 'There is no world with that code' });
// One transaction, so a failure doesn't leave half a world behind. A big
// world is thousands of rows, which is more than the default 5 seconds.
const campaign = await prisma.$transaction((tx) => createCampaignFromSeed(tx, req.user, seed), { timeout: 120000, maxWait: 20000 });
res.status(201).json({ campaign: campaignSummary(campaign, 'DM') });
} catch (err) {
next(err);
}
});
// POST /campaigns/join/:inviteCode — must be before requireCampaignMember-gated routes below
router.post('/join/:inviteCode', async (req, res, next) => {
try {
const campaign = await prisma.campaign.findUnique({ where: { inviteCode: req.params.inviteCode } });
if (!campaign) return res.status(404).json({ error: 'Invalid invite code' });
if (campaign.archivedAt) return res.status(403).json({ error: 'That campaign is archived and is not taking new members' });
const existing = await prisma.campaignMember.findUnique({
where: { campaignId_userId: { campaignId: campaign.id, userId: req.user.id } },
});
if (existing) return res.json({ campaign: campaignSummary(campaign, existing.role) });
await prisma.campaignMember.create({ data: { campaignId: campaign.id, userId: req.user.id, role: 'PLAYER' } });
res.status(201).json({ campaign: campaignSummary(campaign, 'PLAYER') });
} catch (err) {
next(err);
}
});
router.get('/:id', requireCampaignMember(), async (req, res, next) => {
try {
const members = await prisma.campaignMember.findMany({
where: { campaignId: req.campaign.id },
include: { user: { select: { id: true, displayName: true, email: true } } },
});
res.json({
campaign: campaignSummary(req.campaign, req.membership.role),
members: members.map((m) => ({ userId: m.userId, displayName: m.user.displayName, role: m.role })),
});
} catch (err) {
next(err);
}
});
// `archived` puts the campaign away (true) or brings it back (false).
const updateCampaignSchema = createCampaignSchema.partial().extend({ archived: z.boolean().optional() });
router.patch('/:id', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = updateCampaignSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { archived, ...data } = parsed.data;
// Re-archiving keeps the original date.
if (archived === true && !req.campaign.archivedAt) data.archivedAt = new Date();
if (archived === false) data.archivedAt = null;
const campaign = await prisma.campaign.update({ where: { id: req.campaign.id }, data });
res.json({ campaign: campaignSummary(campaign, 'DM') });
} catch (err) {
next(err);
}
});
// Deleting takes everything in the campaign with it — characters, pools,
// encounters, notes — so it is the owner's call alone, not any DM's.
router.delete('/:id', requireCampaignMember(), async (req, res, next) => {
try {
if (req.campaign.ownerId !== req.user.id) {
return res.status(403).json({ error: 'Only the campaign owner can delete it' });
}
await prisma.campaign.delete({ where: { id: req.campaign.id } });
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('campaign:deleted', { campaignId: req.campaign.id });
res.status(204).end();
} catch (err) {
next(err);
}
});
router.post('/:id/invite', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const regenerate = req.body && req.body.regenerate === true;
if (!regenerate) return res.json({ inviteCode: req.campaign.inviteCode });
let inviteCode = generateInviteCode();
for (let i = 0; i < 5; i++) {
const clash = await prisma.campaign.findUnique({ where: { inviteCode } });
if (!clash) break;
inviteCode = generateInviteCode();
}
const campaign = await prisma.campaign.update({ where: { id: req.campaign.id }, data: { inviteCode } });
res.json({ inviteCode: campaign.inviteCode });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Characters within a campaign
// ---------------------------------------------------------------------------
function characterSummary(character) {
const sheet = computeCharacterSheet(
character,
character.skillProficiencies || [],
character.saveProficiencies || []
);
return {
id: character.id,
campaignId: character.campaignId,
userId: character.userId,
createdById: character.createdById,
name: character.name,
species: character.species,
characterClass: character.characterClass,
level: character.level,
xp: character.xp,
buildStage: character.buildStage,
currentHp: character.currentHp,
tempHp: character.tempHp,
deathSaves: deathSaveInfo(character),
gold: character.gold,
silver: character.silver,
copper: character.copper,
cash: character.cash,
maxHp: character.buildStage === 'COMPLETE' ? sheet.hp.max : null,
armorClass: character.buildStage === 'COMPLETE' ? sheet.armorClass : null,
currentLocationId: character.currentLocationId,
currentLocationName: character.currentLocation ? character.currentLocation.name : null,
};
}
router.get('/:id/characters', requireCampaignMember(), async (req, res, next) => {
try {
const characters = await prisma.character.findMany({
where: { campaignId: req.campaign.id },
include: { ...SHEET_INCLUDE, currentLocation: true },
orderBy: { createdAt: 'asc' },
});
const summaries = characters.map(characterSummary);
if (req.membership.role === 'DM') return res.json({ characters: summaries });
// A player sees the party's headline numbers, but another character's
// purse is their own business, and so is a place this player has not been.
const visited = await visitedLocationIds(prisma, req.user.id, req.campaign.id);
res.json({
characters: summaries.map((c) => {
if (c.userId === req.user.id) return c;
const knowsPlace = c.currentLocationId && visited.has(c.currentLocationId);
return { ...c, gold: null, silver: null, copper: null, cash: null, ...(knowsPlace ? {} : { currentLocationId: null, currentLocationName: null }) };
}),
});
} catch (err) {
next(err);
}
});
const createCharacterSchema = z.object({
name: z.string().min(1).max(80),
userId: z.string().optional().nullable(), // DM building for a player; omitted => for self
});
router.post('/:id/characters', requireCampaignMember(), async (req, res, next) => {
try {
const parsed = createCharacterSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const isDM = req.membership.role === 'DM';
let targetUserId = req.user.id;
if (parsed.data.userId) {
if (!isDM && parsed.data.userId !== req.user.id) {
return res.status(403).json({ error: 'Only the DM can build a character for another player' });
}
const targetMembership = await prisma.campaignMember.findUnique({
where: { campaignId_userId: { campaignId: req.campaign.id, userId: parsed.data.userId } },
});
if (!targetMembership) return res.status(400).json({ error: 'That user is not a member of this campaign' });
targetUserId = parsed.data.userId;
}
const startingGold = req.campaign.startingGold;
const character = await prisma.character.create({
data: {
campaignId: req.campaign.id,
userId: targetUserId,
createdById: req.user.id,
name: parsed.data.name,
buildStage: 'ROLLING_SPECIES',
gold: startingGold,
goldTransactions: {
create:
startingGold > 0
? [{ amount: startingGold, balanceAfter: startingGold, reason: 'Starting gold', createdById: req.user.id }]
: [],
},
},
});
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('character:created', { characterId: character.id });
res.status(201).json({ character: characterSummary(character) });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Weapons (campaign-level pool; the DM manages it and sees all of it)
// ---------------------------------------------------------------------------
// What a player may see of a pool: whatever one of their own characters holds,
// plus the starting options while they still have a character to build. The
// rest of the pool — gear yet to be found, spells yet to be learned — is the
// DM's. `held` is the pool model's relation to the per-character rows.
async function poolScope(req, held) {
const where = { campaignId: req.campaign.id };
if (req.membership.role === 'DM') return where;
const mine = { userId: req.user.id, campaignId: req.campaign.id };
const building = await prisma.character.count({ where: { ...mine, buildStage: { not: 'COMPLETE' } } });
return {
...where,
OR: [{ [held]: { some: { character: mine } } }, ...(building > 0 ? [{ isStartingOption: true }] : [])],
};
}
router.get('/:id/weapons', requireCampaignMember(), async (req, res, next) => {
try {
const weapons = await prisma.weapon.findMany({ where: await poolScope(req, 'assigned'), orderBy: { name: 'asc' } });
res.json({ weapons });
} catch (err) {
next(err);
}
});
// What a weapon or item does to the sheet of whoever has it equipped: signed
// amounts on the numbers in GEAR_STATS (armor is an item with an AC effect),
// and a note for what is not a number.
const gearEffects = {
effects: z
.array(z.object({ stat: z.enum(GEAR_STATS), amount: z.number().int().min(-100).max(100).refine((n) => n !== 0, 'An effect of 0 does nothing') }))
.max(12)
.optional(),
effectNote: z.string().trim().max(300).optional().nullable(),
};
// A change to what a pool entry does reaches everyone who has it equipped:
// their maximum HP may have dropped, and every open sheet should refetch.
async function gearChanged(req, heldModel, poolKey, poolId, holderIds) {
const holders = holderIds || (await prisma[heldModel].findMany({ where: { [poolKey]: poolId }, select: { characterId: true } })).map((h) => h.characterId);
await settleHp(prisma, holders);
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('character:updated', {});
}
const weaponSchema = z.object({
name: z.string().min(1).max(80),
damageDice: z.string().min(1).max(20),
damageType: z.string().min(1).max(40),
attackAbility: z.enum(['STR', 'DEX', 'FINESSE']),
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(),
...gearEffects,
});
// 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);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const weapon = await prisma.weapon.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
res.status(201).json({ weapon });
} catch (err) {
next(err);
}
});
router.patch('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = weaponSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
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);
await gearChanged(req, 'characterWeapon', 'weaponId', weapon.id);
res.json({ weapon });
} catch (err) {
next(err);
}
});
router.delete('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const holders = (await prisma.characterWeapon.findMany({ where: { weaponId: req.params.weaponId }, select: { characterId: true } })).map((h) => h.characterId);
if (!(await deletePoolEntry('weapon', req.params.weaponId, req.campaign.id))) {
return res.status(404).json({ error: 'Weapon not found in this campaign' });
}
await gearChanged(req, 'characterWeapon', 'weaponId', req.params.weaponId, holders);
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Spells (campaign-level list; DM manages, used as the starting-spell pool)
// ---------------------------------------------------------------------------
router.get('/:id/spells', requireCampaignMember(), async (req, res, next) => {
try {
const spells = await prisma.spell.findMany({ where: await poolScope(req, 'known'), orderBy: { name: 'asc' } });
res.json({ spells });
} catch (err) {
next(err);
}
});
const spellSchema = z.object({
name: z.string().min(1).max(80),
level: z.number().int().min(0).max(9),
school: z.string().max(40).optional().nullable(),
castingTime: z.string().max(60).optional().nullable(),
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(),
revives: z.boolean().optional(), // brings back the dead
});
router.post('/:id/spells', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = spellSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const spell = await prisma.spell.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
res.status(201).json({ spell });
} catch (err) {
next(err);
}
});
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);
}
});
// ---------------------------------------------------------------------------
// Items (campaign-level pool; DM manages and hands them out to characters)
// ---------------------------------------------------------------------------
router.get('/:id/items', requireCampaignMember(), async (req, res, next) => {
try {
const items = await prisma.item.findMany({ where: await poolScope(req, 'held'), 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(),
...gearEffects,
});
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);
await gearChanged(req, 'inventoryItem', 'itemId', item.id);
res.json({ item });
} catch (err) {
next(err);
}
});
router.delete('/:id/items/:itemId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const holders = (await prisma.inventoryItem.findMany({ where: { itemId: req.params.itemId }, select: { characterId: true } })).map((h) => h.characterId);
if (!(await deletePoolEntry('item', req.params.itemId, req.campaign.id))) {
return res.status(404).json({ error: 'Item not found in this campaign' });
}
await gearChanged(req, 'inventoryItem', 'itemId', req.params.itemId, holders);
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 });
} catch (err) {
next(err);
}
});
const monsterSchema = z.object({
name: z.string().min(1).max(80),
ac: z.number().int().min(0).max(50),
maxHp: z.number().int().min(1).max(100000),
speed: z.number().int().min(0).optional(),
strScore: z.number().int().min(1).max(30).optional(),
dexScore: z.number().int().min(1).max(30).optional(),
conScore: z.number().int().min(1).max(30).optional(),
intScore: z.number().int().min(1).max(30).optional(),
wisScore: z.number().int().min(1).max(30).optional(),
chaScore: z.number().int().min(1).max(30).optional(),
attackBonus: z.number().int().min(-20).max(50).optional(),
damageDice: z.string().max(60).optional().nullable(), // may name its type: "1d6+2 necrotic"
challengeRating: z.string().max(10).optional().nullable(),
specialTrait: z.string().max(500).optional().nullable(),
notes: z.string().max(2000).optional().nullable(),
});
router.post('/:id/monsters', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = monsterSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const monster = await prisma.monster.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
res.status(201).json({ monster });
} catch (err) {
next(err);
}
});
router.patch('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = monsterSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
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);
}
});
router.delete('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
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);
}
});
// ---------------------------------------------------------------------------
// Encounters
// ---------------------------------------------------------------------------
router.get('/:id/encounters', requireCampaignMember(), async (req, res, next) => {
try {
const isDM = req.membership.role === 'DM';
// The DM sees every encounter. A player sees the live ones that one of
// their own characters is in, and nothing of the rest.
const mine = { archivedAt: null, participants: { some: { character: { userId: req.user.id } } } };
const encounters = await prisma.encounter.findMany({
where: { campaignId: req.campaign.id, ...(isDM ? {} : mine) },
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'desc' }],
});
// 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(),
locationId: z.string().optional().nullable(),
});
router.post('/:id/encounters', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = createEncounterSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (parsed.data.locationId) {
const location = await prisma.location.findFirst({ where: { id: parsed.data.locationId, campaignId: req.campaign.id } });
if (!location) return res.status(400).json({ error: 'That location is not part of this campaign.' });
}
// A new encounter goes to the top of the campaign's order.
const first = await prisma.encounter.aggregate({ where: { campaignId: req.campaign.id }, _min: { sortOrder: true } });
const encounter = await prisma.encounter.create({
data: { ...parsed.data, campaignId: req.campaign.id, sortOrder: (first._min.sortOrder ?? 1) - 1 },
});
res.status(201).json({ encounter });
} catch (err) {
next(err);
}
});
const encounterOrderSchema = z.object({ encounterIds: z.array(z.string()).min(1).max(1000) });
// Sets the campaign's own encounter order: the ids given take positions
// 0, 1, 2... in the order sent.
router.put('/:id/encounters/order', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = encounterOrderSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { encounterIds } = parsed.data;
const owned = await prisma.encounter.count({ where: { id: { in: encounterIds }, campaignId: req.campaign.id } });
if (new Set(encounterIds).size !== encounterIds.length || owned !== encounterIds.length) {
return res.status(400).json({ error: 'Send each encounter of this campaign once.' });
}
await prisma.$transaction(
encounterIds.map((id, sortOrder) => prisma.encounter.update({ where: { id }, data: { sortOrder } }))
);
res.status(204).end();
} 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 },
include: { wares: { include: WARE_INCLUDE, orderBy: { createdAt: 'asc' } } },
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).max(50).optional().nullable(),
maxHp: z.number().int().min(1).max(100000).optional().nullable(),
attackBonus: z.number().int().min(-20).max(50).optional().nullable(),
damageDice: z.string().max(20).optional().nullable(),
// The money changer's rate: exchangeGold gold for exchangeCash cash. Both
// null for an NPC who does not change money.
exchangeGold: z.number().int().min(1).max(1000000).optional().nullable(),
exchangeCash: z.number().int().min(1).max(1000000).optional().nullable(),
});
// A rate has two sides: both are given, or both are cleared.
function halfARate(data) {
const sides = [data.exchangeGold, data.exchangeCash];
return sides.some((side) => side === undefined) !== sides.every((side) => side === undefined) || (sides[0] === null) !== (sides[1] === null);
}
const HALF_A_RATE = 'An exchange rate needs both sides: so much gold for so much cash.';
const WARE_INCLUDE = { weapon: true, item: true };
// Open encounter pages refetch: what is for sale in a scene just changed.
function emitTradeChanged(req) {
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('encounter:participant-updated', {});
}
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() });
if (halfARate(parsed.data)) return res.status(400).json({ error: HALF_A_RATE });
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() });
if (halfARate(parsed.data)) return res.status(400).json({ error: HALF_A_RATE });
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' });
emitTradeChanged(req);
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
// ---------------------------------------------------------------------------
router.get('/:id/notes', requireCampaignMember(), async (req, res, next) => {
try {
const isDM = req.membership.role === 'DM';
const notes = await prisma.note.findMany({
where: {
campaignId: req.campaign.id,
...(isDM ? {} : { OR: [{ visibility: 'SHARED' }, { authorId: req.user.id }] }),
},
include: { author: { select: { displayName: true } } },
orderBy: { createdAt: 'desc' },
});
res.json({ notes });
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Locations — DM-managed, used to track where each character currently is.
// A player only sees the places one of their own characters has been to.
// ---------------------------------------------------------------------------
router.get('/:id/locations', requireCampaignMember(), async (req, res, next) => {
try {
const where = { campaignId: req.campaign.id };
if (req.membership.role !== 'DM') {
where.id = { in: [...(await visitedLocationIds(prisma, req.user.id, req.campaign.id))] };
}
const locations = await prisma.location.findMany({ where, orderBy: { name: 'asc' } });
res.json({ locations });
} catch (err) {
next(err);
}
});
const locationSchema = z.object({
name: z.string().min(1).max(80),
description: z.string().max(2000).optional().nullable(),
});
router.post('/:id/locations', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = locationSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const location = await prisma.location.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
res.status(201).json({ location });
} catch (err) {
next(err);
}
});
router.patch('/:id/locations/:locationId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = locationSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
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);
}
});
router.delete('/:id/locations/:locationId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
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);
}
});
// ---------------------------------------------------------------------------
// Wares — weapons and items for sale, by an NPC or at an encounter itself.
// Only the DM sets them up. Players see them, and buy, on the encounter page
// (encounters.routes.js); an NPC's wares go wherever the NPC does.
// ---------------------------------------------------------------------------
const wareSchema = z
.object({
npcId: z.string().optional(),
encounterId: z.string().optional(),
weaponId: z.string().optional(),
itemId: z.string().optional(),
price: z.number().int().min(1).max(1000000),
currency: z.enum(CURRENCIES).default('GOLD'),
level: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
stock: z.number().int().min(0).max(9999).optional().nullable(), // null: no limit
})
.refine((data) => Boolean(data.npcId) !== Boolean(data.encounterId), { message: 'Say who sells it: an NPC or an encounter, not both' })
.refine((data) => Boolean(data.weaponId) !== Boolean(data.itemId), { message: 'Pick one weapon or one item to sell' });
router.post('/:id/wares', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = wareSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const data = parsed.data;
const inCampaign = async (model, id) => (id ? prisma[model].findFirst({ where: { id, campaignId: req.campaign.id } }) : null);
const seller = (await inCampaign('npc', data.npcId)) || (await inCampaign('encounter', data.encounterId));
if (!seller) return res.status(400).json({ error: 'That seller is not part of this campaign.' });
const entry = (await inCampaign('weapon', data.weaponId)) || (await inCampaign('item', data.itemId));
if (!entry) return res.status(400).json({ error: `That ${data.weaponId ? 'weapon' : 'item'} is not part of this campaign.` });
const level = data.level ?? entry.minLevel;
if (level < entry.minLevel) {
return res.status(400).json({ error: `${entry.name} starts at level ${entry.minLevel} and can't go below it.` });
}
const ware = await prisma.saleOffer.create({ data: { ...data, level, campaignId: req.campaign.id }, include: WARE_INCLUDE });
emitTradeChanged(req);
res.status(201).json({ ware });
} catch (err) {
next(err);
}
});
// The price and what is left can change; what is sold, and by whom, cannot.
const patchWareSchema = z.object({
price: z.number().int().min(1).max(1000000).optional(),
currency: z.enum(CURRENCIES).optional(),
stock: z.number().int().min(0).max(9999).nullable().optional(),
});
router.patch('/:id/wares/:wareId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = patchWareSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (!(await updatePoolEntry('saleOffer', req.params.wareId, req.campaign.id, parsed.data))) {
return res.status(404).json({ error: 'Nothing like that is for sale in this campaign' });
}
emitTradeChanged(req);
res.json({ ware: await prisma.saleOffer.findUnique({ where: { id: req.params.wareId }, include: WARE_INCLUDE }) });
} catch (err) {
next(err);
}
});
router.delete('/:id/wares/:wareId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
if (!(await deletePoolEntry('saleOffer', req.params.wareId, req.campaign.id))) {
return res.status(404).json({ error: 'Nothing like that is for sale in this campaign' });
}
emitTradeChanged(req);
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Default content library — static SRD-style weapons/spells/monsters any
// campaign can pull from, instead of the DM hand-typing everything. See
// backend/src/game/data/{weapons,spells,monsters}Library.js for the sets.
// ---------------------------------------------------------------------------
// A library entry goes into a campaign once: it is taken for as long as the
// pool holds a row by its name, and free again when that row is renamed or
// deleted.
async function inPool(model, campaignId, name) {
const row = await prisma[model].findFirst({ where: { campaignId, name: { equals: name, mode: 'insensitive' } }, select: { id: true } });
return Boolean(row);
}
router.get('/:id/library', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
res.json({ weapons: WEAPON_LIBRARY, items: ITEM_LIBRARY, spells: SPELL_LIBRARY, monsters: MONSTER_LIBRARY });
} catch (err) {
next(err);
}
});
router.post('/:id/weapons/from-library', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = z.object({ key: z.string() }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const template = WEAPON_LIBRARY.find((w) => w.key === parsed.data.key);
if (!template) return res.status(404).json({ error: 'Unknown library weapon.' });
if (await inPool('weapon', req.campaign.id, template.name)) {
return res.status(409).json({ error: `${template.name} is already in this campaign.` });
}
const { key, category, ...data } = template;
const weapon = await prisma.weapon.create({ data: { ...data, campaignId: req.campaign.id } });
res.status(201).json({ weapon });
} catch (err) {
next(err);
}
});
router.post('/:id/items/from-library', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = z.object({ key: z.string() }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const template = ITEM_LIBRARY.find((i) => i.key === parsed.data.key);
if (!template) return res.status(404).json({ error: 'Unknown library item.' });
if (await inPool('item', req.campaign.id, template.name)) {
return res.status(409).json({ error: `${template.name} is already in this campaign.` });
}
const { key, category, ...data } = template;
const item = await prisma.item.create({ data: { ...data, campaignId: req.campaign.id } });
res.status(201).json({ item });
} catch (err) {
next(err);
}
});
router.post('/:id/spells/from-library', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = z.object({ key: z.string() }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const template = SPELL_LIBRARY.find((s) => s.key === parsed.data.key);
if (!template) return res.status(404).json({ error: 'Unknown library spell.' });
if (await inPool('spell', req.campaign.id, template.name)) {
return res.status(409).json({ error: `${template.name} is already in this campaign.` });
}
const { key, classes, ...data } = template;
const spell = await prisma.spell.create({ data: { ...data, campaignId: req.campaign.id } });
res.status(201).json({ spell });
} catch (err) {
next(err);
}
});
router.post('/:id/monsters/from-library', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = z.object({ key: z.string() }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const template = MONSTER_LIBRARY.find((m) => m.key === parsed.data.key);
if (!template) return res.status(404).json({ error: 'Unknown library monster.' });
if (await inPool('monster', req.campaign.id, template.name)) {
return res.status(409).json({ error: `${template.name} is already in this campaign.` });
}
const { key, ...data } = template;
const monster = await prisma.monster.create({ data: { ...data, campaignId: req.campaign.id } });
res.status(201).json({ monster });
} catch (err) {
next(err);
}
});
module.exports = router;