The Wild Update: complete web journal, staff permissions and Cookbook #657
|
|
@ -18,3 +18,6 @@ EXCHANGE_READ_TOKEN=
|
|||
# Optional private read-only PostgreSQL role for CP inventory/sales.
|
||||
# Never use the game writer role or publish this URL to browser code.
|
||||
DUNE_INVENTORY_DATABASE_URL=
|
||||
|
||||
# Enable only after the paired native Guild travel release is installed.
|
||||
GUILD_OPEN_TRAVEL=false
|
||||
|
|
|
|||
|
|
@ -0,0 +1,87 @@
|
|||
// Pure view-model for the mission journal: story arcs on the left, one mission on the right.
|
||||
// The server decides state, eligibility and rewards; nothing here grants anything.
|
||||
export const STATUS_LABEL=Object.freeze({done:'Done',ready:'Ready to claim',active:'Active',available:'Available',locked:'Locked'});
|
||||
|
||||
export function questStatus(q){
|
||||
if(q.state==='claimed')return 'done';
|
||||
if(q.canClaim&&q.progress>=q.target)return 'ready';
|
||||
if(q.state==='completed')return 'ready';
|
||||
if(q.state==='active')return 'active';
|
||||
return q.canStart?'available':'locked';
|
||||
}
|
||||
const money=(q,v)=>q.metric?.endsWith('-minor')?(v/100).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2})+' DM':Number(v).toLocaleString('en-US');
|
||||
|
||||
/** Orders an arc so a quest never appears before the quests it requires; ties keep catalogue order. */
|
||||
export function orderArc(quests){
|
||||
const byId=new Map(quests.map(q=>[q.id,q])),placed=new Set(),out=[];
|
||||
const place=q=>{if(placed.has(q.id))return;placed.add(q.id);for(const id of [...(q.requires||[]),...(q.requiresAny||[])]){const parent=byId.get(id);if(parent)place(parent);}out.push(q);};
|
||||
quests.forEach(place);return out;
|
||||
}
|
||||
|
||||
export function buildJournal(data,{arcTitles={}}={}){
|
||||
const quests=Array.isArray(data?.quests)?data.quests:[],order=[],groups=new Map();
|
||||
for(const q of quests){if(!groups.has(q.branch)){groups.set(q.branch,[]);order.push(q.branch);}groups.get(q.branch).push(q);}
|
||||
const titles=new Map([...(data?.branches||[]).map(b=>[b.id,b.title]),...Object.entries(arcTitles)]);
|
||||
const names=new Map(quests.map(q=>[q.id,q.title]));
|
||||
const arcs=order.map(id=>{
|
||||
const list=orderArc(groups.get(id)).map(q=>{
|
||||
const status=questStatus(q),missing=(q.requires||[]).filter(r=>names.has(r)&&quests.find(x=>x.id===r)?.state!=='claimed');
|
||||
return {...q,status,statusLabel:STATUS_LABEL[status],lockedBy:status==='locked'&&missing.length?'Complete '+names.get(missing[0])+' first.':null};
|
||||
});
|
||||
const done=list.filter(q=>q.status==='done').length;
|
||||
return {id,title:titles.get(id)||String(id).toUpperCase(),quests:list,done,total:list.length,complete:done===list.length};
|
||||
});
|
||||
return {arcs,all:arcs.flatMap(a=>a.quests)};
|
||||
}
|
||||
|
||||
/** Chosen mission: the player's pick, else the tracked one, else whatever needs attention first. */
|
||||
export function pickSelection(journal,{preferred=null,tracked=null}={}){
|
||||
const has=id=>id&&journal.all.some(q=>q.id===id);
|
||||
if(has(preferred))return preferred;if(has(tracked))return tracked;
|
||||
for(const status of ['ready','active','available'])for(const q of journal.all)if(q.status===status)return q.id;
|
||||
return journal.all[0]?.id||null;
|
||||
}
|
||||
/** The next unfinished mission in the same arc after the given one. */
|
||||
export function nextInArc(journal,id){
|
||||
const arc=journal.arcs.find(a=>a.quests.some(q=>q.id===id));if(!arc)return null;
|
||||
const index=arc.quests.findIndex(q=>q.id===id);
|
||||
return arc.quests.slice(index+1).find(q=>q.status!=='done')?.id||arc.quests.find(q=>q.status!=='done'&&q.id!==id)?.id||null;
|
||||
}
|
||||
export function advanceTracked(journal,id){
|
||||
return journal.all.find(q=>q.id===id)?.status==='done'?nextInArc(journal,id):id;
|
||||
}
|
||||
export function briefing(q,limit=220){
|
||||
const text=String(q.objective||'').replace(/\s+/g,' ').trim();if(!text)return 'Follow your objective below.';
|
||||
const sentence=text.match(/^.*?[.!?](?:\s|$)/)?.[0].trim()||text;
|
||||
return sentence.length>limit?sentence.slice(0,limit-1).trimEnd()+'…':sentence;
|
||||
}
|
||||
export function objectives(q){
|
||||
const target=Math.max(1,Number(q.target)||1),progress=Math.min(Number(q.progress)||0,target);
|
||||
return [{label:q.objective?briefing(q,120):q.title,progress,target,percent:Math.floor(progress*100/target),done:progress>=target,text:money(q,progress)+' / '+money(q,target)}];
|
||||
}
|
||||
export function rewards(q,{xpType='personal'}={}){
|
||||
const rows=[];
|
||||
if(Number.isSafeInteger(q.xp))rows.push({label:xpType==='pol'?'Reputation':'Experience',value:q.xp.toLocaleString('en-US')+' XP'});
|
||||
if(Number.isSafeInteger(q.personalXP))rows.push({label:'Personal experience',value:q.personalXP.toLocaleString('en-US')+' XP'});
|
||||
if(Number.isSafeInteger(q.baseDMMinor))rows.push({label:'Base funded reward',value:(q.baseDMMinor/100).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2})+' DM'});
|
||||
if(!q.rewardConfigured)rows.push({label:'Reward',value:'Not configured yet'});
|
||||
return rows;
|
||||
}
|
||||
/** Which single button the selected mission offers: Track always, Claim only when something is unpaid, Start when it can begin. */
|
||||
export function actions(q,{tracked=null}={}){
|
||||
const list=[{kind:'track',label:tracked===q.id?'Tracking':'Track',disabled:q.status==='done'||q.status==='locked'}];
|
||||
if(q.status==='ready'&&q.canClaim)list.push({kind:'claim',label:'Claim reward'});
|
||||
else if(q.status==='available'&&q.canStart)list.push({kind:'start',label:'Start mission'});
|
||||
return list;
|
||||
}
|
||||
/** The sidebar shows the tracked mission's current objective, or the first active one when nothing is tracked. */
|
||||
export function currentObjective(journal,tracked){
|
||||
const q=journal.all.find(x=>x.id===tracked&&x.status!=='done')||journal.all.find(x=>x.status==='active')||journal.all.find(x=>x.status==='ready')||null;
|
||||
if(!q)return null;const o=objectives(q)[0];return {id:q.id,title:q.title,objective:o.label,text:o.text,percent:o.percent,ready:q.status==='ready'};
|
||||
}
|
||||
/** Missions that moved forward between two loads, for the objective-complete banner. */
|
||||
export function completions(previous,journal){
|
||||
if(!previous)return [];const before=new Map(previous.all.map(q=>[q.id,q.status])),out=[];
|
||||
for(const q of journal.all){const was=before.get(q.id);if(was&&was!=='ready'&&was!=='done'&&(q.status==='ready'||q.status==='done'))out.push({id:q.id,title:q.title,claimed:q.status==='done'});}
|
||||
return out;
|
||||
}
|
||||
25
website/control-panel/public/cp-v2/cp-v2-mission-journal.css
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
.mj{display:grid;gap:.9rem}
|
||||
.mj-banner{display:flex;gap:.8rem;align-items:center;justify-content:space-between;padding:.7rem 1rem;border:1px solid var(--accent,#d7a548);border-radius:.5rem;background:rgba(215,165,72,.12)}
|
||||
.mj-current{display:grid;gap:.25rem;padding:.7rem 1rem;border-left:4px solid var(--accent,#d7a548);background:rgba(255,255,255,.04);border-radius:.4rem}
|
||||
.mj-current progress,.mj-objectives progress{width:100%;height:.6rem}
|
||||
.mj-layout{display:grid;grid-template-columns:minmax(14rem,22rem) 1fr;gap:1rem;align-items:start}
|
||||
@media(max-width:46rem){.mj-layout{grid-template-columns:1fr}}
|
||||
.mj-arcs{display:grid;gap:.5rem}
|
||||
.mj-arc{border:1px solid rgba(255,255,255,.14);border-radius:.5rem;padding:.25rem .5rem}
|
||||
.mj-arc summary{display:flex;justify-content:space-between;gap:.5rem;cursor:pointer;padding:.4rem .2rem;font-weight:600}
|
||||
.mj-arc ol{list-style:none;margin:0;padding:0 0 .3rem;display:grid;gap:.2rem}
|
||||
.mj-mission{display:flex;flex-wrap:wrap;justify-content:space-between;gap:.2rem .6rem;width:100%;text-align:left;padding:.45rem .6rem;border-radius:.35rem;border:1px solid transparent;background:transparent;color:inherit;cursor:pointer}
|
||||
.mj-mission[aria-pressed=true]{border-color:var(--accent,#d7a548);background:rgba(215,165,72,.1)}
|
||||
.mj-mission[data-status=done]{opacity:.65}.mj-mission[data-status=done] span::before{content:"\2713\00a0"}
|
||||
.mj-mission[data-status=locked]{opacity:.5}.mj-mission[data-status=locked] span::before{content:"\1F512\00a0"}
|
||||
.mj-mission[data-status=ready] small:first-of-type,.mj-mission[data-status=active] small:first-of-type{color:var(--accent,#d7a548);font-weight:600}
|
||||
.mj-tracked{width:100%;font-style:italic}
|
||||
.mj-detail{display:grid;gap:.5rem;padding:1rem;border:1px solid rgba(255,255,255,.14);border-radius:.5rem}
|
||||
.mj-detail h3,.mj-detail h4{margin:.2rem 0}
|
||||
.mj-status{justify-self:start;padding:.1rem .6rem;border-radius:1rem;border:1px solid currentColor;font-size:.8rem}
|
||||
.mj-briefing{font-size:1.02rem;line-height:1.45}
|
||||
.mj-objectives{list-style:none;margin:0;padding:0;display:grid;gap:.6rem}
|
||||
.mj-objectives li{display:grid;gap:.2rem}
|
||||
.mj-objectives li[data-done=true] span::before{content:"\2713\00a0"}
|
||||
.mj-rewards{display:grid;grid-template-columns:auto 1fr;gap:.2rem 1rem;margin:0}.mj-rewards dd{margin:0;font-weight:600}
|
||||
.mj-actions{display:flex;gap:.6rem;flex-wrap:wrap;margin-top:.4rem}
|
||||
56
website/control-panel/public/cp-v2/cp-v2-mission-journal.mjs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {actions,briefing,currentObjective,nextInArc,objectives,rewards} from './cp-v2-mission-journal-model.mjs';
|
||||
|
||||
const bar=(percent,label)=>{const p=el('progress');p.max=100;p.value=percent;p.setAttribute('aria-label',label);return p;};
|
||||
const button=(text,fn,disabled=false)=>{const b=el('button',text);b.type='button';b.disabled=disabled;b.onclick=fn;return b;};
|
||||
|
||||
/** Draws the journal. Pure presentation: every action goes back through the handlers to the server. */
|
||||
export function renderMissionJournal(body,{journal,selected,tracked,banners=[],busy=false,xpType='personal',notice=''},{onSelect,onAct,onTrack,onSteps}){
|
||||
const root=el('div',undefined,'mj');
|
||||
for(const banner of banners){
|
||||
const note=el('div',undefined,'mj-banner');note.setAttribute('role','status');
|
||||
note.append(el('strong',(banner.claimed?'Mission complete: ':'Objective complete: ')+banner.title));
|
||||
const next=nextInArc(journal,banner.id);if(next)note.append(button('Next mission',()=>onSelect(next)));
|
||||
root.append(note);
|
||||
}
|
||||
if(notice){const n=el('p',notice,'progression-notice');n.setAttribute('role','alert');root.append(n);}
|
||||
const current=currentObjective(journal,tracked);
|
||||
const strip=el('div',undefined,'mj-current');
|
||||
if(current){strip.append(el('small','Current objective'),el('strong',current.title),el('span',current.objective+' — '+current.text),bar(current.percent,'Current objective progress'));if(current.ready)strip.append(el('em','Ready to claim'));}
|
||||
else strip.append(el('small','Current objective'),el('span','No active mission. Pick one from the list.'));
|
||||
root.append(strip);
|
||||
|
||||
const layout=el('div',undefined,'mj-layout'),nav=el('nav',undefined,'mj-arcs');nav.setAttribute('aria-label','Story arcs');
|
||||
for(const arc of journal.arcs){
|
||||
const group=el('details',undefined,'mj-arc');group.open=arc.quests.some(q=>q.id===selected)||(!arc.complete&&arc.quests.some(q=>q.status==='active'||q.status==='ready'))||journal.arcs.length===1;
|
||||
const head=el('summary');head.append(el('span',arc.title),el('small',arc.done+' / '+arc.total));group.append(head);
|
||||
const list=el('ol');
|
||||
for(const q of arc.quests){
|
||||
const item=el('li'),pick=button('',()=>onSelect(q.id));pick.className='mj-mission';pick.dataset.status=q.status;pick.setAttribute('aria-pressed',String(q.id===selected));
|
||||
pick.append(el('span',q.title),el('small',q.statusLabel));if(q.id===tracked&&q.status!=='done')pick.append(el('small','Tracked','mj-tracked'));
|
||||
item.append(pick);list.append(item);
|
||||
}
|
||||
group.append(list);nav.append(group);
|
||||
}
|
||||
layout.append(nav);
|
||||
|
||||
const q=journal.all.find(x=>x.id===selected),pane=el('section',undefined,'mj-detail');pane.setAttribute('aria-label','Selected mission');
|
||||
if(!q)pane.append(el('p','No missions are available yet.'));
|
||||
else{
|
||||
pane.append(el('h3',q.title),el('span',q.statusLabel,'mj-status'),el('p',briefing(q),'mj-briefing'));
|
||||
if(q.lockedBy)pane.append(el('p',q.lockedBy,'progression-notice'));
|
||||
if(q.cooldownUntil>Date.now())pane.append(el('p','Next available: '+new Date(q.cooldownUntil).toLocaleString(),'progression-notice'));
|
||||
pane.append(el('h4','Objectives'));const goals=el('ul',undefined,'mj-objectives');
|
||||
for(const o of objectives(q)){const row=el('li');row.dataset.done=String(o.done);row.append(el('span',o.label),el('small',o.text),bar(o.percent,o.label));goals.append(row);}
|
||||
pane.append(goals,el('h4','Rewards'));const prizes=el('dl',undefined,'mj-rewards');
|
||||
for(const r of rewards(q,{xpType})){prizes.append(el('dt',r.label),el('dd',r.value));}
|
||||
pane.append(prizes);
|
||||
const row=el('div',undefined,'mj-actions');
|
||||
for(const a of actions(q,{tracked})){
|
||||
row.append(button(a.label,a.kind==='track'?()=>onTrack(q.id):()=>onAct(q),a.disabled||busy||(a.kind==='track'&&q.id===tracked)));
|
||||
}
|
||||
if(onSteps)row.append(button("Mission steps",()=>onSteps(q),busy));
|
||||
pane.append(row);
|
||||
}
|
||||
layout.append(pane);root.append(layout);body.append(root);
|
||||
}
|
||||
|
|
@ -5,6 +5,8 @@ import {questArtwork,questChannel} from './cp-v2-quest-channels.mjs';
|
|||
import {renderProgressionHistory} from './cp-v2-progression-history.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {MISSION_BRANCHES} from './cp-v2-progression-catalogue.mjs';
|
||||
import {advanceTracked,buildJournal,completions,nextInArc,pickSelection} from './cp-v2-mission-journal-model.mjs';
|
||||
import {renderMissionJournal} from './cp-v2-mission-journal.mjs';
|
||||
|
||||
const art='https://www.dunerealms.com/assets/';
|
||||
const labels={claimed:'Reward claimed',completed:'Ready to claim',active:'In progress','not-started':'Not started'};
|
||||
|
|
@ -15,11 +17,16 @@ const date=n=>new Date(n).toLocaleString(undefined,{dateStyle:'medium',timeStyle
|
|||
|
||||
// The server supplies all state, eligibility and rewards. The browser sends only
|
||||
// the selected definition and its displayed revision, never XP or counters.
|
||||
export function mountPersonalProgression(host,{view='missions',fetcher=fetch,apiBase='/api/progression',onData=()=>{},onBranches=()=>{},externalBranches=false,onCareerNavigate=null,initialBranch='a',allowedBranches=null,artwork=null}={}){
|
||||
export function mountPersonalProgression(host,{view='missions',fetcher=fetch,apiBase='/api/progression',onData=()=>{},onBranches=()=>{},externalBranches=false,onCareerNavigate=null,initialBranch='a',allowedBranches=null,artwork=null,journal=true}={}){
|
||||
const controller=new AbortController(),status=el('p','Opening your mission journal…','progression-notice'),body=el('div');
|
||||
status.setAttribute('role','status');host.replaceChildren(status,body);
|
||||
let active=true,data=null,branch=initialBranch,selected=null,busy=false,uncertain=false,page=1,loadSequence=0,connectorObserver=null;
|
||||
let detailOpen=false;const dossier=createProgressionDialog(host,{onClose:()=>{detailOpen=false;}});
|
||||
const journalMode=journal!==false&&view==='missions';
|
||||
if(journalMode&&!document.querySelector('link[data-mission-journal]')){const link=el('link');link.rel='stylesheet';link.href=new URL('./cp-v2-mission-journal.css',import.meta.url).href;link.dataset.missionJournal='true';document.head.append(link);}
|
||||
const trackKey=()=>'dunerealms.tracked-mission:'+(data?.xpType==='pol'?'pol':'personal');let tracked=null,trackedLoaded=false,lastJournal=null,lastData=null,banners=[];
|
||||
const rememberTrack=id=>{tracked=id;try{if(id)localStorage.setItem(trackKey(),id);else localStorage.removeItem(trackKey());}catch{}try{window.dispatchEvent(new CustomEvent('dunerealms:tracked-mission'));}catch{}};
|
||||
const track=id=>{rememberTrack(id);render();};
|
||||
let detailOpen=false;const dossier=createProgressionDialog(host,{onClose:()=>{detailOpen=false;if(journalMode&&active)render();}});
|
||||
const requestIds=new Map();
|
||||
async function api(path,options={}){
|
||||
const response=await fetcher(apiBase+path,{credentials:'same-origin',cache:'no-store',signal:controller.signal,...options});
|
||||
|
|
@ -46,9 +53,19 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api
|
|||
function render(){
|
||||
connectorObserver?.disconnect();
|
||||
body.replaceChildren();if(!data)return;
|
||||
const reload=button('Reload journal',load);reload.className='progression-reload';reload.disabled=busy;body.append(reload);
|
||||
if(!journalMode){const reload=button('Reload journal',load);reload.className='progression-reload';reload.disabled=busy;body.append(reload);}
|
||||
if(view==='history'){renderProgressionHistory(body,data,{page,busy,onPrevious:()=>{page--;load();},onNext:()=>{page++;load();}});return;}
|
||||
if(data.state!=='active')return;
|
||||
if(journalMode&&!detailOpen){
|
||||
if(!trackedLoaded){trackedLoaded=true;try{tracked=localStorage.getItem(trackKey());}catch{tracked=null;}}
|
||||
const model=buildJournal(data);
|
||||
if(data!==lastData){banners=completions(lastJournal,model);lastData=data;lastJournal=model;const next=advanceTracked(model,tracked);if(next!==tracked)rememberTrack(next);}
|
||||
selected=pickSelection(model,{preferred:selected,tracked});
|
||||
const stats=el('div',undefined,'progression-stats');stats.append(el('strong',(data.xpType==='pol'?'Reputation level ':'Personal level ')+data.profile.level+(data.season.levelCap===null?' · uncapped':' / '+data.season.levelCap)));body.append(stats);
|
||||
onBranches(model.arcs.map(a=>({id:a.id,title:a.title})),branch);
|
||||
renderMissionJournal(body,{journal:model,selected,tracked,banners,busy,xpType:data.xpType,notice:uncertain?status.textContent:''},{onSelect:id=>{selected=id;banners=[];render();},onTrack:track,onSteps:row=>{branch=row.branch;selected=row.id;detailOpen=true;render();},onAct:row=>{const arcNext=()=>nextInArc(buildJournal(data),row.id);act(row).then(()=>{if(!selected||selected===row.id)selected=arcNext()||selected;if(active)render();});}});
|
||||
return;
|
||||
}
|
||||
const stats=el('div',undefined,'progression-stats');stats.append(el('strong',(data.xpType==='pol'?'Reputation level ':'Personal level ')+data.profile.level+(data.season.levelCap===null?' · uncapped':' / '+data.season.levelCap)),el('span',data.profile.effectiveXP.toLocaleString()+(data.xpType==='pol'?' reputation':' seasonal XP')),el('span','Season ends '+date(data.season.endsAt)));
|
||||
const progress=el('progress');progress.max=data.season.levelCap;progress.value=data.profile.level;progress.setAttribute('aria-label','Season level');if(data.season.levelCap!==null)stats.append(progress);body.append(stats);
|
||||
if(data.affiliations?.length){const affiliation=el('aside',undefined,'progression-intro');affiliation.append(el('strong','The Unmarked Caravan'),el('p','Your smuggler clan and company affiliations are secondary. Your ordinary affiliations stay in place.'));body.append(affiliation);}
|
||||
|
|
@ -75,5 +92,5 @@ export function mountPersonalProgression(host,{view='missions',fetcher=fetch,api
|
|||
const connect=()=>{if(!active||!tree.isConnected)return;const box=tree.getBoundingClientRect();svg.setAttribute('viewBox','0 0 '+box.width+' '+box.height);svg.replaceChildren();const cards=new Map([...tree.querySelectorAll('[data-mission-id]')].map(n=>[n.dataset.missionId,n]));for(const row of rows)for(const dependency of row.requires||[]){if(!cards.has(dependency))continue;const a=cards.get(dependency).getBoundingClientRect(),b=cards.get(row.id).getBoundingClientRect(),line=document.createElementNS(svg.namespaceURI,'path'),sameRow=Math.abs(a.top-b.top)<5,x1=(sameRow?a.right:a.left+a.width/2)-box.left,y1=(sameRow?a.top+a.height/2:a.bottom)-box.top,x2=(sameRow?b.left:b.left+b.width/2)-box.left,y2=(sameRow?b.top+b.height/2:b.top)-box.top;line.setAttribute('d',sameRow?`M ${x1} ${y1} H ${x2}`:`M ${x1} ${y1} V ${y1+14} H ${x2} V ${y2}`);svg.append(line);}};
|
||||
connectorObserver=new ResizeObserver(connect);connectorObserver.observe(tree);requestAnimationFrame(connect);
|
||||
}
|
||||
load();const dispose=()=>{active=false;dossier.dispose();connectorObserver?.disconnect();controller.abort();};dispose.selectBranch=id=>{if(active&&data?.quests?.some(q=>q.branch===id)){branch=id;selected=null;render();}};return dispose;
|
||||
load();const poll=journalMode?setInterval(()=>{if(active&&!busy&&!document.hidden)load();},30000):null;const dispose=()=>{active=false;if(poll)clearInterval(poll);dossier.dispose();connectorObserver?.disconnect();controller.abort();};dispose.selectBranch=id=>{if(active&&data?.quests?.some(q=>q.branch===id)){branch=id;const arc=buildJournal(data).arcs.find(a=>a.id===id);selected=arc?.quests.find(q=>q.status!=='done')?.id||arc?.quests[0]?.id||null;render();}};return dispose;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import {MISSION_BRANCHES} from './cp-v2-progression-catalogue.mjs';
|
||||
import {element as el} from './cp-v2-page-template.mjs';
|
||||
import {mentatFromDeeds,mentatFromCharacterChoice,systemPortrait,MENTAT_NAMES} from './cp-v2-mentat-portraits.mjs';
|
||||
export function xpReport(data){
|
||||
export function xpReport(data,{tracked=null}={}){
|
||||
if(data?.state!=='active'||!data.profile||!data.season)return null;
|
||||
const p=data.profile,s=data.season,level=p.level,xp=p.effectiveXP,base=s.curveBase;
|
||||
if(!Number.isSafeInteger(level)||level<1||!Number.isSafeInteger(xp)||xp<0)return null;
|
||||
|
|
@ -10,7 +10,7 @@ export function xpReport(data){
|
|||
const next=capped?null:start===null?null:base*level*(level+1)/2;
|
||||
const percent=capped?100:Number.isSafeInteger(start)&&Number.isSafeInteger(next)&&next>start?Math.max(0,Math.min(100,(xp-start)/(next-start)*100)):null;
|
||||
const quests=(data.quests||[]).filter(q=>q.keyId&&['active','completed'].includes(q.state));
|
||||
return {level,cap:s.levelCap,xp,totalXP:p.totalXP,reserveXP:p.reserveXP,nextXP:Number.isSafeInteger(next)?next:null,percent,capped,quest:quests[0]||null,activeCount:quests.length,season:s.id};
|
||||
return {level,cap:s.levelCap,xp,totalXP:p.totalXP,reserveXP:p.reserveXP,nextXP:Number.isSafeInteger(next)?next:null,percent,capped,quest:quests.find(q=>q.id===tracked)||quests[0]||null,activeCount:quests.length,season:s.id};
|
||||
}
|
||||
export function createProgressionSidebar(host,{fetcher=fetch,onBranch=()=>{},onNavigate=()=>{}}={}){
|
||||
const right=host.closest('#content')?.parentElement?.querySelector('#sidebar-right');
|
||||
|
|
@ -25,7 +25,7 @@ export function createProgressionSidebar(host,{fetcher=fetch,onBranch=()=>{},onN
|
|||
const adviser=el('div',undefined,'mentat-adviser'),name=mentat?MENTAT_NAMES[mentat.username]:'House adviser';adviser.append(portrait(mentat?.portrait||systemPortrait(''),'Portrait of '+name));
|
||||
const caption=el('div');if(mentat){const link=el('a',name);link.href='https://www.dunerealms.com/people/'+mentat.username;link.target='_top';caption.append(link,el('small',mentat.house));}else caption.append(el('strong',name),el('small',houseState==='loading'?'Opening House deed…':'House deed pending'));adviser.append(caption);summary.append(adviser);
|
||||
const citizen=el('div',undefined,'mentat-citizen');if(player?.username){const avatar=el('img');avatar.src='https://cp.dunerealms.com/api/avatars/face/member/'+encodeURIComponent(player.username);avatar.alt=player.username+' avatar';avatar.width=avatar.height=36;avatar.loading='lazy';avatar.onerror=()=>{avatar.replaceWith(portrait(systemPortrait(''),'Player portrait placeholder'));};citizen.append(avatar,el('span',player.name||player.username));}else citizen.append(portrait(systemPortrait(''),'Player portrait placeholder'),el('span','Your account'));summary.append(citizen);
|
||||
for(const [kind,label]of [['personal','Personal level'],['pol','Reputation level']]){const block=el('section',undefined,'mentat-xp mentat-xp-'+kind),data=journals.get(kind),report=xpReport(data);const title=el('h4'),link=el('a',label);link.href=href(kind,'missions');link.setAttribute('aria-current',currentKind===kind?'page':'false');link.onclick=event=>open(event,kind,'missions');title.append(link);block.append(title);
|
||||
for(const [kind,label]of [['personal','Personal level'],['pol','Reputation level']]){const block=el('section',undefined,'mentat-xp mentat-xp-'+kind),data=journals.get(kind),report=xpReport(data,{tracked:(()=>{try{return localStorage.getItem('dunerealms.tracked-mission:'+kind);}catch{return null;}})()});const title=el('h4'),link=el('a',label);link.href=href(kind,'missions');link.setAttribute('aria-current',currentKind===kind?'page':'false');link.onclick=event=>open(event,kind,'missions');title.append(link);block.append(title);
|
||||
const level=el('strong',report?String(report.level)+(report.cap===null?' · uncapped':' / '+report.cap):'—','mentat-level');block.append(level);
|
||||
const progress=el('progress');progress.max=100;progress.value=report?.percent??0;progress.setAttribute('aria-label',label+' progress towards next level');if(report?.percent===null||!report)progress.className='mentat-placeholder';block.append(progress);
|
||||
block.append(el('p',report?format(report.xp)+(report.nextXP!==null?' / '+format(report.nextXP):'')+(kind==='pol'?' reputation':' XP')+(report.capped?' · season cap reached':''):(kind==='pol'?'Reputation —':'XP —'),'mentat-xp-value'));
|
||||
|
|
@ -47,5 +47,6 @@ export function createProgressionSidebar(host,{fetcher=fetch,onBranch=()=>{},onN
|
|||
render();renderViews();directory.hidden=true;
|
||||
ensureJournal('pol');
|
||||
void (async()=>{try{let choice=null;try{choice=await read('/api/account/character');}catch{}if(!alive)return;mentat=mentatFromCharacterChoice(choice);if(!mentat){const deeds=await read('/api/politics/workspace');if(!alive)return;mentat=mentatFromDeeds(deeds.organisations);}houseState='loaded';render();}catch{if(alive){houseState='unavailable';render();}}})();
|
||||
return {available:true,setJournal,setBranches(rows,id){branchRows=rows;branchId=id;renderBranches();},showBranches(show){directory.hidden=!show||!branchRows.length;if(directoryBanner)directoryBanner.hidden=!show;},setNavigation(kind,view){currentKind=kind;currentView=view;updateBranches();if(view!=='missions')ensureJournal(kind);render();renderViews();},dispose(){alive=false;controller.abort();summary.remove();journalMenu.remove();directory.remove();if(directoryBanner&&left&&right.isConnected){directoryBanner.hidden=false;right.insertBefore(directoryBanner,bannerNext?.parentNode===right?bannerNext:null);}}};
|
||||
const onTracked=()=>render();if(typeof window!=='undefined')window.addEventListener('dunerealms:tracked-mission',onTracked);
|
||||
return {available:true,setJournal,setBranches(rows,id){branchRows=rows;branchId=id;renderBranches();},showBranches(show){directory.hidden=!show||!branchRows.length;if(directoryBanner)directoryBanner.hidden=!show;},setNavigation(kind,view){currentKind=kind;currentView=view;updateBranches();if(view!=='missions')ensureJournal(kind);render();renderViews();},dispose(){alive=false;if(typeof window!=='undefined')window.removeEventListener('dunerealms:tracked-mission',onTracked);controller.abort();summary.remove();journalMenu.remove();directory.remove();if(directoryBanner&&left&&right.isConnected){directoryBanner.hidden=false;right.insertBefore(directoryBanner,bannerNext?.parentNode===right?bannerNext:null);}}};
|
||||
}
|
||||
|
|
|
|||
BIN
website/data/cookbook/icons/spice_blast_furnace.png
Normal file
|
After Width: | Height: | Size: 912 B |
BIN
website/data/cookbook/icons/spice_campfire.png
Normal file
|
After Width: | Height: | Size: 1.3 KiB |
BIN
website/data/cookbook/icons/spice_coal.png
Normal file
|
After Width: | Height: | Size: 1.1 KiB |
BIN
website/data/cookbook/icons/spice_furnace.png
Normal file
|
After Width: | Height: | Size: 807 B |
BIN
website/data/cookbook/icons/spice_smoker.png
Normal file
|
After Width: | Height: | Size: 882 B |
BIN
website/data/cookbook/icons/spice_soul_campfire.png
Normal file
|
After Width: | Height: | Size: 1.4 KiB |
BIN
website/data/cookbook/icons/spice_tender.png
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
|
|
@ -217,6 +217,104 @@
|
|||
"quality": "rare",
|
||||
"equipmentMark": 8,
|
||||
"source": "material grade:SEA_LANTERN"
|
||||
},
|
||||
"spice_furnace": {
|
||||
"material": "furnace",
|
||||
"quality": "common",
|
||||
"equipmentMark": 2,
|
||||
"baseEquipmentMark": 1,
|
||||
"source": "spiceCookersAndRails"
|
||||
},
|
||||
"spice_smoker": {
|
||||
"material": "smoker",
|
||||
"quality": "uncommon",
|
||||
"equipmentMark": 3,
|
||||
"baseEquipmentMark": 2,
|
||||
"source": "spiceCookersAndRails"
|
||||
},
|
||||
"spice_blast_furnace": {
|
||||
"material": "blast_furnace",
|
||||
"quality": "uncommon",
|
||||
"equipmentMark": 3,
|
||||
"baseEquipmentMark": 2,
|
||||
"source": "spiceCookersAndRails"
|
||||
},
|
||||
"spice_campfire": {
|
||||
"material": "campfire",
|
||||
"quality": "uncommon",
|
||||
"equipmentMark": 5,
|
||||
"baseEquipmentMark": 4,
|
||||
"source": "spiceCookersAndRails"
|
||||
},
|
||||
"spice_soul_campfire": {
|
||||
"material": "soul_campfire",
|
||||
"quality": "uncommon",
|
||||
"equipmentMark": 4,
|
||||
"baseEquipmentMark": 3,
|
||||
"source": "spiceCookersAndRails"
|
||||
},
|
||||
"spice_coal": {
|
||||
"material": "coal",
|
||||
"quality": "uncommon",
|
||||
"equipmentMark": 4,
|
||||
"baseEquipmentMark": 3,
|
||||
"source": "spiceCookersAndRails"
|
||||
},
|
||||
"spice_tender": {
|
||||
"material": "chest_minecart",
|
||||
"quality": "uncommon",
|
||||
"equipmentMark": 5,
|
||||
"baseEquipmentMark": 4,
|
||||
"source": "spiceCookersAndRails"
|
||||
}
|
||||
},
|
||||
"additionalSources": {
|
||||
"spiceCookersAndRails": {
|
||||
"sourceRepository": "unimatrix/plugins",
|
||||
"sourceCommit": "13a8f23247497ac5cd9d59b6869e19097ee307be",
|
||||
"files": {
|
||||
"network/content-assets/cookbook/spice-crafting.json": "9e5f7bf35f3886dd4e8a78d313075ce4ab8193d2e05546c4bc2028929c2e6c91",
|
||||
"JarvisConnector/src/main/java/com/dunerealms/jarvis/SpiceFurnaces.java": "d30ea6b51e5f3b17db8f847d9325042ae2b495356ed4214ef4799891063c9fea",
|
||||
"JarvisConnector/src/main/resources/item-templates.json": "0eeda8b713de1912cd1dbd2d1c5d93cda2ecdf69a45f5c54974269971a464b5d",
|
||||
"vendor/minecart-trains/spice-coal.patch": "a71e6a7c0c1f565006e0a23d4e71365785aa3d52fd2ded00d83b827a1763775b"
|
||||
},
|
||||
"icons": {
|
||||
"spice_furnace": {
|
||||
"path": "icons/spice_furnace.png",
|
||||
"sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_furnace.png",
|
||||
"sha256": "695e2828feecd30e5bfdd7b5910d548069f3686d4814a7ef619e83fbf21d43b0"
|
||||
},
|
||||
"spice_smoker": {
|
||||
"path": "icons/spice_smoker.png",
|
||||
"sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_smoker.png",
|
||||
"sha256": "cda6b0f98a364a7d601037858107fbd37d67cce35f9e41b6c0f16d88eed8e4c0"
|
||||
},
|
||||
"spice_blast_furnace": {
|
||||
"path": "icons/spice_blast_furnace.png",
|
||||
"sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_blast_furnace.png",
|
||||
"sha256": "007b5adba64020e4381b39e1c5251b7b0a8c6d4dabd18fb94a6947b15615634d"
|
||||
},
|
||||
"spice_campfire": {
|
||||
"path": "icons/spice_campfire.png",
|
||||
"sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_campfire.png",
|
||||
"sha256": "3c1cbe1b7714ff8d310c146fcf24deb6400e93fe4757d0d044eb6f034118641f"
|
||||
},
|
||||
"spice_soul_campfire": {
|
||||
"path": "icons/spice_soul_campfire.png",
|
||||
"sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_soul_campfire.png",
|
||||
"sha256": "9fdb25e9035314bd95326aec07dc044acba1de416e211ed837077930487035a5"
|
||||
},
|
||||
"spice_coal": {
|
||||
"path": "icons/spice_coal.png",
|
||||
"sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_coal.png",
|
||||
"sha256": "228ead2784f3b7b0179b2daf0329e69683805d96c7e50182e3d61fe36b323d70"
|
||||
},
|
||||
"spice_tender": {
|
||||
"path": "icons/spice_tender.png",
|
||||
"sourcePath": "network/resource-pack/central/overlay/assets/dunerealms/textures/item/crafting/spice_tender.png",
|
||||
"sha256": "3c573a0831320ca23172f31dc4ee43656af4abab25dc50bf1e6915cf90423310"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
72
website/data/cookbook/spice-crafting.json
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
[
|
||||
{
|
||||
"id": "spice_furnace",
|
||||
"name": "Spice-Infused Furnace",
|
||||
"material": "FURNACE",
|
||||
"baseMark": 1,
|
||||
"mark": 2,
|
||||
"quality": "common",
|
||||
"ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Furnace",
|
||||
"details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast."
|
||||
},
|
||||
{
|
||||
"id": "spice_smoker",
|
||||
"name": "Spice-Infused Smoker",
|
||||
"material": "SMOKER",
|
||||
"baseMark": 2,
|
||||
"mark": 3,
|
||||
"quality": "uncommon",
|
||||
"ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Smoker",
|
||||
"details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast."
|
||||
},
|
||||
{
|
||||
"id": "spice_blast_furnace",
|
||||
"name": "Spice-Infused Blast Furnace",
|
||||
"material": "BLAST_FURNACE",
|
||||
"baseMark": 2,
|
||||
"mark": 3,
|
||||
"quality": "uncommon",
|
||||
"ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Blast Furnace",
|
||||
"details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast."
|
||||
},
|
||||
{
|
||||
"id": "spice_campfire",
|
||||
"name": "Spice-Infused Campfire",
|
||||
"material": "CAMPFIRE",
|
||||
"baseMark": 4,
|
||||
"mark": 5,
|
||||
"quality": "uncommon",
|
||||
"ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Campfire",
|
||||
"details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast."
|
||||
},
|
||||
{
|
||||
"id": "spice_soul_campfire",
|
||||
"name": "Spice-Infused Soul Campfire",
|
||||
"material": "SOUL_CAMPFIRE",
|
||||
"baseMark": 3,
|
||||
"mark": 4,
|
||||
"quality": "uncommon",
|
||||
"ingredients": "4 Iron Ingots · 4 raw Melange Spice · 1 Soul Campfire",
|
||||
"details": "Put the vanilla cooker in the centre, spice on the four sides, and iron in the corners. Cooks twice as fast."
|
||||
},
|
||||
{
|
||||
"id": "spice_coal",
|
||||
"name": "Spice Coal",
|
||||
"material": "COAL",
|
||||
"baseMark": 3,
|
||||
"mark": 4,
|
||||
"quality": "uncommon",
|
||||
"ingredients": "1 raw Melange Spice · 1 Coal or Charcoal",
|
||||
"details": "Shapeless recipe. Fuels cookers and furnace minecarts."
|
||||
},
|
||||
{
|
||||
"id": "spice_tender",
|
||||
"name": "Spice Fuel Cart",
|
||||
"material": "CHEST_MINECART",
|
||||
"baseMark": 4,
|
||||
"mark": 5,
|
||||
"quality": "uncommon",
|
||||
"ingredients": "1 Minecart · 1 Spice Coal",
|
||||
"details": "Shapeless recipe. A fuel cart for Spice Coal."
|
||||
}
|
||||
]
|
||||
|
|
@ -7,6 +7,11 @@ import {gameAuthorized,validUuid,json} from './game-link.mjs';
|
|||
import {boardingOpen} from './game-organisation-policy.mjs';
|
||||
import {createPostbankAuthority} from './postbank-authority.mjs';
|
||||
import {createGuildPassageLedger} from './guild-passage-ledger.mjs';
|
||||
import {paidTariff,effectiveTrips,classifyRoute,BOUNTY_MULTIPLIER} from './travel-tariff.mjs';
|
||||
import {createNativeHoldingCheck} from './travel-holdings.mjs';
|
||||
import {createTravelBountyClaims,TRAVEL_BOUNTY_CLAIM_SCHEMA} from './travel-bounty-claims.mjs';
|
||||
export {TRAVEL_BOUNTY_CLAIM_SCHEMA};
|
||||
export const TRAVEL_OPEN_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_guild_open_passages(id CHAR(36) PRIMARY KEY,source_world VARCHAR(32) NOT NULL,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
|
||||
import {createOwnedSmugglerRoutes} from './owned-smuggler-routes.mjs';
|
||||
import {createOwnedSmugglerPassages} from './owned-smuggler-passages.mjs';
|
||||
import {validOwnedSmugglerRequest} from './owned-smuggler-request.mjs';
|
||||
|
|
@ -22,15 +27,46 @@ export const GUILD_SCHEMA=`CREATE TABLE IF NOT EXISTS pb_guild_passages(id CHAR(
|
|||
export const SMUGGLER_PASSAGE_SCHEMA="CREATE TABLE IF NOT EXISTS pb_smuggler_passages(id CHAR(36) PRIMARY KEY,permit_key CHAR(36) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
|
||||
const routes={atreides:'caladan',harkonnen:'giedi_prime',corrino:'kaitain',ordos:'sigma_draconis_iv',fremen:'arrakis'};
|
||||
const fail=(message,status=409)=>{throw new BankError(message,status);};
|
||||
export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null,routeBindings=false,homeRoutes=null,authorityForStore=null}={}){
|
||||
export const TRAVEL_LADDER_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_ladder(actor_id CHAR(36) PRIMARY KEY,trips INT NOT NULL,last_paid_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
|
||||
export const TRAVEL_BOUNTY_SCHEMA="CREATE TABLE IF NOT EXISTS pb_travel_bounties(id CHAR(36) PRIMARY KEY,actor_id CHAR(36) NOT NULL,minecraft_uuid CHAR(36) NOT NULL,traveller VARCHAR(64) NOT NULL,world VARCHAR(32) NOT NULL,fare_minor BIGINT NOT NULL,amount_minor BIGINT NOT NULL,state VARCHAR(12) NOT NULL,created_at BIGINT NOT NULL,claimed_by CHAR(36) NULL,claimed_at BIGINT NULL,claim_request CHAR(36) NULL UNIQUE,INDEX travel_bounty_open(minecraft_uuid,state,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
|
||||
export function createGuildService(bank,{authority,resolve,allowArrakis=async()=>false,recordArrival=async()=>{},allowJourney=async()=>true,clock=Date.now,fareMinor=10000,surcharge=async()=>0,discount=async()=>0,openTravel=false,holdingOnWorld=async()=>false,allowSmuggling=null,smugglerFareMinor=fareMinor,prologueReady=async()=>true,subsidies=null,routeBindings=false,homeRoutes=null,authorityForStore=null}={}){
|
||||
if(!Number.isSafeInteger(fareMinor)||fareMinor<1||fareMinor>100000000||!Number.isSafeInteger(smugglerFareMinor)||smugglerFareMinor<1||smugglerFareMinor>100000000)throw Error('Invalid Guild fare');
|
||||
const ledger=createGuildPassageLedger(bank,{authority,clock,subsidies}),{funds,release,reserve,settle}=ledger;
|
||||
const ledger=createGuildPassageLedger(bank,{authority,clock,subsidies}),{funds,release,reserve,settle,payout}=ledger;
|
||||
async function quotedFare(user,store=bank,lock=false){const percent=await surcharge(clock()),reduction=await discount(user.faction,clock());const normal=standardGuildFare(fareMinor,percent,reduction);if(normal===null)fail('The Guild tariff requires review.',503);const offer=subsidies?await subsidies.quote(store,normal,reduction,lock):null;return {price:offer?.price??normal,offer};}
|
||||
const view=r=>({requestId:r.id,destination:r.destination,state:r.state,fareMinor:Number(r.fare_minor),expiresAt:Number(r.expires_at)});
|
||||
const readyForTravel=async(user,uuid,store=bank)=>await prologueReady(user,uuid)||!!await store.first("SELECT id FROM pb_guild_passages WHERE actor_id=? AND minecraft_uuid=? AND state='arrived' LIMIT 1",[user.id,uuid]);
|
||||
const allowed=async(user,destination)=>!!routes[user?.faction]&&(destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user));
|
||||
const allowed=async(user,destination)=>!!routes[user?.faction]&&(openTravel?Object.values(routes).includes(destination):destination===routes[user.faction]||destination==='arrakis'&&await allowArrakis(user.faction,user));
|
||||
async function expire(){const expired=await bank.transaction(async tx=>{const rows=await tx.query("SELECT * FROM pb_guild_passages WHERE state='pending' AND expires_at<=? ORDER BY id LIMIT 25 FOR UPDATE",[clock()]);for(const r of rows)await release(tx,r);return rows.length;});if(subsidies)await subsidies.expire();return expired;}
|
||||
|
||||
// ---- Open travel: race world and Lobby are free, every other world is paid and carries a bounty ----
|
||||
async function tariff(user,uuid,destination,store,lock=false){
|
||||
const decree=destination==='arrakis'&&await allowArrakis(user.faction,user),route=classifyRoute({destination,raceWorld:routes[user.faction],decree});
|
||||
if(route.free)return{free:true,reason:route.reason,fareMinor:0,bountyMinor:0};
|
||||
const row=await store.first('SELECT trips,last_paid_at FROM pb_travel_ladder WHERE actor_id=?'+(lock?' FOR UPDATE':''),[user.id]);
|
||||
const trips=effectiveTrips(row?.trips??0,row?.last_paid_at??null,clock());
|
||||
return{free:false,reason:'paid',...paidTariff({trips,reduced:await holdingOnWorld(user,uuid,destination,{fresh:lock})})};
|
||||
}
|
||||
async function recordTrip(tx,r,user){
|
||||
const fare=Number(r.fare_minor);if(fare<1)return; // a free passage carries no bounty and does not move the ladder
|
||||
const now=clock(),row=await tx.first('SELECT trips,last_paid_at FROM pb_travel_ladder WHERE actor_id=? FOR UPDATE',[user.id]),trips=effectiveTrips(row?.trips??0,row?.last_paid_at??null,now)+1;
|
||||
if(row)await tx.query('UPDATE pb_travel_ladder SET trips=?,last_paid_at=? WHERE actor_id=?',[trips,now,user.id]);else await tx.query('INSERT INTO pb_travel_ladder(actor_id,trips,last_paid_at) VALUES(?,?,?)',[user.id,trips,now]);
|
||||
await tx.query("INSERT INTO pb_travel_bounties(id,actor_id,minecraft_uuid,traveller,world,fare_minor,amount_minor,state,created_at) VALUES(?,?,?,?,?,?,?,'open',?)",[r.id,user.id,r.minecraft_uuid,String(user.username).slice(0,64),r.destination,fare,fare*BOUNTY_MULTIPLIER,now]);
|
||||
}
|
||||
async function quoteOpen(uuid,sourceWorld){
|
||||
await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);
|
||||
const ready=await readyForTravel(user,uuid),open=[],catalog=[];
|
||||
for(const world of TRADE_WORLDS){
|
||||
const t=await tariff(user,uuid,world.id,bank),journey=await allowJourney(sourceWorld,world.id,bank,false),source=ready&&journey&&t.fareMinor>0?await funds(bank,user,t.fareMinor):null;
|
||||
const reason=!ready?'Complete your House Prologue first.':world.id===tradeWorld(sourceWorld)?'Already on this world.':tradeWorld(sourceWorld)!=='lobby'?'Board ordinary passages from the Guild Lobby.':!journey?'The Spacing Guild has embargoed this route.':!boardingOpen(clock())?'Boarding opens at :00, :20 and :40 for five minutes.':t.fareMinor>0&&!source?'Not enough available Dunemarks.':'';
|
||||
if(!reason)open.push(world.id);
|
||||
catalog.push({server:world.id,name:world.name,available:!reason,reason,fareMinor:t.fareMinor,free:t.free,...(t.free?{freeReason:t.reason}:{bountyMinor:t.bountyMinor,reduced:t.reduced,trip:t.trip})});
|
||||
}
|
||||
const home=catalog.find(r=>r.server===routes[user.faction]);
|
||||
return{ok:true,openTravel:true,destination:routes[user.faction],destinations:open,routes:catalog,fareMinor:home?.fareMinor??0,affordable:open.length>0,...(!ready?{prologueRequired:true}:{})};
|
||||
}
|
||||
const bountyClaim=createTravelBountyClaims(bank,{resolve,clock,payout,enabled:()=>openTravel});
|
||||
async function quote(uuid,sourceWorld='lobby'){
|
||||
if(openTravel)return quoteOpen(uuid,sourceWorld);
|
||||
await expire();const user=await resolve(uuid);if(!user||!routes[user.faction])fail('Link your active website account and choose your House first.',403);
|
||||
const ready=await readyForTravel(user,uuid),{price,offer}=await quotedFare(user),source=ready?await funds(bank,user,price):null,open=[],catalog=[];
|
||||
for(const world of TRADE_WORLDS){const lawful=await allowed(user,world.id),journey=lawful&&await allowJourney(sourceWorld,world.id,bank,false);if(ready&&journey)open.push(world.id);
|
||||
|
|
@ -53,16 +89,18 @@ export function createGuildService(bank,{authority,resolve,allowArrakis=async()=
|
|||
const legacy=catalog.find(r=>r.server==='arrakis');return {ok:true,eligible:legacy.eligible,allowed:legacy.allowed,permitExpiresAt:legacy.permitExpiresAt,fareMinor:smugglerFareMinor,affordable:legacy.affordable,keyId:user.keyId,version:user.version,routes:catalog};
|
||||
}
|
||||
async function board(input,smuggler=false){await expire();const user=await resolve(input.uuid);if(!user||!routes[user.faction]||user.keyId!==input.keyId||user.version!==input.version)fail('Your House key changed. Reopen the Guild menu.',403);
|
||||
if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<1||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?!Object.values(routes).includes(destination)||!tradeWorld(input.sourceWorld)||destination===tradeWorld(input.sourceWorld)||!routeBindings&&(destination!=='arrakis'||input.sourceWorld!=='lobby'):!await allowed(user,destination))fail(smuggler?'A current smuggler passage is required.':'Your House has no Imperial passage for this destination.',403);const legacyFingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex'),fingerprint=smuggler&&routeBindings?createHash('sha256').update(JSON.stringify([legacyFingerprint,input.sourceWorld])).digest('hex'):legacyFingerprint;
|
||||
if(!await readyForTravel(user,input.uuid))fail('Complete your House Prologue before first passage.',403);if(!Number.isSafeInteger(input.fareMinor)||input.fareMinor<(openTravel&&!smuggler?0:1)||input.fareMinor>100000000)fail('Invalid Guild fare.',400);const destination=input.destination??routes[user.faction];if(smuggler?!Object.values(routes).includes(destination)||!tradeWorld(input.sourceWorld)||destination===tradeWorld(input.sourceWorld)||!routeBindings&&(destination!=='arrakis'||input.sourceWorld!=='lobby'):!await allowed(user,destination))fail(smuggler?'A current smuggler passage is required.':'Your House has no Imperial passage for this destination.',403);const legacyFingerprint=createHash('sha256').update(JSON.stringify([input.uuid,user.id,input.keyId,input.version,destination,input.fareMinor,...(smuggler?["smuggler"]:[])])).digest('hex'),fingerprint=smuggler&&routeBindings?createHash('sha256').update(JSON.stringify([legacyFingerprint,input.sourceWorld])).digest('hex'):legacyFingerprint;
|
||||
if(openTravel&&!smuggler&&tradeWorld(input.sourceWorld||'lobby')!=='lobby')fail('Board ordinary Guild passages from the Guild Lobby.',403);
|
||||
return bank.transaction(async tx=>{
|
||||
const prior=await tx.first('SELECT * FROM pb_guild_passages WHERE id=? FOR UPDATE',[input.requestId]);if(prior){const legacy=smuggler&&routeBindings&&destination==='arrakis'&&input.sourceWorld==='lobby'&&prior.fingerprint===legacyFingerprint&&!await tx.first('SELECT id FROM pb_guild_route_bindings WHERE id=?',[prior.id]);if(prior.actor_id!==user.id||prior.fingerprint!==fingerprint&&!legacy)fail('This passage reference was already used.');return{ok:true,...view(prior),...(smuggler?{smuggler:true}:{}),replayed:true};}
|
||||
const {price,offer}=smuggler?{price:smugglerFareMinor,offer:null}:await quotedFare(user,tx,true);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.');
|
||||
const openRoute=openTravel&&!smuggler?await tariff(user,input.uuid,destination,tx,true):null,{price,offer}=smuggler?{price:smugglerFareMinor,offer:null}:openRoute?{price:openRoute.fareMinor,offer:null}:await quotedFare(user,tx,true);if(input.fareMinor!==price)fail('The Guild fare changed. Reopen the passage menu.');
|
||||
if(!smuggler&&!await allowJourney(input.sourceWorld||'lobby',destination,tx,true))fail('The Spacing Guild has embargoed this world. Smuggler routes remain available.',403);
|
||||
if(!smuggler&&!boardingOpen(clock()))fail('Boarding opens at :00, :20 and :40 for five minutes.');
|
||||
const fresh=await resolve(input.uuid);if(!fresh||fresh.id!==user.id||fresh.keyId!==input.keyId||fresh.version!==input.version||!await readyForTravel(fresh,input.uuid,tx)||!smuggler&&!await allowed(fresh,destination))fail('Your House key or Imperial passage changed.',403);
|
||||
const permit=smuggler?await smugglerPermit(fresh,input.uuid,input.sourceWorld,tx,true,destination):null;if(smuggler&&!permit)fail("Meet Esmar Tuek for a current personal smuggler permission.",403);
|
||||
// Lock this customer's accounts before checking their other in-flight passage.
|
||||
const now=clock(),r=await reserve(tx,input,user,{price,fingerprint,destination,expiresAt:smuggler?Math.min(now+120000,permit.expiresAt):now+120000,permitKey:permit?.keyId||null,offer});
|
||||
if(openRoute)await tx.query('INSERT INTO pb_guild_open_passages(id,source_world,created_at) VALUES(?,?,?)',[r.id,'lobby',now]);
|
||||
if(smuggler&&routeBindings)await tx.query("INSERT INTO pb_guild_route_bindings(id,route_kind,source_world,created_at) VALUES(?,'esmar',?,?)",[r.id,input.sourceWorld,now]);return{ok:true,...view(r),...(smuggler?{smuggler:true}:{})};
|
||||
});
|
||||
}
|
||||
|
|
@ -73,14 +111,14 @@ export function createGuildService(bank,{authority,resolve,allowArrakis=async()=
|
|||
const marker=allowSmuggling?await tx.first('SELECT permit_key FROM pb_smuggler_passages WHERE id=? FOR UPDATE',[r.id]):null;r.smuggler=!!marker;if(r.state==='arrived')return r;
|
||||
if(Number(r.expires_at)<=clock()){await release(tx,r);return null;}
|
||||
if(user.keyId!==r.house_key||user.version!==Number(r.house_version)||!await readyForTravel(user,uuid,tx)||(marker?(await allowSmuggling(user,uuid,clock()))?.keyId!==marker.permit_key:!await allowed(user,r.destination)||!await allowJourney('lobby',r.destination,tx,true))){await release(tx,r);return null;}
|
||||
await settle(tx,r,user,!!marker);return r;
|
||||
await settle(tx,r,user,!!marker);if(openTravel&&!marker&&await tx.first('SELECT id FROM pb_guild_open_passages WHERE id=?',[r.id]))await recordTrip(tx,r,user);return r;
|
||||
});
|
||||
if(row){if(!row.smuggler)await recordArrival(user,row);await bank.query("UPDATE pb_guild_passages SET reported_at=? WHERE id=? AND state='arrived'",[clock(),row.id]);}return{ok:true,passage:row?{...view(row),...(row.smuggler?{smuggler:true}:{})}:null};
|
||||
if(row){if(!row.smuggler)await recordArrival(user,row);await bank.query("UPDATE pb_guild_passages SET reported_at=? WHERE id=? AND state='arrived'",[clock(),row.id]);}let bounty=null;if(row&&openTravel&&!row.smuggler&&Number(row.fare_minor)>0){const b=await bank.first('SELECT * FROM pb_travel_bounties WHERE id=?',[row.id]);if(b)bounty={requestId:b.id,traveller:b.traveller,world:b.world,amountMinor:Number(b.amount_minor),state:b.state};}return{ok:true,passage:row?{...view(row),...(row.smuggler?{smuggler:true}:{})}:null,...(bounty?{bounty}:{})};
|
||||
}
|
||||
async function checkTravel(uuid,source,destination){if(!await resolve(uuid))fail('A linked account is required.',403);return bank.transaction(async tx=>{if(!await allowJourney(source,destination,tx,true))fail('The Spacing Guild has embargoed journeys to and from this world. Smuggler routes remain available.',403);return{ok:true,source,destination,expiresAt:clock()+5000};});}
|
||||
async function smugglerReturn(uuid,source){const user=await resolve(uuid);if(!user||!Object.values(routes).includes(source)||!routeBindings&&source!=='arrakis'||!allowSmuggling)fail('Meet Esmar Tuek on the arrival world.',403);const r=await bank.first("SELECT p.id,s.permit_key"+(routeBindings?',b.source_world,b.route_kind':'')+" FROM pb_guild_passages p LEFT JOIN pb_smuggler_passages s ON s.id=p.id"+(routeBindings?' LEFT JOIN pb_guild_route_bindings b ON b.id=p.id':'')+" WHERE p.actor_id=? AND p.minecraft_uuid=? AND p.destination=? AND p.state='arrived'"+" ORDER BY p.arrived_at DESC,p.id DESC LIMIT 1",[user.id,uuid,source]);if(!r?.permit_key||r.route_kind==='owned-home')fail('No confirmed personal smuggler arrival is available for return.',403);const destination=tradeWorld(r.source_world||'lobby');if(!destination||destination===source)fail('The recorded return route requires review.');return{ok:true,source,destination,expiresAt:clock()+5000,smuggler:true};}
|
||||
const owned=routeBindings&&homeRoutes?createOwnedSmugglerPassages(bank,homeRoutes,{resolve,clock,price:smugglerFareMinor,ledger,expire,readyForTravel,authorityForStore}):{};
|
||||
return{quote,quoteSmuggler,board,arrive,expire,checkTravel,smugglerReturn,...owned};
|
||||
return{quote,quoteSmuggler,board,arrive,expire,checkTravel,smugglerReturn,bountyClaim,openTravel,...owned};
|
||||
}
|
||||
export function createGuildQuestReceipts(db,bank,keys,{clock=Date.now}={}){
|
||||
const authorize=metric=>async(_actor,p)=>{const row=await bank.first("SELECT * FROM pb_guild_passages WHERE id=? AND state='arrived' AND NOT EXISTS(SELECT 1 FROM pb_smuggler_passages s WHERE s.id=pb_guild_passages.id)",[p.eventId]);return !!row&&row.actor_id===p.accountId&&row.minecraft_uuid===p.minecraftUuid&&p.metric===metric&&p.quantity===1&&p.occurredAt===Number(row.arrived_at)&&p.reference===(metric==='guild-travel'?'guild:':'guild-route:')+row.id;};
|
||||
|
|
@ -91,7 +129,7 @@ export function createGameGuildAPI(db,bank,keys,settings={},dependencies={}){
|
|||
const resolve=dependencies.resolve||(async(uuid,store=db)=>{const rows=await store.query("SELECT a.id,a.username,a.role,c.faction,c.version,h.key_id keyId FROM site_accounts a JOIN site_game_links l ON l.user_id=a.id JOIN site_character_choices c ON c.user_id=a.id AND c.minecraft_uuid=l.minecraft_uuid JOIN jarvis_house_selections h ON h.account_id=a.id AND h.minecraft_uuid=l.minecraft_uuid AND h.version=c.version AND h.faction=c.faction JOIN organisation_keys k ON k.id=h.key_id AND k.revoked_at IS NULL AND (k.expires_at IS NULL OR k.expires_at>UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3))*1000) WHERE LOWER(l.minecraft_uuid)=? AND a.password_hash NOT LIKE '!%' AND a.role NOT IN ('system_account','official_account','memorial')",[uuid]);return rows.length===1?{...rows[0],version:Number(rows[0].version)}:null;});
|
||||
const tradePolicy=db?.worldTradeEnabled&&bank?createBankTradePolicy(db,bank):null;
|
||||
const allowJourney=async(source,destination,tx,lock)=>{if(!tradePolicy)return true;const policy=await tradePolicy(tx,Date.now(),lock);return ![source,destination].some(w=>policy[tradeWorld(w)]?.embargoUntil>Date.now());};
|
||||
const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,clock:dependencies.clock||Date.now,routeBindings:bank.guildRouteBindingsEnabled===true,authorityForStore:reader=>createPostbankAuthority(reader,{bank}),homeRoutes:db?.transaction?createOwnedSmugglerRoutes(db,{resolve,clock:dependencies.clock||Date.now}):null,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready,subsidies:db?.guildSubsidyEnabled?createGuildSubsidies(bank,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)}):null}):null);
|
||||
const service=dependencies.service||(bank?createGuildService(bank,{resolve,allowJourney,clock:dependencies.clock||Date.now,routeBindings:bank.guildRouteBindingsEnabled===true,authorityForStore:reader=>createPostbankAuthority(reader,{bank}),homeRoutes:db?.transaction?createOwnedSmugglerRoutes(db,{resolve,clock:dependencies.clock||Date.now}):null,surcharge:now=>currentGuildSurcharge(db,now),discount:(house,now)=>currentGuildDiscount(db,house,now),allowArrakis:async(house,user)=>await hasImperialPassage(db,house)||await hasOrganisationPassage(db,user),authority:createPostbankAuthority(db,{bank}),fareMinor:Number(settings.GUILD_FARE_MINOR||10000),openTravel:settings.GUILD_OPEN_TRAVEL==='true',holdingOnWorld:createNativeHoldingCheck(db),recordArrival:createGuildQuestReceipts(db,bank,keys),allowSmuggling:(user,uuid,now)=>activeSmugglerPermit(db,keys,user,uuid,now),smugglerFareMinor:Number(settings.SMUGGLER_FARE_MINOR||settings.GUILD_FARE_MINOR||10000),prologueReady:async(user,uuid)=>(await housePrologueState(db,keys,user,uuid)).ready,subsidies:db?.guildSubsidyEnabled?createGuildSubsidies(bank,{verify:(pool,now)=>verifyGuildSubsidy(db,pool,now)}):null}):null);
|
||||
return async request=>{
|
||||
if(!gameAuthorized(request,settings))return json({message:'Unauthorized'},401);
|
||||
if(request.method!=='POST'||new URL(request.url).search||!/^application\/json(?:;|$)/i.test(request.headers.get('content-type')||''))return json({message:'A JSON Guild action is required.'},400);
|
||||
|
|
@ -101,9 +139,9 @@ export function createGameGuildAPI(db,bank,keys,settings={},dependencies={}){
|
|||
if(!service||typeof service[b.action]!=='function')return json({message:'Home Block navigation is unavailable.'},503);
|
||||
try{const result=await service[b.action](b);return json(result,result.needsReview?409:200);}catch(error){return json({message:error instanceof BankError?error.message:'The passage could not be confirmed. Retry the original reference.'},error instanceof BankError?error.status||409:503);}
|
||||
}
|
||||
const fields={smuggler_return:['action','uuid','sourceWorld'],smuggler_quote:['action','uuid','sourceWorld'],smuggler_board:['action','uuid','requestId','keyId','version','fareMinor','sourceWorld','destination'],travel_check:['action','uuid','sourceWorld','destination'],quote:['action','uuid',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[])],board:['action','uuid','requestId','keyId','version','fareMinor',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[]),...(Object.hasOwn(b||{},'destination')?['destination']:[])],arrive:['action','uuid','server'],expire:['action']}[b?.action];
|
||||
if((Object.hasOwn(b||{},'sourceWorld')&&!tradeWorld(b.sourceWorld))||b?.action==='travel_check'&&b.destination!=='lobby'||!fields||Object.keys(b).length!==fields.length||fields.some(f=>!Object.hasOwn(b,f))||b.action!=='expire'&&!validUuid(b.uuid)||['board','smuggler_board'].includes(b.action)&&(!validUuid(b.requestId)||!validUuid(b.keyId)||!Number.isSafeInteger(b.version)||b.version<1||!Number.isSafeInteger(b.fareMinor)||b.fareMinor<1||Object.hasOwn(b,'destination')&&!Object.values(routes).includes(b.destination))||b.action==='arrive'&&!Object.values(routes).includes(b.server))return json({message:'Invalid Guild fields'},400);
|
||||
const fields={smuggler_return:['action','uuid','sourceWorld'],smuggler_quote:['action','uuid','sourceWorld'],smuggler_board:['action','uuid','requestId','keyId','version','fareMinor','sourceWorld','destination'],travel_check:['action','uuid','sourceWorld','destination'],quote:['action','uuid',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[])],board:['action','uuid','requestId','keyId','version','fareMinor',...(Object.hasOwn(b||{},'sourceWorld')?['sourceWorld']:[]),...(Object.hasOwn(b||{},'destination')?['destination']:[])],arrive:['action','uuid','server'],bounty_claim:['action','uuid','victim','requestId','server'],expire:['action']}[b?.action];
|
||||
if((Object.hasOwn(b||{},'sourceWorld')&&!tradeWorld(b.sourceWorld))||b?.action==='travel_check'&&b.destination!=='lobby'||!fields||Object.keys(b).length!==fields.length||fields.some(f=>!Object.hasOwn(b,f))||b.action!=='expire'&&!validUuid(b.uuid)||['board','smuggler_board'].includes(b.action)&&(!validUuid(b.requestId)||!validUuid(b.keyId)||!Number.isSafeInteger(b.version)||b.version<1||!Number.isSafeInteger(b.fareMinor)||b.fareMinor<(b.action==='board'&&service?.openTravel?0:1)||Object.hasOwn(b,'destination')&&!Object.values(routes).includes(b.destination))||b.action==='arrive'&&!Object.values(routes).includes(b.server)||b.action==='bounty_claim'&&(!validUuid(b.victim)||!validUuid(b.requestId)||b.victim===b.uuid||!Object.values(routes).includes(b.server)))return json({message:'Invalid Guild fields'},400);
|
||||
if(!service)return json({message:'The central bank is unavailable.'},503);
|
||||
try{return json(b.action==='smuggler_return'?await service.smugglerReturn(b.uuid,b.sourceWorld):b.action==='smuggler_quote'?await service.quoteSmuggler(b.uuid,b.sourceWorld):b.action==='smuggler_board'?await service.board(b,true):b.action==='quote'?await service.quote(b.uuid,b.sourceWorld):b.action==='travel_check'?await service.checkTravel(b.uuid,b.sourceWorld,b.destination):b.action==='board'?await service.board(b):b.action==='arrive'?await service.arrive(b.uuid,b.server):{ok:true,expired:await service.expire()});}catch(e){return json({message:e instanceof BankError?e.message:'The Guild could not confirm this passage. Retry the same reference.'},e instanceof BankError?e.status||409:503);}
|
||||
try{return json(b.action==='smuggler_return'?await service.smugglerReturn(b.uuid,b.sourceWorld):b.action==='smuggler_quote'?await service.quoteSmuggler(b.uuid,b.sourceWorld):b.action==='smuggler_board'?await service.board(b,true):b.action==='quote'?await service.quote(b.uuid,b.sourceWorld):b.action==='travel_check'?await service.checkTravel(b.uuid,b.sourceWorld,b.destination):b.action==='board'?await service.board(b):b.action==='arrive'?await service.arrive(b.uuid,b.server):b.action==='bounty_claim'?await service.bountyClaim({killer:b.uuid,victim:b.victim,requestId:b.requestId,server:b.server}):{ok:true,expired:await service.expire()});}catch(e){return json({message:e instanceof BankError?e.message:'The Guild could not confirm this passage. Retry the same reference.'},e instanceof BankError?e.status||409:503);}
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,18 @@ export function createGameQuestsAPI(db,settings,{personal=null,pol=null,starter=
|
|||
let input;
|
||||
try{const chunks=[];let size=0;while(true){const {done,value}=await reader.read();if(done)break;size+=value.byteLength;if(size>4096){await reader.cancel();return json({message:'Quest request too large.'},413);}chunks.push(value);}input=JSON.parse(Buffer.concat(chunks).toString('utf8'));}
|
||||
catch{return json({message:'Invalid quest action.'},400);}finally{reader.releaseLock();}
|
||||
if(input?.action==='login_settle'){
|
||||
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['action','uuid'].includes(k))||!validUuid(input.uuid))return json({message:'A player UUID is required.'},400);
|
||||
try{
|
||||
const user=await resolve(input.uuid);if(!user)return json({message:'Link an active personal Minecraft account first.'},403);
|
||||
const actor={...user,revalidate:()=>resolve(input.uuid)},settled=[];let failed=0;
|
||||
for(const [kind,runtime] of [['personal',personal],['pol',pol]]){
|
||||
if(!runtime?.quests?.settleCompleted)continue;
|
||||
try{await runtime.collect?.(actor);const result=await runtime.quests.settleCompleted(actor);for(const row of result.settled)settled.push({...row,kind});failed+=result.failed;if(result.settled.length)await runtime.quests.processCompletions?.({accountId:actor.id});}catch{failed++;}
|
||||
}
|
||||
return json({ok:true,settled,failed});
|
||||
}catch{return json({message:'The quest payout was not confirmed. It will be retried on your next login.'},503);}
|
||||
}
|
||||
const refine=input?.action==='prepare_refine';
|
||||
const equipment=input?.action==='prepare_starter';
|
||||
const meatTurnin=input?.action==='prepare_husbandry_turnin',supply=input?.action==='prepare_pol_supply',dossier=input?.action==='dossier_step',cargoAction=input?.action==='prepare_pol_cargo',cargoPartner=input?.action==='cargo_partner';
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import {PostbankPayments} from './postbank-payments.mjs';
|
|||
import {BankError} from './postbank-service.mjs';
|
||||
import {canDebitAccount} from './postbank-authorisations.mjs';
|
||||
import {ordinaryPaymentAccount} from './postbank-recipient-policy.mjs';
|
||||
import {creditID} from './postbank-credit-ledger.mjs';
|
||||
import {postPayrollIssue} from './postbank-payroll-issuer.mjs';
|
||||
const accountSQL=`SELECT a.*,c.entity_id,e.external_key,e.active entity_active,p.state package_state FROM pb_accounts a LEFT JOIN pb_clients c ON c.client_number=a.client_number LEFT JOIN pb_entities e ON e.id=c.entity_id LEFT JOIN pb_packages p ON p.id=a.package_id`;
|
||||
const fail=(message,status=409)=>{throw new BankError(message,status);};
|
||||
// Shared by ordinary Guild, Esmar and owned-home routes. One reservation and ledger.
|
||||
|
|
@ -10,15 +12,17 @@ export function createGuildPassageLedger(bank,{authority,clock=Date.now,subsidie
|
|||
async function funds(tx,user,amount,lock=false,authorise=authority){const context=await authorise(user,{bank:tx});return(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id"+(lock?' FOR UPDATE':''),[user.id])).find(a=>ordinaryPaymentAccount(a)&&canDebitAccount(context,a.entity_id,a.id)&&BigInt(a.balance_minor)-BigInt(a.reserved_minor)>=BigInt(amount));}
|
||||
async function release(tx,r){if(r.state!=='pending')return;const a=await tx.first('SELECT id,reserved_minor FROM pb_accounts WHERE id=? FOR UPDATE',[r.source_id]);if(!a||BigInt(a.reserved_minor)<BigInt(r.fare_minor))throw Error('Guild reservation requires reconciliation');await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor-? WHERE id=?',[r.fare_minor,r.source_id]);if(subsidies)await subsidies.release(tx,r.id);await tx.query("UPDATE pb_guild_passages SET state='expired' WHERE id=?",[r.id]);r.state='expired';}
|
||||
async function reserve(tx,input,user,{price,fingerprint,destination,expiresAt,permitKey=null,offer=null,authorise=authority}){
|
||||
const source=await funds(tx,user,price,true,authorise);if(!source)fail('Not enough available Dunemarks in your central personal bank account.');
|
||||
// A zero fare (race world, Lobby, decree) reserves nothing and never touches a personal account.
|
||||
const free=BigInt(price)===0n,source=free?await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury' FOR UPDATE"):await funds(tx,user,price,true,authorise);if(!source)fail(free?'The Guild receiving account is unavailable.':'Not enough available Dunemarks in your central personal bank account.',free?503:409);
|
||||
if(await tx.first("SELECT id FROM pb_guild_passages WHERE minecraft_uuid=? AND state='pending' FOR UPDATE",[input.uuid]))fail('Your previous passage is still awaiting arrival.');
|
||||
const target=await tx.first("SELECT * FROM pb_accounts WHERE system_key='sys_game_treasury' FOR UPDATE");if(!target||target.state!=='active')fail('The Guild receiving account is unavailable.',503);
|
||||
const r={id:input.requestId,actor_id:user.id,minecraft_uuid:input.uuid,house_key:input.keyId,house_version:input.version,destination,fare_minor:price,source_id:source.id,target_id:target.id,fingerprint,state:'pending',created_at:clock(),expires_at:expiresAt};
|
||||
await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[price,source.id]);
|
||||
if(!free)await tx.query('UPDATE pb_accounts SET reserved_minor=reserved_minor+? WHERE id=?',[price,source.id]);
|
||||
await tx.query('INSERT INTO pb_guild_passages(id,actor_id,minecraft_uuid,house_key,house_version,destination,fare_minor,source_id,target_id,fingerprint,state,created_at,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',Object.values(r));
|
||||
if(permitKey)await tx.query('INSERT INTO pb_smuggler_passages(id,permit_key) VALUES(?,?)',[r.id,permitKey]);if(offer)await subsidies.reserve(tx,r.id,offer);return r;
|
||||
}
|
||||
async function settle(tx,r,user,smuggler=false,authorise=authority){
|
||||
if(BigInt(r.fare_minor)===0n){r.state='arrived';r.arrived_at=clock();await tx.query("UPDATE pb_guild_passages SET state='arrived',arrived_at=? WHERE id=?",[r.arrived_at,r.id]);return r;}
|
||||
const accounts=await tx.query(accountSQL+' WHERE a.id IN (?,?) ORDER BY a.id FOR UPDATE',[r.source_id,r.target_id]),source=accounts.find(a=>String(a.id)===String(r.source_id)),target=accounts.find(a=>String(a.id)===String(r.target_id));
|
||||
if(!ordinaryPaymentAccount(source)||!target||target.system_key!=='sys_game_treasury'||target.state!=='active'||BigInt(source.reserved_minor)<BigInt(r.fare_minor))fail('The passage payment needs review.');
|
||||
if(!canDebitAccount(await authorise(user,{bank:tx}),source.entity_id,source.id))fail('Your bank account authority changed.',403);
|
||||
|
|
@ -26,5 +30,14 @@ export function createGuildPassageLedger(bank,{authority,clock=Date.now,subsidie
|
|||
await payments.post(tx,{id:r.id,actor_id:user.id,amount_minor:String(r.fare_minor)},source,target,true);if(subsidies)await subsidies.settle(tx,r.id,r.target_id);
|
||||
r.state='arrived';r.arrived_at=clock();await tx.query("UPDATE pb_guild_passages SET state='arrived',arrived_at=? WHERE id=?",[r.arrived_at,r.id]);return r;
|
||||
}
|
||||
return {funds,release,reserve,settle};
|
||||
// Pays a verified travel bounty using the existing fixed P&O issuance path.
|
||||
async function payout(tx,{id,hunter,amountMinor,memo}){
|
||||
const amount=BigInt(amountMinor);if(amount<1n||amount>2500000n)fail('Invalid bounty amount.',400);
|
||||
const source=(await tx.query(accountSQL+" WHERE a.system_key='sys_payroll_po' FOR UPDATE"))[0];if(!source||source.type_code!=='979'||source.state!=='active')fail('The P&O issuer is unavailable.',503);
|
||||
const target=(await tx.query(accountSQL+" WHERE e.kind='person' AND e.external_key=? AND a.system_key IS NULL ORDER BY a.id FOR UPDATE",[hunter.id])).find(ordinaryPaymentAccount);if(!target)fail('The hunter needs an active central bank account to receive a bounty.');
|
||||
const orderId=creditID('travel-bounty:'+id),fingerprint=(await import('node:crypto')).createHash('sha256').update(JSON.stringify(['travel-bounty',id,hunter.id,String(amount),String(target.id)])).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(?,?,?,?,?,?,?,'guild','queued',?)",[orderId,hunter.id,source.id,target.id,fingerprint,String(amount),memo.slice(0,140),clock()]);
|
||||
await postPayrollIssue(tx,{id:orderId,actor_id:hunter.id,amount_minor:String(amount)},source,target,{now:clock()});
|
||||
}
|
||||
return {funds,release,reserve,settle,payout};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -348,6 +348,24 @@
|
|||
"label": "Use voice chat groups",
|
||||
"source": "Simple Voice Chat 2.6.25 plugin.yml",
|
||||
"highRisk": false
|
||||
},
|
||||
{
|
||||
"node": "dunestaff.fly",
|
||||
"label": "Staff self flight",
|
||||
"source": "DuneStaff explicit command or visibility check",
|
||||
"highRisk": true
|
||||
},
|
||||
{
|
||||
"node": "dunestaff.vanish",
|
||||
"label": "Staff self vanish",
|
||||
"source": "DuneStaff explicit command or visibility check",
|
||||
"highRisk": true
|
||||
},
|
||||
{
|
||||
"node": "dunestaff.vanish.see",
|
||||
"label": "See vanished staff",
|
||||
"source": "DuneStaff explicit command or visibility check",
|
||||
"highRisk": true
|
||||
}
|
||||
],
|
||||
"networkAdministratorRoles": [
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import {NODES} from './permissions.mjs';
|
||||
import {ORGANISATION} from './organisation-model.mjs';
|
||||
import {validatePolicyNodes} from './organisation-management.mjs';
|
||||
const staff=['web.menu.staffmanual','web.mail.internal.view'];
|
||||
const staff=['web.menu.staffmanual','web.mail.internal.view','dunestaff.fly','dunestaff.vanish','dunestaff.vanish.see'];
|
||||
const branchNodes={
|
||||
customer_support:['web.tickets.support','web.tickets.staff','web.menu.tickets','web.accounts.view','dune.tickets.staff','dune.staff.open','dune.staff.history'],
|
||||
sales_accounts:['web.tickets.sales','web.tickets.staff','web.menu.tickets','web.shop.support','web.accounts.view','web.bank.staff.view','web.bank.staff.clients'],
|
||||
|
|
|
|||

Staff