- 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>
197 lines
8.1 KiB
TypeScript
197 lines
8.1 KiB
TypeScript
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<Record<string, string>>({});
|
|
const [sides, setSides] = useState<Record<string, ExchangeSide>>({});
|
|
const [done, setDone] = useState<string | null>(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 (
|
|
<div className="card">
|
|
<div className="card-title">Trade</div>
|
|
{!open && (
|
|
<p className="combatant-sub" style={{ marginTop: 0 }}>
|
|
{encounter.status === 'PLANNING' ? 'Trading opens once the quest is in progress.' : 'The quest is over; trading is closed.'}
|
|
</p>
|
|
)}
|
|
{traders.length > 0 && (
|
|
<div className="flex-row flex-wrap gap-sm">
|
|
<select aria-label="Who is trading" value={trader?.id ?? ''} onChange={(e) => setTraderId(e.target.value)} style={{ flex: 1, minWidth: 110 }}>
|
|
{traders.map((c) => (
|
|
<option key={c.id} value={c.id}>
|
|
{c.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
{purse && purse.gold !== null && <span className="mono">{formatPurse(purse)}</span>}
|
|
</div>
|
|
)}
|
|
{traders.length === 0 && (changers.length > 0 || openStalls.length > 0) && (
|
|
<p className="combatant-sub">{isDM ? 'Add a character to the scene to trade for them.' : 'Your character has to be in the scene to trade.'}</p>
|
|
)}
|
|
{done && <p className="combatant-sub">✓ {done}</p>}
|
|
|
|
{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 (
|
|
<div key={npc.id} className="reward-row">
|
|
<strong>💱 {npc.name}</strong>
|
|
<span className="combatant-sub">
|
|
{' '}
|
|
changes {formatMoney(rate.GOLD, 'GOLD', true)} for {formatMoney(rate.CASH, 'CASH')}, either way. No silver or copper.
|
|
</span>
|
|
<div className="flex-row flex-wrap gap-sm mt-sm">
|
|
<NumberInput
|
|
min={1}
|
|
max={1000000}
|
|
placeholder="Amount"
|
|
aria-label={`How much to change with ${npc.name}`}
|
|
value={amounts[npc.id] ?? ''}
|
|
onChange={(e) => setAmounts((a) => ({ ...a, [npc.id]: e.target.value }))}
|
|
style={{ width: 90 }}
|
|
/>
|
|
<select
|
|
aria-label={`What to hand ${npc.name}`}
|
|
value={from}
|
|
onChange={(e) => setSides((s) => ({ ...s, [npc.id]: e.target.value as ExchangeSide }))}
|
|
>
|
|
<option value="GOLD">gold into cash</option>
|
|
<option value="CASH">cash into gold</option>
|
|
</select>
|
|
<button className="btn" disabled={!open || !trader || !whole || busy} onClick={() => handleExchange(npc)}>
|
|
{whole ? `Get ${formatMoney((amount / rate[from]) * rate[to], to, true)}` : 'Exchange'}
|
|
</button>
|
|
</div>
|
|
{amount > 0 && !whole && (
|
|
<div className="combatant-sub">
|
|
Hand over {from.toLowerCase()} in multiples of {rate[from]}.
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
|
|
{openStalls.map(([key, label, wares]) => (
|
|
<div key={key} className="mt-sm">
|
|
<div className="section-label">🛒 {label}</div>
|
|
{wares.map((ware) => (
|
|
<div key={ware.id} className="reward-row">
|
|
<div className="flex-between">
|
|
<span>
|
|
<strong>{wareName(ware)}</strong>
|
|
<span className="combatant-sub"> · {stockLabel(ware)}</span>
|
|
</span>
|
|
<button className="btn" disabled={!open || !trader || ware.stock === 0 || busy} onClick={() => handleBuy(ware)}>
|
|
Buy · {formatMoney(ware.price, ware.currency)}
|
|
</button>
|
|
</div>
|
|
{ware.item?.description && <div className="combatant-sub">{ware.item.description}</div>}
|
|
</div>
|
|
))}
|
|
</div>
|
|
))}
|
|
|
|
{isDM && (
|
|
<div className="mt-md">
|
|
<div className="section-label">Set up: for sale at this encounter</div>
|
|
<p className="combatant-sub" style={{ marginTop: 0 }}>
|
|
For a stall or a machine with nobody behind it. An NPC's wares and exchange rate are set under "Trade" on the{' '}
|
|
<Link to={`/campaigns/${encounter.campaignId}`}>campaign page</Link>, and follow the NPC into every quest.
|
|
</p>
|
|
<WaresEditor
|
|
campaignId={encounter.campaignId}
|
|
seller={{ encounterId: encounter.id }}
|
|
wares={encounter.wares ?? []}
|
|
weapons={weapons}
|
|
items={items}
|
|
onError={onError}
|
|
/>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|