Expand public tariffs with tax rules, reserve instruments and economic formulas; add complete PDF and audited direct publisher
This commit is contained in:
parent
e5d593ee3f
commit
587809a78d
15 changed files with 189 additions and 10 deletions
|
|
@ -15,7 +15,7 @@ export function createDevKeyAuthority({secret,environment,authorize,clock=Date.n
|
|||
return Object.freeze({
|
||||
async issue(actor,manifest,{ttlMs=600000}={}){
|
||||
await allowed(actor);
|
||||
if(!Number.isSafeInteger(ttlMs)||ttlMs<1||ttlMs>900000||manifest?.action!=='clan-reset'||manifest.state!=='planned')throw TypeError('Invalid developer batch');
|
||||
if(!Number.isSafeInteger(ttlMs)||ttlMs<1||ttlMs>900000||!['clan-reset','tariff-publication'].includes(manifest?.action)||manifest.state!=='planned')throw TypeError('Invalid developer batch');
|
||||
const now=clock(),record={id:randomUUID(),environment,actorId:actor.id,issuedAt:now,expiresAt:now+ttlMs,manifestHash:hash(canonical(manifest)),manifest:JSON.parse(canonical(manifest))};
|
||||
const payload=Buffer.from(canonical(record)).toString('base64url');
|
||||
const key='DEV-BATCH.'+payload+'.'+sign(payload);
|
||||
|
|
|
|||
26
tools/jarvis-dev-tariff-receipt.mjs
Normal file
26
tools/jarvis-dev-tariff-receipt.mjs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Root-only companion to the fixed-file publication script, never a web route.
|
||||
import {createDevKeyAuthority} from './jarvis-dev-key.mjs';
|
||||
import {randomBytes,randomUUID} from 'node:crypto';
|
||||
import {createRequire} from 'node:module';
|
||||
let raw='';for await(const part of process.stdin)raw+=part;
|
||||
if(process.getuid?.()!==0||raw.length>65536||!['--issue','--complete','--failed'].includes(process.argv[2]))throw Error('Fixed developer publication command required');
|
||||
const data=JSON.parse(raw),mode=process.argv[2],actor={id:'server-root'};
|
||||
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');
|
||||
const require=createRequire('/home/dunerealms/apps/dunerealms/current/node/mysql.mjs'),mysql=require('mysql2/promise');
|
||||
const db=await mysql.createConnection({host:process.env.DB_HOST||'127.0.0.1',port:Number(process.env.DB_PORT||3306),user:process.env.DB_USER,password:process.env.DB_PASSWORD,database:process.env.DB_NAME,multipleStatements:false});
|
||||
try{
|
||||
let details,action;
|
||||
if(mode==='--issue'){
|
||||
if(data.action!=='tariff-publication'||data.batchId!=='tariff-guide-20261118-v1'||!Array.isArray(data.files)||data.files.length!==5)throw Error('Unexpected tariff manifest');
|
||||
const authority=createDevKeyAuthority({secret:randomBytes(32).toString('hex'),environment:'production',authorize:async who=>who.id===actor.id&&process.getuid()===0});
|
||||
const issued=await authority.issue(actor,data),record=await authority.verify(actor,issued.key,data);
|
||||
details={...issued.audit,batchId:data.batchId,manifest:data};action='dev-key-issued';
|
||||
await db.execute('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[record.id,'f3ffda37-01e4-41ea-b89d-fbeda82e453e',action,JSON.stringify(details),Date.now()]);
|
||||
console.log(JSON.stringify({record,audit:issued.audit}));
|
||||
}else{
|
||||
if(data.record?.manifest?.batchId!=='tariff-guide-20261118-v1'||typeof data.record?.id!=='string')throw Error('Publication receipt required');
|
||||
action=mode==='--complete'?'dev-tariff-published':'dev-tariff-failed';details={keyId:data.record.id,batchId:data.record.manifest.batchId,manifestHash:data.record.manifestHash,files:data.record.manifest.files};
|
||||
await db.execute('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),'f3ffda37-01e4-41ea-b89d-fbeda82e453e',action,JSON.stringify(details),Date.now()]);
|
||||
console.log(JSON.stringify({keyId:data.record.id,state:mode==='--complete'?'completed':'failed'}));
|
||||
}
|
||||
}finally{await db.end();}
|
||||
12
tools/package-tariff-hotfix.mjs
Normal file
12
tools/package-tariff-hotfix.mjs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import {readFileSync,writeFileSync,readdirSync} from 'node:fs';
|
||||
import {createHash} from 'node:crypto';
|
||||
const root=new URL('../',import.meta.url),read=p=>readFileSync(new URL(p,root)),hash=b=>createHash('sha256').update(b).digest('hex');
|
||||
const names=['rates-and-charges.html','bank-rates.css','bank-rates.js','downloads/rates-guide-manifest.json','downloads/dunerealms-rates-guide-20261118.pdf'];
|
||||
const files=Object.fromEntries(names.map(name=>{
|
||||
let bytes=read('website/web/'+name);const mime=name.endsWith('.html')?'text/html; charset=utf-8':name.endsWith('.css')?'text/css; charset=utf-8':name.endsWith('.js')?'text/javascript; charset=utf-8':name.endsWith('.json')?'application/json; charset=utf-8':'application/pdf';
|
||||
if(name.endsWith('.html')){const key=JSON.stringify('/'+name)+':';let prepared=null;for(const shard of [...read('website/dist/server/index.js').toString().matchAll(/from "\.\/(assets-[a-f0-9]+\.mjs)"/g)].map(m=>m[1])){const source=read('website/dist/server/'+shard).toString();const start=source.indexOf(key);if(start>=0){const end=source.indexOf('],',start);prepared=JSON.parse(source.slice(start+key.length,end+1));break;}}if(!prepared)throw Error('Build prepared tariff HTML first');bytes=Buffer.from(prepared[1],'base64');}
|
||||
return[name,{mime,data:bytes.toString('base64'),sha256:hash(bytes)}];
|
||||
}));
|
||||
const helpers=Object.fromEntries(['jarvis-dev-key.mjs','jarvis-dev-tariff-receipt.mjs'].map(name=>{const b=read('tools/'+name);return[name,{data:b.toString('base64'),sha256:hash(b)}];}));
|
||||
const template=read('tools/tariff-hotfix-template.py').toString().replace('__FILES_JSON__',JSON.stringify(JSON.stringify(files))).replace('__HELPERS_JSON__',JSON.stringify(JSON.stringify(helpers)));
|
||||
if(!process.argv[2])throw Error('Specify staged script path');writeFileSync(process.argv[2],template);console.log(JSON.stringify({files:names,script:process.argv[2],containsSecrets:false}));
|
||||
94
tools/tariff-hotfix-template.py
Normal file
94
tools/tariff-hotfix-template.py
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
"""Fixed, manifest-bound publication of five public tariff assets. No policy edits."""
|
||||
import base64, hashlib, json, os, pathlib, re, subprocess, sys, fcntl
|
||||
FILES=json.loads(__FILES_JSON__)
|
||||
HELPERS=json.loads(__HELPERS_JSON__)
|
||||
APP=pathlib.Path('/home/dunerealms/apps/dunerealms')
|
||||
STATE=pathlib.Path('/mnt/HC_Volume_107481500/dunegit/ci/promotion')
|
||||
NODE='/home/dunerealms/.nvm/versions/node/v22.23.3/bin/node'
|
||||
EXPECTED='ci-27d3bef1b60f01e6ddebfb644144002773a3de52'
|
||||
INSTALL=pathlib.Path('/usr/local/libexec/dunerealms-dev/tariff-guide-20261118')
|
||||
def digest(data):return hashlib.sha256(data).hexdigest()
|
||||
def run(args,**kwargs):return subprocess.run(args,check=True,capture_output=True,**kwargs)
|
||||
def atomic(path,data):
|
||||
metadata=path.stat() if path.exists() else None
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
tmp=path.with_name(path.name+'.tariff-new')
|
||||
if tmp.exists() or tmp.is_symlink():raise RuntimeError('Unexpected staged publication file')
|
||||
with tmp.open('xb') as out:out.write(data);out.flush();os.fsync(out.fileno())
|
||||
os.chmod(tmp,metadata.st_mode & 0o777 if metadata else 0o644)
|
||||
if metadata:os.chown(tmp,metadata.st_uid,metadata.st_gid)
|
||||
os.replace(tmp,path)
|
||||
def main():
|
||||
if os.geteuid()!=0:raise RuntimeError('Server administrator required')
|
||||
if len(sys.argv)!=2 or sys.argv[1] not in ('--plan','--apply'):raise RuntimeError('Choose --plan or --apply')
|
||||
release=(APP/'current').resolve(strict=True)
|
||||
if release.parent!=APP/'releases' or release.name!=EXPECTED:raise RuntimeError('Live release changed; regenerate this fixed publication package')
|
||||
payload={name:base64.b64decode(item['data']) for name,item in FILES.items()}
|
||||
if any(digest(payload[n])!=v['sha256'] for n,v in FILES.items()):raise RuntimeError('Publication package integrity failure')
|
||||
source=json.loads(run(['curl','--noproxy','*','-fsS','--max-time','15','--resolve','cp.dunerealms.com:443:127.0.0.1','https://cp.dunerealms.com/api/bank/public/rates']).stdout)
|
||||
guide=json.loads(payload['downloads/rates-guide-manifest.json'])
|
||||
if source['version']!=guide['sourcePublicationVersion']:raise RuntimeError('Financial policy changed; regenerate the guide from its current public snapshot')
|
||||
manifest={'action':'tariff-publication','state':'planned','batchId':'tariff-guide-20261118-v1','release':release.name,'files':[{'path':'/'+n,'sha256':FILES[n]['sha256']} for n in sorted(FILES)],'changesFinancialPolicy':False,'changesBalances':False}
|
||||
if sys.argv[1]=='--plan':print(json.dumps(manifest));return
|
||||
lock=os.fdopen(os.open(STATE/'tariff-guide-20261118.lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600),'w')
|
||||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
receipt_path=STATE/'tariff-guide-20261118-v1.json'
|
||||
if receipt_path.exists():
|
||||
receipt=json.loads(receipt_path.read_text())
|
||||
if receipt.get('state')=='completed':print(json.dumps({'state':'already-completed','keyId':receipt['record']['id']}));return
|
||||
raise RuntimeError('Previous incomplete publication needs inspection before retry')
|
||||
for directory in (INSTALL.parent,INSTALL):
|
||||
if directory.is_symlink():raise RuntimeError('Unsafe developer installation path')
|
||||
directory.mkdir(parents=True,exist_ok=True)
|
||||
st=directory.stat()
|
||||
if st.st_uid!=0 or st.st_mode & 0o022:raise RuntimeError('Developer installation must be root-owned and not writable by others')
|
||||
for name,item in HELPERS.items():
|
||||
data=base64.b64decode(item['data'])
|
||||
if digest(data)!=item['sha256']:raise RuntimeError('Developer helper integrity failure')
|
||||
atomic(INSTALL/name,data)
|
||||
run([NODE,'--check',str(INSTALL/name)])
|
||||
def audit(mode,value):return json.loads(run([NODE,str(INSTALL/'jarvis-dev-tariff-receipt.mjs'),mode],input=json.dumps(value).encode()).stdout)
|
||||
originals={};changes={};shards=[release/'dist/server'/name for name in re.findall(r'from "\./(assets-[a-f0-9]+\.mjs)"',(release/'dist/server/index.js').read_text())]
|
||||
if not shards:raise RuntimeError('Compiled public assets unavailable')
|
||||
for name,item in FILES.items():
|
||||
key=json.dumps('/'+name,separators=(',',':'))
|
||||
entry=key+':'+json.dumps([item['mime'],item['data']],separators=(',',':'))+','
|
||||
matches=[]
|
||||
pattern=re.compile(re.escape(key)+r':\["[^"]+","[A-Za-z0-9+/=]*"\],')
|
||||
for shard in shards:
|
||||
text=changes.get(shard,shard.read_bytes()).decode()
|
||||
if pattern.search(text):matches.append((shard,pattern.sub(lambda _:entry,text,count=1).encode()))
|
||||
if len(matches)>1:raise RuntimeError('Ambiguous compiled publication asset')
|
||||
if matches:changes[matches[0][0]]=matches[0][1]
|
||||
else:
|
||||
shard=shards[0];text=changes.get(shard,shard.read_bytes()).decode()
|
||||
if not text.rstrip().endswith('};'):raise RuntimeError('Unexpected compiled asset format')
|
||||
end=text.rfind('};');changes[shard]=(text[:end]+entry+text[end:]).encode()
|
||||
changes[release/'web'/name]=payload[name]
|
||||
if name in ('rates-and-charges.html','bank-rates.css'):
|
||||
changes[release/'dist/shared-chrome'/name]=payload[name]
|
||||
changes[pathlib.Path('/var/lib/dunerealms-public-rates')/name]=payload[name]
|
||||
slot=(STATE/'active-slot').read_text().strip()
|
||||
if slot not in ('blue','green'):raise RuntimeError('Unknown active website slot')
|
||||
pm2=['runuser','-u','dunerealms','--','env','PM2_HOME='+str(STATE.parent/'pm2'),NODE,'/home/dunerealms/.local/node_modules/pm2/bin/pm2']
|
||||
run(pm2+['describe','dunerealms-web-'+slot])
|
||||
for path in changes:originals[path]=path.read_bytes() if path.exists() else None
|
||||
receipt=audit('--issue',manifest)
|
||||
if receipt['record']['manifest']!=manifest:raise RuntimeError('Developer manifest verification failed')
|
||||
receipt['state']='executing';atomic(receipt_path,json.dumps(receipt).encode())
|
||||
try:
|
||||
for path,data in changes.items():atomic(path,data)
|
||||
run(pm2+['reload','dunerealms-web-'+slot])
|
||||
for name,item in FILES.items():
|
||||
actual=run(['curl','--noproxy','*','-fsS','--retry','5','--retry-delay','1','--max-time','15','--resolve','www.dunerealms.com:443:127.0.0.1','https://www.dunerealms.com/'+name]).stdout
|
||||
if digest(actual)!=item['sha256']:raise RuntimeError('Public tariff verification failed: '+name)
|
||||
audit('--complete',receipt);receipt['state']='completed';atomic(receipt_path,json.dumps(receipt).encode())
|
||||
print(json.dumps({'state':'completed','keyId':receipt['record']['id'],'publishedAssets':len(FILES),'balancesChanged':False,'financialPoliciesChanged':False}))
|
||||
except Exception:
|
||||
for path,data in originals.items():
|
||||
if data is None:path.unlink(missing_ok=True)
|
||||
else:atomic(path,data)
|
||||
run(pm2+['reload','dunerealms-web-'+slot])
|
||||
audit('--failed',receipt);receipt['state']='failed';atomic(receipt_path,json.dumps(receipt).encode())
|
||||
raise
|
||||
if __name__=='__main__':main()
|
||||
|
|
@ -17,3 +17,9 @@ test('expiry, tampering and unavailable developer privileges reject before execu
|
|||
now=10100;await assert.rejects(service.verify(dev,issued.key,manifest),/unavailable/);
|
||||
await assert.rejects(setup({authorize:async()=>false}).issue(dev,manifest),/Developer access/);
|
||||
});
|
||||
test('tariff publication keys bind exact public file hashes and reject unrelated developer actions',async()=>{
|
||||
const service=setup(),publication={action:'tariff-publication',state:'planned',files:[{path:'/rates-and-charges.html',sha256:'ab'.repeat(32)}],changesBalances:false};
|
||||
const issued=await service.issue(dev,publication);assert.equal((await service.verify(dev,issued.key,publication)).manifest.changesBalances,false);
|
||||
await assert.rejects(service.verify(dev,issued.key,{...publication,files:[{path:'/other.html',sha256:'ab'.repeat(32)}]}),/manifest/);
|
||||
await assert.rejects(service.issue(dev,{action:'arbitrary-sql',state:'planned'}),/Invalid developer batch/);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ def render(data,logo=None):
|
|||
green=colors.HexColor('#173c30');gold=colors.HexColor('#af914c');ink=colors.HexColor('#243e34')
|
||||
body=ParagraphStyle('RatesBody',fontName='Rates',fontSize=9,leading=13,textColor=ink,spaceAfter=8)
|
||||
title=ParagraphStyle('RatesTitle',fontName='RatesBold',fontSize=25,leading=30,textColor=green,spaceAfter=15)
|
||||
heading=ParagraphStyle('RatesHeading',fontName='RatesBold',fontSize=14,leading=19,textColor=green,spaceBefore=10,spaceAfter=7)
|
||||
heading=ParagraphStyle('RatesHeading',fontName='RatesBold',fontSize=14,leading=19,textColor=green,spaceBefore=10,spaceAfter=7,keepWithNext=True)
|
||||
small=ParagraphStyle('RatesSmall',parent=body,fontSize=7.5,leading=11)
|
||||
p=lambda text,style=body:Paragraph(escape(str(text)),style)
|
||||
cash=lambda n:f'{int(n)//100:,}.{int(n)%100:02d} DM'
|
||||
|
|
@ -65,6 +65,11 @@ def render(data,logo=None):
|
|||
story.append(p('Destinations & transparency',heading));story.append(p('Bank service charges go to the Website bank treasury. Game taxes and payroll deductions go to I.D. Taxes. Posted entries remain in the relevant account ledgers.'))
|
||||
story.append(p('Sources for the selected payroll parameters',heading))
|
||||
for source in tax.get('sources',[]):story.append(p(source,small))
|
||||
for section in data.get('supplementSections',[]):
|
||||
story.extend([PageBreak(),p(section['title'],title)])
|
||||
for text in section.get('paragraphs',[]):story.append(p(text))
|
||||
headers=section.get('headers',[])
|
||||
if headers:story.append(grid(headers,section.get('rows',[]),[511/len(headers)]*len(headers)))
|
||||
document.build(story,onFirstPage=frame,onLaterPages=frame);return output.getvalue()
|
||||
|
||||
if __name__=='__main__':sys.stdout.buffer.write(render(json.load(sys.stdin),sys.argv[1]if len(sys.argv)>1 else None))
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {ratesReferenceHTML,RATES_GUIDE_EDITION} from './rates-reference.mjs';
|
||||
import {rihlaRatesSection} from './rihla-rates-section.mjs';
|
||||
import {claimRatesSection} from './claim-rates-section.mjs';
|
||||
import {SHARED_HEADER} from './portal-navigation.mjs';
|
||||
|
|
@ -8,5 +9,5 @@ export function bankRatesPage(){
|
|||
const version=createHash('sha256').update(JSON.stringify([PACKAGES,CREDIT_PRODUCTS])).digest('hex').slice(0,10);
|
||||
const packages=PACKAGES.map(p=>`<tr><th>${p.name}</th><td>${p.kinds.join(' / ')}</td><td>${(p.monthly/100).toFixed(2)} DM</td><td>${p.extra}</td><td>${p.extra?(p.extraFee/100).toFixed(2)+' DM':'—'}</td><td>${p.unlimitedInstant?'Unlimited':p.instant}</td></tr>`).join('');
|
||||
const credit=CREDIT_PRODUCTS.filter(p=>!p.revolving).map(p=>`<tr><th>${p.name}</th><td>${(p.annualBps/100).toFixed(2)}%</td><td>${p.min}–${p.max} DM</td><td>${p.terms?p.terms.join(', '):'Up to '+p.maxMonths} months</td></tr>`).join('');
|
||||
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Rates & Charges | Imperial Postbank</title><meta name="description" content="Public Imperial Postbank package fees, credit rates, organisation claim tariffs and service conditions in Dunemarks."><link rel="stylesheet" href="/bank-rates.css"><link rel="stylesheet" href="/portal-navigation.css"><script src="/portal-navigation.js" defer></script><script src="/bank-rates.js" defer></script></head><body>${SHARED_HEADER}<main><section class="hero"><img src="/assets/imperial-postbank-v2.png" alt="Imperial Postbank"><div><p class="eyebrow">YOUR MONEY. CLEAR TERMS.</p><h1>Rates & Charges</h1><p>A clear guide to banking and organisation costs.</p><span class="stamp">PUBLIC TARIFF GUIDE · ${version}</span></div></section><nav class="sections" aria-label="Tariff sections"><a href="#packages">Accounts & packages</a><a href="#credit">Credit rates</a><a href="#services">Services & taxes</a><a href="#claims">Land claims</a></nav><aside class="notice"><strong>Alpha service notice</strong><p>All amounts are fictional Dunemarks (DM). Published monthly package prices are not yet collected automatically. This is a game economy, not a real-money banking service.</p></aside><section id="packages"><span class="eyebrow">01 / EVERYDAY BANKING</span><h2>Accounts & packages</h2><p>One current account is included in each package.</p><div class="table-wrap"><table><thead><tr><th>Package</th><th>Client</th><th>Monthly price</th><th>Extra current accounts¹</th><th>Each / month¹</th><th>Instant quota / month</th></tr></thead><tbody>${packages}</tbody></table></div><p class="fine">¹ Published additional-account limits and prices, subject to feature availability. Flow and Pro include a savings account. Pro includes unlimited instant payments with no per-transfer fee. Transfers have no package amount cap; available funds and payment security apply. Start has no instant payments. Instant quotas are server usage limits.</p></section><section id="credit"><span class="eyebrow">02 / BORROWING</span><h2>Credit rates</h2><p>Annual rates for new applications. Your accepted contract and repayment schedule govern your loan.</p><div class="table-wrap"><table><thead><tr><th>Product</th><th>Annual rate</th><th>Principal range</th><th>Available terms</th></tr></thead><tbody>${credit}</tbody></table></div><p class="fine">Launch grants are repayable at 0% interest. Ordinary loans require review and a first instalment of 5% from your own funds before issue. This instalment counts toward repayment and reduces the remaining loan balance. Eligibility, available funding and refinancing conditions apply. Existing fixed-rate contracts retain their agreed rate. Revolving credit is not available.</p></section><section id="services"><span class="eyebrow">03 / TRANSPARENCY</span><h2>Services & taxes</h2><div class="service-grid"><article><h3>Monthly statements</h3><strong>Free</strong><p>Automatically archived PDF statements after month-end.</p></article><article><h3>Balance Guard</h3><strong>1.00 DM / month</strong><p>Published optional price per eligible account. Preference saving is available; protection and charging are not active yet.</p></article><article><h3>Tax policy</h3><strong>Not yet published</strong><p>VAT and account-tax rates await central configuration. No unconfirmed rate is presented as active.</p></article></div></section>${rihlaRatesSection()}${claimRatesSection()}<section class="document"><div><h2>Your tariff guide</h2><p>Generated from the bank catalogues on each build. Version ${version}. Package terms: ${BANK_VERSION}. Credit terms: ${CREDIT_VERSION}.</p><p class="fine">Catalogue references identify source terms, not a new effective date. Administrative rate editing and automatic downloadable PDF publication are planned. You can print or save this guide as PDF now.</p></div><button onclick="window.print()">Print / Save as PDF</button></section><p class="fine">No private account or transaction data is published here.</p></main><footer><a href="/">DuneRealms</a><a href="/rates-and-charges.html">Rates & Charges</a><a href="https://support.dunerealms.com/">Contact support</a></footer></body></html>`;
|
||||
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Rates & Charges | Imperial Postbank</title><meta name="description" content="Public Imperial Postbank package fees, credit rates, organisation claim tariffs and service conditions in Dunemarks."><link rel="stylesheet" href="/bank-rates.css"><link rel="stylesheet" href="/portal-navigation.css"><script src="/portal-navigation.js" defer></script><script src="/bank-rates.js" defer></script></head><body>${SHARED_HEADER}<main><section class="hero"><img src="/assets/imperial-postbank-v2.png" alt="Imperial Postbank"><div><p class="eyebrow">YOUR MONEY. CLEAR TERMS.</p><h1>Rates & Charges</h1><p>Banking, taxation, reserve policy and the rules behind the realm economy.</p><span class="stamp">PUBLIC TARIFF GUIDE · ${version}</span></div></section><nav class="sections" aria-label="Tariff sections"><a href="#packages">Accounts & packages</a><a href="#credit">Credit rates</a><a href="#services">Services & taxes</a><a href="#claims">Land claims</a><a href="#tax-rules">Tax rules</a><a href="#publication-charges">Publication charges</a><a href="#reserve-instruments">Reserve & keys</a><a href="#economy-formulas">Formulas</a><a href="#payroll-tax">Payroll tax</a></nav><aside class="notice"><strong>Alpha service notice</strong><p>All amounts are fictional Dunemarks (DM). Published monthly package prices are not yet collected automatically. This is a game economy, not a real-money banking service.</p></aside><section id="packages"><span class="eyebrow">01 / EVERYDAY BANKING</span><h2>Accounts & packages</h2><p>One current account is included in each package.</p><div class="table-wrap"><table><thead><tr><th>Package</th><th>Client</th><th>Monthly price</th><th>Extra current accounts¹</th><th>Each / month¹</th><th>Instant quota / month</th></tr></thead><tbody>${packages}</tbody></table></div><p class="fine">¹ Published additional-account limits and prices, subject to feature availability. Flow and Pro include a savings account. Pro includes unlimited instant payments with no per-transfer fee. Transfers have no package amount cap; available funds and payment security apply. Start has no instant payments. Instant quotas are server usage limits.</p></section><section id="credit"><span class="eyebrow">02 / BORROWING</span><h2>Credit rates</h2><p>Annual rates for new applications. Your accepted contract and repayment schedule govern your loan.</p><div class="table-wrap"><table><thead><tr><th>Product</th><th>Annual rate</th><th>Principal range</th><th>Available terms</th></tr></thead><tbody>${credit}</tbody></table></div><p class="fine">Launch grants are repayable at 0% interest. Ordinary loans require review and a first instalment of 5% from your own funds before issue. This instalment counts toward repayment and reduces the remaining loan balance. Eligibility, available funding and refinancing conditions apply. Existing fixed-rate contracts retain their agreed rate. Revolving credit is not available.</p></section><section id="services"><span class="eyebrow">03 / TRANSPARENCY</span><h2>Services & taxes</h2><div class="service-grid"><article><h3>Monthly statements</h3><strong>Free</strong><p>Automatically archived PDF statements after month-end.</p></article><article><h3>Balance Guard</h3><strong>1.00 DM / month</strong><p>Published optional price per eligible account. Preference saving is available; protection and charging are not active yet.</p></article><article><h3>Tax policy</h3><strong>Public register</strong><p>Configured VAT, account tax and payroll deductions are loaded from the public bank publication. The tax-rule tables below explain their application.</p></article></div></section>${rihlaRatesSection()}${claimRatesSection()}${ratesReferenceHTML()}<section class="document"><div><h2>Your tariff guide</h2><p>Generated from the bank catalogues on each build. Version ${version}. Package terms: ${BANK_VERSION}. Credit terms: ${CREDIT_VERSION}.</p><p class="fine">Catalogue references identify source terms, not a new effective date. The live financial register supplies configured bank and tax values. The expanded handbook also records reserve instruments, calculation rules and availability.</p></div><div class="document-actions"><a class="pdf-download guide-download" href="/downloads/dunerealms-rates-guide-20261118.pdf">Download complete guide · PDF</a><span class="fine">Handbook ${RATES_GUIDE_EDITION}</span></div></section><p class="fine">No private account or transaction data is published here.</p></main><footer><a href="/">DuneRealms</a><a href="/rates-and-charges.html">Rates & Charges</a><a href="https://support.dunerealms.com/">Contact support</a></footer></body></html>`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ for(const [source,target] of [['cp-v2/cp-v2-exchange-design.mjs','codex-exchange
|
|||
writeFileSync(path.join(web,target),content);
|
||||
}
|
||||
writeFileSync(path.join(web,'rates-and-charges.html'),bankRatesPage());
|
||||
let assetCount=0;let assetWriter=null,shardSize=0;const shardNames=[];let shardTemporary;function openShard(){shardTemporary=path.join(dist,'server','.assets-build-'+process.pid);assetWriter=openSync(shardTemporary,'w');writeSync(assetWriter,'export default {');shardSize=0;}function closeShard(){writeSync(assetWriter,'};\n');closeSync(assetWriter);const hash=createHash('sha256').update(readFileSync(shardTemporary)).digest('hex'),name='assets-'+hash+'.mjs',target=path.join(dist,'server',name);if(existsSync(target))unlinkSync(shardTemporary);else renameSync(shardTemporary,target);shardNames.push(name);}function writeAsset(entry){if(shardSize>32*1024*1024){closeShard();openShard();}writeSync(assetWriter,entry);shardSize+=Buffer.byteLength(entry);}const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.zip':'application/zip','.svg':'image/svg+xml'};
|
||||
let assetCount=0;let assetWriter=null,shardSize=0;const shardNames=[];let shardTemporary;function openShard(){shardTemporary=path.join(dist,'server','.assets-build-'+process.pid);assetWriter=openSync(shardTemporary,'w');writeSync(assetWriter,'export default {');shardSize=0;}function closeShard(){writeSync(assetWriter,'};\n');closeSync(assetWriter);const hash=createHash('sha256').update(readFileSync(shardTemporary)).digest('hex'),name='assets-'+hash+'.mjs',target=path.join(dist,'server',name);if(existsSync(target))unlinkSync(shardTemporary);else renameSync(shardTemporary,target);shardNames.push(name);}function writeAsset(entry){if(shardSize>32*1024*1024){closeShard();openShard();}writeSync(assetWriter,entry);shardSize+=Buffer.byteLength(entry);}const types={'.html':'text/html; charset=utf-8','.css':'text/css; charset=utf-8','.js':'text/javascript; charset=utf-8','.json':'application/json; charset=utf-8','.webp':'image/webp','.png':'image/png','.mp4':'video/mp4','.pdf':'application/pdf','.zip':'application/zip','.svg':'image/svg+xml'};
|
||||
function collect(directory){for(const entry of readdirSync(directory).sort()){const p=path.join(directory,entry);if(statSync(p).isDirectory())collect(p);else{const relative=path.relative(web,p).split(path.sep).join('/');if(/^assets\/seals\/[^/]+-provenance\.txt$/.test(relative)||/^assets\/organisation-deed(?:s)?-[a-z0-9-]+\.png$/.test(relative))continue;const type=types[path.extname(entry)];if(!type)throw Error('Unexpected asset: '+entry);const bytes=readFileSync(p);const payload=relative.endsWith('.html')?Buffer.from(preparePublicHtml(bytes.toString('utf8'))):relative==='portal-navigation.js'?Buffer.from(withRealmSwitch(withCanonicalMenu(withMenuBadges(bytes.toString('utf8'))))):relative==='portal-navigation.css'?Buffer.concat([bytes,Buffer.from(HOUSE_STYLE_CSS+REALM_SWITCH_CSS)]):bytes;writeAsset(JSON.stringify('/'+relative)+':['+JSON.stringify(type)+','+JSON.stringify(payload.toString('base64'))+'],');assetCount++}}}
|
||||
mkdirSync(path.join(dist,'server'),{recursive:true});mkdirSync(path.join(dist,'.openai'),{recursive:true});const workerTemporary=path.join(dist,'server/index.js.build-'+process.pid);process.once('exit',()=>{if(existsSync(workerTemporary))try{unlinkSync(workerTemporary);}catch{}});openShard();collect(web);const buildCommit=process.env.GITHUB_SHA;if(buildCommit&&/^[0-9a-f]{40}$/.test(buildCommit)){writeAsset(JSON.stringify('/ci-build.json')+':'+JSON.stringify(['application/json; charset=utf-8',Buffer.from(JSON.stringify({commit:buildCommit})).toString('base64')])+',');}closeShard();
|
||||
let api=['feed-api.mjs','exchange-api.mjs','forum-api.mjs','community-api.mjs','portal-api.mjs'].map(file=>readFileSync(path.join(root,'worker',file),'utf8').replace(/export /g,'')).join('\n');let runtime=readFileSync(path.join(root,'worker/runtime.mjs'),'utf8').replace(/^import .*;$/gm,'');
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import {CLAIM_ORGANISATIONS,CLAIM_TARIFF_VERSION,claimTariffs,claimMoney,BASIC_POLITICAL_NOTICE,ORGANISATION_TRANSFER_NOTICE} from '../control-panel/public/cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
export function claimRatesSection(){
|
||||
const cards=Object.entries(CLAIM_ORGANISATIONS).map(([kind,group])=>`<article class="claim-rate-card claim-rate-${kind}"><header><h3>${group.name}</h3><p>${group.description}</p></header><div class="table-wrap" tabindex="0" role="region" aria-label="${group.name} claim tariffs"><table><caption>Per organisation · fictional DM</caption><thead><tr><th scope="col">Tier</th><th scope="col">Chunks</th><th scope="col">Monthly</th><th scope="col">Unlock</th></tr></thead><tbody>${claimTariffs(kind).map(row=>`<tr class="claim-stage-${row.stage.toLowerCase()}"><th scope="row">${row.code}${row.requirement?'<span class="claim-key-note">'+row.requirement+'</span>':''}</th><td>${row.chunks}</td><td>${claimMoney(row.upkeepMinor)}</td><td>${claimMoney(row.unlockMinor)}</td></tr>`).join('')}</tbody></table></div></article>`).join('');
|
||||
return `<section id="claims" class="claim-rates"><div class="claim-rates-heading"><img src="/assets/nav-clan-v2.webp" width="80" height="80" alt=""><div><span class="eyebrow">LAND / ORGANISATION CLAIMS</span><h2>Land claims & upkeep</h2><p>One organisation. One total chunk budget.</p></div></div><aside class="notice"><strong>Published schedule · claims system coming soon</strong><p>These are planned claim limits and prices. This publication does not reserve land, assign a tier, unlock an upgrade or start billing.</p></aside><div class="claim-rules"><article><h3>Count chunks, not radius</h3><p>One chunk is 16 × 16 blocks. Nine chunks in a 3 × 3 square cover 48 × 48 blocks. Limits apply across all claims belonging to the organisation.</p></article><article><h3>Separate status and capacity</h3><p>Create a Basic organisation first. Its original key unlocks Keyed status; a political appointment and new POL-key are required for Royal status. Tier unlock fees are paid once, sequentially. Upgrade claim capacity ingame by right-clicking the Home Block; this guide does not apply upgrades.</p></article><article><h3>Clear multipliers</h3><p>Companies: capacity × 1.5 and fees × 1.5. Protected Houses: capacity × 1.5 and fees × 0.5. Round capacity down to whole chunks. Both upkeep and unlock fees use the cost multiplier.</p></article></div><aside class="notice"><strong>Basic rights & planned transfers</strong><p>${BASIC_POLITICAL_NOTICE}</p><p>${ORGANISATION_TRANSFER_NOTICE}</p><p>Claim upkeep and tier unlock fees go to the Tax treasury.</p></aside><div class="claim-rates-grid">${cards}</div><p class="fine">Unlock calculation: 20 DM per additional chunk of standard clan capacity, plus ten months of the new standard tier’s upkeep; then apply the organisation cost multiplier. BC_T0 is free. Scaled fees are not recalculated from rounded capacity. Standard RC_T3 is 36 chunks: a possible 96 × 96-block square, fitting the agreed 100 × 100-block ceiling. Shapes may vary. A mother house controls its subordinate houses’ claim rights and management. Entitlement sources remain traceable and count only once. The original organisation remains responsible for upkeep and unlock costs, including upgrades performed by the mother house; a change in the mother’s tier does not transfer those costs.</p><p class="fine">Schedule ${CLAIM_TARIFF_VERSION}. Print this page to include claim tariffs; the downloadable bank tariff PDF currently covers bank rates, not this planned claim schedule.</p></section>`;
|
||||
return `<section id="claims" class="claim-rates"><div class="claim-rates-heading"><img src="/assets/nav-clan-v2.webp" width="80" height="80" alt=""><div><span class="eyebrow">LAND / ORGANISATION CLAIMS</span><h2>Land claims & upkeep</h2><p>One organisation. One total chunk budget.</p></div></div><aside class="notice"><strong>Published schedule · claims system coming soon</strong><p>These are planned claim limits and prices. This publication does not reserve land, assign a tier, unlock an upgrade or start billing.</p></aside><div class="claim-rules"><article><h3>Count chunks, not radius</h3><p>One chunk is 16 × 16 blocks. Nine chunks in a 3 × 3 square cover 48 × 48 blocks. Limits apply across all claims belonging to the organisation.</p></article><article><h3>Separate status and capacity</h3><p>Create a Basic organisation first. Its original key unlocks Keyed status; a political appointment and new POL-key are required for Royal status. Tier unlock fees are paid once, sequentially. Upgrade claim capacity ingame by right-clicking the Home Block; this guide does not apply upgrades.</p></article><article><h3>Clear multipliers</h3><p>Companies: capacity × 1.5 and fees × 1.5. Protected Houses: capacity × 1.5 and fees × 0.5. Round capacity down to whole chunks. Both upkeep and unlock fees use the cost multiplier.</p></article></div><aside class="notice"><strong>Basic rights & planned transfers</strong><p>${BASIC_POLITICAL_NOTICE}</p><p>${ORGANISATION_TRANSFER_NOTICE}</p><p>Claim upkeep and tier unlock fees go to the Tax treasury.</p></aside><div class="claim-rates-grid">${cards}</div><p class="fine">Unlock calculation: 20 DM per additional chunk of standard clan capacity, plus ten months of the new standard tier’s upkeep; then apply the organisation cost multiplier. BC_T0 is free. Scaled fees are not recalculated from rounded capacity. Standard RC_T3 is 36 chunks: a possible 96 × 96-block square, fitting the agreed 100 × 100-block ceiling. Shapes may vary. A mother house controls its subordinate houses’ claim rights and management. Entitlement sources remain traceable and count only once. The original organisation remains responsible for upkeep and unlock costs, including upgrades performed by the mother house; a change in the mother’s tier does not transfer those costs.</p><p class="fine">Schedule ${CLAIM_TARIFF_VERSION}. The complete downloadable handbook includes this capacity and fee schedule.</p></section>`;
|
||||
}
|
||||
|
|
|
|||
16
website/scripts/rates-reference.mjs
Normal file
16
website/scripts/rates-reference.mjs
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import {ECONOMY_POLICY as p} from '../node/jarvis-economy-policy.mjs';
|
||||
import {CAMPAIGN_RATES} from '../node/election-campaigns.mjs';
|
||||
import {OFFICE_AUCTION_RULES} from '../node/jarvis-office-auctions.mjs';
|
||||
import {CLAIM_ORGANISATIONS,claimTariffs,claimMoney} from '../control-panel/public/cp-v2/cp-v2-claim-tariffs.mjs';
|
||||
const dm=n=>(n/100).toFixed(2)+' DM';
|
||||
export const RATES_GUIDE_EDITION='alpha-1.0.1.2-20261118';
|
||||
export function ratesReferenceSections(){return [
|
||||
{id:'tax-rules',title:'Tax rules & payment destinations',art:'imperial-postbank-v2.png',paragraphs:['A configured tax rate does not make every website or Minecraft action taxable. The relevant transaction handler must apply the tax and record its ledger entries. No blanket extra tax is added to the prices below.','Rihla: 1% for transfers up to and including 3,000 DM; 5% on the full amount above 3,000 DM. The sender pays principal plus tax; the recipient receives the full principal. Tax rounds upward to the next cent. In-game sending and collection remain a separate integration.'],headers:['Charge','Who pays / basis','Destination / status'],rows:[['Applicable game-sales VAT','Configured public VAT rate; supported taxable sales only','Tax treasury; game-flow integration dependent'],['VAT on bank fees','Configured bank-fee VAT rate shown in the live register','Tax treasury; a zero rate adds no VAT'],['Monthly account tax','Configured fixed amount shown in the live register','A zero amount adds no account tax'],['Package and account charges','Accepted package terms; automated monthly billing remains disabled','Website bank treasury; published fees are not yet monthly collection'],['Rihla transfer tax','Sender; 1% / 5% of full principal','Tax treasury on collection; game execution pending'],['Payroll deductions','Employee social contribution and income tax; employer social contribution is additional','Tax treasury through supported P&O payroll posting'],['Recruitment and campaigns','Publishing organisation or officeholder; accepted quote','Tax treasury; listing charge is distinct from VAT'],['Office auction','Winning bidder; accepted final bid','Tax treasury; losing holds released'],['Claim upkeep / unlock','Original organisation, including upgrades by its mother','Tax treasury; published schedule and supported claim flow apply'],['Server project funding','Approved budget paid from available Tax funds','Dedicated 979 project account; project workflow in development']]},
|
||||
{id:'publication-charges',title:'Recruitment, campaigns & office auctions',art:'exchange-political-positions-v1.png',paragraphs:['Recruitment: Basic clans are free. Keyed/Royal recruitment uses 10 DM + 0.25 DM per occupied member. Protected institutions do not use ordinary recruitment. Political custom vacancies use the same agreed recruitment tariff.','Campaign bookings use whole hourly slots, may cover multiple hours and open no earlier than seven days before the election. A featured slot is exclusive for its election scope and hour. Forum/Discord promotion is optional: 25 DM per selected channel per booking, not per hour; retries do not create another charge.'],headers:['Election campaign','Standard / hour','Featured / hour'],rows:Object.entries(CAMPAIGN_RATES).map(([kind,price])=>[({clan_delegate:'Clan Delegate',house:'House leader',bene:'Veiled Concord',guild:'Spacing Guild',imperial:'Emperor'})[kind],dm(price),dm(price*1.5)]).concat([['Office auction opening bid',dm(OFFICE_AUCTION_RULES.startMinor),'Minimum increase '+dm(OFFICE_AUCTION_RULES.incrementMinor)]])},
|
||||
{id:'reserve-instruments',title:'Federal Reserve & J.A.R.V.I.S. instruments',art:'organisation-deed-keys-v1.png',paragraphs:['An instrument records a purpose and authority; knowing a reference is not permission. Public references never disclose secret codes. These are fictional game-economy instruments, not real-world securities.','Reserve issuance is restricted to the designated reserve owner and existing administration checks. It uses balanced grant postings to the Tax treasury; this guide creates no reserve budget or money. The new baseline and seasonal budget still require configuration.'],headers:['Instrument / flow','Purpose','Availability'],rows:[['Economic snapshot · ECO-SNAP','Sealed observation, baseline, policy version, index and rates; immutable payload hash','Implemented archival instrument; automatic collection is not connected'],['Reserve grant','Existing owner-controlled issuance to the Tax treasury, recorded in both ledgers','Existing restricted bank flow; no public redeemable reserve key'],['Policy / baseline change','Versioned configuration followed by a new observation','Requires a reviewed implementation or supported dev batch; no invented player code'],['Developer batch instrument','Exact manifest, server identity, short expiry, once-only action and audit receipt','Server/CLI only; never a website generator, download or player entitlement'],['Rihla instrument · RIA','Account-bound transfer reference, parties, amount and state','Private website register; in-game execution pending'],['News record · NEWS','Sealed public fact linked to its source and article','Gazette backend batch; not a redeemable reward']]},
|
||||
{id:'economy-formulas',title:'Economic formulas & limits',art:'imperial-postbank-v2.png',paragraphs:['Calculation policy v'+p.version+'. Formula support is implemented; automatic price, savings-interest, lending-rate and wage adjustments are not enabled by publishing this guide. Existing accepted loans keep their contracted rates. Player-set listing prices are not silently rewritten.','M = verified circulating DM; M0 = a strictly positive approved baseline. E is an index, not a direct annual inflation percentage. Unfunded issuance positions and system reserves must be classified by the approved collector; issued minus returned alone is not a complete inflation measure.'],headers:['Calculation','Formula','Limits / meaning'],rows:[['Money index','E = (M / M0)^'+p.moneyExponent,'M0 > 0; a fresh baseline starts at E = 1'],['Demand factor','D = ((sold + '+p.demandSmoothing+') / (offered + '+p.demandSmoothing+'))^'+p.demandExponent,'Verified counts; smoothing avoids empty-market division'],['System price target','target = clamp(base price × E × D, 0.5 × base, 2 × base)','System catalogue prices only; quote policy/version must be stored'],['Published system price','clamp(target, 0.95 × previous, 1.05 × previous)','Maximum ±5% per daily step; round in cents within bounds'],['Savings rate','S = clamp(round(S0 + 500 × (E − 1)), Smin, Smax)','Basis points; +5 percentage points per +1 index unit. Base and bounds require configuration'],['New lending rate','L = clamp(round(L0 + 1000 × (E − 1)), Lmin, Lmax)','Basis points; +10 percentage points per +1 index unit. Existing contracts unchanged'],['Indexed staff wage','target = base wage × E; next = clamp(target, 0.95 × previous, 1.05 × previous)','Maximum ±5% per monthly step; use P&O approved wages'],['Tax-inclusive price','gross = net + applicable tax','Only when that transaction implements the relevant tax rule']]},
|
||||
{id:'payroll-formulas',title:'Payroll calculation',art:'nav-staff-v2.webp',paragraphs:['All amounts use integer DM cents. Contribution and tax calculations round to the nearest cent using the existing payroll model. This is a fictional game model with selected Belgian-inspired parameters; household deductions and real-world tax advice are outside its scope.'],headers:['Step','Calculation'],rows:[['Employee contribution','round(gross monthly × employee social rate)'],['Monthly taxable pay','gross monthly − employee contribution'],['Annual progressive tax','Apply the configured marginal bands to 12 × monthly taxable pay'],['Basic allowance credit','Apply the same tax bands to the annual basic allowance; subtract this credit from annual tax, floor at zero'],['Monthly income tax','round(max(annual tax − allowance credit, 0) / 12)'],['Net wage','gross monthly − employee contribution − monthly income tax'],['Employer cost','gross monthly + round(gross monthly × employer social rate)'],['Tax treasury receipt','employee contribution + monthly income tax + employer contribution']]},
|
||||
...Object.entries(CLAIM_ORGANISATIONS).map(([kind,group])=>({id:'guide-claims-'+kind,title:group.name+' · claim schedule',paragraphs:['Capacity and price schedule; the published guide does not itself reserve land, upgrade a deed or enable recurring billing.'],headers:['Tier','Chunks','Monthly','Unlock'],rows:claimTariffs(kind).map(r=>[r.code,String(r.chunks),claimMoney(r.upkeepMinor),claimMoney(r.unlockMinor)])}))
|
||||
];}
|
||||
const escape=s=>String(s).replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"');
|
||||
export function ratesReferenceHTML(){return ratesReferenceSections().filter(s=>!s.id.startsWith('guide-claims-')).map(s=>`<section id="${s.id}" class="reference-section"><div class="reference-heading"><img src="/assets/${s.art}" alt=""><div><span class="eyebrow">PUBLIC ECONOMIC REGISTER</span><h2>${escape(s.title)}</h2></div></div>${s.paragraphs.map(t=>`<p>${escape(t)}</p>`).join('')}<div class="table-wrap"><table><thead><tr>${s.headers.map(h=>`<th scope="col">${escape(h)}</th>`).join('')}</tr></thead><tbody>${s.rows.map(row=>`<tr>${row.map(c=>`<td>${escape(c)}</td>`).join('')}</tr>`).join('')}</tbody></table></div></section>`).join('');}
|
||||
|
|
@ -11,5 +11,5 @@ test('organisation scaling floors whole chunks and scales both costs without sta
|
|||
const clans=claimTariffs();for(const [kind,multiplier,prefix]of [['company',1.5,'BCO'],['protected',0.5,'PBC']]){const rows=claimTariffs(kind);assert.match(rows[0].code,new RegExp('^'+prefix));rows.forEach((row,i)=>{assert.equal(row.chunks,Math.floor(clans[i].chunks*1.5));assert.equal(row.upkeepMinor,clans[i].upkeepMinor*multiplier);assert.equal(row.unlockMinor,clans[i].unlockMinor*multiplier);assert(Number.isSafeInteger(row.upkeepMinor)&&Number.isSafeInteger(row.unlockMinor));});assert.equal(rows.at(-1).chunks,54);}assert.equal(claimTariffs('company')[4].requirement,'COM-key');assert.throws(()=>claimTariffs('administrator'));assert.equal(claimTariffs()[0].chunks,1);
|
||||
});
|
||||
test('public guide includes all 39 rows as a planned schedule and preserves banking tables',()=>{
|
||||
const html=bankRatesPage();for(const kind of ['clan','company','protected'])for(const row of claimTariffs(kind))assert(html.includes(row.code));assert.match(html,/id="claims"/);assert.match(html,/Published schedule · claims system coming soon/);assert.match(html,/16 × 16 blocks/);assert.match(html,/does not reserve land/);assert.match(html,/id="packages"/);assert.match(html,/id="credit"/);assert.match(html,/bank tariff PDF currently covers bank rates/);
|
||||
const html=bankRatesPage();for(const kind of ['clan','company','protected'])for(const row of claimTariffs(kind))assert(html.includes(row.code));assert.match(html,/id="claims"/);assert.match(html,/Published schedule · claims system coming soon/);assert.match(html,/16 × 16 blocks/);assert.match(html,/does not reserve land/);assert.match(html,/id="packages"/);assert.match(html,/id="credit"/);assert.match(html,/complete downloadable handbook includes this capacity and fee schedule/);
|
||||
});
|
||||
|
|
|
|||
15
website/tests/rates-reference.test.mjs
Normal file
15
website/tests/rates-reference.test.mjs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {readFileSync} from 'node:fs';
|
||||
import {ratesReferenceSections,ratesReferenceHTML} from '../scripts/rates-reference.mjs';
|
||||
import {bankRatesPage} from '../scripts/bank-rates-page.mjs';
|
||||
test('complete tariff handbook covers implemented formulas, availability, payers and destinations without exposing developer codes',()=>{
|
||||
const sections=ratesReferenceSections(),html=bankRatesPage();
|
||||
for(const id of ['tax-rules','publication-charges','reserve-instruments','economy-formulas','payroll-formulas'])assert(sections.some(s=>s.id===id));
|
||||
assert.match(html,/Download complete guide/);assert.match(html,/ECO-SNAP/);assert.match(html,/Server\/CLI only/);assert.match(html,/not enabled by publishing/);assert.match(html,/3,000 DM/);
|
||||
assert(!html.includes('DEV-BATCH.'));assert(!html.includes('DB_PASSWORD'));assert.match(ratesReferenceHTML(),/Tax treasury/);
|
||||
assert.equal(sections.filter(s=>s.id.startsWith('guide-claims-')).length,3);
|
||||
});
|
||||
test('download references the public financial snapshot and ships a real PDF',()=>{
|
||||
const manifest=JSON.parse(readFileSync(new URL('../web/downloads/rates-guide-manifest.json',import.meta.url),'utf8'));
|
||||
assert.match(manifest.sourcePublicationVersion,/^[a-f0-9-]{36}$/i);
|
||||
const pdf=readFileSync(new URL('../web'+manifest.pdf,import.meta.url));assert.equal(pdf.subarray(0,5).toString(),'%PDF-');assert(pdf.length>20000);
|
||||
});
|
||||
|
|
@ -1,2 +1,5 @@
|
|||
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:#091f18;color:#e9eadb;font:16px/1.6 Arial,sans-serif}body>header,footer{padding:22px 5%;border-bottom:1px solid #756337}a{color:#e7cc88}main{max-width:1240px;margin:48px auto;padding:0 28px}.hero{display:flex;gap:48px;align-items:center;padding:54px;border:1px solid #b99a53;border-radius:24px;background:radial-gradient(at top left,#355540,#102e24 70%)}.hero img{width:260px;height:160px;object-fit:contain}.eyebrow{font-size:11px;letter-spacing:.2em;color:#c8af70}h1{font:54px/1.12 Georgia,serif;color:#f2da9d;margin:12px 0}h2{font:32px/1.3 Georgia,serif;color:#f2da9d;margin:10px 0}h3{font-size:18px;color:#ecd79e}.stamp{display:inline-block;border:1px solid #8c8158;border-radius:40px;padding:6px 14px;font-size:11px}.sections{display:flex;gap:12px;margin:24px 0}.sections a,button{border:1px solid #9f874f;border-radius:9px;padding:12px 20px;text-decoration:none;background:#19382c;color:#efdaa3;font-weight:bold}.notice{border-left:4px solid #c5aa64;background:#203c30;border-radius:8px;padding:20px 26px;margin:32px 0}.notice p{margin:5px 0}section[id]{margin:48px 0}.table-wrap{overflow:auto;border:1px solid #55765a;border-radius:14px}table{width:100%;border-collapse:collapse;font-size:14px;text-align:left}thead{background:#294e3d;color:#e2c77d}th,td{padding:17px 20px;border-bottom:1px solid #365342}tbody tr:last-child>*{border:0}tbody th{color:#f2e0b4}tbody tr:nth-child(even){background:#112e23}.fine{font-size:12px;color:#b6c9bc}.service-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.service-grid article{border:1px solid #597659;border-radius:14px;padding:24px;background:#153328}.service-grid strong{font:26px Georgia,serif;color:#abd8c4}.service-grid p{font-size:14px;color:#c2d0c4}.document{display:flex;align-items:center;gap:35px;padding:28px;border:1px solid #9f874f;border-radius:14px}.document p{font-size:13px}.document button{white-space:nowrap;cursor:pointer}footer{display:flex;gap:26px;margin-top:55px}@media print{body{background:white;color:#182d23}body>header,.sections,button,footer{display:none}main{margin:0;max-width:none}.hero{padding:20px}.hero img{width:170px;height:90px}h1{font-size:32px}h1,h2,h3,.fine{color:#263c2c}section[id]{margin:24px 0}th,td{padding:9px}section,article{break-inside:avoid}.service-grid{display:block}.service-grid article,.notice{background:white}.service-grid article{padding:8px}.document{padding:12px}}
|
||||
.sections{flex-wrap:wrap}.claim-rates-heading{display:flex;align-items:center;gap:22px;padding:24px;border:1px solid #9f874f;border-radius:16px;background:linear-gradient(100deg,#102d27f2,#102d27b0),url(/assets/political-imperial-chamber-v1.png) center/cover}.claim-rates-heading img{object-fit:contain}.claim-rules,.claim-rates-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px}.claim-rules{margin:24px 0}.claim-rules article,.claim-rate-card{min-width:0;border:1px solid #597659;border-radius:14px;background:#153328}.claim-rules article{padding:18px}.claim-rules p,.claim-rate-card header p{font-size:13px;color:#c2d0c4}.claim-rate-card header{padding:18px}.claim-rate-card h3{margin:0;color:#e7c879}.claim-rate-company h3{color:#9ad7e0}.claim-rate-protected h3{color:#d2b4e8}.claim-rate-card .table-wrap{border:0;border-radius:0 0 14px 14px}.claim-rate-card table{font-size:12px}.claim-rate-card th,.claim-rate-card td{padding:12px 8px;white-space:nowrap}.claim-rate-card caption{padding:8px;text-align:left;color:#bdcebf}.claim-key-note{display:block;max-width:115px;white-space:normal;font-size:10px;font-weight:normal;color:#bdcebf}@media(max-width:1050px){.claim-rates-grid{grid-template-columns:1fr}.claim-rate-card th,.claim-rate-card td{padding:13px 16px}.claim-rules{grid-template-columns:1fr}}@media(max-width:600px){main{padding:0 14px}.hero{padding:24px;gap:18px;flex-direction:column;align-items:flex-start}.hero img{width:160px;height:110px}h1{font-size:38px}.service-grid{grid-template-columns:1fr}.document{flex-direction:column;align-items:flex-start}.claim-rates-heading{padding:16px;gap:14px}.claim-rates-heading img{width:54px;height:54px}.claim-rates-heading h2{font-size:26px}.claim-rate-card th,.claim-rate-card td{padding:12px 8px}.sections a{flex:1;min-width:130px}footer{flex-wrap:wrap}}@media print{.claim-rates-grid{display:block}.claim-rate-card{margin:14px 0;break-inside:avoid}.claim-rules{display:block}.claim-rates-heading{background:white}.claim-rate-card table{font-size:11px}}
|
||||
|
||||
/* Complete public register: the same framed dev style as the CP. */
|
||||
.hero{background:linear-gradient(90deg,#102d27f2,#102d27b0),url('/assets/minecraft-hero.webp') center/cover}.reference-section,.claim-rates,#packages,#credit,#services,#rihla,#payroll-tax{padding:28px;border:1px solid #8f7945;border-radius:16px;background:linear-gradient(125deg,#203e31ee,#10291fee)}.reference-heading{display:flex;align-items:center;gap:20px;padding:18px;border:1px solid #8d7546;border-radius:12px;background:linear-gradient(90deg,#122e24f0,#122e24bd),url('/assets/minecraft-hero.webp') center/cover;margin-bottom:20px}.reference-heading img{width:76px;height:76px;object-fit:contain}#economy-formulas td:nth-child(2),#payroll-formulas td:nth-child(2){font-family:ui-monospace,monospace;font-size:13px}.document{flex-wrap:wrap;background:#17372b}.document-actions{display:flex;flex-direction:column;gap:12px}.pdf-download{display:inline-block;padding:14px 20px;border:1px solid #dbb763;border-radius:9px;text-decoration:none;background:linear-gradient(#3d5b38,#1c392b);color:#ffe7aa;font-weight:bold}.guide-download{box-shadow:inset 0 0 0 2px #112c1f,0 3px 12px #0003}.sections a{display:flex;align-items:center;justify-content:center;font-size:13px}.reference-section p{max-width:100ch}.table-wrap:focus-visible,.pdf-download:focus-visible{outline:3px solid #f4d681;outline-offset:3px}@media(max-width:650px){.reference-section,.claim-rates,#packages,#credit,#services,#rihla,#payroll-tax{padding:16px}.reference-heading{padding:12px;gap:12px}.reference-heading img{width:48px;height:48px}.reference-heading h2{font-size:25px}.document-actions,.pdf-download{width:100%}}@media print{.reference-section,.claim-rates,#packages,#credit,#services,#rihla,#payroll-tax{background:white;border-color:#98885d;padding:12px;break-inside:auto}.reference-heading{background:white}.reference-heading img{width:40px;height:40px}.pdf-download,.document-actions{display:none}tr{break-inside:avoid}}
|
||||
|
|
|
|||
|
|
@ -15,9 +15,10 @@
|
|||
const wrap=el('div');wrap.className='table-wrap';const table=el('table'),head=el('thead'),header=el('tr'),body=el('tbody');for(const text of ['Annual taxable income','Tax rate'])header.append(el('th',text));head.append(header);let lower=0;
|
||||
for(const band of data.payrollTax.bands){const row=el('tr');row.append(el('td',band.upToMinor===null?'Above '+money(lower):money(lower)+'–'+money(band.upToMinor)),el('td',percent(band.bps)));body.append(row);lower=band.upToMinor;}
|
||||
table.append(head,body);wrap.append(table);section.append(wrap,el('p','Fictional game payroll using selected Belgian-inspired parameters. The basic allowance is a tax credit; individual salaries remain private.'));documentBox.before(section);
|
||||
const description=documentBox.querySelector('div');if(description){description.replaceChildren(el('h2','Download the public tariff guide'),el('p','Publication '+data.version+' · '+new Date(data.publishedAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})),el('p','The PDF and live register use the same immutable publication. Accepted loan rates and recorded package prices retain their agreed terms.'));}
|
||||
status.textContent=data.pdfReady?'Current publication verified.':'The current publication PDF is being prepared. Reload shortly.';
|
||||
if(data.pdfReady){const link=el('a','Download Rates & Charges PDF');link.href=origin+data.pdfUrl;link.className='pdf-download';documentBox.append(link);}
|
||||
const description=documentBox.querySelector('div');if(description){description.replaceChildren(el('h2','Download the public tariff guide'),el('p','Publication '+data.version+' · '+new Date(data.publishedAt).toLocaleString('en-GB',{timeZone:'Europe/Brussels'})),el('p','The complete handbook includes the policy reference and claim schedules. The bank-only PDF preserves its own immutable publication. Accepted contracts retain their agreed terms.'));}
|
||||
status.textContent=data.pdfReady?'Bank publication verified.':'The bank publication PDF is being prepared.';
|
||||
try{const manifest=await (await fetch('/downloads/rates-guide-manifest.json',{cache:'no-store',credentials:'omit'})).json();if(manifest.sourcePublicationVersion!==data.version)status.textContent+=' The expanded handbook uses an earlier financial snapshot; current bank figures above take precedence.';else status.textContent+=' Expanded handbook financial source matches this register.';}catch{status.textContent+=' Handbook source check unavailable.';}
|
||||
if(data.pdfReady){const link=el('a','Download Rates & Charges PDF');link.href=origin+data.pdfUrl;link.className='pdf-download';link.textContent='Bank rates snapshot · PDF';documentBox.append(link);}
|
||||
}catch{status.textContent='Live publication unavailable. Catalogue reference prices are shown; retry before relying on a changed tariff.';}
|
||||
}
|
||||
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',load,{once:true});else void load();
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
Loading…
Reference in a new issue

Staff