Support multiple deferred payments in public deals
Verify and publish checkpoint container / container (push) Successful in 10m22s

This commit is contained in:
Quintine committed 2026-11-16 14:30:36 +11:00
1 parent 0b8a147388
commit cacc88906c
12 files changed
+742 -50

No files matched your search

@@ -0,0 +1,128 @@
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, publicDealRequests } 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:'deferredBribe' as const,payer:'a',recipient:'b',amount:2,dueTurn:2};
const second = {kind:'deferredBribe' as const,payer:'a',recipient:'b',amount:3,dueTurn:3};
const deal = {id:'deal',from:'a',to:'b',terms:'Two payments.',turn:2,status:'active',releaseVotes:[],
additionalPayments:[{payment:first,paymentStatus:'pending'}, {payment:second,paymentStatus:'pending'}]};
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:[deal],deferredDealPaymentOptions:{'deal:payment:0':{blocked:null},'deal:payment:1':{blocked:'Keep funds for the first payment.'}},
} as unknown as GameView;
void test('offer helper sends distinct exact payment terms with legacy payment and travel', () => {
const immediate = {kind:'immediateBribe' as const,payer:'b',recipient:'a',amount:1};
const travel = {kind:'ship' as const,territory:'carthag',minimum:1,answer:true};
assert.deepEqual(publicDealOfferAction(['b'],' Terms ',immediate,'a',2,travel,[first,second]),
{type:'dealOffer',target:'b',terms:'Terms',payment:immediate,travel,additionalPayments:[first,second]});
assert.deepEqual(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,[]),
{type:'dealOffer',target:'b',terms:'Terms'});
for (const terms of [[{...first,payer:'outsider'}],[{...first,recipient:'a'}],[{...first,amount:0}],
[{...first,dueTurn:1}],Array.from({length:13},() => first)])
assert.equal(publicDealOfferAction(['b'],'Terms',undefined,'a',2,undefined,terms),null);
});
void test('each additional payment has its own visible status, quote and exact pay action', () => {
const html = renderToStaticMarkup(createElement(PublicDealList,{game:base,disabled:false,act() {}}));
assert.match(html,/Additional payment 1/); assert.match(html,/Additional payment 2/);
assert.match(html,/exactly 2 spice/); assert.match(html,/exactly 3 spice/);
assert.match(html,/Keep funds for the first payment/);
const calls:Action[] = [];
const nodes = elements(PublicDealList({game:base,disabled:false,act(action) {calls.push(action);}}));
const one = nodes.find(node => label(node.props.children) === 'Pay additional payment 1');
const two = nodes.find(node => label(node.props.children) === 'Pay additional payment 2');
assert.ok(one && two); assert.equal(one.props.disabled,false); assert.equal(two.props.disabled,true);
(one.props.onClick as () => void)();
assert.deepEqual(calls,[{type:'dealPay',deal:'deal',paymentIndex:0}]);
assert.deepEqual(publicDealRequests(base),[['payment','deal','0']]);
const paid = {...base,deals:[{...deal,additionalPayments:[{payment:first,paymentStatus:'paid'},
{payment:second,paymentStatus:'pending'}]}]} as unknown as GameView;
const after = elements(PublicDealList({game:paid,disabled:false,act() {}}));
assert.equal(after.find(node => label(node.props.children) === 'Pay additional payment 1'),undefined);
assert.ok(after.find(node => label(node.props.children) === 'Pay additional payment 2'));
assert.deepEqual(publicDealRequests(paid),[]);
const recipient = {...base,me:'b'} as GameView;
assert.equal(elements(PublicDealList({game:recipient,disabled:false,act() {}}))
.some(node => label(node.props.children) === 'Pay additional payment 1'),false);
});
/** Exercise the actual hook callbacks in a stateful React-compatible VM; this
* is a component-control test, not a hydrated-browser claim. */
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 game = {...base,deals:[]} as GameView;
const render = () => {stateCursor = 0; refCursor = 0;
return elements(exported.PublicDeals!({game,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 payment')));
assert.ok(sets[index]); return elements(sets[index]);};
return {render,click,field,sent};
}
void test('authoring callbacks add, edit and remove independent deferred 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 deferred payment'); ui.click('Add deferred payment');
for (let index = 0; index < 2; index++) {
for (const [position,value] of [[0,'a'],[1,'b']] 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}});
}
for (const [position,value] of [[0,String(index+2)],[1,String(index+2)]] as const) {
const input = ui.field(index).filter(node => node.type === 'input' && node.props.type === 'number')[position]; assert.ok(input);
(input.props.onChange as (event:{target:{value:string}}) => void)({target:{value}});
}
}
ui.click('Remove additional 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 term'}});
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 term',additionalPayments:[second]}]);
});
@@ -0,0 +1,71 @@
// @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}};
}
/** A fresh room only; no pre-existing room is read, changed or removed. */
void test('authenticated participants accept and settle each indexed deal payment once', async () => {
const host = await request('/api/rooms',undefined,{name:'Multiple 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:'Multiple 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 before = await request(path,payer.cookie); assert.equal(before.status,200); view = before.data;
const spice = before.data.players.find(player => player.id === payer.data.me)?.spice;
assert.ok(typeof spice === 'number' && spice >= 5);
const dueTurn = view.turn+1;
const terms = [2,3].map(amount => ({kind:'deferredBribe',payer:payer.data.me,recipient:host.data.me,amount,dueTurn}));
await act(host.cookie,{type:'dealOffer',target:payer.data.me,terms:'Pay two separate amounts.',additionalPayments:terms});
const offered = view.deals.at(-1); assert.ok(offered);
assert.equal(offered.status,'offered');
assert.deepEqual(offered.additionalPayments?.map(line => line.payment),terms);
const acceptance = {type:'dealRespond',deal:offered.id,accept:true};
const forged = await request(path,host.cookie,{version:view.version,action:acceptance},payer.data.me);
assert.equal(forged.status,409,JSON.stringify(forged.data));
await act(payer.cookie,acceptance);
for (const seat of seats) {
const read = await request(path,seat.cookie); assert.equal(read.status,200,JSON.stringify(read.data));
const active:GameView['deals'][number] | undefined = read.data.deals.find(row => row.id === offered.id); assert.ok(active);
assert.equal(active.status,'active');
assert.deepEqual(active.additionalPayments?.map(line => line.paymentStatus),['pending','pending']);
}
const second = {type:'dealPay',deal:offered.id,paymentIndex:1};
const wrongPayer = await request(path,host.cookie,{version:view.version,action:second});
assert.equal(wrongPayer.status,409,JSON.stringify(wrongPayer.data));
const impersonation = await request(path,host.cookie,{version:view.version,action:second},payer.data.me);
assert.equal(impersonation.status,409,JSON.stringify(impersonation.data));
await act(payer.cookie,second);
assert.deepEqual(view.deals.find(row => row.id === offered.id)?.additionalPayments?.map(line => line.paymentStatus),['pending','paid']);
const replay = await request(path,payer.cookie,{version:view.version,action:second});
assert.equal(replay.status,409,JSON.stringify(replay.data));
await act(payer.cookie,{type:'dealPay',deal:offered.id,paymentIndex:0});
const paid = await request(path,payer.cookie); assert.equal(paid.status,200,JSON.stringify(paid.data));
assert.deepEqual(paid.data.deals.find(row => row.id === offered.id)?.additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.equal(paid.data.players.find(player => player.id === payer.data.me)?.spice,spice-5);
});
@@ -0,0 +1,102 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createMultipartyPublicDeal, createPublicDeal, markPublicDealPaid, publicDealDeferredTerms,
PublicDealError, releasePublicDeal, respondPublicDeal, setPublicDealAdditionalPayments,
validatePublicDeals, voidPublicDealPayment, type PublicDeal, type PublicDealSeat,
} from '../game/public-deals';
import { outstandingPublicDealPayments, pendingPublicDealPayments, publicDealPaymentOptionKey,
publicDealPaymentTotal } from '../game/public-deal-obligations';
const seats: PublicDealSeat[] = [{id:'a'}, {id:'b'}, {id:'c'}];
const term = (payer: string, recipient: string, amount: number, dueTurn: number) =>
({kind:'deferredBribe' as const, payer, recipient, amount, dueTurn});
function offered() {
const initial = createMultipartyPublicDeal(seats,'a',['b','c'],'Multiple payments',2,'deal',term('a','b',1,2));
const terms = [term('a','b',2,2), term('a','b',2,2), term('b','c',3,3)];
const next = setPublicDealAdditionalPayments(initial,terms,seats);
terms[0].amount = 99;
assert.equal(next.additionalPayments![0].payment.amount,2, 'Signed terms cannot alias caller objects.');
return next;
}
function active() {
const first = respondPublicDeal(offered(),seats,'b',true);
assert.equal(first.status,'offered');
assert.deepEqual(first.additionalPayments!.map(row => row.paymentStatus),[undefined,undefined,undefined]);
return respondPublicDeal(first,seats,'c',true);
}
void test('distinct indexed payment terms bind only after unanimous consent and preserve legacy terms', () => {
const game = active();
assert.equal(game.paymentStatus,'pending');
assert.deepEqual(game.additionalPayments!.map(row => row.paymentStatus),['pending','pending','pending']);
assert.deepEqual(publicDealDeferredTerms(game).map(row => row.paymentIndex),[undefined,0,1,2]);
assert.deepEqual(pendingPublicDealPayments([game],'a',2).map(row => [row.paymentIndex,row.amount]),
[[undefined,1],[0,2],[1,2]]);
assert.equal(publicDealPaymentTotal([game],'a',2),5);
assert.equal(publicDealPaymentTotal([game],'b',2),0);
assert.deepEqual(outstandingPublicDealPayments([game],'b',2).map(row => [row.paymentIndex,row.dueTurn]),[[2,3]]);
assert.equal(publicDealPaymentOptionKey('deal'),'deal');
assert.equal(publicDealPaymentOptionKey('deal',0),'deal:payment:0');
assert.notEqual(publicDealPaymentOptionKey('deal',0),publicDealPaymentOptionKey('deal',1));
assert.deepEqual(JSON.parse(JSON.stringify(game)),game);
validatePublicDeals([game],seats);
});
void test('only the original payer can pay an exact term once; void and release affect each term independently', () => {
const original = active(), before = structuredClone(original);
for (const index of [-1,3,1.5,Number.NaN])
assert.throws(() => markPublicDealPaid(original,seats,'a',index),PublicDealError);
assert.throws(() => markPublicDealPaid(original,seats,'b',0),PublicDealError);
let game = markPublicDealPaid(original,seats,'a',1);
assert.deepEqual(game.additionalPayments!.map(row => row.paymentStatus),['pending','paid','pending']);
assert.throws(() => markPublicDealPaid(game,seats,'a',1),PublicDealError);
game = voidPublicDealPayment(game,seats,0);
assert.deepEqual(game.additionalPayments!.map(row => row.paymentStatus),['void','paid','pending']);
assert.throws(() => voidPublicDealPayment(game,seats,0),PublicDealError);
assert.throws(() => markPublicDealPaid(game,seats,'a',0),PublicDealError);
assert.equal(game.paymentStatus,'pending');
for (const actor of ['a','b','c']) game = releasePublicDeal(game,seats,actor,true);
assert.equal(game.status,'released');
assert.equal(game.paymentStatus,'released');
assert.deepEqual(game.additionalPayments!.map(row => row.paymentStatus),['released','paid','released']);
validatePublicDeals([game],seats);
assert.deepEqual(original,before, 'Failed attempts and later transitions preserve original records.');
});
void test('malformed additional arrays, term packets and lifecycle states are rejected', () => {
const initial = createPublicDeal(seats,'a','b','Terms',2,'deal');
for (const terms of [[],Array.from({length:13},() => term('a','b',1,2)),[term('a','c',1,2)],
[term('a','b',0,2)],[term('a','b',1,1)],[{kind:'immediateBribe',payer:'a',recipient:'b',amount:1}]])
assert.throws(() => setPublicDealAdditionalPayments(initial,terms,seats),PublicDealError);
const offer = setPublicDealAdditionalPayments(initial,[term('a','b',2,2)],seats);
const accepted = respondPublicDeal(offer,seats,'b',true);
const malformed = [
{...offer,additionalPayments:[]},
{...offer,additionalPayments:[{payment:term('a','b',2,2),paymentStatus:'pending'}]},
{...accepted,additionalPayments:[{payment:term('a','b',2,2)}]},
{...accepted,additionalPayments:[{payment:term('a','b',2,2),paymentStatus:'released'}]},
{...accepted,additionalPayments:[{payment:term('a','b',2,2),paymentStatus:'pending',extra:true}]},
{...accepted,additionalPayments:[{payment:{...term('a','b',2,2),extra:true},paymentStatus:'pending'}]},
];
for (const game of malformed) assert.throws(() => validatePublicDeals([game],seats),PublicDealError);
assert.throws(() => setPublicDealAdditionalPayments(accepted,[term('a','b',1,2)],seats),PublicDealError);
assert.throws(() => setPublicDealAdditionalPayments(offer,[term('a','b',1,2)],seats),PublicDealError);
validatePublicDeals([offer, {...accepted,id:'active'}],seats);
});
void test('older single deferred payment saves and no-payment deals retain exact legacy shape', () => {
const payment = term('a','b',4,3);
const legacy: PublicDeal = respondPublicDeal(createPublicDeal(seats,'a','b','Legacy',3,'legacy',payment),seats,'b',true);
const before = JSON.stringify(legacy);
assert.deepEqual(publicDealDeferredTerms(legacy),[{payment,paymentStatus:'pending'}]);
assert.deepEqual(outstandingPublicDealPayments([legacy],'a',3),
[{deal:'legacy',payer:'a',recipient:'b',dueTurn:3,amount:4}]);
assert.equal(JSON.stringify(legacy),before);
assert.equal(markPublicDealPaid(legacy,seats,'a').paymentStatus,'paid');
const empty = createPublicDeal(seats,'a','b','No payment',2,'empty');
assert.deepEqual(publicDealDeferredTerms(empty),[]);
assert.equal(Object.hasOwn(empty,'additionalPayments'),false);
});
@@ -0,0 +1,179 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { botActions } from '../game/bots';
import { viewGame, type Action, type Game } from '../game/engine';
import type { PublicDeal } from '../game/public-deals';
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';
type Deferred = { kind:'deferredBribe'; payer:string; recipient:string; amount:number; dueTurn:number };
type Line = { payment:Deferred; paymentStatus?:'pending'|'paid'|'void'|'released' };
type MultiDeal = PublicDeal & { additionalPayments?:Line[] };
const term = (payer:string, recipient:string, amount:number, dueTurn:number): Deferred =>
({kind:'deferredBribe',payer,recipient,amount,dueTurn});
const key = (deal:string, index:number) => `${deal}:payment:${index}`;
function deal(game: Game, id: string): MultiDeal {
const found = game.deals?.find(row => row.id === id); assert.ok(found); return found as MultiDeal;
}
function reject(game: Game, actor: string, action: Action) {
const before = structuredClone(game);
assert.throws(() => act(game,actor,action));
assert.deepEqual(game,before,'Rejected actions leave the original state unchanged');
}
function offer(game: Game, from: string, to: string, additionalPayments: Deferred[], payment?: object) {
game = act(game,from,{type:'dealOffer',target:to,terms:'Pay the agreed separate amounts.',additionalPayments,
...(payment ? {payment} : {})});
const id = game.deals?.at(-1)?.id; assert.ok(id);
return {game,id};
}
const accept = (game: Game, actor:string, id:string) => act(game,actor,{type:'dealRespond',deal:id,accept:true});
const pay = (game: Game, actor:string, id:string, paymentIndex:number) =>
act(game,actor,{type:'dealPay',deal:id,paymentIndex});
/** Public Basic H/A/E start, real auction and first Mentat. The inherited
* fixture orders only unopened original cards and Spice; no purse or deal is
* fabricated. Every term's consent and transfer uses native player actions. */
void test('identical deferred terms have separate indices and each exact payment settles once', () => {
const f = fixture(), start = f.game, original = inventory(start);
const terms = [term(f.target,f.asker,3,start.turn),term(f.target,f.asker,3,start.turn)];
const proposed = offer(start,f.asker,f.target,terms);
assert.deepEqual(deal(proposed.game,proposed.id).additionalPayments?.map(line => line.payment),terms);
assert.equal(player(proposed.game,f.target).spice,10);
let game = accept(proposed.game,f.target,proposed.id);
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['pending','pending']);
assert.equal(viewGame(game,f.target).deferredDealPaymentOptions[key(proposed.id,0)]?.blocked,null);
assert.equal(viewGame(game,f.target).deferredDealPaymentOptions[key(proposed.id,1)]?.blocked,null);
reject(game,f.asker,{type:'dealPay',deal:proposed.id,paymentIndex:0});
reject(game,f.target,{type:'dealPay',deal:proposed.id,paymentIndex:2});
reject(game,f.target,{type:'dealPay',deal:proposed.id});
game = pay(game,f.target,proposed.id,1);
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['pending','paid']);
assert.equal(player(game,f.target).spice,7); assert.equal(player(game,f.asker).bribes,3);
reject(game,f.target,{type:'dealPay',deal:proposed.id,paymentIndex:1});
game = pay(game,f.target,proposed.id,0);
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.equal(player(game,f.target).spice,4); assert.equal(player(game,f.asker).bribes,6);
assert.deepEqual(inventory(game),original);
});
void test('final consent rolls back when separate due terms overcommit the same purse', () => {
const f = fixture(), terms = [term(f.target,f.asker,6,f.game.turn),term(f.target,f.asker,5,f.game.turn)];
const proposed = offer(f.game,f.asker,f.target,terms), before = structuredClone(proposed.game);
reject(proposed.game,f.target,{type:'dealRespond',deal:proposed.id,accept:true});
assert.deepEqual(proposed.game,before);
assert.equal(deal(proposed.game,proposed.id).status,'offered');
assert.deepEqual(deal(proposed.game,proposed.id).additionalPayments?.map(line => line.paymentStatus),[undefined,undefined]);
assert.equal(player(proposed.game,f.target).spice,10);
assert.deepEqual(inventory(proposed.game),f.originalCards);
});
void test('current and future terms reserve only the current due amount and keep distinct payment receipts', () => {
const f = fixture(), due = f.game.turn;
const proposed = offer(f.game,f.asker,f.target,[term(f.target,f.asker,3,due),term(f.target,f.asker,8,due+1)]);
let game = accept(proposed.game,f.target,proposed.id);
assert.equal(viewGame(game,f.target).deferredDealPaymentOptions[key(proposed.id,0)]?.blocked,null);
assert.ok(viewGame(game,f.target).deferredDealPaymentOptions[key(proposed.id,1)]?.blocked);
reject(game,f.target,{type:'dealPay',deal:proposed.id,paymentIndex:1});
game = pay(game,f.target,proposed.id,0);
assert.equal(player(game,f.target).spice,7);
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['paid','pending']);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('unanimous release cancels only unpaid terms and does not refund paid spice', () => {
const f = fixture(), proposed = offer(f.game,f.asker,f.target,
[term(f.target,f.asker,2,f.game.turn),term(f.target,f.asker,3,f.game.turn)]);
let game = accept(proposed.game,f.target,proposed.id);
game = pay(game,f.target,proposed.id,0);
game = act(game,f.asker,{type:'dealRelease',deal:proposed.id,agree:true});
assert.equal(deal(game,proposed.id).status,'active');
game = act(game,f.target,{type:'dealRelease',deal:proposed.id,agree:true});
assert.equal(deal(game,proposed.id).status,'released');
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['paid','released']);
assert.equal(player(game,f.target).spice,8); assert.equal(player(game,f.asker).bribes,2);
reject(game,f.target,{type:'dealPay',deal:proposed.id,paymentIndex:1});
assert.deepEqual(inventory(game),f.originalCards);
});
void test('a group can accept distinct payer terms without settling before all consent', () => {
const f = fixture(), start = f.game;
assert.ok(player(start,f.opponent).spice >= 1);
const terms = [term(f.target,f.asker,2,start.turn),term(f.opponent,f.asker,1,start.turn)];
let game = act(start,f.asker,{type:'dealOffer',targets:[f.target,f.opponent],terms:'Both pay agreed spice.',additionalPayments:terms});
const id = game.deals?.at(-1)?.id; assert.ok(id);
game = accept(game,f.target,id);
assert.equal(deal(game,id).status,'offered');
assert.equal(player(game,f.target).spice,player(start,f.target).spice);
game = accept(game,f.opponent,id);
assert.equal(deal(game,id).status,'active');
reject(game,f.target,{type:'dealPay',deal:id,paymentIndex:1});
game = pay(game,f.opponent,id,1);
game = pay(game,f.target,id,0);
assert.equal(player(game,f.asker).bribes,3);
assert.deepEqual(deal(game,id).additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('the original immediate payment and extra deferred payments use separate native transfers', () => {
const f = fixture(), start = f.game;
const immediate = {kind:'immediateBribe',payer:f.target,recipient:f.asker,amount:2};
const proposed = offer(start,f.asker,f.target,[term(f.target,f.asker,3,start.turn)],immediate);
assert.equal(player(proposed.game,f.target).spice,10);
let game = accept(proposed.game,f.target,proposed.id);
assert.equal(player(game,f.target).spice,8); assert.equal(player(game,f.asker).bribes,2);
assert.equal(deal(game,proposed.id).additionalPayments?.[0].paymentStatus,'pending');
game = pay(game,f.target,proposed.id,0);
assert.equal(player(game,f.target).spice,5); assert.equal(player(game,f.asker).bribes,5);
assert.equal(deal(game,proposed.id).additionalPayments?.[0].paymentStatus,'paid');
assert.deepEqual(inventory(game),f.originalCards);
});
void test('autopilot uses a legal indexed action for each payment that is due', () => {
const f = fixture(), proposed = offer(f.game,f.asker,f.target,
[term(f.target,f.asker,2,f.game.turn),term(f.target,f.asker,3,f.game.turn)]);
let game = accept(proposed.game,f.target,proposed.id);
game = act(game,f.target,{type:'setAutopilot',difficulty:'Easy'});
for (let count = 0; count < 2; count++) {
const action = botActions(viewGame(game,f.target))[0]; assert.ok(action);
assert.equal(action.type,'dealPay'); assert.equal(action.deal,proposed.id);
assert.ok(action.paymentIndex === 0 || action.paymentIndex === 1);
game = act(game,f.target,action);
}
assert.deepEqual(deal(game,proposed.id).additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.equal(player(game,f.target).spice,5); assert.equal(player(game,f.asker).bribes,5);
assert.deepEqual(inventory(game),f.originalCards);
});
void test('multiple deferred payments can accompany an actual current-turn shipment', () => {
const f = createTruthTravelFixture(), initial = f.game, original = truthTravelInventory(initial);
const terms = [term(f.target,f.asker,1,initial.turn),term(f.target,f.asker,1,initial.turn)];
let game = actTruthTravel(initial,f.asker,{type:'dealOffer',target:f.target,terms:'Two payments and a shipment.',
additionalPayments:terms,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(viewGame(game,f.target).dealTravelStatus[id],'pending');
game = actTruthTravel(game,f.target,{type:'dealPay',deal:id,paymentIndex:0});
game = settleTruthTravel(actTruthTravel(game,f.target,f.shipmentAction));
game = actTruthTravel(game,f.target,{type:'dealPay',deal:id,paymentIndex:1});
assert.equal(viewGame(game,f.target).dealTravelStatus[id],'fulfilled');
assert.deepEqual(deal(game,id).additionalPayments?.map(line => line.paymentStatus),['paid','paid']);
assert.equal(truthTravelPlayer(game,f.target).forces['polar_sink:0'],1);
assert.deepEqual(truthTravelInventory(game),original);
});
void test('malformed additional payment packets are rejected without opening a deal', () => {
const f = fixture(), due = f.game.turn, valid = term(f.target,f.asker,1,due);
const packet = {type:'dealOffer',target:f.target,terms:'Invalid payment terms.'};
for (const additionalPayments of [
[{...valid,amount:0}], [{...valid,payer:f.asker,recipient:f.asker}],
[{...valid,dueTurn:due-1}], [{...valid,kind:'immediateBribe'}],
[{...valid,extra:true}], Array.from({length:13},() => valid),
]) reject(f.game,f.asker,{...packet,additionalPayments});
});