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

+41 -32
View File
@@ -10,8 +10,9 @@ import { createFactionDraft, validateFactionDraft, currentFactionDrafter, choose
import { createFactionSwap, validateFactionSwap, answerFactionSwap, cancelFactionSwap,
FactionSwapError, type FactionSwap } from './faction-swap';
import { createPublicDeal, createMultipartyPublicDeal, validatePublicDeals, respondPublicDeal, withdrawPublicDeal,
releasePublicDeal, markPublicDealPaid, voidPublicDealPayment, setPublicDealTravel, publicDealTravelActor, publicDealTravelDueTurn, PublicDealError, type PublicDeal, type PublicDealPayment } from './public-deals';
import { outstandingPublicDealPayments, pendingPublicDealPayments, publicDealPaymentTotal, PublicDealObligationError, type PendingPublicDealPayment } from './public-deal-obligations';
releasePublicDeal, markPublicDealPaid, voidPublicDealPayment, setPublicDealTravel, setPublicDealAdditionalPayments,
publicDealDeferredTerms, publicDealTravelActor, publicDealTravelDueTurn, PublicDealError, type PublicDeal, type PublicDealPayment } from './public-deals';
import { outstandingPublicDealPayments, pendingPublicDealPayments, publicDealPaymentTotal, publicDealPaymentOptionKey, PublicDealObligationError, type PendingPublicDealPayment } from './public-deal-obligations';
import { CharityPromiseError, liveCharityPromises, charityPromiseAnswers, bindCharityPromise, guardCharityClaim, guardCharityReady, reconcileCharityPromises, type CharityPromise } from './charity-promises';
import { victoryFinalTurn, continueVictoryCalendar, VictoryCalendarError } from './victory-calendar';
import { createVictoryContinuation, validateVictoryContinuation, voteVictoryContinuation,
@@ -6148,17 +6149,17 @@ function publicDealCompletion(g: Game, payer: Player): boolean {
* possible. Only settled, proven expiry or a base-game Mentat shortfall voids
* a term; temporary pending decisions do not establish impossibility. */
function reconcilePublicDealTruth(g: Game, voluntary?: {actor:string;action:Action}, before?: Game): void {
if (!g.deals?.some(deal => deal.payment?.kind === 'deferredBribe' && deal.paymentStatus === 'pending')) return;
if (!g.deals?.some(deal => publicDealDeferredTerms(deal).some(term => term.paymentStatus === 'pending'))) return;
for (const p of g.players) {
const pending: PublicDeal[] = (g.deals ?? []).filter(deal => deal.status === 'active' && deal.payment?.kind === 'deferredBribe' &&
deal.payment.payer === p.id && deal.paymentStatus === 'pending');
const pending: Array<ReturnType<typeof publicDealDeferredTerms>[number] & {deal:string}> = (g.deals ?? []).flatMap(deal => deal.status === 'active'
? publicDealDeferredTerms(deal).filter(term => term.payment.payer === p.id && term.paymentStatus === 'pending')
.map(term => ({deal:deal.id,...term})) : []);
if (!pending.length) continue;
const beforePayer = before && getPlayer(before,p.id);
const wasPossible = !!before && !!beforePayer && voluntary?.actor === p.id &&
pendingPublicDealPayments(before.deals ?? [],p.id,before.turn).some(debt => !bribeAllied(before, beforePayer, debt.recipient)) &&
publicDealCompletion(before,beforePayer);
const expiredByAction = pending.some(deal => deal.payment?.kind === 'deferredBribe' &&
(g.turn > deal.payment.dueTurn || g.status === 'finished'));
const expiredByAction = pending.some(term => g.turn > term.payment.dueTurn || g.status === 'finished');
const closesPaymentWindow = wasPossible && voluntary?.action.type === 'ready' &&
(before!.phase === 8 || before!.phase === 7 && bribesCloseBeforeNextMentat(before!));
if (wasPossible && (closesPaymentWindow || expiredByAction || !publicDealCompletion(g,p)))
@@ -6166,15 +6167,15 @@ function reconcilePublicDealTruth(g: Game, voluntary?: {actor:string;action:Acti
const quiet = !g.truthtrance && !g.response && !g.decision && !g.phaseOpening &&
!g.pendingKarama && !g.pendingTreacheryDiscard && !g.bureaucratPayments?.pending;
const available = Math.max(0,uncommittedSpice(g,p));
for (const deal of pending) {
const payment = deal.payment!;
if (payment.kind !== 'deferredBribe') continue;
for (const term of pending) {
const payment = term.payment;
const expired = g.turn > payment.dueTurn || g.status === 'finished';
if (!expired && bribeAllied(g, p, payment.recipient)) continue;
const baseMentatShortfall = quiet && g.turn === payment.dueTurn && g.phase === 8 &&
g.expansions.length === 0 && bribePromiseModeSupported(g) && available < payment.amount;
if (expired || baseMentatShortfall) {
g.deals = g.deals!.map(row => row.id === deal.id ? publicDealRule((): PublicDeal => voidPublicDealPayment(row,g.players)) : row);
g.deals = g.deals!.map(row => row.id === term.deal
? publicDealRule((): PublicDeal => voidPublicDealPayment(row,g.players,term.paymentIndex)) : row);
log(g, `${p.name}'s agreed ${payment.amount}-spice payment can no longer be completed and is void.`);
}
}
@@ -6199,19 +6200,21 @@ function protectInsolventDueDeal(g: Game, payer: string, payment: PendingPublicD
'Keep the funding for a currently payable deal before paying a later deal.');
}
/** Only the payer receives its exact native payment quote. */
function projectedDeferredDealPaymentOptions(g: Game, player: string): Record<string,{blocked:string|null}> {
const result: Record<string,{blocked:string|null}> = {};
function projectedDeferredDealPaymentOptions(g: Game, player: string): Record<string,{blocked:string|null;deal?:string;paymentIndex?:number}> {
const result: Record<string,{blocked:string|null;deal?:string;paymentIndex?:number}> = {};
for (const debt of outstandingPublicDealPayments(g.deals ?? [],player,g.turn)) {
const key = publicDealPaymentOptionKey(debt.deal,debt.paymentIndex);
const identity = debt.paymentIndex === undefined ? {} : {deal:debt.deal,paymentIndex:debt.paymentIndex};
try {
protectInsolventDueDeal(g,player,debt);
const trial = structuredClone(g), index = trial.deals!.findIndex(deal => deal.id === debt.deal);
trial.deals![index] = publicDealRule(() => markPublicDealPaid(trial.deals![index],trial.players,player));
trial.deals![index] = publicDealRule(() => markPublicDealPaid(trial.deals![index],trial.players,player,debt.paymentIndex));
applyActionWithInitiator(trial,player,{type:'bribe',target:debt.recipient,amount:debt.amount},player,
{insolventDealPayment:debt.dueTurn === g.turn && publicDealInsolventAtBaseMentat(g,player)});
result[debt.deal] = {blocked:null};
result[key] = {blocked:null,...identity};
} catch (error) {
if (!(error instanceof RuleError)) throw error;
result[debt.deal] = {blocked:error.message};
result[key] = {blocked:error.message,...identity};
}
}
return result;
@@ -17823,7 +17826,8 @@ function basicBribeInterrupt(g: Game, p: Player): boolean {
(g.alliancePromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released) ||
(g.allianceExpressionPromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released) ||
(g.pledgePromises ?? []).some(row => row.player === p.id && row.turn === g.turn && !row.fulfilled && !row.released) ||
(g.deals ?? []).some(row => row.status === 'active' && row.payment?.payer === p.id && row.paymentStatus === 'pending')) return false;
(g.deals ?? []).some(row => row.status === 'active' && publicDealDeferredTerms(row)
.some(term => term.payment.payer === p.id && term.paymentStatus === 'pending'))) return false;
const classic = ['atreides', 'beneGesserit', 'emperor', 'fremen', 'guild', 'harkonnen'];
const nativeRoster = !g.expansions.length
? g.players.every(seat => classic.includes(seat.faction)) : selectedPhaseModuleRoster(g);
@@ -21229,7 +21233,8 @@ function choamMarketSkipCommitments(g: Game): boolean {
recorded(g.bribeExpressionPromises) || recorded(g.pledgePromises) || recorded(g.alliancePromises) ||
recorded(g.allianceExpressionPromises) || recorded(g.movementPromises) || recorded(g.movementExpressionPromises) ||
recorded(g.futureBattleLeaderPromises) ||
!!g.deals?.some(row => row.status === 'active' && row.paymentStatus === 'pending');
!!g.deals?.some(row => row.status === 'active' && publicDealDeferredTerms(row)
.some(term => term.paymentStatus === 'pending'));
}
function choamMarketSkipAvailable(g: Game, p: Player): boolean {
return choamMarketSkipProfile(g, p) && g.decision?.kind === 'choamMarket' &&
@@ -43659,16 +43664,19 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
return g;
}
if (action?.type === 'dealPay') {
requireRule(state.status === 'playing' && Object.keys(action).sort().join(',') === 'deal,type' &&
const keys = Object.keys(action).sort().join(',');
requireRule(state.status === 'playing' && (keys === 'deal,type' || keys === 'deal,paymentIndex,type') &&
(action.paymentIndex === undefined || Number.isSafeInteger(action.paymentIndex) && (action.paymentIndex as number) >= 0) &&
typeof action.deal === 'string', 'Choose your pending deal payment.');
requireRule(!bribeTimingBlock(state), 'Finish the current decision or response before paying a deal.');
const g = structuredClone(state), index = (g.deals ?? []).findIndex(deal => deal.id === action.deal);
requireRule(index >= 0, 'This deal is no longer available.');
const current = g.deals![index], payment = current.payment;
const current = g.deals![index], paymentIndex = action.paymentIndex as number | undefined;
const payment = paymentIndex === undefined ? current.payment : current.additionalPayments?.[paymentIndex]?.payment;
requireRule(payment?.kind === 'deferredBribe' && payment.dueTurn >= g.turn,
'This deferred payment is no longer available.');
protectInsolventDueDeal(state,id,{deal:current.id,...payment});
g.deals![index] = publicDealRule(() => markPublicDealPaid(current,g.players,id));
protectInsolventDueDeal(state,id,{deal:current.id,...payment,...(paymentIndex === undefined ? {} : {paymentIndex})});
g.deals![index] = publicDealRule(() => markPublicDealPaid(current,g.players,id,paymentIndex));
return applyActionWithInitiator(g,id,{type:'bribe',target:payment.recipient,amount:payment.amount},id,
{insolventDealPayment:payment.dueTurn === state.turn && publicDealInsolventAtBaseMentat(state,id)});
}
@@ -43679,11 +43687,10 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
const g = structuredClone(state);
const deals = g.deals ?? [];
if (action.type === 'dealOffer') {
const keys = Object.keys(action).sort().join(',');
const single = (keys === 'target,terms,type' || keys === 'payment,target,terms,type' ||
keys === 'target,terms,travel,type' || keys === 'payment,target,terms,travel,type') && typeof action.target === 'string';
const multiple = (keys === 'targets,terms,type' || keys === 'payment,targets,terms,type' ||
keys === 'targets,terms,travel,type' || keys === 'payment,targets,terms,travel,type') && Array.isArray(action.targets) &&
const keys = Object.keys(action);
const supportedKeys = keys.every(key => ['type','terms','target','targets','payment','additionalPayments','travel'].includes(key));
const single = supportedKeys && !Object.hasOwn(action,'targets') && typeof action.target === 'string';
const multiple = supportedKeys && !Object.hasOwn(action,'target') && Array.isArray(action.targets) &&
action.targets.every(target => typeof target === 'string');
const hasPayment = Object.hasOwn(action, 'payment');
requireRule((single || multiple) && typeof action.terms === 'string' &&
@@ -43699,6 +43706,8 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
: hasPayment
? createMultipartyPublicDeal(seats, id, action.targets as string[], action.terms as string, g.turn, event, payment!)
: createMultipartyPublicDeal(seats, id, action.targets as string[], action.terms as string, g.turn, event));
if (Object.hasOwn(action,'additionalPayments'))
offer = publicDealRule(() => setPublicDealAdditionalPayments(offer,action.additionalPayments,seats));
if (Object.hasOwn(action, 'travel')) {
requireRule(!g.advanced && g.expansions.length === 0 && nativePromiseScopeSupported(g),
'Choose a travel agreement in a supported Basic table.');
@@ -43719,7 +43728,7 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
requireRule(typeof action.accept === 'boolean', 'Choose whether to accept or decline.');
requireRule(!action.accept || !current.travel || publicDealTravelDueTurn(current) >= g.turn,
'The travel agreement’s due turn has passed; decline or withdraw it.');
requireRule(!action.accept || current.payment?.kind !== 'deferredBribe' || current.payment.dueTurn >= g.turn,
requireRule(!action.accept || publicDealDeferredTerms(current).every(term => term.payment.dueTurn >= g.turn),
'The deferred payment deadline has passed; decline or withdraw this offer.');
next = publicDealRule(() => respondPublicDeal(current, publicDealSeats(g), id, action.accept as boolean));
} else if (action.type === 'dealRelease') {
@@ -43745,15 +43754,15 @@ function applyActionWithInitiator(state: Game, id: string, action: Action, initi
requireRule(publicDealCompletion(g,traveler),
'The traveler needs a funded completion for the travel and their payments due this turn.');
}
if (current.status === 'offered' && next.status === 'active' && next.payment?.kind === 'deferredBribe') {
const payer = getPlayer(g,next.payment.payer), dueTurn = next.payment.dueTurn;
if (current.status === 'offered' && next.status === 'active') for (const term of publicDealDeferredTerms(next)) {
const payment = term.payment, payer = getPlayer(g,payment.payer), dueTurn = payment.dueTurn;
requireRule(dueTurn >= g.turn &&
(dueTurn > g.turn || publicDealCompletion(g,payer)),
'The agreed payment needs an unexpired deadline and, when due now, a legal funded completion.');
if (next.payment.dueTurn === g.turn &&
if (dueTurn === g.turn &&
(g.phase === 2 && !g.charityOrder || g.phase === 8 || g.phase === 7 && bribesCloseBeforeNextMentat(g)) &&
g.ready.includes(payer.id)) g.ready = g.ready.filter(playerId => playerId !== payer.id);
log(g, `${payer.name} agreed to pay ${next.payment.amount} spice to ${getPlayer(g,next.payment.recipient).name} by the end of turn ${next.payment.dueTurn}.`);
log(g, `${payer.name} agreed to pay ${payment.amount} spice to ${getPlayer(g,payment.recipient).name} by the end of turn ${dueTurn}.`);
}
if (current.status === 'offered' && next.status === 'active' && next.payment?.kind === 'immediateBribe') {
// The payer consented to these immutable terms. Run the native action