V1.0.1: Aldenfell campaign seed, content library, party overview
- Seed now resets the database and seeds the Aldenfell campaign from the campaign book: admin DM user, default weapons, locations, bestiary, pre-built encounters, and DM/shared notes - Default weapon/spell/monster library, character profile fields, locations and dice mode (new migration) - Party overview page, pagination, info tips, build preview calc - Remove stale demo-login hint; notes preserve line breaks Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -197,3 +197,258 @@ describe('campaigns + characters + build flow', () => {
|
||||
expect(forbiddenRes.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
async function setupCampaign(namePrefix) {
|
||||
const dmRegister = await request(app)
|
||||
.post('/auth/register')
|
||||
.send({ email: uniqueEmail(`${namePrefix}-dm`), password: 'password123', displayName: 'DM' });
|
||||
const dmToken = dmRegister.body.token;
|
||||
cleanupUserIds.push(dmRegister.body.user.id);
|
||||
|
||||
const playerRegister = await request(app)
|
||||
.post('/auth/register')
|
||||
.send({ email: uniqueEmail(`${namePrefix}-player`), password: 'password123', displayName: 'Player' });
|
||||
const playerToken = playerRegister.body.token;
|
||||
cleanupUserIds.push(playerRegister.body.user.id);
|
||||
|
||||
const campaignRes = await request(app)
|
||||
.post('/campaigns')
|
||||
.set('Authorization', `Bearer ${dmToken}`)
|
||||
.send({ name: `${namePrefix} Campaign`, startingItemCount: 0, startingSpellCount: 0, skipMotivationRoll: true });
|
||||
const campaign = campaignRes.body.campaign;
|
||||
cleanupCampaignIds.push(campaign.id);
|
||||
|
||||
await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set('Authorization', `Bearer ${playerToken}`);
|
||||
|
||||
return {
|
||||
dmAuth: { Authorization: `Bearer ${dmToken}` },
|
||||
playerAuth: { Authorization: `Bearer ${playerToken}` },
|
||||
campaign,
|
||||
};
|
||||
}
|
||||
|
||||
describe('dice mode', () => {
|
||||
itIfDb('rejects an out-of-range physical roll and accepts a valid one, matching the digital shape', async () => {
|
||||
const { dmAuth, campaign } = await setupCampaign('dicemode');
|
||||
const characterRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/characters`)
|
||||
.set(dmAuth)
|
||||
.send({ name: 'Physical Roller' });
|
||||
const characterId = characterRes.body.character.id;
|
||||
|
||||
const modeRes = await request(app).patch(`/characters/${characterId}/build/dice-mode`).set(dmAuth).send({ diceMode: 'PHYSICAL' });
|
||||
expect(modeRes.status).toBe(200);
|
||||
expect(modeRes.body.diceMode).toBe('PHYSICAL');
|
||||
|
||||
const tooHigh = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ value: 7 });
|
||||
expect(tooHigh.status).toBe(400);
|
||||
|
||||
const validRoll = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth).send({ value: 3 });
|
||||
expect(validRoll.status).toBe(200);
|
||||
expect(validRoll.body.buildState.speciesRoll).toBe(3);
|
||||
|
||||
// Dice mode can no longer change once rolling has started.
|
||||
const lateSwitch = await request(app).patch(`/characters/${characterId}/build/dice-mode`).set(dmAuth).send({ diceMode: 'DIGITAL' });
|
||||
expect(lateSwitch.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('auto-generated skill proficiencies', () => {
|
||||
itIfDb('assigns the class\'s SRD skill count automatically once ability scores are locked in', async () => {
|
||||
const { dmAuth, campaign } = await setupCampaign('autoskill');
|
||||
const characterRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/characters`)
|
||||
.set(dmAuth)
|
||||
.send({ name: 'Auto Skills' });
|
||||
const characterId = characterRes.body.character.id;
|
||||
|
||||
let rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth);
|
||||
const species = rollRes.body.buildState.speciesChoices.options[0];
|
||||
await request(app)
|
||||
.post(`/characters/${characterId}/build/choose`)
|
||||
.set(dmAuth)
|
||||
.send(species === 'HALF_ELF' ? { species, halfElfBonusAbilities: ['STR', 'INT'] } : { species });
|
||||
|
||||
rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth);
|
||||
while (rollRes.body.buildState.classChoices.type === 'reroll') {
|
||||
rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth);
|
||||
}
|
||||
const characterClass = rollRes.body.buildState.classChoices.options[0];
|
||||
await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ characterClass });
|
||||
|
||||
await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth);
|
||||
const scoresRes = await request(app)
|
||||
.post(`/characters/${characterId}/build/choose`)
|
||||
.set(dmAuth)
|
||||
.send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } });
|
||||
|
||||
expect(scoresRes.body.buildStage).toBe('ASSIGNING_PROFICIENCIES');
|
||||
expect(scoresRes.body.buildState.skillProficiencies.length).toBeGreaterThan(0);
|
||||
expect(new Set(scoresRes.body.buildState.skillProficiencies.map((s) => s.skill)).size).toBe(
|
||||
scoresRes.body.buildState.skillProficiencies.length
|
||||
); // no duplicates
|
||||
});
|
||||
});
|
||||
|
||||
describe('locations', () => {
|
||||
itIfDb('DM manages locations; a player cannot', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('locations');
|
||||
|
||||
const createRes = await request(app).post(`/campaigns/${campaign.id}/locations`).set(dmAuth).send({ name: 'The Rusty Tankard' });
|
||||
expect(createRes.status).toBe(201);
|
||||
const locationId = createRes.body.location.id;
|
||||
|
||||
const playerCreateRes = await request(app).post(`/campaigns/${campaign.id}/locations`).set(playerAuth).send({ name: 'Nope' });
|
||||
expect(playerCreateRes.status).toBe(403);
|
||||
|
||||
const listRes = await request(app).get(`/campaigns/${campaign.id}/locations`).set(playerAuth);
|
||||
expect(listRes.status).toBe(200);
|
||||
expect(listRes.body.locations.map((l) => l.id)).toContain(locationId);
|
||||
|
||||
const charRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/characters`)
|
||||
.set(playerAuth)
|
||||
.send({ name: 'Wanderer' });
|
||||
const patchRes = await request(app)
|
||||
.patch(`/characters/${charRes.body.character.id}`)
|
||||
.set(playerAuth)
|
||||
.send({ currentLocationId: locationId });
|
||||
expect(patchRes.status).toBe(200);
|
||||
expect(patchRes.body.character.currentLocationId).toBe(locationId);
|
||||
});
|
||||
});
|
||||
|
||||
describe('default content library', () => {
|
||||
itIfDb('lists library entries and copies one into the campaign', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('library');
|
||||
|
||||
const listRes = await request(app).get(`/campaigns/${campaign.id}/library`).set(playerAuth);
|
||||
expect(listRes.status).toBe(200);
|
||||
expect(listRes.body.weapons.length).toBeGreaterThan(20);
|
||||
expect(listRes.body.spells.length).toBeGreaterThan(50);
|
||||
expect(listRes.body.monsters.length).toBeGreaterThan(20);
|
||||
|
||||
const addRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/weapons/from-library`)
|
||||
.set(dmAuth)
|
||||
.send({ key: 'longsword' });
|
||||
expect(addRes.status).toBe(201);
|
||||
expect(addRes.body.weapon.name).toBe('Longsword');
|
||||
expect(addRes.body.weapon.campaignId).toBe(campaign.id);
|
||||
|
||||
const playerAddRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/monsters/from-library`)
|
||||
.set(playerAuth)
|
||||
.send({ key: 'goblin' });
|
||||
expect(playerAddRes.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('private notes', () => {
|
||||
itIfDb('is visible to the owning player but hidden from the DM and other players', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('privatenotes');
|
||||
|
||||
const charRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/characters`)
|
||||
.set(playerAuth)
|
||||
.send({ name: 'Secretive' });
|
||||
const characterId = charRes.body.character.id;
|
||||
|
||||
const patchRes = await request(app)
|
||||
.patch(`/characters/${characterId}`)
|
||||
.set(playerAuth)
|
||||
.send({ privateNotes: 'The amulet is cursed.' });
|
||||
expect(patchRes.status).toBe(200);
|
||||
expect(patchRes.body.character.privateNotes).toBe('The amulet is cursed.');
|
||||
|
||||
const ownerReadRes = await request(app).get(`/characters/${characterId}`).set(playerAuth);
|
||||
expect(ownerReadRes.body.character.privateNotes).toBe('The amulet is cursed.');
|
||||
|
||||
const dmReadRes = await request(app).get(`/characters/${characterId}`).set(dmAuth);
|
||||
expect(dmReadRes.body.character.privateNotes).toBeUndefined();
|
||||
|
||||
const dmSetAttempt = await request(app)
|
||||
.patch(`/characters/${characterId}`)
|
||||
.set(dmAuth)
|
||||
.send({ privateNotes: 'DM trying to snoop' });
|
||||
expect(dmSetAttempt.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('DM-only campaign notes', () => {
|
||||
itIfDb('only the DM can post one, and only the DM can read it back', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('dmnotes');
|
||||
|
||||
const playerAttempt = await request(app)
|
||||
.post('/notes')
|
||||
.set(playerAuth)
|
||||
.send({ campaignId: campaign.id, body: 'Sneaky player note', visibility: 'DM_ONLY' });
|
||||
expect(playerAttempt.status).toBe(403);
|
||||
|
||||
const dmNoteRes = await request(app)
|
||||
.post('/notes')
|
||||
.set(dmAuth)
|
||||
.send({ campaignId: campaign.id, body: 'The mayor is the villain.', visibility: 'DM_ONLY' });
|
||||
expect(dmNoteRes.status).toBe(201);
|
||||
|
||||
const dmListRes = await request(app).get(`/campaigns/${campaign.id}/notes`).set(dmAuth);
|
||||
expect(dmListRes.body.notes.some((n) => n.body === 'The mayor is the villain.')).toBe(true);
|
||||
|
||||
const playerListRes = await request(app).get(`/campaigns/${campaign.id}/notes`).set(playerAuth);
|
||||
expect(playerListRes.body.notes.some((n) => n.body === 'The mayor is the villain.')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('encounter combat info', () => {
|
||||
itIfDb('shows a character combatant\'s weapons to every campaign member, not just the DM', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('encountercombat');
|
||||
|
||||
const weaponRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/weapons/from-library`)
|
||||
.set(dmAuth)
|
||||
.send({ key: 'dagger' });
|
||||
const weaponId = weaponRes.body.weapon.id;
|
||||
|
||||
const characterRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/characters`)
|
||||
.set(dmAuth)
|
||||
.send({ name: 'Combatant' });
|
||||
const characterId = characterRes.body.character.id;
|
||||
|
||||
// Fast-path the build with skipMotivationRoll + a single wildcard-free walk.
|
||||
let rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth);
|
||||
const species = rollRes.body.buildState.speciesChoices.options[0];
|
||||
await request(app)
|
||||
.post(`/characters/${characterId}/build/choose`)
|
||||
.set(dmAuth)
|
||||
.send(species === 'HALF_ELF' ? { species, halfElfBonusAbilities: ['STR', 'INT'] } : { species });
|
||||
rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth);
|
||||
while (rollRes.body.buildState.classChoices.type === 'reroll') {
|
||||
rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth);
|
||||
}
|
||||
const characterClass = rollRes.body.buildState.classChoices.options[0];
|
||||
await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ characterClass });
|
||||
await request(app).post(`/characters/${characterId}/build/roll`).set(dmAuth);
|
||||
await request(app)
|
||||
.post(`/characters/${characterId}/build/choose`)
|
||||
.set(dmAuth)
|
||||
.send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } });
|
||||
await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({});
|
||||
await request(app).post(`/characters/${characterId}/build/choose`).set(dmAuth).send({ weaponIds: [], spellIds: [] });
|
||||
await request(app).post(`/characters/${characterId}/build/finalize`).set(dmAuth);
|
||||
|
||||
await request(app).post(`/characters/${characterId}/weapons`).set(dmAuth).send({ weaponId });
|
||||
await request(app).patch(`/characters/${characterId}/weapons/${weaponId}`).set(dmAuth).send({ equipped: true });
|
||||
|
||||
const encounterRes = await request(app).post(`/campaigns/${campaign.id}/encounters`).set(dmAuth).send({ name: 'Ambush' });
|
||||
const encounterId = encounterRes.body.encounter.id;
|
||||
await request(app).post(`/encounters/${encounterId}/participants`).set(dmAuth).send({ characterId, initiative: 10 });
|
||||
|
||||
const playerViewRes = await request(app).get(`/encounters/${encounterId}`).set(playerAuth);
|
||||
expect(playerViewRes.status).toBe(200);
|
||||
const participant = playerViewRes.body.encounter.participants[0];
|
||||
expect(participant.characterCombatInfo.weapons).toHaveLength(1);
|
||||
expect(participant.characterCombatInfo.weapons[0].name).toBe('Dagger');
|
||||
expect(typeof participant.characterCombatInfo.weapons[0].attackBonus).toBe('number');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCampaignMember, requireDM } = require('../middleware/campaignAccess');
|
||||
const { generateInviteCode } = require('../utils/inviteCode');
|
||||
const { computeCharacterSheet } = require('../game/calculations');
|
||||
const { WEAPON_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -168,6 +169,8 @@ function characterSummary(character) {
|
||||
tempHp: character.tempHp,
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -175,7 +178,7 @@ router.get('/:id/characters', requireCampaignMember(), async (req, res, next) =>
|
||||
try {
|
||||
const characters = await prisma.character.findMany({
|
||||
where: { campaignId: req.campaign.id },
|
||||
include: { skillProficiencies: true, saveProficiencies: true },
|
||||
include: { skillProficiencies: true, saveProficiencies: true, currentLocation: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
res.json({ characters: characters.map(characterSummary) });
|
||||
@@ -426,4 +429,109 @@ router.get('/:id/notes', requireCampaignMember(), async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Locations — DM-managed, used to track where each character currently is
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/locations', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const locations = await prisma.location.findMany({ where: { campaignId: req.campaign.id }, 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 prisma.location.update({ where: { id: req.params.locationId }, data: parsed.data });
|
||||
res.json({ location });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/locations/:locationId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.location.delete({ where: { id: req.params.locationId } });
|
||||
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.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/library', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
res.json({ weapons: WEAPON_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.' });
|
||||
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/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.' });
|
||||
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.' });
|
||||
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;
|
||||
|
||||
@@ -15,6 +15,8 @@ const {
|
||||
rollAbilityScore,
|
||||
speciesChoicesForRoll,
|
||||
classChoicesForRoll,
|
||||
autoSelectSkills,
|
||||
validateManualRoll,
|
||||
MOTIVATION_TABLE,
|
||||
} = require('../game/buildFlow');
|
||||
const { SKILLS } = require('../game/data/skills');
|
||||
@@ -32,11 +34,14 @@ async function loadFullCharacter(id) {
|
||||
inventoryItems: true,
|
||||
weapons: { include: { weapon: true } },
|
||||
spells: { include: { spell: true } },
|
||||
currentLocation: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function serializeCharacter(character) {
|
||||
// privateNotes is a real privacy boundary, not a UI hide — it's only ever
|
||||
// included in the payload for the character's own owning player.
|
||||
function serializeCharacter(character, isOwner) {
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
return {
|
||||
id: character.id,
|
||||
@@ -63,6 +68,12 @@ function serializeCharacter(character) {
|
||||
tempHp: character.tempHp,
|
||||
armorBonus: character.armorBonus,
|
||||
specialAbilities: character.specialAbilities,
|
||||
background: character.background,
|
||||
appearance: character.appearance,
|
||||
privateNotes: isOwner ? character.privateNotes : undefined,
|
||||
diceMode: character.diceMode,
|
||||
currentLocationId: character.currentLocationId,
|
||||
currentLocation: character.currentLocation || null,
|
||||
gold: character.gold,
|
||||
buildStage: character.buildStage,
|
||||
buildState: character.buildStage === 'COMPLETE' ? null : character.buildState,
|
||||
@@ -78,7 +89,7 @@ function serializeCharacter(character) {
|
||||
router.get('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
res.json({ character: serializeCharacter(character) });
|
||||
res.json({ character: serializeCharacter(character, req.isOwner) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -91,6 +102,10 @@ const patchCharacterSchema = z.object({
|
||||
armorBonus: z.number().int().min(0).optional(),
|
||||
speedOverride: z.number().int().min(0).nullable().optional(),
|
||||
specialAbilities: z.string().max(4000).nullable().optional(),
|
||||
background: z.string().max(4000).nullable().optional(),
|
||||
appearance: z.string().max(4000).nullable().optional(),
|
||||
privateNotes: z.string().max(4000).nullable().optional(),
|
||||
currentLocationId: z.string().nullable().optional(),
|
||||
gold: z.number().int().min(0).optional(),
|
||||
level: z.number().int().min(1).max(20).optional(),
|
||||
xp: z.number().int().min(0).optional(),
|
||||
@@ -101,12 +116,28 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
|
||||
const parsed = patchCharacterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
// privateNotes is for the owning player only — a DM editing someone
|
||||
// else's character (or another player, though write access already
|
||||
// blocks that) should never be able to set it through this route.
|
||||
if (parsed.data.privateNotes !== undefined && !req.isOwner) {
|
||||
return res.status(403).json({ error: 'Only the owning player can edit private notes.' });
|
||||
}
|
||||
|
||||
if (parsed.data.currentLocationId) {
|
||||
const location = await prisma.location.findUnique({ where: { id: parsed.data.currentLocationId } });
|
||||
if (!location || location.campaignId !== req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'That location is not part of this campaign.' });
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({ where: { id: req.character.id }, data: parsed.data });
|
||||
const full = await loadFullCharacter(updated.id);
|
||||
const payload = serializeCharacter(full);
|
||||
|
||||
req.app.get('io').to(`campaign:${updated.campaignId}`).emit('character:updated', { character: payload });
|
||||
res.json({ character: payload });
|
||||
// Broadcast payload never includes privateNotes — a socket room has
|
||||
// every campaign member in it, not just the owner. Only the direct HTTP
|
||||
// response (below) is allowed to include it.
|
||||
req.app.get('io').to(`campaign:${updated.campaignId}`).emit('character:updated', { character: serializeCharacter(full, false) });
|
||||
res.json({ character: serializeCharacter(full, req.isOwner) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -126,38 +157,90 @@ router.delete('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
// Roll-Your-Character build flow — docs/ROLL_YOUR_CHARACTER.md
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Digital mode rolls server-side (crypto.randomInt) as before. Physical mode
|
||||
// requires the value(s) the roller typed in from their real dice — this
|
||||
// helper validates them against the step's real die range/count and throws
|
||||
// a user-facing error string on failure, otherwise returns the value(s) in
|
||||
// the exact same shape the digital path would have produced.
|
||||
function resolveSingleRoll(character, body, sides) {
|
||||
if (character.diceMode !== 'PHYSICAL') return rollDie(sides);
|
||||
const value = Number(body?.value);
|
||||
if (!validateManualRoll(sides, value)) {
|
||||
throw new Error(`Enter the d${sides} you rolled — a whole number from 1 to ${sides}.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function resolveAbilityRolls(character, body) {
|
||||
if (character.diceMode !== 'PHYSICAL') {
|
||||
return Array.from({ length: 6 }, () => rollAbilityScore());
|
||||
}
|
||||
const sets = body?.abilitySets;
|
||||
if (!Array.isArray(sets) || sets.length !== 6) {
|
||||
throw new Error('Enter all six 4d6 sets you rolled at the table.');
|
||||
}
|
||||
return sets.map((dice, i) => {
|
||||
if (!Array.isArray(dice) || dice.length !== 4 || !dice.every((d) => validateManualRoll(6, d))) {
|
||||
throw new Error(`Ability set ${i + 1}: enter four d6 results, each a whole number from 1 to 6.`);
|
||||
}
|
||||
return abilityScoreFromDice(dice);
|
||||
});
|
||||
}
|
||||
|
||||
router.patch('/:id/build/dice-mode', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
const parsed = z.object({ diceMode: z.enum(['DIGITAL', 'PHYSICAL']) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const alreadyRolling = character.buildStage !== 'ROLLING_SPECIES' || Boolean((character.buildState || {}).speciesRoll);
|
||||
if (alreadyRolling) {
|
||||
return res.status(400).json({ error: 'Dice mode can only be chosen before the first roll of the build.' });
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({ where: { id: character.id }, data: { diceMode: parsed.data.diceMode } });
|
||||
res.json({ diceMode: updated.diceMode });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
const stage = character.buildStage;
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
|
||||
if (stage === 'ROLLING_SPECIES') {
|
||||
const roll = rollDie(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) {
|
||||
return res.status(400).json({ error: 'Class die already rolled for this character — submit a choice, or reroll if the current roll allows it.' });
|
||||
try {
|
||||
if (stage === 'ROLLING_SPECIES') {
|
||||
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) {
|
||||
return res.status(400).json({ error: 'Class die already rolled for this character — submit a choice, or reroll if the current roll allows it.' });
|
||||
}
|
||||
const roll = resolveSingleRoll(character, req.body, 8);
|
||||
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.' });
|
||||
}
|
||||
buildState.abilityRolls = resolveAbilityRolls(character, req.body);
|
||||
} else {
|
||||
return res.status(400).json({ error: `No die roll is required at the "${stage}" step.` });
|
||||
}
|
||||
const roll = rollDie(8);
|
||||
buildState.classRoll = roll;
|
||||
buildState.classChoices = classChoicesForRoll(roll);
|
||||
delete buildState.characterClass;
|
||||
} else if (stage === 'ROLLING_MOTIVATION') {
|
||||
const roll = rollDie(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.' });
|
||||
}
|
||||
buildState.abilityRolls = Array.from({ length: 6 }, () => rollAbilityScore());
|
||||
} else {
|
||||
return res.status(400).json({ error: `No die roll is required at the "${stage}" step.` });
|
||||
} catch (rollErr) {
|
||||
return res.status(400).json({ error: rollErr.message });
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({ where: { id: character.id }, data: { buildState } });
|
||||
@@ -186,14 +269,19 @@ const chooseSchemas = {
|
||||
CHA: z.number().int().min(0).max(5),
|
||||
}),
|
||||
}),
|
||||
// Skill proficiencies are now auto-generated (see autoSelectSkills, applied
|
||||
// when this stage is entered from ASSIGNING_SCORES below) — this payload is
|
||||
// an optional DM correction, not the normal path.
|
||||
ASSIGNING_PROFICIENCIES: z.object({
|
||||
skillProficiencies: z.array(
|
||||
z.object({
|
||||
skill: z.enum(Object.keys(SKILLS)),
|
||||
proficient: z.boolean().default(true),
|
||||
expertise: z.boolean().default(false),
|
||||
})
|
||||
),
|
||||
skillProficiencies: z
|
||||
.array(
|
||||
z.object({
|
||||
skill: z.enum(Object.keys(SKILLS)),
|
||||
proficient: z.boolean().default(true),
|
||||
expertise: z.boolean().default(false),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
}),
|
||||
CHOOSING_EQUIPMENT: z.object({
|
||||
weaponIds: z.array(z.string()).default([]),
|
||||
@@ -274,8 +362,16 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
return res.status(400).json({ error: 'Each of the 6 rolled scores must be assigned to exactly one ability.' });
|
||||
}
|
||||
buildState.abilityAssignments = assignments;
|
||||
// Skill proficiencies are auto-generated per the class's SRD "choose N"
|
||||
// rule the moment ability scores are locked in, so the next step has
|
||||
// something to show immediately rather than an empty picker.
|
||||
buildState.skillProficiencies = autoSelectSkills(buildState.characterClass);
|
||||
} else if (stage === 'ASSIGNING_PROFICIENCIES') {
|
||||
buildState.skillProficiencies = parsed.data.skillProficiencies;
|
||||
// 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_EQUIPMENT') {
|
||||
const { weaponIds, spellIds } = parsed.data;
|
||||
const maxItems = req.campaign.startingItemCount;
|
||||
@@ -373,9 +469,8 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
|
||||
});
|
||||
|
||||
const full = await loadFullCharacter(result.id);
|
||||
const payload = serializeCharacter(full);
|
||||
req.app.get('io').to(`campaign:${result.campaignId}`).emit('character:created', { character: payload });
|
||||
res.json({ character: payload });
|
||||
req.app.get('io').to(`campaign:${result.campaignId}`).emit('character:created', { character: serializeCharacter(full, false) });
|
||||
res.json({ character: serializeCharacter(full, req.isOwner) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
const { computeCharacterSheet } = require('../game/calculations');
|
||||
const { computeCharacterSheet, computeWeaponStats } = require('../game/calculations');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -26,19 +26,60 @@ 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 };
|
||||
}
|
||||
|
||||
async function serializeEncounter(encounterId) {
|
||||
return prisma.encounter.findUnique({
|
||||
const encounter = await prisma.encounter.findUnique({
|
||||
where: { id: encounterId },
|
||||
include: {
|
||||
participants: {
|
||||
include: {
|
||||
character: { select: { id: true, name: true } },
|
||||
character: {
|
||||
include: {
|
||||
skillProficiencies: true,
|
||||
saveProficiencies: true,
|
||||
weapons: { include: { weapon: true } },
|
||||
spells: { include: { spell: true } },
|
||||
},
|
||||
},
|
||||
monster: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { initiative: 'desc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
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),
|
||||
};
|
||||
});
|
||||
return encounter;
|
||||
}
|
||||
|
||||
router.get('/:id', requireEncounterAccess, async (req, res, next) => {
|
||||
|
||||
@@ -34,6 +34,12 @@ router.post('/', async (req, res, next) => {
|
||||
if (resolvedCampaignId) {
|
||||
const membership = await loadCampaignMembership(req.user.id, resolvedCampaignId);
|
||||
if (!membership) return res.status(403).json({ error: 'Not a member of this campaign' });
|
||||
|
||||
// A campaign-level (not character-level) DM_ONLY note is the DM's
|
||||
// private scratchpad — only the DM may create one of those.
|
||||
if (visibility === 'DM_ONLY' && !characterId && membership.role !== 'DM') {
|
||||
return res.status(403).json({ error: 'Only the DM can post a DM-only campaign note.' });
|
||||
}
|
||||
}
|
||||
|
||||
const note = await prisma.note.create({
|
||||
|
||||
Reference in New Issue
Block a user