Initial commit
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
// Integration tests exercising the real Express app + a real Postgres
|
||||
// database through Prisma. These need DATABASE_URL pointed at a reachable,
|
||||
// migrated database (see /README.md) — they are skipped automatically if the
|
||||
// DB isn't reachable so `npm test` still passes in an environment with no DB.
|
||||
const request = require('supertest');
|
||||
const crypto = require('crypto');
|
||||
const prisma = require('../db');
|
||||
const { createApp } = require('../app');
|
||||
|
||||
const app = createApp();
|
||||
app.set('io', { to: () => ({ emit: () => {} }) }); // stub Socket.io for tests
|
||||
|
||||
let dbAvailable = true;
|
||||
const cleanupCampaignIds = [];
|
||||
const cleanupUserIds = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
try {
|
||||
await prisma.$connect();
|
||||
} catch {
|
||||
dbAvailable = false;
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (dbAvailable) {
|
||||
for (const id of cleanupCampaignIds) {
|
||||
await prisma.campaign.delete({ where: { id } }).catch(() => {});
|
||||
}
|
||||
for (const id of cleanupUserIds) {
|
||||
await prisma.user.delete({ where: { id } }).catch(() => {});
|
||||
}
|
||||
}
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
function uniqueEmail(prefix) {
|
||||
return `${prefix}-${crypto.randomUUID()}@test.local`;
|
||||
}
|
||||
|
||||
function itIfDb(name, fn) {
|
||||
test(name, async () => {
|
||||
if (!dbAvailable) {
|
||||
console.warn(`Skipping "${name}" — no reachable database (set DATABASE_URL and run migrations).`);
|
||||
return;
|
||||
}
|
||||
await fn();
|
||||
});
|
||||
}
|
||||
|
||||
describe('auth', () => {
|
||||
itIfDb('registers, logs in, and reads the current user', async () => {
|
||||
const email = uniqueEmail('dm');
|
||||
const registerRes = await request(app)
|
||||
.post('/auth/register')
|
||||
.send({ email, password: 'password123', displayName: 'Test DM' });
|
||||
expect(registerRes.status).toBe(201);
|
||||
expect(registerRes.body.token).toBeTruthy();
|
||||
cleanupUserIds.push(registerRes.body.user.id);
|
||||
|
||||
const loginRes = await request(app).post('/auth/login').send({ email, password: 'password123' });
|
||||
expect(loginRes.status).toBe(200);
|
||||
|
||||
const meRes = await request(app).get('/auth/me').set('Authorization', `Bearer ${loginRes.body.token}`);
|
||||
expect(meRes.status).toBe(200);
|
||||
expect(meRes.body.user.email).toBe(email);
|
||||
});
|
||||
|
||||
itIfDb('rejects a bad password', async () => {
|
||||
const email = uniqueEmail('baduser');
|
||||
const registerRes = await request(app)
|
||||
.post('/auth/register')
|
||||
.send({ email, password: 'password123', displayName: 'Bad Login' });
|
||||
cleanupUserIds.push(registerRes.body.user.id);
|
||||
|
||||
const loginRes = await request(app).post('/auth/login').send({ email, password: 'wrong-password' });
|
||||
expect(loginRes.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('campaigns + characters + build flow', () => {
|
||||
itIfDb('DM creates a campaign, player joins, DM builds a character end-to-end', async () => {
|
||||
const dmEmail = uniqueEmail('dm2');
|
||||
const playerEmail = uniqueEmail('player2');
|
||||
|
||||
const dmRegister = await request(app)
|
||||
.post('/auth/register')
|
||||
.send({ email: dmEmail, password: 'password123', displayName: 'DM Two' });
|
||||
const dmToken = dmRegister.body.token;
|
||||
cleanupUserIds.push(dmRegister.body.user.id);
|
||||
|
||||
const playerRegister = await request(app)
|
||||
.post('/auth/register')
|
||||
.send({ email: playerEmail, password: 'password123', displayName: 'Player Two' });
|
||||
cleanupUserIds.push(playerRegister.body.user.id);
|
||||
|
||||
const campaignRes = await request(app)
|
||||
.post('/campaigns')
|
||||
.set('Authorization', `Bearer ${dmToken}`)
|
||||
.send({ name: 'Integration Test Campaign', startingItemCount: 1, startingSpellCount: 0, skipMotivationRoll: true });
|
||||
expect(campaignRes.status).toBe(201);
|
||||
const campaign = campaignRes.body.campaign;
|
||||
cleanupCampaignIds.push(campaign.id);
|
||||
|
||||
const joinRes = await request(app)
|
||||
.post(`/campaigns/join/${campaign.inviteCode}`)
|
||||
.set('Authorization', `Bearer ${playerRegister.body.token}`);
|
||||
expect(joinRes.status).toBe(201);
|
||||
|
||||
// DM adds a homebrew weapon to the pool so the equipment step has something to pick.
|
||||
const weaponRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/weapons`)
|
||||
.set('Authorization', `Bearer ${dmToken}`)
|
||||
.send({ name: 'Test Dagger', damageDice: '1d4', damageType: 'piercing', attackAbility: 'FINESSE', properties: [] });
|
||||
expect(weaponRes.status).toBe(201);
|
||||
const weaponId = weaponRes.body.weapon.id;
|
||||
|
||||
const characterRes = await request(app)
|
||||
.post(`/campaigns/${campaign.id}/characters`)
|
||||
.set('Authorization', `Bearer ${dmToken}`)
|
||||
.send({ name: 'Integration Hero' });
|
||||
expect(characterRes.status).toBe(201);
|
||||
const characterId = characterRes.body.character.id;
|
||||
const auth = { Authorization: `Bearer ${dmToken}` };
|
||||
|
||||
// Step 1: species
|
||||
let rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth);
|
||||
expect(rollRes.status).toBe(200);
|
||||
let speciesChoices = rollRes.body.buildState.speciesChoices;
|
||||
const species = speciesChoices.options[0];
|
||||
let chooseRes = await request(app)
|
||||
.post(`/characters/${characterId}/build/choose`)
|
||||
.set(auth)
|
||||
.send(species === 'HALF_ELF' ? { species, halfElfBonusAbilities: ['STR', 'INT'] } : { species });
|
||||
expect(chooseRes.status).toBe(200);
|
||||
expect(chooseRes.body.buildStage).toBe('ROLLING_CLASS');
|
||||
|
||||
// Step 2: class (skip any reroll results deterministically)
|
||||
rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth);
|
||||
while (rollRes.body.buildState.classChoices.type === 'reroll') {
|
||||
rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth);
|
||||
}
|
||||
const characterClass = rollRes.body.buildState.classChoices.options[0];
|
||||
chooseRes = await request(app).post(`/characters/${characterId}/build/choose`).set(auth).send({ characterClass });
|
||||
expect(chooseRes.status).toBe(200);
|
||||
// skipMotivationRoll was true, so motivation is skipped entirely.
|
||||
expect(chooseRes.body.buildStage).toBe('ASSIGNING_SCORES');
|
||||
|
||||
// Step 4: ability scores
|
||||
rollRes = await request(app).post(`/characters/${characterId}/build/roll`).set(auth);
|
||||
expect(rollRes.body.buildState.abilityRolls).toHaveLength(6);
|
||||
chooseRes = await request(app)
|
||||
.post(`/characters/${characterId}/build/choose`)
|
||||
.set(auth)
|
||||
.send({ assignments: { STR: 0, DEX: 1, CON: 2, INT: 3, WIS: 4, CHA: 5 } });
|
||||
expect(chooseRes.status).toBe(200);
|
||||
expect(chooseRes.body.buildStage).toBe('ASSIGNING_PROFICIENCIES');
|
||||
|
||||
// Step 5: skills
|
||||
chooseRes = await request(app)
|
||||
.post(`/characters/${characterId}/build/choose`)
|
||||
.set(auth)
|
||||
.send({ skillProficiencies: [{ skill: 'ATHLETICS', proficient: true, expertise: false }] });
|
||||
expect(chooseRes.status).toBe(200);
|
||||
expect(chooseRes.body.buildStage).toBe('CHOOSING_EQUIPMENT');
|
||||
|
||||
// Step 6: equipment
|
||||
chooseRes = await request(app)
|
||||
.post(`/characters/${characterId}/build/choose`)
|
||||
.set(auth)
|
||||
.send({ weaponIds: [weaponId], spellIds: [] });
|
||||
expect(chooseRes.status).toBe(200);
|
||||
expect(chooseRes.body.buildStage).toBe('CHOOSING_EQUIPMENT'); // stays here until finalize
|
||||
|
||||
// Step 7: finalize
|
||||
const finalizeRes = await request(app).post(`/characters/${characterId}/build/finalize`).set(auth);
|
||||
expect(finalizeRes.status).toBe(200);
|
||||
const character = finalizeRes.body.character;
|
||||
expect(character.buildStage).toBe('COMPLETE');
|
||||
expect(character.sheet).not.toBeNull();
|
||||
expect(character.currentHp).toBe(character.sheet.hp.max);
|
||||
expect(character.weapons).toHaveLength(1);
|
||||
|
||||
// Quick stats should now work.
|
||||
const quickStatsRes = await request(app).get(`/characters/${characterId}/quick-stats`).set(auth);
|
||||
expect(quickStatsRes.status).toBe(200);
|
||||
expect(quickStatsRes.body.quickStats.weapons).toHaveLength(1);
|
||||
|
||||
// A non-member cannot read the character.
|
||||
const outsiderRegister = await request(app)
|
||||
.post('/auth/register')
|
||||
.send({ email: uniqueEmail('outsider'), password: 'password123', displayName: 'Outsider' });
|
||||
cleanupUserIds.push(outsiderRegister.body.user.id);
|
||||
const forbiddenRes = await request(app)
|
||||
.get(`/characters/${characterId}`)
|
||||
.set('Authorization', `Bearer ${outsiderRegister.body.token}`);
|
||||
expect(forbiddenRes.status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const registerSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(8, 'Password must be at least 8 characters'),
|
||||
displayName: z.string().min(1).max(60),
|
||||
});
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email(),
|
||||
password: z.string().min(1),
|
||||
});
|
||||
|
||||
function issueToken(user) {
|
||||
return jwt.sign(
|
||||
{ sub: user.id, email: user.email, displayName: user.displayName },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
|
||||
);
|
||||
}
|
||||
|
||||
function publicUser(user) {
|
||||
return { id: user.id, email: user.email, displayName: user.displayName };
|
||||
}
|
||||
|
||||
router.post('/register', async (req, res, next) => {
|
||||
try {
|
||||
const parsed = registerSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { email, password, displayName } = parsed.data;
|
||||
|
||||
const existing = await prisma.user.findUnique({ where: { email } });
|
||||
if (existing) return res.status(409).json({ error: 'An account with that email already exists' });
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 12);
|
||||
const user = await prisma.user.create({ data: { email, passwordHash, displayName } });
|
||||
|
||||
return res.status(201).json({ token: issueToken(user), user: publicUser(user) });
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/login', async (req, res, next) => {
|
||||
try {
|
||||
const parsed = loginSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { email, password } = parsed.data;
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { email } });
|
||||
if (!user) return res.status(401).json({ error: 'Invalid email or password' });
|
||||
|
||||
const valid = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!valid) return res.status(401).json({ error: 'Invalid email or password' });
|
||||
|
||||
return res.json({ token: issueToken(user), user: publicUser(user) });
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/me', requireAuth, async (req, res, next) => {
|
||||
try {
|
||||
const user = await prisma.user.findUnique({ where: { id: req.user.id } });
|
||||
if (!user) return res.status(404).json({ error: 'User not found' });
|
||||
return res.json({ user: publicUser(user) });
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,429 @@
|
||||
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 } = require('../game/calculations');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
function campaignSummary(campaign, role) {
|
||||
return {
|
||||
id: campaign.id,
|
||||
name: campaign.name,
|
||||
description: campaign.description,
|
||||
inviteCode: campaign.inviteCode,
|
||||
startingGold: campaign.startingGold,
|
||||
startingItemCount: campaign.startingItemCount,
|
||||
startingSpellCount: campaign.startingSpellCount,
|
||||
skipMotivationRoll: campaign.skipMotivationRoll,
|
||||
ownerId: campaign.ownerId,
|
||||
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).optional(),
|
||||
startingItemCount: z.number().int().min(0).optional(),
|
||||
startingSpellCount: z.number().int().min(0).optional(),
|
||||
skipMotivationRoll: z.boolean().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/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' });
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
const updateCampaignSchema = createCampaignSchema.partial();
|
||||
|
||||
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 campaign = await prisma.campaign.update({ where: { id: req.campaign.id }, data: parsed.data });
|
||||
res.json({ campaign: campaignSummary(campaign, 'DM') });
|
||||
} 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,
|
||||
maxHp: character.buildStage === 'COMPLETE' ? sheet.hp.max : null,
|
||||
armorClass: character.buildStage === 'COMPLETE' ? sheet.armorClass : null,
|
||||
};
|
||||
}
|
||||
|
||||
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 },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
res.json({ characters: characters.map(characterSummary) });
|
||||
} 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 character = await prisma.character.create({
|
||||
data: {
|
||||
campaignId: req.campaign.id,
|
||||
userId: targetUserId,
|
||||
createdById: req.user.id,
|
||||
name: parsed.data.name,
|
||||
buildStage: 'ROLLING_SPECIES',
|
||||
gold: req.campaign.startingGold,
|
||||
},
|
||||
});
|
||||
|
||||
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('character:created', { character: characterSummary(character) });
|
||||
res.status(201).json({ character: characterSummary(character) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Weapons (campaign-level pool; DM manages, anyone in campaign can read)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/weapons', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const weapons = await prisma.weapon.findMany({ where: { campaignId: req.campaign.id }, orderBy: { name: 'asc' } });
|
||||
res.json({ weapons });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
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(),
|
||||
});
|
||||
|
||||
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 prisma.weapon.update({
|
||||
where: { id: req.params.weaponId },
|
||||
data: parsed.data,
|
||||
});
|
||||
res.json({ weapon });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.weapon.delete({ where: { id: req.params.weaponId } });
|
||||
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: { campaignId: req.campaign.id }, 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(),
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Monsters (DM only, campaign-scoped)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/monsters', requireCampaignMember(), 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),
|
||||
maxHp: z.number().int().min(1),
|
||||
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().optional(),
|
||||
damageDice: z.string().max(20).optional().nullable(),
|
||||
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 prisma.monster.update({ where: { id: req.params.monsterId }, data: parsed.data });
|
||||
res.json({ monster });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/monsters/:monsterId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.monster.delete({ where: { id: req.params.monsterId } });
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Encounters
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/encounters', requireCampaignMember(), async (req, res, next) => {
|
||||
try {
|
||||
const encounters = await prisma.encounter.findMany({
|
||||
where: { campaignId: req.campaign.id },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
res.json({ encounters });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
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 } });
|
||||
res.status(201).json({ encounter });
|
||||
} 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);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,582 @@
|
||||
const express = require('express');
|
||||
const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCharacterAccess } = require('../middleware/characterAccess');
|
||||
const {
|
||||
computeCharacterSheet,
|
||||
computeWeaponStats,
|
||||
getClassSaveProficiencies,
|
||||
getClassSpellcastingAbility,
|
||||
ABILITIES,
|
||||
} = require('../game/calculations');
|
||||
const {
|
||||
rollDie,
|
||||
rollAbilityScore,
|
||||
speciesChoicesForRoll,
|
||||
classChoicesForRoll,
|
||||
MOTIVATION_TABLE,
|
||||
} = require('../game/buildFlow');
|
||||
const { SKILLS } = require('../game/data/skills');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
async function loadFullCharacter(id) {
|
||||
return prisma.character.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
skillProficiencies: true,
|
||||
saveProficiencies: true,
|
||||
inventoryItems: true,
|
||||
weapons: { include: { weapon: true } },
|
||||
spells: { include: { spell: true } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function serializeCharacter(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,
|
||||
motivation: character.motivation,
|
||||
halfElfBonusAbility1: character.halfElfBonusAbility1,
|
||||
halfElfBonusAbility2: character.halfElfBonusAbility2,
|
||||
rolledScores: {
|
||||
STR: character.strScore,
|
||||
DEX: character.dexScore,
|
||||
CON: character.conScore,
|
||||
INT: character.intScore,
|
||||
WIS: character.wisScore,
|
||||
CHA: character.chaScore,
|
||||
},
|
||||
currentHp: character.currentHp,
|
||||
tempHp: character.tempHp,
|
||||
armorBonus: character.armorBonus,
|
||||
specialAbilities: character.specialAbilities,
|
||||
gold: character.gold,
|
||||
buildStage: character.buildStage,
|
||||
buildState: character.buildStage === 'COMPLETE' ? null : character.buildState,
|
||||
skillProficiencies: character.skillProficiencies,
|
||||
saveProficiencies: character.saveProficiencies,
|
||||
inventoryItems: character.inventoryItems,
|
||||
weapons: character.weapons,
|
||||
spells: character.spells,
|
||||
sheet: character.buildStage === 'COMPLETE' ? sheet : null,
|
||||
};
|
||||
}
|
||||
|
||||
router.get('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
res.json({ character: serializeCharacter(character) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const patchCharacterSchema = z.object({
|
||||
name: z.string().min(1).max(80).optional(),
|
||||
currentHp: z.number().int().optional(),
|
||||
tempHp: z.number().int().min(0).optional(),
|
||||
armorBonus: z.number().int().min(0).optional(),
|
||||
speedOverride: z.number().int().min(0).nullable().optional(),
|
||||
specialAbilities: z.string().max(4000).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(),
|
||||
});
|
||||
|
||||
router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = patchCharacterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
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 });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
await prisma.character.delete({ where: { id: req.character.id } });
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Roll-Your-Character build flow — docs/ROLL_YOUR_CHARACTER.md
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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.' });
|
||||
}
|
||||
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.` });
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({ where: { id: character.id }, data: { buildState } });
|
||||
res.json({ buildStage: updated.buildStage, buildState: updated.buildState });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const HALF_ELF_ELIGIBLE_ABILITIES = ABILITIES.filter((a) => a !== 'CHA');
|
||||
|
||||
const chooseSchemas = {
|
||||
ROLLING_SPECIES: z.object({
|
||||
species: z.string(),
|
||||
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() }),
|
||||
ASSIGNING_SCORES: z.object({
|
||||
assignments: z.object({
|
||||
STR: z.number().int().min(0).max(5),
|
||||
DEX: z.number().int().min(0).max(5),
|
||||
CON: z.number().int().min(0).max(5),
|
||||
INT: z.number().int().min(0).max(5),
|
||||
WIS: z.number().int().min(0).max(5),
|
||||
CHA: z.number().int().min(0).max(5),
|
||||
}),
|
||||
}),
|
||||
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),
|
||||
})
|
||||
),
|
||||
}),
|
||||
CHOOSING_EQUIPMENT: z.object({
|
||||
weaponIds: z.array(z.string()).default([]),
|
||||
spellIds: z.array(z.string()).default([]),
|
||||
}),
|
||||
};
|
||||
|
||||
const STAGE_ORDER = [
|
||||
'ROLLING_SPECIES',
|
||||
'ROLLING_CLASS',
|
||||
'ROLLING_MOTIVATION',
|
||||
'ASSIGNING_SCORES',
|
||||
'ASSIGNING_PROFICIENCIES',
|
||||
'CHOOSING_EQUIPMENT',
|
||||
'COMPLETE',
|
||||
];
|
||||
|
||||
function nextStage(current) {
|
||||
const idx = STAGE_ORDER.indexOf(current);
|
||||
return STAGE_ORDER[idx + 1];
|
||||
}
|
||||
|
||||
router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
const stage = character.buildStage;
|
||||
const schema = chooseSchemas[stage];
|
||||
if (!schema) return res.status(400).json({ error: `No choice is expected at the "${stage}" step.` });
|
||||
|
||||
const parsed = schema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
let advanceTo = nextStage(stage);
|
||||
|
||||
if (stage === 'ROLLING_SPECIES') {
|
||||
const choices = buildState.speciesChoices;
|
||||
if (!choices) return res.status(400).json({ error: 'Roll for species before choosing one.' });
|
||||
const { species, halfElfBonusAbilities } = parsed.data;
|
||||
if (choices.type !== 'wildcard' && !choices.options.includes(species)) {
|
||||
return res.status(400).json({ error: `${species} was not offered by this roll.` });
|
||||
}
|
||||
if (species === 'HALF_ELF') {
|
||||
if (!halfElfBonusAbilities) {
|
||||
return res.status(400).json({ error: 'Half-Elf requires choosing two abilities (other than CHA) for the +1/+1 bonus.' });
|
||||
}
|
||||
if (new Set(halfElfBonusAbilities).size !== 2) {
|
||||
return res.status(400).json({ error: 'The two Half-Elf bonus abilities must be different.' });
|
||||
}
|
||||
buildState.halfElfBonusAbilities = halfElfBonusAbilities;
|
||||
} else {
|
||||
delete buildState.halfElfBonusAbilities;
|
||||
}
|
||||
buildState.species = species;
|
||||
} else if (stage === 'ROLLING_CLASS') {
|
||||
const choices = buildState.classChoices;
|
||||
if (!choices || choices.type === 'reroll') {
|
||||
return res.status(400).json({ error: 'Roll for class before choosing one.' });
|
||||
}
|
||||
const { characterClass } = parsed.data;
|
||||
if (choices.type !== 'wildcard' && !choices.options.includes(characterClass)) {
|
||||
return res.status(400).json({ error: `${characterClass} was not offered by this roll.` });
|
||||
}
|
||||
buildState.characterClass = characterClass;
|
||||
if (req.campaign.skipMotivationRoll) {
|
||||
advanceTo = 'ASSIGNING_SCORES';
|
||||
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;
|
||||
} else if (stage === 'ASSIGNING_SCORES') {
|
||||
if (!buildState.abilityRolls) return res.status(400).json({ error: 'Roll ability scores first.' });
|
||||
const { assignments } = parsed.data;
|
||||
const usedIndexes = Object.values(assignments);
|
||||
const uniqueIndexes = new Set(usedIndexes);
|
||||
if (uniqueIndexes.size !== 6 || Math.max(...usedIndexes) > 5) {
|
||||
return res.status(400).json({ error: 'Each of the 6 rolled scores must be assigned to exactly one ability.' });
|
||||
}
|
||||
buildState.abilityAssignments = assignments;
|
||||
} else if (stage === 'ASSIGNING_PROFICIENCIES') {
|
||||
buildState.skillProficiencies = parsed.data.skillProficiencies;
|
||||
} else if (stage === 'CHOOSING_EQUIPMENT') {
|
||||
const { weaponIds, 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).` });
|
||||
}
|
||||
const hasSpellcasting = Boolean(getClassSpellcastingAbility(buildState.characterClass));
|
||||
if (spellIds.length > 0 && !hasSpellcasting) {
|
||||
return res.status(400).json({ error: 'This class has no spellcasting ability — it cannot pick starting spells.' });
|
||||
}
|
||||
if (spellIds.length > maxSpells) {
|
||||
return res.status(400).json({ error: `This campaign allows at most ${maxSpells} starting spell(s).` });
|
||||
}
|
||||
buildState.equipment = { weaponIds, spellIds };
|
||||
advanceTo = 'CHOOSING_EQUIPMENT'; // stay here; POST /build/finalize completes the character
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({
|
||||
where: { id: character.id },
|
||||
data: { buildState, buildStage: advanceTo },
|
||||
});
|
||||
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;
|
||||
if (character.buildStage !== 'CHOOSING_EQUIPMENT') {
|
||||
return res.status(400).json({ error: `Character isn't ready to finalize (currently at "${character.buildStage}").` });
|
||||
}
|
||||
const bs = character.buildState || {};
|
||||
if (!bs.species || !bs.characterClass || !bs.abilityAssignments || !bs.equipment) {
|
||||
return res.status(400).json({ error: 'Build is incomplete — species, class, ability assignments, and equipment are all required.' });
|
||||
}
|
||||
|
||||
const rolledScores = {};
|
||||
for (const ability of ABILITIES) {
|
||||
const rollIndex = bs.abilityAssignments[ability];
|
||||
rolledScores[ability] = bs.abilityRolls[rollIndex].total;
|
||||
}
|
||||
|
||||
const [halfElfBonusAbility1, halfElfBonusAbility2] = bs.halfElfBonusAbilities || [null, null];
|
||||
const saveProfs = getClassSaveProficiencies(bs.characterClass);
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
await tx.characterSkillProficiency.deleteMany({ where: { characterId: character.id } });
|
||||
await tx.characterSaveProficiency.deleteMany({ where: { characterId: character.id } });
|
||||
|
||||
const updated = await tx.character.update({
|
||||
where: { id: character.id },
|
||||
data: {
|
||||
species: bs.species,
|
||||
characterClass: bs.characterClass,
|
||||
motivation: bs.motivationText || null,
|
||||
strScore: rolledScores.STR,
|
||||
dexScore: rolledScores.DEX,
|
||||
conScore: rolledScores.CON,
|
||||
intScore: rolledScores.INT,
|
||||
wisScore: rolledScores.WIS,
|
||||
chaScore: rolledScores.CHA,
|
||||
halfElfBonusAbility1,
|
||||
halfElfBonusAbility2,
|
||||
buildStage: 'COMPLETE',
|
||||
buildState: null,
|
||||
skillProficiencies: {
|
||||
create: (bs.skillProficiencies || []).map((sp) => ({
|
||||
skill: sp.skill,
|
||||
proficient: sp.proficient !== false,
|
||||
expertise: Boolean(sp.expertise),
|
||||
})),
|
||||
},
|
||||
saveProficiencies: {
|
||||
create: ABILITIES.map((ability) => ({ ability, proficient: saveProfs.includes(ability) })),
|
||||
},
|
||||
weapons: {
|
||||
create: (bs.equipment.weaponIds || []).map((weaponId) => ({ weaponId, quantity: 1, equipped: false })),
|
||||
},
|
||||
spells: {
|
||||
create: (bs.equipment.spellIds || []).map((spellId) => ({ spellId, prepared: false })),
|
||||
},
|
||||
},
|
||||
include: { skillProficiencies: true, saveProficiencies: true },
|
||||
});
|
||||
|
||||
const sheet = computeCharacterSheet(updated, updated.skillProficiencies, updated.saveProficiencies);
|
||||
const finalized = await tx.character.update({
|
||||
where: { id: character.id },
|
||||
data: { currentHp: sheet.hp.max },
|
||||
});
|
||||
return finalized;
|
||||
});
|
||||
|
||||
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 });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Quick Stats — combat-context panel (docs/GAME_RULES_REFERENCE.md)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
if (character.buildStage !== 'COMPLETE') {
|
||||
return res.status(400).json({ error: 'Character build is not finished yet.' });
|
||||
}
|
||||
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),
|
||||
}));
|
||||
|
||||
res.json({
|
||||
quickStats: {
|
||||
name: character.name,
|
||||
currentHp: character.currentHp,
|
||||
maxHp: sheet.hp.max,
|
||||
tempHp: character.tempHp,
|
||||
armorClass: sheet.armorClass,
|
||||
initiative: sheet.initiative,
|
||||
speed: sheet.speed,
|
||||
proficiencyBonus: sheet.proficiencyBonus,
|
||||
spellcasting: sheet.spellcasting,
|
||||
specialAbilities: character.specialAbilities,
|
||||
weapons,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Weapons assigned to this character
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/weapons', requireCharacterAccess({ write: true }), 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 },
|
||||
});
|
||||
res.status(201).json({ characterWeapon });
|
||||
} 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) => {
|
||||
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),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
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.' });
|
||||
}
|
||||
|
||||
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 });
|
||||
} 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() });
|
||||
|
||||
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 });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Notes about this character
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.get('/:id/notes', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const notes = await prisma.note.findMany({
|
||||
where: {
|
||||
characterId: req.character.id,
|
||||
...(req.isDM ? {} : { OR: [{ visibility: 'SHARED' }, { authorId: req.user.id }] }),
|
||||
},
|
||||
include: { author: { select: { displayName: true } } },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
res.json({ notes });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,187 @@
|
||||
const express = require('express');
|
||||
const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
const { computeCharacterSheet } = require('../game/calculations');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
async function requireEncounterAccess(req, res, next) {
|
||||
try {
|
||||
const encounter = await prisma.encounter.findUnique({ where: { id: req.params.id } });
|
||||
if (!encounter) return res.status(404).json({ error: 'Encounter not found' });
|
||||
|
||||
const membership = await loadCampaignMembership(req.user.id, encounter.campaignId);
|
||||
if (!membership) return res.status(403).json({ error: 'Not a member of this campaign' });
|
||||
|
||||
req.encounter = encounter;
|
||||
req.membership = membership;
|
||||
req.isDM = membership.role === 'DM';
|
||||
return next();
|
||||
} catch (err) {
|
||||
return next(err);
|
||||
}
|
||||
}
|
||||
|
||||
async function serializeEncounter(encounterId) {
|
||||
return prisma.encounter.findUnique({
|
||||
where: { id: encounterId },
|
||||
include: {
|
||||
participants: {
|
||||
include: {
|
||||
character: { select: { id: true, name: true } },
|
||||
monster: { select: { id: true, name: true } },
|
||||
},
|
||||
orderBy: { initiative: 'desc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
router.get('/:id', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
const encounter = await serializeEncounter(req.encounter.id);
|
||||
res.json({ encounter });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const participantSchema = z
|
||||
.object({
|
||||
characterId: z.string().optional(),
|
||||
monsterId: 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',
|
||||
});
|
||||
|
||||
router.post('/:id/participants', requireEncounterAccess, 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;
|
||||
|
||||
let currentHp, maxHp, resolvedName, isMonster;
|
||||
|
||||
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({
|
||||
where: { id: characterId },
|
||||
include: { skillProficiencies: true, saveProficiencies: true },
|
||||
});
|
||||
const sheet = computeCharacterSheet(full, full.skillProficiencies, full.saveProficiencies);
|
||||
currentHp = character.currentHp;
|
||||
maxHp = sheet.hp.max;
|
||||
resolvedName = displayName || character.name;
|
||||
isMonster = false;
|
||||
} else {
|
||||
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.' });
|
||||
}
|
||||
currentHp = monster.maxHp;
|
||||
maxHp = monster.maxHp;
|
||||
resolvedName = displayName || monster.name;
|
||||
isMonster = true;
|
||||
}
|
||||
|
||||
const participant = await prisma.encounterParticipant.create({
|
||||
data: {
|
||||
encounterId: req.encounter.id,
|
||||
characterId: characterId || null,
|
||||
monsterId: monsterId || null,
|
||||
displayName: resolvedName,
|
||||
initiative,
|
||||
currentHp,
|
||||
maxHp,
|
||||
isMonster,
|
||||
},
|
||||
});
|
||||
|
||||
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 });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
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(),
|
||||
displayName: z.string().min(1).max(80).optional(),
|
||||
});
|
||||
|
||||
router.patch('/:id/participants/:participantId', requireEncounterAccess, 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({
|
||||
where: { id: req.params.participantId },
|
||||
data: parsed.data,
|
||||
});
|
||||
|
||||
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 });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/participants/:participantId', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
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 });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/advance-round', requireEncounterAccess, async (req, res, next) => {
|
||||
try {
|
||||
if (!req.isDM) return res.status(403).json({ error: 'DM only' });
|
||||
const updated = await prisma.encounter.update({
|
||||
where: { id: req.encounter.id },
|
||||
data: { currentRound: { increment: 1 }, status: 'ACTIVE' },
|
||||
});
|
||||
req.app.get('io').to(`campaign:${req.encounter.campaignId}`).emit('encounter:round-advanced', {
|
||||
encounterId: updated.id,
|
||||
currentRound: updated.currentRound,
|
||||
});
|
||||
res.json({ encounter: updated });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id', requireEncounterAccess, 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);
|
||||
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 });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,63 @@
|
||||
const express = require('express');
|
||||
const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
const createNoteSchema = z
|
||||
.object({
|
||||
campaignId: z.string().optional(),
|
||||
characterId: z.string().optional(),
|
||||
body: z.string().min(1).max(10000),
|
||||
visibility: z.enum(['DM_ONLY', 'SHARED']).default('SHARED'),
|
||||
})
|
||||
.refine((data) => Boolean(data.campaignId) || Boolean(data.characterId), {
|
||||
message: 'Provide campaignId and/or characterId',
|
||||
});
|
||||
|
||||
router.post('/', async (req, res, next) => {
|
||||
try {
|
||||
const parsed = createNoteSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { campaignId, characterId, body, visibility } = parsed.data;
|
||||
|
||||
let resolvedCampaignId = campaignId || null;
|
||||
if (characterId) {
|
||||
const character = await prisma.character.findUnique({ where: { id: characterId } });
|
||||
if (!character) return res.status(404).json({ error: 'Character not found' });
|
||||
resolvedCampaignId = resolvedCampaignId || character.campaignId;
|
||||
}
|
||||
if (resolvedCampaignId) {
|
||||
const membership = await loadCampaignMembership(req.user.id, resolvedCampaignId);
|
||||
if (!membership) return res.status(403).json({ error: 'Not a member of this campaign' });
|
||||
}
|
||||
|
||||
const note = await prisma.note.create({
|
||||
data: { campaignId, characterId, authorId: req.user.id, body, visibility },
|
||||
include: { author: { select: { displayName: true } } },
|
||||
});
|
||||
res.status(201).json({ note });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', async (req, res, next) => {
|
||||
try {
|
||||
const note = await prisma.note.findUnique({ where: { id: req.params.id } });
|
||||
if (!note) return res.status(404).json({ error: 'Note not found' });
|
||||
if (note.authorId !== req.user.id) {
|
||||
return res.status(403).json({ error: 'You can only delete your own notes' });
|
||||
}
|
||||
await prisma.note.delete({ where: { id: req.params.id } });
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user