Merge pull request 'Fund Church patronage for consenting clans with atomic administration' (#590) from dev/MC:feature/church-sponsorship-20261125 into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 4m3s
All checks were successful
DuneRealms Web CI / web (push) Successful in 4m3s
This commit is contained in:
commit
126e47301e
6 changed files with 30 additions and 18 deletions
|
|
@ -13,7 +13,7 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){
|
|||
else if(d.kind==='event'){title=field('Session title','input');title.maxLength=100;body=field('Purpose and invitation','textarea');body.maxLength=2000;body.rows=4;startsAt=field('Start time (UTC)','input');endsAt=field('End time (UTC)','input');startsAt.type=endsAt.type='datetime-local';form.append(el('p','Schedule at least one minute ahead and no more than 30 days ahead. The session must finish before your mandate ends and last at most '+(d.maxEventMs||86400000)/3600000+' hours. It appears in the existing political calendar.'));if(d.id==='SG-06')form.append(el('p','This convenes voluntary mediation. Participants must separately approve any treaty, coalition or peace through its existing consent flow.'));}
|
||||
else if(d.kind==='tariff'){percent=field('Guild surcharge','select');for(let n=0;n<=5;n++){const o=el('option',n===0?'0% · repeal':n+'%');o.value=String(n);percent.append(o);}form.append(el('p','Applies to new Guild bookings for seven days, while this mandate remains current. Confirmed fares remain unchanged. It does not open blocked routes or change smuggler fares.'));}
|
||||
else if(d.kind==='guild-discount'){houseSelect=field('Native House','select');for(const w of TRADE_WORLDS){const o=el('option',w.name+' · '+w.house);o.value=w.house;houseSelect.append(o);}form.append(el('p',d.discountPercent+'% preferred Guild fare for '+d.durationMs/3600000+' hours. The strongest eligible discount applies; discounts do not stack. It does not grant new routes, alter boarding windows or override an embargo or Imperial Arrakis permission.'));}
|
||||
else if(d.kind==='clan-grant'){clanSelect=field('Receiving clan','select');grantAmount=field('Development allocation (DM)','input');grantAmount.type='number';grantAmount.step='0.01';grantAmount.min=String(d.grantMinMinor/100);grantAmount.max=String(d.grantMaxMinor/100);grantAmount.value=String(d.grantMaxMinor/100);grantAmount.readOnly=d.grantMinMinor===d.grantMaxMinor;grantReason=field('Development purpose','textarea');grantReason.minLength=10;grantReason.maxLength=2000;grantReason.rows=4;form.append(el('p','Paid from the House account to the receiving clan’s active account. A Basic clan receives through its current legal owner’s personal payment account. The receipt records the allocation and its purpose.'));}
|
||||
else if(d.kind==='clan-grant'){clanSelect=field('Receiving clan','select');grantAmount=field('Development allocation (DM)','input');grantAmount.type='number';grantAmount.step='0.01';grantAmount.min=String(d.grantMinMinor/100);grantAmount.max=String(d.grantMaxMinor/100);grantAmount.value=String(d.grantMaxMinor/100);grantAmount.readOnly=d.grantMinMinor===d.grantMaxMinor;grantReason=field('Development purpose','textarea');grantReason.minLength=10;grantReason.maxLength=2000;grantReason.rows=4;form.append(el('p','Paid from the authorised office account to the receiving clan’s active account. A Basic clan receives through its current legal owner’s personal payment account. The receipt records the allocation and its purpose.'));}
|
||||
else if(d.kind==='honour'){search=field('Find recipient by player name','input');search.maxLength=64;find=el('button','Find players');find.type='button';form.append(find);recipient=field('Recipient','select');citation=field('Citation','textarea');citation.maxLength=2000;citation.rows=4;form.append(el('p','Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted. Renewing replaces the displayed recognition.'));}
|
||||
const reportHost=el('section');if(d.kind==='report')host.append(reportHost);
|
||||
function drawReport(report){reportHost.replaceChildren();if(!report)return;const dm=value=>{const n=BigInt(value);return(n/100n).toLocaleString('en-GB')+'.'+String(n%100n).padStart(2,'0')+' DM';};reportHost.append(el('h4','Verified market report'),el('p','Snapshot: '+new Date(report.observedAt).toLocaleString()),el('p',report.scope),el('p',report.listedStacks+' listings · '+report.units+' units · '+dm(report.askingValueMinor)+' asking value'));const table=el('table'),head=el('tr');for(const text of ['Creation world','Listings','Units','Asking value'])head.append(el('th',text));table.append(head);for(const row of report.byWorld){const tr=el('tr');for(const text of [row.world.replaceAll('_',' '),row.listedStacks,row.units,dm(row.askingValueMinor)])tr.append(el('td',String(text)));table.append(tr);}reportHost.append(table);if(report.transport){reportHost.append(el('h4','Guild arrivals · last seven days'),el('p',report.transport.scope));for(const row of report.transport.arrivals)reportHost.append(el('p',row.world.replaceAll('_',' ')+': '+row.total));if(!report.transport.arrivals.length)reportHost.append(el('p','No confirmed arrivals in this period.'));}}
|
||||
|
|
@ -27,16 +27,16 @@ export function mountPoliticalDecision(host,id,{fetcher=fetch}={}){
|
|||
if(clanSelect){const selected=clanSelect.value;clanSelect.replaceChildren();for(const c of data.clans){const o=el('option',c.name);o.value=c.id;clanSelect.append(o);}if(data.clans.some(c=>c.id===selected))clanSelect.value=selected;}
|
||||
if(recipient){const selected=recipient.value;recipient.replaceChildren();for(const r of data.recipients){const o=el('option',r.username);o.value=r.id;recipient.append(o);}if(data.recipients.some(r=>r.id===selected))recipient.value=selected;}
|
||||
status.textContent=(data.canManage?'Current office verified. ':'Current elected office required. ')+(d.feeMinor/100).toFixed(2)+' DM from the selected office account · '+d.xp+' Reputation points · Reputation level '+data.levelNow+'/'+d.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():d.cooldownMs/3600000+'-hour office cooldown.')+(data.reportAvailable===false?' Verified reporting is unavailable; no payment can be made.':'');if(d.kind==='report')drawReport(data.report);
|
||||
if(d.kind==='clan-grant')status.textContent=(data.canManage?'Current House office verified. ':'Current House office required. ')+(d.grantMinMinor/100).toFixed(2)+'–'+(d.grantMaxMinor/100).toFixed(2)+' DM development allocation; up to '+d.xp+' Reputation points, proportional to the funded amount. Reputation '+data.levelNow+'/'+d.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():d.cooldownMs/3600000+'-hour office cooldown.');
|
||||
if(d.kind==='clan-grant')status.textContent=(data.canManage?'Current office verified. ':'Current office required. ')+(d.grantMinMinor/100).toFixed(2)+'–'+(d.grantMaxMinor/100).toFixed(2)+' DM development allocation'+(d.feeMinor?' + '+(d.feeMinor/100).toFixed(2)+' DM administrative fee':'')+'; up to '+d.xp+' Reputation points, proportional to the funded amount. Reputation '+data.levelNow+'/'+d.level+' required. '+(data.cooldownUntil>Date.now()?'Available after '+new Date(data.cooldownUntil).toLocaleString():d.cooldownMs/3600000+'-hour office cooldown.');
|
||||
}catch(e){status.textContent=e.message;}finally{busy=false;controls();}}
|
||||
prepare.onclick=()=>{
|
||||
const payload=d.kind==='agreement'?{targetOffice:officeSelect.value,title:title.value,terms:body.value}:d.kind==='proclamation'?{title:title.value,body:body.value}:d.kind==='event'?{title:title.value,description:body.value,startsAt:Date.parse(startsAt.value+'Z'),endsAt:Date.parse(endsAt.value+'Z')}:d.kind==='clan-grant'?{clanId:clanSelect.value,amountMinor:Math.round(Number(grantAmount.value)*100),reason:grantReason.value}:d.kind==='guild-discount'?{house:houseSelect.value}:d.kind==='tariff'?{percent:Number(percent.value)}:d.kind==='report'?{}:{recipientId:recipient.value,citation:citation.value};
|
||||
if(d.kind==='agreement'&&(!officeSelect.value||title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Choose a receiving office and complete the proposal title and terms.';return;}
|
||||
if(d.kind==='clan-grant'&&(!clanSelect.value||!grantAmount.reportValidity()||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinor<d.grantMinMinor||payload.amountMinor>d.grantMaxMinor||grantReason.value.trim().length<10)){status.textContent='Choose a receiving clan, published grant amount and development purpose.';return;}
|
||||
if(!account.value||['proclamation','event'].includes(d.kind)&&(title.value.trim().length<3||body.value.trim().length<10)||d.kind==='event'&&(!Number.isSafeInteger(payload.startsAt)||!Number.isSafeInteger(payload.endsAt)||payload.startsAt<Date.now()+60000||payload.endsAt<=payload.startsAt)||d.kind==='honour'&&(!recipient.value||citation.value.trim().length<3)){status.textContent='Choose funding and complete the decision details and dates.';return;}
|
||||
const paymentMinor=d.kind==='clan-grant'?payload.amountMinor:d.feeMinor,rewardXP=d.kind==='clan-grant'?Math.max(1,Math.floor(d.xp*payload.amountMinor/d.grantMaxMinor)):d.xp;
|
||||
const paymentMinor=d.kind==='clan-grant'?payload.amountMinor+d.feeMinor:d.feeMinor,rewardXP=d.kind==='clan-grant'?Math.max(1,Math.floor(d.xp*payload.amountMinor/d.grantMaxMinor)):d.xp;
|
||||
if(!current?.accounts.some(a=>String(a.id)===account.value&&BigInt(a.availableMinor)>=BigInt(paymentMinor))){status.textContent='The selected office account has insufficient available funds for this amount.';return;}
|
||||
pending={decisionId:id,requestId:crypto.randomUUID(),sourceAccount:account.value,...payload,confirmed:true};review.textContent='Confirm '+d.title+(officeSelect?' to '+officeSelect.selectedOptions[0].textContent:recipient?' for '+recipient.selectedOptions[0].textContent:title?' “'+title.value.trim()+'”':clanSelect?' for '+clanSelect.selectedOptions[0].textContent:houseSelect?' for '+houseSelect.selectedOptions[0].textContent:percent?' '+percent.value+'%':'')+' · '+(paymentMinor/100).toFixed(2)+' DM from '+account.selectedOptions[0].textContent+'. '+rewardXP+' Reputation points; cooldown '+d.cooldownMs/3600000+' hours.';confirm.hidden=false;controls();
|
||||
pending={decisionId:id,requestId:crypto.randomUUID(),sourceAccount:account.value,...payload,confirmed:true};review.textContent='Confirm '+d.title+(officeSelect?' to '+officeSelect.selectedOptions[0].textContent:recipient?' for '+recipient.selectedOptions[0].textContent:title?' “'+title.value.trim()+'”':clanSelect?' for '+clanSelect.selectedOptions[0].textContent:houseSelect?' for '+houseSelect.selectedOptions[0].textContent:percent?' '+percent.value+'%':'')+' · '+(paymentMinor/100).toFixed(2)+' DM from '+account.selectedOptions[0].textContent+'. '+rewardXP+' Reputation points; cooldown '+d.cooldownMs/3600000+' hours.';if(d.kind==='clan-grant'&&d.feeMinor)review.textContent+=' Includes '+(payload.amountMinor/100).toFixed(2)+' DM sponsorship and '+(d.feeMinor/100).toFixed(2)+' DM administration.';confirm.hidden=false;controls();
|
||||
};
|
||||
confirm.onclick=async()=>{if(busy||!pending)return;busy=true;controls();try{const receipt=await api.request(endpoint,pending);pending=null;confirm.hidden=true;review.textContent=(receipt.grant?'Allocated '+(Number(receipt.grant.amountMinor)/100).toFixed(2)+' DM to '+receipt.grant.clanName+'. ':'Completed. ')+'J.A.R.V.I.S. reference: '+receipt.keyId;if(title){title.value='';body.value='';}if(citation)citation.value='';await load();}catch(e){status.textContent=e.message+(e.uncertain?' Retry this same confirmation to check or complete it without a second charge.':'');if(!e.uncertain){pending=null;confirm.hidden=true;}}finally{busy=false;controls();}};
|
||||
refresh.onclick=load;if(find)find.onclick=load;load();
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ export const MASTER_KEY_TEMPLATES=[
|
|||
{id:'politics',label:'POL & orders',actions:[
|
||||
action('politics.diplomatic-proposal','Confidential diplomatic proposal','entity-state',[field('decisionId','Diplomatic decision','select',{options:['ATR-05','COR-06','ORD-05','BG-05','NF-05']}),field('sourceAccount','Authorised office funding account'),field('targetOffice','Receiving Royal office'),field('title','Proposal title'),field('terms','Confidential diplomatic terms','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalAgreements',executionStatus:'current-officeholder-bilateral-consent-consumer',effect:'Five fixed diplomatic policies charge the published office fee and award Reputation atomically with a confidential proposal. A different current Royal office holder must answer within72h; both mandates must cover that full window. Accepted terms last at most7d, or14d for Corrino, and end with either original mandate. Original participants alone see the terms. No votes, ownership, bank authority, travel or war consent move.'}),
|
||||
action('politics.diplomatic-response','Accept or refuse a diplomatic proposal','entity-state',[field('proposalId','Proposal UUID'),field('choice','Response','select',{options:['accept','decline']}),field('requestId','Response UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalAgreements.reply',executionStatus:'original-receiving-officeholder-consent-consumer',effect:'Only the original receiving current Royal mandate can accept or refuse a live72h proposal. Recheck both original mandates and the unrevoked signed proposal under the same transaction; record one signed response. Exact retries return the original receipt; conflicting responses, changed holders, expired or revoked proposals cannot manufacture acceptance. No further payment or Reputation is issued for replying.'}),
|
||||
action('politics.clan-development-grant','House clan development allocation','entity-state',[field('decisionId','Registered development grant','select',{options:['ATR-01','ATR-04','HAR-02','COR-02','COR-04']}),field('sourceAccount','Authorised House funding account'),field('clanId','Receiving clan UUID'),field('amountMinor','Development allocation in DM minor units','number',{min:10000}),field('reason','Development purpose','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalClanGrants / organisationRewardRoute',executionStatus:'current-house-office-and-current-clan-deed-consumer',effect:'Five fixed House policies re-read the native clan homeworld, current legal deed, active receiving bank account and authorised House source. Atreides Patronage is exactly10,000 DM; other published grants range from100 DM to their15,000/25,000 DM cap. Basic clans route to their current legal owner, keyed clans to their own account; mother control never substitutes for that owner. Actual funded amount scales Reputation up to the catalogue cap. Existing balanced bank transfer, immutable purpose, ordinary key and Reputation commit together; safe retries retain the original payment recipient. No P&O issuance, account activation, construction completion, inventory progress or ownership change is fabricated.'}),
|
||||
action('politics.clan-development-grant','Office clan development allocation','entity-state',[field('decisionId','Registered development grant','select',{options:['ATR-01','ATR-04','HAR-02','COR-02','COR-04','NF-03']}),field('sourceAccount','Authorised House funding account'),field('clanId','Receiving clan UUID'),field('amountMinor','Development allocation in DM minor units','number',{min:10000}),field('reason','Development purpose','textarea'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createPoliticalClanGrants / organisationRewardRoute',executionStatus:'current-house-office-and-current-clan-deed-consumer',effect:'House development policies re-read the native clan homeworld, current legal deed, active receiving bank account and authorised House source. Atreides Patronage is exactly10,000 DM; other published grants range from100 DM to their15,000/25,000 DM cap. Basic clans route to their current legal owner, keyed clans to their own account; mother control never substitutes for that owner. Actual funded amount scales Reputation up to the catalogue cap. Existing balanced bank transfer, immutable purpose, ordinary key and Reputation commit together; safe retries retain the original payment recipient. Church sponsorship additionally requires current signed New Faith consent, caps funding at10,000 DM and pays a separate2,500 DM Tax admin fee; grant, fee and proportional Reputation commit or roll back together, with a7d cooldown. No P&O issuance, account activation, construction completion, inventory progress or ownership change is fabricated.'}),
|
||||
action('politics.guild-mediation','Convene Guild mediation','entity-state',[field('decisionId','Mediation decision','select',{options:['SG-06']}),field('sourceAccount','Authorised Guild funding account'),field('title','Session title'),field('description','Dispute and invitation','textarea'),field('startsAt','Start UTC timestamp','number'),field('endsAt','End UTC timestamp','number'),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / createRealmEventRecord',executionStatus:'current-guild-officeholder-calendar-consumer',effect:'Current Royal Guild holder, Reputation35,5,000 DM office fee and600 Reputation points. A72h successor-safe cooldown; schedule voluntary mediation for at most72h, entirely within the source mandate and at most30 days ahead. Reuse the political EVT calendar and its existing management rights. Fee, calendar history, Reputation and ordinary key commit atomically. No automatic peace, treaty, war, coalition or participant consent is fabricated; participants use the existing mutual agreement flows.'}),
|
||||
action('politics.guild-preferred-fare','Guild preferred House fares','entity-state',[field('decisionId','Guild decision','select',{options:['SG-02','SG-07']}),field('sourceAccount','Authorised Guild funding account'),field('house','Native House','select',{options:['atreides','harkonnen','corrino','ordos','fremen']}),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / currentGuildDiscount / createGuildService',executionStatus:'current-guild-officeholder-preferred-fare-consumer',effect:'Priority Passage: Reputation 15, fixed 2,500 DM Guild fee, 250 Reputation, 25% preferred fare for72h and48h cooldown. Guild Favour: Reputation10, 5,000 DM fee, 200 Reputation,10% for7d and7d cooldown. Latest signed grant per decision replaces the earlier House; current source mandate and expiry required. Only the strongest eligible discount applies after any surcharge. No new routes, boarding priority, embargo override, Imperial Arrakis permission or smuggler rate. Confirmed ticket fares remain immutable and no grant activates by default.'}),
|
||||
action('politics.guild-surcharge','Guild transport surcharge','entity-state',[field('decisionId','Guild decision','select',{options:['SG-05']}),field('sourceAccount','Authorised Guild funding account'),field('percent','Surcharge percentage','number',{min:0,max:5}),field('requestId','Request UUID')],{version:1,webIssue:false,recordOnly:true,domainAdapter:'createPoliticalDecisions.execute / currentGuildSurcharge / createGuildService',executionStatus:'current-guild-officeholder-fare-consumer',effect:'Royal Guild office holder, Reputation 40, fixed 5,000 DM office fee and 750 Reputation points. Seven-day successor-safe cooldown and at most seven-day 0–5% tariff, ending with its source mandate; 0 repeals. The latest signed unrevoked record controls new quote/boarding fares. Stale quotes cannot reserve funds. Existing confirmed fares and identical ticket retries retain their original amount; no route, embargo, Arrakis or smuggler right changes. No client plugin rollout or default activation.'}),
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ export const POLITICAL_DECISIONS=Object.freeze([
|
|||
['BG-05','veiled_concord','Whispered Alliance',35,600,500000,168,7],
|
||||
['NF-05','muad_dib','Whispered Alliance',35,600,500000,168,7]
|
||||
].map(([id,office,title,level,xp,feeMinor,hours,days])=>({id,office,title,level,xp,feeMinor,cooldownMs:hours*3600000,kind:'agreement',responseMs:72*3600000,durationMs:days*86400000})),
|
||||
{id:'NF-03',office:'muad_dib',title:'Church Patronage',kind:'clan-grant',grantFaith:'muad_dib',level:25,xp:400,feeMinor:250000,grantMinMinor:10000,grantMaxMinor:1000000,cooldownMs:7*86400000},
|
||||
{id:'ATR-01',office:'atreides',title:'Atreides Patronage',kind:'clan-grant',grantWorld:'caladan',level:10,xp:200,feeMinor:0,grantMinMinor:1000000,grantMaxMinor:1000000,cooldownMs:72*3600000},
|
||||
{id:'ATR-04',office:'atreides',title:'Waterworld Development',kind:'clan-grant',grantWorld:'caladan',level:25,xp:400,feeMinor:0,grantMinMinor:10000,grantMaxMinor:2500000,cooldownMs:7*86400000},
|
||||
{id:'HAR-02',office:'harkonnen',title:'Baronial Patronage',kind:'clan-grant',grantWorld:'giedi_prime',level:15,xp:250,feeMinor:0,grantMinMinor:10000,grantMaxMinor:1500000,cooldownMs:72*3600000},
|
||||
|
|
@ -37,4 +38,4 @@ export const POLITICAL_DECISIONS=Object.freeze([
|
|||
].map(d=>Object.freeze({...d,durationMs:d.durationMs??(d.kind==='honour'?30*86400000:null)})));
|
||||
export const politicalDecision=id=>POLITICAL_DECISIONS.find(d=>d.id===id)||null;
|
||||
export function proclamationDecisionId(kind,faction){return kind==='imperial'?'IMP-04':kind==='guild'?'SG-PROCLAIM':kind==='house'?({atreides:'ATR-PROCLAIM',harkonnen:'HAR-PROCLAIM',corrino:'COR-PROCLAIM',ordos:'ORD-PROCLAIM',veiled_concord:'BG-04',muad_dib:'NF-04'})[faction]||null:null;}
|
||||
export const POLITICAL_DECISION_CATALOGUE=Object.freeze(POLITICAL_DECISIONS.map(d=>Object.freeze({...d,office:({emperor:'IMP',atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',veiled_concord:'BG',muad_dib:'NF',spacing_guild:'SG'})[d.office],cost:(d.kind==='clan-grant'?(d.grantMinMinor===d.grantMaxMinor?(d.grantMaxMinor/100).toLocaleString('en-GB'):'Grant amount'):(d.feeMinor/100).toLocaleString('en-GB'))+' / '+d.cooldownMs/3600000+'h',effect:d.kind==='agreement'?'Send a confidential diplomatic proposal to another current Royal office holder, who must consent within 72 hours. Accepted terms last '+d.durationMs/86400000+' days at most and end with either mandate. This records diplomatic terms without moving votes, ownership, military allegiance or bank rights.':d.kind==='clan-grant'?'Allocate '+(d.grantMaxMinor/100).toLocaleString('en-GB')+' DM'+(d.grantMinMinor===d.grantMaxMinor?'':' maximum')+' from this House to a current clan on its native world. Basic clans receive through the current legal owner; other clans use their own account. Reputation scales with the amount; allocation and its purpose are recorded together.':d.kind==='guild-discount'?'Give one native House '+d.discountPercent+'% off new Guild bookings for '+d.durationMs/3600000+' hours. Preferred fares never stack, open routes, change boarding windows or override embargoes and Imperial Arrakis access.':d.kind==='tariff'?'Set a 0–5% surcharge on new Guild bookings for seven days; choose 0 to repeal. Existing confirmed fares remain unchanged.':d.kind==='event'?(d.effect||'Schedule an official audience in the existing House calendar. Fixed office funding, Reputation and cooldown; no election, membership or travel change.'):d.kind==='report'?'Read a sealed aggregate of available Exchange stock. Guild reports also include seven-day confirmed arrival totals. No passenger identities, private orders or account balances. Fixed office funding and cooldown.':d.kind==='proclamation'?'Publish an official message in this office’s existing proclamation archive. Fixed office funding and cooldown; no membership or voting rights change.':'Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted.'})));
|
||||
export const POLITICAL_DECISION_CATALOGUE=Object.freeze(POLITICAL_DECISIONS.map(d=>Object.freeze({...d,office:({emperor:'IMP',atreides:'ATR',harkonnen:'HAR',corrino:'COR',ordos:'ORD',veiled_concord:'BG',muad_dib:'NF',spacing_guild:'SG'})[d.office],cost:(d.kind==='clan-grant'?(d.grantMinMinor===d.grantMaxMinor?(d.grantMaxMinor/100).toLocaleString('en-GB'):'Grant amount')+(d.feeMinor?' + '+(d.feeMinor/100).toLocaleString('en-GB')+' admin':''):(d.feeMinor/100).toLocaleString('en-GB'))+' / '+d.cooldownMs/3600000+'h',effect:d.kind==='agreement'?'Send a confidential diplomatic proposal to another current Royal office holder, who must consent within 72 hours. Accepted terms last '+d.durationMs/86400000+' days at most and end with either mandate. This records diplomatic terms without moving votes, ownership, military allegiance or bank rights.':d.kind==='clan-grant'?'Allocate '+(d.grantMaxMinor/100).toLocaleString('en-GB')+' DM'+(d.grantMinMinor===d.grantMaxMinor?'':' maximum')+(d.grantFaith?' from the Church to a clan with current signed New Faith consent. A separate 2,500 DM administrative fee goes to Tax.':' from this House to a current clan on its native world.')+' Basic clans receive through the current legal owner; other clans use their own account. Reputation scales with the amount; allocation and its purpose are recorded together.':d.kind==='guild-discount'?'Give one native House '+d.discountPercent+'% off new Guild bookings for '+d.durationMs/3600000+' hours. Preferred fares never stack, open routes, change boarding windows or override embargoes and Imperial Arrakis access.':d.kind==='tariff'?'Set a 0–5% surcharge on new Guild bookings for seven days; choose 0 to repeal. Existing confirmed fares remain unchanged.':d.kind==='event'?(d.effect||'Schedule an official audience in the existing House calendar. Fixed office funding, Reputation and cooldown; no election, membership or travel change.'):d.kind==='report'?'Read a sealed aggregate of available Exchange stock. Guild reports also include seven-day confirmed arrival totals. No passenger identities, private orders or account balances. Fixed office funding and cooldown.':d.kind==='proclamation'?'Publish an official message in this office’s existing proclamation archive. Fixed office funding and cooldown; no membership or voting rights change.':'Ceremonial profile recognition for '+d.durationMs/86400000+' days. No office, rank, vote or permission is granted.'})));
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"schemaVersion": 1,
|
||||
"sourceHash": "6f4a3e5d3ff1857ae218f3f51db437b84de888575d242b84db567d9ee06ecbfe",
|
||||
"sourceHash": "44c98855fa02fc5a36c6dae8457232fd9177b869eca449fad50074c6f36ca4b8",
|
||||
"actions": [
|
||||
{
|
||||
"id": "war.coalition-consent",
|
||||
|
|
@ -536,7 +536,7 @@
|
|||
},
|
||||
{
|
||||
"id": "politics.clan-development-grant",
|
||||
"label": "POL & orders · House clan development allocation",
|
||||
"label": "POL & orders · Office clan development allocation",
|
||||
"version": 1,
|
||||
"keyType": "entity-state",
|
||||
"fields": [
|
||||
|
|
@ -557,7 +557,8 @@
|
|||
"ATR-04",
|
||||
"HAR-02",
|
||||
"COR-02",
|
||||
"COR-04"
|
||||
"COR-04",
|
||||
"NF-03"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -592,7 +593,7 @@
|
|||
"required": true
|
||||
}
|
||||
],
|
||||
"effect": "Five fixed House policies re-read the native clan homeworld, current legal deed, active receiving bank account and authorised House source. Atreides Patronage is exactly10,000 DM; other published grants range from100 DM to their15,000/25,000 DM cap. Basic clans route to their current legal owner, keyed clans to their own account; mother control never substitutes for that owner. Actual funded amount scales Reputation up to the catalogue cap. Existing balanced bank transfer, immutable purpose, ordinary key and Reputation commit together; safe retries retain the original payment recipient. No P&O issuance, account activation, construction completion, inventory progress or ownership change is fabricated.",
|
||||
"effect": "House development policies re-read the native clan homeworld, current legal deed, active receiving bank account and authorised House source. Atreides Patronage is exactly10,000 DM; other published grants range from100 DM to their15,000/25,000 DM cap. Basic clans route to their current legal owner, keyed clans to their own account; mother control never substitutes for that owner. Actual funded amount scales Reputation up to the catalogue cap. Existing balanced bank transfer, immutable purpose, ordinary key and Reputation commit together; safe retries retain the original payment recipient. Church sponsorship additionally requires current signed New Faith consent, caps funding at10,000 DM and pays a separate2,500 DM Tax admin fee; grant, fee and proportional Reputation commit or roll back together, with a7d cooldown. No P&O issuance, account activation, construction completion, inventory progress or ownership change is fabricated.",
|
||||
"fixedTargets": [],
|
||||
"webIssue": false,
|
||||
"recordOnly": true
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
|
|||
// The production central pool exposes prepared reads rather than first().
|
||||
// Keep every transaction callback on its original connection.
|
||||
db={...boardReadStore(db,db),transaction:db.transaction.bind(db)};
|
||||
const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,centralTables:['jarvis_political_decisions','jarvis_political_agreement_replies','political_proclamations','political_office_terms','political_office_charters','organisation_keys','organisation_key_events','codex_instance_editions','account_audit','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts']});
|
||||
const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,centralTables:['jarvis_political_decisions','jarvis_political_agreement_replies','political_proclamations','political_office_terms','political_office_charters','organisation_keys','organisation_key_events','codex_instance_editions','account_audit','jarvis_pol_progression_seasons','jarvis_pol_progression_accounts','jarvis_pol_progression_history','jarvis_pol_progression_outbox','jarvis_clan_faith','jarvis_faith_consents','site_clans','site_clan_deeds','site_clan_charters','site_clan_members','site_game_links','site_accounts']});
|
||||
async function accounts(tx,actor,d){const b=banking.view(tx),r=politicalDecisionReader(tx,db),authority=deps.authority||createPostbankAuthority(r,{bank:b,clock});const rights=await authority(actor,{bank:b});return(await b.query(accountsSQL+' WHERE c.entity_id=? AND a.system_key IS NULL ORDER BY a.id',[funding(d)])).filter(a=>ordinaryPaymentAccount(a)&&canDebitAccount(rights,a.entity_id,a.id));}
|
||||
const eventBanking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,bankTables:['jarvis_events','jarvis_event_history']});
|
||||
async function recipients(tx,actor,d,search=''){
|
||||
|
|
@ -64,7 +64,7 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
|
|||
const xp=await polProgressionStore(db).first('SELECT effective_xp FROM jarvis_progression_accounts WHERE account_id=?',[actor.id]),seasons=await polProgressionStore(db).query("SELECT * FROM jarvis_progression_seasons WHERE state='active' AND starts_at<=? AND ends_at>?",[now,now]);
|
||||
const season=seasons.length===1?seasons[0]:null,level=season?levelForXP(Number(xp?.effective_xp||0),{base:Number(season.curve_base),cap:Number(season.level_cap)||null}):0;
|
||||
const choices=holder?await accounts(db,actor,d):[];let reportAvailable=true;if(d.kind==='report'){try{if(!deps.marketReports)throw Error('No reporting source');await deps.marketReports.ready();}catch{reportAvailable=false;}}
|
||||
const clans=holder&&d.kind==='clan-grant'&&deps.clanGrants?await deps.clanGrants.targets(db,d):[],grantAvailable=d.kind!=='clan-grant'||!!deps.clanGrants&&clans.length>0,minimum=d.kind==='clan-grant'?d.grantMinMinor:d.feeMinor;
|
||||
const clans=holder&&d.kind==='clan-grant'&&deps.clanGrants?await deps.clanGrants.targets(db,d):[],grantAvailable=d.kind!=='clan-grant'||!!deps.clanGrants&&clans.length>0,minimum=d.kind==='clan-grant'?d.grantMinMinor+d.feeMinor:d.feeMinor;
|
||||
const diplomacyTargets=holder&&d.kind==='agreement'&&deps.agreements?await deps.agreements.targets(db,d,actor,now):[];
|
||||
return{...d,diplomacyTargets,clans,grantAvailable,canManage:!!holder,canExecute:(d.kind!=='agreement'||diplomacyTargets.length>0)&&grantAvailable&&reportAvailable&&!!holder&&!!keys&&!!season&&level>=d.level&&(!cooldownUntil||now>=cooldownUntil)&&choices.some(a=>BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(minimum)),reportAvailable,report:holder&&d.kind==='report'&&prior?JSON.parse(prior.receipt_json).report||null:null,levelNow:level,cooldownUntil,accounts:choices.map(a=>({id:String(a.id),name:a.display_name,number:a.account_number,availableMinor:String(BigInt(a.balance_minor)-BigInt(a.reserved_minor))})),recipients:holder?await recipients(db,actor,d,search):[]};
|
||||
}
|
||||
|
|
@ -85,10 +85,12 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
|
|||
const b=banking.view(tx);await b.first('SELECT id FROM pb_entities WHERE id=? FOR SHARE',[funding(d)]);
|
||||
let grant=null;if(d.kind==='clan-grant'){if(!deps.clanGrants)fail('Clan grant records unavailable.',503);grant=await deps.clanGrants.resolve(tx,b,d,payload.clanId);}
|
||||
const taxMeta=grant?.account||await b.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!taxMeta)fail('Receiving treasury unavailable.',503);
|
||||
await b.query('SELECT id FROM pb_accounts WHERE id IN (?,?) ORDER BY id FOR UPDATE',[sourceAccount,taxMeta.id]);
|
||||
const source=(await accounts(tx,actor,d)).find(a=>String(a.id)===sourceAccount),tax=await b.first(grant?accountsSQL+' WHERE a.id=?':'SELECT * FROM pb_accounts WHERE id=?',[taxMeta.id]),amount=BigInt(grant?payload.amountMinor:d.feeMinor);
|
||||
const adminMeta=grant&&d.feeMinor?await b.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'"):null;if(grant&&d.feeMinor&&!adminMeta)fail('Administrative treasury unavailable.',503);
|
||||
const lockedIds=[sourceAccount,taxMeta.id,...(adminMeta?[adminMeta.id]:[])];await b.query('SELECT id FROM pb_accounts WHERE id IN ('+lockedIds.map(()=>'?').join(',')+') ORDER BY id FOR UPDATE',lockedIds);
|
||||
const source=(await accounts(tx,actor,d)).find(a=>String(a.id)===sourceAccount),tax=await b.first(grant?accountsSQL+' WHERE a.id=?':'SELECT * FROM pb_accounts WHERE id=?',[taxMeta.id]),amount=BigInt(grant?payload.amountMinor:d.feeMinor),adminAmount=BigInt(grant?d.feeMinor:0),admin=adminMeta?await b.first('SELECT * FROM pb_accounts WHERE id=?',[adminMeta.id]):null;
|
||||
if(!source)fail('Choose an authorised office funding account.',403);
|
||||
if(!tax||tax.state!=='active'||grant&&!ordinaryPaymentAccount(tax)||String(source.id)===String(tax.id)||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount||BigInt(tax.balance_minor)+amount>9223372036854775807n)fail('Insufficient funds or unavailable treasury.');
|
||||
if(!tax||tax.state!=='active'||grant&&!ordinaryPaymentAccount(tax)||String(source.id)===String(tax.id)||BigInt(source.balance_minor)-BigInt(source.reserved_minor)<amount+adminAmount||BigInt(tax.balance_minor)+amount>9223372036854775807n)fail('Insufficient funds or unavailable treasury.');
|
||||
if(adminAmount&&(!admin||admin.system_key!=='sys_tax_treasury'||admin.state!=='active'||[source.id,tax.id].map(String).includes(String(admin.id))||BigInt(admin.balance_minor)+adminAmount>9223372036854775807n))fail('Administrative treasury unavailable.');
|
||||
const pol=polProgressionStore(tx),season=await readActiveXPSeason(pol,now),state=await lockXPAccount(pol,actor.id,now),level=levelForXP(state.effectiveXP,{base:Number(season.curve_base),cap:Number(season.level_cap)||null});if(level<d.level)fail('Reputation level '+d.level+' is required.',403);
|
||||
let report=null;if(d.kind==='report'){if(!deps.marketReports)fail('Verified Exchange reporting unavailable. No decision was charged.',503);report=await deps.marketReports.report(tx,d,now);}
|
||||
let agreement=null;if(d.kind==='agreement'){if(!deps.agreements)fail('Political agreements unavailable.',503);agreement=await deps.agreements.create(tx,{d,actor,payload,holder,now});}
|
||||
|
|
@ -96,9 +98,10 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){
|
|||
let receipt;
|
||||
await keys.issue({accountId:STAFF_OFFICE_ACCOUNT_ID,keyType:'entity-state',scopeId:'state:political-decision:'+requestId,transactionStore:tx,authorize:async(_,{keyId})=>{
|
||||
const effectId=randomUUID(),expiresAt=d.durationMs?now+d.durationMs:null;
|
||||
receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:String(amount),xp:rewardXP,expiresAt,cooldownUntil:now+d.cooldownMs,...(report?{report}:{}),...(agreement?{agreement}:{}),...(grant?{grant:{clanId:grant.clanId,clanName:grant.clanName,amountMinor:String(amount),basicFallback:grant.basic,recipientKind:grant.recipientKind}}:{})};
|
||||
receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:String(amount+adminAmount),adminFeeMinor:String(adminAmount),xp:rewardXP,expiresAt,cooldownUntil:now+d.cooldownMs,...(report?{report}:{}),...(agreement?{agreement}:{}),...(grant?{grant:{clanId:grant.clanId,clanName:grant.clanName,amountMinor:String(amount),basicFallback:grant.basic,recipientKind:grant.recipientKind}}:{})};
|
||||
await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[requestId,actor.id,source.id,tax.id,digest,String(amount),d.title,now]);
|
||||
await new PostbankPayments(bank,null,{clock}).post(b,{id:requestId,actor_id:actor.id,amount_minor:String(amount)},source,tax,false);
|
||||
if(adminAmount){const adminId=randomUUID(),remaining=await b.first(accountsSQL+' WHERE a.id=?',[source.id]);await b.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[adminId,actor.id,source.id,admin.id,fingerprint([requestId,d.id,'administration']),String(adminAmount),d.title+' administration',now]);await new PostbankPayments(bank,null,{clock}).post(b,{id:adminId,actor_id:actor.id,amount_minor:String(adminAmount)},remaining,admin,false);}
|
||||
if(d.kind==='proclamation')await tx.query('INSERT INTO political_proclamations(id,request_id,scope,title,body,author_id,created_at,version) VALUES(?,?,?,?,?,?,?,1)',[effectId,requestId,d.scope||'imperium',payload.title,payload.body,actor.id,now]);
|
||||
if(d.kind==='event'){const event=await createRealmEventRecord(eventBanking.view(tx),actor,{requestId,kind:'politics',scopeId:d.office,...payload},now);receipt.eventId=event.eventId;receipt.calendarScope=d.office;}
|
||||
const updated=creditXP(state,rewardXP,{capXP:Number(season.level_cap)===0?Number.MAX_SAFE_INTEGER:xpAtLevel(Number(season.level_cap),Number(season.curve_base))});
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ import {currentGuildSurcharge,currentGuildDiscount} from '../node/guild-tariff-p
|
|||
import {createPoliticalClanGrants} from '../node/political-clan-grants.mjs';
|
||||
import {initializeClans} from '../control-panel/clans.mjs';
|
||||
import {POLITICAL_AGREEMENT_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs';
|
||||
import {initializeClanFaith,createClanFaith} from '../node/clan-faith.mjs';
|
||||
import {POLITICAL_APPOINTMENT_SCHEMA} from '../node/political-appointments.mjs';
|
||||
async function fixture(office='emperor',extra={}){
|
||||
const f=await companyFixture(),old=f.db.query.bind(f.db);f.db.query=(sql,args=[])=>old(sql.replace(/,\s*KEY \w+\([^)]*\)/g,''),args);f.db.sqlite.function('CONCAT',{varargs:true},(...args)=>args.join(''));
|
||||
f.db.sqlite.exec('ALTER TABLE political_office_terms ADD COLUMN id TEXT;ALTER TABLE political_office_terms ADD COLUMN kind TEXT;CREATE TABLE political_office_charters(office_key TEXT PRIMARY KEY,charter_kind TEXT,staff_key_id TEXT);CREATE TABLE site_character_choices(minecraft_uuid TEXT PRIMARY KEY,faction TEXT);');
|
||||
|
|
@ -31,13 +33,13 @@ async function fixture(office='emperor',extra={}){
|
|||
}
|
||||
async function grantFixture(office='atreides'){
|
||||
const f=await fixture(office);f.db.sqlite.exec('DROP TABLE site_clan_members;DROP TABLE site_clans;');await initializeClans(f.db,{mysql:false});
|
||||
const clanId=randomUUID(),home={atreides:'kaladam',harkonnen:'giedermark',corrino:'kaiterhof'}[office];await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,'Development Clan','development clan','DEV','Our clan',?,?,1,1)",[clanId,home,f.people.Other.id]);
|
||||
const clanId=randomUUID(),home={atreides:'kaladam',harkonnen:'giedermark',corrino:'kaiterhof',muad_dib:'kaladam'}[office];await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,'Development Clan','development clan','DEV','Our clan',?,?,1,1)",[clanId,home,f.people.Other.id]);
|
||||
const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Other.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[f.people.Other.id,link.minecraft_uuid,clanId]);
|
||||
async function activate(person,kind='person',key=person.id){const entity={id:entityId(kind,key),kind,key,name:'Receiving account',canView:true,canActivate:true,canPay:true,charterKind:kind==='clan'?'original':null};await new PostbankService(f.db,async()=>({entities:[entity]})).activate(person,{entityId:entity.id,packageKey:kind==='clan'?'pb_connect':'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});return f.db.first('SELECT a.* FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number WHERE c.entity_id=?',[entity.id]);}
|
||||
const target=await activate(f.people.Other),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,clanGrants:createPoliticalClanGrants(f.db)});
|
||||
return{...f,service,clanId,target,activate,grant:(decisionId='ATR-01',amountMinor=1000000)=>({decisionId,requestId:randomUUID(),sourceAccount:String(f.source.id),clanId,amountMinor,reason:'Develop the clan’s water and transport infrastructure.',confirmed:true})};
|
||||
}
|
||||
test('catalogue prices, Reputation requirements and XP agree with connected policy',()=>{for(const d of POLITICAL_DECISIONS){const row=DECISION_CATALOGUE.find(r=>r.id===d.id);assert.equal(row.level,d.level);assert.equal(row.xp,d.xp);const [dm,hours]=row.cost.replaceAll(',','').split(' / ');if(d.kind==='clan-grant'){assert(d.grantMinMinor>=10000&&d.grantMaxMinor>=d.grantMinMinor);assert.equal(dm,d.grantMinMinor===d.grantMaxMinor?String(d.grantMaxMinor/100):'Grant amount');}else assert.equal(Number(dm)*100,d.feeMinor);assert.equal(Number(hours.replace('h',''))*3600000,d.cooldownMs);}});
|
||||
test('catalogue prices, Reputation requirements and XP agree with connected policy',()=>{for(const d of POLITICAL_DECISIONS){const row=DECISION_CATALOGUE.find(r=>r.id===d.id);assert.equal(row.level,d.level);assert.equal(row.xp,d.xp);const [dm,hours]=row.cost.replaceAll(',','').split(' / ');if(d.kind==='clan-grant'){assert(d.grantMinMinor>=10000&&d.grantMaxMinor>=d.grantMinMinor);assert.equal(dm,(d.grantMinMinor===d.grantMaxMinor?String(d.grantMaxMinor/100):'Grant amount')+(d.feeMinor?' + '+d.feeMinor/100+' admin':''));}else assert.equal(Number(dm)*100,d.feeMinor);assert.equal(Number(hours.replace('h',''))*3600000,d.cooldownMs);}});
|
||||
|
||||
test('House development grants fund the legal Basic owner through the existing balanced bank transfer once',async()=>{
|
||||
const f=await grantFixture();try{
|
||||
|
|
@ -250,3 +252,8 @@ test('diplomacy input rejects office impersonation, self approval and short mand
|
|||
test('a revoked diplomatic response never restores acceptance or reopens a decided proposal',async()=>{const f=await diplomacyFixture();try{const input=f.proposal();await f.service.execute(f.people.Owner,input);const response=f.reply(input.requestId),receipt=await f.agreements.reply(f.people.Other,response);await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.reference]);const item=(await f.agreements.read(f.people.Other)).agreements[0];assert.equal(item.state,'response-unavailable');assert.equal(item.canReply,false);await assert.rejects(f.agreements.reply(f.people.Other,f.reply(input.requestId,'decline')),/already has a response/);}finally{f.db.close();}});
|
||||
test('accepted diplomacy expires at its fixed duration and cannot be accepted by a holder acting on both sides',async()=>{const f=await diplomacyFixture();try{await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Owner.id,f.targetTerm]);await assert.rejects(f.service.execute(f.people.Owner,f.proposal()),/different current/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.db.query('UPDATE political_office_terms SET user_id=? WHERE id=?',[f.people.Other.id,f.targetTerm]);const input=f.proposal();await f.service.execute(f.people.Owner,input);await f.agreements.reply(f.people.Other,f.reply(input.requestId));f.setTime(1000+7*86400000);assert.equal((await f.agreements.read(f.people.Owner)).agreements[0].state,'expired');}finally{f.db.close();}});
|
||||
test('Baron’s Favour reuses House profile honours with seven-day expiry, fixed funding and no self or foreign House award',async()=>{const f=await fixture('harkonnen');try{await f.pol.query('UPDATE jarvis_progression_accounts SET effective_xp=50000,total_xp=50000');const link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[f.people.Other.id]);await f.db.query('INSERT INTO site_character_choices VALUES(?,?)',[link.minecraft_uuid,'harkonnen']);const input=f.input('HAR-07');await assert.rejects(f.service.execute(f.people.Owner,{...input,recipientId:f.people.Owner.id}),/another active/);const r=await f.service.execute(f.people.Owner,input);assert.equal(r.expiresAt,1000+7*86400000);assert.equal(r.xp,1200);assert.equal(r.feeMinor,'500000');assert.equal((await politicalHonours(f.db,f.people.Other.id,r.expiresAt)).length,0);}finally{f.db.close();}});
|
||||
|
||||
async function sponsorshipFixture(){const f=await grantFixture('muad_dib');for(const sql of POLITICAL_APPOINTMENT_SCHEMA)await f.db.query(sql);await initializeClanFaith(f.db);const faith=createClanFaith(f.db,f.keys,{clock:f.clock});const offer={decisionId:'NF-CONVERT',clanId:f.clanId,requestId:randomUUID(),confirmed:true};await faith.offer(f.people.Owner,offer);const response={offerId:offer.requestId,clanId:f.clanId,requestId:randomUUID(),choice:'accept',confirmed:true};await faith.reply(f.people.Other,response);return{...f,consent:response.requestId};}
|
||||
test('Church sponsorship pays the signed consenting clan and a separate Tax admin fee atomically without minting money',async()=>{const f=await sponsorshipFixture();try{const input=f.grant('NF-03',1000000),before=(await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,view=await f.service.read(f.people.Owner,'NF-03');assert.equal(view.clans[0].id,f.clanId);const r=await f.service.execute(f.people.Owner,input);assert.equal(r.feeMinor,'1250000');assert.equal(r.adminFeeMinor,'250000');assert.equal(r.grant.amountMinor,'1000000');assert.equal(r.xp,400);assert.equal((await f.service.execute(f.people.Owner,input)).keyId,r.keyId);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,750000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,1000000);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_tax_treasury'")).balance_minor,250000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,before+2);assert.equal((await f.db.first('SELECT SUM(amount_minor) n FROM pb_entries')).n,0);}finally{f.db.close();}});
|
||||
test('sponsorship rechecks current faith consent and total funding before either transfer',async()=>{for(const failure of ['consent','funds']){const f=await sponsorshipFixture();try{if(failure==='consent')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=(SELECT key_id FROM jarvis_faith_consents WHERE request_id=?)',[f.consent]);else await f.db.query('UPDATE pb_accounts SET balance_minor=1000000 WHERE id=?',[f.source.id]);await assert.rejects(f.service.execute(f.people.Owner,f.grant('NF-03',1000000)),failure==='consent'?/eligible clan/:/Insufficient funds/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}}});
|
||||
test('failed sponsorship administration rolls back the grant, fee, key and Reputation as one decision',async()=>{const f=await sponsorshipFixture();try{const tax=await f.db.first("SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'"),count=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec('CREATE TRIGGER fail_sponsorship_fee BEFORE INSERT ON pb_entries WHEN NEW.account_id='+Number(tax.id)+" AND NEW.amount_minor>0 BEGIN SELECT RAISE(ABORT,'administration failed');END");await assert.rejects(f.service.execute(f.people.Owner,f.grant('NF-03',1000000)),/administration failed/);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,2000000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.target.id])).balance_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,count);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,10000);}finally{f.db.close();}});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff