web/website/scripts/render-rates-guide.py

43 lines
7.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from pathlib import Path
import json,sys,datetime,html
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle
from reportlab.lib.enums import TA_LEFT
from reportlab.platypus import SimpleDocTemplate,Paragraph,Spacer,Table,TableStyle,PageBreak,KeepTogether
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.utils import ImageReader
D=json.loads(Path(sys.argv[1]).read_text());out=sys.argv[2]
import reportlab
font=Path(reportlab.__file__).parent/'fonts/Vera.ttf';bold=font.with_name('VeraBd.ttf')
if font.exists():
pdfmetrics.registerFont(TTFont('Guide',str(font)));pdfmetrics.registerFont(TTFont('GuideBold',str(bold)));pdfmetrics.registerFontFamily('Guide',normal='Guide',bold='GuideBold')
else: raise RuntimeError('Reviewed readable fonts required')
green=colors.HexColor('#12382d');gold=colors.HexColor('#9c792b');muted=colors.HexColor('#52665d')
styles=getSampleStyleSheet();styles.add(ParagraphStyle(name='BodyGuide',fontName='Guide',fontSize=8.3,leading=12,spaceAfter=7,textColor=green));styles.add(ParagraphStyle(name='CellGuide',parent=styles['BodyGuide'],fontSize=7.1,leading=10,spaceAfter=0));styles.add(ParagraphStyle(name='HGuide',fontName='GuideBold',fontSize=18,leading=23,textColor=green,spaceBefore=12,spaceAfter=12,keepWithNext=True));styles.add(ParagraphStyle(name='SubGuide',fontName='GuideBold',fontSize=10,leading=14,textColor=gold,spaceAfter=9));styles.add(ParagraphStyle(name='CoverGuide',fontName='GuideBold',fontSize=31,leading=38,textColor=green,spaceAfter=20))
p=lambda text,style='BodyGuide':Paragraph(html.escape(str(text).replace('\u00c2\u00b7','\u00b7')),styles[style])
flow=[]
def paragraph(t):flow.append(p(t))
def table(headers,rows,widths=None):
data=[[p(x,'CellGuide') for x in headers]]+[[p(x,'CellGuide') for x in row] for row in rows]
t=Table(data,colWidths=widths or [499/len(headers)]*len(headers),repeatRows=1,hAlign='LEFT');t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),colors.HexColor('#e2e8df')),('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white,colors.HexColor('#f1f4ef')]),('LINEBELOW',(0,0),(-1,0),1,gold),('VALIGN',(0,0),(-1,-1),'TOP'),('LEFTPADDING',(0,0),(-1,-1),7),('RIGHTPADDING',(0,0),(-1,-1),7),('TOPPADDING',(0,0),(-1,-1),7),('BOTTOMPADDING',(0,0),(-1,-1),7)]));flow.extend([t,Spacer(1,12)])
date=lambda ms:datetime.datetime.fromtimestamp(ms/1000,datetime.timezone.utc).strftime('%d %B %Y')
pub=D['publication'];flow.extend([Spacer(1,35),p('IMPERIAL POSTBANK','SubGuide'),p('Rates & Charges','CoverGuide'),p('The DuneRealms financial handbook','HGuide')]);paragraph('Edition '+D['edition']+' · Published '+date(D['publishedAt']));paragraph('Fictional game economy · all amounts in Dunemarks (DM).');paragraph('Bank snapshot '+pub['version']+' · Bank rules dated '+date(pub['publishedAt'])+'. The handbook publication date is distinct from the immutable bank snapshot date.');paragraph('The active bank rules were independently checked against this public snapshot. Existing contracts keep their agreed conditions. A newly published guide never retroactively changes a loan or accepted contract.');paragraph('Package terms: '+D['bankVersion']+'. Credit terms: '+D['creditVersion']+'.');paragraph('For changes after this edition, consult https://www.dunerealms.com/rates-and-charges.html and the versioned public bank tariff snapshot. Earlier guides and snapshots remain available.');flow.append(p('Service availability','HGuide'))
for notice in pub['serviceNotices']:paragraph(notice)
flow.append(PageBreak());flow.append(p('Accounts & packages','HGuide'));rates={r['key']:r for r in pub['packages']}
table(['Package / client','Monthly','Extra accounts','Each extra / month','Instant / month'],[[x['name']+' / '+', '.join(x['kinds']),f"{rates[x['key']]['monthlyMinor']/100:.2f} DM",x['extra'],f"{rates[x['key']]['extraMinor']/100:.2f} DM" if x['extra'] else '—','Unlimited' if x.get('unlimitedInstant') else x['instant']]for x in D['packages']],[140,78,90,106,85]);paragraph('One current account is included. Flow and Pro include savings. Extra-account limits and prices apply only where the service is available. No package transfer-amount cap; available funds and payment authorization still apply. Published monthly package billing remains disabled.')
flow.append(p('Credit & accepted contracts','HGuide'));credit={r['key']:r for r in pub['credit']};table(['Product','Annual rate','Principal range','Term'],[[x['name'],f"{credit[x['key']]['annualBps']/100:.2f}%",f"{x['min']}–{x['max']} DM",', '.join(map(str,x['terms']))+' months' if x.get('terms') else 'Up to '+str(x.get('maxMonths','—'))+' months']for x in D['credit']],[145,80,124,150]);paragraph('Launch grants are repayable at 0%. Ordinary loans require review and an initial 5% instalment from own funds, which reduces the loan balance. Pro ceilings and collateral conditions are in the service notices. No revolving credit is offered. A new rate is not a rewrite of an existing fixed-rate contract.')
flow.append(p('Configured tax register','HGuide'));tax=pub['taxes'];table(['Tax','Current configured value'],[['Applicable sales VAT',f"{tax['vatBps']/100:.2f}%"],['Bank fee VAT',f"{tax['bankFeeVatBps']/100:.2f}%"],['Monthly account tax',f"{tax['monthlyAccountTaxMinor']/100:.2f} DM"]]);paragraph('A configured tax does not enable tax collection for unsupported flows. The specific transaction consumer must implement it and post its ledger entries.')
pay=pub['payrollTax'];flow.append(p('Payroll register','HGuide'));paragraph(f"Employee social contribution {pay['employeeSocialBps']/100:.2f}%; employer contribution {pay['employerSocialBps']/100:.2f}%. Annual basic allowance {pay['annualAllowanceMinor']/100:.2f} DM. Game model basis year {pay['basisYear']}.");lower=0;bands=[]
for b in pay['bands']:
bands.append([('Above '+f'{lower/100:.2f}') if b['upToMinor'] is None else f"{lower/100:.2f}–{b['upToMinor']/100:.2f}",f"{b['bps']/100:.2f}%"]);lower=b['upToMinor']
table(['Annual taxable DM','Marginal rate'],bands)
for section in D['sections']:
flow.append(PageBreak());flow.append(p(section['title'],'HGuide'))
for text in section.get('paragraphs',[]):paragraph(text)
table(section['headers'],section['rows'])
flow.append(p('Versioned instruments and rewards','HGuide'));paragraph('Keys define scoped authority; a generated or listed key is not proof of execution. System accounts have no player/staff banking rights. Reputation quest payouts require an explicitly configured reward, a consumed verified claim and existing funded treasury money. Eligible Mentat bonuses are recorded by policy; no automatic default cash reward is enabled. Personal XP and ordinary accepted contract conditions remain independent.');paragraph('Political v2.2 proposal amounts use the same numerical DM values. A proposal is not an active charge or effect. Current deed, target, cost, cooldown and duration must be implemented by its registered domain consumer before execution is available.')
def page(c,doc):
c.saveState();w,h=doc.pagesize;c.setStrokeColor(gold);c.setLineWidth(1);c.line(48,h-57,w-48,h-57);c.setFont('GuideBold',9);c.setFillColor(green);c.drawString(48,h-40,'IMPERIAL POSTBANK');c.setFont('Guide',7);c.drawRightString(w-48,h-40,'DUNEREALMS · RATES & CHARGES');c.line(48,42,w-48,42);c.setFillColor(muted);c.setFont('Guide',6.7);c.drawString(48,29,D['edition']);c.drawRightString(w-48,29,'Fictional game economy · Page '+str(doc.page));c.restoreState()
SimpleDocTemplate(out,pagesize=(595,842),rightMargin=48,leftMargin=48,topMargin=73,bottomMargin=59,title='DuneRealms Rates & Charges '+D['edition'],author='Imperial Postbank').build(flow,onFirstPage=page,onLaterPages=page)
print(json.dumps({'pdf':out,'bytes':Path(out).stat().st_size,'edition':D['edition']}))