import { useState } from 'react'; import { Link } from 'react-router-dom'; import { useBuyWare, useExchangeWithNpc } from '../api/queries'; import { NumberInput } from './NumberInput'; import { WaresEditor } from './Wares'; import { stockLabel, wareName } from '../lib/wares'; import { formatMoney, formatPurse } from '../lib/format'; import type { CharacterSummary, Encounter, Item, SaleOffer, Weapon } from '../api/types'; type ExchangeSide = 'GOLD' | 'CASH'; // Trade in a quest: changing gold and cash with an NPC who does that, at // their own rate, and buying what the NPCs in the scene โ€” or the scene itself // โ€” have for sale. Everyone sees what is on offer; a player trades for their // own character, the DM for anyone. Trading is open only while the quest is in // progress, and there is none in a battle. The DM sets it all up: an NPC's // rate and wares on the campaign page, the scene's own wares here. export function TradePanel({ encounter, isDM, userId, characters, weapons, items, onError, }: { encounter: Encounter; isDM: boolean; userId: string | undefined; characters: CharacterSummary[]; weapons: Weapon[]; items: Item[]; onError: (err: unknown) => void; }) { const exchange = useExchangeWithNpc(encounter.id); const buy = useBuyWare(encounter.id); const [traderId, setTraderId] = useState(''); const [amounts, setAmounts] = useState>({}); const [sides, setSides] = useState>({}); const [done, setDone] = useState(null); if (encounter.mode !== 'QUEST') return null; const here = (encounter.participants ?? []).filter((p) => !p.hidden); const npcs = here.flatMap((p) => (p.npc ? [p.npc] : [])); const changers = npcs.filter((npc) => npc.exchangeGold && npc.exchangeCash); const stalls: [string, string, SaleOffer[]][] = [ ...npcs.map((npc): [string, string, SaleOffer[]] => [npc.id, `${npc.name} sells`, npc.wares ?? []]), ['here', 'For sale here', encounter.wares ?? []], ]; const openStalls = stalls.filter(([, , wares]) => wares.length > 0); if (!isDM && changers.length === 0 && openStalls.length === 0) return null; // Who can do the trading: a player's own characters in the scene, or for the DM anyone's. const traders = here.flatMap((p) => (p.character && (isDM || p.character.userId === userId) ? [p.character] : [])); const trader = traders.find((c) => c.id === traderId) ?? traders[0]; const purse = characters.find((c) => c.id === trader?.id); const open = encounter.status === 'ACTIVE'; const busy = exchange.isPending || buy.isPending; function handleExchange(npc: (typeof changers)[number]) { const from = sides[npc.id] ?? 'GOLD'; const amount = Math.floor(Number(amounts[npc.id])); if (!trader || !(amount > 0)) return; setDone(null); exchange.mutate( { characterId: trader.id, npcId: npc.id, from, amount }, { onError, onSuccess: ({ received, currency }) => { setDone(`${trader.name} changed ${formatMoney(amount, from, true)} for ${formatMoney(received, currency, true)} with ${npc.name}.`); setAmounts((a) => ({ ...a, [npc.id]: '' })); }, } ); } function handleBuy(ware: SaleOffer) { if (!trader) return; setDone(null); buy.mutate( { wareId: ware.id, characterId: trader.id }, { onError, onSuccess: () => setDone(`${trader.name} bought ${(ware.weapon ?? ware.item)?.name} for ${formatMoney(ware.price, ware.currency, true)}.`) } ); } return (
Trade
{!open && (

{encounter.status === 'PLANNING' ? 'Trading opens once the quest is in progress.' : 'The quest is over; trading is closed.'}

)} {traders.length > 0 && (
{purse && purse.gold !== null && {formatPurse(purse)}}
)} {traders.length === 0 && (changers.length > 0 || openStalls.length > 0) && (

{isDM ? 'Add a character to the scene to trade for them.' : 'Your character has to be in the scene to trade.'}

)} {done &&

โœ“ {done}

} {changers.map((npc) => { const from = sides[npc.id] ?? 'GOLD'; const to = from === 'GOLD' ? 'CASH' : 'GOLD'; const rate = { GOLD: npc.exchangeGold ?? 1, CASH: npc.exchangeCash ?? 1 }; const amount = Math.floor(Number(amounts[npc.id])); const whole = amount > 0 && amount % rate[from] === 0; return (
๐Ÿ’ฑ {npc.name} {' '} changes {formatMoney(rate.GOLD, 'GOLD', true)} for {formatMoney(rate.CASH, 'CASH')}, either way. No silver or copper.
setAmounts((a) => ({ ...a, [npc.id]: e.target.value }))} style={{ width: 90 }} />
{amount > 0 && !whole && (
Hand over {from.toLowerCase()} in multiples of {rate[from]}.
)}
); })} {openStalls.map(([key, label, wares]) => (
๐Ÿ›’ {label}
{wares.map((ware) => (
{wareName(ware)} ยท {stockLabel(ware)}
{ware.item?.description &&
{ware.item.description}
}
))}
))} {isDM && (
Set up: for sale at this encounter

For a stall or a machine with nobody behind it. An NPC's wares and exchange rate are set under "Trade" on the{' '} campaign page, and follow the NPC into every quest.

)}
); }