// docgen.js - synthetic enterprise document generator used to build the
// hyperbots-inc/synthetic-* datasets on the Hugging Face Hub.
// Everything (companies, people, IDs, amounts) is fictional and generated from a seeded PRNG.
// Pure-JS content generation works anywhere; rendering needs a 2D canvas (browser).
(function (root) {
'use strict';
// ---------------------------------------------------------------- RNG
function RNG(seed) {
let s = seed >>> 0;
const r = function () { s = (s + 0x6D2B79F5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
r.pick = (a) => a[Math.floor(r() * a.length)];
r.int = (lo, hi) => lo + Math.floor(r() * (hi - lo + 1));
r.float = (lo, hi) => lo + r() * (hi - lo);
r.bool = (p) => r() < (p == null ? 0.5 : p);
r.shuffle = (a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); const x = a[i]; a[i] = a[j]; a[j] = x; } return a; };
r.sample = (a, k) => r.shuffle(a).slice(0, k);
r.gauss = () => { let u = 0; while (u === 0) u = r(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * r()); };
r.digits = (n) => { let x = ''; for (let i = 0; i < n; i++) x += String(Math.floor(r() * 10)); return x; };
r.letters = (n) => { let x = ''; for (let i = 0; i < n; i++) x += 'ABCDEFGHJKLMNPQRSTUVWXYZ'[Math.floor(r() * 24)]; return x; };
return r;
}
const pad = (n, w) => String(n).padStart(w, '0');
const r2 = (x) => Math.round(x * 100) / 100;
// ---------------------------------------------------------------- pools
const FN = ['Aarav', 'Priya', 'James', 'Mei', 'Sofia', 'Liam', 'Fatima', 'Noah', 'Chen', 'Olivia', 'Mateo', 'Amara', 'Ethan', 'Yuki', 'Hannah', 'Omar', 'Isabella', 'Lucas', 'Zara', 'Daniel', 'Ananya', 'Rohan', 'Emma', 'Kwame', 'Elena', 'Arjun', 'Grace', 'Hiro', 'Leila', 'Marcus', 'Nadia', 'Oliver', 'Ravi', 'Sara', 'Tomas', 'Uma', 'Victor', 'Wen', 'Ximena', 'Yusuf'];
const LN = ['Sharma', 'Okafor', 'Smith', 'Chen', 'Garcia', 'Muller', 'Nguyen', 'Patel', 'Rossi', 'Kim', 'Silva', 'Haddad', 'Johnson', 'Tanaka', 'Iyer', 'Kowalski', 'Dubois', 'Mensah', 'Fischer', 'Reddy', 'Brooks', 'Novak', 'Kapoor', 'Hart', 'Walsh', 'Morgan', 'Ali', 'Costa', 'Larsen', 'Rao'];
const PRE = ['Apex', 'Bluefield', 'Cedar', 'Driftwood', 'Evergreen', 'Foxglove', 'Granite', 'Harbor', 'Ironleaf', 'Juniper', 'Kestrel', 'Lakeshore', 'Meridian', 'Northgate', 'Oakridge', 'Pinecrest', 'Quarry', 'Redstone', 'Silverline', 'Tidewater', 'Upland', 'Valemont', 'Westbrook', 'Yarrow', 'Zenith', 'Brightwater', 'Copperfield', 'Falcon Ridge', 'Greystone', 'Maplewood'];
const IND = {
supplier: ['Industrial Supply', 'Packaging', 'Office Solutions', 'Fabrication', 'Electrical', 'Components', 'Print & Media', 'Lab Supplies', 'Hardware', 'Textiles', 'Facility Services', 'IT Services', 'Chemicals', 'Engineering'],
buyer: ['Manufacturing', 'Retail Group', 'Healthcare Systems', 'Foods', 'Motors', 'Pharma', 'Apparel', 'Construction', 'Media Group', 'Logistics', 'Energy', 'Hospitality'],
bank: ['Savings Bank', 'Commerce Bank', 'Credit Union', 'Federal Bank', 'Trust Bank'],
insurer: ['Mutual Insurance', 'Assurance', 'Health Plan', 'Insurance Co.'],
utility: ['Power & Light', 'Water Authority', 'Energy', 'Gas & Electric', 'Utilities'],
carrier: ['Shipping Line', 'Freight', 'Logistics', 'Ocean Lines', 'Transport'],
clinic: ['Family Clinic', 'Medical Center', 'Diagnostics', 'Health Partners', 'Laboratories'],
};
const SUF = ['LLC', 'Inc.', 'Ltd', 'Co.', 'GmbH', 'Pvt. Ltd.', 'Corp.', 'LLP', 'PLC', 'Pte. Ltd.'];
const STREET = ['Maple Ave', 'Industrial Pkwy', 'Commerce St', 'Harbor Rd', 'Station Lane', 'Market St', 'Riverside Dr', 'Mill Road', 'Park Blvd', 'Elm Street', 'Canal Way', 'Bridge St', 'King Street', 'Victoria Rd', 'Lake View Ave', 'Orchard Lane'];
const LOC = {
US: { cities: [['Austin', 'TX', '787'], ['Columbus', 'OH', '432'], ['Denver', 'CO', '802'], ['Raleigh', 'NC', '276'], ['Phoenix', 'AZ', '850'], ['Portland', 'OR', '972']], cur: 'USD', sym: '$', tax: 'Sales Tax', rates: [0, 6.25, 7.5, 8.25], dates: ['us', 'short', 'iso'], num: 'en' },
UK: { cities: [['Leeds', '', 'LS1'], ['Bristol', '', 'BS1'], ['Manchester', '', 'M1'], ['Glasgow', '', 'G2']], cur: 'GBP', sym: '£', tax: 'VAT', rates: [20], dates: ['eu', 'long', 'iso'], num: 'en' },
IN: { cities: [['Pune', 'MH', '411'], ['Bengaluru', 'KA', '560'], ['Chennai', 'TN', '600'], ['Hyderabad', 'TS', '500']], cur: 'INR', sym: '₹', tax: 'GST', rates: [5, 12, 18], dates: ['eu', 'long', 'short'], num: 'en' },
CA: { cities: [['Toronto', 'ON', 'M5V'], ['Calgary', 'AB', 'T2P'], ['Ottawa', 'ON', 'K1P']], cur: 'CAD', sym: 'CA$', tax: 'GST/HST', rates: [5, 13], dates: ['iso', 'short', 'long'], num: 'en' },
AU: { cities: [['Melbourne', 'VIC', '3000'], ['Brisbane', 'QLD', '4000'], ['Perth', 'WA', '6000']], cur: 'AUD', sym: 'A$', tax: 'GST', rates: [10], dates: ['eu', 'long'], num: 'en' },
DE: { cities: [['Hamburg', '', '20095'], ['Munich', '', '80331'], ['Cologne', '', '50667']], cur: 'EUR', sym: '€', tax: 'VAT', rates: [19, 7], dates: ['eu', 'iso'], num: 'eu' },
FR: { cities: [['Lyon', '', '69002'], ['Lille', '', '59000'], ['Nantes', '', '44000']], cur: 'EUR', sym: '€', tax: 'VAT', rates: [20, 10], dates: ['eu', 'long'], num: 'eu' },
SG: { cities: [['Singapore', '', '0189']], cur: 'SGD', sym: 'S$', tax: 'GST', rates: [9], dates: ['eu', 'short'], num: 'en' },
AE: { cities: [['Dubai', '', ''], ['Abu Dhabi', '', '']], cur: 'AED', sym: 'AED ', tax: 'VAT', rates: [5], dates: ['eu', 'short'], num: 'en' },
};
const COUNTRY = { US: 'USA', UK: 'United Kingdom', IN: 'India', CA: 'Canada', AU: 'Australia', DE: 'Germany', FR: 'France', SG: 'Singapore', AE: 'UAE' };
const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const MONL = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
// ---------------------------------------------------------------- formatting
function fmtNum(x, num) { const neg = x < 0; const [a, b] = Math.abs(x).toFixed(2).split('.'); const g = num === 'eu' ? '.' : ','; const d = num === 'eu' ? ',' : '.'; return (neg ? '-' : '') + a.replace(/\B(?=(\d{3})+(?!\d))/g, g) + d + b; }
const gold = (x) => fmtNum(x, 'en');
function money(x, L) { return L.num === 'eu' ? fmtNum(x, 'eu') + ' ' + L.sym.trim() : L.sym + fmtNum(x, 'en'); }
const iso = (d) => d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1, 2) + '-' + pad(d.getUTCDate(), 2);
function fmtDate(d, f) {
const y = d.getUTCFullYear(), m = d.getUTCMonth(), dd = d.getUTCDate();
if (f === 'iso') return iso(d);
if (f === 'us') return pad(m + 1, 2) + '/' + pad(dd, 2) + '/' + y;
if (f === 'eu') return pad(dd, 2) + '/' + pad(m + 1, 2) + '/' + y;
if (f === 'short') return MON[m] + ' ' + dd + ', ' + y;
return dd + ' ' + MONL[m] + ' ' + y;
}
const addDays = (d, n) => new Date(d.getTime() + n * 86400000);
function ibanFor(r, cc) {
const bban = cc === 'GB' ? 'SYNT' + r.digits(6) + r.digits(8) : (cc === 'DE' ? r.digits(8) + r.digits(10) : r.digits(5) + r.digits(5) + r.digits(11) + r.digits(2));
const conv = (bban + cc + '00').split('').map((ch) => (/[A-Z]/.test(ch) ? String(ch.charCodeAt(0) - 55) : ch)).join('');
let m = 0; for (const ch of conv) m = (m * 10 + Number(ch)) % 97;
const iban = cc + pad(98 - m, 2) + bban;
return iban.replace(/(.{4})/g, '$1 ').trim();
}
// ---------------------------------------------------------------- entities
function locale(r, only) { const k = only || r.pick(Object.keys(LOC)); return Object.assign({ code: k }, LOC[k]); }
function address(r, L) {
const c = r.pick(L.cities); const k = L.code;
let post = c[2];
if (k === 'US') post = c[2] + pad(r.int(1, 99), 2); else if (k === 'IN') post = c[2] + pad(r.int(1, 99), 3); else if (k === 'UK') post = c[2] + ' ' + r.int(1, 9) + r.letters(2); else if (k === 'CA') post = c[2] + ' ' + r.int(1, 9) + r.letters(1) + r.int(1, 9); else if (k === 'SG') post = c[2] + pad(r.int(1, 99), 2);
return r.int(10, 9800) + ' ' + r.pick(STREET) + ', ' + c[0] + (c[1] ? ', ' + c[1] : '') + (post ? ' ' + post : '') + ', ' + COUNTRY[k];
}
function phone(r, L) {
if (L.code === 'US' || L.code === 'CA') return '+1 (' + r.int(201, 989) + ') 555-01' + pad(r.int(0, 99), 2);
if (L.code === 'UK') return '+44 7700 900' + pad(r.int(0, 999), 3);
if (L.code === 'AU') return '+61 491 570 1' + pad(r.int(10, 99), 2);
const cc = { IN: '+91', DE: '+49', FR: '+33', SG: '+65', AE: '+971' }[L.code];
return cc + ' ' + r.digits(3) + ' ' + r.digits(3) + ' ' + r.digits(4);
}
function company(r, L, kind) {
const name = r.pick(PRE) + ' ' + r.pick(IND[kind || 'supplier']) + ' ' + r.pick(SUF);
const slug = name.toLowerCase().replace(/[^a-z]+/g, '').slice(0, 14);
return { name, address: address(r, L), phone: phone(r, L), email: r.pick(['accounts', 'billing', 'info', 'ap', 'orders']) + '@' + slug + '.example.com', taxId: (L.code === 'IN' ? '27' + r.letters(5) + r.digits(4) + r.letters(1) + '1Z' + r.digits(1) : (L.code === 'US' ? '9' + r.digits(1) + '-' + r.digits(7) : L.code + r.digits(9))) };
}
function person(r, L) {
const first = r.pick(FN), last = r.pick(LN);
const dob = new Date(Date.UTC(r.int(1955, 2003), r.int(0, 11), r.int(1, 28)));
let nid; if (L.code === 'US') nid = '9' + r.digits(2) + '-' + r.digits(2) + '-' + r.digits(4); else if (L.code === 'UK') nid = 'QQ' + r.digits(6) + r.pick(['A', 'B', 'C', 'D']); else if (L.code === 'IN') nid = r.letters(5) + r.digits(4) + r.letters(1); else nid = r.letters(2) + r.digits(7);
return { first, last, name: first + ' ' + last, dob, email: first.toLowerCase() + '.' + last.toLowerCase() + r.int(1, 99) + '@mail.example.org', phone: phone(r, L), address: address(r, L), nid, passport: r.letters(1) + r.digits(8) };
}
function baseDate(r) { return new Date(Date.UTC(2025, 0, 1) + r.int(0, 364) * 86400000); }
// ---------------------------------------------------------------- taxonomy
const TYPES = {
invoice: [1, 'A', 'Invoice'], tax_invoice: [10, 'A', 'Tax Invoice'], statement_of_account: [11, 'B', 'Statement of Account / Aging Statement'],
credit_card_statement: [13, 'B', 'Credit Card Statement'], bank_statement: [14, 'B', 'Bank Statement'], credit_note: [15, 'C', 'Credit Note'],
receipt: [17, 'D', 'Receipt'], remittance_advice: [20, 'D', 'Remittance Advice'], dunning_letter: [25, 'E', 'Dunning / Collection Letter'],
purchase_order: [28, 'F', 'Purchase Order'], quotation: [30, 'F', 'Quotation / Estimate'], work_order: [32, 'F', 'Work Order'],
delivery_note: [38, 'G', 'Delivery Note / Challan'], bill_of_lading: [39, 'G', 'Bill of Lading'], packing_list: [41, 'G', 'Packing List'], timesheet: [42, 'G', 'Timesheet'],
expense_report: [43, 'H', 'Expense Report'], payroll_statement: [44, 'H', 'Payroll Statement'], bank_details_form: [51, 'I', 'Bank Details Form'], kyc_form: [54, 'I', 'KYC Documentation'],
balance_sheet: [56, 'J', 'Balance Sheet'], profit_and_loss: [57, 'J', 'Profit & Loss Statement'], credit_application: [62, 'K', 'Credit Application Form'],
lab_report: [79, 'L', 'Lab Test Report / Result'], patient_intake_form: [80, 'L', 'Patient Intake / Registration Form'], claim_form: [83, 'L', 'Explanation of Benefits (EOB) / Claim Form'],
meeting_minutes: [87, 'M', 'Meeting Minutes / Notes'], nda: [90, 'N', 'Non-Disclosure Agreement (NDA)'], offer_letter: [95, 'N', 'Offer Letter / Employment Contract'],
maintenance_report: [98, 'O', 'Incident / Service & Maintenance Report'], utility_bill: [99, 'O', 'Lease Agreement / Utility Bill'],
};
const CAT = { A: 'Payables & Invoices', B: 'Account Statements & Reconciliation', C: 'Credits & Adjustments', D: 'Payments & Settlements', E: 'Collections', F: 'Procurement & Ordering', G: 'Shipping & Logistics', H: 'Internal & Employee Documents', I: 'Onboarding & Compliance', J: 'Financial Statements & Reports', K: 'Credit, Lending & Risk', L: 'Clinical, Laboratory & Healthcare', M: 'Digital & Communication Artifacts', N: 'Legal, HR & Administrative', O: 'Operations, Quality & Facilities' };
// ---------------------------------------------------------------- doc model
function newDoc(type, title) { const t = TYPES[type]; return { type, type_id: t[0], category: t[1] + '. ' + CAT[t[1]], financial: t[1] <= 'K', title, blocks: [], entities: {}, schema: {}, form: false }; }
const B = {
brand: (name, lines, title, logo) => ({ t: 'brand', name, lines, title, logo: logo !== false }),
title: (text) => ({ t: 'title', text }),
h: (text) => ({ t: 'h', text }),
kv: (items, cols) => ({ t: 'kv', items, cols: cols || 2 }),
p: (segs) => ({ t: 'p', segs: typeof segs === 'string' ? [{ text: segs }] : segs }),
table: (head, rows, key, align) => ({ t: 'table', head, rows, key, align }),
totals: (items) => ({ t: 'totals', items }),
checks: (label, options, checked, key) => ({ t: 'checks', label, options, checked, key }),
sign: (parties) => ({ t: 'sign', parties }),
list: (items) => ({ t: 'list', items }),
footer: (text) => ({ t: 'footer', text }),
cols: (n, sections) => ({ t: 'cols', n, sections }),
};
const S = (text, pii) => (pii ? { text, pii } : { text });
function kvi(label, value, key, pii, extra) { return Object.assign({ label, value: String(value), key, pii }, extra || {}); }
// ---------------------------------------------------------------- line items
const CATALOG = [['Corrugated shipping box 18x12x10', 0.8, 3.5, 'BX'], ['Nitrile gloves, box of 100', 6, 14, 'GL'], ['A4 copy paper, 5-ream case', 18, 42, 'PP'], ['Steel hex bolt M8x40 (50 pk)', 7, 19, 'HB'], ['LED panel light 600x600', 22, 65, 'LD'], ['Pallet wrap film 500mm', 9, 24, 'PW'], ['Laptop docking station', 85, 210, 'DK'], ['Cat6 patch cable 3m', 2.5, 8, 'CB'], ['Safety helmet, class E', 12, 35, 'SH'], ['Thermal label roll 4x6', 4, 11, 'TL'], ['Hydraulic hose assembly', 38, 120, 'HH'], ['Ergonomic office chair', 140, 420, 'OC'], ['Printer toner cartridge', 35, 110, 'TN'], ['Industrial degreaser 5L', 15, 48, 'DG'], ['Stainless valve DN50', 60, 180, 'SV'], ['Bearing 6204-2RS', 3, 9, 'BR'], ['Cleanroom wipes (300)', 20, 55, 'CW'], ['Solar inverter 5kW', 650, 1400, 'SI']];
const SERVICES = [['On-site maintenance, per hour', 45, 140], ['Consulting, per hour', 80, 250], ['Cloud backup subscription, monthly', 30, 220], ['Calibration service', 90, 380], ['Freight charge, LTL', 120, 640], ['Software license, annual', 400, 2400], ['Training workshop, per seat', 150, 600], ['Equipment rental, per day', 150, 320]];
function items(r, L, n, opts) {
opts = opts || {}; const mult = L.cur === 'INR' ? 80 : (L.cur === 'AED' ? 3.6 : 1); const out = [];
for (let k = 0; k < n; k++) {
const svc = !opts.goodsOnly && r.bool(0.25); const it = svc ? r.pick(SERVICES) : r.pick(CATALOG);
const q = it[2] > 100 ? r.int(1, 8) : r.int(1, 120); const up = r2(r.float(it[1], it[2]) * mult);
out.push({ code: (svc ? 'SV' : it[3]) + '-' + r.digits(4), description: it[0], quantity: q, unit_price: up, total: r2(q * up), weight: r2(q * r.float(0.2, 4)) });
}
return out;
}
// ---------------------------------------------------------------- builders
function header(r, doc, org, title) { doc.blocks.push(B.brand(org.name, [org.address, org.phone + ' · ' + org.email], title)); }
function txn(r, type, cfg) {
const L = locale(r); const seller = company(r, L, 'supplier'); const buyer = company(r, L, 'buyer'); const df = r.pick(L.dates);
const date = baseDate(r); const doc = newDoc(type, cfg.title(r)); doc.locale = L.code;
const idv = cfg.prefix(r) + r.digits(r.int(4, 6)); const n = r.int(1, cfg.maxItems || 8); const li = items(r, L, n, cfg);
const from = cfg.swap ? buyer : seller, to = cfg.swap ? seller : buyer;
header(r, doc, from, doc.title);
const meta = [kvi(cfg.idLabel(r), idv, cfg.idKey), kvi(r.pick(['Date', 'Issue Date', 'Dated']), fmtDate(date, df), 'date')];
const E = doc.entities; E[cfg.idKey] = idv; E.date = iso(date);
if (cfg.due) { const terms = r.pick([['Net 30', 30], ['Net 45', 45], ['Net 15', 15], ['Due on receipt', 0]]); const due = addDays(date, terms[1]); meta.push(kvi(r.pick(['Due Date', 'Payment Due']), fmtDate(due, df), 'due_date'), kvi('Terms', terms[0], 'payment_terms')); E.due_date = iso(due); E.payment_terms = terms[0]; }
if (cfg.ref) { const ref = cfg.ref(r); meta.push(kvi(ref[0], ref[1], ref[2])); E[ref[2]] = ref[1]; }
if (cfg.extraMeta) cfg.extraMeta(r, meta, E, date, df);
doc.blocks.push(B.kv(meta, 2));
doc.blocks.push(B.h(cfg.toLabel(r)));
doc.blocks.push(B.kv([kvi('Name', to.name, cfg.toKey), kvi('Address', to.address, cfg.toKey.replace('name', 'address'), null, { span: true })], 2));
E[cfg.fromKey] = from.name; E[cfg.toKey] = to.name; E[cfg.toKey.replace('name', 'address')] = to.address;
const cols = cfg.cols || 'priced'; let head, rows, lines;
if (cols === 'priced') { head = ['Item', 'Description', 'Qty', 'Unit Price', 'Amount']; rows = li.map((l) => [l.code, l.description, String(l.quantity), money(l.unit_price, L), money(l.total, L)]); lines = li.map((l) => ({ item_code: l.code, description: l.description, quantity: l.quantity, unit_price: gold(l.unit_price), total: gold(l.total) })); }
else if (cols === 'qty') { head = ['Item', 'Description', 'Ordered', 'Delivered']; rows = li.map((l) => [l.code, l.description, String(l.quantity), String(l.quantity - (r.bool(0.15) ? 1 : 0))]); lines = li.map((l, i) => ({ item_code: l.code, description: l.description, quantity_ordered: l.quantity, quantity_delivered: Number(rows[i][3]) })); }
else { head = ['Item', 'Description', 'Qty', 'Net Wt (kg)', 'Cartons']; rows = li.map((l) => [l.code, l.description, String(l.quantity), fmtNum(l.weight, 'en'), String(Math.max(1, Math.ceil(l.quantity / 24)))]); lines = li.map((l, i) => ({ item_code: l.code, description: l.description, quantity: l.quantity, net_weight_kg: gold(l.weight), cartons: Number(rows[i][4]) })); }
doc.blocks.push(B.table(head, rows, 'line_items')); E.line_items = lines;
if (cols === 'priced') {
const sub = r2(li.reduce((a, l) => a + l.total, 0)); const rate = r.pick(L.rates); const tax = r2(sub * rate / 100); const tot = r2(sub + tax);
doc.blocks.push(B.totals([kvi('Subtotal', money(sub, L), 'subtotal'), kvi(L.tax + ' (' + rate + '%)', money(tax, L), 'tax_amount'), kvi(r.pick(cfg.totalLabels || ['Total', 'Total Due', 'Amount Due', 'Grand Total']), money(tot, L), 'total_amount')]));
Object.assign(E, { currency: L.cur, subtotal: gold(sub), tax_rate: rate, tax_amount: gold(tax), total_amount: gold(tot) });
}
if (cfg.notes) doc.blocks.push(B.p(cfg.notes(r)));
if (cfg.signed) doc.blocks.push(B.sign([{ label: cfg.signed, name: person(r, L).name, pii: 'PERSON_NAME' }]));
doc.blocks.push(B.footer(from.name + ' · ' + (cfg.footer || 'Thank you for your business.')));
doc.schema = schemaOf(E);
return doc;
}
function schemaOf(E) { const s = {}; for (const k in E) { const v = E[k]; if (Array.isArray(v)) { s[k] = v.length ? [Object.fromEntries(Object.keys(v[0]).map((kk) => [kk, null]))] : []; } else s[k] = null; } return s; }
const BUILD = {
invoice: (r) => txn(r, 'invoice', { title: (r) => r.pick(['INVOICE', 'Invoice', 'COMMERCIAL INVOICE']), prefix: (r) => r.pick(['INV-', 'INV', 'SI-', '']), idLabel: (r) => r.pick(['Invoice No.', 'Invoice #', 'Invoice Number']), idKey: 'invoice_number', due: true, ref: (r) => ['PO Number', 'PO-' + r.digits(6), 'po_number'], toLabel: (r) => r.pick(['Bill To', 'Billed To', 'Customer']), fromKey: 'vendor_name', toKey: 'bill_to_name' }),
tax_invoice: (r) => txn(r, 'tax_invoice', { title: () => 'TAX INVOICE', prefix: (r) => r.pick(['TI/', 'GST-', 'TX']), idLabel: () => 'Tax Invoice No.', idKey: 'invoice_number', due: true, extraMeta: (r, m, E) => { const g = 'REG-' + r.letters(2) + r.digits(9); m.push(kvi('Supplier Tax Reg. No.', g, 'supplier_tax_id')); E.supplier_tax_id = g; m.push(kvi('Place of Supply', r.pick(['Maharashtra', 'Karnataka', 'Dubai', 'Victoria', 'Ontario']), 'place_of_supply')); E.place_of_supply = m[m.length - 1].value; }, toLabel: () => 'Recipient', fromKey: 'vendor_name', toKey: 'bill_to_name' }),
credit_note: (r) => txn(r, 'credit_note', { title: () => r.pick(['CREDIT NOTE', 'Credit Memo']), prefix: () => 'CN-', idLabel: () => 'Credit Note No.', idKey: 'credit_note_number', maxItems: 3, ref: (r) => ['Original Invoice', 'INV-' + r.digits(5), 'original_invoice_number'], extraMeta: (r, m, E) => { const rs = r.pick(['Damaged goods returned', 'Pricing error', 'Volume discount', 'Short shipment']); m.push(kvi('Reason', rs, 'reason')); E.reason = rs; }, totalLabels: ['Total Credit', 'Credit Amount'], toLabel: () => 'Credit To', fromKey: 'vendor_name', toKey: 'customer_name' }),
purchase_order: (r) => txn(r, 'purchase_order', { swap: true, title: () => r.pick(['PURCHASE ORDER', 'Purchase Order']), prefix: () => 'PO-', idLabel: () => r.pick(['PO Number', 'P.O. No.', 'Order No.']), idKey: 'po_number', extraMeta: (r, m, E, d, df) => { const dd = addDays(d, r.int(7, 40)); m.push(kvi('Delivery Date', fmtDate(dd, df), 'delivery_date')); E.delivery_date = iso(dd); }, due: false, toLabel: () => r.pick(['Supplier', 'Vendor']), fromKey: 'buyer_name', toKey: 'supplier_name', signed: 'Authorized by', footer: 'Please quote the PO number on all invoices.' }),
quotation: (r) => txn(r, 'quotation', { title: () => r.pick(['QUOTATION', 'Estimate', 'Price Quote']), prefix: () => 'Q-', idLabel: () => r.pick(['Quote No.', 'Estimate #']), idKey: 'quote_number', extraMeta: (r, m, E, d, df) => { const v = addDays(d, r.pick([15, 30, 60])); m.push(kvi('Valid Until', fmtDate(v, df), 'valid_until')); E.valid_until = iso(v); }, toLabel: () => r.pick(['Prepared For', 'Customer']), fromKey: 'vendor_name', toKey: 'customer_name', notes: () => 'Prices are valid until the date shown. This quotation is not binding until accepted in writing.' }),
work_order: (r) => txn(r, 'work_order', { swap: true, title: () => 'WORK ORDER', prefix: () => 'WO-', idLabel: () => 'Work Order No.', idKey: 'work_order_number', maxItems: 4, extraMeta: (r, m, E) => { const s = r.pick(['Replace HVAC filters, Building B', 'Repair loading dock door 3', 'Annual fire-system inspection', 'Install network cabling, floor 2']); m.push(kvi('Scope', s, 'scope', null, { span: true })); E.scope = s; }, toLabel: () => 'Contractor', fromKey: 'issuer_name', toKey: 'contractor_name', signed: 'Approved by' }),
delivery_note: (r) => txn(r, 'delivery_note', { title: () => r.pick(['DELIVERY NOTE', 'Delivery Challan', 'Goods Delivery Note']), prefix: () => 'DN-', idLabel: () => 'Delivery Note No.', idKey: 'delivery_note_number', cols: 'qty', ref: (r) => ['Customer PO', 'PO-' + r.digits(6), 'po_number'], toLabel: () => r.pick(['Deliver To', 'Consignee']), fromKey: 'supplier_name', toKey: 'consignee_name', signed: 'Received by (signature)', footer: 'Goods received in good condition unless noted.' }),
packing_list: (r) => txn(r, 'packing_list', { title: () => 'PACKING LIST', prefix: () => 'PL-', idLabel: () => 'Packing List No.', idKey: 'packing_list_number', cols: 'weights', goodsOnly: true, ref: (r) => ['Invoice Ref.', 'INV-' + r.digits(5), 'invoice_number'], toLabel: () => 'Ship To', fromKey: 'shipper_name', toKey: 'consignee_name' }),
receipt: (r) => {
const L = locale(r); const m = company(r, L, 'supplier'); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('receipt', r.pick(['RECEIPT', 'Sales Receipt', 'Payment Receipt'])); doc.locale = L.code;
const no = r.digits(6); const li = items(r, L, r.int(1, 6)); const sub = r2(li.reduce((a, l) => a + l.total, 0)); const rate = r.pick(L.rates); const tax = r2(sub * rate / 100); const tip = r.bool(0.3) ? r2(sub * 0.1) : 0; const tot = r2(sub + tax + tip);
const pm = r.pick(['VISA', 'Mastercard', 'AMEX', 'Cash', 'Debit']); const last4 = pm === 'Cash' ? null : r.digits(4); const time = pad(r.int(7, 21), 2) + ':' + pad(r.int(0, 59), 2);
header(r, doc, m, doc.title);
doc.blocks.push(B.kv([kvi('Receipt No.', no, 'receipt_number'), kvi('Date', fmtDate(d, df), 'date'), kvi('Time', time, 'time'), kvi('Payment', pm + (last4 ? ' **** ' + last4 : ''), 'payment_method')], 2));
doc.blocks.push(B.table(['Item', 'Qty', 'Amount'], li.map((l) => [l.description, String(l.quantity), money(l.total, L)]), 'line_items'));
const tots = [kvi('Subtotal', money(sub, L), 'subtotal'), kvi(L.tax, money(tax, L), 'tax_amount')]; if (tip) tots.push(kvi('Tip', money(tip, L), 'tip')); tots.push(kvi('TOTAL', money(tot, L), 'total_amount'));
doc.blocks.push(B.totals(tots)); doc.blocks.push(B.footer('Thank you! Keep this receipt for returns within 30 days.'));
Object.assign(doc.entities, { merchant_name: m.name, merchant_address: m.address, receipt_number: no, date: iso(d), time, payment_method: pm, card_last4: last4, currency: L.cur, subtotal: gold(sub), tax_amount: gold(tax), tip: gold(tip), total_amount: gold(tot), line_items: li.map((l) => ({ description: l.description, quantity: l.quantity, total: gold(l.total) })) });
doc.schema = schemaOf(doc.entities); return doc;
},
remittance_advice: (r) => {
const L = locale(r); const payer = company(r, L, 'buyer'); const payee = company(r, L, 'supplier'); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('remittance_advice', 'REMITTANCE ADVICE'); doc.locale = L.code;
const n = r.int(1, 6); const inv = []; let tot = 0; for (let i = 0; i < n; i++) { const a = r2(r.float(200, 9000)); const disc = r.bool(0.2) ? r2(a * 0.02) : 0; inv.push({ invoice_number: 'INV-' + r.digits(5), invoice_date: iso(addDays(d, -r.int(20, 70))), amount: a, discount: disc, paid: r2(a - disc) }); tot += a - disc; }
tot = r2(tot); const ref = r.pick(['ACH', 'WIRE', 'EFT']) + r.digits(8);
header(r, doc, payer, doc.title);
doc.blocks.push(B.kv([kvi('Payment Date', fmtDate(d, df), 'payment_date'), kvi('Payment Reference', ref, 'payment_reference'), kvi('Payment Method', ref.slice(0, ref.search(/\d/)), 'payment_method'), kvi('Payee', payee.name, 'payee_name')], 2));
doc.blocks.push(B.p('The following invoices have been settled by the payment referenced above. Please contact our accounts payable team with any questions.'));
doc.blocks.push(B.table(['Invoice No.', 'Invoice Date', 'Amount', 'Discount', 'Paid'], inv.map((x) => [x.invoice_number, fmtDate(new Date(x.invoice_date + 'T00:00:00Z'), df), money(x.amount, L), money(x.discount, L), money(x.paid, L)]), 'invoices_paid'));
doc.blocks.push(B.totals([kvi('Total Paid', money(tot, L), 'total_paid')])); doc.blocks.push(B.footer(payer.name + ' Accounts Payable · ' + payer.email));
Object.assign(doc.entities, { payer_name: payer.name, payee_name: payee.name, payment_date: iso(d), payment_reference: ref, payment_method: ref.slice(0, ref.search(/\d/)), currency: L.cur, total_paid: gold(tot), invoices_paid: inv.map((x) => ({ invoice_number: x.invoice_number, invoice_date: x.invoice_date, amount: gold(x.amount), discount: gold(x.discount), paid: gold(x.paid) })) });
doc.schema = schemaOf(doc.entities); return doc;
},
bank_statement: (r, opt) => statement(r, 'bank_statement', opt),
credit_card_statement: (r, opt) => statement(r, 'credit_card_statement', opt),
statement_of_account: (r) => {
const L = locale(r); const v = company(r, L, 'supplier'); const c = company(r, L, 'buyer'); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('statement_of_account', r.pick(['STATEMENT OF ACCOUNT', 'Aging Statement'])); doc.locale = L.code;
const n = r.int(3, 9); const rows = []; const buckets = { current: 0, d30: 0, d60: 0, d90: 0 };
for (let i = 0; i < n; i++) { const age = r.int(0, 120); const a = r2(r.float(150, 8000)); const b = age <= 30 ? 'current' : age <= 60 ? 'd30' : age <= 90 ? 'd60' : 'd90'; buckets[b] = r2(buckets[b] + a); rows.push(['INV-' + r.digits(5), fmtDate(addDays(d, -age), df), String(age), money(a, L)]); }
const tot = r2(buckets.current + buckets.d30 + buckets.d60 + buckets.d90);
header(r, doc, v, doc.title);
doc.blocks.push(B.kv([kvi('Statement Date', fmtDate(d, df), 'statement_date'), kvi('Customer', c.name, 'customer_name'), kvi('Customer Account', 'CUST-' + r.digits(5), 'customer_account'), kvi('Currency', L.cur, 'currency')], 2));
doc.blocks.push(B.table(['Invoice', 'Invoice Date', 'Days Outstanding', 'Open Amount'], rows, 'open_items'));
doc.blocks.push(B.table(['Current', '31-60', '61-90', '90+', 'Total Due'], [[money(buckets.current, L), money(buckets.d30, L), money(buckets.d60, L), money(buckets.d90, L), money(tot, L)]], 'aging'));
doc.blocks.push(B.footer('Please remit payment for all overdue items.'));
Object.assign(doc.entities, { vendor_name: v.name, customer_name: c.name, statement_date: iso(d), customer_account: doc.blocks[1].items[2].value, currency: L.cur, aging_current: gold(buckets.current), aging_31_60: gold(buckets.d30), aging_61_90: gold(buckets.d60), aging_over_90: gold(buckets.d90), total_due: gold(tot), open_items: rows.map((x) => ({ invoice_number: x[0], days_outstanding: Number(x[2]) })) });
doc.schema = schemaOf(doc.entities); return doc;
},
dunning_letter: (r) => letterDoc(r, 'dunning_letter'),
offer_letter: (r) => letterDoc(r, 'offer_letter'),
nda: (r) => letterDoc(r, 'nda'),
meeting_minutes: (r) => letterDoc(r, 'meeting_minutes'),
bill_of_lading: (r) => {
const L = locale(r); const sh = company(r, L, 'supplier'); const L2 = locale(r); const cn = company(r, L2, 'buyer'); const ca = company(r, L, 'carrier'); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('bill_of_lading', r.pick(['BILL OF LADING', 'Bill of Lading - Non-Negotiable', 'Straight Bill of Lading'])); doc.locale = L.code;
const no = r.letters(4) + r.digits(7); const ports = ['Port of Hamburg', 'Port of Singapore', 'Jebel Ali', 'Nhava Sheva', 'Port of Los Angeles', 'Felixstowe', 'Port of Melbourne', 'Port of Rotterdam'];
const pol = r.pick(ports), pod = r.pick(ports.filter((x) => x !== pol)); const vessel = r.pick(['MV ', 'MSC ', 'CMA ']) + r.pick(PRE).toUpperCase() + ' ' + r.pick(['STAR', 'SPIRIT', 'TRADER', 'EXPRESS']); const terms = r.pick(['Prepaid', 'Collect']);
const li = items(r, L, r.int(1, 5), { goodsOnly: true }); const pk = li.map((l) => Math.max(1, Math.ceil(l.quantity / 10))); const totPk = pk.reduce((a, b) => a + b, 0); const totW = r2(li.reduce((a, l) => a + l.weight, 0));
header(r, doc, ca, doc.title);
doc.blocks.push(B.kv([kvi('B/L Number', no, 'bol_number'), kvi('Date of Shipment', fmtDate(d, df), 'ship_date'), kvi('Shipper', sh.name, 'shipper_name'), kvi('Consignee', cn.name, 'consignee_name'), kvi('Notify Party', cn.name, 'notify_party'), kvi('Vessel / Voyage', vessel + ' / ' + r.digits(3) + r.letters(1), 'vessel'), kvi('Port of Loading', pol, 'port_of_loading'), kvi('Port of Discharge', pod, 'port_of_discharge'), kvi('Freight Terms', terms, 'freight_terms'), kvi('Container No.', r.letters(4) + r.digits(7), 'container_number')], 2));
doc.blocks.push(B.table(['Marks', 'Description of Goods', 'Packages', 'Gross Wt (kg)'], li.map((l, i) => ['LOT ' + (i + 1), l.description, String(pk[i]), fmtNum(l.weight, 'en')]), 'items'));
doc.blocks.push(B.totals([kvi('Total Packages', String(totPk), 'total_packages'), kvi('Total Gross Weight (kg)', fmtNum(totW, 'en'), 'total_weight_kg')]));
doc.blocks.push(B.p('Received in apparent good order and condition, unless otherwise noted, the goods described above for carriage to the port of discharge.'));
doc.blocks.push(B.sign([{ label: 'For the Carrier', name: person(r, L).name, pii: 'PERSON_NAME' }, { label: 'Shipper', name: person(r, L).name, pii: 'PERSON_NAME' }]));
const kv = doc.blocks[1].items; Object.assign(doc.entities, { bol_number: no, ship_date: iso(d), carrier_name: ca.name, shipper_name: sh.name, consignee_name: cn.name, notify_party: cn.name, vessel: kv[5].value, port_of_loading: pol, port_of_discharge: pod, freight_terms: terms, container_number: kv[9].value, total_packages: totPk, total_weight_kg: gold(totW), items: li.map((l, i) => ({ description: l.description, packages: pk[i], gross_weight_kg: gold(l.weight) })) });
doc.schema = schemaOf(doc.entities); return doc;
},
timesheet: (r) => {
const L = locale(r); const co = company(r, L, 'supplier'); const p = person(r, L); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('timesheet', r.pick(['TIMESHEET', 'Weekly Timesheet'])); doc.locale = L.code;
const proj = r.pick(['ERP Migration', 'Plant Maintenance', 'Audit Support', 'Network Upgrade', 'Warehouse Fit-out']); const rows = []; let tot = 0;
for (let i = 0; i < 5; i++) { const h = r.pick([0, 4, 6, 7.5, 8, 8, 8, 9]); tot += h; rows.push([fmtDate(addDays(d, i), df), proj, r.pick(['Analysis', 'On-site work', 'Testing', 'Meetings', 'Documentation']), fmtNum(h, 'en')]); }
const rate = r2(r.float(35, 140)); header(r, doc, co, doc.title);
doc.blocks.push(B.kv([kvi('Employee', p.name, 'employee_name', 'PERSON_NAME'), kvi('Employee ID', 'E' + r.digits(5), 'employee_id'), kvi('Week Starting', fmtDate(d, df), 'week_start'), kvi('Client / Project', proj, 'project'), kvi('Hourly Rate', money(rate, L), 'hourly_rate')], 2));
doc.blocks.push(B.table(['Date', 'Project', 'Task', 'Hours'], rows, 'entries'));
doc.blocks.push(B.totals([kvi('Total Hours', fmtNum(tot, 'en'), 'total_hours'), kvi('Billable Amount', money(r2(tot * rate), L), 'billable_amount')]));
doc.blocks.push(B.sign([{ label: 'Employee', name: p.name, pii: 'PERSON_NAME' }, { label: 'Approver', name: person(r, L).name, pii: 'PERSON_NAME' }]));
Object.assign(doc.entities, { company_name: co.name, employee_name: p.name, employee_id: doc.blocks[1].items[1].value, week_start: iso(d), project: proj, hourly_rate: gold(rate), currency: L.cur, total_hours: gold(tot), billable_amount: gold(r2(tot * rate)) });
doc.schema = schemaOf(doc.entities); return doc;
},
expense_report: (r) => {
const L = locale(r); const co = company(r, L, 'buyer'); const p = person(r, L); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('expense_report', r.pick(['EXPENSE REPORT', 'Travel & Expense Claim'])); doc.locale = L.code;
const cats = [['Airfare', 180, 900], ['Hotel', 90, 320], ['Meals', 12, 85], ['Taxi / Ride share', 9, 60], ['Mileage', 20, 140], ['Conference fee', 150, 900], ['Client entertainment', 40, 300]]; const n = r.int(2, 8); const rows = []; let tot = 0;
for (let i = 0; i < n; i++) { const c = r.pick(cats); const a = r2(r.float(c[1], c[2])); tot += a; rows.push([fmtDate(addDays(d, i - n), df), c[0], r.pick(['Customer visit', 'Team offsite', 'Trade show', 'Training']), money(a, L)]); }
tot = r2(tot); header(r, doc, co, doc.title);
doc.blocks.push(B.kv([kvi('Employee Name', p.name, 'employee_name', 'PERSON_NAME'), kvi('Employee ID', 'E' + r.digits(5), 'employee_id'), kvi('Department', r.pick(['Sales', 'Finance', 'Engineering', 'Operations']), 'department'), kvi('Report Date', fmtDate(d, df), 'report_date'), kvi('Cost Center', 'CC-' + r.digits(4), 'cost_center')], 2));
doc.blocks.push(B.table(['Date', 'Category', 'Purpose', 'Amount'], rows, 'expenses'));
doc.blocks.push(B.totals([kvi('Total Claimed', money(tot, L), 'total_amount')]));
doc.blocks.push(B.sign([{ label: 'Employee', name: p.name, pii: 'PERSON_NAME' }, { label: 'Manager Approval', name: person(r, L).name, pii: 'PERSON_NAME' }]));
const kv = doc.blocks[1].items; Object.assign(doc.entities, { company_name: co.name, employee_name: p.name, employee_id: kv[1].value, department: kv[2].value, report_date: iso(d), cost_center: kv[4].value, currency: L.cur, total_amount: gold(tot), expenses: rows.map((x) => ({ category: x[1], purpose: x[2], amount: gold(Number(x[3].replace(/[^0-9.,]/g, '').replace(L.num === 'eu' ? /\./g : /,/g, '').replace(',', '.'))) })) });
doc.schema = schemaOf(doc.entities); return doc;
},
payroll_statement: (r) => {
const L = locale(r); const co = company(r, L, 'buyer'); const p = person(r, L); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('payroll_statement', r.pick(['PAYSLIP', 'Earnings Statement', 'Pay Advice'])); doc.locale = L.code;
const mult = L.cur === 'INR' ? 60 : 1; const basic = r2(r.float(2500, 9000) * mult); const earn = [['Basic Salary', basic], ['Housing Allowance', r2(basic * r.float(0.1, 0.3))]]; if (r.bool(0.5)) earn.push(['Overtime', r2(r.float(50, 600) * mult)]); if (r.bool(0.3)) earn.push(['Bonus', r2(r.float(200, 2000) * mult)]);
const gross = r2(earn.reduce((a, e) => a + e[1], 0)); const ded = [['Income Tax', r2(gross * r.float(0.08, 0.25))], ['Social Security / Pension', r2(gross * r.float(0.04, 0.12))]]; if (r.bool(0.5)) ded.push(['Health Insurance', r2(r.float(40, 300) * mult)]);
const td = r2(ded.reduce((a, e) => a + e[1], 0)); const net = r2(gross - td); const ps = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1)); const pe = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)); const pd = addDays(pe, r.int(0, 5));
header(r, doc, co, doc.title);
doc.blocks.push(B.kv([kvi('Employee', p.name, 'employee_name', 'PERSON_NAME'), kvi('Employee ID', 'E' + r.digits(5), 'employee_id'), kvi('Pay Period', fmtDate(ps, df) + ' - ' + fmtDate(pe, df), 'pay_period'), kvi('Pay Date', fmtDate(pd, df), 'pay_date'), kvi('Bank Account', '****' + r.digits(4), 'bank_account', 'ACCOUNT_NUMBER'), kvi('Tax ID', p.nid, 'tax_id', 'NATIONAL_ID')], 2));
doc.blocks.push(B.table(['Earnings', 'Amount'], earn.map((e) => [e[0], money(e[1], L)]), 'earnings'));
doc.blocks.push(B.table(['Deductions', 'Amount'], ded.map((e) => [e[0], money(e[1], L)]), 'deductions'));
doc.blocks.push(B.totals([kvi('Gross Pay', money(gross, L), 'gross_pay'), kvi('Total Deductions', money(td, L), 'total_deductions'), kvi('Net Pay', money(net, L), 'net_pay')]));
doc.blocks.push(B.footer('This is a computer-generated statement. Confidential.'));
Object.assign(doc.entities, { employer_name: co.name, employee_name: p.name, employee_id: doc.blocks[1].items[1].value, pay_period_start: iso(ps), pay_period_end: iso(pe), pay_date: iso(pd), currency: L.cur, gross_pay: gold(gross), total_deductions: gold(td), net_pay: gold(net), earnings: earn.map((e) => ({ type: e[0], amount: gold(e[1]) })), deductions: ded.map((e) => ({ type: e[0], amount: gold(e[1]) })) });
doc.schema = schemaOf(doc.entities); return doc;
},
bank_details_form: (r) => formDoc(r, 'bank_details_form'),
kyc_form: (r) => formDoc(r, 'kyc_form'),
credit_application: (r) => formDoc(r, 'credit_application'),
patient_intake_form: (r) => formDoc(r, 'patient_intake_form'),
claim_form: (r) => formDoc(r, 'claim_form'),
balance_sheet: (r, opt) => finStatement(r, 'balance_sheet', opt),
profit_and_loss: (r, opt) => finStatement(r, 'profit_and_loss', opt),
lab_report: (r) => {
const L = locale(r); const lab = company(r, L, 'clinic'); const p = person(r, L); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('lab_report', r.pick(['LABORATORY REPORT', 'Lab Test Results', 'Pathology Report'])); doc.locale = L.code;
const tests = [['Hemoglobin', 'g/dL', 11.5, 17.5, '13.0 - 17.0'], ['WBC Count', 'x10^9/L', 3.5, 12, '4.0 - 11.0'], ['Platelets', 'x10^9/L', 120, 450, '150 - 400'], ['Glucose (fasting)', 'mg/dL', 70, 140, '70 - 100'], ['HbA1c', '%', 4.5, 8.5, '< 5.7'], ['Total Cholesterol', 'mg/dL', 140, 280, '< 200'], ['LDL Cholesterol', 'mg/dL', 60, 190, '< 100'], ['Creatinine', 'mg/dL', 0.5, 1.6, '0.6 - 1.2'], ['TSH', 'mIU/L', 0.3, 6, '0.4 - 4.0'], ['Vitamin D', 'ng/mL', 12, 60, '30 - 100']];
const sel = r.sample(tests, r.int(4, 9)); const rows = sel.map((t) => { const v = Math.round(r.float(t[2], t[3]) * 10) / 10; return [t[0], String(v), t[1], t[4]]; });
header(r, doc, lab, doc.title);
doc.blocks.push(B.kv([kvi('Patient Name', p.name, 'patient_name', 'PERSON_NAME'), kvi('Date of Birth', fmtDate(p.dob, df), 'date_of_birth', 'DATE_OF_BIRTH'), kvi('Patient ID', 'MRN-' + r.digits(7), 'patient_id'), kvi('Collected', fmtDate(d, df), 'collection_date'), kvi('Referring Physician', 'Dr. ' + person(r, L).name, 'physician', 'PERSON_NAME'), kvi('Specimen', r.pick(['Whole blood', 'Serum', 'Plasma']), 'specimen')], 2));
doc.blocks.push(B.table(['Test', 'Result', 'Units', 'Reference Range'], rows, 'results'));
doc.blocks.push(B.p('Results should be interpreted in conjunction with clinical findings. Values outside the reference range are not necessarily abnormal for every patient.'));
doc.blocks.push(B.sign([{ label: 'Verified by (Pathologist)', name: 'Dr. ' + person(r, L).name, pii: 'PERSON_NAME' }]));
const kv = doc.blocks[1].items; Object.assign(doc.entities, { lab_name: lab.name, patient_name: p.name, date_of_birth: iso(p.dob), patient_id: kv[2].value, collection_date: iso(d), physician: kv[4].value, specimen: kv[5].value, results: rows.map((x) => ({ test: x[0], result: x[1], units: x[2], reference_range: x[3] })) });
doc.schema = schemaOf(doc.entities); return doc;
},
maintenance_report: (r) => {
const L = locale(r); const co = company(r, L, 'supplier'); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('maintenance_report', r.pick(['SERVICE REPORT', 'Maintenance Report', 'Incident Report'])); doc.locale = L.code;
const asset = r.pick(['Air compressor AC-200', 'Forklift FL-12', 'Chiller unit CH-3', 'Conveyor line 4', 'Backup generator G-2', 'CNC mill M-7']); const tech = person(r, L); const hrs = r.pick([1, 1.5, 2, 3, 4.5, 6]);
header(r, doc, co, doc.title);
doc.blocks.push(B.kv([kvi('Report No.', 'SR-' + r.digits(6), 'report_number'), kvi('Date', fmtDate(d, df), 'date'), kvi('Asset', asset, 'asset'), kvi('Location', r.pick(['Plant 2, Bay C', 'Warehouse North', 'Building A, Roof', 'Line 4']), 'location'), kvi('Technician', tech.name, 'technician', 'PERSON_NAME'), kvi('Labour Hours', String(hrs), 'labour_hours')], 2));
doc.blocks.push(B.h('Problem Reported')); doc.blocks.push(B.p(r.pick(['Unit tripping on high temperature during peak load.', 'Abnormal vibration and noise from drive motor.', 'Hydraulic leak observed near the lift cylinder.', 'Intermittent failure to start in the morning.'])));
doc.blocks.push(B.h('Work Performed')); doc.blocks.push(B.list(r.sample(['Inspected and cleaned condenser coils', 'Replaced worn drive belt', 'Tightened electrical terminals', 'Replaced hydraulic seal kit', 'Updated controller firmware', 'Lubricated bearings', 'Performed load test for 30 minutes'], r.int(2, 4))));
const st = r.pick(['Resolved', 'Resolved - monitor', 'Parts on order']); doc.blocks.push(B.checks('Status', ['Resolved', 'Resolved - monitor', 'Parts on order'], [st], 'status'));
doc.blocks.push(B.sign([{ label: 'Technician', name: tech.name, pii: 'PERSON_NAME' }, { label: 'Customer Acknowledgement', name: person(r, L).name, pii: 'PERSON_NAME' }]));
const kv = doc.blocks[1].items; Object.assign(doc.entities, { service_company: co.name, report_number: kv[0].value, date: iso(d), asset, location: kv[3].value, technician: tech.name, labour_hours: hrs, status: st });
doc.schema = schemaOf(doc.entities); return doc;
},
utility_bill: (r) => {
const L = locale(r); const u = company(r, L, 'utility'); const p = person(r, L); const df = r.pick(L.dates); const d = baseDate(r); const doc = newDoc('utility_bill', r.pick(['ELECTRICITY BILL', 'Water & Sewer Bill', 'Gas Bill', 'Utility Statement'])); doc.locale = L.code;
const unit = doc.title.indexOf('Water') >= 0 ? 'm3' : (doc.title.indexOf('Gas') >= 0 ? 'therms' : 'kWh'); const prev = r.int(10000, 90000); const use = r.int(80, 1800); const rate = r.float(0.08, 0.35) * (L.cur === 'INR' ? 40 : 1); const chg = r2(use * rate); const fixed = r2(r.float(5, 25) * (L.cur === 'INR' ? 40 : 1)); const tax = r2((chg + fixed) * r.pick(L.rates) / 100); const tot = r2(chg + fixed + tax);
const ps = addDays(d, -30); const due = addDays(d, 21); const acct = r.digits(10); const meter = 'MTR-' + r.digits(8);
header(r, doc, u, doc.title);
doc.blocks.push(B.kv([kvi('Account Number', acct, 'account_number', 'ACCOUNT_NUMBER'), kvi('Customer', p.name, 'customer_name', 'PERSON_NAME'), kvi('Service Address', p.address, 'service_address', 'ADDRESS', { span: true }), kvi('Billing Period', fmtDate(ps, df) + ' - ' + fmtDate(d, df), 'billing_period'), kvi('Due Date', fmtDate(due, df), 'due_date'), kvi('Meter No.', meter, 'meter_number')], 2));
doc.blocks.push(B.table(['Previous Reading', 'Current Reading', 'Usage', 'Unit'], [[String(prev), String(prev + use), String(use), unit]], 'meter_readings'));
doc.blocks.push(B.table(['Charge', 'Amount'], [['Energy / usage charge', money(chg, L)], ['Fixed service charge', money(fixed, L)], ['Taxes', money(tax, L)]], 'charges'));
doc.blocks.push(B.totals([kvi('Amount Due', money(tot, L), 'amount_due')])); doc.blocks.push(B.footer('Pay online, by direct debit or at any authorised payment centre.'));
Object.assign(doc.entities, { provider_name: u.name, account_number: acct, customer_name: p.name, service_address: p.address, billing_period_start: iso(ps), billing_period_end: iso(d), due_date: iso(due), meter_number: meter, usage: use, usage_unit: unit, currency: L.cur, amount_due: gold(tot) });
doc.schema = schemaOf(doc.entities); return doc;
},
};
function statement(r, type, opt) {
opt = opt || {}; const L = locale(r); const bank = company(r, L, 'bank'); const p = person(r, L); const df = r.pick(L.dates); const d = baseDate(r);
const cc = type === 'credit_card_statement'; const doc = newDoc(type, cc ? r.pick(['CREDIT CARD STATEMENT', 'Card Account Statement']) : r.pick(['ACCOUNT STATEMENT', 'Bank Statement', 'Statement of Account Activity'])); doc.locale = L.code;
const ps = addDays(d, -30); const mult = L.cur === 'INR' ? 60 : 1; let bal = r2(r.float(500, 25000) * mult); const open = bal; const n = opt.rows || r.int(6, 16); const rows = []; let dr = 0, cr = 0;
const descs = ['POS PURCHASE ', 'ACH DEBIT ', 'DIRECT DEPOSIT ', 'TRANSFER TO ', 'CARD PAYMENT ', 'ATM WITHDRAWAL', 'UTILITY PAYMENT ', 'REFUND '];
for (let i = 0; i < n; i++) {
const dsc = r.pick(descs); const isCr = cc ? /REFUND|CARD PAYMENT/.test(dsc) : /DEPOSIT|REFUND/.test(dsc); const a = r2(r.float(5, isCr ? 4000 : 900) * mult);
if (cc) bal = r2(bal + (isCr ? -a : a)); else bal = r2(bal + (isCr ? a : -a)); if (isCr) cr += a; else dr += a;
rows.push([fmtDate(addDays(ps, Math.floor(i * 30 / n)), df), (dsc + (dsc.endsWith(' ') ? r.pick(PRE).toUpperCase() + ' ' + r.digits(4) : '')).trim(), isCr ? '' : money(a, L), isCr ? money(a, L) : '', money(bal, L)]);
}
const acct = r.digits(r.int(8, 12)); const masked = cc ? '**** **** **** ' + r.digits(4) : acct; const ib = L.code === 'UK' ? ibanFor(r, 'GB') : (L.code === 'DE' ? ibanFor(r, 'DE') : (L.code === 'FR' ? ibanFor(r, 'FR') : null));
header(r, doc, bank, doc.title);
const kv = [kvi('Account Holder', p.name, 'account_holder', 'PERSON_NAME'), kvi('Address', p.address, 'holder_address', 'ADDRESS', { span: true }), kvi(cc ? 'Card Number' : 'Account Number', masked, 'account_number', 'ACCOUNT_NUMBER'), kvi('Statement Period', fmtDate(ps, df) + ' - ' + fmtDate(d, df), 'statement_period')];
if (ib) kv.push(kvi('IBAN', ib, 'iban', 'IBAN'));
doc.blocks.push(B.kv(kv, 2));
doc.blocks.push(B.table(['Date', 'Description', cc ? 'Charges' : 'Withdrawals', cc ? 'Credits' : 'Deposits', 'Balance'], rows, 'transactions'));
doc.blocks.push(B.totals([kvi(cc ? 'Previous Balance' : 'Opening Balance', money(open, L), 'opening_balance'), kvi(cc ? 'Payments & Credits' : 'Total Deposits', money(r2(cr), L), 'total_credits'), kvi(cc ? 'Purchases & Charges' : 'Total Withdrawals', money(r2(dr), L), 'total_debits'), kvi(cc ? 'New Balance' : 'Closing Balance', money(bal, L), 'closing_balance')]));
if (cc) doc.blocks.push(B.kv([kvi('Minimum Payment Due', money(r2(Math.max(25, bal * 0.03)), L), 'minimum_due'), kvi('Payment Due Date', fmtDate(addDays(d, 25), df), 'due_date')], 2));
doc.blocks.push(B.footer('Please examine this statement promptly and report any discrepancy within 30 days.'));
Object.assign(doc.entities, { bank_name: bank.name, account_holder: p.name, holder_address: p.address, account_number: masked, iban: ib, statement_period_start: iso(ps), statement_period_end: iso(d), currency: L.cur, opening_balance: gold(open), total_credits: gold(r2(cr)), total_debits: gold(r2(dr)), closing_balance: gold(bal) });
if (cc) { doc.entities.minimum_due = gold(r2(Math.max(25, bal * 0.03))); doc.entities.due_date = iso(addDays(d, 25)); }
const num = (s) => (s ? gold(Number(s.replace(L.sym.trim(), '').trim().replace(L.num === 'eu' ? /\./g : /,/g, '').replace(',', '.'))) : null);
doc.entities.transactions = rows.map((x) => ({ description: x[1], debit: num(x[2]), credit: num(x[3]), balance: num(x[4]) }));
doc.schema = schemaOf(doc.entities); return doc;
}
function finStatement(r, type, opt) {
opt = opt || {}; const L = locale(r, r.pick(['US', 'UK', 'IN', 'SG', 'AU'])); const co = company(r, L, 'buyer'); const yr = r.int(2022, 2025); const k = r.pick([1, 1000]); const unit = k === 1000 ? ' (in thousands)' : '';
const bs = type === 'balance_sheet'; const doc = newDoc(type, bs ? r.pick(['BALANCE SHEET', 'Statement of Financial Position']) : r.pick(['PROFIT & LOSS STATEMENT', 'Income Statement', 'Statement of Profit or Loss'])); doc.locale = L.code;
const v = () => Math.round(r.float(50, 9000) * (k === 1 ? 1000 : 1)); const fmt = (x) => (x < 0 ? '(' + Math.abs(x).toLocaleString('en-US') + ')' : x.toLocaleString('en-US'));
header(r, doc, co, doc.title);
doc.blocks.push(B.p((bs ? 'As at 31 December ' : 'For the year ended 31 December ') + yr + '. Amounts in ' + L.cur + unit + '.'));
const E = doc.entities; E.company_name = co.name; E.fiscal_year = yr; E.currency = L.cur; E.unit = k === 1000 ? 'thousands' : 'units';
const sections = bs ? [['Current assets', ['Cash and cash equivalents', 'Trade receivables', 'Inventories', 'Prepayments', 'Other current assets']], ['Non-current assets', ['Property, plant and equipment', 'Right-of-use assets', 'Intangible assets', 'Deferred tax assets']], ['Current liabilities', ['Trade payables', 'Accrued expenses', 'Short-term borrowings', 'Current tax payable']], ['Non-current liabilities', ['Long-term borrowings', 'Lease liabilities', 'Provisions']], ['Equity', ['Share capital', 'Retained earnings', 'Other reserves']]]
: [['Revenue', ['Product revenue', 'Service revenue', 'Other operating income']], ['Cost of sales', ['Materials', 'Direct labour', 'Manufacturing overhead']], ['Operating expenses', ['Selling and marketing', 'General and administrative', 'Research and development', 'Depreciation and amortisation']], ['Finance and tax', ['Finance costs', 'Interest income', 'Income tax expense']]];
const extra = opt.dense ? 1 : 0; const totals = {};
for (const s of sections) {
const lines = s[1].slice(); if (extra) lines.push(...r.sample(['Other receivables', 'Derivative assets', 'Contract assets', 'Investment property', 'Employee benefits', 'Deferred revenue', 'Government grants', 'Hedging reserve'], r.int(1, 3)));
const rows = []; let t = 0, tp = 0; for (const ln of lines) { const cur = v(); const prv = Math.round(cur * r.float(0.8, 1.15)); t += cur; tp += prv; rows.push([ln, fmt(cur), fmt(prv)]); }
rows.push(['Total ' + s[0].toLowerCase(), fmt(t), fmt(tp)]); totals[s[0]] = t;
doc.blocks.push(B.h(s[0])); doc.blocks.push(B.table(['', String(yr), String(yr - 1)], rows, s[0].toLowerCase().replace(/[^a-z]+/g, '_'), ['l', 'r', 'r']));
}
if (bs) { E.total_assets = totals['Current assets'] + totals['Non-current assets']; E.total_liabilities = totals['Current liabilities'] + totals['Non-current liabilities']; E.total_equity = totals['Equity']; }
else { E.total_revenue = totals['Revenue']; E.gross_profit = totals['Revenue'] - totals['Cost of sales']; E.operating_profit = E.gross_profit - totals['Operating expenses']; }
doc.blocks.push(B.p('The accompanying notes form an integral part of these financial statements.'));
doc.blocks.push(B.footer(co.name + ' · Unaudited management accounts'));
doc.schema = schemaOf(E); return doc;
}
const LEGAL_HEADS = ['Definitions', 'Term', 'Payment', 'Confidentiality', 'Limitation of Liability', 'Indemnification', 'Termination', 'Governing Law', 'Force Majeure', 'Assignment', 'Notices', 'Entire Agreement', 'Severability', 'Data Protection', 'Audit Rights', 'Intellectual Property', 'Warranties', 'Insurance', 'Dispute Resolution', 'Non-Solicitation'];
const LEGAL_S = ['Each party shall {v} the {o} of the other party {c}.', 'The {o} shall remain in effect {c}, unless terminated earlier in accordance with this Agreement.', 'Neither party shall be liable for any {o} arising from {x}, except as expressly provided herein.', 'All {o} disclosed under this Agreement shall be {v2} {c}.', 'Any notice required under this Agreement shall be given in writing and delivered {d}.', 'The Supplier warrants that all {o} will be performed with reasonable skill and care {c}.', 'This clause shall survive the expiry or termination of this Agreement {c}.', 'Invoices shall be payable within {n} days of receipt, and late amounts may accrue interest at {p}% per annum.', 'The parties shall use reasonable endeavours to resolve any dispute through good-faith negotiation {c}.', 'Nothing in this Agreement shall be construed as creating a partnership, joint venture or agency relationship.'];
const LEGAL_F = { v: ['protect', 'respect', 'safeguard', 'not disclose'], o: ['Confidential Information', 'Services', 'deliverables', 'obligations', 'personal data', 'intellectual property rights', 'records'], c: ['for the duration of the Term', 'to the extent permitted by applicable law', 'in accordance with Schedule 2', 'save as required by any regulatory authority', 'for a period of three years thereafter'], x: ['a delay caused by events beyond its reasonable control', 'indirect or consequential loss', 'loss of profit or revenue'], v2: ['held in strict confidence', 'used solely for the Purpose', 'returned or destroyed upon request'], d: ['by hand or by recorded delivery', 'by email with confirmation of receipt', 'to the registered office of the receiving party'], n: ['30', '45', '60'], p: ['2', '4', '8'] };
function legalPara(r, k) { const out = []; for (let i = 0; i < k; i++) out.push(r.pick(LEGAL_S).replace(/\{(\w+)\}/g, (m, g) => r.pick(LEGAL_F[g]))); return out.join(' '); }
function letterDoc(r, type) {
const L = locale(r); const co = company(r, L, type === 'dunning_letter' ? 'supplier' : 'buyer'); const df = r.pick(L.dates); const d = baseDate(r); const p = person(r, L); const sig = person(r, L);
const titles = { dunning_letter: [r.pick(['PAYMENT REMINDER', 'FINAL NOTICE', 'Overdue Account Notice'])], offer_letter: [r.pick(['OFFER OF EMPLOYMENT', 'Employment Offer Letter'])], nda: [r.pick(['MUTUAL NON-DISCLOSURE AGREEMENT', 'Confidentiality Agreement'])], meeting_minutes: [r.pick(['MINUTES OF MEETING', 'Meeting Notes'])] };
const doc = newDoc(type, titles[type][0]); doc.locale = L.code; const E = doc.entities; header(r, doc, co, doc.title);
if (type === 'dunning_letter') {
const cust = company(r, L, 'buyer'); const amt = r2(r.float(400, 30000)); const days = r.pick([30, 45, 60, 90]); const inv = 'INV-' + r.digits(5); const deadline = addDays(d, r.pick([7, 10, 14]));
doc.blocks.push(B.kv([kvi('Date', fmtDate(d, df), 'date'), kvi('Account No.', 'CUST-' + r.digits(5), 'customer_account'), kvi('To', cust.name, 'customer_name'), kvi('Attn', p.name, 'contact_name', 'PERSON_NAME')], 2));
doc.blocks.push(B.p([S('Dear '), S(p.name, 'PERSON_NAME'), S(',')]));
doc.blocks.push(B.p('Our records show that invoice ' + inv + ' for ' + money(amt, L) + ' is now ' + days + ' days past due. Despite previous reminders, we have not received payment or a response regarding this balance.'));
doc.blocks.push(B.p('Please arrange payment in full by ' + fmtDate(deadline, df) + '. If payment is not received by this date, we may place your account on credit hold and refer the balance to a collection agency.'));
doc.blocks.push(B.p([S('If you have already paid, please disregard this notice. For questions, contact '), S(sig.email, 'EMAIL'), S(' or '), S(sig.phone, 'PHONE'), S('.')]));
doc.blocks.push(B.sign([{ label: 'Credit Control', name: sig.name, pii: 'PERSON_NAME' }]));
Object.assign(E, { creditor_name: co.name, customer_name: cust.name, date: iso(d), invoice_number: inv, amount_overdue: gold(amt), currency: L.cur, days_past_due: days, payment_deadline: iso(deadline) });
} else if (type === 'offer_letter') {
const role = r.pick(['Senior Accountant', 'Data Engineer', 'Procurement Manager', 'Plant Supervisor', 'HR Business Partner', 'Product Designer']); const sal = r2(r.float(40000, 160000) * (L.cur === 'INR' ? 25 : 1)); const start = addDays(d, r.int(14, 60)); const notice = r.pick(['30 days', 'one month', 'three months', '60 days']);
doc.blocks.push(B.kv([kvi('Date', fmtDate(d, df), 'date'), kvi('Candidate', p.name, 'employee_name', 'PERSON_NAME'), kvi('Address', p.address, 'employee_address', 'ADDRESS', { span: true })], 2));
doc.blocks.push(B.p([S('Dear '), S(p.first, 'PERSON_NAME'), S(',')]));
doc.blocks.push(B.p('We are pleased to offer you the position of ' + role + ' at ' + co.name + ', starting on ' + fmtDate(start, df) + '. This letter sets out the principal terms of your employment.'));
doc.blocks.push(B.list(['Annual base salary: ' + money(sal, L) + ', paid monthly in arrears.', 'Probation period: six months.', 'Notice period: ' + notice + ' after confirmation.', 'Working hours: 40 hours per week, with flexible arrangements by agreement.', 'Benefits: health cover, retirement plan and 25 days of annual leave.']));
doc.blocks.push(B.p('This offer is subject to satisfactory references and verification of your right to work. Please sign and return a copy of this letter to confirm your acceptance.'));
doc.blocks.push(B.sign([{ label: 'For ' + co.name, name: sig.name, pii: 'PERSON_NAME' }, { label: 'Accepted by', name: p.name, pii: 'PERSON_NAME' }]));
Object.assign(E, { employer_name: co.name, employee_name: p.name, employee_address: p.address, offer_date: iso(d), job_title: role, start_date: iso(start), annual_salary: gold(sal), currency: L.cur, notice_period: notice });
} else if (type === 'nda') {
const other = company(r, L, 'supplier'); const yrs = r.pick([2, 3, 5]); const law = r.pick(['England and Wales', 'the State of Delaware', 'Singapore', 'New South Wales', 'Ontario', 'India']);
doc.blocks.push(B.p('This Agreement is made on ' + fmtDate(d, df) + ' between ' + co.name + ' ("Party A") and ' + other.name + ' ("Party B") in connection with discussions regarding a potential business relationship (the "Purpose").'));
const heads = r.sample(LEGAL_HEADS, r.int(4, 6)); heads.forEach((h, i) => { doc.blocks.push(B.h((i + 1) + '. ' + h)); doc.blocks.push(B.p(h === 'Term' ? 'This Agreement shall remain in force for ' + yrs + ' years from the date above. ' + legalPara(r, 1) : (h === 'Governing Law' ? 'This Agreement is governed by the laws of ' + law + '. ' + legalPara(r, 1) : legalPara(r, r.int(2, 3))))); });
if (heads.indexOf('Term') < 0) { doc.blocks.push(B.h((heads.length + 1) + '. Term')); doc.blocks.push(B.p('This Agreement shall remain in force for ' + yrs + ' years from the date above.')); }
if (heads.indexOf('Governing Law') < 0) { doc.blocks.push(B.h((heads.length + 2) + '. Governing Law')); doc.blocks.push(B.p('This Agreement is governed by the laws of ' + law + '.')); }
doc.blocks.push(B.sign([{ label: 'For Party A', name: sig.name, pii: 'PERSON_NAME' }, { label: 'For Party B', name: p.name, pii: 'PERSON_NAME' }]));
Object.assign(E, { party_a: co.name, party_b: other.name, effective_date: iso(d), term_years: yrs, governing_law: law });
} else {
const att = [p, sig, person(r, L), person(r, L)].slice(0, r.int(3, 4)); const topic = r.pick(['Q3 close review', 'Supplier onboarding project', 'Warehouse safety committee', 'ERP migration steering group', 'Budget planning FY26']);
doc.blocks.push(B.kv([kvi('Meeting', topic, 'meeting_title', null, { span: true }), kvi('Date', fmtDate(d, df), 'date'), kvi('Chair', att[0].name, 'chair', 'PERSON_NAME'), kvi('Location', r.pick(['Conference Room 3', 'Video call', 'Head office, Level 5']), 'location')], 2));
doc.blocks.push(B.h('Attendees')); const asg = []; att.forEach((a, i) => { if (i) asg.push(S(', ')); asg.push(S(a.name, 'PERSON_NAME')); }); doc.blocks.push(B.p(asg));
doc.blocks.push(B.h('Discussion')); doc.blocks.push(B.list(r.sample(['Reviewed open action items from the previous meeting.', 'Finance presented the variance analysis against budget.', 'Agreed to extend the pilot by four weeks.', 'Discussed vendor performance and two late deliveries.', 'Reviewed the risk register; no new high risks.', 'IT confirmed the cut-over date for the new system.'], r.int(3, 5))));
const acts = att.slice(0, r.int(2, 3)).map((a) => [r.pick(['Circulate revised forecast', 'Confirm vendor SLA', 'Update project plan', 'Schedule training sessions', 'Close open audit points']), a.name, fmtDate(addDays(d, r.int(5, 30)), df)]);
doc.blocks.push(B.h('Action Items')); doc.blocks.push(B.table(['Action', 'Owner', 'Due'], acts, 'action_items'));
Object.assign(E, { meeting_title: topic, date: iso(d), chair: att[0].name, attendees: att.map((a) => a.name), action_items: acts.map((x) => ({ action: x[0], owner: x[1] })) });
}
doc.blocks.push(B.footer(co.name + ' · ' + co.address));
doc.schema = schemaOf(E); return doc;
}
function formDoc(r, type) {
const L = locale(r); const org = company(r, L, type === 'patient_intake_form' || type === 'claim_form' ? (type === 'claim_form' ? 'insurer' : 'clinic') : (type === 'bank_details_form' || type === 'credit_application' ? 'supplier' : 'bank')); const df = r.pick(L.dates); const d = baseDate(r); const p = person(r, L);
const titles = { kyc_form: r.pick(['CUSTOMER ONBOARDING (KYC) FORM', 'Account Opening Form']), bank_details_form: r.pick(['VENDOR BANK DETAILS FORM', 'Supplier Payment Details']), credit_application: r.pick(['CREDIT APPLICATION', 'Trade Credit Application Form']), patient_intake_form: r.pick(['PATIENT REGISTRATION FORM', 'New Patient Intake']), claim_form: r.pick(['INSURANCE CLAIM FORM', 'Health Claim Form']) };
const doc = newDoc(type, titles[type]); doc.locale = L.code; doc.form = true; const E = doc.entities; header(r, doc, org, doc.title);
const F = (label, value, key, pii, extra) => { E[key] = (extra && extra.gold !== undefined) ? extra.gold : value; return kvi(label, value, key, pii, extra); };
if (type === 'kyc_form') {
doc.blocks.push(B.h('Section 1 - Personal Details'));
doc.blocks.push(B.kv([F('Full Name', p.name, 'full_name', 'PERSON_NAME'), F('Date of Birth', fmtDate(p.dob, df), 'date_of_birth', 'DATE_OF_BIRTH', { gold: iso(p.dob) }), F('Nationality', COUNTRY[L.code], 'nationality'), F('Occupation', r.pick(['Engineer', 'Teacher', 'Business Owner', 'Accountant', 'Nurse', 'Consultant']), 'occupation'), F('Residential Address', p.address, 'address', 'ADDRESS', { span: true }), F('Email', p.email, 'email', 'EMAIL'), F('Mobile', p.phone, 'phone', 'PHONE')], 2));
doc.blocks.push(B.h('Section 2 - Identification'));
const idt = r.pick(['Passport', 'National ID', 'Driving Licence']); doc.blocks.push(B.kv([F('ID Type', idt, 'id_type'), F('ID Number', idt === 'Passport' ? p.passport : p.nid, 'id_number', idt === 'Passport' ? 'PASSPORT_NUMBER' : 'NATIONAL_ID'), F('Issue Date', fmtDate(addDays(d, -r.int(300, 3000)), df), 'id_issue_date'), F('Expiry Date', fmtDate(addDays(d, r.int(300, 3000)), df), 'id_expiry_date')], 2));
const at = r.pick(['Savings', 'Current', 'Joint']); doc.blocks.push(B.checks('Account Type', ['Savings', 'Current', 'Joint'], [at], 'account_type')); E.account_type = at;
const sf = r.pick(['Salary', 'Business income', 'Investments', 'Inheritance']); doc.blocks.push(B.checks('Source of Funds', ['Salary', 'Business income', 'Investments', 'Inheritance'], [sf], 'source_of_funds')); E.source_of_funds = sf;
const pep = r.bool(0.1) ? 'Yes' : 'No'; doc.blocks.push(B.checks('Are you a politically exposed person (PEP)?', ['Yes', 'No'], [pep], 'pep_status')); E.pep_status = pep;
doc.blocks.push(B.p('I confirm that the information provided is true and complete, and I consent to identity verification checks.'));
doc.blocks.push(B.sign([{ label: 'Applicant Signature', name: p.name, pii: 'PERSON_NAME', date: fmtDate(d, df) }]));
} else if (type === 'bank_details_form') {
const v = company(r, L, 'supplier'); const bank = company(r, L, 'bank'); const ib = ibanFor(r, r.pick(['GB', 'DE', 'FR']));
doc.blocks.push(B.p('Please complete all fields so that payments can be made to your account. Changes to bank details must be confirmed by a call-back to a known contact.'));
doc.blocks.push(B.h('Supplier Information'));
doc.blocks.push(B.kv([F('Supplier Name', v.name, 'supplier_name'), F('Supplier ID', 'V' + r.digits(6), 'supplier_id'), F('Registered Address', v.address, 'supplier_address', null, { span: true }), F('Contact Person', p.name, 'contact_name', 'PERSON_NAME'), F('Contact Email', p.email, 'contact_email', 'EMAIL'), F('Contact Phone', p.phone, 'contact_phone', 'PHONE'), F('Tax ID', v.taxId, 'tax_id')], 2));
doc.blocks.push(B.h('Bank Information'));
doc.blocks.push(B.kv([F('Bank Name', bank.name, 'bank_name'), F('Account Holder', v.name, 'account_holder'), F('Account Number', r.digits(10), 'account_number', 'ACCOUNT_NUMBER'), F('Routing / Sort Code', r.digits(2) + '-' + r.digits(2) + '-' + r.digits(2), 'routing_code'), F('IBAN', ib, 'iban', 'IBAN', { span: true }), F('SWIFT / BIC', r.letters(4) + 'XX' + r.letters(2), 'swift_bic')], 2));
const pm = r.pick(['ACH', 'Wire', 'SEPA']); doc.blocks.push(B.checks('Preferred Payment Method', ['ACH', 'Wire', 'SEPA', 'Cheque'], [pm], 'payment_method')); E.payment_method = pm;
doc.blocks.push(B.sign([{ label: 'Authorised Signatory', name: p.name, pii: 'PERSON_NAME', date: fmtDate(d, df) }]));
} else if (type === 'credit_application') {
const c = company(r, L, 'buyer'); const lim = r2(r.pick([5000, 10000, 25000, 50000, 100000]) * (L.cur === 'INR' ? 50 : 1));
doc.blocks.push(B.h('Business Information'));
doc.blocks.push(B.kv([F('Legal Business Name', c.name, 'applicant_name'), F('Trading As', c.name.split(' ').slice(0, 2).join(' '), 'trading_name'), F('Business Address', c.address, 'applicant_address', null, { span: true }), F('Years in Business', String(r.int(1, 40)), 'years_in_business'), F('Tax ID', c.taxId, 'tax_id'), F('Credit Limit Requested', money(lim, L), 'credit_limit_requested', null, { gold: gold(lim) })], 2));
const et = r.pick(['Corporation', 'LLC', 'Partnership', 'Sole proprietor']); doc.blocks.push(B.checks('Entity Type', ['Corporation', 'LLC', 'Partnership', 'Sole proprietor'], [et], 'entity_type')); E.entity_type = et;
doc.blocks.push(B.h('Principal / Guarantor'));
doc.blocks.push(B.kv([F('Name', p.name, 'principal_name', 'PERSON_NAME'), F('Title', r.pick(['CEO', 'Owner', 'CFO', 'Director']), 'principal_title'), F('Home Address', p.address, 'principal_address', 'ADDRESS', { span: true }), F('ID Number', p.nid, 'principal_id_number', 'NATIONAL_ID'), F('Phone', p.phone, 'principal_phone', 'PHONE')], 2));
doc.blocks.push(B.h('Trade References'));
const refs = [0, 1].map(() => { const x = company(r, L, 'supplier'); return [x.name, x.phone, 'Net ' + r.pick([30, 45, 60])]; }); doc.blocks.push(B.table(['Company', 'Phone', 'Terms'], refs, 'trade_references'));
E.trade_references = refs.map((x) => ({ company: x[0], terms: x[2] }));
doc.blocks.push(B.sign([{ label: 'Applicant Signature', name: p.name, pii: 'PERSON_NAME', date: fmtDate(d, df) }]));
} else if (type === 'patient_intake_form') {
doc.blocks.push(B.h('Patient Information'));
doc.blocks.push(B.kv([F('Full Name', p.name, 'patient_name', 'PERSON_NAME'), F('Date of Birth', fmtDate(p.dob, df), 'date_of_birth', 'DATE_OF_BIRTH', { gold: iso(p.dob) }), F('Address', p.address, 'address', 'ADDRESS', { span: true }), F('Phone', p.phone, 'phone', 'PHONE'), F('Email', p.email, 'email', 'EMAIL')], 2));
const sex = r.pick(['Female', 'Male', 'Other']); doc.blocks.push(B.checks('Sex', ['Female', 'Male', 'Other'], [sex], 'sex')); E.sex = sex;
const ins = company(r, L, 'insurer'); doc.blocks.push(B.h('Insurance'));
doc.blocks.push(B.kv([F('Insurance Provider', ins.name, 'insurance_provider'), F('Member ID', r.letters(3) + r.digits(9), 'member_id', 'ACCOUNT_NUMBER'), F('Group Number', r.digits(6), 'group_number')], 2));
const ec = person(r, L); doc.blocks.push(B.h('Emergency Contact'));
doc.blocks.push(B.kv([F('Name', ec.name, 'emergency_contact_name', 'PERSON_NAME'), F('Phone', ec.phone, 'emergency_contact_phone', 'PHONE')], 2));
const cond = r.sample(['Diabetes', 'Hypertension', 'Asthma', 'Allergies', 'Heart disease', 'None'], r.int(1, 2)); doc.blocks.push(B.checks('Medical history (tick all that apply)', ['Diabetes', 'Hypertension', 'Asthma', 'Allergies', 'Heart disease', 'None'], cond, 'medical_history')); E.medical_history = cond;
doc.blocks.push(B.sign([{ label: 'Patient Signature', name: p.name, pii: 'PERSON_NAME', date: fmtDate(d, df) }]));
} else {
const loss = addDays(d, -r.int(3, 40)); const amt = r2(r.float(120, 9000)); const ct = r.pick(['Outpatient', 'Inpatient', 'Dental', 'Pharmacy']);
doc.blocks.push(B.h('Policyholder'));
doc.blocks.push(B.kv([F('Claimant Name', p.name, 'claimant_name', 'PERSON_NAME'), F('Policy Number', 'POL-' + r.digits(8), 'policy_number'), F('Date of Birth', fmtDate(p.dob, df), 'date_of_birth', 'DATE_OF_BIRTH', { gold: iso(p.dob) }), F('Phone', p.phone, 'phone', 'PHONE'), F('Email', p.email, 'email', 'EMAIL'), F('Address', p.address, 'address', 'ADDRESS', { span: true })], 2));
doc.blocks.push(B.checks('Claim Type', ['Outpatient', 'Inpatient', 'Dental', 'Pharmacy'], [ct], 'claim_type')); E.claim_type = ct;
doc.blocks.push(B.h('Claim Details'));
doc.blocks.push(B.kv([F('Date of Service', fmtDate(loss, df), 'date_of_service', null, { gold: iso(loss) }), F('Provider', company(r, L, 'clinic').name, 'provider_name'), F('Diagnosis Code', r.letters(1) + r.digits(2) + '.' + r.digits(1), 'diagnosis_code'), F('Amount Claimed', money(amt, L), 'amount_claimed', null, { gold: gold(amt) })], 2));
E.currency = L.cur; E.claim_number = 'CLM-' + r.digits(9);
doc.blocks.splice(1, 0, B.kv([kvi('Claim No.', E.claim_number, 'claim_number'), kvi('Received', fmtDate(d, df), 'received_date')], 2)); E.received_date = iso(d);
doc.blocks.push(B.p('I declare that the information given is correct and authorise the release of medical information needed to process this claim.'));
doc.blocks.push(B.sign([{ label: 'Claimant Signature', name: p.name, pii: 'PERSON_NAME', date: fmtDate(d, df) }]));
}
for (const b of doc.blocks) if (b.t === 'kv') for (const it of b.items) if (b !== doc.blocks[1] || type !== 'claim_form') it.hand = true;
doc.blocks.push(B.footer(org.name + ' · Form ' + r.letters(2) + '-' + r.digits(3) + ' · Rev. ' + r.int(1, 9) + '/' + r.int(2019, 2025)));
doc.schema = schemaOf(E); return doc;
}
function generate(type, seed, opt) { const r = RNG(seed); const d = BUILD[type](r, opt); d.seed = seed; return d; }
// ---------------------------------------------------------------- text / html / markdown
function blockText(b) {
// returns {text, spans:[{type,start,end}]}
let s = ''; const spans = [];
const add = (t, pii) => { if (pii) spans.push({ type: pii, start: s.length, end: s.length + t.length }); s += t; };
const segs = (arr) => arr.forEach((x) => add(x.text, x.pii));
switch (b.t) {
case 'brand': add(b.name + '\n' + b.lines.join('\n')); break;
case 'title': case 'h': case 'footer': add(b.text); break;
case 'p': segs(b.segs); break;
case 'kv': b.items.forEach((it, i) => { if (i) add('\n'); add(it.label + ': '); add(it.value, it.pii); }); break;
case 'totals': b.items.forEach((it, i) => { if (i) add('\n'); add(it.label + ': ' + it.value); }); break;
case 'table': { const all = [b.head].concat(b.rows); const w = b.head.map((_, c) => Math.max.apply(null, all.map((row) => String(row[c]).length))); all.forEach((row, i) => { if (i) add('\n'); add(row.map((c, j) => String(c).padEnd(w[j])).join(' ').trimEnd()); }); break; }
case 'checks': add(b.label + ': ' + b.options.map((o) => (b.checked.indexOf(o) >= 0 ? '[x] ' : '[ ] ') + o).join(' ')); break;
case 'sign': b.parties.forEach((pp, i) => { if (i) add('\n'); add(pp.label + ': '); add(pp.name, pp.pii); if (pp.date) add(' Date: ' + pp.date); }); break;
case 'list': add(b.items.map((x) => '- ' + x).join('\n')); break;
case 'cols': b.sections.forEach((sec, i) => { if (i) add('\n\n'); if (sec.h) add(sec.h + '\n'); segs(sec.segs); }); break;
}
return { text: s, spans };
}
function joinBlocks(parts) { let s = ''; const spans = []; parts.forEach((p, i) => { if (i) s += '\n\n'; p.spans.forEach((sp) => spans.push({ type: sp.type, start: sp.start + s.length, end: sp.end + s.length, text: p.text.slice(sp.start, sp.end) })); s += p.text; }); return { text: s, spans }; }
function toText(doc) { const out = []; for (const b of doc.blocks) { if (b.t === 'brand') { out.push(blockText(b)); out.push(blockText({ t: 'title', text: b.title })); } else out.push(blockText(b)); } return joinBlocks(out); }
const esc = (x) => String(x).replace(/&/g, '&').replace(//g, '>');
function blockHTML(b) {
switch (b.t) {
case 'brand': return ' ' + b.lines.map(esc).join('' + esc(b.name) + '
') + '' + esc(b.title) + '
' + b.segs.map((x) => esc(x.text)).join('') + '
'; case 'kv': case 'totals': return '' + esc(pp.label) + ': ' + esc(pp.name) + '' + (pp.date ? ' Date: ' + esc(pp.date) : '') + '
').join('') + '' + s.segs.map((x) => esc(x.text)).join('') + '
').join('') + '| ' + esc(h) + ' | ').join('') + '
|---|
| ' + esc(c) + ' | ').join('') + '