Datasets:
File size: 111,991 Bytes
43f852d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 | // 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, '<').replace(/>/g, '>');
function blockHTML(b) {
switch (b.t) {
case 'brand': return '<header><h2>' + esc(b.name) + '</h2><p>' + b.lines.map(esc).join('<br>') + '</p><h1>' + esc(b.title) + '</h1></header>';
case 'title': return '<h1>' + esc(b.text) + '</h1>';
case 'h': return '<h3>' + esc(b.text) + '</h3>';
case 'p': return '<p>' + b.segs.map((x) => esc(x.text)).join('') + '</p>';
case 'kv': case 'totals': return '<dl class="' + b.t + '">' + b.items.map((it) => '<dt>' + esc(it.label) + '</dt><dd>' + esc(it.value) + '</dd>').join('') + '</dl>';
case 'table': return tableHTML(b.head, b.rows);
case 'checks': return '<fieldset><legend>' + esc(b.label) + '</legend>' + b.options.map((o) => '<label><input type="checkbox"' + (b.checked.indexOf(o) >= 0 ? ' checked' : '') + '> ' + esc(o) + '</label>').join(' ') + '</fieldset>';
case 'sign': return '<div class="signatures">' + b.parties.map((pp) => '<p>' + esc(pp.label) + ': <i>' + esc(pp.name) + '</i>' + (pp.date ? ' Date: ' + esc(pp.date) : '') + '</p>').join('') + '</div>';
case 'list': return '<ul>' + b.items.map((x) => '<li>' + esc(x) + '</li>').join('') + '</ul>';
case 'footer': return '<footer>' + esc(b.text) + '</footer>';
case 'cols': return '<div style="column-count:' + b.n + '">' + b.sections.map((s) => (s.h ? '<h4>' + esc(s.h) + '</h4>' : '') + '<p>' + s.segs.map((x) => esc(x.text)).join('') + '</p>').join('') + '</div>';
}
return '';
}
function tableHTML(head, rows) { return '<table border="1" cellpadding="4" style="border-collapse:collapse"><thead><tr>' + head.map((h) => '<th>' + esc(h) + '</th>').join('') + '</tr></thead><tbody>' + rows.map((row) => '<tr>' + row.map((c) => '<td>' + esc(c) + '</td>').join('') + '</tr>').join('') + '</tbody></table>'; }
function toHTML(doc) { return '<!DOCTYPE html><html><head><meta charset="utf-8"><title>' + esc(doc.title) + '</title><style>body{font-family:Arial,sans-serif;max-width:800px;margin:24px auto;font-size:14px}dl{display:grid;grid-template-columns:max-content 1fr;gap:2px 12px}dt{font-weight:bold}footer{color:#666;font-size:12px;margin-top:24px}</style></head><body>' + doc.blocks.map(blockHTML).join('\n') + '</body></html>'; }
function mdCell(x) { return String(x).replace(/\|/g, '\\|'); }
function blockMD(b) {
switch (b.label) {
case 'title': return '# ' + b.text;
case 'section_header': return '## ' + b.text;
case 'table': { const rows = b.table; return '| ' + rows[0].map(mdCell).join(' | ') + ' |\n|' + rows[0].map(() => ' --- |').join('') + '\n' + rows.slice(1).map((r) => '| ' + r.map(mdCell).join(' | ') + ' |').join('\n'); }
case 'list': return b.text;
case 'checkbox_group': return b.text.replace(/\[x\]/g, '- [x]').replace(/\[ \]/g, '- [ ]').replace(/: /, ':\n').replace(/ - /g, '\n- ');
case 'logo': case 'stamp': case 'signature_mark': return '';
default: return b.text;
}
}
// ---------------------------------------------------------------- canvas renderer
const PRINT_FONTS = ['Helvetica', 'Arial', 'Georgia', 'Times New Roman', 'Verdana', 'Palatino', 'Gill Sans', 'Avenir', 'Optima', 'Trebuchet MS', 'Baskerville', 'Futura'];
const HAND_FONTS = ['Bradley Hand', 'Noteworthy', 'Chalkboard SE', 'Marker Felt', 'Snell Roundhand', 'Apple Chancery', 'Savoye LET', 'Brush Script MT'];
const INKS = { blue: '#1c3f94', black: '#1d1d1f', darkblue: '#14285e', green: '#1e5a32' };
function handStyle(r) { const font = r.pick(HAND_FONTS); const big = /Savoye|Brush|Snell/.test(font) ? 1.35 : 1; const ink = r.pick(['blue', 'blue', 'black', 'darkblue']); return { font, scale: r.float(1.0, 1.25) * big, ink, color: INKS[ink], slant: r.float(-0.12, 0.08), jitter: r.float(0.5, 2.2), rot: r.float(0.01, 0.06), spacing: r.float(0.95, 1.12) }; }
function makeCanvas(w, h, opts) { if (opts && opts.createCanvas) return opts.createCanvas(w, h); const c = document.createElement('canvas'); c.width = w; c.height = h; return c; }
function render(doc, opts) {
opts = opts || {}; const r = opts.rnd || RNG((doc.seed || 1) * 7 + 3);
const W = opts.W || 1240, H = opts.H || 1754; const cv = makeCanvas(W, H, opts); const ctx = cv.getContext('2d');
const F = opts.font || r.pick(PRINT_FONTS); const SZ = opts.size || r.pick([20, 21, 22, 23, 24]); const M = opts.margin || r.int(80, 110); const accent = opts.accent || r.pick(['#1f3a5f', '#2b2b2b', '#0f5257', '#5b2a86', '#8a1c1c', '#1d4ed8', '#374151']);
let hand = opts.hand ? (opts.handStyle || handStyle(r)) : null; const lh = 1.32;
ctx.fillStyle = opts.bg || '#ffffff'; ctx.fillRect(0, 0, W, H); ctx.textBaseline = 'top';
const out = { width: W, height: H, font: F, size: SZ, blocks: [], fields: [], pii: [], checkboxes: [], signatures: [], tables: {}, truncated: false, hand: hand ? { font: hand.font, ink: hand.ink } : null };
const font = (sz, w, fam) => (w ? w + ' ' : '') + Math.round(sz) + 'px "' + (fam || F) + '"';
const tw = (t, f) => { ctx.font = f; return ctx.measureText(t).width; };
const rec = (label, bbox, text, extra) => { const b = Object.assign({ id: 'b' + out.blocks.length, order: out.blocks.length, label, bbox: bbox.map(Math.round), text }, extra || {}); out.blocks.push(b); return b; };
const x0 = M, x1 = W - M; let y = M; const bottom = H - M - SZ * 1.6;
function text(t, x, yy, f, color, align) { ctx.font = f; ctx.fillStyle = color || '#111'; let w = ctx.measureText(t).width; let xx = align === 'right' ? x - w : (align === 'center' ? x - w / 2 : x); ctx.fillText(t, xx, yy); const sz = parseFloat(f.match(/(\d+)px/)[1]); return [xx, yy, xx + w, yy + sz * 1.2]; }
function handText(t, x, yy, sz, maxW) {
const st = hand; let s = sz * st.scale; ctx.font = font(s, '', st.font); let w = ctx.measureText(t).width * st.spacing; if (maxW && w > maxW) { s = s * maxW / w; w = maxW; }
ctx.fillStyle = st.color; let cx = x; const base = yy + r.float(-2, 2);
for (const ch of t) { ctx.font = font(s * r.float(0.94, 1.06), '', st.font); const cw = ctx.measureText(ch).width; ctx.save(); ctx.translate(cx, base + r.gauss() * st.jitter); ctx.transform(1, 0, st.slant, 1, 0, 0); ctx.rotate(r.gauss() * st.rot); ctx.fillText(ch, 0, 0); ctx.restore(); cx += cw * st.spacing; }
return [x, yy - s * 0.1, cx, yy + s * 1.15];
}
function wrap(segs, maxW, f) {
// returns lines: [{pieces:[{text,pii,w}], w}]
const words = []; segs.forEach((sg, si) => { const parts = sg.text.split(/(\s+)/); parts.forEach((pt) => { if (pt) words.push({ text: pt, pii: sg.pii, seg: si }); }); });
const lines = []; let cur = { pieces: [], w: 0 };
for (const wd of words) { const w = tw(wd.text, f); if (/\n/.test(wd.text)) { while (cur.pieces.length && cur.pieces[cur.pieces.length - 1].text === ' ') { cur.w -= cur.pieces.pop().w; } lines.push(cur); cur = { pieces: [], w: 0 }; continue; } if (/^\s+$/.test(wd.text)) { if (cur.pieces.length) { cur.pieces.push({ text: ' ', pii: wd.pii, seg: wd.seg, w: tw(' ', f) }); cur.w += tw(' ', f); } continue; } if (cur.w + w > maxW && cur.pieces.length) { while (cur.pieces.length && cur.pieces[cur.pieces.length - 1].text === ' ') { cur.w -= cur.pieces.pop().w; } lines.push(cur); cur = { pieces: [], w: 0 }; } cur.pieces.push({ text: wd.text, pii: wd.pii, seg: wd.seg, w }); cur.w += w; }
if (cur.pieces.length) lines.push(cur); return lines;
}
function drawLines(lines, x, yy, f, color, sz) {
const piiBoxes = []; let cy = yy; let maxX = x;
for (const ln of lines) { let cx = x; for (const pc of ln.pieces) { ctx.font = f; ctx.fillStyle = color; ctx.fillText(pc.text, cx, cy); if (pc.pii && pc.text !== ' ') { const last = piiBoxes[piiBoxes.length - 1]; if (last && last.seg === pc.seg && last.line === cy) { last.bbox[2] = cx + pc.w; last.text += pc.text; } else piiBoxes.push({ pii: pc.pii, seg: pc.seg, line: cy, text: pc.text, bbox: [cx, cy, cx + pc.w, cy + sz * 1.2] }); } else if (pc.pii && pc.text === ' ') { const last = piiBoxes[piiBoxes.length - 1]; if (last && last.seg === pc.seg && last.line === cy) last.text += ' '; } cx += pc.w; } maxX = Math.max(maxX, cx); cy += sz * lh; }
return { h: cy - yy, piiBoxes, maxX };
}
function logo(x, yy, sz, name) { const shape = r.int(0, 2); ctx.fillStyle = accent; const s = sz * 2.6; if (shape === 0) { ctx.beginPath(); ctx.arc(x + s / 2, yy + s / 2, s / 2, 0, Math.PI * 2); ctx.fill(); } else if (shape === 1) { ctx.fillRect(x, yy, s, s); } else { ctx.beginPath(); ctx.moveTo(x + s / 2, yy); ctx.lineTo(x + s, yy + s); ctx.lineTo(x, yy + s); ctx.closePath(); ctx.fill(); } const ini = name.split(' ').slice(0, 2).map((w) => w[0]).join(''); text(ini, x + s / 2, yy + s * (shape === 2 ? 0.45 : 0.28), font(sz * 1.05, 'bold'), '#fff', 'center'); return [x, yy, x + s, yy + s]; }
const blocks = doc.blocks.filter((b) => b.t !== 'footer'); const footer = doc.blocks.find((b) => b.t === 'footer');
const twoColumnMeta = r.bool(0.5);
function doBlock(b, draw) {
// returns height used; when draw, renders and records
const sz = SZ;
if (b.t === 'brand') {
const nameF = font(sz * 1.45, 'bold'); const lineF = font(sz * 0.82); if (!b._ts) b._ts = r.pick([1.7, 1.9, 2.1]); const titleF = font(sz * b._ts, 'bold'); const lg = b.logo && (opts.logo !== false);
const ls = sz * 2.6; const tx = x0 + (lg ? ls + sz * 0.8 : 0); const bw = tx + Math.max(tw(b.name, nameF), ...b.lines.map((l) => tw(l, lineF))); const below = !!b.title && x1 - tw(b.title, titleF) < bw + sz;
const h = Math.max(lg ? ls : 0, sz * 1.45 * 1.2 + b.lines.length * sz * 0.82 * lh) + sz * 1.2 + (below ? sz * b._ts * 1.5 : 0);
if (draw) {
if (lg) { const bb = logo(x0, y, sz, b.name); rec('logo', bb, ''); }
const nb = text(b.name, tx, y, nameF, accent); let yy = y + sz * 1.45 * 1.25; let mx = nb[2]; for (const l of b.lines) { const lb = text(l, tx, yy, lineF, '#444'); mx = Math.max(mx, lb[2]); yy += sz * 0.82 * lh; }
rec('page_header', [tx, y, mx, yy], b.name + '\n' + b.lines.join('\n'));
const tb = below ? text(b.title, x0, y + h - sz * 0.9 - sz * b._ts * 1.3, titleF, accent) : text(b.title, x1, y + (h - sz * 1.2) - sz * 2.2, titleF, accent, 'right');
rec('title', tb, b.title);
ctx.fillStyle = accent; ctx.fillRect(x0, y + h - sz * 0.6, x1 - x0, 3);
}
return h;
}
if (b.t === 'title') { const f = font(sz * 1.6, 'bold'); const h = sz * 1.6 * 1.6; if (draw) rec('title', text(b.text, x0, y, f, accent), b.text); return h; }
if (b.t === 'h') { const f = font(sz * 1.12, 'bold'); const h = sz * 1.12 * 1.9; if (draw) { const bb = text(b.text, x0, y + sz * 0.35, f, accent); rec('section_header', bb, b.text); } return h; }
if (b.t === 'p' || b.t === 'list') {
const f = font(sz); const segs = b.t === 'p' ? b.segs : b.items.map((it, i) => ({ text: (i ? '\n' : '') + it }));
let lines; if (b.t === 'list') { lines = []; b.items.forEach((it) => { const ls = wrap([{ text: it }], x1 - x0 - sz * 1.4, f); ls.forEach((l, i) => { l.bullet = i === 0; lines.push(l); }); }); } else lines = wrap(segs, x1 - x0, f);
const h = lines.length * sz * lh + sz * 0.7; if (!draw) return h;
if (b.t === 'list') { let cy = y; for (const l of lines) { if (l.bullet) text('•', x0 + sz * 0.3, cy, f, '#222'); drawLines([l], x0 + sz * 1.4, cy, f, '#222', sz); cy += sz * lh; } rec('list', [x0, y, x1, cy], blockText(b).text); }
else { const res = drawLines(lines, x0, y, f, '#222', sz); const bt = blockText(b); rec('text', [x0, y, Math.max(res.maxX, x0), y + res.h], bt.text, { spans: bt.spans }); res.piiBoxes.forEach((pb) => out.pii.push({ type: pb.pii, text: pb.text.trim(), bbox: pb.bbox.map(Math.round) })); }
return h;
}
if (b.t === 'kv') {
const form = doc.form; const cols = b.cols; const cw = (x1 - x0) / cols; const lf = font(sz * (form ? 0.72 : 0.92), form ? '' : 'bold'); const vf = font(sz);
// layout cells
const cells = []; let c = 0, row = 0; for (const it of b.items) { if (it.span && c > 0) { row++; c = 0; } cells.push({ it, row, col: c, span: it.span ? cols : 1 }); c += it.span ? cols : 1; if (c >= cols) { row++; c = 0; } }
const nrows = cells.length ? cells[cells.length - 1].row + 1 : 0; const rh = form ? sz * 3.0 : sz * lh * 1.05; const h = nrows * rh + sz * 0.6; if (!draw) return h;
let minY = y, maxY = y; const textOut = [];
for (const cl of cells) {
const cx = x0 + cl.col * cw; const cy = y + cl.row * rh; const w = cw * cl.span - sz * 0.8; const it = cl.it; let vb;
if (form) { text(it.label, cx, cy, lf, '#555'); ctx.strokeStyle = '#9aa1a9'; ctx.lineWidth = 1.2; if (r.bool(0.5)) ctx.strokeRect(cx, cy + sz * 0.95, w, sz * 1.7); else { ctx.beginPath(); ctx.moveTo(cx, cy + sz * 2.6); ctx.lineTo(cx + w, cy + sz * 2.6); ctx.stroke(); }
vb = (hand && it.hand) ? handText(it.value, cx + sz * 0.4, cy + sz * 1.05, sz, w - sz * 0.6) : fitText(it.value, cx + sz * 0.4, cy + sz * 1.2, w - sz * 0.6, sz, '#111'); }
else { const lb = text(it.label + ':', cx, cy, lf, '#333'); const vx = lb[2] + sz * 0.45; vb = fitText(it.value, vx, cy, cx + w - vx, sz, '#111'); }
out.fields.push({ key: it.key, label: it.label, value: it.value, bbox: vb.map(Math.round), handwritten: !!(hand && it.hand) });
if (it.pii) out.pii.push({ type: it.pii, text: it.value, bbox: vb.map(Math.round) });
maxY = Math.max(maxY, cy + rh); textOut.push(it.label + ': ' + it.value);
}
const kbt = blockText(b); rec('key_value', [x0, minY, x1, maxY], kbt.text, { spans: kbt.spans });
return h;
}
if (b.t === 'totals') {
const lf = font(sz, 'bold'); const vf = font(sz); const rh = sz * lh * 1.1; const h = b.items.length * rh + sz * 0.6; if (!draw) return h;
let cy = y; let minX = x1; const lines = [];
b.items.forEach((it, i) => { const last = i === b.items.length - 1; const vb = text(it.value, x1, cy, last ? lf : vf, '#111', 'right'); const lb = text(it.label, x1 - sz * 11, cy, lf, '#333', 'right'); minX = Math.min(minX, lb[0]); out.fields.push({ key: it.key, label: it.label, value: it.value, bbox: vb.map(Math.round), handwritten: false }); lines.push(it.label + ': ' + it.value); cy += rh; });
rec('key_value', [minX, y, x1, cy], lines.join('\n')); return h;
}
if (b.t === 'table') return drawTable(b, draw);
if (b.t === 'checks') {
const f = font(sz * 0.95); const bx = sz * 0.85; const lw = tw(b.label, font(sz * 0.95, 'bold'));
const optsW = b.options.map((o) => bx + sz * 0.5 + tw(o, f) + sz * 1.4); const total = optsW.reduce((a, c) => a + c, 0); const inline = lw + sz + total < x1 - x0; const h = (inline ? 1 : 2) * sz * lh * 1.15 + sz * 0.5; if (!draw) return h;
const lb = text(b.label, x0, y, font(sz * 0.95, 'bold'), '#222'); let cx = inline ? lb[2] + sz : x0; let cy = inline ? y : y + sz * lh * 1.15; const boxes = [];
b.options.forEach((o, i) => { ctx.strokeStyle = '#333'; ctx.lineWidth = 1.5; ctx.strokeRect(cx, cy + sz * 0.1, bx, bx); const on = b.checked.indexOf(o) >= 0; if (on) checkMark(cx, cy + sz * 0.1, bx); text(o, cx + bx + sz * 0.5, cy, f, '#222'); boxes.push({ option: o, checked: on, bbox: [cx, cy + sz * 0.1, cx + bx, cy + sz * 0.1 + bx].map(Math.round) }); cx += optsW[i]; });
out.checkboxes.push({ key: b.key, label: b.label, checked: b.checked.slice(), options: boxes, handwritten: !!hand });
rec('checkbox_group', [x0, y, Math.min(x1, cx), cy + sz * 1.2], blockText(b).text); return h;
}
if (b.t === 'sign') {
const n = b.parties.length; const cw = (x1 - x0) / Math.max(n, 2); const h = sz * 5.2; if (!draw) return h;
const texts = [];
b.parties.forEach((pp, i) => {
const cx = x0 + i * cw; const ly = y + sz * 3.0; const w = cw - sz * 2; const signed = opts.signatures !== false && r.bool(opts.signProb == null ? 0.85 : opts.signProb);
let sb = null; if (signed) { sb = scribble(cx + sz * 0.5, y + sz * 0.6, Math.min(w * 0.7, sz * 12), sz * 2.2, hand ? hand.color : r.pick([INKS.blue, INKS.black])); out.signatures.push({ signer: pp.name, label: pp.label, bbox: sb.map(Math.round) }); rec('signature_mark', sb, ''); }
ctx.strokeStyle = '#444'; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(cx, ly); ctx.lineTo(cx + w, ly); ctx.stroke();
text(pp.label, cx, ly + sz * 0.3, font(sz * 0.78), '#555'); const nb = text(pp.name + (pp.date ? ' Date: ' + pp.date : ''), cx, ly + sz * 1.25, font(sz * 0.85), '#222');
if (pp.pii) out.pii.push({ type: pp.pii, text: pp.name, bbox: [nb[0], nb[1], nb[0] + tw(pp.name, font(sz * 0.85)), nb[3]].map(Math.round) });
texts.push(pp.label + ': ' + pp.name + (pp.date ? ' Date: ' + pp.date : ''));
});
const sbt = blockText(b); rec('signature', [x0, y, x1, y + h - sz * 0.6], sbt.text, { spans: sbt.spans }); return h;
}
if (b.t === 'cols') return drawCols(b, draw);
return 0;
}
function fitText(t, x, yy, maxW, sz, color) { let s = sz; let f = font(s); let w = tw(t, f); if (w > maxW && maxW > 0) { s = Math.max(sz * 0.55, sz * maxW / w); f = font(s); } return text(t, x, yy, f, color); }
function checkMark(x, yy, s) {
ctx.save(); ctx.strokeStyle = hand ? hand.color : '#111'; ctx.lineWidth = hand ? 2.6 : 2; ctx.beginPath();
if (hand && r.bool(0.6)) { ctx.moveTo(x + s * 0.1 + r.float(-2, 2), yy + s * 0.55); ctx.lineTo(x + s * 0.42, yy + s * 0.92 + r.float(-2, 2)); ctx.lineTo(x + s * 1.15 + r.float(-3, 3), yy - s * 0.25 + r.float(-3, 3)); }
else { ctx.moveTo(x + s * 0.15, yy + s * 0.15); ctx.lineTo(x + s * 0.85 + (hand ? r.float(-2, 2) : 0), yy + s * 0.85); ctx.moveTo(x + s * 0.85, yy + s * 0.15); ctx.lineTo(x + s * 0.15, yy + s * 0.85 + (hand ? r.float(-2, 2) : 0)); }
ctx.stroke(); ctx.restore();
}
function scribble(x, yy, w, h, color) {
ctx.save(); ctx.strokeStyle = color; ctx.lineWidth = r.float(1.6, 3); ctx.lineCap = 'round'; ctx.beginPath(); let px = x, py = yy + h * 0.6; ctx.moveTo(px, py); let minX = x, maxX = x, minY = py, maxY = py;
const n = r.int(5, 9); for (let i = 0; i < n; i++) { const nx = x + w * (i + 1) / n + r.float(-w * 0.05, w * 0.05); const ny = yy + r.float(0.1, 0.95) * h; const c1x = px + r.float(-w * 0.15, w * 0.25), c1y = yy + r.float(-0.2, 1.2) * h; const c2x = nx + r.float(-w * 0.2, w * 0.1), c2y = yy + r.float(-0.2, 1.2) * h; ctx.bezierCurveTo(c1x, c1y, c2x, c2y, nx, ny); [c1x, c2x, nx].forEach((v) => { minX = Math.min(minX, v); maxX = Math.max(maxX, v); }); [c1y, c2y, ny].forEach((v) => { minY = Math.min(minY, v); maxY = Math.max(maxY, v); }); px = nx; py = ny; }
if (r.bool(0.6)) { ctx.moveTo(x - w * 0.05, yy + h * 0.95); ctx.quadraticCurveTo(x + w * 0.5, yy + h * 1.15, x + w * 1.05, yy + h * 0.8); maxY = Math.max(maxY, yy + h * 1.1); }
ctx.stroke(); ctx.restore(); return [Math.max(0, minX), Math.max(0, minY), Math.min(W, maxX), Math.min(H, maxY)];
}
const tableStyle = { grid: r.pick(['full', 'rows', 'zebra', 'header']), headBg: r.pick(['#e5e7eb', '#dbe4f0', accent, '#f3f4f6']) };
function drawTable(b, draw, maxH) {
const all = [b.head].concat(b.rows); const n = b.head.length; let sz = SZ * (opts.dense ? 1 : 0.95); const pad = sz * 0.5;
const natural = (s) => { const f = font(s), fb = font(s, 'bold'); return b.head.map((h, c) => Math.max(tw(h, fb), ...b.rows.map((rw) => tw(String(rw[c]), f))) + pad * 2); };
let ws = natural(sz); let tot = ws.reduce((a, c) => a + c, 0); const avail = x1 - x0; if (tot > avail) { sz = Math.max(SZ * 0.5, sz * avail / tot * 0.98); ws = natural(sz); tot = ws.reduce((a, c) => a + c, 0); }
const extra = (avail - tot) / n; ws = ws.map((w) => w + extra); const rh = sz * 1.75; const avail2 = bottom - y; let fitRows = b.rows.length; const need = (b.rows.length + 1) * rh + SZ * 0.8;
if (!draw) return need;
if (need > avail2) fitRows = Math.max(0, Math.floor((avail2 - SZ * 0.8) / rh) - 1);
const f = font(sz), fb = font(sz, 'bold'); const align = b.align || b.head.map((h, c) => (c > 0 && /^[-(]?[^a-z]*[0-9][0-9.,)%\s]*$/i.test(String(b.rows[0] ? b.rows[0][c] : '').replace(/^[A-Z]{0,3}\$|^[£€₹]|\s?[€]$|^AED /, '')) ? 'r' : 'l'));
let cy = y; const darkHead = tableStyle.headBg === accent;
ctx.fillStyle = tableStyle.headBg; ctx.fillRect(x0, cy, avail, rh);
const drawRow = (row, bold, color) => { let cx = x0; row.forEach((cell, c) => { const s = String(cell); if (align[c] === 'r') text(s, cx + ws[c] - pad, cy + (rh - sz * 1.2) / 2, bold ? fb : f, color, 'right'); else text(s, cx + pad, cy + (rh - sz * 1.2) / 2, bold ? fb : f, color); cx += ws[c]; }); };
drawRow(b.head, true, darkHead ? '#fff' : '#111'); cy += rh;
for (let i = 0; i < fitRows; i++) { if (tableStyle.grid === 'zebra' && i % 2 === 1) { ctx.fillStyle = '#f4f6f8'; ctx.fillRect(x0, cy, avail, rh); } const last = /^total/i.test(String(b.rows[i][0])); drawRow(b.rows[i], last, '#111'); cy += rh; if (tableStyle.grid !== 'header' && tableStyle.grid !== 'zebra') { ctx.strokeStyle = '#c7ccd1'; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(x0, cy); ctx.lineTo(x1, cy); ctx.stroke(); } }
ctx.strokeStyle = '#8b939b'; ctx.lineWidth = 1.2; ctx.strokeRect(x0, y, avail, cy - y); if (tableStyle.grid === 'full') { let cx = x0; for (let c = 0; c < n - 1; c++) { cx += ws[c]; ctx.beginPath(); ctx.moveTo(cx, y); ctx.lineTo(cx, cy); ctx.stroke(); } }
const rows = [b.head].concat(b.rows.slice(0, fitRows)); const tb = rec('table', [x0, y, x1, cy], blockText({ t: 'table', head: b.head, rows: b.rows.slice(0, fitRows) }).text, { table: rows, html: tableHTML(b.head, b.rows.slice(0, fitRows)), key: b.key });
out.tables[b.key] = { rows_rendered: fitRows, rows_total: b.rows.length, block: tb.id };
if (fitRows < b.rows.length) out.truncated = true;
return Math.min(need, cy - y + SZ * 0.8);
}
function drawCols(b, draw) {
const n = b.n; const gap = SZ * 1.2; const cw = (x1 - x0 - gap * (n - 1)) / n; const sz = SZ; const f = font(sz), fh = font(sz * 1.02, 'bold');
const items = []; b.sections.forEach((sec) => { if (sec.h) items.push({ h: true, lines: wrap([{ text: sec.h }], cw, fh), text: sec.h }); items.push({ h: false, lines: wrap(sec.segs, cw, f), text: sec.segs.map((x) => x.text).join('') }); });
const lineH = sz * lh; const totalLines = items.reduce((a, it) => a + it.lines.length + 0.5, 0); const colH = Math.min(bottom - y, Math.ceil(totalLines / n + 2) * lineH);
if (!draw) return Math.min(bottom - y, colH + SZ);
let col = 0, cy = y; for (const it of items) { let startY = cy, startCol = col; let buf = []; const flush = () => { if (!buf.length) return; const res = drawLines(buf, x0 + col * (cw + gap), startY, it.h ? fh : f, it.h ? accent : '#222', sz); rec(it.h ? 'section_header' : 'text', [x0 + col * (cw + gap), startY, x0 + col * (cw + gap) + cw, startY + res.h], buf.map((l) => l.pieces.map((p) => p.text).join('')).join(' ')); buf = []; };
for (const ln of it.lines) { if (cy + lineH > y + colH) { flush(); col++; cy = y; startY = y; if (col >= n) { out.truncated = true; return colH + SZ; } } buf.push(ln); cy += lineH; } flush(); cy += lineH * 0.5; }
return colH + SZ;
}
for (const b of blocks) {
if (out.truncated) break; const h = doBlock(b, false);
if (y + h > bottom) { if (b.t === 'table' && bottom - y > SZ * 6) { y += drawTable(b, true); } out.truncated = true; break; }
doBlock(b, true); y += h;
}
if (footer && opts.footer !== false) { const fb = text(footer.text, W / 2, H - M * 0.6 - SZ, font(SZ * 0.72), '#777', 'center'); rec('page_footer', fb, footer.text); const pn = 'Page 1 of 1'; const pb = text(pn, x1, H - M * 0.6 - SZ, font(SZ * 0.72), '#777', 'right'); if (pb[0] > fb[2] + 10) rec('page_number', pb, pn); else ctx.clearRect(0, 0, 0, 0); }
out.drawHand = (t, x, yy, sz) => { const keep = hand; if (!hand) { hand = opts.handStyle || handStyle(r); } const bb = handText(t, x, yy, sz || SZ); hand = keep; return bb.map(Math.round); };
out.freeSpace = () => { const occ = out.blocks.map((b) => b.bbox); return occ; };
out.canvas = cv; out.ctx = ctx; out.accent = accent; out.renderedKeys = {}; out.fields.forEach((f) => { out.renderedKeys[f.key] = true; });
return out;
}
function ocrFromRender(out) { const parts = out.blocks.filter((b) => b.text).map((b) => ({ text: b.text, spans: b.spans || [] })); return joinBlocks(parts); }
function markdownFromRender(out) { return out.blocks.map(blockMD).filter((x) => x).join('\n\n'); }
// ---------------------------------------------------------------- stamps
const STAMPS = [['PAID', 'rect'], ['RECEIVED', 'rect'], ['APPROVED', 'rect'], ['ENTERED', 'rect'], ['VERIFIED', 'oval'], ['COPY', 'rect'], ['CONFIDENTIAL', 'rect'], ['POSTED', 'rect'], ['FOR PAYMENT', 'rect'], ['DUPLICATE', 'rect'], ['CANCELLED', 'rect'], ['QC PASSED', 'oval'], ['SEAL', 'round']];
const STAMP_COLORS = { red: '#c1121f', blue: '#1d4ed8', purple: '#6b21a8', green: '#15803d', black: '#222222' };
function drawStamp(out, r, spec) {
const ctx = out.ctx; const sz = spec.size || 34; const color = STAMP_COLORS[spec.color]; let w, h; const lines = spec.lines;
const off = makeCanvas(10, 10, spec.opts); let octx = off.getContext('2d'); octx.font = 'bold ' + sz + 'px "' + (spec.font || 'Arial Black') + '"'; const mw = Math.max.apply(null, lines.map((l, i) => { octx.font = 'bold ' + Math.round(i ? sz * 0.55 : sz) + 'px "' + (spec.font || 'Arial') + '"'; return octx.measureText(l).width; }));
if (spec.kind === 'round') { w = h = Math.max(mw + sz * 1.5, sz * 6.2); } else { w = mw + sz * 1.4; h = sz * 1.6 + (lines.length - 1) * sz * 0.8; if (spec.kind === 'oval') { w *= 1.25; h *= 1.35; } }
off.width = Math.ceil(w + 10); off.height = Math.ceil(h + 10); octx = off.getContext('2d'); octx.translate(5, 5); octx.strokeStyle = color; octx.fillStyle = color; octx.textBaseline = 'middle'; octx.textAlign = 'center';
if (spec.kind === 'rect') { octx.lineWidth = sz * 0.13; octx.strokeRect(0, 0, w, h); if (r.bool(0.5)) { octx.lineWidth = sz * 0.05; octx.strokeRect(sz * 0.18, sz * 0.18, w - sz * 0.36, h - sz * 0.36); } }
else if (spec.kind === 'oval') { octx.lineWidth = sz * 0.12; octx.beginPath(); octx.ellipse(w / 2, h / 2, w / 2 - 2, h / 2 - 2, 0, 0, Math.PI * 2); octx.stroke(); }
else { octx.lineWidth = sz * 0.12; octx.beginPath(); octx.arc(w / 2, h / 2, w / 2 - 3, 0, Math.PI * 2); octx.stroke(); octx.lineWidth = sz * 0.05; octx.beginPath(); octx.arc(w / 2, h / 2, w / 2 - sz * 1.25, 0, Math.PI * 2); octx.stroke();
const ring = spec.ring.toUpperCase(); octx.font = 'bold ' + Math.round(sz * 0.5) + 'px Arial'; const rad = w / 2 - sz * 0.68; const step = (Math.PI * 1.7) / ring.length; for (let i = 0; i < ring.length; i++) { const a = -Math.PI * 0.85 + i * step - Math.PI / 2 + Math.PI * 0.15; octx.save(); octx.translate(w / 2 + Math.cos(a) * rad, h / 2 + Math.sin(a) * rad); octx.rotate(a + Math.PI / 2); octx.fillText(ring[i], 0, 0); octx.restore(); } }
lines.forEach((l, i) => { const s = i ? sz * 0.55 : sz * (spec.kind === 'round' ? 0.62 : 1); octx.font = 'bold ' + Math.round(s) + 'px "' + (spec.font || 'Arial') + '"'; const ty = spec.kind === 'round' ? h / 2 + (i - (lines.length - 1) / 2) * sz * 0.7 : (lines.length === 1 ? h / 2 : sz * 0.85 + i * sz * 0.8 - (i ? sz * 0.1 : 0)); octx.fillText(l, w / 2, ty); });
if (spec.handDate) { octx.font = Math.round(sz * 0.62) + 'px "' + spec.handDate.font + '"'; octx.fillStyle = spec.handDate.color; octx.fillText(spec.handDate.text, w / 2 + r.float(-8, 8), h - sz * 0.42 + r.float(-3, 3)); }
// ink texture: erase random specks
octx.globalCompositeOperation = 'destination-out'; const nsp = Math.floor(w * h / 60 * spec.wear); for (let i = 0; i < nsp; i++) { octx.globalAlpha = r.float(0.3, 1); octx.fillRect(r.float(-5, w + 5), r.float(-5, h + 5), r.float(1, 3.5), r.float(1, 3.5)); } octx.globalAlpha = 1; octx.globalCompositeOperation = 'source-over';
ctx.save(); ctx.globalAlpha = spec.alpha; ctx.globalCompositeOperation = 'multiply'; ctx.translate(spec.cx, spec.cy); ctx.rotate(spec.angle); ctx.drawImage(off, -off.width / 2, -off.height / 2); ctx.restore();
const c = Math.abs(Math.cos(spec.angle)), s = Math.abs(Math.sin(spec.angle)); const bw = off.width * c + off.height * s, bh = off.width * s + off.height * c;
return [spec.cx - bw / 2, spec.cy - bh / 2, spec.cx + bw / 2, spec.cy + bh / 2].map(Math.round);
}
function overlap(a, b) { const ix = Math.max(0, Math.min(a[2], b[2]) - Math.max(a[0], b[0])); const iy = Math.max(0, Math.min(a[3], b[3]) - Math.max(a[1], b[1])); return ix * iy; }
function addStamps(out, r, n, opts) {
const res = []; const d = new Date(Date.UTC(2025, r.int(0, 11), r.int(1, 28))); opts = opts || {};
for (let i = 0; i < n; i++) {
const st = r.pick(STAMPS); const color = r.pick(['red', 'red', 'blue', 'blue', 'purple', 'green', 'black']); const dt = pad(d.getUTCDate(), 2) + ' ' + MON[d.getUTCMonth()].toUpperCase() + ' ' + d.getUTCFullYear();
let lines = [st[0]]; let ring = null; let handDate = null;
if (st[1] === 'round') { ring = r.pick(PRE) + ' ' + r.pick(IND.buyer) + ' * ' + r.pick(['ACCOUNTS', 'FINANCE', 'STORES', 'QUALITY']) + ' *'; lines = [r.pick(['APPROVED', 'AUTHORISED', 'OFFICIAL']), dt]; }
else if (/RECEIVED|PAID|ENTERED|POSTED/.test(st[0])) { if (r.bool(0.5)) lines.push(dt); else if (opts.hand !== false) { lines.push(' '); handDate = { text: fmtDate(d, r.pick(['eu', 'us', 'short'])), font: r.pick(HAND_FONTS), color: INKS[r.pick(['blue', 'black'])] }; } if (r.bool(0.3)) lines.push('BY: ________'); }
const sz = r.int(26, 46) * (out.width / 1240); const cx = r.float(out.width * 0.2, out.width * 0.8), cy = r.float(out.height * 0.15, out.height * 0.85);
const ang = r.float(-0.45, 0.45); const bbox = drawStamp(out, r, { kind: st[1], lines, ring, color, size: sz, angle: ang, alpha: r.float(0.55, 0.9), wear: r.float(0.05, 0.6), cx, cy, handDate, opts, font: r.pick(['Arial', 'Helvetica', 'Courier New', 'Verdana']) });
const area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]); let ov = 0; const hit = []; out.blocks.forEach((b) => { if (b.label === 'logo' || b.label === 'stamp') return; const o = overlap(bbox, b.bbox); if (o > 0) { ov += o; hit.push(b.id); } });
const text = (ring ? ring.replace(/\s*\*\s*/g, ' ').trim() + ' ' : '') + lines.filter((l) => l.trim() && l.indexOf('____') < 0).join(' ') + (handDate ? ' ' + handDate.text : '');
const sb = { id: 'b' + out.blocks.length, order: out.blocks.length, label: 'stamp', bbox, text: text.trim() }; out.blocks.push(sb);
res.push({ type: st[0] === 'SEAL' ? 'seal' : st[0].toLowerCase().replace(/ /g, '_'), shape: st[1], text: text.trim(), color, bbox, rotation_deg: Math.round(ang * 1800 / Math.PI) / 10, overlaps_text: ov > 0, overlap_ratio: Math.round(Math.min(1, ov / area) * 1000) / 1000, overlapped_blocks: hit, handwritten_date: handDate ? handDate.text : null });
}
return res;
}
// ---------------------------------------------------------------- degradation (bad scans)
const LEVELS = { mild: { rot: 1.5, blur: 0.6, noise: 6, sp: 0.0005, scale: [0.75, 0.95], jpeg: [0.55, 0.8], contrast: [0.85, 1.0], shadow: 0.15, streak: 0.2, fold: 0.15, holes: 0.1, dust: 200 }, moderate: { rot: 4, blur: 1.2, noise: 14, sp: 0.002, scale: [0.5, 0.75], jpeg: [0.3, 0.55], contrast: [0.65, 0.9], shadow: 0.45, streak: 0.45, fold: 0.4, holes: 0.3, dust: 900 }, severe: { rot: 8, blur: 2.0, noise: 26, sp: 0.006, scale: [0.33, 0.55], jpeg: [0.12, 0.32], contrast: [0.45, 0.75], shadow: 0.8, streak: 0.7, fold: 0.6, holes: 0.5, dust: 2500 } };
function degrade(out, r, level, opts) {
const P = LEVELS[level]; const W = out.width, H = out.height; const src = out.canvas; const params = { level };
const sc = r.float(P.scale[0], P.scale[1]); params.downscale = Math.round(sc * 100) / 100; params.effective_dpi = Math.round(150 * sc);
const small = makeCanvas(Math.round(W * sc), Math.round(H * sc), opts); const sctx = small.getContext('2d'); sctx.imageSmoothingEnabled = true; sctx.drawImage(src, 0, 0, small.width, small.height);
const dst = makeCanvas(W, H, opts); const ctx = dst.getContext('2d'); const paper = r.pick(['#f7f4ec', '#f2f2f2', '#efe9da', '#fbfbf8', '#e9eef2']); ctx.fillStyle = paper; ctx.fillRect(0, 0, W, H); params.paper = paper;
const ang = r.float(-P.rot, P.rot) * Math.PI / 180; params.rotation_deg = Math.round(ang * 180 / Math.PI * 100) / 100;
const blur = Math.round(r.float(0, P.blur) * 100) / 100; const con = Math.round(r.float(P.contrast[0], P.contrast[1]) * 100) / 100; const bri = Math.round(r.float(0.95, 1.12) * 100) / 100; params.blur_px = blur; params.contrast = con; params.brightness = bri;
ctx.save(); ctx.filter = 'blur(' + blur + 'px) contrast(' + con + ') brightness(' + bri + ')'; ctx.translate(W / 2, H / 2); ctx.rotate(ang); ctx.globalCompositeOperation = 'multiply'; ctx.imageSmoothingEnabled = r.bool(0.6); ctx.drawImage(small, -W / 2, -H / 2, W, H); ctx.restore(); ctx.filter = 'none';
// shadow / uneven illumination
if (r.bool(P.shadow)) { const side = r.pick(['left', 'right', 'top', 'bottom', 'corner']); const g = side === 'corner' ? ctx.createRadialGradient(0, 0, 0, 0, 0, W * 0.9) : ctx.createLinearGradient(side === 'right' ? W : 0, side === 'bottom' ? H : 0, side === 'left' ? W * 0.35 : (side === 'right' ? W * 0.65 : 0), side === 'top' ? H * 0.3 : (side === 'bottom' ? H * 0.7 : 0)); const a = r.float(0.25, 0.6); g.addColorStop(0, 'rgba(60,55,50,' + a + ')'); g.addColorStop(1, 'rgba(60,55,50,0)'); ctx.save(); ctx.globalCompositeOperation = 'multiply'; ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); ctx.restore(); params.shadow = side; } else params.shadow = null;
if (r.bool(P.fold)) { const fy = r.float(H * 0.3, H * 0.7); const g = ctx.createLinearGradient(0, fy - 18, 0, fy + 18); g.addColorStop(0, 'rgba(0,0,0,0)'); g.addColorStop(0.5, 'rgba(0,0,0,0.18)'); g.addColorStop(0.55, 'rgba(255,255,255,0.25)'); g.addColorStop(1, 'rgba(0,0,0,0)'); ctx.fillStyle = g; ctx.fillRect(0, fy - 18, W, 36); params.fold_y = Math.round(fy); } else params.fold_y = null;
if (r.bool(P.holes)) { ctx.fillStyle = '#2a2a2a'; [0.25, 0.75].forEach((f) => { ctx.beginPath(); ctx.arc(45, H * f, 20, 0, Math.PI * 2); ctx.fill(); }); params.punch_holes = true; } else params.punch_holes = false;
// pixel pass: noise, salt & pepper, toner streaks
const im = ctx.getImageData(0, 0, W, H); const px = im.data; const sigma = r.float(P.noise * 0.4, P.noise); params.noise_sigma = Math.round(sigma * 10) / 10; const sp = P.sp * r.float(0.3, 1); params.salt_pepper = Math.round(sp * 10000) / 10000;
const streaks = []; if (r.bool(P.streak)) { const k = r.int(1, 4); for (let i = 0; i < k; i++) streaks.push([r.int(0, W - 40), r.int(6, 40), r.float(0.25, 0.7)]); } params.toner_streaks = streaks.length;
let g2 = 0; for (let i = 0; i < px.length; i += 4) { const x = (i / 4) % W; let n = 0; if (sigma > 0) { if ((i & 4) === 0) g2 = r.gauss(); n = g2 * sigma; } let lift = 0; for (const s of streaks) if (x >= s[0] && x < s[0] + s[1]) lift = Math.max(lift, s[2]); for (let c = 0; c < 3; c++) { let v = px[i + c] + n; if (lift) v = v + (255 - v) * lift; px[i + c] = v < 0 ? 0 : v > 255 ? 255 : v; } if (sp && r() < sp) { const v = r() < 0.5 ? 0 : 255; px[i] = px[i + 1] = px[i + 2] = v; } }
ctx.putImageData(im, 0, 0);
const dust = r.int(0, P.dust); ctx.fillStyle = 'rgba(30,30,30,0.7)'; for (let i = 0; i < dust; i++) { ctx.fillRect(r.float(0, W), r.float(0, H), r.float(0.8, 2.6), r.float(0.8, 2.6)); } params.dust_specks = dust;
params.jpeg_quality = Math.round(r.float(P.jpeg[0], P.jpeg[1]) * 100) / 100;
const ca = Math.cos(ang), sa = Math.sin(ang); const mapPt = (x, y) => [W / 2 + (x - W / 2) * ca - (y - H / 2) * sa, H / 2 + (x - W / 2) * sa + (y - H / 2) * ca];
const mapBox = (b) => { const pts = [mapPt(b[0], b[1]), mapPt(b[2], b[1]), mapPt(b[0], b[3]), mapPt(b[2], b[3])]; return [Math.min.apply(null, pts.map((p) => p[0])), Math.min.apply(null, pts.map((p) => p[1])), Math.max.apply(null, pts.map((p) => p[0])), Math.max.apply(null, pts.map((p) => p[1]))].map(Math.round); };
return { canvas: dst, params, mapBox };
}
// ---------------------------------------------------------------- pagination (for splitting)
function paginate(doc, r, capacity) {
// splits doc blocks into pages by estimated line count; long tables are split by rows
const est = (b) => { const t = blockText(b).text; return t.split('\n').length + (b.t === 'h' ? 1 : 0) + Math.floor(t.length / 95) + 1; };
const pages = []; let cur = []; let used = 0; const cap = capacity || 48;
for (const b of doc.blocks) {
if (b.t === 'footer') continue;
if (b.t === 'table' && b.rows.length + 2 > cap - used && b.rows.length > 6) { let rows = b.rows.slice(); while (rows.length) { const room = Math.max(4, cap - used - 2); const part = rows.slice(0, room); rows = rows.slice(room); cur.push(Object.assign({}, b, { rows: part })); used += part.length + 2; if (rows.length) { pages.push(cur); cur = [{ t: 'p', segs: [{ text: doc.title + ' (continued)' }] }]; used = 2; } } continue; }
const e = est(b); if (used + e > cap && cur.length) { pages.push(cur); cur = []; used = 0; if (r.bool(0.5)) { cur.push({ t: 'p', segs: [{ text: doc.title + ' - continued' }] }); used = 2; } }
cur.push(b); used += e;
}
if (cur.length) pages.push(cur);
const foot = doc.blocks.find((b) => b.t === 'footer');
return pages.map((blks, i) => { const withNo = r.bool(0.6); const f = (foot ? foot.text : '') + (withNo ? ' · Page ' + (i + 1) + ' of ' + pages.length : ''); return blks.concat(f.trim() ? [{ t: 'footer', text: f.replace(/^\s*·\s*/, '') }] : []); });
}
const API = { RNG, TYPES, CAT, BUILD, generate, toText, toHTML, blockText, render, ocrFromRender, markdownFromRender, addStamps, degrade, paginate, handStyle, HAND_FONTS, PRINT_FONTS, LEVELS, legalPara, locale, company, person, money, gold, fmtDate, iso, B, newDoc, schemaOf, kvi, S, tableHTML, pad };
if (typeof module !== 'undefined') module.exports = API; else root.DocGen = API;
})(typeof window !== 'undefined' ? window : this);
|