V1.11.0: gear that applies itself, equipping that matters, a character panel
- Weapons and items can carry effects: bonuses and penalties to AC, speed, initiative, max HP, passive Perception, ability scores, saving throws and skills, plus a note. They apply on their own while equipped and stop when the thing comes off. Armor is an item with an AC effect. The DM sets them with "Effects" on a row in the weapon or item pool. - The sheet's "armor bonus" is now "Extra AC", the DM's own adjustment on top of gear, and only the DM can set it. - Only what is equipped counts: a weapon has to be equipped to be used in an encounter. A character can have two things equipped at once, one of them a weapon (campaign settings). Equipping at the limit is refused with a message, and can be changed at any time, mid-encounter included. - A built-in item library: armor, shields, worn gear and supplies, with their effects set. The weapon library gains paired weapons (a pair of daggers is one weapon). - A floating character button on every page opens a panel with a character's numbers and everything they hold, with equip ticks. Players get their own characters, the DM everyone's, and each character card in an encounter has an Inventory button. It replaces the quick stats drawer. - A player's own characters stand out: marked and highlighted in encounters, with a button that jumps to their card; highlighted on the party screen; and listed once, not twice, on the campaign page. - All packages at version 1.11.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -419,7 +419,7 @@ describe('who can change what on a character', () => {
|
||||
expect((await request(app).patch(`/characters/${characterId}`).set(dmAuth).send({ gold: 999 })).status).toBe(400);
|
||||
|
||||
// The player can still edit the rest of their own sheet.
|
||||
expect((await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ armorBonus: 2 })).status).toBe(200);
|
||||
expect((await request(app).patch(`/characters/${characterId}`).set(playerAuth).send({ tempHp: 2 })).status).toBe(200);
|
||||
|
||||
const dmRes = await request(app)
|
||||
.patch(`/characters/${characterId}`)
|
||||
@@ -795,11 +795,16 @@ describe('gear levels', () => {
|
||||
expect(levelled.body.characterWeapon).toMatchObject({ level: 3, equipped: false });
|
||||
expect(await held('Spear')).toMatchObject({ scaledDamageDice: '1d10', usable: false });
|
||||
|
||||
// Unusable weapons stay out of quick stats and the encounter view.
|
||||
// The character panel lists everything held and marks what is out of reach;
|
||||
// the encounter view leaves unusable weapons out.
|
||||
const quick = async () => (await request(app).get(`${ch}/quick-stats`).set(playerAuth)).body.quickStats.weapons;
|
||||
expect(await quick()).toEqual([]);
|
||||
expect((await quick()).map((w) => [w.name, w.usable]).sort()).toEqual([
|
||||
['Relic Blade', false],
|
||||
['Spear', false],
|
||||
]);
|
||||
|
||||
// At character level 3 both are usable, at their own level's dice.
|
||||
await request(app).patch(c).set(dmAuth).send({ maxEquippedWeapons: 2 });
|
||||
await request(app).patch(ch).set(dmAuth).send({ level: 3 });
|
||||
expect(await held('Spear')).toMatchObject({ usable: true });
|
||||
expect((await request(app).patch(`${ch}/weapons/${spear.id}`).set(playerAuth).send({ equipped: true })).status).toBe(200);
|
||||
@@ -2530,3 +2535,177 @@ describe('trade', () => {
|
||||
expect((await request(app).get(e).set(playerAuth)).body.encounter.wares).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gear effects', () => {
|
||||
itIfDb('equipped gear changes the sheet on its own, and the character panel lists everything held', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('gear');
|
||||
const c = `/campaigns/${campaign.id}`;
|
||||
const heroId = await buildCharacter(campaign.id, playerAuth, 'Aria');
|
||||
const ch = `/characters/${heroId}`;
|
||||
const post = (path, body, auth = dmAuth) => request(app).post(path).set(auth).send(body);
|
||||
const sheet = async (auth = playerAuth) => (await request(app).get(ch).set(auth)).body.character;
|
||||
const quick = async (auth = playerAuth) => (await request(app).get(`${ch}/quick-stats`).set(auth)).body.quickStats;
|
||||
|
||||
const before = (await sheet()).sheet;
|
||||
expect(before.gear).toEqual({ effects: [], notes: [] });
|
||||
|
||||
// Only the DM says what gear does, and only with numbers the sheet has.
|
||||
const mail = {
|
||||
name: 'Chain Mail',
|
||||
effects: [{ stat: 'AC', amount: 6 }, { stat: 'SPEED', amount: -10 }, { stat: 'SKILL_STEALTH', amount: -2 }, { stat: 'CON', amount: 2 }, { stat: 'SAVES', amount: 1 }],
|
||||
effectNote: 'Disadvantage on Stealth',
|
||||
};
|
||||
expect((await post(`${c}/items`, mail, playerAuth)).status).toBe(403);
|
||||
expect((await post(`${c}/items`, { name: 'Bad', effects: [{ stat: 'LUCK', amount: 1 }] })).status).toBe(400);
|
||||
expect((await post(`${c}/items`, { name: 'Bad', effects: [{ stat: 'AC', amount: 0 }] })).status).toBe(400);
|
||||
const armor = (await post(`${c}/items`, mail)).body.item;
|
||||
expect(armor).toMatchObject({ effects: mail.effects, effectNote: 'Disadvantage on Stealth' });
|
||||
const heavy = (await post(`${c}/items`, { name: 'Dragon Plate', minLevel: 5, effects: [{ stat: 'AC', amount: 9 }] })).body.item;
|
||||
const ring = (await post(`${c}/weapons`, { name: 'Warded Blade', damageDice: '1d8', damageType: 'slashing', attackAbility: 'STR', effects: [{ stat: 'AC', amount: 1 }] })).body.weapon;
|
||||
|
||||
// Carried but not worn, it does nothing.
|
||||
await post(`${ch}/inventory`, { itemId: armor.id, quantity: 2 });
|
||||
await post(`${ch}/inventory`, { itemId: heavy.id });
|
||||
await post(`${ch}/weapons`, { weaponId: ring.id });
|
||||
expect((await sheet()).sheet).toMatchObject({ armorClass: before.armorClass, speed: before.speed });
|
||||
|
||||
// Worn, every number moves, however many are carried; the player may put it on.
|
||||
const wear = (path, id, equipped, auth = playerAuth) => request(app).patch(`${ch}/${path}/${id}`).set(auth).send({ equipped });
|
||||
expect((await wear('inventory', armor.id, true)).status).toBe(200);
|
||||
expect((await wear('weapons', ring.id, true)).status).toBe(200);
|
||||
const worn = (await sheet()).sheet;
|
||||
expect(worn.armorClass).toBe(before.armorClass + 6 + 1);
|
||||
expect(worn.speed).toBe(before.speed - 10);
|
||||
expect(worn.abilities.CON.final).toBe(before.abilities.CON.final + 2);
|
||||
expect(worn.hp.max).toBe(before.hp.max + 1); // +2 CON is +1 to the modifier, at level 1
|
||||
expect(worn.skills.STEALTH.bonus).toBe(before.skills.STEALTH.bonus - 2);
|
||||
expect(worn.saves.DEX.bonus).toBe(before.saves.DEX.bonus + 1);
|
||||
expect(worn.saves.CON.bonus).toBe(before.saves.CON.bonus + 2); // the save's own +1, and +1 from CON
|
||||
expect(worn.gear.notes).toEqual([{ source: 'Chain Mail', note: 'Disadvantage on Stealth' }]);
|
||||
expect(worn.gear.effects).toContainEqual({ stat: 'AC', amount: 1, source: 'Warded Blade' });
|
||||
|
||||
// The same numbers reach the party list and an encounter.
|
||||
const listed = (await request(app).get(`${c}/characters`).set(dmAuth)).body.characters.find((x) => x.id === heroId);
|
||||
expect(listed).toMatchObject({ armorClass: worn.armorClass, maxHp: worn.hp.max });
|
||||
const encounterId = (await post(`${c}/encounters`, { name: 'Gear check' })).body.encounter.id;
|
||||
const joined = (await post(`/encounters/${encounterId}/participants`, { characterId: heroId })).body.encounter.participants[0];
|
||||
expect(joined.maxHp).toBe(worn.hp.max);
|
||||
expect(joined.characterCombatInfo).toMatchObject({ armorClass: worn.armorClass, speed: worn.speed });
|
||||
expect(joined.characterCombatInfo.gear.effects).toHaveLength(6);
|
||||
|
||||
// Gear above the character's level cannot be put on, but is still listed.
|
||||
expect((await wear('inventory', heavy.id, true)).status).toBe(400);
|
||||
const panel = await quick();
|
||||
expect(panel).toMatchObject({ armorClass: worn.armorClass, speed: worn.speed, maxHp: worn.hp.max, restricted: false });
|
||||
expect(panel.inventory.map((i) => [i.name, i.quantity, i.equipped, i.usable]).sort()).toEqual([
|
||||
['Chain Mail', 2, true, true],
|
||||
['Dragon Plate', 1, false, false],
|
||||
]);
|
||||
expect(panel.inventory.find((i) => i.name === 'Chain Mail')).toMatchObject({ effects: mail.effects, effectNote: 'Disadvantage on Stealth' });
|
||||
expect(panel.weapons.find((w) => w.name === 'Warded Blade')).toMatchObject({ equipped: true, usable: true, effects: [{ stat: 'AC', amount: 1 }] });
|
||||
expect(panel.purse).toEqual({ gold: 0, silver: 0, copper: 0, cash: 0 });
|
||||
expect((await quick(dmAuth)).inventory).toHaveLength(2);
|
||||
|
||||
// Another player sees the numbers, not the pack or the purse.
|
||||
const other = await request(app).post('/auth/register').send({ email: uniqueEmail('gear-other'), password: 'password123', displayName: 'Other' });
|
||||
cleanupUserIds.push(other.body.user.id);
|
||||
const otherAuth = { Authorization: `Bearer ${other.body.token}` };
|
||||
await request(app).post(`/campaigns/join/${campaign.inviteCode}`).set(otherAuth);
|
||||
expect(await quick(otherAuth)).toMatchObject({ armorClass: worn.armorClass, restricted: true, inventory: [], spells: [], purse: null });
|
||||
|
||||
// The DM's own adjustment sits on top, and is the DM's alone.
|
||||
expect((await request(app).patch(ch).set(playerAuth).send({ armorBonus: 2 })).status).toBe(403);
|
||||
expect((await request(app).patch(ch).set(dmAuth).send({ armorBonus: -1 })).body.character.sheet.armorClass).toBe(worn.armorClass - 1);
|
||||
await request(app).patch(ch).set(dmAuth).send({ armorBonus: 0 });
|
||||
|
||||
// Changing what the item does reaches whoever wears it.
|
||||
const patched = await request(app).patch(`${c}/items/${armor.id}`).set(dmAuth).send({ effects: [{ stat: 'AC', amount: 4 }], effectNote: null });
|
||||
expect(patched.body.item).toMatchObject({ effects: [{ stat: 'AC', amount: 4 }], effectNote: null });
|
||||
const lighter = (await sheet()).sheet;
|
||||
expect(lighter.armorClass).toBe(before.armorClass + 4 + 1);
|
||||
expect(lighter.speed).toBe(before.speed);
|
||||
// The +1 max HP went with the CON bonus, and current HP came down with it.
|
||||
expect(lighter.hp.max).toBe(before.hp.max);
|
||||
expect((await sheet()).currentHp).toBe(before.hp.max);
|
||||
|
||||
// Taking it off, or losing it, takes its effects away.
|
||||
await wear('inventory', armor.id, false);
|
||||
expect((await sheet()).sheet.armorClass).toBe(before.armorClass + 1);
|
||||
expect((await request(app).delete(`${c}/weapons/${ring.id}`).set(dmAuth)).status).toBe(204);
|
||||
expect((await sheet()).sheet).toMatchObject({ armorClass: before.armorClass, gear: { effects: [], notes: [] } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('equipping', () => {
|
||||
itIfDb('only so much can be equipped at once, and only what is equipped is used in an encounter', async () => {
|
||||
const { dmAuth, playerAuth, campaign } = await setupCampaign('equip');
|
||||
const c = `/campaigns/${campaign.id}`;
|
||||
expect(campaign).toMatchObject({ maxEquipped: 2, maxEquippedWeapons: 1 });
|
||||
const heroId = await buildCharacter(campaign.id, playerAuth, 'Aria');
|
||||
const ch = `/characters/${heroId}`;
|
||||
const post = (path, body, auth = dmAuth) => request(app).post(path).set(auth).send(body);
|
||||
|
||||
// The library has armor, with its effects, and weapons made as a pair.
|
||||
const library = (await request(app).get(`${c}/library`).set(dmAuth)).body;
|
||||
expect(library.items.length).toBeGreaterThan(20);
|
||||
expect(library.items.find((i) => i.key === 'chain-mail')).toMatchObject({ category: 'Heavy Armor', effects: [{ stat: 'AC', amount: 6 }, { stat: 'SPEED', amount: -10 }] });
|
||||
expect(library.weapons.find((w) => w.key === 'paired-daggers')).toMatchObject({ category: 'Paired', damageDice: '2d4' });
|
||||
expect((await post(`${c}/items/from-library`, { key: 'shield' }, playerAuth)).status).toBe(403);
|
||||
expect((await post(`${c}/items/from-library`, { key: 'nope' })).status).toBe(404);
|
||||
const shield = (await post(`${c}/items/from-library`, { key: 'shield' })).body.item;
|
||||
expect(shield).toMatchObject({ name: 'Shield', effects: [{ stat: 'AC', amount: 2 }], isStartingOption: false });
|
||||
const mail = (await post(`${c}/items/from-library`, { key: 'leather-armor' })).body.item;
|
||||
const ring = (await post(`${c}/items/from-library`, { key: 'ring-of-protection' })).body.item;
|
||||
const sword = (await post(`${c}/weapons/from-library`, { key: 'longsword' })).body.weapon;
|
||||
const daggers = (await post(`${c}/weapons/from-library`, { key: 'paired-daggers' })).body.weapon;
|
||||
expect(daggers.effectNote).toContain('both hands');
|
||||
|
||||
for (const item of [shield, mail, ring]) await post(`${ch}/inventory`, { itemId: item.id });
|
||||
for (const weapon of [sword, daggers]) await post(`${ch}/weapons`, { weaponId: weapon.id });
|
||||
|
||||
const encounterId = (await post(`${c}/encounters`, { name: 'Drill' })).body.encounter.id;
|
||||
await post(`/encounters/${encounterId}/participants`, { characterId: heroId });
|
||||
const combat = async () => (await request(app).get(`/encounters/${encounterId}`).set(playerAuth)).body.encounter.participants[0].characterCombatInfo;
|
||||
const wear = (path, id, equipped, auth = playerAuth) => request(app).patch(`${ch}/${path}/${id}`).set(auth).send({ equipped });
|
||||
|
||||
// Nothing in hand: nothing to fight with, though it is all in the pack.
|
||||
expect(await combat()).toMatchObject({ weapons: [], items: [] });
|
||||
const panel = async () => (await request(app).get(`${ch}/quick-stats`).set(playerAuth)).body.quickStats;
|
||||
expect((await panel()).weapons.map((w) => w.name).sort()).toEqual(['Longsword', 'Paired Daggers']);
|
||||
|
||||
// One weapon at a time; the player changes it themselves, mid-encounter.
|
||||
expect((await wear('weapons', sword.id, true)).status).toBe(200);
|
||||
expect((await combat()).weapons.map((w) => w.name)).toEqual(['Longsword']);
|
||||
const second = await wear('weapons', daggers.id, true);
|
||||
expect(second.status).toBe(400);
|
||||
expect(second.body.error).toContain('Longsword');
|
||||
expect((await wear('weapons', sword.id, true)).status).toBe(200); // already on: no complaint
|
||||
await wear('weapons', sword.id, false);
|
||||
expect((await wear('weapons', daggers.id, true)).status).toBe(200);
|
||||
expect((await combat()).weapons.map((w) => [w.name, w.damageDice])).toEqual([['Paired Daggers', '2d4']]);
|
||||
|
||||
// Two things in all: a weapon and an item, or two items.
|
||||
expect((await wear('inventory', shield.id, true)).status).toBe(200);
|
||||
expect((await combat()).items.map((i) => i.name)).toEqual(['Shield']);
|
||||
const third = await wear('inventory', mail.id, true);
|
||||
expect(third.status).toBe(400);
|
||||
expect(third.body.error).toContain('Shield');
|
||||
expect((await post(`${ch}/inventory`, { itemId: ring.id, equipped: true })).status).toBe(400); // nor by handing it over equipped
|
||||
await wear('weapons', daggers.id, false);
|
||||
expect((await wear('inventory', mail.id, true)).status).toBe(200);
|
||||
expect((await wear('weapons', sword.id, true)).status).toBe(400); // both places are taken by items
|
||||
expect((await combat()).items.map((i) => i.name).sort()).toEqual(['Leather Armor', 'Shield']);
|
||||
|
||||
// The DM sets the limits; raising them makes room, lowering them takes nothing off.
|
||||
expect((await request(app).patch(c).set(playerAuth).send({ maxEquipped: 5 })).status).toBe(403);
|
||||
expect((await request(app).patch(c).set(dmAuth).send({ maxEquipped: 0 })).status).toBe(400);
|
||||
expect((await request(app).patch(c).set(dmAuth).send({ maxEquipped: 4, maxEquippedWeapons: 2 })).body.campaign).toMatchObject({ maxEquipped: 4, maxEquippedWeapons: 2 });
|
||||
expect((await wear('weapons', sword.id, true)).status).toBe(200);
|
||||
expect((await wear('weapons', daggers.id, true)).status).toBe(200);
|
||||
expect((await wear('inventory', ring.id, true)).status).toBe(400); // four on
|
||||
await request(app).patch(c).set(dmAuth).send({ maxEquipped: 2, maxEquippedWeapons: 1 });
|
||||
expect((await combat()).weapons).toHaveLength(2);
|
||||
await wear('weapons', sword.id, false);
|
||||
expect((await wear('weapons', sword.id, true)).status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,8 +4,9 @@ const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCampaignMember, requireDM } = require('../middleware/campaignAccess');
|
||||
const { generateInviteCode } = require('../utils/inviteCode');
|
||||
const { computeCharacterSheet, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { WEAPON_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
|
||||
const { computeCharacterSheet, GEAR_STATS, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { SHEET_INCLUDE, settleHp } = require('../utils/sheet');
|
||||
const { WEAPON_LIBRARY, ITEM_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
|
||||
const { visitedLocationIds } = require('../utils/locations');
|
||||
const { deathSaveInfo } = require('../utils/hp');
|
||||
const { CURRENCIES } = require('../utils/grants');
|
||||
@@ -27,6 +28,8 @@ function campaignSummary(campaign, role) {
|
||||
skipMotivationRoll: campaign.skipMotivationRoll,
|
||||
showMonsterHp: campaign.showMonsterHp,
|
||||
areaAttackAcPenalty: campaign.areaAttackAcPenalty,
|
||||
maxEquipped: campaign.maxEquipped,
|
||||
maxEquippedWeapons: campaign.maxEquippedWeapons,
|
||||
ownerId: campaign.ownerId,
|
||||
archivedAt: campaign.archivedAt,
|
||||
role,
|
||||
@@ -57,6 +60,11 @@ const createCampaignSchema = z.object({
|
||||
skipMotivationRoll: z.boolean().optional(),
|
||||
showMonsterHp: z.boolean().optional(),
|
||||
areaAttackAcPenalty: z.number().int().min(0).max(10).optional(),
|
||||
// How many weapons and items a character can have equipped together, and
|
||||
// how many of those can be weapons. Lowering them takes nothing off anyone:
|
||||
// they are checked when something is put on.
|
||||
maxEquipped: z.number().int().min(1).max(20).optional(),
|
||||
maxEquippedWeapons: z.number().int().min(0).max(20).optional(),
|
||||
});
|
||||
|
||||
// POST /campaigns — create, creator becomes DM/owner
|
||||
@@ -214,7 +222,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, currentLocation: true },
|
||||
include: { ...SHEET_INCLUDE, currentLocation: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
const summaries = characters.map(characterSummary);
|
||||
@@ -312,6 +320,25 @@ router.get('/:id/weapons', requireCampaignMember(), async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
// What a weapon or item does to the sheet of whoever has it equipped: signed
|
||||
// amounts on the numbers in GEAR_STATS (armor is an item with an AC effect),
|
||||
// and a note for what is not a number.
|
||||
const gearEffects = {
|
||||
effects: z
|
||||
.array(z.object({ stat: z.enum(GEAR_STATS), amount: z.number().int().min(-100).max(100).refine((n) => n !== 0, 'An effect of 0 does nothing') }))
|
||||
.max(12)
|
||||
.optional(),
|
||||
effectNote: z.string().trim().max(300).optional().nullable(),
|
||||
};
|
||||
|
||||
// A change to what a pool entry does reaches everyone who has it equipped:
|
||||
// their maximum HP may have dropped, and every open sheet should refetch.
|
||||
async function gearChanged(req, heldModel, poolKey, poolId, holderIds) {
|
||||
const holders = holderIds || (await prisma[heldModel].findMany({ where: { [poolKey]: poolId }, select: { characterId: true } })).map((h) => h.characterId);
|
||||
await settleHp(prisma, holders);
|
||||
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('character:updated', {});
|
||||
}
|
||||
|
||||
const weaponSchema = z.object({
|
||||
name: z.string().min(1).max(80),
|
||||
damageDice: z.string().min(1).max(20),
|
||||
@@ -323,6 +350,7 @@ const weaponSchema = z.object({
|
||||
damageScaling: z.number().int().min(1).max(MAX_DAMAGE_SCALING).optional(),
|
||||
minLevel: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
isStartingOption: z.boolean().optional(),
|
||||
...gearEffects,
|
||||
});
|
||||
|
||||
// Raising a pool entry's starting level lifts every held copy that is now
|
||||
@@ -367,6 +395,7 @@ router.patch('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), asy
|
||||
const weapon = await updatePoolEntry('weapon', req.params.weaponId, req.campaign.id, parsed.data);
|
||||
if (!weapon) return res.status(404).json({ error: 'Weapon not found in this campaign' });
|
||||
await liftHeldCopies('characterWeapon', 'weaponId', weapon.id, parsed.data.minLevel);
|
||||
await gearChanged(req, 'characterWeapon', 'weaponId', weapon.id);
|
||||
res.json({ weapon });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -375,9 +404,11 @@ router.patch('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), asy
|
||||
|
||||
router.delete('/:id/weapons/:weaponId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const holders = (await prisma.characterWeapon.findMany({ where: { weaponId: req.params.weaponId }, select: { characterId: true } })).map((h) => h.characterId);
|
||||
if (!(await deletePoolEntry('weapon', req.params.weaponId, req.campaign.id))) {
|
||||
return res.status(404).json({ error: 'Weapon not found in this campaign' });
|
||||
}
|
||||
await gearChanged(req, 'characterWeapon', 'weaponId', req.params.weaponId, holders);
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -464,6 +495,7 @@ const itemSchema = z.object({
|
||||
damageScaling: z.number().int().min(1).max(MAX_DAMAGE_SCALING).optional(),
|
||||
minLevel: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
|
||||
isStartingOption: z.boolean().optional(),
|
||||
...gearEffects,
|
||||
});
|
||||
|
||||
router.post('/:id/items', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
@@ -484,6 +516,7 @@ router.patch('/:id/items/:itemId', requireCampaignMember(), requireDM(), async (
|
||||
const item = await updatePoolEntry('item', req.params.itemId, req.campaign.id, parsed.data);
|
||||
if (!item) return res.status(404).json({ error: 'Item not found in this campaign' });
|
||||
await liftHeldCopies('inventoryItem', 'itemId', item.id, parsed.data.minLevel);
|
||||
await gearChanged(req, 'inventoryItem', 'itemId', item.id);
|
||||
res.json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -492,9 +525,11 @@ router.patch('/:id/items/:itemId', requireCampaignMember(), requireDM(), async (
|
||||
|
||||
router.delete('/:id/items/:itemId', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const holders = (await prisma.inventoryItem.findMany({ where: { itemId: req.params.itemId }, select: { characterId: true } })).map((h) => h.characterId);
|
||||
if (!(await deletePoolEntry('item', req.params.itemId, req.campaign.id))) {
|
||||
return res.status(404).json({ error: 'Item not found in this campaign' });
|
||||
}
|
||||
await gearChanged(req, 'inventoryItem', 'itemId', req.params.itemId, holders);
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
@@ -891,7 +926,7 @@ router.delete('/:id/wares/:wareId', requireCampaignMember(), requireDM(), async
|
||||
|
||||
router.get('/:id/library', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
res.json({ weapons: WEAPON_LIBRARY, spells: SPELL_LIBRARY, monsters: MONSTER_LIBRARY });
|
||||
res.json({ weapons: WEAPON_LIBRARY, items: ITEM_LIBRARY, spells: SPELL_LIBRARY, monsters: MONSTER_LIBRARY });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
@@ -911,6 +946,20 @@ router.post('/:id/weapons/from-library', requireCampaignMember(), requireDM(), a
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/items/from-library', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ key: z.string() }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const template = ITEM_LIBRARY.find((i) => i.key === parsed.data.key);
|
||||
if (!template) return res.status(404).json({ error: 'Unknown library item.' });
|
||||
const { key, category, ...data } = template;
|
||||
const item = await prisma.item.create({ data: { ...data, campaignId: req.campaign.id } });
|
||||
res.status(201).json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/spells/from-library', requireCampaignMember(), requireDM(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ key: z.string() }).safeParse(req.body);
|
||||
|
||||
@@ -31,6 +31,7 @@ const characterOptions = require('../game/data/characterOptions');
|
||||
const { SKILLS } = require('../game/data/skills');
|
||||
const { CURRENCIES, COINS, COIN_VALUE, COIN_COLUMN, InsufficientGoldError, adjustGold, spendCoins, worthInGold, giveGear } = require('../utils/grants');
|
||||
const { recordVisits } = require('../utils/locations');
|
||||
const { SHEET_INCLUDE, settleHp } = require('../utils/sheet');
|
||||
const { absorbDamage, NO_DEATH_SAVES, lifeState, deathSaveInfo, settleDeathSaves, changeHp, rollDeathSave } = require('../utils/hp');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -150,7 +151,7 @@ const patchCharacterSchema = z.object({
|
||||
name: z.string().min(1).max(80).optional(),
|
||||
currentHp: z.number().int().optional(),
|
||||
tempHp: z.number().int().min(0).max(9999).optional(),
|
||||
armorBonus: z.number().int().min(0).max(30).optional(),
|
||||
armorBonus: z.number().int().min(-30).max(30).optional(),
|
||||
speedOverride: z.number().int().min(0).nullable().optional(),
|
||||
specialAbilities: z.string().max(4000).nullable().optional(),
|
||||
background: z.string().max(4000).nullable().optional(),
|
||||
@@ -165,8 +166,9 @@ const patchCharacterSchema = z.object({
|
||||
// builder composed (special abilities, background, appearance): a player
|
||||
// picks those from lists and cannot type their own. The owning player can
|
||||
// edit the rest of their own sheet. Gold is not patchable at all — it only
|
||||
// moves through the ledger (POST /:id/gold).
|
||||
const DM_ONLY_PATCH_FIELDS = ['level', 'xp', 'currentLocationId', 'speedOverride', 'specialAbilities', 'background', 'appearance'];
|
||||
// moves through the ledger (POST /:id/gold). The armor bonus is the DM's
|
||||
// adjustment on top of what equipped gear gives, so it is the DM's too.
|
||||
const DM_ONLY_PATCH_FIELDS = ['level', 'xp', 'currentLocationId', 'speedOverride', 'armorBonus', 'specialAbilities', 'background', 'appearance'];
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
@@ -181,7 +183,7 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
if (!req.isDM && DM_ONLY_PATCH_FIELDS.some((field) => parsed.data[field] !== undefined)) {
|
||||
return res.status(403).json({ error: 'Only the DM can change level, XP, speed, location, special abilities, background or appearance.' });
|
||||
return res.status(403).json({ error: 'Only the DM can change level, XP, speed, armor bonus, location, special abilities, background or appearance.' });
|
||||
}
|
||||
|
||||
// Damage is soaked by temp HP before it reaches real HP — unless this
|
||||
@@ -190,7 +192,8 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
|
||||
const settingTempHp = parsed.data.tempHp !== undefined;
|
||||
if (req.character.buildStage === 'COMPLETE' && (settingHp || parsed.data.level !== undefined)) {
|
||||
// Current HP stays within 0..max, including when a level change moves max.
|
||||
const maxHp = computeCharacterSheet({ ...req.character, ...parsed.data }).hp.max;
|
||||
const geared = await prisma.character.findUnique({ where: { id: req.character.id }, include: SHEET_INCLUDE });
|
||||
const maxHp = computeCharacterSheet({ ...geared, ...parsed.data }, geared.skillProficiencies, geared.saveProficiencies).hp.max;
|
||||
if (!settingHp) {
|
||||
parsed.data.currentHp = clamp(req.character.currentHp, 0, maxHp);
|
||||
} else {
|
||||
@@ -233,6 +236,8 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
|
||||
where: { characterId: updated.id, spell: { level: { gt: updated.level } } },
|
||||
data: { prepared: false },
|
||||
});
|
||||
// Gear that came off may have been holding the maximum HP up.
|
||||
await settleHp(prisma, [updated.id]);
|
||||
}
|
||||
const full = await loadFullCharacter(updated.id);
|
||||
|
||||
@@ -893,22 +898,53 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
return res.status(400).json({ error: 'Character build is not finished yet.' });
|
||||
}
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
// The pack, the spell list and the purse are the owner's and the DM's to
|
||||
// see, as on the sheet; anyone else gets what is visible across the table.
|
||||
const restricted = !req.isOwner && !req.isDM;
|
||||
const effectsOf = (entry) => ({ effects: Array.isArray(entry.effects) ? entry.effects : [], effectNote: entry.effectNote || null });
|
||||
|
||||
const weapons = character.weapons
|
||||
.filter((cw) => canUseGear(character.level, cw.level))
|
||||
.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
weaponId: cw.weaponId,
|
||||
name: cw.weapon.name,
|
||||
level: cw.level,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level),
|
||||
}));
|
||||
// Everything held is listed, usable or not: `usable` says whether the
|
||||
// character is high enough level for it.
|
||||
const weapons = character.weapons.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
weaponId: cw.weaponId,
|
||||
name: cw.weapon.name,
|
||||
level: cw.level,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
usable: canUseGear(character.level, cw.level),
|
||||
...effectsOf(cw.weapon),
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level),
|
||||
}));
|
||||
const inventory = character.inventoryItems.map((ii) => ({
|
||||
inventoryItemId: ii.id,
|
||||
itemId: ii.itemId,
|
||||
name: ii.item.name,
|
||||
description: ii.item.description,
|
||||
level: ii.level,
|
||||
equipped: ii.equipped,
|
||||
quantity: ii.quantity,
|
||||
usable: canUseGear(character.level, ii.level),
|
||||
damageDice: ii.item.damageDice ? scaledDamageDice(ii.item.damageDice, ii.level, ii.item.damageScaling, ii.item.minLevel) : null,
|
||||
...effectsOf(ii.item),
|
||||
}));
|
||||
const spells = character.spells.map((cs) => ({
|
||||
characterSpellId: cs.id,
|
||||
name: cs.spell.name,
|
||||
level: cs.spell.level,
|
||||
damageDice: cs.spell.damageDice,
|
||||
description: cs.spell.description,
|
||||
prepared: cs.prepared,
|
||||
usable: canUseGear(character.level, cs.spell.level),
|
||||
}));
|
||||
|
||||
res.json({
|
||||
quickStats: {
|
||||
id: character.id,
|
||||
name: character.name,
|
||||
level: character.level,
|
||||
species: character.species,
|
||||
characterClass: character.characterClass,
|
||||
currentHp: character.currentHp,
|
||||
maxHp: sheet.hp.max,
|
||||
tempHp: character.tempHp,
|
||||
@@ -918,8 +954,16 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
speed: sheet.speed,
|
||||
proficiencyBonus: sheet.proficiencyBonus,
|
||||
spellcasting: sheet.spellcasting,
|
||||
passivePerception: sheet.passivePerception,
|
||||
abilities: sheet.abilities,
|
||||
specialAbilities: character.specialAbilities,
|
||||
// What equipped gear is adding and taking away, and what else it does.
|
||||
gear: sheet.gear,
|
||||
weapons,
|
||||
restricted,
|
||||
inventory: restricted ? [] : inventory,
|
||||
spells: restricted ? [] : spells,
|
||||
purse: restricted ? null : { gold: character.gold, silver: character.silver, copper: character.copper, cash: character.cash },
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
@@ -1068,6 +1112,29 @@ const GEAR = [
|
||||
|
||||
const gearLevelSchema = z.number().int().min(1).max(MAX_GEAR_LEVEL);
|
||||
|
||||
// A character can only have so much equipped at once (campaign settings:
|
||||
// weapons and items together, and weapons alone). Returns why `adding` — a
|
||||
// weapon or an item, not yet counted — cannot go on as well, or null if it
|
||||
// can. `exceptPoolId` is the pool entry being equipped, in case it already is.
|
||||
async function equipBlocked(req, kind, exceptPoolId) {
|
||||
const { maxEquipped, maxEquippedWeapons } = req.campaign;
|
||||
const where = { characterId: req.character.id, equipped: true };
|
||||
const [weapons, items] = await Promise.all([
|
||||
prisma.characterWeapon.findMany({ where: { ...where, ...(kind === 'weapon' ? { weaponId: { not: exceptPoolId } } : {}) }, include: { weapon: true } }),
|
||||
prisma.inventoryItem.findMany({ where: { ...where, ...(kind === 'item' ? { itemId: { not: exceptPoolId } } : {}) }, include: { item: true } }),
|
||||
]);
|
||||
const names = (rows, key) => rows.map((row) => row[key].name).join(', ');
|
||||
if (kind === 'weapon' && weapons.length >= maxEquippedWeapons) {
|
||||
if (maxEquippedWeapons === 0) return 'Nobody can equip a weapon in this campaign.';
|
||||
return `${req.character.name} already has ${names(weapons, 'weapon')} equipped, and can hold ${maxEquippedWeapons === 1 ? 'one weapon' : `${maxEquippedWeapons} weapons`} at a time. Unequip it first.`;
|
||||
}
|
||||
if (weapons.length + items.length >= maxEquipped) {
|
||||
const on = [names(weapons, 'weapon'), names(items, 'item')].filter(Boolean).join(', ');
|
||||
return `${req.character.name} already has ${maxEquipped === 1 ? 'something' : `${maxEquipped} things`} equipped (${on}). Unequip one first.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const gear of GEAR) {
|
||||
const uniqueKey = `characterId_${gear.key}`;
|
||||
const whereHeld = (req) => ({ [uniqueKey]: { characterId: req.character.id, [gear.key]: req.params.poolId } });
|
||||
@@ -1105,6 +1172,10 @@ for (const gear of GEAR) {
|
||||
if (parsed.data[gear.flag] && !canUseGear(req.character.level, requiredLevel(parsed.data, entry))) {
|
||||
return res.status(400).json({ error: tooHighMessage(requiredLevel(parsed.data, entry)) });
|
||||
}
|
||||
if (gear.ownLevel && parsed.data.equipped) {
|
||||
const blocked = await equipBlocked(req, gear.pool, poolId);
|
||||
if (blocked) return res.status(400).json({ error: blocked });
|
||||
}
|
||||
|
||||
// Giving something the character already holds adds to the stack (the
|
||||
// stack keeps the level it has).
|
||||
@@ -1114,6 +1185,7 @@ for (const gear of GEAR) {
|
||||
update: gear.ownLevel ? { quantity: { increment: parsed.data.quantity } } : { [gear.flag]: parsed.data[gear.flag] },
|
||||
include,
|
||||
});
|
||||
if (gear.ownLevel) await settleHp(prisma, [req.character.id]);
|
||||
emitCharacterUpdated(req);
|
||||
res.status(201).json({ [gear.held]: row });
|
||||
} catch (err) {
|
||||
@@ -1145,8 +1217,13 @@ for (const gear of GEAR) {
|
||||
if (data[gear.flag]) return res.status(400).json({ error: tooHighMessage(needed) });
|
||||
data[gear.flag] = false; // levelled past its holder: it comes off
|
||||
}
|
||||
if (gear.ownLevel && data.equipped && !existing.equipped) {
|
||||
const blocked = await equipBlocked(req, gear.pool, req.params.poolId);
|
||||
if (blocked) return res.status(400).json({ error: blocked });
|
||||
}
|
||||
|
||||
const row = await prisma[gear.held].update({ where: whereHeld(req), data, include });
|
||||
if (gear.ownLevel) await settleHp(prisma, [req.character.id]);
|
||||
emitCharacterUpdated(req);
|
||||
res.json({ [gear.held]: row });
|
||||
} catch (err) {
|
||||
@@ -1161,6 +1238,7 @@ for (const gear of GEAR) {
|
||||
where: { characterId: req.character.id, [gear.key]: req.params.poolId },
|
||||
});
|
||||
if (count === 0) return res.status(404).json({ error: `This character doesn't have that ${gear.label}.` });
|
||||
if (gear.ownLevel) await settleHp(prisma, [req.character.id]);
|
||||
emitCharacterUpdated(req);
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
@@ -1247,6 +1325,8 @@ router.post('/:id/give', requireCharacterAccess({ write: true }), async (req, re
|
||||
throw err;
|
||||
}
|
||||
|
||||
// What was handed over may have been equipped, and holding the giver's maximum HP up.
|
||||
await settleHp(prisma, [giver.id]);
|
||||
const io = req.app.get('io');
|
||||
for (const characterId of [giver.id, recipient.id]) {
|
||||
io.to(`campaign:${giver.campaignId}`).emit('character:updated', { characterId });
|
||||
|
||||
@@ -3,9 +3,10 @@ const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
const { computeCharacterSheet, computeWeaponStats, canUseGear, abilityModifier, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { computeCharacterSheet, computeWeaponStats, scaledDamageDice, canUseGear, abilityModifier, MAX_GEAR_LEVEL } = require('../game/calculations');
|
||||
const { CURRENCIES, InsufficientGoldError, adjustGold, spendCoins, giveGear } = require('../utils/grants');
|
||||
const { moveCharacters, visitedLocationIds } = require('../utils/locations');
|
||||
const { SHEET_INCLUDE } = require('../utils/sheet');
|
||||
const { NO_DEATH_SAVES, lifeState, deathSaveInfo, changeHp } = require('../utils/hp');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -106,15 +107,26 @@ function revivalSpell(character) {
|
||||
const initiativeRollSchema = z.number().int().min(1, 'An initiative roll is a d20: 1 to 20').max(20, 'An initiative roll is a d20: 1 to 20');
|
||||
|
||||
// What every campaign member sees about a character in an encounter: the
|
||||
// sheet's headline numbers plus the weapons and spells it can actually use —
|
||||
// so the party can plan around each other mid-fight, not only the DM. Uses the
|
||||
// sheet's headline numbers plus what it has in hand — the weapons and items
|
||||
// it has equipped — and the spells it can cast, so the party can plan around
|
||||
// each other mid-fight, not only the DM. A weapon has to be equipped to be
|
||||
// used; what is still in the pack is in the character panel, for the
|
||||
// character's own player and the DM. Uses the
|
||||
// same calculation-engine functions as the sheet, never re-deriving formulas.
|
||||
function characterCombatInfo(character) {
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
// Gear and spells above the character's level are held but can't be used,
|
||||
// so they stay out of the fight.
|
||||
// so they stay out of the fight; so does anything not equipped.
|
||||
const inHand = (held) => held.equipped && canUseGear(character.level, held.level);
|
||||
const items = character.inventoryItems.filter(inHand).map((ii) => ({
|
||||
inventoryItemId: ii.id,
|
||||
name: ii.item.name,
|
||||
level: ii.level,
|
||||
quantity: ii.quantity,
|
||||
damageDice: ii.item.damageDice ? scaledDamageDice(ii.item.damageDice, ii.level, ii.item.damageScaling, ii.item.minLevel) : null,
|
||||
}));
|
||||
const weapons = character.weapons
|
||||
.filter((cw) => canUseGear(character.level, cw.level))
|
||||
.filter(inHand)
|
||||
.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
name: cw.weapon.name,
|
||||
@@ -149,7 +161,10 @@ function characterCombatInfo(character) {
|
||||
abilities: sheet.abilities,
|
||||
saves: sheet.saves,
|
||||
specialAbilities: character.specialAbilities,
|
||||
// What equipped gear is adding and taking away. The numbers above already include it.
|
||||
gear: sheet.gear,
|
||||
weapons,
|
||||
items,
|
||||
spells,
|
||||
spellcasting: sheet.spellcasting,
|
||||
};
|
||||
@@ -180,9 +195,7 @@ async function serializeEncounter(encounterId, isDM, viewerId) {
|
||||
include: {
|
||||
character: {
|
||||
include: {
|
||||
skillProficiencies: true,
|
||||
saveProficiencies: true,
|
||||
weapons: { include: { weapon: true } },
|
||||
...SHEET_INCLUDE,
|
||||
spells: { include: { spell: true } },
|
||||
},
|
||||
},
|
||||
@@ -365,7 +378,7 @@ router.post('/:id/participants', requireEncounterAccess, requireDM, async (req,
|
||||
if (characterId) {
|
||||
const character = await prisma.character.findUnique({
|
||||
where: { id: characterId },
|
||||
include: { skillProficiencies: true, saveProficiencies: true },
|
||||
include: SHEET_INCLUDE,
|
||||
});
|
||||
if (!character || character.campaignId !== req.encounter.campaignId) {
|
||||
return res.status(400).json({ error: 'That character is not part of this campaign.' });
|
||||
@@ -436,7 +449,7 @@ router.patch('/:id/participants/:participantId', requireEncounterAccess, async (
|
||||
|
||||
const existing = await prisma.encounterParticipant.findUnique({
|
||||
where: { id: req.params.participantId },
|
||||
include: { character: { include: { skillProficiencies: true, saveProficiencies: true } }, monster: true },
|
||||
include: { character: { include: SHEET_INCLUDE }, monster: true },
|
||||
});
|
||||
if (!existing || existing.encounterId !== req.encounter.id) {
|
||||
return res.status(404).json({ error: 'Combatant not found in this encounter' });
|
||||
|
||||
Reference in New Issue
Block a user