V1.1.0: gear levels, encounter overhaul, guided builder, trading, docs
Characters - Builder: pick-then-Next on every step with live preview, Back button, plain-language help throughout, and "Suggest for me" for ability scores - Motivation is picked from a list; new steps for special abilities, background and appearance, all composed from fixed lists and DM-only to edit afterwards - Copy a character to another campaign - Characters can give gold, weapons, items and spells to each other - Money tracker: gold only changes through a logged ledger - Fixes: level/XP/location are DM-only, HP stays within 0..max, physical dice ability rolls, every die is rolled once Gear - DM-managed item pool; weapons, items and spells are handed out by the DM - Starting-option flag per pool entry - Gear levels 1-9 per held copy with a damage ladder, growth rate and starting level; spells gated by spell level with a fixed damage value - Spell library carries default damage; damage is picked from a list Encounters - Battle and NPC quest modes, turn tracking, scene description, DM notes - NPCs, richer combatant cards, conditions from a list - Rewards (gold, weapons, items) lined up and awarded, with gold splitting - Character HP is shared between the sheet and the encounter - Monster stat blocks and NPC secrets are never sent to players Other - Dice roller on every page - Docs for characters, weapons, spells, items, encounters, monsters and NPCs, with full lists generated from the data (npm run docs:lists) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,23 +3,33 @@ const { z } = require('zod');
|
||||
const prisma = require('../db');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCharacterAccess } = require('../middleware/characterAccess');
|
||||
const { loadCampaignMembership } = require('../middleware/campaignAccess');
|
||||
const {
|
||||
computeCharacterSheet,
|
||||
computeWeaponStats,
|
||||
getClassSaveProficiencies,
|
||||
getClassSpellcastingAbility,
|
||||
scaledDamageDice,
|
||||
canUseGear,
|
||||
MAX_GEAR_LEVEL,
|
||||
ABILITIES,
|
||||
} = require('../game/calculations');
|
||||
const {
|
||||
rollDie,
|
||||
rollAbilityScore,
|
||||
abilityScoreFromDice,
|
||||
speciesChoicesForRoll,
|
||||
classChoicesForRoll,
|
||||
autoSelectSkills,
|
||||
validateManualRoll,
|
||||
MOTIVATION_TABLE,
|
||||
validatePicks,
|
||||
composeFromPicks,
|
||||
validateTalents,
|
||||
composeSpecialAbilities,
|
||||
} = require('../game/buildFlow');
|
||||
const characterOptions = require('../game/data/characterOptions');
|
||||
const { SKILLS } = require('../game/data/skills');
|
||||
const { InsufficientGoldError, adjustGold, giveGear } = require('../utils/grants');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -31,7 +41,7 @@ async function loadFullCharacter(id) {
|
||||
include: {
|
||||
skillProficiencies: true,
|
||||
saveProficiencies: true,
|
||||
inventoryItems: true,
|
||||
inventoryItems: { include: { item: true } },
|
||||
weapons: { include: { weapon: true } },
|
||||
spells: { include: { spell: true } },
|
||||
currentLocation: true,
|
||||
@@ -79,13 +89,40 @@ function serializeCharacter(character, isOwner) {
|
||||
buildState: character.buildStage === 'COMPLETE' ? null : character.buildState,
|
||||
skillProficiencies: character.skillProficiencies,
|
||||
saveProficiencies: character.saveProficiencies,
|
||||
inventoryItems: character.inventoryItems,
|
||||
weapons: character.weapons,
|
||||
spells: character.spells,
|
||||
// Each held entry carries what its level works out to: the dice at that
|
||||
// level, and whether this character is high enough level to use it.
|
||||
inventoryItems: character.inventoryItems.map((ii) => ({
|
||||
...ii,
|
||||
scaledDamageDice: ii.item.damageDice
|
||||
? scaledDamageDice(ii.item.damageDice, ii.level, ii.item.damageScaling, ii.item.minLevel)
|
||||
: null,
|
||||
usable: canUseGear(character.level, ii.level),
|
||||
})),
|
||||
weapons: character.weapons.map((cw) => ({
|
||||
...cw,
|
||||
scaledDamageDice: scaledDamageDice(cw.weapon.damageDice, cw.level, cw.weapon.damageScaling, cw.weapon.minLevel),
|
||||
usable: canUseGear(character.level, cw.level),
|
||||
})),
|
||||
spells: character.spells.map((cs) => ({ ...cs, usable: canUseGear(character.level, cs.spell.level) })),
|
||||
sheet: character.buildStage === 'COMPLETE' ? sheet : null,
|
||||
};
|
||||
}
|
||||
|
||||
// The lists the builder's story steps are made of. Static, and the same for
|
||||
// everyone; the page fetches them rather than keeping a second copy.
|
||||
router.get('/build/options', (req, res) => {
|
||||
const { MOTIVATIONS, SPECIES_TRAITS, CLASS_FEATURES, TALENTS, TALENT_PICKS, BACKGROUND_GROUPS, APPEARANCE_GROUPS } = characterOptions;
|
||||
res.json({
|
||||
motivations: MOTIVATIONS,
|
||||
speciesTraits: SPECIES_TRAITS,
|
||||
classFeatures: CLASS_FEATURES,
|
||||
talents: TALENTS,
|
||||
talentPicks: TALENT_PICKS,
|
||||
background: BACKGROUND_GROUPS,
|
||||
appearance: APPEARANCE_GROUPS,
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const character = await loadFullCharacter(req.character.id);
|
||||
@@ -106,16 +143,39 @@ const patchCharacterSchema = z.object({
|
||||
appearance: z.string().max(4000).nullable().optional(),
|
||||
privateNotes: z.string().max(4000).nullable().optional(),
|
||||
currentLocationId: z.string().nullable().optional(),
|
||||
gold: z.number().int().min(0).optional(),
|
||||
level: z.number().int().min(1).max(20).optional(),
|
||||
xp: z.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
// Progression and placement are the DM's call, and so is rewriting what the
|
||||
// builder composed (special abilities, background, appearance): a player
|
||||
// picks those from lists and cannot type their own. The owning player can
|
||||
// edit the rest of their own sheet. Gold is not patchable at all — it only
|
||||
// moves through the ledger (POST /:id/gold).
|
||||
const DM_ONLY_PATCH_FIELDS = ['level', 'xp', 'currentLocationId', 'speedOverride', 'specialAbilities', 'background', 'appearance'];
|
||||
|
||||
function clamp(value, min, max) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
if (req.body && req.body.gold !== undefined) {
|
||||
return res.status(400).json({ error: 'Gold changes go through the money tracker.' });
|
||||
}
|
||||
const parsed = patchCharacterSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
if (!req.isDM && DM_ONLY_PATCH_FIELDS.some((field) => parsed.data[field] !== undefined)) {
|
||||
return res.status(403).json({ error: 'Only the DM can change level, XP, speed, location, special abilities, background or appearance.' });
|
||||
}
|
||||
|
||||
// Current HP stays within 0..max, including when a level change moves max.
|
||||
if (req.character.buildStage === 'COMPLETE' && (parsed.data.currentHp !== undefined || parsed.data.level !== undefined)) {
|
||||
const maxHp = computeCharacterSheet({ ...req.character, ...parsed.data }).hp.max;
|
||||
parsed.data.currentHp = clamp(parsed.data.currentHp ?? req.character.currentHp, 0, maxHp);
|
||||
}
|
||||
|
||||
// privateNotes is for the owning player only — a DM editing someone
|
||||
// else's character (or another player, though write access already
|
||||
// blocks that) should never be able to set it through this route.
|
||||
@@ -131,6 +191,16 @@ router.patch('/:id', requireCharacterAccess({ write: true }), async (req, res, n
|
||||
}
|
||||
|
||||
const updated = await prisma.character.update({ where: { id: req.character.id }, data: parsed.data });
|
||||
if (updated.level < req.character.level) {
|
||||
// Dropping a level can put equipped gear and prepared spells out of reach.
|
||||
const tooHigh = { characterId: updated.id, level: { gt: updated.level } };
|
||||
await prisma.characterWeapon.updateMany({ where: tooHigh, data: { equipped: false } });
|
||||
await prisma.inventoryItem.updateMany({ where: tooHigh, data: { equipped: false } });
|
||||
await prisma.characterSpell.updateMany({
|
||||
where: { characterId: updated.id, spell: { level: { gt: updated.level } } },
|
||||
data: { prepared: false },
|
||||
});
|
||||
}
|
||||
const full = await loadFullCharacter(updated.id);
|
||||
|
||||
// Broadcast payload never includes privateNotes — a socket room has
|
||||
@@ -153,6 +223,154 @@ router.delete('/:id', requireCharacterAccess(), async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Copy to another campaign
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Weapons, spells and items are per-campaign rows, so a copied character's gear
|
||||
// is re-pointed at the target campaign's entry of the same name
|
||||
// (case-insensitive), creating that entry from the source row when the target
|
||||
// doesn't have one. A created entry is never a starting option — that stays
|
||||
// the target DM's decision.
|
||||
// Returns source id -> the target pool row.
|
||||
async function mapPoolByName(tx, model, sourceRows, targetCampaignId) {
|
||||
const existing = await tx[model].findMany({ where: { campaignId: targetCampaignId } });
|
||||
const byName = new Map(existing.map((row) => [row.name.toLowerCase(), row]));
|
||||
const idMap = new Map();
|
||||
for (const { id, campaignId, createdAt, ...fields } of sourceRows) {
|
||||
const key = fields.name.toLowerCase();
|
||||
if (!byName.has(key)) {
|
||||
const created = await tx[model].create({
|
||||
data: { ...fields, isStartingOption: false, campaignId: targetCampaignId },
|
||||
});
|
||||
byName.set(key, created);
|
||||
}
|
||||
idMap.set(id, byName.get(key));
|
||||
}
|
||||
return idMap;
|
||||
}
|
||||
|
||||
// The copy is an independent character owned by whoever made it: the original
|
||||
// is untouched and the two never sync. Campaign-bound state (location, notes,
|
||||
// encounter entries) stays behind, and the copy arrives at full HP.
|
||||
router.post('/:id/copy', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ targetCampaignId: z.string().min(1) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { targetCampaignId } = parsed.data;
|
||||
|
||||
if (!req.isDM && !req.isOwner) {
|
||||
return res.status(403).json({ error: 'You can only copy your own character' });
|
||||
}
|
||||
if (req.character.buildStage !== 'COMPLETE') {
|
||||
return res.status(400).json({ error: 'Finish building this character before copying it.' });
|
||||
}
|
||||
if (targetCampaignId === req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'Pick a different campaign to copy this character into.' });
|
||||
}
|
||||
const targetMembership = await loadCampaignMembership(req.user.id, targetCampaignId);
|
||||
if (!targetMembership) return res.status(403).json({ error: 'Not a member of the target campaign' });
|
||||
|
||||
const source = await loadFullCharacter(req.character.id);
|
||||
const sheet = computeCharacterSheet(source, source.skillProficiencies, source.saveProficiencies);
|
||||
|
||||
const copyId = await prisma.$transaction(async (tx) => {
|
||||
const targetWeapons = await mapPoolByName(tx, 'weapon', source.weapons.map((cw) => cw.weapon), targetCampaignId);
|
||||
const targetSpells = await mapPoolByName(tx, 'spell', source.spells.map((cs) => cs.spell), targetCampaignId);
|
||||
const targetItems = await mapPoolByName(tx, 'item', source.inventoryItems.map((ii) => ii.item), targetCampaignId);
|
||||
|
||||
// Two source entries that differ only by case land on one target row.
|
||||
const items = new Map();
|
||||
for (const ii of source.inventoryItems) {
|
||||
const target = targetItems.get(ii.itemId);
|
||||
const itemId = target.id;
|
||||
const prev = items.get(itemId);
|
||||
items.set(itemId, {
|
||||
itemId,
|
||||
quantity: (prev ? prev.quantity : 0) + ii.quantity,
|
||||
equipped: Boolean(prev && prev.equipped) || ii.equipped,
|
||||
// The target campaign's entry may start at a higher level than the source's.
|
||||
level: Math.max(prev ? prev.level : 1, ii.level, target.minLevel),
|
||||
});
|
||||
}
|
||||
const weapons = new Map();
|
||||
for (const cw of source.weapons) {
|
||||
const target = targetWeapons.get(cw.weaponId);
|
||||
const weaponId = target.id;
|
||||
const prev = weapons.get(weaponId);
|
||||
weapons.set(weaponId, {
|
||||
weaponId,
|
||||
quantity: (prev ? prev.quantity : 0) + cw.quantity,
|
||||
equipped: Boolean(prev && prev.equipped) || cw.equipped,
|
||||
level: Math.max(prev ? prev.level : 1, cw.level, target.minLevel),
|
||||
});
|
||||
}
|
||||
const spells = new Map();
|
||||
for (const cs of source.spells) {
|
||||
const spellId = targetSpells.get(cs.spellId).id;
|
||||
const prev = spells.get(spellId);
|
||||
spells.set(spellId, { spellId, prepared: Boolean(prev && prev.prepared) || cs.prepared });
|
||||
}
|
||||
|
||||
const created = await tx.character.create({
|
||||
data: {
|
||||
campaignId: targetCampaignId,
|
||||
userId: req.user.id,
|
||||
createdById: req.user.id,
|
||||
name: source.name,
|
||||
species: source.species,
|
||||
characterClass: source.characterClass,
|
||||
level: source.level,
|
||||
xp: source.xp,
|
||||
motivation: source.motivation,
|
||||
strScore: source.strScore,
|
||||
dexScore: source.dexScore,
|
||||
conScore: source.conScore,
|
||||
intScore: source.intScore,
|
||||
wisScore: source.wisScore,
|
||||
chaScore: source.chaScore,
|
||||
halfElfBonusAbility1: source.halfElfBonusAbility1,
|
||||
halfElfBonusAbility2: source.halfElfBonusAbility2,
|
||||
currentHp: sheet.hp.max,
|
||||
armorBonus: source.armorBonus,
|
||||
speedOverride: source.speedOverride,
|
||||
specialAbilities: source.specialAbilities,
|
||||
gold: source.gold,
|
||||
background: source.background,
|
||||
appearance: source.appearance,
|
||||
// Same privacy boundary as serializeCharacter: a DM copying a
|
||||
// player's character never carries the player's private notes along.
|
||||
privateNotes: req.isOwner ? source.privateNotes : null,
|
||||
diceMode: source.diceMode,
|
||||
buildStage: 'COMPLETE',
|
||||
skillProficiencies: {
|
||||
create: source.skillProficiencies.map(({ skill, proficient, expertise }) => ({ skill, proficient, expertise })),
|
||||
},
|
||||
saveProficiencies: {
|
||||
create: source.saveProficiencies.map(({ ability, proficient }) => ({ ability, proficient })),
|
||||
},
|
||||
inventoryItems: { create: [...items.values()] },
|
||||
goldTransactions: {
|
||||
create:
|
||||
source.gold > 0
|
||||
? [{ amount: source.gold, balanceAfter: source.gold, reason: 'Carried over from another campaign', createdById: req.user.id }]
|
||||
: [],
|
||||
},
|
||||
weapons: { create: [...weapons.values()] },
|
||||
spells: { create: [...spells.values()] },
|
||||
},
|
||||
});
|
||||
return created.id;
|
||||
});
|
||||
|
||||
const full = await loadFullCharacter(copyId);
|
||||
req.app.get('io').to(`campaign:${targetCampaignId}`).emit('character:created', { character: serializeCharacter(full, false) });
|
||||
res.status(201).json({ character: serializeCharacter(full, true) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Roll-Your-Character build flow — docs/ROLL_YOUR_CHARACTER.md
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -212,12 +430,15 @@ router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (r
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
|
||||
try {
|
||||
// Every die is rolled once. Going back to a step shows the roll that was
|
||||
// already made; it never hands out a fresh one.
|
||||
if (stage === 'ROLLING_SPECIES') {
|
||||
if (buildState.speciesRoll) {
|
||||
return res.status(400).json({ error: 'Species die already rolled for this character — choose from what it offered.' });
|
||||
}
|
||||
const roll = resolveSingleRoll(character, req.body, 6);
|
||||
buildState.speciesRoll = roll;
|
||||
buildState.speciesChoices = speciesChoicesForRoll(roll);
|
||||
delete buildState.species;
|
||||
delete buildState.halfElfBonusAbilities;
|
||||
} else if (stage === 'ROLLING_CLASS') {
|
||||
const alreadyRolled = buildState.classChoices && buildState.classChoices.type !== 'reroll';
|
||||
if (alreadyRolled) {
|
||||
@@ -227,10 +448,6 @@ router.post('/:id/build/roll', requireCharacterAccess({ write: true }), async (r
|
||||
buildState.classRoll = roll;
|
||||
buildState.classChoices = classChoicesForRoll(roll);
|
||||
delete buildState.characterClass;
|
||||
} else if (stage === 'ROLLING_MOTIVATION') {
|
||||
const roll = resolveSingleRoll(character, req.body, 6);
|
||||
buildState.motivationRoll = roll;
|
||||
buildState.motivationText = MOTIVATION_TABLE[roll];
|
||||
} else if (stage === 'ASSIGNING_SCORES') {
|
||||
if (buildState.abilityRolls) {
|
||||
return res.status(400).json({ error: 'Ability scores were already rolled for this character.' });
|
||||
@@ -258,7 +475,9 @@ const chooseSchemas = {
|
||||
halfElfBonusAbilities: z.array(z.enum(HALF_ELF_ELIGIBLE_ABILITIES)).length(2).optional(),
|
||||
}),
|
||||
ROLLING_CLASS: z.object({ characterClass: z.string() }),
|
||||
ROLLING_MOTIVATION: z.object({ motivation: z.string().max(500).optional() }),
|
||||
// Motivation is story only, so it is simply picked from the list (the stage
|
||||
// keeps its old name from when it was a die roll).
|
||||
ROLLING_MOTIVATION: z.object({ motivation: z.number().int() }),
|
||||
ASSIGNING_SCORES: z.object({
|
||||
assignments: z.object({
|
||||
STR: z.number().int().min(0).max(5),
|
||||
@@ -283,18 +502,35 @@ const chooseSchemas = {
|
||||
)
|
||||
.optional(),
|
||||
}),
|
||||
CHOOSING_ABILITIES: z.object({ talents: z.array(z.string()) }),
|
||||
CHOOSING_BACKGROUND: z.object({ picks: z.record(z.array(z.string())) }),
|
||||
CHOOSING_APPEARANCE: z.object({ picks: z.record(z.array(z.string())) }),
|
||||
CHOOSING_EQUIPMENT: z.object({
|
||||
weaponIds: z.array(z.string()).default([]),
|
||||
itemIds: z.array(z.string()).default([]),
|
||||
spellIds: z.array(z.string()).default([]),
|
||||
}),
|
||||
};
|
||||
|
||||
// Every id must be a distinct entry in this campaign's pool that the DM has
|
||||
// marked as a starting option. `reach` narrows that to entries a character of
|
||||
// this level can already use (gear by its starting level, spells by their level).
|
||||
async function allStartingOptions(model, ids, campaignId, reach) {
|
||||
if (new Set(ids).size !== ids.length) return false;
|
||||
if (ids.length === 0) return true;
|
||||
const count = await prisma[model].count({ where: { id: { in: ids }, campaignId, isStartingOption: true, ...reach } });
|
||||
return count === ids.length;
|
||||
}
|
||||
|
||||
const STAGE_ORDER = [
|
||||
'ROLLING_SPECIES',
|
||||
'ROLLING_CLASS',
|
||||
'ROLLING_MOTIVATION',
|
||||
'ASSIGNING_SCORES',
|
||||
'ASSIGNING_PROFICIENCIES',
|
||||
'CHOOSING_ABILITIES',
|
||||
'CHOOSING_BACKGROUND',
|
||||
'CHOOSING_APPEARANCE',
|
||||
'CHOOSING_EQUIPMENT',
|
||||
'COMPLETE',
|
||||
];
|
||||
@@ -351,8 +587,10 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
buildState.motivationText = null;
|
||||
}
|
||||
} else if (stage === 'ROLLING_MOTIVATION') {
|
||||
if (!buildState.motivationRoll) return res.status(400).json({ error: 'Roll for motivation first.' });
|
||||
if (parsed.data.motivation) buildState.motivationText = parsed.data.motivation;
|
||||
const motivation = characterOptions.MOTIVATIONS.find((m) => m.key === parsed.data.motivation);
|
||||
if (!motivation) return res.status(400).json({ error: 'Pick a motivation from the list.' });
|
||||
buildState.motivationChoice = motivation.key;
|
||||
buildState.motivationText = motivation.label;
|
||||
} else if (stage === 'ASSIGNING_SCORES') {
|
||||
if (!buildState.abilityRolls) return res.status(400).json({ error: 'Roll ability scores first.' });
|
||||
const { assignments } = parsed.data;
|
||||
@@ -364,20 +602,41 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
buildState.abilityAssignments = assignments;
|
||||
// Skill proficiencies are auto-generated per the class's SRD "choose N"
|
||||
// rule the moment ability scores are locked in, so the next step has
|
||||
// something to show immediately rather than an empty picker.
|
||||
buildState.skillProficiencies = autoSelectSkills(buildState.characterClass);
|
||||
// something to show immediately rather than an empty picker. They are
|
||||
// generated once per class and remembered: stepping back and forward
|
||||
// again (or switching class and switching back) never re-rolls them.
|
||||
const cls = buildState.characterClass;
|
||||
if (buildState.skillsForClass !== cls) {
|
||||
buildState.autoSkills = { ...(buildState.autoSkills || {}) };
|
||||
buildState.autoSkills[cls] = buildState.autoSkills[cls] || autoSelectSkills(cls);
|
||||
buildState.skillProficiencies = buildState.autoSkills[cls];
|
||||
buildState.skillsForClass = cls;
|
||||
}
|
||||
} else if (stage === 'ASSIGNING_PROFICIENCIES') {
|
||||
// Optional DM override of the auto-generated picks; if omitted, the
|
||||
// auto-generated set from the previous step stands as-is.
|
||||
if (parsed.data.skillProficiencies) {
|
||||
buildState.skillProficiencies = parsed.data.skillProficiencies;
|
||||
}
|
||||
} else if (stage === 'CHOOSING_ABILITIES') {
|
||||
const problem = validateTalents(parsed.data.talents);
|
||||
if (problem) return res.status(400).json({ error: problem });
|
||||
buildState.talents = parsed.data.talents;
|
||||
} else if (stage === 'CHOOSING_BACKGROUND' || stage === 'CHOOSING_APPEARANCE') {
|
||||
const isBackground = stage === 'CHOOSING_BACKGROUND';
|
||||
const groups = isBackground ? characterOptions.BACKGROUND_GROUPS : characterOptions.APPEARANCE_GROUPS;
|
||||
const problem = validatePicks(groups, parsed.data.picks);
|
||||
if (problem) return res.status(400).json({ error: problem });
|
||||
// Keep only the groups that exist, so nothing else rides along in the build state.
|
||||
const picks = Object.fromEntries(groups.map((g) => [g.key, parsed.data.picks[g.key] || []]));
|
||||
buildState[isBackground ? 'backgroundPicks' : 'appearancePicks'] = picks;
|
||||
} else if (stage === 'CHOOSING_EQUIPMENT') {
|
||||
const { weaponIds, spellIds } = parsed.data;
|
||||
const { weaponIds, itemIds, spellIds } = parsed.data;
|
||||
const maxItems = req.campaign.startingItemCount;
|
||||
const maxSpells = req.campaign.startingSpellCount;
|
||||
if (weaponIds.length > maxItems) {
|
||||
return res.status(400).json({ error: `This campaign allows at most ${maxItems} starting item(s).` });
|
||||
// Weapons and items share the one "starting items" allowance.
|
||||
if (weaponIds.length + itemIds.length > maxItems) {
|
||||
return res.status(400).json({ error: `This campaign allows at most ${maxItems} starting item(s), weapons included.` });
|
||||
}
|
||||
const hasSpellcasting = Boolean(getClassSpellcastingAbility(buildState.characterClass));
|
||||
if (spellIds.length > 0 && !hasSpellcasting) {
|
||||
@@ -386,7 +645,18 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
if (spellIds.length > maxSpells) {
|
||||
return res.status(400).json({ error: `This campaign allows at most ${maxSpells} starting spell(s).` });
|
||||
}
|
||||
buildState.equipment = { weaponIds, spellIds };
|
||||
// A new character can only start with what it can already use.
|
||||
const gearInReach = { minLevel: { lte: character.level } };
|
||||
const allOffered =
|
||||
(await allStartingOptions('weapon', weaponIds, req.campaign.id, gearInReach)) &&
|
||||
(await allStartingOptions('item', itemIds, req.campaign.id, gearInReach)) &&
|
||||
(await allStartingOptions('spell', spellIds, req.campaign.id, { level: { lte: character.level } }));
|
||||
if (!allOffered) {
|
||||
return res.status(400).json({
|
||||
error: `Pick only from the starting options the DM has made available for a level ${character.level} character.`,
|
||||
});
|
||||
}
|
||||
buildState.equipment = { weaponIds, itemIds, spellIds };
|
||||
advanceTo = 'CHOOSING_EQUIPMENT'; // stay here; POST /build/finalize completes the character
|
||||
}
|
||||
|
||||
@@ -400,6 +670,40 @@ router.post('/:id/build/choose', requireCharacterAccess({ write: true }), async
|
||||
}
|
||||
});
|
||||
|
||||
// Steps back to the previous step so its choice can be changed. Dice are
|
||||
// never re-rolled: the earlier step comes back with the same roll, the same
|
||||
// options and the previous pick still in place. The only thing dropped is the
|
||||
// equipment selection, which is re-confirmed on the way forward (a change of
|
||||
// class can change which starting spells are allowed).
|
||||
router.post('/:id/build/back', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
const stage = character.buildStage;
|
||||
const buildState = { ...(character.buildState || {}) };
|
||||
|
||||
let backTo;
|
||||
if (stage === 'CHOOSING_EQUIPMENT' && buildState.equipment) {
|
||||
backTo = 'CHOOSING_EQUIPMENT'; // from the finalize prompt back to picking equipment
|
||||
} else {
|
||||
const idx = STAGE_ORDER.indexOf(stage);
|
||||
if (idx <= 0 || stage === 'COMPLETE') {
|
||||
return res.status(400).json({ error: 'There is no earlier step to go back to.' });
|
||||
}
|
||||
backTo = STAGE_ORDER[idx - 1];
|
||||
if (backTo === 'ROLLING_MOTIVATION' && req.campaign.skipMotivationRoll) backTo = 'ROLLING_CLASS';
|
||||
}
|
||||
delete buildState.equipment;
|
||||
|
||||
const updated = await prisma.character.update({
|
||||
where: { id: character.id },
|
||||
data: { buildState, buildStage: backTo },
|
||||
});
|
||||
res.json({ buildStage: updated.buildStage, buildState: updated.buildState });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const character = req.character;
|
||||
@@ -430,6 +734,11 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
|
||||
species: bs.species,
|
||||
characterClass: bs.characterClass,
|
||||
motivation: bs.motivationText || null,
|
||||
// Composed here, from the picks, so the text can only ever say what
|
||||
// the lists allow.
|
||||
specialAbilities: composeSpecialAbilities(bs.species, bs.characterClass, bs.talents || []),
|
||||
background: bs.backgroundPicks ? composeFromPicks(characterOptions.BACKGROUND_GROUPS, bs.backgroundPicks) : null,
|
||||
appearance: bs.appearancePicks ? composeFromPicks(characterOptions.APPEARANCE_GROUPS, bs.appearancePicks) : null,
|
||||
strScore: rolledScores.STR,
|
||||
dexScore: rolledScores.DEX,
|
||||
conScore: rolledScores.CON,
|
||||
@@ -453,6 +762,9 @@ router.post('/:id/build/finalize', requireCharacterAccess({ write: true }), asyn
|
||||
weapons: {
|
||||
create: (bs.equipment.weaponIds || []).map((weaponId) => ({ weaponId, quantity: 1, equipped: false })),
|
||||
},
|
||||
inventoryItems: {
|
||||
create: (bs.equipment.itemIds || []).map((itemId) => ({ itemId, quantity: 1, equipped: false })),
|
||||
},
|
||||
spells: {
|
||||
create: (bs.equipment.spellIds || []).map((spellId) => ({ spellId, prepared: false })),
|
||||
},
|
||||
@@ -488,14 +800,17 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
}
|
||||
const sheet = computeCharacterSheet(character, character.skillProficiencies, character.saveProficiencies);
|
||||
|
||||
const weapons = character.weapons.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
weaponId: cw.weaponId,
|
||||
name: cw.weapon.name,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true),
|
||||
}));
|
||||
const weapons = character.weapons
|
||||
.filter((cw) => canUseGear(character.level, cw.level))
|
||||
.map((cw) => ({
|
||||
characterWeaponId: cw.id,
|
||||
weaponId: cw.weaponId,
|
||||
name: cw.weapon.name,
|
||||
level: cw.level,
|
||||
equipped: cw.equipped,
|
||||
quantity: cw.quantity,
|
||||
...computeWeaponStats(cw.weapon, sheet.abilities, sheet.proficiencyBonus, true, cw.level),
|
||||
}));
|
||||
|
||||
res.json({
|
||||
quickStats: {
|
||||
@@ -518,137 +833,267 @@ router.get('/:id/quick-stats', requireCharacterAccess(), async (req, res, next)
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Weapons assigned to this character
|
||||
// Money tracker — the gold balance only ever changes through this ledger
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/weapons', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
const GOLD_TRANSACTION_INCLUDE = { createdBy: { select: { displayName: true } } };
|
||||
|
||||
router.get('/:id/gold', requireCharacterAccess(), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ weaponId: z.string(), quantity: z.number().int().min(1).default(1) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const weapon = await prisma.weapon.findUnique({ where: { id: parsed.data.weaponId } });
|
||||
if (!weapon || weapon.campaignId !== req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'That weapon is not part of this campaign.' });
|
||||
}
|
||||
|
||||
const characterWeapon = await prisma.characterWeapon.upsert({
|
||||
where: { characterId_weaponId: { characterId: req.character.id, weaponId: parsed.data.weaponId } },
|
||||
create: { characterId: req.character.id, weaponId: parsed.data.weaponId, quantity: parsed.data.quantity },
|
||||
update: { quantity: { increment: parsed.data.quantity } },
|
||||
include: { weapon: true },
|
||||
const transactions = await prisma.goldTransaction.findMany({
|
||||
where: { characterId: req.character.id },
|
||||
include: GOLD_TRANSACTION_INCLUDE,
|
||||
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
||||
});
|
||||
res.status(201).json({ characterWeapon });
|
||||
res.json({ gold: req.character.gold, transactions });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/weapons/:weaponId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({ quantity: z.number().int().min(0).optional(), equipped: z.boolean().optional() })
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const characterWeapon = await prisma.characterWeapon.update({
|
||||
where: { characterId_weaponId: { characterId: req.character.id, weaponId: req.params.weaponId } },
|
||||
data: parsed.data,
|
||||
include: { weapon: true },
|
||||
});
|
||||
res.json({ characterWeapon });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Inventory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/inventory', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
// amount is signed: positive = gained, negative = spent. The owning player
|
||||
// and the DM can both record entries; each one is stamped with who made it.
|
||||
router.post('/:id/gold', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({
|
||||
name: z.string().min(1).max(120),
|
||||
description: z.string().max(2000).optional().nullable(),
|
||||
quantity: z.number().int().min(1).default(1),
|
||||
equipped: z.boolean().default(false),
|
||||
amount: z.number().int().refine((n) => n !== 0, 'Amount cannot be zero'),
|
||||
reason: z.string().trim().max(200).optional().nullable(),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const { amount, reason } = parsed.data;
|
||||
|
||||
const item = await prisma.inventoryItem.create({ data: { ...parsed.data, characterId: req.character.id } });
|
||||
res.status(201).json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/inventory/:itemId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z
|
||||
.object({
|
||||
name: z.string().min(1).max(120).optional(),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
quantity: z.number().int().min(0).optional(),
|
||||
equipped: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const item = await prisma.inventoryItem.update({ where: { id: req.params.itemId }, data: parsed.data });
|
||||
res.json({ item });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id/inventory/:itemId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
await prisma.inventoryItem.delete({ where: { id: req.params.itemId } });
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Spells known by this character
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
router.post('/:id/spells', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ spellId: z.string(), prepared: z.boolean().default(false) }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
|
||||
const spell = await prisma.spell.findUnique({ where: { id: parsed.data.spellId } });
|
||||
if (!spell || spell.campaignId !== req.character.campaignId) {
|
||||
return res.status(400).json({ error: 'That spell is not part of this campaign.' });
|
||||
let transaction;
|
||||
try {
|
||||
// Throwing inside the transaction rolls the balance change back.
|
||||
transaction = await prisma.$transaction((tx) =>
|
||||
adjustGold(tx, { characterId: req.character.id, amount, reason, userId: req.user.id, include: GOLD_TRANSACTION_INCLUDE })
|
||||
);
|
||||
} catch (err) {
|
||||
if (!(err instanceof InsufficientGoldError)) throw err;
|
||||
return res.status(400).json({ error: `Not enough gold — the balance is ${req.character.gold}.` });
|
||||
}
|
||||
|
||||
const characterSpell = await prisma.characterSpell.upsert({
|
||||
where: { characterId_spellId: { characterId: req.character.id, spellId: parsed.data.spellId } },
|
||||
create: { characterId: req.character.id, spellId: parsed.data.spellId, prepared: parsed.data.prepared },
|
||||
update: { prepared: parsed.data.prepared },
|
||||
include: { spell: true },
|
||||
});
|
||||
res.status(201).json({ characterSpell });
|
||||
emitCharacterUpdated(req);
|
||||
res.status(201).json({ gold: transaction.balanceAfter, transaction });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.patch('/:id/spells/:spellId', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = z.object({ prepared: z.boolean() }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
// ---------------------------------------------------------------------------
|
||||
// Gear held by this character — weapons, items and spells all come from the
|
||||
// campaign's DM-managed pools. Only the DM hands them out, changes quantities
|
||||
// or levels, or takes them away; the owning player can toggle equipped /
|
||||
// prepared — but only on gear the character is high enough level to use.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const characterSpell = await prisma.characterSpell.update({
|
||||
where: { characterId_spellId: { characterId: req.character.id, spellId: req.params.spellId } },
|
||||
data: parsed.data,
|
||||
include: { spell: true },
|
||||
});
|
||||
res.json({ characterSpell });
|
||||
function requireDmForGear(req, res) {
|
||||
if (req.isDM) return true;
|
||||
res.status(403).json({ error: 'Only the DM can give, remove, re-count or level up gear.' });
|
||||
return false;
|
||||
}
|
||||
|
||||
function emitCharacterUpdated(req) {
|
||||
req.app.get('io').to(`campaign:${req.character.campaignId}`).emit('character:updated', { characterId: req.character.id });
|
||||
}
|
||||
|
||||
// One set of routes per kind of gear. `key` is the pool-entry id column on the
|
||||
// join row (also the route param), `flag` the boolean the owner may toggle.
|
||||
// A held weapon or item (`ownLevel`) has a quantity and its own level; a spell
|
||||
// has neither, and the level a character needs is the spell's classic level.
|
||||
const GEAR = [
|
||||
{ path: 'weapons', pool: 'weapon', held: 'characterWeapon', key: 'weaponId', flag: 'equipped', ownLevel: true, label: 'weapon' },
|
||||
{ path: 'inventory', pool: 'item', held: 'inventoryItem', key: 'itemId', flag: 'equipped', ownLevel: true, label: 'item' },
|
||||
{ path: 'spells', pool: 'spell', held: 'characterSpell', key: 'spellId', flag: 'prepared', ownLevel: false, label: 'spell' },
|
||||
];
|
||||
|
||||
const gearLevelSchema = z.number().int().min(1).max(MAX_GEAR_LEVEL);
|
||||
|
||||
for (const gear of GEAR) {
|
||||
const uniqueKey = `characterId_${gear.key}`;
|
||||
const whereHeld = (req) => ({ [uniqueKey]: { characterId: req.character.id, [gear.key]: req.params.poolId } });
|
||||
const include = { [gear.pool]: true };
|
||||
|
||||
const requiredLevel = (row, poolEntry) => (gear.ownLevel ? row.level : poolEntry.level);
|
||||
const tooHighMessage = (level) =>
|
||||
`Requires character level ${level} to ${gear.flag === 'prepared' ? 'prepare' : 'equip'} this ${gear.label}.`;
|
||||
|
||||
const belowStartMessage = (entry) => `${entry.name} starts at level ${entry.minLevel} and can't go below it.`;
|
||||
|
||||
const assignSchema = z.object({
|
||||
[gear.key]: z.string(),
|
||||
...(gear.ownLevel ? { quantity: z.number().int().min(1).default(1), level: gearLevelSchema.optional() } : {}),
|
||||
[gear.flag]: z.boolean().default(false),
|
||||
});
|
||||
|
||||
router.post(`/:id/${gear.path}`, requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
if (!requireDmForGear(req, res)) return;
|
||||
const parsed = assignSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const poolId = parsed.data[gear.key];
|
||||
|
||||
const entry = await prisma[gear.pool].findUnique({ where: { id: poolId } });
|
||||
if (!entry || entry.campaignId !== req.character.campaignId) {
|
||||
return res.status(400).json({ error: `That ${gear.label} is not part of this campaign.` });
|
||||
}
|
||||
|
||||
if (gear.ownLevel) {
|
||||
// Given at the entry's starting level unless the DM picks a higher one.
|
||||
parsed.data.level = parsed.data.level ?? entry.minLevel;
|
||||
if (parsed.data.level < entry.minLevel) return res.status(400).json({ error: belowStartMessage(entry) });
|
||||
}
|
||||
if (parsed.data[gear.flag] && !canUseGear(req.character.level, requiredLevel(parsed.data, entry))) {
|
||||
return res.status(400).json({ error: tooHighMessage(requiredLevel(parsed.data, entry)) });
|
||||
}
|
||||
|
||||
// Giving something the character already holds adds to the stack (the
|
||||
// stack keeps the level it has).
|
||||
const row = await prisma[gear.held].upsert({
|
||||
where: { [uniqueKey]: { characterId: req.character.id, [gear.key]: poolId } },
|
||||
create: { characterId: req.character.id, ...parsed.data },
|
||||
update: gear.ownLevel ? { quantity: { increment: parsed.data.quantity } } : { [gear.flag]: parsed.data[gear.flag] },
|
||||
include,
|
||||
});
|
||||
emitCharacterUpdated(req);
|
||||
res.status(201).json({ [gear.held]: row });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
const patchSchema = z.object({
|
||||
...(gear.ownLevel ? { quantity: z.number().int().min(1).optional(), level: gearLevelSchema.optional() } : {}),
|
||||
[gear.flag]: z.boolean().optional(),
|
||||
});
|
||||
|
||||
router.patch(`/:id/${gear.path}/:poolId`, requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = patchSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const dmOnlyChange = parsed.data.quantity !== undefined || parsed.data.level !== undefined;
|
||||
if (dmOnlyChange && !requireDmForGear(req, res)) return;
|
||||
|
||||
const existing = await prisma[gear.held].findUnique({ where: whereHeld(req), include });
|
||||
if (!existing) return res.status(404).json({ error: `This character doesn't have that ${gear.label}.` });
|
||||
|
||||
const data = { ...parsed.data };
|
||||
if (data.level !== undefined && data.level < existing[gear.pool].minLevel) {
|
||||
return res.status(400).json({ error: belowStartMessage(existing[gear.pool]) });
|
||||
}
|
||||
const needed = requiredLevel({ ...existing, ...data }, existing[gear.pool]);
|
||||
if (!canUseGear(req.character.level, needed)) {
|
||||
if (data[gear.flag]) return res.status(400).json({ error: tooHighMessage(needed) });
|
||||
data[gear.flag] = false; // levelled past its holder: it comes off
|
||||
}
|
||||
|
||||
const row = await prisma[gear.held].update({ where: whereHeld(req), data, include });
|
||||
emitCharacterUpdated(req);
|
||||
res.json({ [gear.held]: row });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
router.delete(`/:id/${gear.path}/:poolId`, requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
if (!requireDmForGear(req, res)) return;
|
||||
const { count } = await prisma[gear.held].deleteMany({
|
||||
where: { characterId: req.character.id, [gear.key]: req.params.poolId },
|
||||
});
|
||||
if (count === 0) return res.status(404).json({ error: `This character doesn't have that ${gear.label}.` });
|
||||
emitCharacterUpdated(req);
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Giving to another character — a player (or the DM) hands something this
|
||||
// character holds to another character in the same campaign. It always moves:
|
||||
// whatever is given leaves the giver. That keeps the DM in control of how much
|
||||
// gear, gold and magic exists, while letting the party share it out.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const giveSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('gold'), toCharacterId: z.string(), amount: z.number().int().min(1) }),
|
||||
z.object({ kind: z.literal('weapon'), toCharacterId: z.string(), id: z.string(), quantity: z.number().int().min(1).default(1) }),
|
||||
z.object({ kind: z.literal('item'), toCharacterId: z.string(), id: z.string(), quantity: z.number().int().min(1).default(1) }),
|
||||
z.object({ kind: z.literal('spell'), toCharacterId: z.string(), id: z.string() }),
|
||||
]);
|
||||
|
||||
class GiveError extends Error {}
|
||||
|
||||
router.post('/:id/give', requireCharacterAccess({ write: true }), async (req, res, next) => {
|
||||
try {
|
||||
const parsed = giveSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
|
||||
const give = parsed.data;
|
||||
const giver = req.character;
|
||||
|
||||
const recipient = await prisma.character.findUnique({ where: { id: give.toCharacterId } });
|
||||
if (!recipient || recipient.campaignId !== giver.campaignId) {
|
||||
return res.status(400).json({ error: 'That character is not part of this campaign.' });
|
||||
}
|
||||
if (recipient.id === giver.id) return res.status(400).json({ error: 'Pick a different character to give it to.' });
|
||||
if (giver.buildStage !== 'COMPLETE' || recipient.buildStage !== 'COMPLETE') {
|
||||
return res.status(400).json({ error: 'Both characters must be finished before they can trade.' });
|
||||
}
|
||||
|
||||
try {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
if (give.kind === 'gold') {
|
||||
await adjustGold(tx, { characterId: giver.id, amount: -give.amount, reason: `Gave to ${recipient.name}`, userId: req.user.id });
|
||||
await adjustGold(tx, { characterId: recipient.id, amount: give.amount, reason: `Received from ${giver.name}`, userId: req.user.id });
|
||||
return;
|
||||
}
|
||||
|
||||
if (give.kind === 'spell') {
|
||||
const key = { characterId_spellId: { characterId: giver.id, spellId: give.id } };
|
||||
const known = await tx.characterSpell.findUnique({ where: key, include: { spell: true } });
|
||||
if (!known) throw new GiveError(`${giver.name} doesn't know that spell.`);
|
||||
const already = await tx.characterSpell.findUnique({
|
||||
where: { characterId_spellId: { characterId: recipient.id, spellId: give.id } },
|
||||
});
|
||||
if (already) throw new GiveError(`${recipient.name} already knows ${known.spell.name}.`);
|
||||
await tx.characterSpell.delete({ where: key });
|
||||
await tx.characterSpell.create({ data: { characterId: recipient.id, spellId: give.id } });
|
||||
return;
|
||||
}
|
||||
|
||||
// Weapons and items: take from the giver's stack, add to the
|
||||
// recipient's. A new stack arrives at the giver's level, unequipped; an
|
||||
// existing one just grows and keeps its own level.
|
||||
const model = give.kind === 'weapon' ? 'characterWeapon' : 'inventoryItem';
|
||||
const poolKey = `${give.kind}Id`;
|
||||
const key = { [`characterId_${poolKey}`]: { characterId: giver.id, [poolKey]: give.id } };
|
||||
const held = await tx[model].findUnique({ where: key, include: { [give.kind]: true } });
|
||||
if (!held) throw new GiveError(`${giver.name} doesn't have that ${give.kind}.`);
|
||||
if (give.quantity > held.quantity) {
|
||||
throw new GiveError(`${giver.name} only has ${held.quantity} of ${held[give.kind].name}.`);
|
||||
}
|
||||
if (give.quantity === held.quantity) await tx[model].delete({ where: key });
|
||||
else await tx[model].update({ where: key, data: { quantity: { decrement: give.quantity } } });
|
||||
await giveGear(tx, give.kind, { characterId: recipient.id, entry: held[give.kind], quantity: give.quantity, level: held.level });
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof InsufficientGoldError) {
|
||||
return res.status(400).json({ error: `Not enough gold — ${giver.name} has ${giver.gold}.` });
|
||||
}
|
||||
if (err instanceof GiveError) return res.status(400).json({ error: err.message });
|
||||
throw err;
|
||||
}
|
||||
|
||||
const io = req.app.get('io');
|
||||
for (const characterId of [giver.id, recipient.id]) {
|
||||
io.to(`campaign:${giver.campaignId}`).emit('character:updated', { characterId });
|
||||
}
|
||||
const full = await loadFullCharacter(giver.id);
|
||||
res.json({ character: serializeCharacter(full, req.isOwner) });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user