Support multiple deferred payments in public deals
Verify and publish checkpoint container / container (push) Successful in 10m22s
Verify and publish checkpoint container / container (push) Successful in 10m22s
This commit is contained in:
1 parent
0b8a147388
commit
cacc88906c
12 files changed
+742
-50
No files matched your search
+4
-2
@@ -4401,10 +4401,12 @@ export function botActions(g: GameView): Action[] {
|
||||
if ((dealPayer?.bot || dealPayer?.autopilot) && g.status === 'playing' &&
|
||||
!g.roomControl?.paused && !g.roomControl?.closed && !g.automaticContinuationPending) {
|
||||
const payable = Object.entries(g.deferredDealPaymentOptions ?? {}).find(([id,option]) => {
|
||||
const payment = g.deals.find(deal => deal.id === id)?.payment;
|
||||
const deal = g.deals.find(row => row.id === (option.deal ?? id));
|
||||
const payment = option.paymentIndex === undefined ? deal?.payment : deal?.additionalPayments?.[option.paymentIndex]?.payment;
|
||||
return !option.blocked && payment?.kind === 'deferredBribe' && payment.dueTurn <= g.turn;
|
||||
});
|
||||
if (payable) return [{type:'dealPay',deal:payable[0]}];
|
||||
if (payable) return [{type:'dealPay',deal:payable[1].deal ?? payable[0],
|
||||
...(payable[1].paymentIndex === undefined ? {} : {paymentIndex:payable[1].paymentIndex})}];
|
||||
}
|
||||
if (g.decision?.kind === 'homeworldTupileCleanup' || g.homeworldTupileCleanup)
|
||||
return tupileCleanupActions(g);
|
||||
|
||||
+41
-32
@@ -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
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { validatePublicDeals, voidPublicDealPayment, type PublicDeal, type PublicDealSeat } from './public-deals';
|
||||
import { publicDealDeferredTerms, validatePublicDeals, voidPublicDealPayment, type PublicDeal, type PublicDealSeat } from './public-deals';
|
||||
|
||||
/** A deal-linked obligation is independent of every other deal and of
|
||||
* Truthtrance. It is due once for its exact gross payment, not a threshold
|
||||
* shared with a different agreement. */
|
||||
export type PendingPublicDealPayment = {
|
||||
deal: string;
|
||||
paymentIndex?: number;
|
||||
payer: string;
|
||||
recipient: string;
|
||||
dueTurn: number;
|
||||
amount: number;
|
||||
};
|
||||
|
||||
/** Projection key is stable for a term and preserves the legacy deal key. */
|
||||
export function publicDealPaymentOptionKey(deal: string, paymentIndex?: number): string {
|
||||
return paymentIndex === undefined ? deal : `${deal}:payment:${paymentIndex}`;
|
||||
}
|
||||
|
||||
export class PublicDealObligationError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
@@ -32,10 +38,12 @@ export function outstandingPublicDealPayments(
|
||||
if (!Array.isArray(deals) || !identifier(payer) || !Number.isSafeInteger(turn) || turn < 1)
|
||||
throw new PublicDealObligationError('Retain the payer and original turn of the deferred payments.');
|
||||
return deals.flatMap(deal => {
|
||||
const payment = deal.payment;
|
||||
if (deal.status !== 'active' || deal.paymentStatus !== 'pending' ||
|
||||
payment?.kind !== 'deferredBribe' || payment.payer !== payer || payment.dueTurn < turn) return [];
|
||||
return [{ deal: deal.id, payer, recipient: payment.recipient, dueTurn: payment.dueTurn, amount: payment.amount }];
|
||||
if (deal.status !== 'active') return [];
|
||||
return publicDealDeferredTerms(deal).flatMap(({payment, paymentStatus, paymentIndex}) => {
|
||||
if (paymentStatus !== 'pending' || payment.payer !== payer || payment.dueTurn < turn) return [];
|
||||
return [{deal: deal.id, ...(paymentIndex === undefined ? {} : {paymentIndex}), payer,
|
||||
recipient: payment.recipient, dueTurn: payment.dueTurn, amount: payment.amount}];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -83,7 +91,7 @@ export function reconcilePublicDealPayments(
|
||||
throw new PublicDealObligationError('Retain the actual funded witness and cause of the change.');
|
||||
const pending = pendingPublicDealPayments(deals, payer, turn);
|
||||
const ids = witness.impossibleDealIds ?? [];
|
||||
if (new Set(ids).size !== ids.length || ids.some(id => !pending.some(row => row.deal === id)))
|
||||
if (new Set(ids).size !== ids.length || ids.some(id => !pending.some(row => row.deal === id && row.paymentIndex === undefined)))
|
||||
throw new PublicDealObligationError('Void only individually proven pending terms of this payer and turn.');
|
||||
if (witness.change === 'voluntary' && (ids.length > 0 ||
|
||||
witness.available !== null && witness.available < publicDealPaymentTotal(deals, payer, turn)))
|
||||
|
||||
+83
-3
@@ -15,6 +15,13 @@ export type PublicDealPayment = {
|
||||
dueTurn: number;
|
||||
};
|
||||
export type PublicDealPaymentStatus = 'pending' | 'paid' | 'void' | 'released';
|
||||
export type PublicDealDeferredPayment = Extract<PublicDealPayment, { kind: 'deferredBribe' }>;
|
||||
/** The index is the stable identity of a term within its immutable offer. */
|
||||
export type PublicDealAdditionalPayment = {
|
||||
payment: PublicDealDeferredPayment;
|
||||
paymentStatus?: PublicDealPaymentStatus;
|
||||
};
|
||||
export const MAX_ADDITIONAL_DEAL_PAYMENTS = 12;
|
||||
/** One invited recipient commits to one native action (or its absence).
|
||||
* Old two-party records identify that recipient through `to`. */
|
||||
export type PublicDealTravel = {
|
||||
@@ -42,6 +49,7 @@ export type PublicDeal = {
|
||||
payment?: PublicDealPayment;
|
||||
/** Present only for accepted or released deferred payments. */
|
||||
paymentStatus?: PublicDealPaymentStatus;
|
||||
additionalPayments?: PublicDealAdditionalPayment[];
|
||||
travel?: PublicDealTravel;
|
||||
};
|
||||
|
||||
@@ -86,6 +94,17 @@ function notAllied(seats: readonly PublicDealSeat[]): void {
|
||||
export function publicDealParticipants(deal: PublicDeal): string[] {
|
||||
return deal.participants ? [...deal.participants] : [deal.from, deal.to];
|
||||
}
|
||||
/** Enumerate legacy and indexed deferred terms without rewriting older saves. */
|
||||
export function publicDealDeferredTerms(deal: PublicDeal): Array<{
|
||||
payment: PublicDealDeferredPayment;
|
||||
paymentStatus?: PublicDealPaymentStatus;
|
||||
paymentIndex?: number;
|
||||
}> {
|
||||
const legacy = deal.payment?.kind === 'deferredBribe'
|
||||
? [{payment: deal.payment, ...(deal.paymentStatus ? {paymentStatus: deal.paymentStatus} : {})}]
|
||||
: [];
|
||||
return [...legacy, ...(deal.additionalPayments ?? []).map((term,paymentIndex) => ({...term,paymentIndex}))];
|
||||
}
|
||||
export function publicDealAcceptVotes(deal: PublicDeal): string[] {
|
||||
if (deal.acceptVotes) return [...deal.acceptVotes];
|
||||
return deal.status === 'active' || deal.status === 'released'
|
||||
@@ -154,7 +173,7 @@ export function validatePublicDeals(value: unknown, players: readonly PublicDeal
|
||||
requireDeal(Array.isArray(value), 'The public deal ledger is malformed.');
|
||||
const ids = new Set<string>();
|
||||
for (const deal of value) {
|
||||
const keys = object(deal) ? Object.keys(deal).filter(key => key !== 'payment' && key !== 'paymentStatus' && key !== 'travel').sort().join(',') : '';
|
||||
const keys = object(deal) ? Object.keys(deal).filter(key => key !== 'payment' && key !== 'paymentStatus' && key !== 'travel' && key !== 'additionalPayments').sort().join(',') : '';
|
||||
const multi = keys === 'acceptVotes,from,id,participants,releaseVotes,status,terms,to,turn';
|
||||
requireDeal(object(deal) && (multi || keys === 'from,id,releaseVotes,status,terms,to,turn') &&
|
||||
id(deal.id) && id(deal.from) && id(deal.to) && deal.from !== deal.to &&
|
||||
@@ -206,6 +225,23 @@ export function validatePublicDeals(value: unknown, players: readonly PublicDeal
|
||||
!Object.hasOwn(deal, 'paymentStatus'), 'The deferred payment status does not match the deal lifecycle.');
|
||||
} else requireDeal(!Object.hasOwn(deal, 'paymentStatus'),
|
||||
'Only an accepted deferred payment has a payment status.');
|
||||
if (Object.hasOwn(deal, 'additionalPayments')) {
|
||||
requireDeal(Array.isArray(deal.additionalPayments) && deal.additionalPayments.length >= 1 &&
|
||||
deal.additionalPayments.length <= MAX_ADDITIONAL_DEAL_PAYMENTS,
|
||||
'Choose between one and twelve additional deferred payments.');
|
||||
for (const term of deal.additionalPayments) {
|
||||
requireDeal(object(term) && (Object.keys(term).sort().join(',') === 'payment' ||
|
||||
Object.keys(term).sort().join(',') === 'payment,paymentStatus'),
|
||||
'An additional payment term is malformed.');
|
||||
const parsed = parsePublicDealPayment(term.payment, parties, deal.turn as number);
|
||||
requireDeal(parsed.kind === 'deferredBribe', 'Additional payments must have a due turn.');
|
||||
const status = term.paymentStatus;
|
||||
requireDeal(deal.status === 'active' ? status === 'pending' || status === 'paid' || status === 'void' :
|
||||
deal.status === 'released' ? status === 'released' || status === 'paid' :
|
||||
!Object.hasOwn(term, 'paymentStatus'),
|
||||
'An additional payment status does not match the deal lifecycle.');
|
||||
}
|
||||
}
|
||||
const votes = deal.releaseVotes as string[];
|
||||
requireDeal(new Set(votes).size === votes.length && votes.every(vote => parties.includes(vote)) &&
|
||||
(!multi || orderedSubset(votes, parties)) &&
|
||||
@@ -248,6 +284,28 @@ export function createMultipartyPublicDeal(
|
||||
...paymentTerm };
|
||||
}
|
||||
|
||||
/** Attach independent deferred payment terms to an unchanged fresh offer. */
|
||||
export function setPublicDealAdditionalPayments(deal: PublicDeal, value: unknown, players: readonly PublicDealSeat[]): PublicDeal {
|
||||
validatePublicDeals([deal], players);
|
||||
requireDeal(deal.status === 'offered' && !Object.hasOwn(deal, 'additionalPayments') &&
|
||||
!Object.hasOwn(deal, 'paymentStatus') && (deal.participants
|
||||
? !!deal.acceptVotes && deal.acceptVotes.length === 1 && deal.acceptVotes[0] === deal.from
|
||||
: !Object.hasOwn(deal, 'acceptVotes')),
|
||||
'Only a fresh offer may add deferred payment terms.');
|
||||
requireDeal(Array.isArray(value) && value.length >= 1 && value.length <= MAX_ADDITIONAL_DEAL_PAYMENTS,
|
||||
'Choose between one and twelve additional deferred payments.');
|
||||
const parties = publicDealParticipants(deal);
|
||||
notAllied(participants(players, parties));
|
||||
const additionalPayments = value.map(value => {
|
||||
const payment = parsePublicDealPayment(value, parties, deal.turn);
|
||||
requireDeal(payment.kind === 'deferredBribe', 'Additional payments must have a due turn.');
|
||||
return {payment};
|
||||
});
|
||||
const result = {...deal, additionalPayments};
|
||||
validatePublicDeals([result], players);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Attach a travel term while constructing a fresh offer. */
|
||||
export function setPublicDealTravel(deal: PublicDeal, value: unknown, players: readonly PublicDealSeat[]): PublicDeal {
|
||||
validatePublicDeals([deal], players);
|
||||
@@ -270,6 +328,7 @@ export function respondPublicDeal(deal: PublicDeal, players: readonly PublicDeal
|
||||
if (!accept) return { ...deal, status: 'declined', releaseVotes: [] };
|
||||
notAllied(participants(players, parties));
|
||||
if (!deal.participants) return { ...deal, status: 'active', releaseVotes: [],
|
||||
...(deal.additionalPayments ? {additionalPayments: deal.additionalPayments.map(term => ({...term, paymentStatus:'pending' as const}))} : {}),
|
||||
...(deal.payment?.kind === 'deferredBribe' ? { paymentStatus: 'pending' as const } : {}) };
|
||||
const alreadyAccepted = publicDealAcceptVotes(deal);
|
||||
requireDeal(!alreadyAccepted.includes(actor), 'This participant already accepted the offer.');
|
||||
@@ -279,6 +338,7 @@ export function respondPublicDeal(deal: PublicDeal, players: readonly PublicDeal
|
||||
const accepts = parties.filter(seat => seat === actor || alreadyAccepted.includes(seat));
|
||||
const active = accepts.length === parties.length;
|
||||
return { ...deal, acceptVotes: accepts, status: active ? 'active' : 'offered', releaseVotes: [],
|
||||
...(active && deal.additionalPayments ? {additionalPayments: deal.additionalPayments.map(term => ({...term, paymentStatus:'pending' as const}))} : {}),
|
||||
...(active && deal.payment?.kind === 'deferredBribe' ? { paymentStatus: 'pending' as const } : {}) };
|
||||
}
|
||||
|
||||
@@ -300,6 +360,8 @@ export function releasePublicDeal(deal: PublicDeal, players: readonly PublicDeal
|
||||
if (deal.participants) votes = parties.filter(seat => votes.includes(seat));
|
||||
const released = votes.length === parties.length;
|
||||
return { ...deal, status: released ? 'released' : 'active', releaseVotes: votes,
|
||||
...(released && deal.additionalPayments ? {additionalPayments: deal.additionalPayments.map(term => ({...term,
|
||||
paymentStatus: term.paymentStatus === 'paid' ? 'paid' as const : 'released' as const}))} : {}),
|
||||
...(released && deal.payment?.kind === 'deferredBribe' && deal.paymentStatus !== 'paid'
|
||||
? { paymentStatus: 'released' as const } : {}) };
|
||||
}
|
||||
@@ -307,8 +369,17 @@ export function releasePublicDeal(deal: PublicDeal, players: readonly PublicDeal
|
||||
/** The engine must first authorize the native payer and exact bribe action.
|
||||
* Apply this transition on its detached action state, so native failure rolls
|
||||
* both the payment and the status change back together. */
|
||||
export function markPublicDealPaid(deal: PublicDeal, players: readonly PublicDealSeat[], payer: string): PublicDeal {
|
||||
export function markPublicDealPaid(deal: PublicDeal, players: readonly PublicDealSeat[], payer: string, paymentIndex?: number): PublicDeal {
|
||||
validatePublicDeals([deal], players);
|
||||
if (paymentIndex !== undefined) {
|
||||
requireDeal(Number.isSafeInteger(paymentIndex) && paymentIndex >= 0 &&
|
||||
paymentIndex < (deal.additionalPayments?.length ?? 0), 'Choose an existing additional payment.');
|
||||
const term = deal.additionalPayments![paymentIndex];
|
||||
requireDeal(deal.status === 'active' && term.paymentStatus === 'pending' && term.payment.payer === payer,
|
||||
'Only the payer may settle a pending deferred deal payment.');
|
||||
return {...deal, additionalPayments: deal.additionalPayments!.map((row,index) =>
|
||||
index === paymentIndex ? {...row, paymentStatus:'paid' as const} : row)};
|
||||
}
|
||||
requireDeal(deal.status === 'active' && deal.payment?.kind === 'deferredBribe' &&
|
||||
deal.paymentStatus === 'pending' && deal.payment.payer === payer,
|
||||
'Only the payer may settle a pending deferred deal payment.');
|
||||
@@ -316,8 +387,17 @@ export function markPublicDealPaid(deal: PublicDeal, players: readonly PublicDea
|
||||
}
|
||||
|
||||
/** The caller must establish actual external impossibility before voiding. */
|
||||
export function voidPublicDealPayment(deal: PublicDeal, players: readonly PublicDealSeat[]): PublicDeal {
|
||||
export function voidPublicDealPayment(deal: PublicDeal, players: readonly PublicDealSeat[], paymentIndex?: number): PublicDeal {
|
||||
validatePublicDeals([deal], players);
|
||||
if (paymentIndex !== undefined) {
|
||||
requireDeal(Number.isSafeInteger(paymentIndex) && paymentIndex >= 0 &&
|
||||
paymentIndex < (deal.additionalPayments?.length ?? 0), 'Choose an existing additional payment.');
|
||||
const term = deal.additionalPayments![paymentIndex];
|
||||
requireDeal(deal.status === 'active' && term.paymentStatus === 'pending',
|
||||
'Only a pending deferred deal payment can become impossible.');
|
||||
return {...deal, additionalPayments: deal.additionalPayments!.map((row,index) =>
|
||||
index === paymentIndex ? {...row, paymentStatus:'void' as const} : row)};
|
||||
}
|
||||
requireDeal(deal.status === 'active' && deal.payment?.kind === 'deferredBribe' && deal.paymentStatus === 'pending',
|
||||
'Only a pending deferred deal payment can become impossible.');
|
||||
return { ...deal, paymentStatus: 'void' };
|
||||
|
||||
+2
-2
@@ -302,9 +302,9 @@ export const RULE_TOPICS: RuleTopic[] = [
|
||||
'A qualifying Bureaucrat may divert two spice to the Bank without reducing the payer’s cost. The remainder stays deferred. Unsupported combinations remain unavailable and do not imply an official rule prohibition.',
|
||||
'In Public deals, propose written terms to one or more human seats. Every pair of participants must be nonallied when the offer is made and accepted, a provisional interpretation. Every recipient must accept; any recipient can decline, and the proposer can withdraw the outstanding offer. Any party may request release; all must agree. The record remains active until mutually released, even when players consider it fulfilled.',
|
||||
'A deal may include one immediate spice payment between two participants. The last acceptance invokes the normal bribe action: the payer loses the gross amount immediately, Bureaucrat may divert two, and the recipient collects the remaining share at the next Mentat opening. Nothing is reserved before acceptance, and an unavailable payment leaves the offer open.',
|
||||
'A deal may instead specify one exact payment due this turn or a later turn. After everyone accepts, the payer can use that deal’s Pay button early or by the deadline. Future payments do not reserve current funds; obligations due now must still be respected. Separate deals require separate payments. A compatible Truthtrance bribe answer can be satisfied by the same payment. Mutual release cancels an unpaid term; a paid amount is not refunded.',
|
||||
'A deal may also specify multiple exact deferred payments due this turn or later. After everyone accepts, each payer can use the matching Pay button early or by its deadline. Future payments do not reserve current funds; obligations due now must still be respected. Each term requires its own payment, even when the amounts match. A compatible Truthtrance bribe answer can be satisfied by the same payment. Mutual release cancels unpaid terms; paid amounts are not refunded.',
|
||||
'In a supported Basic classic table, two to six people can agree that one invited recipient will make or avoid one reserve shipment or ground move of at least a selected number of physical forces to a named territory in the current or a later turn. In a group offer the other recipients accept first and the named traveler accepts last. A current-turn term is checked on acceptance; a later-turn term is scheduled without reserving present forces or spice. The actual action fulfills a required term; a forbidden action cannot be taken. Compatible travel terms can share one action. A bounded due-turn search protects witnessed completions; when the travel turn closes without a witness, the game provisionally voids that term. Unsupported combinations remain in development.',
|
||||
'Two-party or group travel can include one immediate or deferred payment between two participants. All parties accept, including the payer, and the traveler accepts last. An immediate payment settles with final consent; a deferred payment can be paid by its chosen deadline. When payment and travel are due this turn, acceptance checks that the payer can complete both with the available resources. Multiple-payment travel remains unfinished.',
|
||||
'Two-party or group travel can include deferred payments and at most one immediate payment between participants. All parties accept, including the payers, and the traveler accepts last. An immediate payment settles with final consent; each deferred payment can be paid by its chosen deadline. When payment and travel are due this turn, acceptance checks that the payer can complete both with the available resources. Multiple immediate payments remain unfinished.',
|
||||
'Players must honor legal deal terms; an impossible part is void. The game does not interpret or enforce free-text promises or determine impossibility. Free text alone pays no spice. Deals must not transfer cards, leaders, forces or faction advantages or contradict the rules.',
|
||||
'Minimal AI follows supported Truthtrance ordinary-payment answers and their legal guides. AI deal negotiation and automatic enforcement of prose remain unfinished.',
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user