V1.10.0: NPCs change money and sell things

- An NPC can change gold and cash at a rate of their own ("2 gold = $15"),
  the same both ways. Only gold and cash are taken: no silver, no copper
  and no change, and the amount has to be a whole multiple of the rate.
- An NPC can sell weapons and items from the campaign pools, each with a
  price in any coin or in cash, a level and an optional stock. The wares
  follow the NPC into every quest. An encounter can sell things itself
  too, for a stall with nobody behind it.
- Trading is open only in an NPC quest in progress, never in a battle,
  with an NPC who is in the scene and standing, for a character who is in
  it. Players see every rate and ware and trade for their own character
  in a new Trade card; the DM can trade for anyone.
- Only the DM sets trade up: "Trade" on an NPC's row on the campaign page,
  and the DM's part of the Trade card for an encounter's own wares. A
  ware's price and stock can be edited afterwards.
- Every exchange and purchase is written to the character's money log.
- All packages at version 1.10.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-07 13:45:40 +02:00
co-authored by Claude Opus 5.5
parent bdce3399ee
commit c852ecb2e4
23 changed files with 1281 additions and 65 deletions
+130 -1
View File
@@ -989,7 +989,11 @@ describe('encounters', () => {
await request(app).post(`${e}/participants`).set(dmAuth).send({ characterId: heroId });
const playerView = byName((await request(app).get(e).set(playerAuth)).body.encounter);
expect(playerView['Mayor Orla'].npc).toEqual({ id: mayor.id, name: 'Mayor Orla', role: 'Mayor', disposition: 'HOSTILE', description: 'Tired but kind.' });
// What a player gets is exactly this: the public face, plus what the NPC trades (nothing, here).
expect(playerView['Mayor Orla'].npc).toEqual({
id: mayor.id, name: 'Mayor Orla', role: 'Mayor', disposition: 'HOSTILE', description: 'Tired but kind.',
exchangeGold: null, exchangeCash: null, wares: [],
});
// Deleting an NPC takes it out of the scenes it was in.
expect((await request(app).delete(`${c}/npcs/${hermit.id}`).set(dmAuth)).status).toBe(204);
@@ -2401,3 +2405,128 @@ describe('paying with change', () => {
expect(await purse()).toEqual([0, 6, 5]);
});
});
describe('trade', () => {
itIfDb('changes gold and cash with an NPC and sells wares, in a quest in progress only', async () => {
const { dmAuth, playerAuth, campaign } = await setupCampaign('trade');
const c = `/campaigns/${campaign.id}`;
const heroId = await buildCharacter(campaign.id, playerAuth, 'Aria');
const post = (path, body, auth = dmAuth) => request(app).post(path).set(auth).send(body);
// An NPC's rate has two sides, and only the DM sets it.
expect((await post(`${c}/npcs`, { name: 'Half', exchangeGold: 2 })).status).toBe(400);
const changer = (await post(`${c}/npcs`, { name: 'Vex', exchangeGold: 2, exchangeCash: 15 })).body.npc;
expect(changer).toMatchObject({ exchangeGold: 2, exchangeCash: 15 });
const baker = (await post(`${c}/npcs`, { name: 'Baker' })).body.npc;
const elsewhere = (await post(`${c}/npcs`, { name: 'Hermit' })).body.npc;
const patchNpc = (id, body) => request(app).patch(`${c}/npcs/${id}`).set(dmAuth).send(body);
expect((await patchNpc(baker.id, { exchangeCash: 3 })).status).toBe(400);
// Wares come from the campaign pools and belong to one seller.
const bread = (await post(`${c}/items`, { name: 'Bread' })).body.item;
const sword = (await post(`${c}/weapons/from-library`, { key: 'longsword' })).body.weapon;
const quest = (await post(`${c}/encounters`, { name: 'Market Day', mode: 'QUEST' })).body.encounter;
const e = `/encounters/${quest.id}`;
expect((await post(`${c}/wares`, { npcId: baker.id, itemId: bread.id, price: 3, currency: 'SILVER' }, playerAuth)).status).toBe(403);
expect((await post(`${c}/wares`, { itemId: bread.id, price: 3 })).status).toBe(400); // no seller
expect((await post(`${c}/wares`, { npcId: baker.id, encounterId: quest.id, itemId: bread.id, price: 3 })).status).toBe(400); // two sellers
expect((await post(`${c}/wares`, { npcId: baker.id, itemId: bread.id, weaponId: sword.id, price: 3 })).status).toBe(400); // two things
expect((await post(`${c}/wares`, { npcId: baker.id, itemId: 'nope', price: 3 })).status).toBe(400);
const loaf = (await post(`${c}/wares`, { npcId: baker.id, itemId: bread.id, price: 3, currency: 'SILVER', stock: 2 })).body.ware;
const blade = (await post(`${c}/wares`, { encounterId: quest.id, weaponId: sword.id, price: 40, currency: 'CASH' })).body.ware;
const relic = (await post(`${c}/wares`, { npcId: elsewhere.id, itemId: bread.id, price: 1 })).body.ware;
expect(loaf).toMatchObject({ stock: 2, level: 1, item: { name: 'Bread' } });
expect(blade.stock).toBeNull();
const npcList = (await request(app).get(`${c}/npcs`).set(dmAuth)).body.npcs;
expect(npcList.find((n) => n.id === baker.id).wares).toHaveLength(1);
await post(`${e}/participants`, { characterId: heroId });
await post(`${e}/participants`, { npcId: changer.id });
const bakerRow = (await post(`${e}/participants`, { npcId: baker.id })).body.participant;
await post(`/characters/${heroId}/gold`, { amount: 10 });
// Players see the rate and everything for sale in the scene.
const seen = (await request(app).get(e).set(playerAuth)).body.encounter;
const seenNpc = (name) => seen.participants.find((p) => p.npc?.name === name).npc;
expect(seenNpc('Vex')).toMatchObject({ exchangeGold: 2, exchangeCash: 15 });
expect(seenNpc('Baker').wares.map((w) => [w.item.name, w.price, w.currency, w.stock])).toEqual([['Bread', 3, 'SILVER', 2]]);
expect(seen.wares.map((w) => w.weapon.name)).toEqual(['Longsword']);
expect(seenNpc('Baker').dmNotes).toBeUndefined();
const exchange = (body, auth = playerAuth) => post(`${e}/exchange`, { characterId: heroId, npcId: changer.id, ...body }, auth);
const buy = (wareId, body = {}, auth = playerAuth) => post(`${e}/wares/${wareId}/buy`, { characterId: heroId, ...body }, auth);
const purse = async () => {
const { gold, silver, copper, cash } = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character;
return { gold, silver, copper, cash };
};
// Nothing is traded before the quest begins, and never in a battle.
expect((await exchange({ from: 'GOLD', amount: 2 })).status).toBe(400);
expect((await buy(loaf.id)).status).toBe(400);
await request(app).patch(e).set(dmAuth).send({ status: 'ACTIVE', mode: 'BATTLE' });
expect((await exchange({ from: 'GOLD', amount: 2 })).status).toBe(400);
expect((await buy(loaf.id)).status).toBe(400);
await request(app).patch(e).set(dmAuth).send({ mode: 'QUEST' });
// Gold and cash only, in whole multiples of the rate, either way.
expect((await exchange({ from: 'SILVER', amount: 10 })).status).toBe(400);
expect((await exchange({ from: 'GOLD', amount: 3 })).status).toBe(400);
expect((await exchange({ from: 'GOLD', amount: 12 })).status).toBe(400); // only has 10
expect((await exchange({ from: 'GOLD', amount: 2, npcId: baker.id })).status).toBe(400); // not a money changer
const changed = await exchange({ from: 'GOLD', amount: 6 });
expect(changed.status).toBe(201);
expect(changed.body).toMatchObject({ received: 45, currency: 'CASH' });
expect(await purse()).toEqual({ gold: 4, silver: 0, copper: 0, cash: 45 });
expect((await exchange({ from: 'CASH', amount: 20 })).status).toBe(400);
expect((await exchange({ from: 'CASH', amount: 15 })).body.received).toBe(2);
expect(await purse()).toEqual({ gold: 6, silver: 0, copper: 0, cash: 30 });
const ledger = (await request(app).get(`/characters/${heroId}/gold`).set(playerAuth)).body.transactions;
expect(ledger.slice(0, 2).map((t) => [t.currency, t.amount, t.reason]).sort()).toEqual([
['CASH', -15, 'Changed with Vex for 2 gold'],
['GOLD', 2, 'Changed with Vex from $15'],
]);
// Buying pays the price (coins make change), hands the thing over and uses up stock.
expect((await buy(relic.id)).status).toBe(400); // that NPC is not here
expect((await buy(blade.id)).status).toBe(400); // $40, has $30
expect((await buy(loaf.id, { quantity: 3 })).status).toBe(400); // only 2 left
const bought = await buy(loaf.id, { quantity: 2 });
expect(bought.status).toBe(201);
expect(await purse()).toEqual({ gold: 5, silver: 4, copper: 0, cash: 30 });
expect((await buy(loaf.id)).body.error).toContain('sold out');
await exchange({ from: 'GOLD', amount: 2 });
expect((await buy(blade.id)).status).toBe(201);
expect(await purse()).toEqual({ gold: 3, silver: 4, copper: 0, cash: 5 });
const sheet = (await request(app).get(`/characters/${heroId}`).set(playerAuth)).body.character;
expect(sheet.inventoryItems.map((i) => [i.item.name, i.quantity])).toEqual([['Bread', 2]]);
expect(sheet.weapons.map((w) => w.weapon.name)).toContain('Longsword');
// A player trades for their own character only; an NPC who is down sells nothing.
const other = await request(app).post('/auth/register').send({ email: uniqueEmail('trade-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);
const otherId = await buildCharacter(campaign.id, otherAuth, 'Bo');
await post(`${e}/participants`, { characterId: otherId });
expect((await buy(blade.id, {}, otherAuth)).status).toBe(403);
expect((await exchange({ from: 'GOLD', amount: 2 }, dmAuth)).status).toBe(201); // the DM can, for anyone
// The DM can reprice and restock a ware; nobody else can.
const patchWare = (auth, body) => request(app).patch(`${c}/wares/${loaf.id}`).set(auth).send(body);
expect((await patchWare(playerAuth, { price: 1 })).status).toBe(403);
expect((await patchWare(dmAuth, { price: 0 })).status).toBe(400);
expect((await patchWare(dmAuth, { stock: 5, price: 1, currency: 'COPPER' })).body.ware).toMatchObject({ stock: 5, price: 1, currency: 'COPPER', item: { name: 'Bread' } });
expect((await patchWare(dmAuth, { stock: null })).body.ware).toMatchObject({ stock: null, price: 1 });
expect((await buy(loaf.id)).status).toBe(201);
expect(await purse()).toEqual({ gold: 1, silver: 3, copper: 9, cash: 20 });
await patchNpc(baker.id, { maxHp: 5 });
await request(app).delete(`${e}/participants/${bakerRow.id}`).set(dmAuth);
const downRow = (await post(`${e}/participants`, { npcId: baker.id })).body.participant;
await request(app).patch(`${e}/participants/${downRow.id}`).set(dmAuth).send({ currentHp: 0 });
expect((await buy(loaf.id)).status).toBe(400);
expect((await request(app).delete(`${c}/wares/${blade.id}`).set(playerAuth)).status).toBe(403);
expect((await request(app).delete(`${c}/wares/${blade.id}`).set(dmAuth)).status).toBe(204);
expect((await request(app).get(e).set(playerAuth)).body.encounter.wares).toEqual([]);
});
});
+104 -1
View File
@@ -8,6 +8,7 @@ const { computeCharacterSheet, MAX_DAMAGE_SCALING, MAX_GEAR_LEVEL } = require('.
const { WEAPON_LIBRARY, SPELL_LIBRARY, MONSTER_LIBRARY } = require('../game/data/library');
const { visitedLocationIds } = require('../utils/locations');
const { deathSaveInfo } = require('../utils/hp');
const { CURRENCIES } = require('../utils/grants');
const router = express.Router();
@@ -645,7 +646,11 @@ router.put('/:id/encounters/order', requireCampaignMember(), requireDM(), async
router.get('/:id/npcs', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const npcs = await prisma.npc.findMany({ where: { campaignId: req.campaign.id }, orderBy: { name: 'asc' } });
const npcs = await prisma.npc.findMany({
where: { campaignId: req.campaign.id },
include: { wares: { include: WARE_INCLUDE, orderBy: { createdAt: 'asc' } } },
orderBy: { name: 'asc' },
});
res.json({ npcs });
} catch (err) {
next(err);
@@ -662,12 +667,31 @@ const npcSchema = z.object({
maxHp: z.number().int().min(1).max(100000).optional().nullable(),
attackBonus: z.number().int().min(-20).max(50).optional().nullable(),
damageDice: z.string().max(20).optional().nullable(),
// The money changer's rate: exchangeGold gold for exchangeCash cash. Both
// null for an NPC who does not change money.
exchangeGold: z.number().int().min(1).max(1000000).optional().nullable(),
exchangeCash: z.number().int().min(1).max(1000000).optional().nullable(),
});
// A rate has two sides: both are given, or both are cleared.
function halfARate(data) {
const sides = [data.exchangeGold, data.exchangeCash];
return sides.some((side) => side === undefined) !== sides.every((side) => side === undefined) || (sides[0] === null) !== (sides[1] === null);
}
const HALF_A_RATE = 'An exchange rate needs both sides: so much gold for so much cash.';
const WARE_INCLUDE = { weapon: true, item: true };
// Open encounter pages refetch: what is for sale in a scene just changed.
function emitTradeChanged(req) {
req.app.get('io').to(`campaign:${req.campaign.id}`).emit('encounter:participant-updated', {});
}
router.post('/:id/npcs', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = npcSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (halfARate(parsed.data)) return res.status(400).json({ error: HALF_A_RATE });
const npc = await prisma.npc.create({ data: { ...parsed.data, campaignId: req.campaign.id } });
res.status(201).json({ npc });
} catch (err) {
@@ -679,8 +703,10 @@ router.patch('/:id/npcs/:npcId', requireCampaignMember(), requireDM(), async (re
try {
const parsed = npcSchema.partial().safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (halfARate(parsed.data)) return res.status(400).json({ error: HALF_A_RATE });
const npc = await updatePoolEntry('npc', req.params.npcId, req.campaign.id, parsed.data);
if (!npc) return res.status(404).json({ error: 'NPC not found in this campaign' });
emitTradeChanged(req);
res.json({ npc });
} catch (err) {
next(err);
@@ -780,6 +806,83 @@ router.delete('/:id/locations/:locationId', requireCampaignMember(), requireDM()
}
});
// ---------------------------------------------------------------------------
// Wares — weapons and items for sale, by an NPC or at an encounter itself.
// Only the DM sets them up. Players see them, and buy, on the encounter page
// (encounters.routes.js); an NPC's wares go wherever the NPC does.
// ---------------------------------------------------------------------------
const wareSchema = z
.object({
npcId: z.string().optional(),
encounterId: z.string().optional(),
weaponId: z.string().optional(),
itemId: z.string().optional(),
price: z.number().int().min(1).max(1000000),
currency: z.enum(CURRENCIES).default('GOLD'),
level: z.number().int().min(1).max(MAX_GEAR_LEVEL).optional(),
stock: z.number().int().min(0).max(9999).optional().nullable(), // null: no limit
})
.refine((data) => Boolean(data.npcId) !== Boolean(data.encounterId), { message: 'Say who sells it: an NPC or an encounter, not both' })
.refine((data) => Boolean(data.weaponId) !== Boolean(data.itemId), { message: 'Pick one weapon or one item to sell' });
router.post('/:id/wares', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = wareSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const data = parsed.data;
const inCampaign = async (model, id) => (id ? prisma[model].findFirst({ where: { id, campaignId: req.campaign.id } }) : null);
const seller = (await inCampaign('npc', data.npcId)) || (await inCampaign('encounter', data.encounterId));
if (!seller) return res.status(400).json({ error: 'That seller is not part of this campaign.' });
const entry = (await inCampaign('weapon', data.weaponId)) || (await inCampaign('item', data.itemId));
if (!entry) return res.status(400).json({ error: `That ${data.weaponId ? 'weapon' : 'item'} is not part of this campaign.` });
const level = data.level ?? entry.minLevel;
if (level < entry.minLevel) {
return res.status(400).json({ error: `${entry.name} starts at level ${entry.minLevel} and can't go below it.` });
}
const ware = await prisma.saleOffer.create({ data: { ...data, level, campaignId: req.campaign.id }, include: WARE_INCLUDE });
emitTradeChanged(req);
res.status(201).json({ ware });
} catch (err) {
next(err);
}
});
// The price and what is left can change; what is sold, and by whom, cannot.
const patchWareSchema = z.object({
price: z.number().int().min(1).max(1000000).optional(),
currency: z.enum(CURRENCIES).optional(),
stock: z.number().int().min(0).max(9999).nullable().optional(),
});
router.patch('/:id/wares/:wareId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
const parsed = patchWareSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
if (!(await updatePoolEntry('saleOffer', req.params.wareId, req.campaign.id, parsed.data))) {
return res.status(404).json({ error: 'Nothing like that is for sale in this campaign' });
}
emitTradeChanged(req);
res.json({ ware: await prisma.saleOffer.findUnique({ where: { id: req.params.wareId }, include: WARE_INCLUDE }) });
} catch (err) {
next(err);
}
});
router.delete('/:id/wares/:wareId', requireCampaignMember(), requireDM(), async (req, res, next) => {
try {
if (!(await deletePoolEntry('saleOffer', req.params.wareId, req.campaign.id))) {
return res.status(404).json({ error: 'Nothing like that is for sale in this campaign' });
}
emitTradeChanged(req);
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------------------------------------------------------------------------
// Default content library — static SRD-style weapons/spells/monsters any
// campaign can pull from, instead of the DM hand-typing everything. See
+151 -3
View File
@@ -4,7 +4,7 @@ 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 { CURRENCIES, adjustGold, giveGear } = require('../utils/grants');
const { CURRENCIES, InsufficientGoldError, adjustGold, spendCoins, giveGear } = require('../utils/grants');
const { moveCharacters, visitedLocationIds } = require('../utils/locations');
const { NO_DEATH_SAVES, lifeState, deathSaveInfo, changeHp } = require('../utils/hp');
@@ -155,9 +155,14 @@ function characterCombatInfo(character) {
};
}
// What is for sale, oldest first, with the weapon or item itself.
const WARES = { include: { weapon: true, item: true }, orderBy: { createdAt: 'asc' } };
// The DM gets everything. Players get the scene as their characters see it:
// no DM notes, no monster stat blocks, no NPC secrets or stats, and only the
// rewards that have actually been handed out. The fallen (isFallen) are left
// rewards that have actually been handed out. What an NPC sells and the rate
// they change money at are for everyone: `npc.wares`, `npc.exchangeGold` and
// `npc.exchangeCash`, and the scene's own `wares`. The fallen (isFallen) are left
// out of a player's list altogether; of those, only the dead characters are
// named, in `fallen`, so an ally can try to revive them.
//
@@ -182,10 +187,11 @@ async function serializeEncounter(encounterId, isDM, viewerId) {
},
},
monster: true,
npc: true,
npc: { include: { wares: WARES } },
},
},
rewards: { include: { weapon: true, item: true }, orderBy: { createdAt: 'asc' } },
wares: WARES,
},
});
if (!encounter) return encounter;
@@ -777,4 +783,146 @@ router.post('/:id/rewards/:rewardId/award', requireEncounterAccess, requireDM, a
}
});
// ---------------------------------------------------------------------------
// Trade — changing gold and cash with an NPC, and buying what is for sale.
// The DM sets the rates and the wares up (campaigns.routes.js); here the
// players, or the DM for them, use them.
// ---------------------------------------------------------------------------
class TradeError extends Error {
constructor(message, status = 400) {
super(message);
this.status = status;
}
}
function money(amount, currency) {
return currency === 'CASH' ? `$${amount}` : `${amount} ${currency.toLowerCase()}`;
}
// Trading takes someone to trade with and the time to do it, so it happens
// in a quest in progress and never in a battle.
function assertTradeOpen(encounter) {
if (encounter.mode !== 'QUEST') throw new TradeError('Trading happens in a quest, not in a battle.');
if (encounter.status !== 'ACTIVE') throw new TradeError('Trading opens once the quest is in progress.');
}
// The character doing the trading: in this scene, alive, and the player's
// own (the DM can trade for anyone).
async function loadTrader(req, characterId) {
const row = await prisma.encounterParticipant.findFirst({ where: { encounterId: req.encounter.id, characterId }, include: { character: true } });
if (!row) throw new TradeError('That character is not in this encounter.');
if (!req.isDM && row.character.userId !== req.user.id) throw new TradeError('You can only trade for your own character.', 403);
if (isFallen(row)) throw new TradeError(`${row.character.name} is dead.`);
return row.character;
}
// An NPC to trade with has to be in the scene and still standing.
async function loadTradingNpc(req, npcId) {
const row = await prisma.encounterParticipant.findFirst({ where: { encounterId: req.encounter.id, npcId }, include: { npc: true } });
if (!row || isFallen(row)) throw new TradeError('That NPC is not here to trade with.');
return row.npc;
}
function tradeRoute(handler) {
return async (req, res, next) => {
try {
assertTradeOpen(req.encounter);
await handler(req, res);
} catch (err) {
if (err instanceof TradeError) return res.status(err.status).json({ error: err.message });
next(err);
}
};
}
// Changes gold into cash, or cash into gold, at the NPC's own rate. Only
// gold counts: silver and copper are not taken, and none come back. `amount`
// is what is handed over, and has to come to a whole number the other way.
router.post(
'/:id/exchange',
requireEncounterAccess,
tradeRoute(async (req, res) => {
const parsed = z
.object({ characterId: z.string(), npcId: z.string(), from: z.enum(['GOLD', 'CASH']), amount: z.number().int().min(1).max(1000000) })
.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { characterId, npcId, from, amount } = parsed.data;
const to = from === 'GOLD' ? 'CASH' : 'GOLD';
const character = await loadTrader(req, characterId);
const npc = await loadTradingNpc(req, npcId);
if (!npc.exchangeGold || !npc.exchangeCash) throw new TradeError(`${npc.name} does not change money.`);
const rate = { GOLD: npc.exchangeGold, CASH: npc.exchangeCash };
if (amount % rate[from] !== 0) {
throw new TradeError(
`${npc.name} gives ${money(rate.CASH, 'CASH')} for ${money(rate.GOLD, 'GOLD')}: hand over ${from.toLowerCase()} in multiples of ${rate[from]}.`
);
}
const received = (amount / rate[from]) * rate[to];
try {
await prisma.$transaction(async (tx) => {
const base = { characterId: character.id, userId: req.user.id };
await adjustGold(tx, { ...base, currency: from, amount: -amount, reason: `Changed with ${npc.name} for ${money(received, to)}` });
await adjustGold(tx, { ...base, currency: to, amount: received, reason: `Changed with ${npc.name} from ${money(amount, from)}` });
});
} catch (err) {
if (!(err instanceof InsufficientGoldError)) throw err;
throw new TradeError(`${character.name} only has ${money(from === 'GOLD' ? character.gold : character.cash, from)}.`);
}
emitCharacterUpdated(req, character.id);
await respondWithEncounter(req, res, 201, { received, currency: to });
})
);
// Buys something that is for sale here: from an NPC in the scene, or from the
// scene itself. The price is paid from the purse (coins make change; a cash
// price takes cash), and the weapon or item joins what the character holds.
router.post(
'/:id/wares/:wareId/buy',
requireEncounterAccess,
tradeRoute(async (req, res) => {
const parsed = z.object({ characterId: z.string(), quantity: z.number().int().min(1).max(999).default(1) }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error.flatten() });
const { characterId, quantity } = parsed.data;
const character = await loadTrader(req, characterId);
const ware = await prisma.saleOffer.findUnique({ where: { id: req.params.wareId }, include: { weapon: true, item: true } });
if (!ware || ware.campaignId !== req.encounter.campaignId || (ware.encounterId && ware.encounterId !== req.encounter.id)) {
throw new TradeError('That is not for sale here.', 404);
}
const seller = ware.npcId ? (await loadTradingNpc(req, ware.npcId)).name : null;
const kind = ware.weapon ? 'weapon' : 'item';
const entry = ware[kind];
const total = ware.price * quantity;
try {
await prisma.$transaction(async (tx) => {
if (ware.stock !== null) {
// The atomic decrement is the stock check: two buyers can't both take the last one.
const taken = await tx.saleOffer.updateMany({ where: { id: ware.id, stock: { gte: quantity } }, data: { stock: { decrement: quantity } } });
if (taken.count === 0) throw new TradeError(ware.stock === 0 ? `${entry.name} is sold out.` : `Only ${ware.stock} of ${entry.name} left.`);
}
const what = `${quantity > 1 ? `${quantity} × ` : ''}${entry.name}`;
await spendCoins(tx, {
characterId: character.id,
amount: total,
currency: ware.currency,
reason: seller ? `Bought ${what} from ${seller}` : `Bought ${what}`,
userId: req.user.id,
});
await giveGear(tx, kind, { characterId: character.id, entry, quantity, level: ware.level });
});
} catch (err) {
if (!(err instanceof InsufficientGoldError)) throw err;
throw new TradeError(`${character.name} can't afford that: it costs ${money(total, ware.currency)}.`);
}
emitCharacterUpdated(req, character.id);
await respondWithEncounter(req, res, 201);
})
);
module.exports = router;