A mortgage application is a story with rules at every step
A mortgage is not a form to submit: it is a case that spans weeks and people (the applicant, the officer, the surveyor, whoever decides), and at every step the law demands something. The software of a mortgage lending platform therefore has three tasks that no framework solves on its own: preventing the case from making jumps it cannot make, computing precisely the money that changes hands, and meeting statutory deadlines that depend on how days are counted. This article takes one task at a time, with one executed listing for each.
A note on scope. This is not a description of a credit-granting system, nor is it legal advice: the regulatory references are quoted with the text I read and the date, and every domain rule that appears in the code (the thresholds, the rates) is an example parameter, not a risk policy. An institution's policy is its own, and it changes.
The state machine: whatever is not allowed is forbidden
The case has states (draft, review, survey, decision and so on) and the risk is that someone, or some
service, moves it into a state without passing through the others: an approved case without a survey, a
rejection that no person has seen. You avoid this with an explicit table of allowed transitions and a
single function that moves the case, muovi, which refuses the rest and records every step
with who did it and when.
type Stato = 'BOZZA' | 'ISTRUTTORIA' | 'PERIZIA' | 'DELIBERA' | 'APPROVATA' | 'RIFIUTATA' | 'EROGATA' | 'RITIRATA';
// Table of allowed transitions: whatever is not here is forbidden.
const AMMESSE: Record<Stato, Stato[]> = {
BOZZA: ['ISTRUTTORIA', 'RITIRATA'],
ISTRUTTORIA: ['PERIZIA', 'RITIRATA'],
PERIZIA: ['DELIBERA', 'RITIRATA'],
DELIBERA: ['APPROVATA', 'RIFIUTATA', 'RITIRATA'],
APPROVATA: ['EROGATA', 'RITIRATA'],
RIFIUTATA: [],
EROGATA: [],
RITIRATA: [],
};
interface Evento { da: Stato; a: Stato; chi: string; quando: string }
class Pratica {
private stato: Stato = 'BOZZA';
private meritoValutato = false;
readonly storico: Evento[] = [];
registraValutazioneMerito(): void { this.meritoValutato = true; }
muovi(a: Stato, chi: string, quando: string): void {
if (!AMMESSE[this.stato].includes(a)) {
throw new Error(`transizione vietata: ${this.stato} -> ${a}`);
}
// Domain rule: no positive decision without a creditworthiness assessment.
if (a === 'APPROVATA' && !this.meritoValutato) {
throw new Error('APPROVATA senza valutazione del merito creditizio registrata');
}
// Design choice: a negative outcome taken by an automated system is not final.
if (a === 'RIFIUTATA' && chi === 'sistema') {
throw new Error('RIFIUTATA richiede una persona: un esito negativo automatico va rivisto');
}
this.storico.push({ da: this.stato, a, chi, quando });
this.stato = a;
}
get corrente(): Stato { return this.stato; }
}
const p = new Pratica();
const tenta = (a: Stato, chi: string, quando: string) => {
try { p.muovi(a, chi, quando); console.log(`ok -> ${a}`); }
catch (e) { console.log(`errore -> ${(e as Error).message}`); }
};
tenta('ISTRUTTORIA', 'sistema', '2026-11-02');
tenta('DELIBERA', 'sistema', '2026-11-03'); // skips the survey
tenta('PERIZIA', 'operatore:rossi', '2026-11-04');
tenta('DELIBERA', 'sistema', '2026-11-06');
tenta('APPROVATA', 'sistema', '2026-11-06'); // creditworthiness not recorded
p.registraValutazioneMerito();
tenta('RIFIUTATA', 'sistema', '2026-11-06'); // automatic: not allowed
tenta('APPROVATA', 'operatore:rossi', '2026-11-07');
console.log('stato finale:', p.corrente, '| eventi registrati:', p.storico.length);
// Output:
// ok -> ISTRUTTORIA
// errore -> transizione vietata: ISTRUTTORIA -> DELIBERA
// ok -> PERIZIA
// ok -> DELIBERA
// errore -> APPROVATA senza valutazione del merito creditizio registrata
// errore -> RIFIUTATA richiede una persona: un esito negativo automatico va rivisto
// ok -> APPROVATA
// stato finale: APPROVATA | eventi registrati: 4
The AMMESSE table uses the right direction for reasoning: it lists what can be done, and
everything else is forbidden by absence. The output shows it at the second attempt, where the jump from
review to decision is rejected. The other two rules are inside muovi. The first requires that a
creditworthiness assessment be recorded before approval: Directive 2014/17/EU on credit agreements for
residential immovable property, in Article 18, requires the creditor to carry out a thorough assessment of
the consumer's creditworthiness before concluding the agreement, to document it, and not to base it
predominantly on the fact that the value of the property exceeds the credit. The second is a design choice
and not a legal obligation: a negative outcome decided by an automated system is not final, it must go
through a person.
The reason for the second rule lies in Regulation (EU) 2016/679, Article 22: the data subject has the right not to be subject to a decision based solely on automated processing which produces legal effects concerning them, and where an exception applies they must have at least the right to obtain human intervention, to express their point of view and to contest the decision. Writing the rule in the code rather than in the procedure has a concrete advantage: it cannot be violated by distraction. The cost is rigidity: if tomorrow an authority or your legal counsel indicates a different model, the rule is one line to change, and that is a good reason to keep it in a single place.
The amortisation schedule: compute in cents, not in euros
In a "French-style" mortgage the instalment is constant: in each instalment the interest share, computed on the outstanding debt, goes down, and the principal share goes up in proportion. The instalment formula is the standard annuity one: principal times the monthly rate, divided by one minus the inverse of the growth factor raised to the number of months. The practical problem is not the formula, it is the money: floating-point sums accumulate errors and 300 instalments rounded to the cent do not close the debt exactly at zero.
// French-style schedule: constant instalment, decreasing interest share. Computed in whole CENTS.
function piano(capitaleEuro: number, tanAnnuo: number, mesi: number) {
const capitale = Math.round(capitaleEuro * 100);
const i = tanAnnuo / 12;
const rata = Math.round((capitale * i) / (1 - Math.pow(1 + i, -mesi)));
let residuo = capitale;
const righe: { n: number; rata: number; interessi: number; quota: number; residuo: number }[] = [];
for (let n = 1; n <= mesi; n++) {
const interessi = Math.round(residuo * i);
// The last instalment closes the debt: it absorbs the accumulated rounding.
const quota = n === mesi ? residuo : rata - interessi;
const pagata = n === mesi ? quota + interessi : rata;
residuo -= quota;
righe.push({ n, rata: pagata, interessi, quota, residuo });
}
return { rata, righe };
}
const euro = (c: number) => (c / 100).toFixed(2);
const { rata, righe } = piano(150_000, 0.035, 300);
console.log('rata mensile:', euro(rata), 'euro');
for (const r of [righe[0], righe[1], righe[298], righe[299]]) {
console.log(`rata ${String(r.n).padStart(3)}: pagata=${euro(r.rata)} interessi=${euro(r.interessi)} quota capitale=${euro(r.quota)} residuo=${euro(r.residuo)}`);
}
const quote = righe.reduce((s, r) => s + r.quota, 0);
const totale = righe.reduce((s, r) => s + r.rata, 0);
console.log('somma quote capitale:', euro(quote), '| totale pagato:', euro(totale), '| interessi totali:', euro(totale - quote));
// Output:
// rata mensile: 750.94 euro
// rata 1: pagata=750.94 interessi=437.50 quota capitale=313.44 residuo=149686.56
// rata 2: pagata=750.94 interessi=436.59 quota capitale=314.35 residuo=149372.21
// rata 299: pagata=750.94 interessi=4.36 quota capitale=746.58 residuo=746.67
// rata 300: pagata=748.85 interessi=2.18 quota capitale=746.67 residuo=0.00
// somma quote capitale: 150000.00 | totale pagato: 225279.91 | interessi totali: 75279.91
The listing keeps the amounts as integers in cents and rounds only once, every month, the interest share. The last instalment acts as the closing one: its principal share is the entire outstanding balance, and the instalment paid absorbs the accumulated rounding difference. For 150,000 euros at 3.5% nominal annual rate over 300 months, the instalment is 750.94 euros, and the first instalment contains 437.50 euros of interest and 313.44 of principal; the last is 748.85, two euros less than the others, exactly the difference that would otherwise remain as debt. The sum of the principal shares is 150,000.00 (the check that the schedule closes) and total interest is 75,279.91. These are figures computed by the listing for these example parameters; they are not an offer and do not include fees, insurance or the APR (TAEG).
Statutory deadlines: which "business day"?
US mortgages, for those serving that market, have disclosure deadlines set in business days: the creditor must deliver or mail the Loan Estimate no later than the third business day after receiving the application (Regulation Z, 12 CFR 1026.19(e)(1)(iii)(A)). The code that computes the date is written in one line, until you read the definition. The regulation gives two: in general, a day on which the creditor's offices are open for substantially all of its business functions; for a list of provisions, including the seventh-day deadline before consummation (1026.19(e)(1)(iii)(B)), instead, all calendar days except Sundays and federal legal holidays (12 CFR 1026.2(a)(6)). Saturday counts in the second case and not in the first.
// Two definitions of "business day" in the same regulation (Reg. Z, 12 CFR 1026.2(a)(6)).
// (a) days on which the creditor's offices are open: here Monday-Friday, holidays excluded.
// (b) all days except Sundays and federal legal holidays.
const FESTIVI = new Set(['2026-11-26', '2026-12-25']); // Thanksgiving, Christmas
type Regola = 'uffici-aperti' | 'tutti-tranne-domeniche';
function conta(valido: (d: Date) => boolean, da: string, giorni: number): string {
const d = new Date(da + 'T12:00:00Z');
let fatti = 0;
while (fatti < giorni) {
d.setUTCDate(d.getUTCDate() + 1);
if (valido(d) && !FESTIVI.has(d.toISOString().slice(0, 10))) fatti++;
}
return d.toISOString().slice(0, 10);
}
const regole: Record<Regola, (d: Date) => boolean> = {
'uffici-aperti': (d) => d.getUTCDay() >= 1 && d.getUTCDay() <= 5,
'tutti-tranne-domeniche': (d) => d.getUTCDay() !== 0,
};
const domanda = '2026-11-24'; // Tuesday
for (const r of Object.keys(regole) as Regola[]) {
const scade = conta(regole[r], domanda, 3);
const giorno = ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'][new Date(scade + 'T12:00:00Z').getUTCDay()];
console.log(`${r.padEnd(24)} terzo giorno dopo ${domanda}: ${scade} (${giorno})`);
}
// Output:
// uffici-aperti terzo giorno dopo 2026-11-24: 2026-11-30 (lun)
// tutti-tranne-domeniche terzo giorno dopo 2026-11-24: 2026-11-28 (sab)
With an application received on Tuesday 24 November 2026 and Thanksgiving Day (Thursday 26) as a holiday,
the third business day is Monday 30 November if the offices work Monday to Friday, Saturday 28 if the broad
definition applies. Two days of difference on a statutory deadline is the kind of error discovered in an
inspection. The general lesson holds beyond the United States: a deadline is modelled as data (which
calendar, which holidays, which definition), not as a +3 scattered in the code. The listing
assumes the offices are open Monday to Friday; check this against your own organisation. For the other
rules of the same discipline, and for the reporting required by Regulation C (HMDA, whose stated purpose
includes identifying possible discriminatory lending patterns), it is best to start from the sources below
and from a consultant.
Where it intersects with the rest of the series
Credit is the point where automated property valuation meets people: how an estimate is measured before trusting it is in the article on valuation with machine learning, and how to prevent a model from penalising groups of people, and which obligations the AI Act links to creditworthiness assessment, is in the article on privacy and compliance. The archive of a case's steps, so that it cannot be rewritten, is covered in the same article.
What you can do now
You can model a case as a state machine with a single transition function, and you know why the table lists the permission and not the prohibition. You can compute an amortisation schedule in cents, close it at the last instalment and verify that the principal shares add up to the principal. You can treat a statutory deadline as data, with the calendar made explicit. What stays outside this article, and falls to whoever is responsible for the product, is the credit policy: debt thresholds, income verification, rates. They change by institution and are not copied from a blog.
In this series, the previous article is Smart Building IoT: MQTT, Modbus and Hysteresis Control and the next one is Real-Time Property Market Data Pipeline.
Sources
- Directive 2014/17/EU on credit agreements for consumers relating to residential immovable property, Article 18 - the obligation of a thorough creditworthiness assessment before the agreement, accessed on 2026-11-12
- Regulation (EU) 2016/679, Article 22 - the right not to be subject to a solely automated decision and the safeguards, including human intervention, accessed on 2026-11-12
- 12 CFR 1026.19, Certain mortgage and variable-rate transactions (Regulation Z) - the third-business-day deadline for the Loan Estimate, paragraph (e)(1)(iii), accessed on 2026-11-12
- 12 CFR 1026.2, Definitions and rules of construction - the two definitions of business day in paragraph (a)(6), accessed on 2026-11-12
- 12 CFR 1003.1, Authority, purpose, and scope (Regulation C, HMDA) - the stated purpose of mortgage data collection, accessed on 2026-11-12
The three listings were run with Node 24 on 2026-11-12. Amounts, rate and dates are invented examples; the regulatory quotations reflect the text read on the date indicated, and versions of the law change.

Commenti
Caricamento commenti...
Sign in to comment