Komparli
Tunisian credit and insurance comparator where every figure cites its official source.
- Fintech
- Web products
- Role
- Founder and sole engineer
- Client
- Own product
- Timeline
- Jun - Aug 2026
- Status
- Live in productionkomparli.vercel.app
Recorded on the live site: ranked offers with every rate sourced, the Arabic right-to-left version, borrowing capacity by term and the insurer table.
- Vitest tests across 42 files
- 388
- Vitest tests across 42 files
- banks, each rate quoted from its official tariff PDF
- 11
- banks, each rate quoted from its official tariff PDF
- commits in 8 weeks, 8 merged PRs
- 169
- commits in 8 weeks, 8 merged PRs
- pairwise data corruptions brute-forced against the insurer dataset
- 253
- pairwise data corruptions brute-forced against the insurer dataset
- motor tariff cells verified by OCR of the circular
- 26 / 26
- motor tariff cells verified by OCR of the circular
The problem
Tunisian consumers have no working way to compare loans across banks. Banks do publish their lending margins, but only inside dense, central-bank-mandated tariff PDFs, not on their product pages, and the one self-styled comparator appears dormant.
The law narrows the design: lending without a licence is a crime, prospect lists are restricted by the data-protection law, and routing insurance leads is brokerage. The product had to be useful, legally clean (a publisher with consented lead routing) and credible: no number shown as fact unless it is sourced and dated.
Architecture
Sources become typed data
Bank tariff PDFs, the FTUSA market report and the CGA circular are read by hand-run scripts (pdftotext word boxes, tesseract OCR) and committed as typed TypeScript, each figure with its source URL and date.
- Service
- Data
- AI model
- External
Hard problems I solved
A rotated PDF table that misreads by exactly 1e9
The per-insurer table in the FTUSA 2024 report is printed rotated. A flattened pdftotext dump glued a footnote marker '1' to one insurer's motor premiums: 1,197,006,533 instead of 197,006,533, which would have published a 79% motor market share instead of 13%.
Approach. scripts/extract-ftusa.py rebuilds the table from word bounding boxes using measured gaps: 1.71-3.42 pt is a thousands separator, 4.58 pt or more is a new cell, about 0 is a footnote marker. The two pages sort insurers differently, so the emitter joins by name with an alias table, never by position, and the script exits if an unexplained marker appears.
The live table shows the correct 13.0% share for that insurer.
Sum checks that a row swap defeats
Row sums, column sums and grand totals still balance when two insurers' rows are swapped. Brute-forcing all 253 pairwise corruptions, 92 claim mis-joins and 91 row swaps passed every sum gate, including two adjacent rows where a swap moves one insurer's fire loss ratio from 0.3% to 46.0%.
Approach. Gate 5b pins every insurer name to its own two published totals, read independently from the printed TOTAL columns, so any swap or mis-join fails the test.
All 183 corruptions that passed the sum gates are now caught.
Primary source over summary: a tenfold tariff error
The first motor engine was built from a public summary that charges heavy goods vehicles '4 DT per quintal' above 3.5 t, on total weight. The CGA circular itself says 4 per tonne of payload for third-party carriage: the summary billed ten times the surcharge, on the wrong basis for 2 of 3 usages.
Approach. Found the regulator's circulars index, OCR'd the scanned circular (its embedded text layer was corrupt, with non-monotonic values) and re-verified all 26 tariff cells. The Arabic circular 1/2018 was OCR-read to confirm it covers border insurance and does not replace the tariff. Until then a TARIFF_CURRENCY_CONFIRMED flag kept the page out of the sitemap, the navigation and search indexes, in code.
A third-party haulier with 10.5 t of payload is now quoted 250 DT + 28 DT (278 DT live), and a test pins the summary's error so nobody 'fixes' the engine back.
Honest prices from partial bank data
Banks publish a margin over the money-market rate, sometimes only a maximum, and one bank's latest tariff dates from 2021. The legal TEG folds fees into the rate and has no closed form.
Approach. rate = TMM + margin + bounded adjustment, clamped to [TMM, usury ceiling], with rateConfidence, marginIsCeiling and feeConfidence on every figure and rendered as published, estimated or ceiling. TEG is solved by bisection on present value. A credibility audit then fixed a per-instalment commission misread as a 2.2% fee, downgraded the 2021 tariff to estimated, and renamed 'Éligible' to 'A priori éligible'.
Regulation and bank rules that compose
Central-bank circular 2016-02 caps car-loan financing by fiscal horsepower (80 / 60 / 30%) and term (84 months), and a bank may only tighten it. A structural type guard silently exempted banks that publish no auto terms from every auto check.
Approach. Effective cap = min(regulation, bank) and minimum down payment = max(bank floor, 100 - cap), with the UI showing which one binds. The type guard was deleted so the regulation applies to every bank, and car loans use the 12.46% medium-term usury ceiling, not the 13.90% consumer one, because Tunisian banks book them as medium-term equipment credit.
Two engines that can never disagree
The capacity page inverts the annuity; the results page computes it forward and rounds payments to the millime. A naive inverse can show a 'max' amount that the results page then flags as over the 40% ratio.
Approach. Budgets are floored to 3 decimals before the closed-form inversion, so a rounded payment can never exceed the true budget, and a salary-sweep parity test asserts both engines agree with no tolerance.
Code
The gap thresholds were measured on both source pages. A near-zero gap means the previous glyph is a footnote marker, which is exactly the '1' that turned 197 million into 1.197 billion in a flat text dump.
"""The tables are rotated 90 degrees: X is the row axis, Y the column axis, reading order
runs along DECREASING Y. Measured facts this relies on (verified across both pages):
* 1.71-1.72 gap -> thousands separator inside one number
* 3.42 gap -> still inside one number (wider tracking in some columns)
* >=4.58 gap -> a new cell
* ~0 gap -> the preceding glyph is NOT a digit group but a footnote marker.
"""
SEP_MAX = 4.0
MARKER_MAX = 0.6
def cells_of(row):
"""Digit groups -> numbers, honouring separators, markers and both minus encodings."""
...
for w in toks:
...
gap = cur["ymin"] - w["ymax"]
if gap < MARKER_MAX:
markers.append(cur["d"])
cur = {"d": digits, "ymin": w["ymin"], "neg": neg or pending_neg}
elif gap <= SEP_MAX and not neg:
cur = {"d": cur["d"] + digits, "ymin": w["ymin"], "neg": cur["neg"]}
else:
out.append(cur)
cur = {"d": digits, "ymin": w["ymin"], "neg": neg or pending_neg}
pending_neg = False/**
* Above 3.5 t, per Circulaire n°1/2017 art. « Barème », verified against the primary
* source (both its embedded text and an independent OCR pass of the scan):
*
* propre compte : « 21 pour chaque tonne supplémentaire dont le POIDS TOTAL dépasse 3,5 t »
* compte d'autrui: « 4 pour chaque tonne supplémentaire dont la CHARGE UTILE dépasse 3,5 t »
* agricole : « 13 pour chaque tonne supplémentaire dont la CHARGE UTILE dépasse 3,5 t »
*
* CORRECTION: the BCT/OIF summary states "4 DT sur chaque QUINTAL supplémentaire" for
* third-party carriage and gives "poids total" as the basis for all three. Both are wrong
* against the circular. Billing per quintal is 40 DT/tonne, a TENFOLD overcharge, and
* the measurement basis differs by category. The circular governs; the summary does not.
*/
export const HEAVY = {
marchandisesPropre: { base: 257 as const, perTonne: 21, basis: 'poidsTotal' as const },
marchandisesAutrui: { base: 250 as const, perTonne: 4, basis: 'chargeUtile' as const },
agricole: { base: 'cvGrid' as const, perTonne: 13, basis: 'chargeUtile' as const },
} as const
// Set back to false if a later circular surfaces: the surface is withheld while it is false.
export const TARIFF_CURRENCY_CONFIRMED = true
// src/app/sitemap.ts
...(TARIFF_CURRENCY_CONFIRMED ? ['/assurance-auto'] : [])export function estimateRate(marginPct: number, input: SimulationInput, m: RateMarket = CONSUMER): number {
let adj = 0
if (input.termMonths > 24) adj += 0.3
else if (input.termMonths <= 12) adj -= 0.2
if (input.netMonthlySalary < 1000) adj += 0.4
else if (input.netMonthlySalary >= 3000) adj -= 0.3
if (input.employment === 'cdd') adj += 0.5
else if (input.employment === 'independant') adj += 0.7
adj = Math.max(-0.5, Math.min(1.5, adj))
const rate = m.tmmPct + marginPct + adj
return round3(Math.max(m.tmmPct, Math.min(rate, m.ceilingPct)))
}
export function computeTEG(amount: number, monthlyPayment: number, termMonths: number,
fileFees: number, m: RateMarket = CONSUMER): number {
const net = amount - fileFees
if (net <= 0 || monthlyPayment <= 0 || termMonths <= 0) return m.ceilingPct
const pv = (r: number) => (r === 0 ? monthlyPayment * termMonths
: (monthlyPayment * (1 - Math.pow(1 + r, -termMonths))) / r)
let lo = 0, hi = 1
for (let i = 0; i < 100; i++) { const mid = (lo + hi) / 2; if (pv(mid) > net) lo = mid; else hi = mid }
return Math.min(round3(((lo + hi) / 2) * 12 * 100), m.ceilingPct)
}What I built
Credit engine
- Rate = money-market rate (TMM) + bank margin + bounded profile adjustment, clamped to the usury ceiling
- TEG (APR) with file fees folded in, solved by 100-step bisection, money rounded to the millime
- Car-loan caps from central-bank circular 2016-02: 80 / 60 / 30% by fiscal horsepower, 84 months
- Borrowing capacity by closed-form inverse annuity, with a parity test against the results page
Sourced data
- 11 banks with a source URL, quoted line and verification date per product
- Every rate labelled published, estimated or published ceiling
- FTUSA insurer table rebuilt from word bounding boxes in a rotated PDF, behind 7 test gates
- Motor premium from CGA Circular 1/2017 and the 2019 bonus-malus decision
Bilingual product
- French and Arabic with <html dir> from the locale and an Arabic-capable font
- Derja for calls to action, Modern Standard Arabic for legal and financial terms
- FR / AR key-parity test and a Playwright test for the RTL switch
- Inputs in URL search params: shareable results, no client state store
Leads and admin
- Two-layer consent that names the recipient bank; version, locale and time stored
- Server action into Postgres through Prisma 7, operator email through Resend
- Admin with timing-safe login, HMAC-signed cookie and CSV export with a UTF-8 BOM for Arabic
- No lead capture on insurance pages, because routing them would be brokerage
Screens
The same results in French and Arabic: the layout mirrors right-to-left, figures stay in Western digits.
Insurer table rebuilt from a rotated PDF: 23 insurers x 9 branches from the FTUSA 2024 report.
Borrowing capacity by term: inverse annuity at the 40% and 32% debt-service ratios.
Mandatory motor premium for a third-party haulier: 250 DT base plus 4 DT per tonne of payload above 3.5 t.
Stack
Web
- Next.js 16 (App Router, RSC, server actions)
- React 19
- TypeScript
- Tailwind CSS 4
- next-intl 4 (FR + AR RTL)
Data
- Prisma 7 + adapter-pg
- PostgreSQL 16 (Neon)
- Zod 4 discriminated unions
Source tooling
- Python 3 (stdlib)
- pdftotext -bbox-layout
- tesseract OCR (fra, ara)
Quality
- Vitest 4
- Testing Library
- Playwright E2E
- Real Postgres test database
Ops
- Vercel (prod + branch previews)
- Resend
- Plausible
How it was built
Built solo in 8 weeks with an AI-native workflow: I wrote the specs and plans (6 design specs, 8 plans in the repo), Claude Code implemented them test-first with subagent reviews, and 128 of the 169 commits carry a Claude co-author trailer. The quality gates are mine: every bank figure verified by quoting the exact line from the official PDF, an adversarial review of the insurer data, and browser smoke tests. There is no AI in the product at runtime.