Settle multiple immediate deal payments
Verify and publish checkpoint container / container (push) Successful in 10m59s

This commit is contained in:
Quintine committed 2026-11-16 14:44:06 +11:00
1 parent cacc88906c
commit b03efd2371
11 files changed
+652 -18

No files matched your search

+10 -5
View File
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import type { DatabaseSync } from 'node:sqlite';
import test from 'node:test';
import { applyAction, viewGame, type Game } from '../game/engine';
import { applyAction, synchronizeAuctionClock, viewGame, type Game } from '../game/engine';
import type * as Rooms from '../db/rooms';
import { unitStore } from './fixture-nexus-room-store';
import {
@@ -87,6 +87,11 @@ async function fixture(
allow: true,
});
assert.equal(game.decision?.kind, 'bureaucratPayment');
// Store the same paused native clock that an authenticated room read would
// initialize; the fixture is testing the payment continuation, not migration
// from an unclocked staged auction.
game = synchronizeAuctionClock(game, clock.now(), '0:0');
assert.equal(game.decision?.kind, 'bureaucratPayment');
game.version = 41;
const code = game.code,
event = game.decision!.event!;
@@ -126,8 +131,8 @@ async function views(f: Awaited<ReturnType<typeof fixture>>, game: Game) {
room = f.restart();
for (const player of game.players) {
const auth = await room.authenticate(f.code, f.tokens[player.id]);
const view = await room.readSeatView(f.code, auth);
assert.deepEqual(view, viewGame(game, player.id));
const view = await room.readSeatView(f.code, auth, clock);
assert.deepEqual(view, viewGame(game, player.id, clock.now()));
assert.equal('bureaucratPayments' in view, false);
assert.equal('bureaucratUseEvents' in view, false);
for (const rival of view.players.filter((p) => p.id !== player.id)) {
@@ -341,10 +346,10 @@ void test('saved normal, Richese cache and Black Market payments resume card cus
assert.ok(!JSON.stringify(viewGame(after, 'g')).includes(purchased));
const saved = rows(f.sqlite);
await assert.rejects(
f.restart().act(f.code, f.auths.b, 41, action),
f.restart().act(f.code, f.auths.b, 41, action, clock),
/table changed/,
);
await assert.rejects(f.restart().act(f.code, f.auths.b, 42, action));
await assert.rejects(f.restart().act(f.code, f.auths.b, 42, action, clock));
assert.deepEqual(rows(f.sqlite), saved);
assert.deepEqual(
f.writes.map((write) => write.changes),
@@ -0,0 +1,80 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { applyAction, normalizeAutomaticGame, viewGame, type Action, type Game } from '../game/engine';
import { bureaucratPaymentGame, bureaucratPlayer as player, bureaucratReload } from './bureaucrat-payment-fixture';
const payment = (amount: number) => ({ kind:'immediateBribe', payer:'p', recipient:'e', amount } as const);
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => applyAction(game,actor,action));
assert.deepEqual(game,before,'Rejected actions cannot change the saved settlement.');
}
/** The shared fixture uses genuine Leader Skills setup, then stages a conserved
* quiet position and balances. All deal consent, native bribes, Bureaucrat
* decisions and continuation below use real actions. */
for (const trigger of ['first','second'] as const) for (const redirect of [false,true]) {
void test(`multiple immediate payments resume after the ${trigger} Bureaucrat opportunity (${redirect ? 'redirect' : 'pass'})`, () => {
const initial = bureaucratPaymentGame(), first = trigger === 'first' ? 5 : 1;
const second = trigger === 'second' ? 5 : 1;
let game = applyAction(initial,'p',{type:'dealOffer',target:'e',terms:'Two immediate bribes.',
payment:payment(first),additionalImmediatePayments:[payment(second)]});
const id = game.deals?.at(-1)?.id; assert.ok(id);
assert.equal(player(game,'p').spice,30); assert.equal(player(game,'e').bribes,0);
game = applyAction(game,'e',{type:'dealRespond',deal:id,accept:true});
assert.equal(game.deals?.find(deal => deal.id === id)?.status,'active');
assert.equal(game.decision?.kind,'bureaucratPayment');
const event = game.bureaucratPaymentEvent; assert.ok(event);
assert.equal(player(game,'p').spice,trigger === 'first' ? 25 : 24);
assert.equal(player(game,'e').bribes,trigger === 'first' ? 0 : 1);
assert.equal(viewGame(game,'b').bureaucrat.pending?.event,event);
reject(game,'p',{type:'bribe',target:'e',amount:1});
reject(game,'e',{type:'dealRelease',deal:id,agree:true});
const saved = bureaucratReload(game);
assert.deepEqual(viewGame(saved,'b').bureaucrat.pending,viewGame(game,'b').bureaucrat.pending);
assert.equal(normalizeAutomaticGame(saved).bureaucratPaymentEvent,event);
game = applyAction(saved,'b',{type:'decision',event,redirect});
assert.equal(game.bureaucratPayments?.pending,undefined);
assert.equal(player(game,'p').spice,24,'Both original gross payments are debited exactly once.');
assert.equal(player(game,'e').bribes,redirect ? 4 : 6,'Only the native redirect is withheld.');
assert.equal(viewGame(game,'b').bureaucrat.usedThisPhase,redirect);
reject(game,'b',{type:'decision',event,redirect});
reject(game,'e',{type:'dealRespond',deal:id,accept:true});
assert.equal(player(game,'p').spice,24);
assert.equal(player(game,'e').bribes,redirect ? 4 : 6);
});
}
void test('passing the first Bureaucrat opportunity preserves the second distinct payment and its decision', () => {
let game = applyAction(bureaucratPaymentGame(),'p',{type:'dealOffer',target:'e',terms:'Two five-spice bribes.',
payment:payment(5),additionalImmediatePayments:[payment(5)]});
const id = game.deals?.at(-1)?.id; assert.ok(id);
game = applyAction(game,'e',{type:'dealRespond',deal:id,accept:true});
const first = game.bureaucratPaymentEvent; assert.ok(first);
assert.equal(player(game,'p').spice,25); assert.equal(player(game,'e').bribes,0);
const forgedCursor = bureaucratReload(game);
assert.ok(forgedCursor.pendingPublicDealSettlement);
forgedCursor.pendingPublicDealSettlement.next = 2;
reject(forgedCursor,'b',{type:'decision',event:first,redirect:false});
const forgedTerms = bureaucratReload(game);
forgedTerms.deals!.find(deal => deal.id === id)!.additionalImmediatePayments![0].amount = 6;
reject(forgedTerms,'b',{type:'decision',event:first,redirect:false});
game = applyAction(bureaucratReload(game),'b',{type:'decision',event:first,redirect:false});
const second = game.bureaucratPaymentEvent; assert.ok(second); assert.notEqual(second,first);
assert.equal(game.decision?.kind,'bureaucratPayment');
assert.equal(player(game,'p').spice,20); assert.equal(player(game,'e').bribes,5);
assert.equal(viewGame(game,'b').bureaucrat.usedThisPhase,false);
reject(game,'b',{type:'decision',event:first,redirect:true});
reject(game,'e',{type:'dealRelease',deal:id,agree:true});
game = applyAction(bureaucratReload(game),'b',{type:'decision',event:second,redirect:true});
assert.equal(game.bureaucratPayments?.pending,undefined);
assert.equal(player(game,'p').spice,20); assert.equal(player(game,'e').bribes,8);
assert.equal(viewGame(game,'b').bureaucrat.usedThisPhase,true);
reject(game,'b',{type:'decision',event:second,redirect:true});
reject(game,'e',{type:'dealRespond',deal:id,accept:true});
assert.equal(player(game,'p').spice,20); assert.equal(player(game,'e').bribes,8);
});
@@ -0,0 +1,117 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import * as jsxRuntime from 'react/jsx-runtime';
import ts from 'typescript';
import * as board from '../game/board';
import * as catalog from '../game/catalog';
import * as coalitionAlliance from '../game/coalition-alliance';
import * as publicDeals from '../game/public-deals';
import { PublicDealList, PublicDeals, publicDealOfferAction } from '../components/public-deals';
import type { Action, GameView } from '../game/engine';
type Element = ReactElement<{children?:ReactNode; [key:string]:unknown}>;
function elements(node: ReactNode): Element[] {
if (Array.isArray(node)) return node.flatMap(elements);
if (!isValidElement<{children?:ReactNode; [key:string]:unknown}>(node)) return [];
return [node,...elements(node.props.children)];
}
function label(node: ReactNode): string {
if (Array.isArray(node)) return node.map(label).join('');
return typeof node === 'string' || typeof node === 'number' ? String(node) : '';
}
const first = {kind:'immediateBribe' as const,payer:'a',recipient:'b',amount:2};
const second = {kind:'immediateBribe' as const,payer:'b',recipient:'a',amount:3};
const deferred = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:1,dueTurn:3};
const base = {status:'playing',turn:2,me:'a',roomControl:null,coalitionState:null,
players:[{id:'a',name:'Alice',faction:'atreides',ally:null},{id:'b',name:'Basil',faction:'harkonnen',ally:null}],
deals:[],deferredDealPaymentOptions:{}} as unknown as GameView;
void test('offer helper retains each immediate term alongside deferred and travel terms', () => {
const travel = {kind:'ship' as const,territory:'carthag',minimum:1,answer:true};
assert.deepEqual(publicDealOfferAction(['b'],' Terms ',first,'a',2,travel,[deferred],[second]),
{type:'dealOffer',target:'b',terms:'Terms',payment:first,travel,
additionalPayments:[deferred],additionalImmediatePayments:[second]});
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[],[first,second]),
{type:'dealOffer',target:'b',terms:'Terms',additionalImmediatePayments:[first,second]});
for (const terms of [[{...first,payer:'outsider'}],[{...first,recipient:'a'}],
[{...first,amount:0}],Array.from({length:13},() => first)])
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[],terms),null);
});
void test('the offer displays all immediate terms to every participant', () => {
const deal = {id:'deal',from:'a',to:'b',terms:'Two immediate payments.',turn:2,status:'offered',releaseVotes:[],
additionalImmediatePayments:[first,second]};
for (const viewer of ['a','b']) {
const game = {...base,me:viewer,deals:[deal]} as unknown as GameView;
const html = renderToStaticMarkup(createElement(PublicDealList,{game,disabled:false,act() {}}));
assert.match(html,/Additional immediate payment 1/); assert.match(html,/Additional immediate payment 2/);
assert.match(html,/Alice \(Atreides\) pays 2 spice to Basil \(Harkonnen\)/);
assert.match(html,/Basil \(Harkonnen\) pays 3 spice to Alice \(Atreides\)/);
assert.match(html,/final acceptance/);
}
});
/** Exercise actual hook callbacks with a stateful React-compatible VM. This
* verifies the component controls, not a hydrated-browser session. */
function form() {
const states:unknown[] = [], refs:{current:unknown}[] = [], sent:Action[] = [];
let stateCursor = 0, refCursor = 0;
const exported:{PublicDeals?:typeof PublicDeals} = {};
runInNewContext(ts.transpileModule(readFileSync(new URL('../components/public-deals.tsx',import.meta.url),'utf8'),{
compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.ReactJSX},
}).outputText,{exports:exported,require(name:string) {
if (name === 'react/jsx-runtime') return jsxRuntime;
if (name === 'react') return {useState(initial:unknown) {
const index = stateCursor++;
if (!(index in states)) states[index] = typeof initial === 'function' ? initial() : initial;
return [states[index],(next:unknown) => {states[index] = typeof next === 'function' ? next(states[index]) : next;}];
},useRef(initial:unknown) {const index = refCursor++; return refs[index] ??= {current:initial};},useEffect() {}};
if (name === '@/components/ui/button') return {Button:'button'};
if (name === '@/game/board') return board;
if (name === '@/game/catalog') return catalog;
if (name === '@/game/coalition-alliance') return coalitionAlliance;
if (name === '@/game/public-deals') return publicDeals;
throw Error(`Unexpected import ${name}`);
}});
assert.ok(exported.PublicDeals);
const render = () => {stateCursor = 0; refCursor = 0;
return elements(exported.PublicDeals!({game:base,busy:false,act(action) {sent.push(action);}}));};
const click = (name:string) => {
const button = render().find(node => node.type === 'button' && label(node.props.children) === name);
assert.ok(button); assert.equal(button.props.disabled,false); (button.props.onClick as () => void)();
};
const field = (index:number) => {
const sets = render().filter(node => node.type === 'fieldset' && elements(node).some(child =>
child.type === 'legend' && JSON.stringify(child.props.children).includes('Additional immediate payment')));
assert.ok(sets[index]); return elements(sets[index]);
};
return {render,click,field,sent};
}
void test('authoring callbacks add, edit and remove immediate terms', () => {
const ui = form();
const recipient = ui.render().find(node => node.type === 'input' && node.props.type === 'checkbox'); assert.ok(recipient);
(recipient.props.onChange as (event:{target:{checked:boolean}}) => void)({target:{checked:true}});
ui.click('Add immediate payment'); ui.click('Add immediate payment');
for (let index = 0; index < 2; index++) {
for (const [position,value] of [[0,index === 0 ? 'a' : 'b'],[1,index === 0 ? 'b' : 'a']] as const) {
const select = ui.field(index).filter(node => node.type === 'select')[position]; assert.ok(select);
(select.props.onChange as (event:{target:{value:string}}) => void)({target:{value}});
}
const input = ui.field(index).find(node => node.type === 'input' && node.props.type === 'number'); assert.ok(input);
(input.props.onChange as (event:{target:{value:string}}) => void)({target:{value:String(index+2)}});
}
ui.click('Remove immediate payment 1');
const terms = ui.render().find(node => node.type === 'textarea'); assert.ok(terms);
(terms.props.onChange as (event:{target:{value:string}}) => void)({target:{value:'One retained immediate payment'}});
const submit = ui.render().find(node => node.type === 'button' && node.props.type === 'submit');
assert.ok(submit); assert.equal(submit.props.disabled,false);
const root = ui.render().find(node => node.type === 'form'); assert.ok(root);
(root.props.onSubmit as (event:{preventDefault():void}) => void)({preventDefault() {}});
assert.deepEqual(JSON.parse(JSON.stringify(ui.sent)),[{type:'dealOffer',target:'b',terms:'One retained immediate payment',
additionalImmediatePayments:[second]}]);
});
@@ -0,0 +1,65 @@
// @dune-suite integration
import assert from 'node:assert/strict';
import test from 'node:test';
import type { GameView } from '../game/engine';
const base = process.env.DUNE_TEST_URL ?? 'http://localhost:3000';
async function request(path:string,cookie?:string,body?:unknown,selected?:string) {
const response = await fetch(base+path,{
method:body === undefined ? 'GET' : 'POST',signal:AbortSignal.timeout(15_000),
headers:{...(body === undefined ? {} : {'Content-Type':'application/json'}),
...(cookie ? {cookie} : {}),...(selected ? {'X-Dune-Seat':selected} : {})},
...(body === undefined ? {} : {body:JSON.stringify(body)}),
});
return {status:response.status,cookie:response.headers.get('set-cookie')?.split(';')[0],
data:await response.json() as GameView & {error?:string}};
}
/** Create a fresh test room; do not use or remove pre-existing games. */
void test('authenticated final consent settles each immediate payment exactly once', async () => {
const host = await request('/api/rooms',undefined,{name:'Immediate recipient',faction:'atreides',advanced:false,expansions:[]});
assert.equal(host.status,201,JSON.stringify(host.data)); assert.ok(host.cookie);
const path = `/api/rooms/${host.data.code}`;
const payer = await request(path,undefined,{type:'join',name:'Immediate payer',faction:'harkonnen'});
assert.equal(payer.status,200,JSON.stringify(payer.data)); assert.ok(payer.cookie);
const seats = [{id:host.data.me,cookie:host.cookie},{id:payer.data.me,cookie:payer.cookie}];
let view = payer.data;
const act = async (cookie:string,action:object) => {
const next = await request(path,cookie,{version:view.version,action});
assert.equal(next.status,200,JSON.stringify(next.data)); view = next.data;
};
for (const seat of seats) await act(seat.cookie,{type:'ready'});
await act(host.cookie,{type:'start'});
for (const seat of seats) {
const own = await request(path,seat.cookie); assert.equal(own.status,200,JSON.stringify(own.data)); view = own.data;
const choices = own.data.players.find(player => player.id === seat.id)?.traitorChoices;
if (choices?.length) await act(seat.cookie,{type:'traitor',leader:choices[0]});
}
assert.equal(view.status,'playing');
const beforePayer = await request(path,payer.cookie), beforeRecipient = await request(path,host.cookie);
assert.equal(beforePayer.status,200); assert.equal(beforeRecipient.status,200); view = beforePayer.data;
const spice = beforePayer.data.players.find(player => player.id === payer.data.me)?.spice;
const incoming = beforeRecipient.data.bribeOptions.incoming;
assert.ok(typeof spice === 'number' && spice >= 5);
const terms = [2,3].map(amount => ({kind:'immediateBribe',payer:payer.data.me,recipient:host.data.me,amount}));
await act(host.cookie,{type:'dealOffer',target:payer.data.me,terms:'Pay two immediate amounts.',additionalImmediatePayments:terms});
const offered = view.deals.at(-1); assert.ok(offered);
assert.equal(offered.status,'offered'); assert.deepEqual(offered.additionalImmediatePayments,terms);
const acceptance = {type:'dealRespond',deal:offered.id,accept:true};
const wrongActor = await request(path,host.cookie,{version:view.version,action:acceptance});
assert.equal(wrongActor.status,409,JSON.stringify(wrongActor.data));
const forged = await request(path,host.cookie,{version:view.version,action:acceptance},payer.data.me);
assert.equal(forged.status,409,JSON.stringify(forged.data));
const beforeVersion = view.version;
await act(payer.cookie,acceptance);
assert.equal(view.deals.find(row => row.id === offered.id)?.status,'active');
const paidPayer = await request(path,payer.cookie), paidRecipient = await request(path,host.cookie);
assert.equal(paidPayer.status,200); assert.equal(paidRecipient.status,200);
assert.equal(paidPayer.data.players.find(player => player.id === payer.data.me)?.spice,spice-5);
assert.equal(paidRecipient.data.bribeOptions.incoming,incoming+5);
const stale = await request(path,payer.cookie,{version:beforeVersion,action:acceptance});
assert.equal(stale.status,409,JSON.stringify(stale.data));
const replay = await request(path,payer.cookie,{version:view.version,action:acceptance});
assert.equal(replay.status,409,JSON.stringify(replay.data));
assert.equal((await request(path,host.cookie)).data.bribeOptions.incoming,incoming+5);
});
@@ -0,0 +1,128 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { viewGame, type Action, type Game } from '../game/engine';
import {
actMentatBribe as act, createMentatBribeFixture as fixture,
mentatBribeInventory as inventory, mentatBribePlayer as player,
} from './fixture-mentat-bribes';
import {
actTruthTravel, createTruthTravelFixture, settleTruthTravel,
truthTravelInventory, truthTravelPlayer,
} from './fixture-truth-travel';
const immediate = (payer: string, recipient: string, amount: number) =>
({kind:'immediateBribe', payer, recipient, amount} as const);
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => act(game,actor,action));
assert.deepEqual(game,before,'Rejected consent or action leaves the original table untouched.');
}
/** Real public Basic H/A/E setup, auction and first Mentat. The inherited
* fixture orders unopened cards and Spice, without fabricating purses or
* commitments. Every offer and vote uses the normal public actions. */
void test('two immediate terms settle once at final consent in their stated order', () => {
const f = fixture(), original = f.game, originalCards = inventory(original);
const first = immediate(f.target,f.asker,2), second = immediate(f.target,f.asker,3);
const offered = act(original,f.asker,{type:'dealOffer',target:f.target,terms:'Two separate payments.',
payment:first,additionalImmediatePayments:[second]});
const id = offered.deals?.at(-1)?.id; assert.ok(id);
assert.equal(player(offered,f.target).spice,10);
assert.equal(player(offered,f.asker).bribes,0);
const logStart = offered.log.length;
let game = act(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(game.deals?.find(row => row.id === id)?.status,'active');
assert.equal(player(game,f.target).spice,5);
assert.equal(player(game,f.asker).bribes,5);
const payments = game.log.slice(logStart).map(row => row.text).filter(text => /paid a \d+-spice bribe/i.test(text));
assert.equal(payments.length,2);
assert.match(payments[0],/paid a 2-spice bribe/i);
assert.match(payments[1],/paid a 3-spice bribe/i);
reject(game,f.target,{type:'dealRespond',deal:id,accept:true});
game = act(game,f.asker,{type:'dealRelease',deal:id,agree:true});
game = act(game,f.target,{type:'dealRelease',deal:id,agree:true});
assert.equal(game.deals?.find(row => row.id === id)?.status,'released');
assert.equal(player(game,f.target).spice,5);
assert.equal(player(game,f.asker).bribes,5);
assert.deepEqual(inventory(game),originalCards);
});
void test('two additional immediate payments work without a legacy payment term', () => {
const f = fixture(), payments = [immediate(f.target,f.asker,2),immediate(f.target,f.asker,2)];
const offered = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'Two matching payments.',
additionalImmediatePayments:payments});
const id = offered.deals?.at(-1)?.id; assert.ok(id);
const done = act(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(done.deals?.find(row => row.id === id)?.status,'active');
assert.equal(player(done,f.target).spice,6);
assert.equal(player(done,f.asker).bribes,4);
reject(done,f.target,{type:'dealRespond',deal:id,accept:true});
assert.deepEqual(inventory(done),f.originalCards);
});
void test('final consent atomically rejects two immediate terms that exceed the same purse', () => {
const f = fixture();
const offered = act(f.game,f.asker,{type:'dealOffer',target:f.target,terms:'An unfunded pair of payments.',
payment:immediate(f.target,f.asker,6),additionalImmediatePayments:[immediate(f.target,f.asker,5)]});
const id = offered.deals?.at(-1)?.id; assert.ok(id);
reject(offered,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(offered.deals?.find(row => row.id === id)?.status,'offered');
assert.equal(player(offered,f.target).spice,10);
assert.equal(player(offered,f.asker).bribes,0);
assert.deepEqual(inventory(offered),f.originalCards);
});
void test('a group settles immediate terms from different payers only after all consent', () => {
const f = fixture(), start = f.game;
const targetBefore = player(start,f.target).spice, otherBefore = player(start,f.opponent).spice;
assert.ok(targetBefore >= 2 && otherBefore >= 1);
let game = act(start,f.asker,{type:'dealOffer',targets:[f.target,f.opponent],terms:'Two separate group payments.',
payment:immediate(f.target,f.asker,2),additionalImmediatePayments:[immediate(f.opponent,f.asker,1)]});
const id = game.deals?.at(-1)?.id; assert.ok(id);
game = act(game,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(game.deals?.find(row => row.id === id)?.status,'offered');
assert.equal(player(game,f.target).spice,targetBefore);
assert.equal(player(game,f.opponent).spice,otherBefore);
assert.equal(player(game,f.asker).bribes,0);
game = act(game,f.opponent,{type:'dealRespond',deal:id,accept:true});
assert.equal(game.deals?.find(row => row.id === id)?.status,'active');
assert.equal(player(game,f.target).spice,targetBefore-2);
assert.equal(player(game,f.opponent).spice,otherBefore-1);
assert.equal(player(game,f.asker).bribes,3);
reject(game,f.opponent,{type:'dealRespond',deal:id,accept:true});
assert.deepEqual(inventory(game),f.originalCards);
});
void test('immediate payments, deferred payment and travel share actual resources', () => {
const f = createTruthTravelFixture(), initial = f.game, originalCards = truthTravelInventory(initial);
const cash = truthTravelPlayer(initial,f.target).spice, incoming = truthTravelPlayer(initial,f.asker).bribes;
assert.ok(cash >= f.shipmentCost+4);
let game = actTruthTravel(initial,f.asker,{type:'dealOffer',target:f.target,terms:'Pay and make the shipment.',
payment:immediate(f.target,f.asker,1),additionalImmediatePayments:[immediate(f.target,f.asker,2)],
additionalPayments:[{kind:'deferredBribe',payer:f.target,recipient:f.asker,amount:1,dueTurn:initial.turn}],
travel:{kind:'ship',territory:f.shipmentTerritory,minimum:1,answer:true}});
const id = game.deals?.at(-1)?.id; assert.ok(id);
game = actTruthTravel(game,f.target,{type:'dealRespond',deal:id,accept:true});
assert.equal(truthTravelPlayer(game,f.target).spice,cash-3);
assert.equal(truthTravelPlayer(game,f.asker).bribes,incoming+3);
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'pending');
assert.equal(game.deals?.find(row => row.id === id)?.additionalPayments?.[0].paymentStatus,'pending');
game = settleTruthTravel(actTruthTravel(game,f.target,f.shipmentAction));
game = actTruthTravel(game,f.target,{type:'dealPay',deal:id,paymentIndex:0});
assert.equal(truthTravelPlayer(game,f.target).spice,cash-4-f.shipmentCost);
assert.equal(truthTravelPlayer(game,f.asker).bribes,incoming+4);
assert.equal(game.deals?.find(row => row.id === id)?.additionalPayments?.[0].paymentStatus,'paid');
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'fulfilled');
assert.deepEqual(truthTravelInventory(game),originalCards);
});
void test('invalid additional immediate terms reject without creating a deal', () => {
const f = fixture(), good = immediate(f.target,f.asker,1);
const packet = {type:'dealOffer',target:f.target,terms:'Invalid payment.'};
for (const additionalImmediatePayments of [
[{...good,amount:0}], [{...good,payer:f.asker,recipient:f.asker}],
[{...good,payer:f.opponent}], [{...good,kind:'deferredBribe',dueTurn:f.game.turn}],
[{...good,extra:true}],
]) reject(f.game,f.asker,{...packet,additionalImmediatePayments});
});