web/website/node/postbank-rates-pdf.py
2026-11-21 20:22:37 +01:00

75 lines
7.2 KiB
Python

"""Render an immutable public game-bank tariff snapshot; JSON in, PDF out."""
import io
import json
import os
import sys
from datetime import datetime
from zoneinfo import ZoneInfo
from xml.sax.saxutils import escape
import reportlab
from PIL import Image
from reportlab.lib.utils import ImageReader
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
def render(data,logo=None):
fonts=os.path.join(os.path.dirname(reportlab.__file__),'fonts')
regular=os.path.join(fonts,'Vera.ttf');bold=os.path.join(fonts,'VeraBd.ttf')
if not os.path.isfile(regular):
regular='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf';bold='/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf'
pdfmetrics.registerFont(TTFont('Rates',regular))
pdfmetrics.registerFont(TTFont('RatesBold',bold))
pdfmetrics.registerFontFamily('Rates',normal='Rates',bold='RatesBold',italic='Rates',boldItalic='RatesBold')
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,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'
percent=lambda n:f'{int(n)/100:.2f}%'
published=datetime.fromtimestamp(data['publishedAt']/1000,ZoneInfo('Europe/Brussels')).strftime('%d %B %Y %H:%M')
logo_image=None
if logo and os.path.isfile(logo):
with Image.open(logo) as image:
image=image.convert('RGBA');image.thumbnail((720,200));logo_image=ImageReader(image.copy())
output=io.BytesIO();document=SimpleDocTemplate(output,pagesize=A4,leftMargin=42,rightMargin=42,topMargin=101,bottomMargin=61,title='Imperial Postbank - Rates & Charges',author='Imperial Postbank')
def frame(canvas,doc):
w,h=A4;canvas.setFillColor(green);canvas.rect(0,h-80,w,80,fill=1,stroke=0)
if logo_image:canvas.drawImage(logo_image,42,h-66,width=163,height=45,preserveAspectRatio=True,mask='auto')
else:canvas.setFillColor(colors.white);canvas.setFont('RatesBold',18);canvas.drawString(42,h-44,'Imperial Postbank')
canvas.setFillColor(colors.HexColor('#eedca7'));canvas.setFont('RatesBold',10);canvas.drawRightString(w-42,h-36,'RATES & CHARGES');canvas.setFont('Rates',8);canvas.drawRightString(w-42,h-54,published+' - Brussels')
canvas.setStrokeColor(gold);canvas.line(42,47,w-42,47);canvas.setFillColor(ink);canvas.setFont('Rates',7);canvas.drawString(42,33,'DuneRealms | Fictional game currency | No real-world banking product');canvas.drawRightString(w-42,33,'Page '+str(doc.page))
def grid(headers,rows,widths):
table=Table([[p(c,small) for c in headers]]+[[p(c,small) for c in row]for row in rows],colWidths=widths,repeatRows=1,hAlign='LEFT')
table.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),colors.HexColor('#e4ece5')),('ROWBACKGROUNDS',(0,1),(-1,-1),[colors.white,colors.HexColor('#f5f7f3')]),('VALIGN',(0,0),(-1,-1),'TOP'),('LINEBELOW',(0,0),(-1,0),1,gold),('LINEBELOW',(0,1),(-1,-1),.3,colors.HexColor('#d8e0d5')),('LEFTPADDING',(0,0),(-1,-1),9),('RIGHTPADDING',(0,0),(-1,-1),9),('TOPPADDING',(0,0),(-1,-1),6),('BOTTOMPADDING',(0,0),(-1,-1),6)]));return table
story=[p('Rates & Charges',title),p('Public tariff register for Imperial Postbank. All amounts are Dunemarks (DM), a fictional game currency.'),p('Publication '+data['version']+' | '+published,small),p('Account packages',heading)]
story.append(grid(['Package','Monthly charge','Additional current account'],[[r['name'],cash(r['monthlyMinor']),cash(r['extraMinor'])]for r in data['packages']],[180,150,181]))
story.append(p('Existing accepted package prices remain recorded on each contract. Published changes apply to new package acceptance; changing an existing package requires confirmation.',small))
story.append(p('Services & payment processing',heading))
for notice in data.get('serviceNotices',[]):story.append(p(notice))
story.extend([PageBreak(),p('Credit interest',title)]);story.append(grid(['Product','Annual interest','Availability'],[[r['name'],percent(r['annualBps']),r.get('availability','Subject to approval')]for r in data['credit']],[240,110,161]))
story.append(p('Accepted credit contracts keep their agreed interest rate and repayment schedule. Grants remain interest-free.',small))
story.extend([PageBreak(),p('Taxes & deductions',title),p('These are DuneRealms game rules. The payroll model uses selected Belgian-inspired parameters; it is not a personal tax calculation or a Belgian payslip.'),p('Account & transaction taxes',heading)])
taxes=data['taxes'];story.append(grid(['Tax','Rate'],[['VAT on applicable game sales',percent(taxes['vatBps'])],['VAT on bank fees',percent(taxes['bankFeeVatBps'])],['Monthly account tax',cash(taxes['monthlyAccountTaxMinor'])]],[350,161]))
tax=data['payrollTax'];story.append(p('Payroll contributions',heading));story.append(grid(['Contribution','Rate'],[['Employee social contribution',percent(tax['employeeSocialBps'])],['Employer social contribution',percent(tax['employerSocialBps'])],['Annual basic allowance',cash(tax['annualAllowanceMinor'])]],[350,161]))
bands=[];start=0
for b in tax['bands']:
bands.append([cash(start)+' to '+cash(b['upToMinor']) if b['upToMinor']is not None else 'Above '+cash(start),percent(b['bps'])]);start=b['upToMinor']
story.append(p('Annual progressive payroll income tax',heading));story.append(grid(['Taxable annual band','Rate'],bands,[350,161]))
story.append(p('The basic allowance is applied as a tax credit. Household circumstances, regional additions, work bonuses and other real-world deductions are outside this fictional model. Individual staff salaries are private and are not included here.',small))
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))