From 47e42ba64bd11a067f688e1b06048e1882ecf691 Mon Sep 17 00:00:00 2001 From: Dev Date: Wed, 25 Nov 2026 18:36:14 +0100 Subject: [PATCH] Connect Ordos trade incentives to atomic verified native Exchange rebates --- .../com/dunerealms/gui/ExchangeMenus.java | 2 +- .../public/cp-v2/cp-v2-decision-audit.mjs | 2 +- .../cp-v2/cp-v2-political-decisions.mjs | 12 +++++----- .../public/political-decision-policy.mjs | 4 +++- website/control-panel/server.mjs | 5 ++-- website/node/exchange-incentive.mjs | 24 +++++++++++++++++++ website/node/game-exchange-payments.mjs | 4 ++-- website/node/game-exchange-service.mjs | 8 +++---- website/node/game-exchange.mjs | 3 ++- website/node/political-decisions.mjs | 19 ++++++++------- website/node/postbank-db.mjs | 3 ++- website/tests/political-decisions.test.mjs | 7 +++++- 12 files changed, 64 insertions(+), 29 deletions(-) create mode 100644 website/node/exchange-incentive.mjs diff --git a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java index bdd9a5bb..60030713 100644 --- a/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java +++ b/DuneRealmsGUI/src/main/java/com/dunerealms/gui/ExchangeMenus.java @@ -70,7 +70,7 @@ final class ExchangeMenus implements Listener,AutoCloseable { }).buildConversation(p); priceInputs.put(owner,conversation);conversation.begin(); } - private void purchase(Player p,Purchase purchase){if(purchase.row.has("kitsetId")){kitPurchase(p,purchase);return;}var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nSeller: "+row.get("seller").getAsString()+"\nQuantity: "+purchase.amount+" · Total: "+money(row.get("priceMinor").getAsLong()*purchase.amount);try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This item cannot be delivered by your current version.");return;}quantityPresets(s,Math.min(64,row.get("quantity").getAsInt()),amount->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Buy "+purchase.amount,()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.max(1,purchase.amount-1))));button(s,31,Material.PAPER,"Quantity: "+purchase.amount,money(row.get("priceMinor").getAsLong())+" per item",()->purchase(p,purchase));button(s,32,Material.LIME_DYE,"+ Quantity","Maximum "+Math.min(64,row.get("quantity").getAsInt()),()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.min(Math.min(64,row.get("quantity").getAsInt()),purchase.amount+1))));button(s,45,Material.ARROW,"Back","Return to the Exchange",()->{if(retries.containsKey(p.getUniqueId())){p.sendMessage("Resolve the previous purchase by retrying the same confirmation first.");purchase(p,purchase);}else list(p,false,0);});button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry purchase · ":"Buy · ")+money(row.get("priceMinor").getAsLong()*purchase.amount),"Pay from your central personal bank account",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy");q.addProperty("requestId",purchase.request.toString());q.addProperty("listingId",row.get("id").getAsString());q.addProperty("amount",purchase.amount);q.addProperty("priceMinor",row.get("priceMinor").getAsLong());q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Purchase confirmed: "+money(receipt.get("totalMinor").getAsLong())+". Your items are ready for delivery.");deliver(p,true);list(p,false,0);},error->{p.sendMessage(error+" Retry this confirmation with the same purchase reference.");purchase(p,purchase);});});show(p,s);} + private void purchase(Player p,Purchase purchase){if(purchase.row.has("kitsetId")){kitPurchase(p,purchase);return;}var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nSeller: "+row.get("seller").getAsString()+"\nQuantity: "+purchase.amount+" · Total: "+money(row.get("priceMinor").getAsLong()*purchase.amount);try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This item cannot be delivered by your current version.");return;}quantityPresets(s,Math.min(64,row.get("quantity").getAsInt()),amount->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(amount)));button(s,30,Material.RED_DYE,"− Quantity","Buy "+purchase.amount,()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.max(1,purchase.amount-1))));button(s,31,Material.PAPER,"Quantity: "+purchase.amount,money(row.get("priceMinor").getAsLong())+" per item",()->purchase(p,purchase));button(s,32,Material.LIME_DYE,"+ Quantity","Maximum "+Math.min(64,row.get("quantity").getAsInt()),()->purchase(p,retries.containsKey(p.getUniqueId())?purchase:purchase.quantity(Math.min(Math.min(64,row.get("quantity").getAsInt()),purchase.amount+1))));button(s,45,Material.ARROW,"Back","Return to the Exchange",()->{if(retries.containsKey(p.getUniqueId())){p.sendMessage("Resolve the previous purchase by retrying the same confirmation first.");purchase(p,purchase);}else list(p,false,0);});button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry purchase · ":"Buy · ")+money(row.get("priceMinor").getAsLong()*purchase.amount),"Pay from your central personal bank account",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy");q.addProperty("requestId",purchase.request.toString());q.addProperty("listingId",row.get("id").getAsString());q.addProperty("amount",purchase.amount);q.addProperty("priceMinor",row.get("priceMinor").getAsLong());q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Purchase confirmed: "+money(receipt.get("totalMinor").getAsLong())+". Your items are ready for delivery.");if(receipt.has("rebateMinor")&&receipt.get("rebateMinor").getAsLong()>0)p.sendMessage("Ordos trade incentive credited: "+money(receipt.get("rebateMinor").getAsLong())+".");deliver(p,true);list(p,false,0);},error->{p.sendMessage(error+" Retry this confirmation with the same purchase reference.");purchase(p,purchase);});});show(p,s);} private void kits(Player p,int page){var q=action("read_kits");q.addProperty("page",page);request(p,q,data->{var s=panel(p,"Exchange · Kits");button(s,1,Material.EMERALD,"Buy items","Browse loose goods",()->list(p,false,0));button(s,4,Material.NETHERITE_CHESTPLATE,"Kits","Published organisation designs",()->kits(p,0));button(s,7,Material.CHEST,"Sell","Your listings",()->list(p,true,0));int index=0;for(var value:data.getAsJsonArray("listings")){var row=value.getAsJsonObject();int slot=10+(index/6)*9+index%6;index++;String title=row.get("title").getAsString(),description=row.get("seller").getAsString()+" · "+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());if(row.get("purchaseAvailable").getAsBoolean())button(s,slot,Material.NETHERITE_CHESTPLATE,title,description,()->kitPurchase(p,new Purchase(row.deepCopy(),1,UUID.randomUUID())));else{s.inventory.setItem(slot,icon(Material.GRAY_DYE,title,description,"Organisation banking is unavailable"));s.description+="\n"+title+" · unavailable";}}if(page>0)button(s,45,Material.ARROW,"Previous","Previous kits",()->kits(p,page-1));button(s,49,Material.ARROW,"Back","Imperial Codex",()->back.accept(p));if(data.get("hasNext").getAsBoolean())button(s,53,Material.ARROW,"Next","More kits",()->kits(p,page+1));show(p,s);});} private void kitPurchase(Player p,Purchase purchase){var row=purchase.row;var s=panel(p,"Exchange · Confirm purchase");s.description=row.get("title").getAsString()+"\nOrganisation: "+row.get("seller").getAsString()+"\n"+row.get("items").getAsInt()+" items · "+money(row.get("priceMinor").getAsLong());s.inventory.setItem(13,icon(Material.NETHERITE_CHESTPLATE,row.get("title").getAsString(),row.get("seller").getAsString(),row.get("items").getAsInt()+" items"));button(s,45,Material.ARROW,"Back","Kit catalogue",()->{if(retries.containsKey(p.getUniqueId())){p.sendMessage("Resolve the previous purchase with the same reference first.");kitPurchase(p,purchase);}else kits(p,0);});button(s,49,Material.EMERALD,(retries.containsKey(p.getUniqueId())?"Retry kit · ":"Buy kit · ")+money(row.get("priceMinor").getAsLong()),"Pay personally; proceeds go to the organisation",()->{retries.put(p.getUniqueId(),purchase);var q=action("buy_kit");q.addProperty("requestId",purchase.request.toString());q.addProperty("kitsetId",row.get("kitsetId").getAsString());q.add("listingVersion",row.get("listingVersion"));q.add("priceMinor",row.get("priceMinor"));q.addProperty("confirmed",true);request(p,q,receipt->{retries.remove(p.getUniqueId());p.sendMessage("Kit purchased: "+money(receipt.get("totalMinor").getAsLong())+". Delivery follows automatically; make room for the complete kit.");try{bridge.refreshKits(p);}catch(Exception unavailable){p.sendMessage("Your kit remains owed until the next inventory sync.");}kits(p,0);},error->{p.sendMessage(error+" Retry this confirmation with the same reference.");kitPurchase(p,purchase);});});show(p,s);} private void withdraw(Player p,JsonObject row){var s=panel(p,"Exchange · Withdraw listing");try{s.inventory.setItem(13,bridge.exchangeIcon(row));}catch(Exception bad){p.sendMessage("This stored item cannot be decoded.");return;}button(s,45,Material.ARROW,"Back","Your listings",()->list(p,true,0));button(s,49,Material.CHEST,"Withdraw "+row.get("quantity").getAsInt()+" items","Return all unsold stock to your inventory",()->{UUID id=UUID.randomUUID();var q=action("prepare_cancel");q.addProperty("requestId",id.toString());request(p,q,permit->{try{int quantity=bridge.exchangeCancel(p,permit,id,Long.parseLong(row.get("id").getAsString()));p.sendMessage("Listing withdrawn. Returned "+quantity+" items.");list(p,true,0);}catch(Exception e){p.sendMessage(e.getMessage()==null?"The listing was not withdrawn.":e.getMessage());}});});show(p,s);} 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 85a70119..4950b485 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.':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.'); + 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==='exchange-incentive'?'Reserve 100–20,000 DM for up to seven days; only a native Ordos-origin ordinary Exchange purchase earns the immediate bounded 10% rebate. No price, seller levy or kit changes. Unused reserves are released.':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 e675e7b1..68bfaa82 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,7 +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(['guild-subsidy','exchange-incentive'].includes(d.kind)){grantAmount=field(d.kind==='exchange-incentive'?'Trade incentive pool (DM)':'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',d.kind==='exchange-incentive'?'Reserve funds for a 10% rebate on verified ordinary purchases of native Ordos goods. Buyers must be able to pay the gross price, seller proceeds and levies remain unchanged, and no kit purchases qualify.':'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); @@ -42,22 +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(['guild-subsidy','exchange-incentive'].includes(d.kind))status.textContent=(data.canManage?'Current office verified. ':'Current 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==='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}; + 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')}:['guild-subsidy','exchange-incentive'].includes(d.kind)?{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(['guild-subsidy','exchange-incentive'].includes(d.kind)&&(!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.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();}}; + 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.incentive?'Reserved '+(Number(receipt.incentive.amountMinor)/100).toFixed(2)+' DM for Ordos trade rebates. ':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 ef7f04f7..aaa09b8f 100644 --- a/website/control-panel/public/political-decision-policy.mjs +++ b/website/control-panel/public/political-decision-policy.mjs @@ -1,6 +1,7 @@ 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 EXCHANGE_INCENTIVE_POLICY=Object.freeze({minMinor:10000,maxMinor:2000000,percent:10,world:'sigma_draconis_iv'}); 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:'ATR-03',office:'atreides',house:'atreides',title:'Honour of the Duke',kind:'honour',level:20,xp:300,feeMinor:250000,cooldownMs:72*3600000}, {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-04',office:'ordos',title:'Trade Incentive',kind:'exchange-incentive',level:20,xp:300,feeMinor:0,poolMinMinor:EXCHANGE_INCENTIVE_POLICY.minMinor,poolMaxMinor:EXCHANGE_INCENTIVE_POLICY.maxMinor,discountPercent:EXCHANGE_INCENTIVE_POLICY.percent,cooldownMs:7*86400000,durationMs:7*86400000}, {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}, @@ -62,4 +64,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==='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.'}))); +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:(['guild-subsidy','exchange-incentive'].includes(d.kind)?'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==='exchange-incentive'?'Reserve up to 20,000 DM for seven days. A verified ordinary Exchange purchase of native Ordos goods earns a 10% buyer rebate, bounded by the remaining pool; no self-funded office transactions, kit changes, price manipulation or seller tax changes. Unused reserves are released.':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 1d4312f6..98189b9d 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 {createExchangeIncentives,verifyExchangeIncentive} from '../node/exchange-incentive.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'; @@ -605,9 +606,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;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'; + 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;db.exchangeIncentiveEnabled=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:'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 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:'exchange_incentives',slot:now=>Math.floor(now/60000)*60000,run:()=>createExchangeIncentives(bankDatabase,{verify:(pool,now)=>verifyExchangeIncentive(db,pool,now)}).expire()},{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/exchange-incentive.mjs b/website/node/exchange-incentive.mjs new file mode 100644 index 00000000..df7571e0 --- /dev/null +++ b/website/node/exchange-incentive.mjs @@ -0,0 +1,24 @@ +import {EXCHANGE_INCENTIVE_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 EXCHANGE_INCENTIVE_SCHEMA=[ + `CREATE TABLE IF NOT EXISTS pb_exchange_incentive_pools(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,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_exchange_incentive_rebates(purchase_id CHAR(36) PRIMARY KEY,pool_id CHAR(36) NOT NULL,buyer_id CHAR(36) NOT NULL,amount_minor BIGINT NOT NULL,payment_id CHAR(36) NOT NULL UNIQUE,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4` +]; +export const INCENTIVE_PERCENT=EXCHANGE_INCENTIVE_POLICY.percent,INCENTIVE_WORLD=EXCHANGE_INCENTIVE_POLICY.world; +export async function reserveExchangeIncentivePool(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_exchange_incentive_pools(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:INCENTIVE_PERCENT,world:INCENTIVE_WORLD,expiresAt};} +export async function verifyExchangeIncentive(central,pool,now){if(!central.exchangeIncentiveEnabled)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='ORD-04'",[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.incentive?.poolId!==pool.id||r.incentive.amountMinor!==String(pool.total_minor)||String(r.incentive.sourceId)!==String(pool.source_id)||Number(p.amountMinor)!==Number(pool.total_minor))return false;const current=await officeAuthority(db,{office:'ordos'},{id:pool.actor_id},now);return current?.termId===proof.term_id;} +export function createExchangeIncentives(bank,{verify,clock=Date.now}={}){ + const payments=new PostbankPayments(bank,null,{clock}),remaining=p=>BigInt(p.total_minor)-BigInt(p.spent_minor)-BigInt(p.released_minor); + async function rebate(tx,{purchaseId,buyerId,sellerId,buyerAccountId,originWorld,grossMinor}){ + if(originWorld!==INCENTIVE_WORLD||buyerId===sellerId)return 0;const pool=await tx.first("SELECT * FROM pb_exchange_incentive_pools WHERE state='active' AND expires_at>? ORDER BY expires_at DESC,id DESC LIMIT 1 FOR UPDATE",[clock()]);if(!pool||pool.actor_id===buyerId||pool.actor_id===sellerId||!await verify(pool,clock()))return 0; + const prior=await tx.first('SELECT buyer_id,amount_minor FROM pb_exchange_incentive_rebates WHERE purchase_id=?',[purchaseId]);if(prior){if(prior.buyer_id!==buyerId)throw Error('Exchange incentive reference conflict');return Number(prior.amount_minor);}const maximum=BigInt(grossMinor)*BigInt(INCENTIVE_PERCENT)/100n,amount=remaining(pool)9223372036854775807n)throw Error('Exchange incentive settlement needs review');const id=randomUUID(),fingerprint=createHash('sha256').update(JSON.stringify([pool.id,purchaseId,buyerId,amount.toString()])).digest('hex');await tx.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,amount.toString(),'Ordos trade incentive · '+purchaseId,clock()]);await payments.post(tx,{id,actor_id:pool.actor_id,amount_minor:amount.toString()},source,target,true);await tx.query('UPDATE pb_exchange_incentive_pools SET spent_minor=spent_minor+? WHERE id=?',[amount.toString(),pool.id]);await tx.query('INSERT INTO pb_exchange_incentive_rebates VALUES(?,?,?,?,?,?)',[purchaseId,pool.id,buyerId,amount.toString(),id,clock()]);return Number(amount); + } + async function replay(tx,purchaseId){const row=await tx.first('SELECT amount_minor FROM pb_exchange_incentive_rebates WHERE purchase_id=?',[purchaseId]);return Number(row?.amount_minor||0);} + async function expire(){return bank.transaction(async tx=>{const rows=await tx.query("SELECT * FROM pb_exchange_incentive_pools WHERE state='active' ORDER BY expires_at,id LIMIT 50 FOR UPDATE");let closed=0;for(const pool of rows){if(Number(pool.expires_at)>clock()&&await verify(pool,clock()))continue;const amount=remaining(pool),source=await tx.first('SELECT reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[pool.source_id]);if(amount<0n||!source||BigInt(source.reserved_minor)canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(amount)))throw new BankError('Insufficient available funds in an authorised personal payment account.',409); }, - async post(tx,actor,seller,hold,tax=null){ + async post(tx,actor,seller,hold,tax=null,incentive=null){ if(!payments)throw new BankError('The central bank is unavailable.',503); const amount=BigInt(hold.unit_minor)*BigInt(hold.quantity),fingerprint=exchangeFingerprint(hold); const candidates=await personal(tx,actor.id),recipients=await personal(tx,seller.id),taxMinor=tradeTaxMinor(amount,tax?.percent||0),houseId=taxMinor>0n?entityId('office','leader:'+tax.house):null; @@ -64,7 +64,7 @@ export function createGameExchangePayments(bank,authority,{clock=Date.now}={}){ await payments.post(tx,{id:taxPayment,actor_id:seller.id,amount_minor:taxMinor.toString()},{...target,balance_minor:(BigInt(target.balance_minor)+amount).toString()},house,false); } await tx.query('INSERT INTO pb_exchange_levies(purchase_id,payment_id,policy_request_id,origin_world,percent,gross_minor,tax_minor,net_minor,house_entity_id,target_id,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)',[hold.id,taxPayment,tax?.requestId||null,tax?.world||null,tax?.percent||0,amount.toString(),taxMinor.toString(),(amount-taxMinor).toString(),houseId,house?.id||null,clock()]); - return {replayed:false,taxMinor:Number(taxMinor),sellerNetMinor:Number(amount-taxMinor)}; + const rebateMinor=incentive?await incentive.service.rebate(tx,{purchaseId:hold.id,buyerId:actor.id,sellerId:seller.id,buyerAccountId:source.id,originWorld:incentive.world,grossMinor:amount}):0;return {replayed:false,taxMinor:Number(taxMinor),sellerNetMinor:Number(amount-taxMinor),...(incentive?{rebateMinor}:{})}; } }); } diff --git a/website/node/game-exchange-service.mjs b/website/node/game-exchange-service.mjs index be2260d6..20195576 100644 --- a/website/node/game-exchange-service.mjs +++ b/website/node/game-exchange-service.mjs @@ -14,7 +14,7 @@ export function exchangeListing(row){ if(!/^[1-9]\d{0,17}$/.test(String(row.id))||!Number.isSafeInteger(Number(row.quantity))||Number(row.quantity)<1||!/^\w{1,80}$/.test(row.material)||row.payload!==null&&(typeof row.payload!=='string'||row.payload.length>65536))throw new BankError('This listing is not supported.',409); return {id:String(row.id),sellerUuid:row.seller,seller:String(row.seller_name||'Seller').slice(0,32),title:String(row.display_name||row.material).slice(0,120),material:row.material,payload:row.payload,quantity:Number(row.quantity),priceMinor:exchangeMinor(row.price),origin:String(row.origin).slice(0,48)}; } -export function createGameExchangeService(bank,{gameSchema,authority,resolveSeller,revalidate=async actor=>actor,clock=Date.now,tradePolicy=async()=>({})}={}){ +export function createGameExchangeService(bank,{gameSchema,authority,resolveSeller,revalidate=async actor=>actor,clock=Date.now,tradePolicy=async()=>({}),incentives=null}={}){ if(!/^[a-z][a-z0-9_]{2,63}$/.test(gameSchema||''))throw Error('A verified game schema is required.'); const table=name=>'`'+gameSchema+'`.`'+name+'`',listings=table('dune_exchange_listings'),deliveries=table('dune_exchange_deliveries'),sales=table('dune_exchange_sales'); const payments=createGameExchangePayments(bank,authority,{clock}); @@ -44,7 +44,7 @@ export function createGameExchangeService(bank,{gameSchema,authority,resolveSell const paid=await tx.first('SELECT state,fingerprint FROM pb_orders WHERE id=?',[input.requestId]); if(paid?.state!=='posted'||paid.fingerprint!==exchangeFingerprint(prior))throw new BankError('The purchase requires reconciliation.',503); const levy=await tx.first('SELECT tax_minor,net_minor FROM pb_exchange_levies WHERE purchase_id=?',[input.requestId]); - return {...receipt(prior),taxMinor:Number(levy?.tax_minor||0),sellerNetMinor:levy?Number(levy.net_minor):Number(prior.unit_minor)*Number(prior.quantity),replayed:true}; + return {...receipt(prior),...(incentives?{rebateMinor:await incentives.replay(tx,input.requestId)}:{}),taxMinor:Number(levy?.tax_minor||0),sellerNetMinor:levy?Number(levy.net_minor):Number(prior.unit_minor)*Number(prior.quantity),replayed:true}; } const row=await tx.first('SELECT * FROM '+listings+' WHERE id=? FOR UPDATE',[input.listingId]); if(!row)throw new BankError('That listing was sold or withdrawn. Refresh the Exchange.',409); @@ -56,12 +56,12 @@ export function createGameExchangeService(bank,{gameSchema,authority,resolveSell const current=await revalidate(actor,player);if(!current||current.id!==actor.id)throw new BankError('Your current Exchange authority is unavailable.',403); const seller=await resolveSeller(offer.sellerUuid);if(!seller||seller.id===actor.id)throw new BankError('The seller is not linked to an eligible personal account.',409); const order={id:input.requestId,buyer_uuid:player,buyer_account_id:actor.id,seller_uuid:offer.sellerUuid,listing_id:offer.id,quantity:input.amount,unit_minor:offer.priceMinor,payload_hash:createHash('sha256').update(row.material+'\n'+(row.payload||'')).digest('hex'),display_name:offer.title}; - const settlement=await payments.post(tx,current,seller,order,rule?{...rule,requestId:rule.taxRequestId}:null); + const settlement=await payments.post(tx,current,seller,order,rule?{...rule,requestId:rule.taxRequestId}:null,incentives?{service:incentives,world}:null); if(offer.quantity===input.amount)await tx.query('DELETE FROM '+listings+' WHERE id=?',[offer.id]); else await tx.query('UPDATE '+listings+' SET quantity=quantity-? WHERE id=?',[input.amount,offer.id]); await tx.query('INSERT INTO '+deliveries+'(id,buyer_uuid,buyer_account_id,seller_uuid,listing_id,quantity,unit_minor,material,payload,payload_hash,display_name,origin,state,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,\'queued\',?)',[order.id,player,actor.id,offer.sellerUuid,offer.id,input.amount,offer.priceMinor,offer.material,offer.payload,order.payload_hash,offer.title,offer.origin,clock()]); await tx.query('INSERT INTO '+sales+'(listing_id,seller,seller_name,buyer,buyer_name,material,display_name,quantity,unit_price,total_price,origin) VALUES(?,?,?,?,?,?,?,?,?,?,?)',[offer.id,offer.sellerUuid,offer.seller,player,actor.username,offer.material,offer.title,input.amount,(offer.priceMinor/100).toFixed(2),(offer.priceMinor*input.amount/100).toFixed(2),offer.origin]); - return {id:order.id,state:'queued',quantity:input.amount,totalMinor:offer.priceMinor*input.amount,taxMinor:settlement.taxMinor,sellerNetMinor:settlement.sellerNetMinor,replayed:false}; + return {id:order.id,state:'queued',quantity:input.amount,totalMinor:offer.priceMinor*input.amount,taxMinor:settlement.taxMinor,sellerNetMinor:settlement.sellerNetMinor,...(incentives?{rebateMinor:settlement.rebateMinor}:{}),replayed:false}; }); } }); diff --git a/website/node/game-exchange.mjs b/website/node/game-exchange.mjs index 60c9731a..5ac6200d 100644 --- a/website/node/game-exchange.mjs +++ b/website/node/game-exchange.mjs @@ -2,6 +2,7 @@ import {kitsetCatalogue} from './kitset-catalogue.mjs'; import {gameAuthorized,validUuid,json} from './game-link.mjs'; import {can} from './permissions.mjs'; import {createPostbankAuthority} from './postbank-authority.mjs'; +import {createExchangeIncentives,verifyExchangeIncentive} from './exchange-incentive.mjs'; import {createGameExchangeService} from './game-exchange-service.mjs'; import {BankError} from './postbank-service.mjs'; import {createBankTradePolicy} from './world-trade-governance.mjs'; @@ -26,7 +27,7 @@ export function createGameExchangeAPI(db,bank,pool,settings={},dependencies={}){ const tables=['dune_exchange_listings','dune_exchange_sales','dune_exchange_deliveries']; const engines=await bank.query('SELECT TABLE_NAME AS name,ENGINE AS engine FROM information_schema.TABLES WHERE TABLE_SCHEMA=? AND TABLE_NAME IN (?,?,?)',[url.pathname.slice(1),...tables]); if(engines.length!==tables.length||engines.some(row=>row.engine!=='InnoDB'||!tables.includes(row.name)))throw Error('Transactional Exchange tables required'); - service=createGameExchangeService(bank,{gameSchema:url.pathname.slice(1),tradePolicy:db.worldTradeEnabled?createBankTradePolicy(db,bank):undefined,authority:createPostbankAuthority(db,{bank}),resolveSeller:actorFor,revalidate:async(actor,player)=>{const fresh=await actorFor(player);return fresh?.id===actor.id&&await allowed(fresh)?fresh:null;}}); + service=createGameExchangeService(bank,{gameSchema:url.pathname.slice(1),tradePolicy:db.worldTradeEnabled?createBankTradePolicy(db,bank):undefined,incentives:db.exchangeIncentiveEnabled?createExchangeIncentives(bank,{verify:(pool,now)=>verifyExchangeIncentive(db,pool,now)}):null,authority:createPostbankAuthority(db,{bank}),resolveSeller:actorFor,revalidate:async(actor,player)=>{const fresh=await actorFor(player);return fresh?.id===actor.id&&await allowed(fresh)?fresh:null;}}); })().catch(error=>{storage=null;throw error;}); await storage; }; diff --git a/website/node/political-decisions.mjs b/website/node/political-decisions.mjs index 1d1274ce..79f228ee 100644 --- a/website/node/political-decisions.mjs +++ b/website/node/political-decisions.mjs @@ -1,3 +1,4 @@ +import {reserveExchangeIncentivePool} from './exchange-incentive.mjs'; import {reserveGuildSubsidyPool} from './guild-subsidy.mjs'; import {passageOrganisations,prepareOrganisationPassage} from './imperial-organisation-passage.mjs'; import {createHash,randomUUID} from 'node:crypto'; @@ -27,13 +28,13 @@ const fingerprint=x=>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==='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'; + 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':['guild-subsidy','exchange-incentive'].includes(d?.kind)?'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==='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)}; + 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}:['guild-subsidy','exchange-incentive'].includes(d.kind)?{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(['guild-subsidy','exchange-incentive'].includes(d.kind)&&(!Number.isSafeInteger(payload.amountMinor)||payload.amountMinord.poolMaxMinor))fail('Choose a funding 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); @@ -56,7 +57,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,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']}); + const clock=deps.clock||Date.now,banking=atomicBankAccess(db,bank,{verifyStorage:deps.verifyStorage,bankTables:['pb_guild_subsidies','pb_exchange_incentive_pools'],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=''){ @@ -69,11 +70,11 @@ 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==='guild-subsidy'?d.poolMinMinor: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=['guild-subsidy','exchange-incentive'].includes(d.kind)?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; - 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; + const pool=holder&&['guild-subsidy','exchange-incentive'].includes(d.kind)&&prior?await banking.view(db).first('SELECT * FROM '+(d.kind==='guild-subsidy'?'pb_guild_subsidies':'pb_exchange_incentive_pools')+' WHERE id=?',[prior.request_id]):null;const subsidyPool=pool?{amountMinor:String(pool.total_minor),spentMinor:String(pool.spent_minor),pendingMinor:String(pool.pending_minor||0),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){ @@ -92,7 +93,7 @@ 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 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 subsidy=['guild-subsidy','exchange-incentive'].includes(d.kind);const taxMeta=grant?.account||await b.first(d.kind==='guild-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||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; @@ -105,12 +106,12 @@ export function createPoliticalDecisions(db,bank,keys,deps={}){ 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=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.'); + 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 office 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=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(subsidy){const args={requestId,keyId,actorId:actor.id,sourceId:source.id,amountMinor:payload.amountMinor,expiresAt};if(d.kind==='guild-subsidy')receipt.subsidy=await reserveGuildSubsidyPool(b,args);else receipt.incentive=await reserveExchangeIncentivePool(b,args);}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 47ade7af..9d0a73f9 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 {EXCHANGE_INCENTIVE_SCHEMA} from './exchange-incentive.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'; @@ -27,7 +28,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);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;} + 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,...EXCHANGE_INCENTIVE_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 53f02124..9f68bcc7 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==='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('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(['guild-subsidy','exchange-incentive'].includes(d.kind)){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{ @@ -369,3 +369,8 @@ 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();}}); +import {readFileSync} from 'node:fs';import {originPayload} from './native-origin-fixture.mjs'; +import {createExchangeIncentives,verifyExchangeIncentive,EXCHANGE_INCENTIVE_SCHEMA} from '../node/exchange-incentive.mjs';import {createGameExchangeService} from '../node/game-exchange-service.mjs'; +async function incentiveFixture(){const f=await fixture('ordos');for(const sql of EXCHANGE_INCENTIVE_SCHEMA)await f.db.query(sql);f.db.exchangeIncentiveEnabled=true;const users=[f.people.Member,f.people.Other].map(u=>({...u,uuid:randomUUID()})),entities=users.map(u=>({id:entityId('person',u.id),kind:'person',key:u.id,name:u.username,canView:true,canPay:true,canActivate:true})),authority=async actor=>({entities:entities.filter(e=>e.key===actor.id)});for(let i=0;i(await f.db.first('SELECT a.id FROM pb_accounts a JOIN pb_clients c ON a.client_number=c.client_number WHERE c.entity_id=?',[entities[i].id])).id;await f.db.query('UPDATE pb_accounts SET balance_minor=50000 WHERE id=?',[await account(0)]);f.db.sqlite.exec("ATTACH DATABASE ':memory:' AS dunegameplay;CREATE TABLE dunegameplay.dune_exchange_listings(id INTEGER PRIMARY KEY,seller TEXT,seller_name TEXT,origin TEXT,category TEXT,material TEXT,quantity INT,price TEXT,payload TEXT,display_name TEXT);CREATE TABLE dunegameplay.dune_exchange_sales(id INTEGER PRIMARY KEY,listing_id INT,seller TEXT,seller_name TEXT,buyer TEXT,buyer_name TEXT,material TEXT,display_name TEXT,quantity INT,unit_price TEXT,total_price TEXT,origin TEXT);");const schema=readFileSync(new URL('../integrations/game-exchange-schema.sql',import.meta.url),'utf8').replace(/--[^\n]*\n/g,'').replaceAll('CREATE TABLE IF NOT EXISTS dune_','CREATE TABLE IF NOT EXISTS dunegameplay.dune_').replace(/,\s*INDEX exchange_delivery_pending\([^)]*\)/g,'').replaceAll(' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4','');f.db.sqlite.exec(schema);for(const [id,payload]of [[1,originPayload('sigma_draconis_iv')],[2,originPayload('arrakis')],[3,null]])await f.db.query('INSERT INTO dunegameplay.dune_exchange_listings VALUES(?,?,?,?,?,?,?,?,?,?)',[id,users[1].uuid,users[1].username,'sigma_draconis_iv','ores','DIAMOND',3,'100.00',payload,'Diamond']);const incentives=createExchangeIncentives(f.db,{verify:(pool,n)=>verifyExchangeIncentive(f.db,pool,n),clock:f.clock}),exchange=createGameExchangeService(f.db,{gameSchema:'dunegameplay',authority,resolveSeller:async uuid=>users.find(u=>u.uuid===uuid),clock:f.clock,incentives});const input={decisionId:'ORD-04',requestId:randomUUID(),sourceAccount:String(f.source.id),amountMinor:2000000,confirmed:true};const buy=id=>({requestId:randomUUID(),listingId:String(id),amount:1,priceMinor:10000});return {...f,users,account,incentives,exchange,input,buy};} +test('Ordos incentive pays a bounded rebate only on native verified goods, without changing seller price or inventing delivery',async()=>{const f=await incentiveFixture();try{const r=await f.service.execute(f.people.Owner,f.input);assert.equal(r.incentive.amountMinor,'2000000');assert.equal(r.xp,300);assert.equal((await f.db.first('SELECT reserved_minor FROM pb_accounts WHERE id=?',[f.source.id])).reserved_minor,2000000);const a=f.buy(1),p=await f.exchange.buy(f.users[0],f.users[0].uuid,a);assert.equal(p.rebateMinor,1000);assert.equal(p.totalMinor,10000);assert.equal(p.sellerNetMinor,10000);assert.equal((await f.exchange.buy(f.users[0],f.users[0].uuid,a)).rebateMinor,1000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[await f.account(0)])).balance_minor,41000);assert.equal((await f.db.first('SELECT balance_minor FROM pb_accounts WHERE id=?',[await f.account(1)])).balance_minor,10000);for(const id of [2,3])assert.equal((await f.exchange.buy(f.users[0],f.users[0].uuid,f.buy(id))).rebateMinor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_exchange_incentive_rebates')).n,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM dunegameplay.dune_exchange_deliveries')).n,3);f.setTime(r.expiresAt);await f.incentives.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 balance_minor FROM pb_accounts WHERE id=?',[f.source.id])).balance_minor,1999000);}finally{f.db.close();}}); +test('Exchange delivery/history rollback also rolls back reserved pool spending and rebate',async()=>{const f=await incentiveFixture();try{await f.service.execute(f.people.Owner,f.input);f.db.sqlite.exec("CREATE TRIGGER dunegameplay.fail_incentive_sale BEFORE INSERT ON dune_exchange_sales BEGIN SELECT RAISE(ABORT,'history fault');END;");await assert.rejects(f.exchange.buy(f.users[0],f.users[0].uuid,f.buy(1)),/history fault/);assert.equal((await f.db.first('SELECT spent_minor FROM pb_exchange_incentive_pools')).spent_minor,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_exchange_incentive_rebates')).n,0);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_orders')).n,0);}finally{f.db.close();}});