diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java index 812eaf38..e124eb7c 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/DuneGUI.java @@ -130,7 +130,7 @@ public final class DuneGUI extends JavaPlugin implements Listener,CommandExecuto private void guildRequest(Player p,JsonObject input,Consumer done){UUID id=p.getUniqueId(),world=p.getWorld().getUID();if(!boarding.add(id)){p.sendMessage("J.A.R.V.I.S. is processing your passage.");return;}Bukkit.getScheduler().runTaskAsynchronously(this,()->{JsonObject result=null;String failure=null;try{result=bridge.guild(id,input);}catch(Exception e){failure=e.getMessage();}var response=result;String message=failure;if(!isEnabled())return;Bukkit.getScheduler().runTask(this,()->{if(!boarding.remove(id)||!p.isOnline()||!p.getWorld().getUID().equals(world))return;if(response==null){p.sendMessage(message==null?"The central Guild service is unavailable.":message);return;}done.accept(response);});});} private void renderTravelMenu(Player p,JsonObject data){ String house=selection(data);var home=GuildRoutes.home(house);if(home==null){select(p,data,null);return;}if(data.getAsJsonObject("guildQuote").has("prologueRequired")&&data.getAsJsonObject("guildQuote").get("prologueRequired").getAsBoolean()){p.sendMessage("Complete the House Prologue first: meet your matching named Mentat at the Guild spawn, finish your website account and profile, and obtain your original starter kit with /start.");mentat(p,data);return;} - String quote="Guild fare: "+String.format(java.util.Locale.ROOT,"%.2f",data.getAsJsonObject("guildQuote").get("fareMinor").getAsInt()/100.0)+" DM from your central personal bank account. Collected after arrival."; + String quote="Guild fare: "+String.format(java.util.Locale.ROOT,"%.2f",data.getAsJsonObject("guildQuote").get("fareMinor").getAsInt()/100.0)+" DM from your central personal bank account. Collected after arrival."+(data.getAsJsonObject("guildQuote").has("subsidyMinor")?" Guild subsidy: "+String.format(java.util.Locale.ROOT,"%.2f",data.getAsJsonObject("guildQuote").get("subsidyMinor").getAsInt()/100.0)+" DM.":""); var booked=bookings.get(p.getUniqueId());String detail=quote+"\nTravel opens at :00, :20 and :40 for five minutes."+(booked==null?"":"\nYour passage is already booked."); if(BedrockForms.isBedrock(p)){List choices=new ArrayList<>();for(var route:GuildRoutes.ALL){boolean allowed=quotedDestinations(data.getAsJsonObject("guildQuote")).contains(route.world());choices.add(new BedrockForms.Choice((allowed?"§6":"§8")+route.name()+(allowed?(route.house().equals(house)?" · Your House":" · Imperial passage"):" · Unavailable"),allowed?detail:"Another House world",allowed?()->bookPassage(p,data,route.world()):()->travelMenu(p,data),"https://www.dunerealms.com/assets/gui/guild-world-"+route.world().replace('_','-')+(allowed?"":"-locked")+"-v1.png"));}choices.add(new BedrockForms.Choice("Cancel booking","No fare has been charged",()->{cancelBooking(p);travelMenu(p,data);}));choices.add(new BedrockForms.Choice("Your Mentat","Return to your House adviser",()->mentat(p,data)));BedrockForms.show(this,p,"Spacing Guild · Imperial passage",detail,choices);return;} int own=Arrays.asList(IDS).indexOf(house);Screen screen=screen(p,"Spacing Guild · Imperial passage",0xE330+own); diff --git a/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs b/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs index d8a3336a..85a70119 100644 --- a/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-decision-audit.mjs @@ -13,7 +13,7 @@ const related={ const authority={IMP:'Current Emperor deed',ATR:'Current Aerdrecht House office deed',HAR:'Current Harkveen House office deed',COR:'Current Korenholt House office deed',ORD:'Current Oordwijk House office deed',FRE:'Current recognised sietch deed; independent Council',BG:'Current Veiled Concord office deed',NF:'Current Church of Muad’Dib office deed',SG:'Current Spacing Guild office deed',CLD:'Current clan delegate deed'}; function paidDecisionGap(id){ const kind=politicalDecision(id)?.kind,base='Current office, Reputation, authorised office funding and successor-safe cooldown checked atomically. '; - return base+(kind==='organisation-passage'?'The signed charter is consumed at Guild quote, boarding and arrival for current direct organisation members.72h maximum, clipped to the original Imperial mandate. Revocation, expiry or leaving removes permission; normal fares and embargoes remain in force.':kind==='ballot'&&politicalDecision(id).pax?'Paid signed House ballot and independent Council offer close after24h. Both must adopt; consenting parties are restricted from new overlapping Arrakis war blocks for72h, without canceling prior agreements.':kind==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'&&politicalDecision(id).agreementMode==='steward'?'A linked citizen must explicitly accept the Imperial nomination within48h. The single administrative appointment replaces its predecessor and ends with the issuing mandate; no authority or board membership is granted.':kind==='agreement'&&politicalDecision(id).agreementMode==='representation'?'The receiving Royal holder signs within72h. Acceptance and an actual observer appointment commit together, clipped to14d and both source terms. Projection rejects revoked source/response proofs or either ended mandate. No leadership or bank authority moves.':kind==='agreement'&&politicalDecision(id).agreementMode==='petition'?'A confidential petition requires a signed response from its original receiving Royal holder within72h. Acknowledgement is historical receipt only; hearings, votes and concession changes require separate authorised actions. No bank, vote, ownership or war rights change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder or legal company owner. Acceptance or refusal requires that same current mandate or company ownership, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'&&politicalDecision(id).reportType==='political'?'The exact existing public Government or citizen Voting Directory projection supplies a sealed factual snapshot. No private boards, mail, ballots or balances are queried. Fee, Reputation, snapshot and source-mandate expiry commit together. Only the original current holder may read it; permitted publication is explicit, generated from office facts, signed once and gives no extra reward.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.'); + return base+(kind==='organisation-passage'?'The signed charter is consumed at Guild quote, boarding and arrival for current direct organisation members.72h maximum, clipped to the original Imperial mandate. Revocation, expiry or leaving removes permission; normal fares and embargoes remain in force.':kind==='ballot'&&politicalDecision(id).pax?'Paid signed House ballot and independent Council offer close after24h. Both must adopt; consenting parties are restricted from new overlapping Arrakis war blocks for72h, without canceling prior agreements.':kind==='ballot'?'Paid consultation records a frozen institutional electorate. Current independent clan owners or original Royal Great House mandates cast one signed vote per seat; no personal election allocation is consumed. Shared quorum and strict-majority tally closes once; ties and low participation fail. This is a nonbinding resolution, with no automatic law or war change.':kind==='agreement'&&politicalDecision(id).agreementMode==='steward'?'A linked citizen must explicitly accept the Imperial nomination within48h. The single administrative appointment replaces its predecessor and ends with the issuing mandate; no authority or board membership is granted.':kind==='agreement'&&politicalDecision(id).agreementMode==='representation'?'The receiving Royal holder signs within72h. Acceptance and an actual observer appointment commit together, clipped to14d and both source terms. Projection rejects revoked source/response proofs or either ended mandate. No leadership or bank authority moves.':kind==='agreement'&&politicalDecision(id).agreementMode==='petition'?'A confidential petition requires a signed response from its original receiving Royal holder within72h. Acknowledgement is historical receipt only; hearings, votes and concession changes require separate authorised actions. No bank, vote, ownership or war rights change.':kind==='agreement'?'A confidential proposal is delivered only to its original receiving office holder or legal company owner. Acceptance or refusal requires that same current mandate or company ownership, a signed response and the 72-hour window. Accepted terms expire with either mandate; no votes, ownership or war rights move.':kind==='clan-grant'?'The current native clan deed selects its own active bank account or its legal Basic owner. The balanced transfer, recorded purpose and proportional Reputation commit together; retries cannot pay twice.':kind==='report'&&politicalDecision(id).reportType==='political'?'The exact existing public Government or citizen Voting Directory projection supplies a sealed factual snapshot. No private boards, mail, ballots or balances are queried. Fee, Reputation, snapshot and source-mandate expiry commit together. Only the original current holder may read it; permitted publication is explicit, generated from office facts, signed once and gives no extra reward.':kind==='report'?'Verified aggregate snapshot, fee and reward share one receipt; no private identities or balances are disclosed.':kind==='event'?'The existing political calendar and event history commit with the fee and reward; a diplomatic meeting does not manufacture participant consent.':kind==='guild-subsidy'?'Reserve 100–20,000 DM for up to seven days. Signed current office policy is checked on ordinary Guild quotes. Only actual confirmed arrivals settle the 20% subsidy; existing preferential fares are not stacked, pending journeys remain reserved, and unused funds are released. Reputation scales to the reserved pool.':['tariff','guild-discount'].includes(kind)?'The latest signed current-mandate policy controls new Guild quote and boarding fares. Confirmed tickets retain their amount; no travel or embargo rights change.':'Existing publication/profile consumers display the result.'); } export const DECISION_AUDIT=Object.freeze(DECISION_CATALOGUE.map(d=>Object.freeze({id:d.id,office:d.office,status:naibDecision(d.id)||houseFaithDecision(d.id)||clanFaithDecision(d.id)||tradeDecision(d.id)||politicalDecision(d.id)||d.id==='IMP-10'||faithBlessing(d.id)?'active':'design',currency:'DM',amountConversion:1,authority:authority[d.office],conditions:'Current unexpired and unrevoked deed, eligible target and all stated effect conditions must be checked by the domain consumer. Level and XP do not grant office authority.',costCooldown:d.cost,effect:d.effect,level:d.level,proposedXP:d.xp,adapter:naibDecision(d.id)?.claimOnly?'createPaxRejections / signed Council vote':naibDecision(d.id)?.petitionOnly?'createNaibPetitions / createNaibCouncilFunding / createPoliticalAgreements':naibDecision(d.id)?'createNaibCouncil / createNaibCouncilFunding':houseFaithDecision(d.id)?'createHouseFaithLaws / missionaryFaithOutlawed':clanFaithDecision(d.id)?'createClanFaith.offer / reply':tradeDecision(d.id)?'createWorldTradeGovernance / createGameExchangeService / createGuildService':politicalDecision(d.id)?'createPoliticalDecisions':faithBlessing(d.id)?'createFaithBlessings / faithAward':d.id==='IMP-10'?'createImperialPassage / createGuildService':related[d.id]?.adapter||null,gap:naibDecision(d.id)?.claimOnly?'Current independent Naib, Rep50, actual paid Pax Council dossier rejected and this seat personally voted reject. Free, once per declaration, 1200 Reputation.':naibDecision(d.id)?.petitionOnly?'Current independent sietch owner,Rep15,1000DM from the same legal sietch funding route,250 Reputation and48h successor-safe cooldown. Private petition, not a Council ballot. Only the original Royal Emperor can sign its acknowledgement or refusal within72h; no gameplay authority is granted.':naibDecision(d.id)?'Current independent sietch deed, Reputation'+naibDecision(d.id).level+','+naibDecision(d.id).feeMinor/100+'DM from its active account or the legal Basic owner,'+naibDecision(d.id).xp+' Reputation and'+naibDecision(d.id).cooldownMs/3600000+'h seat cooldown. Fee, signed key, proposal electorate and reward commit together. No free production fallback; one Council vote per current sietch. Personal election votes are unchanged.':houseFaithDecision(d.id)?'Royal House authority and Reputation checked before a sealed 48-hour personal referendum. Seven-day office cooldown survives succession; quorum and strict majority required. Only future invitations and clan-owner acceptance are gated by the latest live law; existing allegiance and earned rewards remain unchanged.':clanFaithDecision(d.id)?'Current faith officer can invite; only the receiving clan’s legal owner can consent. Daily invitation and seven-day clan-change cooldowns are enforced; no membership or rights move.':tradeDecision(d.id)?'Current Royal office and Reputation, immutable creation-world metadata, seven-day cooldown, retained stock and atomic seller-funded bank levy; no default activation.':politicalDecision(d.id)?paidDecisionGap(d.id):faithBlessing(d.id)?'Current faith leader/officer deed, owner-approved clan allegiance, appointment expiry and cooldown are checked centrally. Old Faith and New Faith use the same capped bonus consumer; historical queued rewards retain their claim-time consent proof.':d.id==='IMP-10'?'Native House selection replaces the prior grant; seven-day office cooldown and current Emperor deed are checked centrally.':related[d.id]?.gap||'No complete registered domain consumer implements this exact target, price, cooldown, duration and effect. Execution remains unavailable.',repeatability:'Only after the stated cooldown; no implied stacking or automatic renewal.',executionEnabled:!!naibDecision(d.id)||!!houseFaithDecision(d.id)||!!clanFaithDecision(d.id)||!!tradeDecision(d.id)||!!politicalDecision(d.id)||d.id==='IMP-10'||!!faithBlessing(d.id)}))); export const decisionAudit=id=>DECISION_AUDIT.find(row=>row.id===id)||null; diff --git a/website/control-panel/public/cp-v2/cp-v2-political-decisions.mjs b/website/control-panel/public/cp-v2/cp-v2-political-decisions.mjs index aa8bc5b1..e675e7b1 100644 --- a/website/control-panel/public/cp-v2/cp-v2-political-decisions.mjs +++ b/website/control-panel/public/cp-v2/cp-v2-political-decisions.mjs @@ -16,6 +16,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==='guild-subsidy'){grantAmount=field('Travel subsidy pool (DM)','input');grantAmount.type='number';grantAmount.step='0.01';grantAmount.min=String(d.poolMinMinor/100);grantAmount.max=String(d.poolMaxMinor/100);grantAmount.value=String(d.poolMaxMinor/100);form.append(el('p','Reserve funds for up to 20% off new ordinary Guild passages. Existing preferred fares do not stack, only a verified arrival spends the subsidy, and unused reserves are released.'));} 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); @@ -41,20 +42,22 @@ 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==='guild-subsidy')status.textContent=(data.canManage?'Current Guild office verified. ':'Current Guild office required. ')+(d.poolMinMinor/100).toFixed(2)+'–'+(d.poolMaxMinor/100).toFixed(2)+' DM reserved pool; up to '+d.xp+' proportional Reputation. Reputation '+data.levelNow+'/'+d.level+' required.'+(data.subsidyPool?' Previous/current pool: '+(Number(data.subsidyPool.spentMinor)/100).toFixed(2)+' DM spent, '+(Number(data.subsidyPool.pendingMinor)/100).toFixed(2)+' DM pending; '+data.subsidyPool.state+' until '+new Date(data.subsidyPool.endsAt).toLocaleString()+'.':''); 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.reportType==='political'?(d.reviewKind==='candidate'?{candidateId:reviewTarget.value}:{targetOffice:reviewTarget.value}):d.kind==='organisation-passage'?{targetKind:organisationSelect.value.split(':')[0],targetId:organisationSelect.value.split(':')[1]}:d.kind==='ballot'?{title:title.value,terms:body.value}:d.kind==='agreement'?{...(d.targetKind==='company'?{targetCompanyId:officeSelect.value}:d.targetKind==='person'?{targetPersonId:officeSelect.value}:{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}; + const payload=d.reportType==='political'?(d.reviewKind==='candidate'?{candidateId:reviewTarget.value}:{targetOffice:reviewTarget.value}):d.kind==='organisation-passage'?{targetKind:organisationSelect.value.split(':')[0],targetId:organisationSelect.value.split(':')[1]}:d.kind==='ballot'?{title:title.value,terms:body.value}:d.kind==='agreement'?{...(d.targetKind==='company'?{targetCompanyId:officeSelect.value}:d.targetKind==='person'?{targetPersonId:officeSelect.value}:{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==='guild-subsidy'?{amountMinor:Math.round(Number(grantAmount.value)*100)}: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.reportType==='political'&&!reviewTarget.value){status.textContent='Choose a current public record to review.';return;} if(d.kind==='organisation-passage'&&!organisationSelect.value){status.textContent='Choose an active receiving organisation.';return;} if(d.kind==='ballot'&&(title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Complete the resolution title and terms.';return;} if(d.kind==='agreement'&&(!officeSelect.value||title.value.trim().length<3||body.value.trim().length<20)){status.textContent='Choose a recipient and complete the proposal title and terms.';return;} + if(d.kind==='guild-subsidy'&&(!grantAmount.reportValidity()||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinord.poolMaxMinor)){status.textContent='Choose a subsidy pool within the published amount.';return;} if(d.kind==='clan-grant'&&(!clanSelect.value||!grantAmount.reportValidity()||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinord.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.startsAtString(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+(reviewTarget?' for '+reviewTarget.selectedOptions[0].textContent:organisationSelect?' for '+organisationSelect.selectedOptions[0].textContent: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();}}; + 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.subsidy?'Reserved '+(Number(receipt.subsidy.amountMinor)/100).toFixed(2)+' DM for Guild travel. ':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(); } diff --git a/website/control-panel/public/political-decision-policy.mjs b/website/control-panel/public/political-decision-policy.mjs index 7eca12dc..ef7f04f7 100644 --- a/website/control-panel/public/political-decision-policy.mjs +++ b/website/control-panel/public/political-decision-policy.mjs @@ -1,5 +1,6 @@ import {polDecisionDialogue} from './cp-v2/cp-v2-pol-dialogue.mjs'; // Fixed catalogue prices are DM minor units. Browser fields cannot override policy. +export const GUILD_SUBSIDY_POLICY=Object.freeze({minMinor:10000,maxMinor:2000000,percent:20}); export const POLITICAL_DECISIONS=Object.freeze([ ...[ ['HAR-05','harkonnen','Intelligence Network',35,600,750000,72,48,'office',false], @@ -41,6 +42,7 @@ export const POLITICAL_DECISIONS=Object.freeze([ {id:'COR-03',office:'corrino',house:'corrino',title:'Noble Recognition',kind:'honour',level:20,xp:300,feeMinor:250000,cooldownMs:72*3600000}, {id:'COR-01',office:'corrino',title:'Imperial Court Audience',kind:'event',level:10,xp:200,feeMinor:100000,cooldownMs:24*3600000}, {id:'ORD-03',office:'ordos',title:'Market Intelligence',kind:'report',level:25,xp:400,feeMinor:250000,cooldownMs:72*3600000}, + {id:'SG-03',office:'spacing_guild',title:'Guild Subsidy',kind:'guild-subsidy',level:20,xp:300,feeMinor:0,poolMinMinor:GUILD_SUBSIDY_POLICY.minMinor,poolMaxMinor:GUILD_SUBSIDY_POLICY.maxMinor,discountPercent:GUILD_SUBSIDY_POLICY.percent,cooldownMs:7*86400000,durationMs:7*86400000}, {id:'SG-04',office:'spacing_guild',title:'Commercial Intelligence',kind:'report',level:30,xp:500,feeMinor:250000,cooldownMs:72*3600000}, {id:'NF-07',office:'muad_dib',title:'Church’s Favour',kind:'honour',level:15,xp:250,feeMinor:250000,cooldownMs:72*3600000,durationMs:7*86400000}, {id:'HAR-07',office:'harkonnen',house:'harkonnen',title:'Baron’s Favour',kind:'honour',level:50,xp:1200,feeMinor:500000,cooldownMs:7*86400000,durationMs:7*86400000}, @@ -60,4 +62,4 @@ export const POLITICAL_DECISIONS=Object.freeze([ ].map(d=>Object.freeze({...d,dialogue:polDecisionDialogue(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',clan_delegate:'CLD'})[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==='organisation-passage'?'Grant current members of one active clan or company sanctioned Arrakis passage for at most72 hours and no longer than the issuing Imperial mandate. Normal fares, boarding windows and Guild embargoes still apply; no membership or military rights change.':d.kind==='ballot'?d.pax?'Open a 24-hour House ballot and independent Council of Naibs offer. Both must adopt the proposal; accepting parties then observe a 72-hour Arrakis peace in new War Exchange calendar agreements. Nonconsenting clans and existing agreed campaigns are not overwritten.':'Open a '+d.ballotMs/3600000+'-hour nonbinding resolution vote. '+(d.electorate==='houses'?'One seat for each currently occupied Royal Great House office. Its original mandate must still be current to vote.':'One seat for each current native Caladan clan, exercised by its legal owner; mother control does not confer a seat.')+' Frozen electorate; more-than-half participation and strict majority required. Ties fail. Personal election votes are untouched.':d.kind==='agreement'?d.agreementMode==='steward'?'Nominate one linked citizen for the Imperial administrative Steward role. The candidate must consent within 48 hours. Acceptance replaces the previous Steward for the remainder of the Emperor’s mandate; it grants no Council of Naibs, office, vote, bank, ownership or military authority.':d.agreementMode==='representation'?'Petition another current Royal office holder for advisory representation. Within72h that holder can consent to an observer appointment lasting at most14 days, clipped to both mandates. It ends if either original mandate or signed proof ceases. No leadership, bank, vote, military or ownership authority is granted.':d.agreementMode==='petition'?'Send a confidential petition to another current Royal office holder for a signed response within 72 hours. Acknowledgement records receipt only; any hearing, vote, grant, concession change or war still needs its own authorised action. An answered petition remains a historical record.':(d.targetKind==='company'?'Send a confidential proposal to an active company. Its current legal owner must consent within 72 hours.':'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 '+(d.targetKind==='company'?'the issuing mandate or a change of company ownership':'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'&&d.reportType==='political'?'Authorise a confidential '+d.durationMs/3600000+'-hour review of '+(d.reviewKind==='candidate'?'a current candidate using the existing citizen Voting Directory':'one office using the public Government Register')+'. It is a factual snapshot, not access to private mail, boards, ballots or bank data.'+(d.canExpose?' The original holder may explicitly publish its verified office facts once through the existing proclamation archive; no accusation can be invented.':''):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',clan_delegate:'CLD'})[d.office],cost:(d.kind==='guild-subsidy'?'Pool amount':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==='organisation-passage'?'Grant current members of one active clan or company sanctioned Arrakis passage for at most72 hours and no longer than the issuing Imperial mandate. Normal fares, boarding windows and Guild embargoes still apply; no membership or military rights change.':d.kind==='ballot'?d.pax?'Open a 24-hour House ballot and independent Council of Naibs offer. Both must adopt the proposal; accepting parties then observe a 72-hour Arrakis peace in new War Exchange calendar agreements. Nonconsenting clans and existing agreed campaigns are not overwritten.':'Open a '+d.ballotMs/3600000+'-hour nonbinding resolution vote. '+(d.electorate==='houses'?'One seat for each currently occupied Royal Great House office. Its original mandate must still be current to vote.':'One seat for each current native Caladan clan, exercised by its legal owner; mother control does not confer a seat.')+' Frozen electorate; more-than-half participation and strict majority required. Ties fail. Personal election votes are untouched.':d.kind==='agreement'?d.agreementMode==='steward'?'Nominate one linked citizen for the Imperial administrative Steward role. The candidate must consent within 48 hours. Acceptance replaces the previous Steward for the remainder of the Emperor’s mandate; it grants no Council of Naibs, office, vote, bank, ownership or military authority.':d.agreementMode==='representation'?'Petition another current Royal office holder for advisory representation. Within72h that holder can consent to an observer appointment lasting at most14 days, clipped to both mandates. It ends if either original mandate or signed proof ceases. No leadership, bank, vote, military or ownership authority is granted.':d.agreementMode==='petition'?'Send a confidential petition to another current Royal office holder for a signed response within 72 hours. Acknowledgement records receipt only; any hearing, vote, grant, concession change or war still needs its own authorised action. An answered petition remains a historical record.':(d.targetKind==='company'?'Send a confidential proposal to an active company. Its current legal owner must consent within 72 hours.':'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 '+(d.targetKind==='company'?'the issuing mandate or a change of company ownership':'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-subsidy'?'Reserve up to 20,000 DM from the Guild account for up to seven days. New ordinary passages receive up to 20% off, without stacking with preferred fares. Only actual arrival settles the subsidy; unused funds are released. No smuggling, embargo, permission or boarding-rule change.':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'&&d.reportType==='political'?'Authorise a confidential '+d.durationMs/3600000+'-hour review of '+(d.reviewKind==='candidate'?'a current candidate using the existing citizen Voting Directory':'one office using the public Government Register')+'. It is a factual snapshot, not access to private mail, boards, ballots or bank data.'+(d.canExpose?' The original holder may explicitly publish its verified office facts once through the existing proclamation archive; no accusation can be invented.':''):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.'}))); diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index fef5720f..1d4312f6 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -5,6 +5,7 @@ import {ensureFaithQuestPolicy,ensureFaunaQuestPolicy,ensureBountyQuestPolicy,en import {initializeClanFaith,createClanFaithAPI,createClanFaith} from '../node/clan-faith.mjs'; import {initializeHouseFaith,createHouseFaithAPI,createHouseFaithLaws,missionaryFaithOutlawed} from '../node/house-faith-laws.mjs'; import {createPoliticalMarketReports} from '../node/political-market-reports.mjs'; +import {createGuildSubsidies,verifyGuildSubsidy} from '../node/guild-subsidy.mjs'; import {paxBlocksWar} from '../node/imperial-pax.mjs'; import {POLITICAL_CONSULTATION_SCHEMA,createPoliticalConsultations,createPoliticalConsultationAPI} from '../node/political-consultations.mjs'; import {POLITICAL_AGREEMENT_SCHEMA,POLITICAL_COMPANY_REPLY_SCHEMA,POLITICAL_PERSON_REPLY_SCHEMA,createPoliticalAgreements,createPoliticalAgreementAPI} from '../node/political-agreements.mjs'; @@ -23,7 +24,7 @@ import {createKitsetCommerce} from '../node/kitset-commerce.mjs'; import {createKitsetPurchaseAPI} from './kitset-purchase-api.mjs'; import {createGameExchangeAPI} from '../node/game-exchange.mjs'; import {createGameKitGrantsAPI} from '../node/game-kit-grants.mjs'; -import {createGameGuildAPI} from '../node/game-guild.mjs'; +import {createGameGuildAPI,createGuildService} from '../node/game-guild.mjs'; import {createImperialPassageAPI,createImperialPassage,IMPERIAL_PASSAGE_SCHEMA} from '../node/imperial-passage.mjs'; import {createFaithBlessingAPI,createFaithBlessings,FAITH_BLESSING_SCHEMA} from '../node/faith-blessings.mjs'; import {createGameHomeAPI} from '../node/game-home.mjs'; @@ -604,9 +605,9 @@ export async function startPanel(settings=process.env){ inventoryPool.on('error',()=>console.error('Inventory database connection unavailable.')); } const bankDatabase=await openPostbankDatabase(settings); - const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);await db.query(POLITICAL_COMPANY_REPLY_SCHEMA);await db.query(POLITICAL_PERSON_REPLY_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeElectionRallies(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;db.paxEnabled=true;await initializeProgression(db);db.questAchievementsEnabled=true;await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureProgressionPolicy(db,organisationKeys,{policy:{...XP_POLICY,version:2},definitions:QUEST_DEFINITIONS.filter(d=>HOUSE_PROLOGUE_IDS.includes(d.id))});await initializeHousePrologue(db);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);await db.query(POL_DOSSIER_SCHEMA);await db.query(POL_CARGO_SCHEMA);await db.query(POL_COOP_CARGO_SCHEMA);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensureFaunaQuestPolicy(db,organisationKeys);db.faunaQuestsEnabled=true;db.smugglerContractsEnabled=true;db.polSupplyEnabled=true;db.polContractMissionsEnabled=true;await ensureBountyQuestPolicy(db,organisationKeys);db.bountyQuestsEnabled=true;await ensureSpiceUpgradeQuestPolicy(db,organisationKeys);db.spiceUpgradeEnabled=true;await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; + const db=await openDatabase(settings);await initializeItemDesigns(db);await initializeKitsets(db);await initializeResearchSpecialists(db);await db.query(POLITICAL_DECISION_SCHEMA);await db.query(POLITICAL_REVIEW_PUBLICATION_SCHEMA);await initializeWorldTrade(db);await initializeClanFaith(db);await initializeHouseFaith(db);await db.query(POLITICAL_AGREEMENT_SCHEMA);await db.query(POLITICAL_COMPANY_REPLY_SCHEMA);await db.query(POLITICAL_PERSON_REPLY_SCHEMA);for(const sql of POLITICAL_CONSULTATION_SCHEMA)await db.query(sql);db.worldTradeEnabled=settings.WORLD_TRADE_ENABLED==='true';db.politicalDecisionsEnabled=true;await db.query(FAITH_BLESSING_SCHEMA);db.faithBlessingsEnabled=true;await db.query(IMPERIAL_PASSAGE_SCHEMA);await db.query(HOUSE_SELECTION_SCHEMA);await db.query(GAME_ORGANISATION_SCHEMA);await db.query(ECONOMIC_SNAPSHOT_SCHEMA);await initializeCodexEquipment(db);await initializeFirstLogin(db);await db.prepare(accountSchema).run();await initializeProclamations(db);await initializeCharters(db);await initializeApplications(db);await initializeRounds(db);await initializeElectionRallies(db);await initializeBallots(db);await initializeOfficeLedger(db);await initializeContactEmails(db);await initializeBanEvidence(db);await initializeClans(db);await db.prepare(CHARACTER_PREFERENCE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await db.prepare(CHARACTER_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4').run();await applyRoyalClanRollout(db);const organisationKeys=await openOrganisationKeyService(db,settings);await ensurePoliticalOfficeCharters(db,organisationKeys);const keyGrants=await grantCurrentAccountKeys(db,organisationKeys);console.log('Original founding key grants reconciled',JSON.stringify(keyGrants));await resetOwnerTestClaims(db,bankDatabase);await initializeClanShop(db);await initializeMailIdentities(db);await initializeGitIdentities(db);await initializeRanks(db);await initializeHonours(db);await initializeStaffBureau(db);await initializeOrganisation(db);await initializeLifeStatus(db);await initializeBadges(db);await initializeSealEntitlements(db);await initializeSealCatalog(db);await initializeCompanyRegistry(db);await initializeCompanyDeeds(db);await initializePassiveOrders(db);await initializeJarvisGenerator(db);await initializeEntityState(db);await initializeSystemCharacters(db);await applyUnicorpRoyalMailbox(db,organisationKeys,{apply:true}).catch(error=>console.error('Unicorp Royal mailbox rollout pending:',error.message));await initializeShareLedger(db);await initializeNews(db);await initializeCommunityAccess(db);await initializeQuestAccess(db);await initializeBankAccess(db);await initializeGameRanks(db);await db.query(NETWORK_LAYOUT_SCHEMA);db.networkLayoutsEnabled=true;await ensureJarvisIdentity(db);await db.query(VALIDATION_CASE_SCHEMA);await reconcileCrysknifeCompany(db,organisationKeys); /* Passive POL conversion waits for scoped adapters instead of company management. */await provisionRihlaAccounts(db,bankDatabase);await initializeOfficeAuctionRuntime(db,bankDatabase);for(const sql of [...POLITICAL_JOB_SCHEMA,...NAIB_COUNCIL_SCHEMA])await db.query(sql);db.naibCouncilEnabled=true;db.paxEnabled=true;db.guildSubsidyEnabled=true;await initializeProgression(db);db.questAchievementsEnabled=true;await initializeStarterKitEvents(db);db.starterKitEventsEnabled=true;await initializeServerProjects(db);if(bankDatabase)await bankDatabase.query(PROJECT_BANK_SCHEMA);await db.query(GAZETTE_SCHEMA);await ensureProgressionPolicy(db,organisationKeys);await ensureProgressionPolicy(db,organisationKeys,{policy:{...XP_POLICY,version:2},definitions:QUEST_DEFINITIONS.filter(d=>HOUSE_PROLOGUE_IDS.includes(d.id))});await initializeHousePrologue(db);await ensureStarterKitRewardPolicy(db,organisationKeys).catch(()=>console.error('Starter kit reward policy requires review; existing custom configuration was preserved'));await initializePOLProgression(db);await initializeSecondaryAffiliations(db);await initializePersonalActivityEvents(db);db.personalActivityEventsEnabled=true;await initializePOLActivityEvents(db);await db.query(POL_DOSSIER_SCHEMA);await db.query(POL_CARGO_SCHEMA);await db.query(POL_COOP_CARGO_SCHEMA);db.polActivityEventsEnabled=true;await initializeRebellionRewards(db);await ensurePOLProgressionPolicy(db,organisationKeys);await ensurePOLRepeatablePolicy(db,organisationKeys);await ensureElytraQuestPolicy(db,organisationKeys);await ensureWarQuestPolicy(db,organisationKeys);await ensureFaithQuestPolicy(db,organisationKeys);await ensureFaunaQuestPolicy(db,organisationKeys);db.faunaQuestsEnabled=true;db.smugglerContractsEnabled=true;db.polSupplyEnabled=true;db.polContractMissionsEnabled=true;await ensureBountyQuestPolicy(db,organisationKeys);db.bountyQuestsEnabled=true;await ensureSpiceUpgradeQuestPolicy(db,organisationKeys);db.spiceUpgradeEnabled=true;await ensurePOLMentorPolicy(db,organisationKeys);db.polMentorBonusEnabled=true;db.polRepeatablesEnabled=true;db.organisationResearchEnabled=true;db.researchSuppliesEnabled=true;const progressionRuntime=createProgressionRuntime(db,bankDatabase,organisationKeys);const officeAuctionRuntime=createOfficeAuctionRuntime(db,bankDatabase);const promotionDelivery=bankDatabase?await configurePromotionDelivery(db,bankDatabase,settings):null;const deedPurchases=bankDatabase&&settings.POSTBANK_ENABLED==='true'?createDeedPurchases(db,bankDatabase,organisationKeys,{authority:createPostbankAuthority(db,{bank:bankDatabase})}):null;const starterKitDelivery=await openStarterKitDelivery(db,settings);const boardRuntime=await openBoardKeyRuntime(db,organisationKeys,settings);const handle=createPanel(db,settings,{boardRuntime,inventoryPool,bankDatabase,organisationKeys,deedPurchases,officeAuctionRuntime,promotionDelivery,progressionRuntime}),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com'; await initializeInternalMailAccess(db);await reconcileHistoricalQuestAchievements(db).catch(error=>console.error('Historical quest achievements pending:',error.message));const stopElectionClock=startElectionClock(db);const stopOfficeLedger=startOfficeLedger(db); - const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'political_consultations',slot:now=>Math.floor(now/60000)*60000,run:()=>createPoliticalConsultations(db,organisationKeys).reconcile()},{key:'house_faith_ballots',slot:now=>Math.floor(now/60000)*60000,run:()=>createHouseFaithLaws(db,organisationKeys).reconcile()},{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'organisation_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createOrganisationFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); + const stopBanSync=startModerationSync(db,settings),stopInternalMail=startInternalMailSync(db,{jarvisStore:bankDatabase}),stopCentralScheduler=startCentralScheduler(db,bankDatabase,settings,{extraTasks:[...(settings.MILITARY_PROJECTION_ENABLED==='true'&&organisationKeys?[{key:'military_affiliations',slot:now=>Math.floor(now/60000)*60000,run:()=>createMilitaryAffiliations(db,organisationKeys).drain()}]:[]),{key:'political_consultations',slot:now=>Math.floor(now/60000)*60000,run:()=>createPoliticalConsultations(db,organisationKeys).reconcile()},{key:'house_faith_ballots',slot:now=>Math.floor(now/60000)*60000,run:()=>createHouseFaithLaws(db,organisationKeys).reconcile()},{key:'starter_kit_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>starterKitDelivery.drain()},...(boardRuntime?[{key:'board_keys',slot:now=>Math.floor(now/60000)*60000,run:()=>boardRuntime.drain()}]:[]),...(bankDatabase?[{key:'guild_subsidies',slot:now=>Math.floor(now/60000)*60000,run:()=>createGuildService(bankDatabase,{subsidies:createGuildSubsidies(bankDatabase,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)})}).expire()},{key:'federal_reserve',slot:now=>Math.floor(now/60000)*60000,run:()=>createEconomyRuntime(db,bankDatabase,organisationKeys).federal.run()},{key:'organisation_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createOrganisationFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'research_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createResearchFundedRewards(db,bankDatabase).drain()},{key:'pol_funded_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createPOLFundedRewards(db,bankDatabase,organisationKeys).drain()},{key:'rebellion_rewards',slot:now=>Math.floor(now/60000)*60000,run:()=>createRebellionRewards(db,bankDatabase,{sourceAccount:settings.REBELLION_REWARD_SOURCE_ACCOUNT,sourceOwnerId:settings.REBELLION_REWARD_SOURCE_OWNER_ID,useWebsiteTreasury:settings.REBELLION_REWARD_FUND==='website-treasury'}).drain()},...(deedPurchases?[{key:'deed_purchases',slot:now=>Math.floor(now/60000)*60000,run:()=>deedPurchases.drain()}]:[]),{key:'server_projects',slot:now=>Math.floor(now/60000)*60000,run:()=>createServerProjectRuntime(db,bankDatabase,organisationKeys).drain()},{key:'progression_completion',slot:now=>Math.floor(now/60000)*60000,run:async()=>{const completed=await progressionRuntime.quests.processCompletions();const news=await progressionRuntime.announcements.drain();return {completed,news};}},{key:'naib_council',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await reconcileNaibChairs(db);return createNaibCouncil(db).reconcile();}},{key:'jarvis_promotions',slot:now=>Math.floor(now/15000)*15000,run:()=>promotionDelivery.drain()},{key:'political_jobs',slot:now=>Math.floor(now/60000)*60000,run:async()=>{await createPoliticalJobs(db,bankDatabase).reconcile();return drainPoliticalJobNotifications(db,{broker:internalMailBroker,eligible:internalMailEligible});}},{key:'order_membership',slot:now=>Math.floor(now/60000)*60000,run:()=>reconcileCrysknifeCompany(db,organisationKeys)},{key:'office_auctions',slot:now=>Math.floor(now/60000)*60000,run:()=>officeAuctionRuntime.process()},{key:'jarvis_settlement',slot:now=>standardCycle(now).cutoff,async run(cutoff){const payments=createJarvisPayments(bankDatabase,createPostbankAuthority(db,{bank:bankDatabase}));for(let i=0;i<40;i++){const result=await payments.settle(cutoff);if(result.failed)return result;if(result.attempted<100)return result;}return {failed:1};}}]:[])]}); const security={'X-Robots-Tag':'noindex, nofollow, noarchive','X-Content-Type-Options':'nosniff','Referrer-Policy':'no-referrer','Cache-Control':'no-store','Content-Security-Policy':PANEL_SERVICE_CSP}; const server=createServer(async(req,res)=>{try{ req.setTimeout(req.url==='/api/internal-mail/messages/send'?120000:30000);const bodyLimit=panelBodyLimit(req.method,req.url);let length=0;const chunks=[];for await(const chunk of req){length+=chunk.length;if(length>bodyLimit){res.writeHead(413,{...security,'Content-Type':'application/json'});res.end(JSON.stringify({message:'The upload exceeds the permitted request size.'}));return;}chunks.push(chunk);} diff --git a/website/node/game-guild.mjs b/website/node/game-guild.mjs index 624eecd0..94d6cc81 100644 --- a/website/node/game-guild.mjs +++ b/website/node/game-guild.mjs @@ -1,5 +1,6 @@ import {createBankTradePolicy} from './world-trade-governance.mjs'; import {tradeWorld} from '../control-panel/public/world-trade-policy.mjs'; +import {createGuildSubsidies,verifyGuildSubsidy} from './guild-subsidy.mjs'; import {currentGuildSurcharge,currentGuildDiscount} from './guild-tariff-policy.mjs'; import {createHash} from 'node:crypto'; import {gameAuthorized,validUuid,json} from './game-link.mjs'; @@ -21,24 +22,24 @@ export const SMUGGLER_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_smuggler_pas const routes={atreides:'caladan',harkonnen:'giedi_prime',corrino:'kaitain',ordos:'sigma_draconis_iv',fremen:'arrakis'}; const accountSQL=`SELECT a.*,c.entity_id,e.external_key,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id`; const fail=(message,status=409)=>{throw new BankError(message,status);}; -export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true}={}){ +export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null}={}){ if(!Number.isSafeInteger(fareMinor)||fareMinor<1||fareMinor>100000000||!Number.isSafeInteger(smugglerFareMinor)||smugglerFareMinor<1||smugglerFareMinor>100000000)throw Error('Invalid Guild fare'); const payments=new PostbankPayments(bank,authority,{clock}); - async function quotedFare(user){const percent=await surcharge(clock()),reduction=await discount(user.faction,clock());if(!Number.isInteger(percent)||percent<0||percent>5||!Number.isInteger(reduction)||reduction<0||reduction>25)fail('The Guild tariff requires review.',503);return Math.min(100000000,Math.max(1,Math.ceil(fareMinor*(100+percent)*(100-reduction)/10000)));} + async function quotedFare(user,store=bank,lock=false){const percent=await surcharge(clock()),reduction=await discount(user.faction,clock());if(!Number.isInteger(percent)||percent<0||percent>5||!Number.isInteger(reduction)||reduction<0||reduction>25)fail('The Guild tariff requires review.',503);const normal=Math.min(100000000,Math.max(1,Math.ceil(fareMinor*(100+percent)*(100-reduction)/10000))),offer=subsidies?await subsidies.quote(store,normal,reduction,lock):null;return {price:offer?.price??normal,offer};} const view=r=>({requestId:r.id,destination:r.destination,state:r.state,fareMinor:Number(r.fare_minor),expiresAt:Number(r.expires_at)}); const readyForTravel=async(user,uuid,store=bank)=>await prologueReady(user,uuid)||!!await store.first("SELECT id FROM pb_guild_passages WHERE actor_id=? AND minecraft_uuid=? AND state='arrived' LIMIT 1",[user.id,uuid]); const allowed=async(user,destination)=>!!routes[user?.faction]&&(destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user)); async function funds(tx,user,amount,lock=false){const context=await authority(user,{bank:tx});return(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id"+(lock?' FOR UPDATE':''),[user.id])).find(a=>ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(amount));} - async function release(tx,r){if(r.state!=='pending')return;const a=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[r.source_id]);if(!a||BigInt(a.reserved_minor){const rows=await tx.query("SELECT * FROM pb_guild_passages WHERE state='pending' AND expires_at<=? ORDER BY id LIMIT 25 FOR UPDATE",[clock()]);for(const r of rows)await release(tx,r);return rows.length;});} - async function quote(uuid,sourceWorld='lobby'){await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);const ready=await readyForTravel(user,uuid);if(!ready)return {ok:true,destination:routes[user.faction],destinations:[],fareMinor:await quotedFare(user),affordable:false,account:null,prologueRequired:true};const price=await quotedFare(user),source=await funds(bank,user,price),destinations=[routes[user.faction]];if(!destinations.includes('arrakis')&&await allowArrakis(user.faction,user))destinations.push('arrakis');const open=[];for(const destination of destinations)if(await allowJourney(sourceWorld,destination,bank,false))open.push(destination);return{ok:true,destination:routes[user.faction],destinations:open,fareMinor:price,affordable:!!source,account:source?.account_number||null};} + async function release(tx,r){if(r.state!=='pending')return;const a=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[r.source_id]);if(!a||BigInt(a.reserved_minor){const rows=await tx.query("SELECT * FROM pb_guild_passages WHERE state='pending' AND expires_at<=? ORDER BY id LIMIT 25 FOR UPDATE",[clock()]);for(const r of rows)await release(tx,r);return rows.length;});if(subsidies)await subsidies.expire();return expired;} + async function quote(uuid,sourceWorld='lobby'){await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);const ready=await readyForTravel(user,uuid);if(!ready)return {ok:true,destination:routes[user.faction],destinations:[],fareMinor:(await quotedFare(user)).price,affordable:false,account:null,prologueRequired:true};const {price,offer}=await quotedFare(user),source=await funds(bank,user,price),destinations=[routes[user.faction]];if(!destinations.includes('arrakis')&&await allowArrakis(user.faction,user))destinations.push('arrakis');const open=[];for(const destination of destinations)if(await allowJourney(sourceWorld,destination,bank,false))open.push(destination);return{ok:true,destination:routes[user.faction],destinations:open,fareMinor:price,...(offer?{subsidyMinor:offer.amount}:{}),affordable:!!source,account:source?.account_number||null};} async function smugglerPermit(user,uuid,source,tx,lock=false){if(!allowSmuggling||source!=='lobby'||!routes[user?.faction]||!await readyForTravel(user,uuid))return null;if(await allowed(user,'arrakis')&&await allowJourney(source,'arrakis',tx,lock))return null;return allowSmuggling(user,uuid,clock());} async function quoteSmuggler(uuid,sourceWorld='lobby'){await expire();const user=await resolve(uuid);if(!user)fail('Link your active website account and choose your House first.',403);const eligible=!!allowSmuggling&&sourceWorld==='lobby'&&!!routes[user.faction]&&await readyForTravel(user,uuid)&&(!await allowed(user,'arrakis')||!await allowJourney(sourceWorld,'arrakis',bank,false)),permit=eligible?await allowSmuggling(user,uuid,clock()):null;return{ok:true,eligible,allowed:!!permit,permitExpiresAt:permit?.expiresAt||null,fareMinor:smugglerFareMinor,affordable:!!permit&&!!await funds(bank,user,smugglerFareMinor),keyId:user.keyId,version:user.version};} async function board(input,smuggler=false){await expire();const user=await resolve(input.uuid);if(!user||!routes[user.faction]||user.keyId!==input.keyId||user.version!==input.version)fail('Your House key changed. Reopen the Guild menu.',403); if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<1||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?destination!=='arrakis'||input.sourceWorld!=='lobby':!await allowed(user,destination))fail(smuggler?'A current smuggler passage is required.':'Your House has no Imperial passage for this destination.',403);const fingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex'); return bank.transaction(async tx=>{ const prior=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]);if(prior){if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint)fail('This passage reference was already used.');return{ok:true,...view(prior),...(smuggler?{smuggler:true}:{}),replayed:true};} - const price=smuggler?smugglerFareMinor:await quotedFare(user);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.'); + const {price,offer}=smuggler?{price:smugglerFareMinor,offer:null}:await quotedFare(user,tx,true);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.'); if(!smuggler&&!await allowJourney(input.sourceWorld||'lobby',destination,tx,true))fail('The Spacing Guild has embargoed this world. Smuggler routes remain available.',403); if(!smuggler&&!boardingOpen(clock()))fail('Boarding opens at :00, :20 and :40 for five minutes.'); const fresh=await resolve(input.uuid);if(!fresh||fresh.id!==user.id||fresh.keyId!==input.keyId||fresh.version!==input.version||!await readyForTravel(fresh,input.uuid,tx)||!smuggler&&!await allowed(fresh,destination))fail('Your House key or Imperial passage changed.',403); @@ -49,7 +50,7 @@ export function createGuildService(bank,{authority,resolve,allowArrakis=async()= const target=await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury' FOR UPDATE");if(!target||target.state!=='active')fail('The Guild receiving account is unavailable.',503); const now=clock(),r={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,house_key:input.keyId,house_version:input.version,destination,fare_minor:price,source_id:source.id,target_id:target.id,fingerprint,state:'pending',created_at:now,expires_at:smuggler?Math.min(now+120000,permit.expiresAt):now+120000}; await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[price,source.id]); - await tx.query('INSERT INTO pb_guild_passages(id,actor_id,minecraft_uuid,house_key,house_version,destination,fare_minor,source_id,target_id,fingerprint,state,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',Object.values(r));if(smuggler)await tx.query("INSERT INTO pb_smuggler_passages(id,permit_key) VALUES(?,?)",[r.id,permit.keyId]);return{ok:true,...view(r),...(smuggler?{smuggler:true}:{})}; + await tx.query('INSERT INTO pb_guild_passages(id,actor_id,minecraft_uuid,house_key,house_version,destination,fare_minor,source_id,target_id,fingerprint,state,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',Object.values(r));if(smuggler)await tx.query("INSERT INTO pb_smuggler_passages(id,permit_key) VALUES(?,?)",[r.id,permit.keyId]);if(offer)await subsidies.reserve(tx,r.id,offer);return{ok:true,...view(r),...(smuggler?{smuggler:true}:{})}; }); } async function arrive(uuid,server){ @@ -63,7 +64,7 @@ export function createGuildService(bank,{authority,resolve,allowArrakis=async()= if(!ordinaryPaymentAccount(source)||!target||target.system_key!=='sys_game_treasury'||target.state!=='active'||BigInt(source.reserved_minor){const rows=await db.query("SELECT a.id,a.username,a.role,c.faction,c.version,h.key_id keyId FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id JOIN site_character_choices c ON c.user_id=a.id AND c.minecraft_uuid=l.minecraft_uuid JOIN jarvis_house_selections h ON h.account_id=a.id AND h.minecraft_uuid=l.minecraft_uuid AND h.version=c.version AND h.faction=c.faction JOIN organisation_keys k ON k.id=h.key_id AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000) WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[uuid]);return rows.length===1?{...rows[0],version:Number(rows[0].version)}:null;}); const tradePolicy=db?.worldTradeEnabled&&bank?createBankTradePolicy(db,bank):null; const allowJourney=async(source,destination,tx,lock)=>{if(!tradePolicy)return true;const policy=await tradePolicy(tx,Date.now(),lock);return ![source,destination].some(w=>policy[tradeWorld(w)]?.embargoUntil>Date.now());}; - const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready}):null); + const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready,subsidies:db?.guildSubsidyEnabled?createGuildSubsidies(bank,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)}):null}):null); return async request=>{ if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401); if(request.method!=='POST'||new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'A JSON Guild action is required.'},400); diff --git a/website/node/guild-subsidy.mjs b/website/node/guild-subsidy.mjs new file mode 100644 index 00000000..76cc8710 --- /dev/null +++ b/website/node/guild-subsidy.mjs @@ -0,0 +1,25 @@ +import {GUILD_SUBSIDY_POLICY} from '../control-panel/public/political-decision-policy.mjs'; +import {createHash,randomUUID} from 'node:crypto'; +import {PostbankPayments} from './postbank-payments.mjs'; +import {boardReadStore} from './board-deed-source.mjs'; +import {officeAuthority} from './political-decisions.mjs'; +import {STAFF_OFFICE_ACCOUNT_ID} from './organisation-keys.mjs'; +export const GUILD_SUBSIDY_SCHEMA=[ + `CREATE TABLE IF NOT EXISTS pb_guild_subsidies(id CHAR(36) PRIMARY KEY,key_id CHAR(36) NOT NULL UNIQUE,source_id BIGINT UNSIGNED NOT NULL,actor_id CHAR(36) NOT NULL,total_minor BIGINT NOT NULL,spent_minor BIGINT NOT NULL DEFAULT 0,pending_minor BIGINT NOT NULL DEFAULT 0,released_minor BIGINT NOT NULL DEFAULT 0,expires_at BIGINT NOT NULL,state VARCHAR(16) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`, + `CREATE TABLE IF NOT EXISTS pb_guild_subsidy_passages(id CHAR(36) PRIMARY KEY,pool_id CHAR(36) NOT NULL,amount_minor BIGINT NOT NULL,payment_id CHAR(36) NOT NULL UNIQUE,state VARCHAR(16) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` +]; +export const SUBSIDY_MIN=GUILD_SUBSIDY_POLICY.minMinor,SUBSIDY_MAX=GUILD_SUBSIDY_POLICY.maxMinor,SUBSIDY_PERCENT=GUILD_SUBSIDY_POLICY.percent; +export async function reserveGuildSubsidyPool(bank,{requestId,keyId,actorId,sourceId,amountMinor,expiresAt}){ + await bank.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[amountMinor,sourceId]);await bank.query("INSERT INTO pb_guild_subsidies(id,key_id,source_id,actor_id,total_minor,expires_at,state) VALUES(?,?,?,?,?,?,'active')",[requestId,keyId,sourceId,actorId,amountMinor,expiresAt]);return{poolId:requestId,sourceId:String(sourceId),amountMinor:String(amountMinor),percent:SUBSIDY_PERCENT,expiresAt}; +} +export async function verifyGuildSubsidy(central,pool,now){if(!central.guildSubsidyEnabled)return false;const db=boardReadStore(central,central),proof=await db.first("SELECT d.* FROM jarvis_political_decisions d JOIN organisation_keys k ON k.id=d.key_id AND k.account_id=? AND k.key_type='entity-state' AND k.scope_id=CONCAT('state:political-decision:',d.request_id) AND k.revoked_at IS NULL WHERE d.request_id=? AND d.decision_id='SG-03'",[STAFF_OFFICE_ACCOUNT_ID,pool.id]);if(!proof||proof.actor_id!==pool.actor_id||proof.key_id!==pool.key_id||Number(proof.expires_at)!==Number(pool.expires_at)||Number(proof.expires_at)<=now)return false;const r=JSON.parse(proof.receipt_json),p=JSON.parse(proof.payload_json);if(r.subsidy?.poolId!==pool.id||r.subsidy.amountMinor!==String(pool.total_minor)||String(r.subsidy.sourceId)!==String(pool.source_id)||Number(p.amountMinor)!==Number(pool.total_minor))return false;const current=await officeAuthority(db,{office:'spacing_guild'},{id:pool.actor_id},now);return current?.termId===proof.term_id;} +export function createGuildSubsidies(bank,{verify,clock=Date.now}={}){ + const payments=new PostbankPayments(bank,null,{clock}); + const available=p=>BigInt(p.total_minor)-BigInt(p.spent_minor)-BigInt(p.pending_minor)-BigInt(p.released_minor); + async function quote(store,price,existingDiscount,lock=false){if(existingDiscount>0||price<2)return null;const pool=await store.first("SELECT * FROM pb_guild_subsidies WHERE state='active' AND expires_at>? ORDER BY expires_at DESC,id DESC LIMIT 1"+(lock?' FOR UPDATE':''),[clock()]);if(!pool||!await verify(pool,clock()))return null;const amount=Math.min(Math.floor(price*SUBSIDY_PERCENT/100),Number(available(pool)),price-1);return amount>0?{poolId:pool.id,price:price-amount,amount}:null;} + async function reserve(store,passageId,offer){const pool=await store.first('SELECT * FROM pb_guild_subsidies WHERE id=? FOR UPDATE',[offer.poolId]);if(!pool||pool.state!=='active'||Number(pool.expires_at)<=clock()||available(pool)9223372036854775807n)throw Error('Subsidy settlement needs reconciliation');const id=marker.payment_id,fingerprint=createHash('sha256').update(JSON.stringify([pool.id,passageId,marker.amount_minor])).digest('hex');await store.query("INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at) VALUES(?,?,?,?,?,?,?,'system','queued',?)",[id,pool.actor_id,source.id,target.id,fingerprint,marker.amount_minor,'Guild travel subsidy · '+passageId,clock()]);await payments.post(store,{id,actor_id:pool.actor_id,amount_minor:String(marker.amount_minor)},source,target,true);await store.query('UPDATE pb_guild_subsidies SET spent_minor=spent_minor+?,pending_minor=pending_minor-? WHERE id=?',[marker.amount_minor,marker.amount_minor,pool.id]);await store.query("UPDATE pb_guild_subsidy_passages SET state='posted' WHERE id=?",[passageId]);} + async function expire(){return bank.transaction(async tx=>{const pools=await tx.query("SELECT * FROM pb_guild_subsidies WHERE state='active' ORDER BY expires_at,id LIMIT 50 FOR UPDATE");let closed=0;for(const pool of pools){if(Number(pool.expires_at)>clock()&&await verify(pool,clock()))continue;const remainder=available(pool);if(remainder<0n)throw Error('Subsidy ledger requires review');const source=await tx.first('SELECT reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[pool.source_id]);if(!source||BigInt(source.reserved_minor)createHash('sha256').update(JSON.stringify(x)).digest('hex' const funding=d=>entityId('office',d.office==='emperor'?'emperor':'leader:'+d.office); export function politicalDecisionReader(tx,base){const reader=boardReadStore(tx,base);if(tx!==base)reader.readSnapshot=async work=>work(reader);return reader;} export function decisionInput(input){ - const d=politicalDecision(input?.decisionId),fields=d?.kind==='organisation-passage'?'confirmed,decisionId,requestId,sourceAccount,targetId,targetKind':d?.kind==='ballot'?'confirmed,decisionId,requestId,sourceAccount,terms,title':d?.kind==='agreement'?(d.targetKind==='company'?'confirmed,decisionId,requestId,sourceAccount,targetCompanyId,terms,title':d.targetKind==='person'?'confirmed,decisionId,requestId,sourceAccount,targetPersonId,terms,title':'confirmed,decisionId,requestId,sourceAccount,targetOffice,terms,title'):d?.kind==='proclamation'?'body,confirmed,decisionId,requestId,sourceAccount,title':d?.kind==='event'?'confirmed,decisionId,description,endsAt,requestId,sourceAccount,startsAt,title':d?.kind==='tariff'?'confirmed,decisionId,percent,requestId,sourceAccount':d?.kind==='guild-discount'?'confirmed,decisionId,house,requestId,sourceAccount':d?.kind==='clan-grant'?'amountMinor,clanId,confirmed,decisionId,reason,requestId,sourceAccount':d?.kind==='report'?(d.reportType==='political'?(d.reviewKind==='candidate'?'candidateId,confirmed,decisionId,requestId,sourceAccount':'confirmed,decisionId,requestId,sourceAccount,targetOffice'):'confirmed,decisionId,requestId,sourceAccount'):'citation,confirmed,decisionId,recipientId,requestId,sourceAccount'; + const d=politicalDecision(input?.decisionId),fields=d?.kind==='organisation-passage'?'confirmed,decisionId,requestId,sourceAccount,targetId,targetKind':d?.kind==='ballot'?'confirmed,decisionId,requestId,sourceAccount,terms,title':d?.kind==='agreement'?(d.targetKind==='company'?'confirmed,decisionId,requestId,sourceAccount,targetCompanyId,terms,title':d.targetKind==='person'?'confirmed,decisionId,requestId,sourceAccount,targetPersonId,terms,title':'confirmed,decisionId,requestId,sourceAccount,targetOffice,terms,title'):d?.kind==='proclamation'?'body,confirmed,decisionId,requestId,sourceAccount,title':d?.kind==='event'?'confirmed,decisionId,description,endsAt,requestId,sourceAccount,startsAt,title':d?.kind==='tariff'?'confirmed,decisionId,percent,requestId,sourceAccount':d?.kind==='guild-discount'?'confirmed,decisionId,house,requestId,sourceAccount':d?.kind==='guild-subsidy'?'amountMinor,confirmed,decisionId,requestId,sourceAccount':d?.kind==='clan-grant'?'amountMinor,clanId,confirmed,decisionId,reason,requestId,sourceAccount':d?.kind==='report'?(d.reportType==='political'?(d.reviewKind==='candidate'?'candidateId,confirmed,decisionId,requestId,sourceAccount':'confirmed,decisionId,requestId,sourceAccount,targetOffice'):'confirmed,decisionId,requestId,sourceAccount'):'citation,confirmed,decisionId,recipientId,requestId,sourceAccount'; if(!d||!input||Object.keys(input).sort().join(',')!==fields||!validUuid(input.requestId)||input.confirmed!==true||typeof input.sourceAccount!=='string'||!/^\d{1,12}$/.test(input.sourceAccount))fail('Review and confirm a registered decision and its funding account.',400); const clean=(value,min,max)=>{if(typeof value!=='string'||value.trim().lengthmax||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))fail('Invalid announcement or citation.',400);return value.replaceAll('\r\n','\n').trim();}; - const payload=d.kind==='organisation-passage'?{targetKind:input.targetKind,targetId:input.targetId}:d.kind==='ballot'?{title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='agreement'?{...(d.targetKind==='company'?{targetCompanyId:input.targetCompanyId}:d.targetKind==='person'?{targetPersonId:input.targetPersonId}:{targetOffice:input.targetOffice}),title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='proclamation'?{title:clean(input.title,3,120),body:clean(input.body,10,6000)}:d.kind==='event'?{title:clean(input.title,3,100),description:clean(input.description,10,2000),startsAt:input.startsAt,endsAt:input.endsAt}:d.kind==='clan-grant'?{clanId:typeof input.clanId==='string'?input.clanId.toLowerCase():input.clanId,amountMinor:input.amountMinor,reason:clean(input.reason,10,2000)}:d.kind==='guild-discount'?{house:input.house,percent:d.discountPercent}:d.kind==='tariff'?{percent:input.percent}:d.kind==='report'?(d.reportType==='political'?(d.reviewKind==='candidate'?{candidateId:input.candidateId}:{targetOffice:input.targetOffice}):{}):{recipientId:input.recipientId,citation:clean(input.citation,3,2000)}; + const payload=d.kind==='organisation-passage'?{targetKind:input.targetKind,targetId:input.targetId}:d.kind==='ballot'?{title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='agreement'?{...(d.targetKind==='company'?{targetCompanyId:input.targetCompanyId}:d.targetKind==='person'?{targetPersonId:input.targetPersonId}:{targetOffice:input.targetOffice}),title:clean(input.title,3,100),terms:clean(input.terms,20,4000)}:d.kind==='proclamation'?{title:clean(input.title,3,120),body:clean(input.body,10,6000)}:d.kind==='event'?{title:clean(input.title,3,100),description:clean(input.description,10,2000),startsAt:input.startsAt,endsAt:input.endsAt}:d.kind==='guild-subsidy'?{amountMinor:input.amountMinor}:d.kind==='clan-grant'?{clanId:typeof input.clanId==='string'?input.clanId.toLowerCase():input.clanId,amountMinor:input.amountMinor,reason:clean(input.reason,10,2000)}:d.kind==='guild-discount'?{house:input.house,percent:d.discountPercent}:d.kind==='tariff'?{percent:input.percent}:d.kind==='report'?(d.reportType==='political'?(d.reviewKind==='candidate'?{candidateId:input.candidateId}:{targetOffice:input.targetOffice}):{}):{recipientId:input.recipientId,citation:clean(input.citation,3,2000)}; if(d.kind==='organisation-passage'&&(!['clan','company'].includes(payload.targetKind)||!validUuid(payload.targetId)))fail('Choose a current clan or company.',400); if(d.kind==='agreement'&&(d.targetKind==='company'?!validUuid(payload.targetCompanyId):d.targetKind==='person'?!validUuid(payload.targetPersonId):!PUBLIC_OFFICES.some(o=>o.key===payload.targetOffice)||payload.targetOffice===d.office))fail('Choose another registered political office.',400); + if(d.kind==='guild-subsidy'&&(!Number.isSafeInteger(payload.amountMinor)||payload.amountMinord.poolMaxMinor))fail('Choose a Guild subsidy pool within the published limit.',400); if(d.kind==='clan-grant'&&(!validUuid(payload.clanId)||!Number.isSafeInteger(payload.amountMinor)||payload.amountMinord.grantMaxMinor))fail('Choose an eligible clan and a grant within the published budget.',400); if(d.kind==='guild-discount'&&!TRADE_WORLDS.some(w=>w.house===payload.house))fail('Choose a native House for the preferred fare.',400); if(d.kind==='tariff'&&(!Number.isInteger(payload.percent)||payload.percent<0||payload.percent>5))fail('Choose a Guild surcharge from 0 to 5 percent.',400); @@ -54,7 +56,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_review_publications','jarvis_political_agreement_replies','jarvis_political_person_replies','jarvis_political_consultations','jarvis_political_consultation_votes','jarvis_council_dossiers','jarvis_council_events','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','corrino_companies','site_company_deeds','site_company_members','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,bankTables:['pb_guild_subsidies'],centralTables:['jarvis_political_decisions','jarvis_political_review_publications','jarvis_political_agreement_replies','jarvis_political_person_replies','jarvis_political_consultations','jarvis_political_consultation_votes','jarvis_council_dossiers','jarvis_council_events','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','corrino_companies','site_company_deeds','site_company_members','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=''){ @@ -67,11 +69,12 @@ 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{const reporting=d.reportType==='political'?deps.politicalReports:deps.marketReports;if(!reporting)throw Error('No reporting source');await reporting.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: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==='guild-subsidy'?d.poolMinMinor: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):[]; const organisations=holder&&d.kind==='organisation-passage'?await passageOrganisations(db):[]; const reviewTargets=holder&&d.reportType==='political'&&reportAvailable?await deps.politicalReports.targets(db,d,now):[],savedReport=holder&&d.kind==='report'&&prior?(d.reportType==='political'?await deps.politicalReports?.current(db,actor,d,prior,now):JSON.parse(prior.receipt_json).report||null):null; - return{...d,reviewTargets,organisations,diplomacyTargets,clans,grantAvailable,canManage:!!holder,canExecute:(d.reportType!=='political'||reviewTargets.length>0)&&(d.kind!=='organisation-passage'||organisations.length>0)&&(d.kind!=='ballot'||!!deps.consultations)&&(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:savedReport,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):[]}; + const pool=holder&&d.kind==='guild-subsidy'&&prior?await banking.view(db).first('SELECT * FROM pb_guild_subsidies WHERE id=?',[prior.request_id]):null;const subsidyPool=pool?{amountMinor:String(pool.total_minor),spentMinor:String(pool.spent_minor),pendingMinor:String(pool.pending_minor),releasedMinor:String(pool.released_minor),endsAt:Number(pool.expires_at),state:pool.state}:null; + return{...d,subsidyPool,reviewTargets,organisations,diplomacyTargets,clans,grantAvailable,canManage:!!holder,canExecute:(d.reportType!=='political'||reviewTargets.length>0)&&(d.kind!=='organisation-passage'||organisations.length>0)&&(d.kind!=='ballot'||!!deps.consultations)&&(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:savedReport,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):[]}; } async function execute(actor,input){ const {d,requestId,sourceAccount,payload}=decisionInput(input);if(!keys)fail('Key service unavailable.',503);await banking.ready();if(d.kind==='event')await eventBanking.ready();const digest=fingerprint([actor.id,d.id,sourceAccount,payload]); @@ -89,10 +92,10 @@ 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); + const subsidy=d.kind==='guild-subsidy';const taxMeta=grant?.account||await b.first(subsidy?"SELECT id FROM pb_accounts WHERE system_key='sys_game_treasury'":"SELECT id FROM pb_accounts WHERE system_key='sys_tax_treasury'");if(!taxMeta)fail('Receiving treasury unavailable.',503); 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; + 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||subsidy?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)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.'); @@ -101,13 +104,13 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){ const organisationPassage=d.kind==='organisation-passage'?await prepareOrganisationPassage(tx,payload,holder,now):null; 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});} let ballot=null;if(d.kind==='ballot'){if(!deps.consultations)fail('Consultations unavailable.',503);ballot=await deps.consultations.create(tx,{d,holder,now,requestId,payload});} - const rewardXP=grant?Math.max(1,Math.floor(d.xp*payload.amountMinor/d.grantMaxMinor)):d.xp; + const rewardXP=subsidy?Math.max(1,Math.floor(d.xp*payload.amountMinor/d.poolMaxMinor)):grant?Math.max(1,Math.floor(d.xp*payload.amountMinor/d.grantMaxMinor)):d.xp; + const subsidyExpiry=subsidy?Math.min(now+d.durationMs,Number((await tx.first('SELECT expires_at FROM political_office_terms WHERE id=?',[holder.termId]))?.expires_at||0)):null;if(subsidy&&subsidyExpiry<=now)fail('The Guild mandate has expired.'); 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=report?.expiresAt??organisationPassage?.expiresAt??(d.durationMs?now+d.durationMs:null); - receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:String(amount+adminAmount),adminFeeMinor:String(adminAmount),xp:rewardXP,expiresAt,cooldownUntil:now+d.cooldownMs,...(organisationPassage?{organisationPassage}:{}),...(report?{report}:{}),...(agreement?{agreement}:{}),...(ballot?{ballot}:{}),...(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); + const effectId=randomUUID(),expiresAt=subsidyExpiry??report?.expiresAt??organisationPassage?.expiresAt??(d.durationMs?now+d.durationMs:null); + receipt={ok:true,requestId,keyId,effectId,decisionId:d.id,feeMinor:subsidy?'0':String(amount+adminAmount),adminFeeMinor:String(adminAmount),xp:rewardXP,expiresAt,cooldownUntil:now+d.cooldownMs,...(organisationPassage?{organisationPassage}:{}),...(report?{report}:{}),...(agreement?{agreement}:{}),...(ballot?{ballot}:{}),...(grant?{grant:{clanId:grant.clanId,clanName:grant.clanName,amountMinor:String(amount),basicFallback:grant.basic,recipientKind:grant.recipientKind}}:{})}; + if(subsidy)receipt.subsidy=await reserveGuildSubsidyPool(b,{requestId,keyId,actorId:actor.id,sourceId:source.id,amountMinor:payload.amountMinor,expiresAt});else{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;} diff --git a/website/node/postbank-db.mjs b/website/node/postbank-db.mjs index 688f2486..47ade7af 100644 --- a/website/node/postbank-db.mjs +++ b/website/node/postbank-db.mjs @@ -2,6 +2,7 @@ import {WAR_CAMPAIGN_SCHEMA} from './war-campaign-store.mjs'; import {ECONOMY_OPERATION_SCHEMA} from './economy-operations.mjs'; import {WAR_SETTLEMENT_JOB_SCHEMA} from './war-settlement-jobs.mjs'; import {WAR_EXCHANGE_SCHEMA} from './war-exchange.mjs'; +import {GUILD_SUBSIDY_SCHEMA} from './guild-subsidy.mjs'; import {GUILD_SCHEMA,SMUGGLER_PASSAGE_SCHEMA} from './game-guild.mjs'; import {HOME_SCHEMA} from './game-home.mjs'; import {DEED_PURCHASE_SCHEMA} from './deed-purchases.mjs'; @@ -26,7 +27,7 @@ export async function openPostbankDatabase(settings){ const pool=mysql.createPool({host:settings.BANK_DB_HOST||'127.0.0.1',port:Number(settings.BANK_DB_PORT||3306),database:name,user:settings.BANK_DB_USER,password:settings.BANK_DB_PASSWORD,connectionLimit:4,supportBigNumbers:true,bigNumberStrings:true,charset:'utf8mb4',connectTimeout:8000}); const api=c=>({async query(sql,args=[]){return(await c.execute(sql,args))[0];},async first(sql,args=[]){return(await c.execute(sql,args))[0][0]||null;}}); const db={async query(sql,args=[]){return(await pool.execute(sql,args))[0];},async first(sql,args=[]){return(await pool.execute(sql,args))[0][0]||null;},async transaction(work){const c=await pool.getConnection();try{await c.beginTransaction();const result=await work(api(c));await c.commit();return result;}catch(error){await c.rollback();throw error;}finally{c.release();}},async close(){await pool.end();}}; - try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);await db.query(SMUGGLER_PASSAGE_SCHEMA);await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;} + try{for(const sql of(await readFile(new URL('./postbank-schema.sql',import.meta.url),'utf8')).split(';').map(s=>s.trim()).filter(Boolean))await db.query(sql);for(const sql of [...CLAIM_PRODUCT_SCHEMA,CLAIM_RESET_SCHEMA])await db.query(sql+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(NETWORTH_SCHEMA);for(const sql of [...RIHLA_SCHEMA,...EVENT_SCHEMA,...WAR_EXCHANGE_SCHEMA,WAR_CAMPAIGN_SCHEMA,WAR_SETTLEMENT_JOB_SCHEMA,...CAMPAIGN_SCHEMA])await db.query(sql);await initializeJarvisListings(db);await db.query(DEED_PURCHASE_SCHEMA);await db.query(ESTATE_SCHEMA+' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');await db.query(PROMOTION_DELIVERY_SCHEMA);for(const sql of POLITICAL_JOB_BANK_SCHEMA)await db.query(sql);await db.query(JARVIS_CHARGE_SCHEMA);await db.query(GUILD_SCHEMA);for(const sql of GUILD_SUBSIDY_SCHEMA)await db.query(sql);await db.query(SMUGGLER_PASSAGE_SCHEMA);await db.query(HOME_SCHEMA);await ensureClaimBatchColumns(db);await ensureCreditColumns(db);await ensurePostbankIndexes(db);await db.query(ECONOMY_OPERATION_SCHEMA);}catch(error){await pool.end();throw error;} return db; } diff --git a/website/tests/political-decisions.test.mjs b/website/tests/political-decisions.test.mjs index ef4b529c..53f02124 100644 --- a/website/tests/political-decisions.test.mjs +++ b/website/tests/political-decisions.test.mjs @@ -56,7 +56,7 @@ test('factual exposure publishes once in the existing proclamation archive with test('publication is original-holder and unexpired-proof only, and its archive/key failure rolls back together',async()=>{for(const change of['expiry','source-key','source-term','journal']){const f=await reviewFixture('muad_dib');try{const input=f.review('NF-06'),r=await f.service.execute(f.people.Owner,input);await assert.rejects(f.reviews.publish(f.people.Member,f.publish(input.requestId)),/cannot be published/);if(change==='expiry')f.setTime(r.expiresAt);if(change==='source-key')await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[r.keyId]);if(change==='source-term')await f.db.query("UPDATE political_office_terms SET outcome='ended' WHERE id=?",[f.term]);if(change==='journal')f.db.sqlite.exec("CREATE TRIGGER fail_review_publication BEFORE INSERT ON jarvis_political_review_publications BEGIN SELECT RAISE(ABORT,'publication journal failed');END");const keys=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;await assert.rejects(f.reviews.publish(f.people.Owner,f.publish(input.requestId)),change==='journal'?/publication journal failed/:/expired/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,keys);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_proclamations')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}}}); test('candidate reviews exclude closed records, truncate long public text explicitly and never consume election votes',async()=>{const f=await reviewFixture('veiled_concord');try{await f.db.query('UPDATE site_profiles SET bio=?',['x'.repeat(8000)]);const input=f.review('BG-02'),r=await f.service.execute(f.people.Owner,input);assert.equal(r.report.target.bio.length,2000);assert.equal(r.report.target.textTruncated,true);assert.equal((await f.db.first('SELECT COUNT(*) n FROM political_round_candidates')).n,0);await assert.rejects(f.reviews.publish(f.people.Owner,f.publish(input.requestId)),/cannot be published/);await f.db.query("UPDATE political_applications SET status='withdrawn'");f.setTime(1000+48*3600000);await assert.rejects(f.service.execute(f.people.Owner,f.review('BG-02')),/current public candidate/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}}); test('paid review failure rolls back fee and Reputation, while the publication API keeps origin and payload checks',async()=>{const f=await reviewFixture('veiled_concord');try{const input=f.review('BG-06'),keys=(await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n;f.db.sqlite.exec("CREATE TRIGGER fail_review BEFORE INSERT ON jarvis_political_decisions BEGIN SELECT RAISE(ABORT,'review journal failed');END");await assert.rejects(f.service.execute(f.people.Owner,input),/review journal 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.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[f.people.Owner.id])).total_xp,50000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM organisation_keys')).n,keys);const api=createPoliticalReviewAPI(f.db,f.reviews,{authenticate:async()=>f.people.Owner}),post=(body,origin='https://cp.dunerealms.com')=>api(new Request('https://cp.dunerealms.com/api/politics/reviews/publish',{method:'POST',headers:{origin,'Content-Type':'application/json'},body:JSON.stringify(body)}));assert.equal((await post(f.publish(input.requestId),'https://example.invalid')).status,403);assert.equal((await post({...f.publish(input.requestId),actorId:f.people.Member.id})).status,400);}finally{f.db.close();}}); -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('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==='guild-subsidy'){assert.equal(dm,'Pool amount');assert.equal(d.poolMaxMinor,2000000);}else 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{ @@ -364,3 +364,8 @@ import {currentPax,paxBlocksWar} from '../node/imperial-pax.mjs'; async function paxFixture(){const f=await diplomacyFixture('emperor');f.db.sqlite.exec('DROP TABLE site_clan_members;DROP TABLE site_clans;');await initializeClans(f.db,{mysql:false});for(const sql of NAIB_COUNCIL_SCHEMA)await f.db.query(sql);f.db.paxEnabled=true;await f.db.query('UPDATE pb_accounts SET balance_minor=7000000 WHERE id=?',[f.source.id]);const clans=[];for(const person of [f.people.Member,f.people.Ceo]){const id=randomUUID(),link=await f.db.first('SELECT minecraft_uuid FROM site_game_links WHERE user_id=?',[person.id]);await f.db.query("INSERT INTO site_clans(id,name,name_key,tag,description,home_world,owner_id,created_at,updated_at) VALUES(?,?,?,?,?,'arrakduin',?,1,1)",[id,person.username+' sietch',person.username.toLowerCase()+' sietch',person.username.toUpperCase(),'Independent sietch',person.id]);await f.db.query("INSERT INTO site_clan_members(user_id,minecraft_uuid,clan_id,clan_role,joined_at) VALUES(?,?,?,'owner',1)",[person.id,link.minecraft_uuid,id]);await f.pol.query('INSERT INTO jarvis_progression_accounts VALUES(?,50000,50000,63,1,0)',[person.id]);clans.push({id,person});}const consultations=createPoliticalConsultations(f.db,f.keys,{clock:f.clock}),council=createNaibCouncil(f.db,{clock:f.clock,keys:f.keys}),service=createPoliticalDecisions(f.db,f.db,f.keys,{verifyStorage:async()=>null,authority:f.authority,clock:f.clock,consultations});const input={decisionId:'IMP-01',requestId:randomUUID(),sourceAccount:String(f.source.id),title:'Pax Imperialis',terms:'The Imperial throne offers a voluntary temporary peace on Arrakis.',confirmed:true};return {...f,clans,consultations,council,service,input};} test('Pax Imperialis pays once, opens separate real House and Council ballots, limits new Arrakis agreements only among consenters',async()=>{const f=await paxFixture();try{const receipt=await f.service.execute(f.people.Owner,f.input);assert.equal(receipt.feeMinor,'5000000');assert.equal(receipt.xp,1500);assert.equal(receipt.ballot.paxDossierId,f.input.requestId);assert.equal((await f.service.execute(f.people.Owner,f.input)).keyId,receipt.keyId);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);assert.equal(await currentPax(f.db,f.clock()),null);await f.consultations.vote(f.people.Other,{ballotId:f.input.requestId,seatKey:'office:'+f.targetOffice,choice:'yes',requestId:randomUUID(),confirmed:true});for(const c of f.clans)await f.council.vote(c.person,{dossierId:f.input.requestId,choice:'accept',confirmed:true});f.setTime(1000+86400000);await f.consultations.reconcile();await f.council.reconcile();const pact=await currentPax(f.db,f.clock());assert.equal(pact.endsAt,f.clock()+72*3600000);assert.equal(pact.clans.length,2);const block={startsAt:f.clock()+3600000,endsAt:f.clock()+7200000};assert.equal(await paxBlocksWar(f.db,[{kind:'clan',id:f.clans[0].id},{kind:'politics',id:f.targetOffice}],block,f.clock()),true);assert.equal(await paxBlocksWar(f.db,[{kind:'clan',id:f.clans[0].id},{kind:'clan',id:randomUUID()}],block,f.clock()),false);assert.equal(await paxBlocksWar(f.db,[{kind:'politics',id:'emperor'},{kind:'politics',id:f.targetOffice}],block,f.clock()),false);assert.equal(await currentPax(f.db,pact.endsAt),null);}finally{f.db.close();}}); test('a genuinely rejected paid Pax enables free once-per-declaration Reputation only for currently eligible rejecting Naibs',async()=>{const f=await paxFixture();try{await f.service.execute(f.people.Owner,f.input);await f.consultations.vote(f.people.Other,{ballotId:f.input.requestId,seatKey:'office:'+f.targetOffice,choice:'yes',requestId:randomUUID(),confirmed:true});for(const c of f.clans)await f.council.vote(c.person,{dossierId:f.input.requestId,choice:'reject',confirmed:true});f.setTime(1000+86400000);await f.consultations.reconcile();await f.council.reconcile();assert.equal(await currentPax(f.db,f.clock()),null);const p=f.clans[0].person;assert.deepEqual((await f.council.context(p)).rejections,[f.input.requestId]);const claim={dossierId:f.input.requestId,requestId:randomUUID(),confirmed:true};await assert.rejects(f.council.rejectPax(f.people.Other,claim),/current sietch/);assert.equal((await f.council.rejectPax(p,claim)).xp,1200);assert.equal((await f.council.rejectPax(p,claim)).replayed,true);assert.equal((await f.pol.first('SELECT total_xp FROM jarvis_progression_accounts WHERE account_id=?',[p.id])).total_xp,51200);assert.deepEqual((await f.council.context(p)).rejections,[]);await assert.rejects(f.council.rejectPax(p,{...claim,requestId:randomUUID()}),/already recorded/);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,1);}finally{f.db.close();}}); +import {createGuildSubsidies,verifyGuildSubsidy,GUILD_SUBSIDY_SCHEMA} from '../node/guild-subsidy.mjs'; +import {createGuildService,GUILD_SCHEMA} from '../node/game-guild.mjs'; +async function guildSubsidyFixture(){const f=await fixture('spacing_guild');for(const sql of GUILD_SUBSIDY_SCHEMA)await f.db.query(sql);await f.db.query(GUILD_SCHEMA.replace(/,INDEX guild_pending\([^)]*\)/,''));await f.db.query("INSERT INTO pb_accounts(system_key,type_code,display_name,balance_minor,state,created_at) VALUES('sys_game_treasury','999','Game treasury',0,'active',1)");f.db.guildSubsidyEnabled=true;const user={...f.people.Other,uuid:randomUUID(),faction:'atreides',version:1,keyId:randomUUID()},entity={id:entityId('person',user.id),kind:'person',key:user.id,name:'Traveller',canView:true,canPay:true,canActivate:true},authority=async()=>({entities:[entity]});await new PostbankService(f.db,authority).activate(user,{entityId:entity.id,packageKey:'pb_flow',termsVersion:BANK_VERSION,accepted:true,requestId:randomUUID()});const passenger=await f.db.first('SELECT a.* FROM pb_accounts a JOIN pb_clients c ON a.client_number=c.client_number WHERE c.entity_id=?',[entity.id]);await f.db.query('UPDATE pb_accounts SET balance_minor=50000 WHERE id=?',[passenger.id]);const subsidies=createGuildSubsidies(f.db,{verify:(p,n)=>verifyGuildSubsidy(f.db,p,n),clock:f.clock});let preferred=0;const guild=createGuildService(f.db,{authority,resolve:async()=>user,clock:f.clock,discount:async()=>preferred,subsidies});const input={decisionId:'SG-03',requestId:randomUUID(),sourceAccount:String(f.source.id),amountMinor:2000000,confirmed:true};const board=price=>({uuid:user.uuid,requestId:randomUUID(),keyId:user.keyId,version:1,fareMinor:price,destination:'caladan'});return {...f,user,passenger,subsidies,guild,input,board,preferred:v=>preferred=v};} +test('Guild subsidy reserves the named office funds and pays only actual completed journeys with nonstacking fares and unused release',async()=>{const f=await guildSubsidyFixture();try{const receipt=await f.service.execute(f.people.Owner,f.input);assert.equal(receipt.subsidy.amountMinor,'2000000');assert.equal(receipt.xp,300);assert.equal(receipt.feeMinor,'0');assert.equal((await f.service.execute(f.people.Owner,f.input)).keyId,receipt.keyId);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2000000);f.preferred(10);assert.equal((await f.guild.quote(f.user.uuid)).fareMinor,9000);f.preferred(0);const quote=await f.guild.quote(f.user.uuid);assert.equal(quote.fareMinor,8000);assert.equal(quote.subsidyMinor,2000);const ticket=f.board(quote.fareMinor);await f.guild.board(ticket);assert.equal((await f.db.first('SELECT pending_minor FROM pb_guild_subsidies')).pending_minor,2000);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);await f.guild.arrive(f.user.uuid,'caladan');await f.guild.arrive(f.user.uuid,'caladan');assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,2);assert.equal((await f.db.first("SELECT balance_minor FROM pb_accounts WHERE system_key='sys_game_treasury'")).balance_minor,10000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[f.passenger.id])).balance_minor,42000);assert.equal((await f.db.first('SELECT spent_minor FROM pb_guild_subsidies')).spent_minor,2000);f.setTime(receipt.expiresAt);await f.subsidies.expire();const source=await f.db.first('SELECT balance_minor,reserved_minor FROM pb_accounts WHERE id=?',[f.source.id]);assert.deepEqual({...source},{balance_minor:1998000,reserved_minor:0});assert.equal((await f.guild.quote(f.user.uuid)).fareMinor,10000);}finally{f.db.close();}}); +test('revocation releases unused Guild subsidy funds but preserves a confirmed pending fare, and expiry releases an unused ticket',async()=>{const f=await guildSubsidyFixture();try{const receipt=await f.service.execute(f.people.Owner,f.input);await f.guild.board(f.board(8000));await f.db.query('UPDATE organisation_keys SET revoked_at=1 WHERE id=?',[receipt.keyId]);await f.subsidies.expire();assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2000);assert.equal((await f.guild.quote(f.user.uuid)).fareMinor,10000);f.setTime(1000+120001);await f.guild.expire();assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});