Add Payslip Generator tool

A self-contained, entirely client-side tool (fill in details, live
preview, download PDF) - no server-side business logic, so unlike the
other tools there's no logic.py, just a route serving the page.

- Wired into the platform: Blueprint at /payslip/, registered in
  main.py, landing-page card added.
- Header logo linked back to / (every other tool's header does this;
  the original standalone page didn't).
- SRI-pinned the PDF-generation script tags so a compromised/MITM'd CDN
  response can't silently run in a page handling employee/contractor
  pay data.
- Earnings/deductions columns padded with blank filler rows so
  "Gross earnings" and "Total deductions" always land on the same
  line, regardless of how many rows either side has.
- Rewrote PDF generation to call html2canvas + jsPDF directly instead
  of through html2pdf.js: its bundled html2canvas mis-rendered (blank
  or truncated) shorter payslips, reproducible and confirmed via a
  controlled A/B test against the current standalone html2canvas.
  Direct usage also fixes page-fit (custom page size, hotfixes for
  correct px scaling, orientation/rounding handled explicitly) so the
  PDF matches the on-screen preview on a single page.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-08-27 17:41:52 -04:00
parent dfd3a710e0
commit 3336bf98bb
4 changed files with 877 additions and 0 deletions

View File

@ -4,6 +4,7 @@ from flask import Flask, render_template
from tools.eib import eib_bp
from tools.donor_report import donor_report_bp
from tools.financial_reports import financial_reports_bp
from tools.payslip import payslip_bp
# ── Tool registry ────────────────────────────────────────────────────────────
# Each entry drives one card on the landing page. Add a new tool by
@ -42,6 +43,17 @@ TOOLS = [
"url": "/financial-reports/",
"status": "online",
},
{
"name": "Payslip Generator",
"tagline": "Fill in, preview, download PDF",
"description": (
"Generates a formatted payslip from company/employee details and "
"earnings/deductions lines, entirely in the browser - nothing is "
"uploaded to a server."
),
"url": "/payslip/",
"status": "online",
},
]
@ -54,6 +66,7 @@ def create_app():
app.register_blueprint(eib_bp)
app.register_blueprint(donor_report_bp)
app.register_blueprint(financial_reports_bp)
app.register_blueprint(payslip_bp)
@app.route("/")
def home():

View File

@ -0,0 +1,3 @@
from .routes import payslip_bp
__all__ = ["payslip_bp"]

View File

@ -0,0 +1,12 @@
from flask import Blueprint, render_template
# Payslip Generator is entirely client-side (form -> live preview -> PDF, all
# in the browser, nothing uploaded) - there's no server-side business logic,
# so unlike this repo's other tools there's no logic.py here, just the one
# page route.
payslip_bp = Blueprint("payslip", __name__, url_prefix="/payslip")
@payslip_bp.route("/")
def index():
return render_template("payslip/index.html")

View File

@ -0,0 +1,849 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Payslip Generator — Undo Designs</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&family=Newsreader:wght@400;500;600&display=swap" rel="stylesheet">
<!-- html2pdf.js 0.10.1 bundles an old html2canvas that mis-renders this
page for certain (short) content - confirmed by testing the current
standalone html2canvas directly, which renders it correctly. Loading
html2canvas + jsPDF separately (current versions) and driving them
ourselves avoids that bug entirely - see the Download PDF handler. -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"
integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/4.2.1/jspdf.umd.min.js"
integrity="sha512-plOdviVmws4Y3JAvbnpfKb2hVxKM1lCwsi3vmElYRj+tiDLffZ4FVUj5a8vyKJ9pIgl8JCAHEJ4D1iUKBecswg=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
:root {
--navy: #0C1A3A;
--navy-2: #12244C;
--navy-3: #1a2f5e;
--navy-4: #0a1428;
--cyan: #00D4FF;
--cyan-dim: rgba(0,212,255,.12);
--cyan-glow: rgba(0,212,255,.06);
--blue: #1B8EF8;
--green: #10D98A;
--green-dim: rgba(16,217,138,.12);
--red: #F04438;
--red-dim: rgba(240,68,56,.12);
--w1: rgba(255,255,255,.95);
--w2: rgba(255,255,255,.65);
--w3: rgba(255,255,255,.35);
--w4: rgba(255,255,255,.10);
--w5: rgba(255,255,255,.05);
--border: rgba(255,255,255,.07);
--border-c: rgba(0,212,255,.18);
--mono: 'JetBrains Mono', monospace;
--disp: 'Space Grotesk', sans-serif;
--body: 'Inter', sans-serif;
--radius: 10px;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: var(--body);
background: var(--navy-4);
color: var(--w1);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
}
body::before {
content: '';
position: fixed; inset: 0; pointer-events: none; z-index: 0;
background-image: radial-gradient(circle, rgba(0,212,255,.06) 1px, transparent 1px);
background-size: 28px 28px;
}
header {
position: sticky; top: 0; z-index: 100;
background: rgba(12,26,58,.9);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
padding: 0 28px;
height: 58px;
display: flex; align-items: center; justify-content: space-between;
}
.logo-mark {
display: flex; align-items: center; gap: 10px;
font-family: var(--disp); font-size: 15px; font-weight: 600;
color: var(--w1); text-decoration: none;
}
.logo-mark-icon {
width: 28px; height: 28px;
background: linear-gradient(135deg, var(--navy-3), var(--navy-2));
border: 1px solid var(--border-c);
border-radius: 7px;
display: flex; align-items: center; justify-content: center;
}
.logo-mark-icon svg { width: 15px; height: 15px; }
.logo-mark span { color: var(--cyan); }
.privacy-badge {
display: flex; align-items: center; gap: 6px;
font-family: var(--mono); font-size: 10.5px; color: var(--green);
background: var(--green-dim); border: 1px solid rgba(16,217,138,.25);
padding: 5px 12px; border-radius: 20px;
}
.privacy-badge svg { width: 12px; height: 12px; }
main {
position: relative; z-index: 1;
max-width: 1400px; margin: 0 auto;
padding: 32px 24px 80px;
display: grid;
grid-template-columns: 420px 1fr;
gap: 24px;
align-items: start;
}
@media (max-width: 980px) {
main { grid-template-columns: 1fr; }
}
.page-title { margin-bottom: 20px; grid-column: 1 / -1; }
.eyebrow {
font-family: var(--mono); font-size: 10px; letter-spacing: .16em;
text-transform: uppercase; color: var(--cyan); margin-bottom: 8px;
}
.page-title h1 {
font-family: var(--disp); font-size: 24px; font-weight: 700; margin-bottom: 6px;
}
.page-title p { font-size: 13px; color: var(--w2); line-height: 1.6; max-width: 560px; }
/* ── FORM PANEL ── */
.panel {
background: var(--navy-2);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 20px;
margin-bottom: 16px;
}
.panel-title {
font-family: var(--disp); font-size: 13px; font-weight: 600;
display: flex; align-items: center; gap: 8px;
margin-bottom: 16px; color: var(--w1);
}
.panel-num {
width: 20px; height: 20px; border-radius: 50%;
background: var(--cyan-dim); border: 1px solid var(--border-c);
color: var(--cyan); font-family: var(--mono); font-size: 10px;
display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.field { margin-bottom: 12px; }
.field:last-child { margin-bottom: 0; }
.field label {
display: block; font-family: var(--mono); font-size: 10px;
letter-spacing: .06em; text-transform: uppercase; color: var(--w3);
margin-bottom: 5px;
}
.field input[type="text"],
.field input[type="date"],
.field input[type="number"],
.field textarea {
width: 100%; background: var(--navy-4); border: 1px solid var(--border);
border-radius: 6px; padding: 9px 11px; color: var(--w1);
font-family: var(--body); font-size: 13px; transition: border-color .15s;
}
.field textarea { resize: vertical; min-height: 52px; font-family: var(--body); }
.field input:focus, .field textarea:focus {
outline: none; border-color: var(--cyan); background: var(--cyan-glow);
}
.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.field-row-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; }
/* ── LOGO UPLOAD ── */
.logo-zone {
border: 1.5px dashed var(--border); border-radius: 8px;
padding: 16px; text-align: center; cursor: pointer;
transition: all .2s; position: relative;
}
.logo-zone:hover, .logo-zone.drag-over { border-color: var(--cyan); background: var(--cyan-glow); }
.logo-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
.logo-zone-empty { font-size: 12px; color: var(--w2); }
.logo-zone-empty strong { color: var(--cyan); }
.logo-preview-wrap {
display: none; align-items: center; gap: 12px; justify-content: center;
}
.logo-preview-wrap.visible { display: flex; }
.logo-preview-wrap img { max-height: 44px; max-width: 140px; border-radius: 4px; background: #fff; padding: 4px; }
.logo-remove {
background: var(--red-dim); border: 1px solid rgba(240,68,56,.25); color: var(--red);
font-family: var(--mono); font-size: 10px; padding: 4px 10px; border-radius: 6px;
cursor: pointer;
}
/* ── ROW LISTS (earnings/deductions) ── */
.line-items { margin-bottom: 10px; }
.line-item {
display: grid; grid-template-columns: 1fr 110px 28px; gap: 8px;
margin-bottom: 8px; align-items: center;
}
.line-item input { width: 100%; }
.line-remove {
width: 28px; height: 28px; border-radius: 6px;
background: var(--w5); border: 1px solid var(--border); color: var(--w3);
cursor: pointer; font-size: 14px; display: flex; align-items: center; justify-content: center;
transition: all .15s;
}
.line-remove:hover { background: var(--red-dim); border-color: rgba(240,68,56,.3); color: var(--red); }
.btn-add-line {
width: 100%; padding: 8px; border-radius: 6px;
background: var(--w5); border: 1px dashed var(--border); color: var(--w2);
font-family: var(--mono); font-size: 11px; cursor: pointer; transition: all .15s;
}
.btn-add-line:hover { border-color: var(--cyan); color: var(--cyan); background: var(--cyan-glow); }
/* ── BUTTONS ── */
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 7px;
padding: 11px 18px; border-radius: 8px; border: none;
font-family: var(--disp); font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .2s;
}
.btn-primary { background: linear-gradient(135deg, var(--cyan), var(--blue)); color: var(--navy); }
.btn-primary:hover { filter: brightness(1.08); transform: translateY(-1px); }
.btn-ghost { background: var(--w5); border: 1px solid var(--border); color: var(--w2); }
.btn-ghost:hover { border-color: var(--border-c); color: var(--w1); }
.btn-full { width: 100%; }
.btn-row { display: flex; gap: 10px; grid-column: 1 / -1; margin-top: 4px; }
.btn-row .btn { flex: 1; }
/* ── PAYSLIP PREVIEW (the actual printable document) ── */
.preview-wrap { position: sticky; top: 78px; }
.preview-toolbar {
display: flex; align-items: center; justify-content: space-between;
margin-bottom: 12px;
}
.preview-label {
font-family: var(--mono); font-size: 10px; letter-spacing: .12em;
text-transform: uppercase; color: var(--w3);
}
#payslip {
background: #ffffff;
color: #1a1a1a;
border-radius: 4px;
box-shadow: 0 20px 50px rgba(0,0,0,.4);
padding: 44px 48px;
font-family: 'Inter', Arial, sans-serif;
max-width: 760px;
margin: 0 auto;
}
.ps-header {
display: flex; justify-content: space-between; align-items: flex-start;
padding-bottom: 20px; margin-bottom: 20px;
border-bottom: 2px solid #1a1a1a;
}
.ps-company-block { display: flex; align-items: center; gap: 14px; }
.ps-logo-img { max-height: 52px; max-width: 160px; object-fit: contain; }
.ps-company-name { font-family: 'Newsreader', Georgia, serif; font-size: 20px; font-weight: 600; color: #111; }
.ps-company-address { font-size: 11px; color: #555; margin-top: 3px; white-space: pre-line; line-height: 1.5; max-width: 260px; }
.ps-doc-title { text-align: right; }
.ps-doc-title h2 {
font-family: 'Newsreader', Georgia, serif; font-size: 22px; font-weight: 600;
letter-spacing: .01em; color: #111;
}
.ps-doc-title .ps-period { font-size: 12px; color: #666; margin-top: 4px; }
.ps-meta-grid {
display: grid; grid-template-columns: 1fr 1fr; gap: 4px 32px;
margin-bottom: 24px; font-size: 12px;
}
.ps-meta-item { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid #eee; }
.ps-meta-item span:first-child { color: #666; }
.ps-meta-item span:last-child { font-weight: 500; color: #111; }
.ps-tables { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 20px; }
.ps-table-title {
font-size: 10.5px; letter-spacing: .08em; text-transform: uppercase;
color: #666; font-weight: 600; padding-bottom: 6px; margin-bottom: 8px;
border-bottom: 1px solid #1a1a1a;
}
.ps-table-title.deductions { color: #8a3a3a; border-bottom-color: #8a3a3a; }
.ps-line { display: flex; justify-content: space-between; padding: 5px 0; font-size: 12.5px; }
.ps-line span:first-child { color: #333; }
.ps-line span:last-child { font-variant-numeric: tabular-nums; color: #111; }
.ps-line-filler { visibility: hidden; }
.ps-subtotal {
display: flex; justify-content: space-between; padding-top: 8px; margin-top: 6px;
border-top: 1px solid #1a1a1a; font-size: 12.5px; font-weight: 600;
}
.ps-summary {
background: #f7f7f5; border-radius: 6px; padding: 16px 20px; margin-top: 8px;
}
.ps-summary-row { display: flex; justify-content: space-between; font-size: 13px; padding: 4px 0; }
.ps-summary-row.net {
font-size: 16px; font-weight: 700; padding-top: 10px; margin-top: 6px;
border-top: 1.5px solid #1a1a1a; color: #0a5c3a;
}
.ps-words {
margin-top: 10px; font-size: 11px; color: #666; font-style: italic;
}
.ps-footer {
margin-top: 28px; padding-top: 14px; border-top: 1px solid #eee;
font-size: 10px; color: #999; text-align: center;
}
footer.app-footer {
position: relative; z-index: 1; text-align: center; padding: 24px;
font-size: 11px; color: var(--w3); border-top: 1px solid var(--border);
margin-top: 20px;
}
footer.app-footer a { color: var(--cyan); text-decoration: none; }
/* ── PRINT: isolate only the payslip ── */
@media print {
body * { visibility: hidden; }
#payslip, #payslip * { visibility: visible; }
#payslip {
position: absolute; left: 0; top: 0; width: 100%;
box-shadow: none; max-width: none;
}
body::before { display: none; }
}
</style>
</head>
<body>
<header>
<a class="logo-mark" href="/">
<div class="logo-mark-icon">
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4h12M2 8h8M2 12h5" stroke="#00D4FF" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</div>
Payslip <span>Generator</span>
</a>
<div class="privacy-badge">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
</svg>
Runs entirely in your browser — nothing is uploaded
</div>
</header>
<main>
<div class="page-title">
<div class="eyebrow">Undo Designs</div>
<h1>Payslip Generator</h1>
<p>Fill in the details on the left — the payslip updates live on the right. Your company logo, employee data, and figures never leave this page: there's no server, no upload, no tracking.</p>
</div>
<!-- ── FORM COLUMN ── -->
<div>
<div class="panel">
<div class="panel-title"><span class="panel-num">1</span>Company</div>
<div class="field">
<label>Logo (optional)</label>
<div class="logo-zone" id="logoZone">
<input type="file" id="logoInput" accept="image/*">
<div class="logo-zone-empty" id="logoEmpty"><strong>Click to upload</strong> or drag & drop — stays on this page only</div>
<div class="logo-preview-wrap" id="logoPreviewWrap">
<img id="logoPreviewImg" alt="Logo preview">
<button class="logo-remove" id="logoRemoveBtn" type="button">Remove</button>
</div>
</div>
</div>
<div class="field">
<label>Company name</label>
<input type="text" id="companyName" value="Undo Designs">
</div>
<div class="field">
<label>Company address</label>
<textarea id="companyAddress">19 Charlotte Street&#10;Toronto, ON M5V 2H5</textarea>
</div>
</div>
<div class="panel">
<div class="panel-title"><span class="panel-num">2</span>Contractor</div>
<div class="field-row">
<div class="field">
<label>Contractor name</label>
<input type="text" id="empName" value="Jordan Rivers">
</div>
<div class="field">
<label>Contractor ID</label>
<input type="text" id="empId" value="EMP-0142">
</div>
</div>
<div class="field-row">
<div class="field">
<label>Designation</label>
<input type="text" id="empTitle" value="Software Engineer">
</div>
<div class="field">
<label>Department</label>
<input type="text" id="empDept" value="Engineering">
</div>
</div>
<div class="field-row">
<div class="field">
<label>Pay period</label>
<input type="text" id="payPeriod" value="August 2026">
</div>
<div class="field">
<label>Pay date</label>
<input type="date" id="payDate">
</div>
</div>
<div class="field-row">
<div class="field">
<label>Bank name</label>
<input type="text" id="bankName" value="">
</div>
<div class="field">
<label>Account (last 4)</label>
<input type="text" id="bankAcct" value="" maxlength="4" placeholder="4417">
</div>
</div>
<div class="field">
<label>Currency symbol</label>
<input type="text" id="currency" value="$" maxlength="4" style="max-width:80px">
</div>
</div>
<div class="panel">
<div class="panel-title"><span class="panel-num">3</span>Earnings</div>
<div class="line-items" id="earningsList"></div>
<button class="btn-add-line" id="addEarningBtn" type="button">+ Add earning line</button>
</div>
<div class="panel">
<div class="panel-title"><span class="panel-num">4</span>Deductions</div>
<div class="line-items" id="deductionsList"></div>
<button class="btn-add-line" id="addDeductionBtn" type="button">+ Add deduction line</button>
</div>
<div class="btn-row" style="margin-bottom:16px">
<button class="btn btn-ghost" id="resetBtn" type="button">Reset</button>
<button class="btn btn-ghost" id="saveDraftBtn" type="button">Save draft</button>
</div>
</div>
<!-- ── PREVIEW COLUMN ── -->
<div class="preview-wrap">
<div class="preview-toolbar">
<div class="preview-label">Live preview</div>
<div style="display:flex; gap:8px">
<button class="btn btn-ghost" id="printBtn" type="button">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="6,9 6,2 18,2 18,9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
Print
</button>
<button class="btn btn-primary" id="downloadBtn" type="button">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7,10 12,15 17,10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
Download PDF
</button>
</div>
</div>
<div id="payslip">
<div class="ps-header">
<div class="ps-company-block">
<img id="psLogo" class="ps-logo-img" style="display:none" alt="">
<div>
<div class="ps-company-name" id="psCompanyName">Undo Designs</div>
<div class="ps-company-address" id="psCompanyAddress">19 Charlotte Street
Toronto, ON M5V 2H5</div>
</div>
</div>
<div class="ps-doc-title">
<h2>Payslip</h2>
<div class="ps-period" id="psPeriod">August 2026</div>
</div>
</div>
<div class="ps-meta-grid">
<div class="ps-meta-item"><span>Contractor name</span><span id="psEmpName">Jordan Rivers</span></div>
<div class="ps-meta-item"><span>Contractor ID</span><span id="psEmpId">EMP-0142</span></div>
<div class="ps-meta-item"><span>Designation</span><span id="psEmpTitle">Software Engineer</span></div>
<div class="ps-meta-item"><span>Department</span><span id="psEmpDept">Engineering</span></div>
<div class="ps-meta-item"><span>Pay date</span><span id="psPayDate">—</span></div>
<div class="ps-meta-item" id="psBankRow"><span>Bank account</span><span id="psBankInfo">—</span></div>
</div>
<div class="ps-tables">
<div>
<div class="ps-table-title">Earnings</div>
<div id="psEarnings"></div>
<div class="ps-subtotal"><span>Gross earnings</span><span id="psGross">0.00</span></div>
</div>
<div>
<div class="ps-table-title deductions">Deductions</div>
<div id="psDeductions"></div>
<div class="ps-subtotal"><span>Total deductions</span><span id="psTotalDed">0.00</span></div>
</div>
</div>
<div class="ps-summary">
<div class="ps-summary-row"><span>Gross earnings</span><span id="psSummaryGross">0.00</span></div>
<div class="ps-summary-row"><span>Total deductions</span><span id="psSummaryDed">0.00</span></div>
<div class="ps-summary-row net"><span>Net pay</span><span id="psNetPay">0.00</span></div>
<div class="ps-words" id="psWords">Zero only</div>
</div>
<div class="ps-footer">This payslip is computer-generated and does not require a signature.</div>
</div>
</div>
</main>
<footer class="app-footer">
Built by <a href="https://undodesigns.com" target="_blank">Undo Designs</a> · Payslip Generator v1 · 100% client-side
</footer>
<script>
const $ = id => document.getElementById(id);
// ── State ────────────────────────────────────────────────────────────────────
let earnings = [
{ desc: 'Basic Salary', amount: 4200.00 },
{ desc: 'Housing Allowance', amount: 600.00 },
{ desc: 'Transport Allowance', amount: 150.00 },
];
let deductions = [
{ desc: 'Income Tax', amount: 780.00 },
{ desc: 'Retirement Contribution', amount: 210.00 },
];
let logoDataUrl = null;
// ── Number to words ────────────────────────────────────────────────────────────
function numberToWords(num) {
const ones = ['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten',
'Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen'];
const tens = ['','','Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety'];
function chunk(n) {
let s = '';
if (n >= 100) { s += ones[Math.floor(n / 100)] + ' Hundred '; n %= 100; }
if (n >= 20) { s += tens[Math.floor(n / 10)] + ' '; n %= 10; }
if (n > 0) { s += ones[n] + ' '; }
return s;
}
if (num === 0) return 'Zero';
const intPart = Math.floor(Math.abs(num));
let result = '';
let n = intPart;
const scales = [
[1000000000, 'Billion'], [1000000, 'Million'], [1000, 'Thousand'],
];
for (const [value, label] of scales) {
if (n >= value) {
result += chunk(Math.floor(n / value)) + label + ' ';
n %= value;
}
}
if (n > 0) result += chunk(n);
return result.trim() || 'Zero';
}
function formatWords(num) {
const cur = $('currency').value.trim() || '$';
const intPart = Math.floor(Math.abs(num));
const cents = Math.round((Math.abs(num) - intPart) * 100);
let words = numberToWords(intPart);
if (cents > 0) {
words += ` and ${cents}/100`;
}
return `${words} Only`;
}
// ── Formatting ──────────────────────────────────────────────────────────────
function fmt(n) {
const cur = $('currency').value.trim() || '$';
return cur + ' ' + (n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
// ── Line item rendering (form side) ────────────────────────────────────────────
function renderLineItems(listEl, items, onChange) {
listEl.innerHTML = '';
items.forEach((item, idx) => {
const row = document.createElement('div');
row.className = 'line-item';
row.innerHTML = `
<input type="text" value="${escapeAttr(item.desc)}" data-idx="${idx}" data-field="desc">
<input type="number" step="0.01" value="${item.amount}" data-idx="${idx}" data-field="amount">
<button class="line-remove" data-idx="${idx}" type="button">✕</button>
`;
listEl.appendChild(row);
});
listEl.querySelectorAll('input').forEach(inp => {
inp.addEventListener('input', () => {
const idx = +inp.dataset.idx;
const field = inp.dataset.field;
items[idx][field] = field === 'amount' ? (parseFloat(inp.value) || 0) : inp.value;
onChange();
renderPayslip();
});
});
listEl.querySelectorAll('.line-remove').forEach(btn => {
btn.addEventListener('click', () => {
items.splice(+btn.dataset.idx, 1);
renderLineItems(listEl, items, onChange);
renderPayslip();
});
});
}
function escapeAttr(s) {
return String(s).replace(/&/g,'&amp;').replace(/"/g,'&quot;');
}
function escapeHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function refreshEarnings() { renderLineItems($('earningsList'), earnings, () => {}); }
function refreshDeductions() { renderLineItems($('deductionsList'), deductions, () => {}); }
$('addEarningBtn').addEventListener('click', () => {
earnings.push({ desc: '', amount: 0 });
refreshEarnings();
renderPayslip();
});
$('addDeductionBtn').addEventListener('click', () => {
deductions.push({ desc: '', amount: 0 });
refreshDeductions();
renderPayslip();
});
// ── Logo upload (client-side only, never leaves the browser) ──────────────────
const logoInput = $('logoInput');
const logoZone = $('logoZone');
function handleLogoFile(file) {
if (!file || !file.type.startsWith('image/')) return;
const reader = new FileReader();
reader.onload = e => {
logoDataUrl = e.target.result;
$('logoPreviewImg').src = logoDataUrl;
$('logoPreviewWrap').classList.add('visible');
$('logoEmpty').style.display = 'none';
renderPayslip();
};
reader.readAsDataURL(file);
}
logoInput.addEventListener('change', () => handleLogoFile(logoInput.files[0]));
logoZone.addEventListener('dragover', e => { e.preventDefault(); logoZone.classList.add('drag-over'); });
logoZone.addEventListener('dragleave', () => logoZone.classList.remove('drag-over'));
logoZone.addEventListener('drop', e => {
e.preventDefault(); logoZone.classList.remove('drag-over');
if (e.dataTransfer.files[0]) handleLogoFile(e.dataTransfer.files[0]);
});
$('logoRemoveBtn').addEventListener('click', (e) => {
e.stopPropagation();
logoDataUrl = null;
logoInput.value = '';
$('logoPreviewWrap').classList.remove('visible');
$('logoEmpty').style.display = 'block';
renderPayslip();
});
// ── Live payslip rendering ──────────────────────────────────────────────────
function renderPayslip() {
$('psCompanyName').textContent = $('companyName').value || 'Company Name';
$('psCompanyAddress').textContent = $('companyAddress').value;
$('psPeriod').textContent = $('payPeriod').value || '—';
$('psEmpName').textContent = $('empName').value || '—';
$('psEmpId').textContent = $('empId').value || '—';
$('psEmpTitle').textContent = $('empTitle').value || '—';
$('psEmpDept').textContent = $('empDept').value || '—';
const payDateVal = $('payDate').value;
$('psPayDate').textContent = payDateVal
? new Date(payDateVal + 'T00:00:00').toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })
: '—';
const bankName = $('bankName').value.trim();
const bankAcct = $('bankAcct').value.trim();
if (bankName || bankAcct) {
$('psBankInfo').textContent = `${bankName || '—'}${bankAcct ? ' •••• ' + bankAcct : ''}`;
$('psBankRow').style.display = 'flex';
} else {
$('psBankRow').style.display = 'none';
}
if (logoDataUrl) {
$('psLogo').src = logoDataUrl;
$('psLogo').style.display = 'block';
} else {
$('psLogo').style.display = 'none';
}
// Earnings / Deductions - padded with blank filler rows so "Gross
// earnings" and "Total deductions" always land on the same line, even
// when one side has fewer rows (or none at all).
const fillerLines = n => '<div class="ps-line ps-line-filler"><span>&nbsp;</span><span>&nbsp;</span></div>'.repeat(Math.max(0, n));
const maxLines = Math.max(earnings.length, deductions.length);
const earningsEl = $('psEarnings');
earningsEl.innerHTML = earnings.map(e =>
`<div class="ps-line"><span>${escapeHtml(e.desc || 'Untitled')}</span><span>${fmt(e.amount)}</span></div>`
).join('') + fillerLines(maxLines - earnings.length);
const gross = earnings.reduce((s, e) => s + (parseFloat(e.amount) || 0), 0);
$('psGross').textContent = fmt(gross);
const dedEl = $('psDeductions');
dedEl.innerHTML = deductions.map(d =>
`<div class="ps-line"><span>${escapeHtml(d.desc || 'Untitled')}</span><span>${fmt(d.amount)}</span></div>`
).join('') + fillerLines(maxLines - deductions.length);
const totalDed = deductions.reduce((s, d) => s + (parseFloat(d.amount) || 0), 0);
$('psTotalDed').textContent = fmt(totalDed);
// Summary
const net = gross - totalDed;
$('psSummaryGross').textContent = fmt(gross);
$('psSummaryDed').textContent = fmt(totalDed);
$('psNetPay').textContent = fmt(net);
$('psWords').textContent = formatWords(net);
}
// ── Wire up all top-level fields to live-update ────────────────────────────────
['companyName','companyAddress','empName','empId','empTitle','empDept','payPeriod',
'payDate','bankName','bankAcct','currency'].forEach(id => {
$(id).addEventListener('input', renderPayslip);
});
// ── Reset ─────────────────────────────────────────────────────────────────────
$('resetBtn').addEventListener('click', () => {
if (!confirm('Clear all fields and start over?')) return;
['companyName','companyAddress','empName','empId','empTitle','empDept','payPeriod',
'bankName','bankAcct'].forEach(id => $(id).value = '');
$('currency').value = '$';
$('payDate').value = '';
earnings = [{ desc: '', amount: 0 }];
deductions = [{ desc: '', amount: 0 }];
logoDataUrl = null;
$('logoPreviewWrap').classList.remove('visible');
$('logoEmpty').style.display = 'block';
logoInput.value = '';
refreshEarnings();
refreshDeductions();
renderPayslip();
});
// ── Save / load draft (localStorage - stays on this device only) ──────────────
$('saveDraftBtn').addEventListener('click', () => {
const draft = {
companyName: $('companyName').value, companyAddress: $('companyAddress').value,
empName: $('empName').value, empId: $('empId').value, empTitle: $('empTitle').value,
empDept: $('empDept').value, payPeriod: $('payPeriod').value, payDate: $('payDate').value,
bankName: $('bankName').value, bankAcct: $('bankAcct').value, currency: $('currency').value,
earnings, deductions, logoDataUrl,
};
localStorage.setItem('payslip_draft', JSON.stringify(draft));
const btn = $('saveDraftBtn');
const original = btn.textContent;
btn.textContent = 'Saved ✓';
setTimeout(() => btn.textContent = original, 1500);
});
function loadDraft() {
const raw = localStorage.getItem('payslip_draft');
if (!raw) return;
try {
const d = JSON.parse(raw);
$('companyName').value = d.companyName ?? $('companyName').value;
$('companyAddress').value = d.companyAddress ?? $('companyAddress').value;
$('empName').value = d.empName ?? $('empName').value;
$('empId').value = d.empId ?? $('empId').value;
$('empTitle').value = d.empTitle ?? $('empTitle').value;
$('empDept').value = d.empDept ?? $('empDept').value;
$('payPeriod').value = d.payPeriod ?? $('payPeriod').value;
$('payDate').value = d.payDate ?? '';
$('bankName').value = d.bankName ?? '';
$('bankAcct').value = d.bankAcct ?? '';
$('currency').value = d.currency ?? '$';
if (Array.isArray(d.earnings) && d.earnings.length) earnings = d.earnings;
if (Array.isArray(d.deductions) && d.deductions.length) deductions = d.deductions;
if (d.logoDataUrl) {
logoDataUrl = d.logoDataUrl;
$('logoPreviewImg').src = logoDataUrl;
$('logoPreviewWrap').classList.add('visible');
$('logoEmpty').style.display = 'none';
}
} catch (e) { /* ignore corrupt draft */ }
}
// ── Print ─────────────────────────────────────────────────────────────────────
$('printBtn').addEventListener('click', () => window.print());
// ── Download PDF (client-side, html2canvas + jsPDF directly) ──────────────────
// Not html2pdf.js: its bundled html2canvas (0.10.1's dependency) mis-renders
// this page for shorter payslips - confirmed by testing (rendered blank or
// truncated for a payslip with only 1-2 line items per side, reproducibly).
// The current standalone html2canvas renders the exact same content
// correctly, so we call html2canvas + jsPDF ourselves instead of going
// through html2pdf.js's wrapper.
$('downloadBtn').addEventListener('click', async () => {
const el = $('payslip');
const empName = ($('empName').value || 'payslip').replace(/[^a-z0-9]+/gi, '_');
const period = ($('payPeriod').value || '').replace(/[^a-z0-9]+/gi, '_');
const filename = `Payslip_${empName}${period ? '_' + period : ''}.pdf`;
if (!window.html2canvas || !window.jspdf) {
alert('PDF library did not load (likely no internet connection). Use Print instead and choose "Save as PDF" in the print dialog.');
window.print();
return;
}
const w = el.offsetWidth, h = el.offsetHeight;
const canvas = await html2canvas(el, {
scale: 2, useCORS: true, backgroundColor: '#ffffff',
// The on-screen card has a drop shadow for the floating-card look;
// that's screen chrome, not part of the document, so strip it on the
// cloned copy html2canvas rasterizes, or it gets baked into the page
// as a clipped smudge along the edges instead of a clean white page.
onclone: (doc) => {
const clone = doc.getElementById('payslip');
if (clone) clone.style.boxShadow = 'none';
},
});
const imgData = canvas.toDataURL('image/jpeg', 0.98);
// unit:'px' + format sized to the element's own CSS-pixel dimensions
// makes the PDF page fit the content on one page, matching what's on
// screen. Two things this needs to stay a single, uncropped page:
// - hotfixes:['px_scaling'] - required for jsPDF to interpret px
// dimensions at the correct 96dpi (CSS) scale instead of its legacy
// 72dpi assumption, which otherwise mis-sizes the page.
// - height is never less than width (Math.max), always with
// orientation:'portrait'. A short payslip (few line items) can
// render wider than tall; giving jsPDF a landscape-shaped array
// while declaring 'portrait' makes it swap width/height on its own
// and mismatch the placed image. A short payslip just gets a bit of
// blank space at the bottom instead.
// - a small +8px height buffer: a page sized to EXACTLY match content
// height can round to just under the image height and force a
// trailing near-empty second page; +8px gives headroom against that
// without a visible gap.
const { jsPDF } = window.jspdf;
const pdf = new jsPDF({
unit: 'px', format: [w, Math.max(h, w) + 8],
orientation: 'portrait', hotfixes: ['px_scaling'],
});
pdf.addImage(imgData, 'JPEG', 0, 0, w, h);
pdf.save(filename);
});
// ── Init ──────────────────────────────────────────────────────────────────────
refreshEarnings();
refreshDeductions();
loadDraft();
renderPayslip();
</script>
</body>
</html>