Open-source personal finance manager. Self-hosted, privacy-first.
fix(loans): open the schedule on the current installment (#1323)
Tássio Noronhaa84fec29180a
diff --git a/frontend/src/components/loan-schedule-card.test.tsx b/frontend/src/components/loan-schedule-card.test.tsxindex 7ebdfc3b..a7a2ba83 100644--- a/frontend/src/components/loan-schedule-card.test.tsx+++ b/frontend/src/components/loan-schedule-card.test.tsx@@ -1,5 +1,5 @@import { fireEvent, screen } from '@testing-library/react'-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { LoanScheduleCard } from '@/components/loan-schedule-card'import { formatCurrency } from '@/lib/format'@@ -56,6 +56,14 @@ const money = (value: number) => formatCurrency(value, 'EUR', 'en-US')describe('LoanScheduleCard', () => {beforeEach(() => loanSchedule.mockReset())+ // The layout test below stands in for jsdom's missing geometry on the+ // prototype, so put both back or it leaks into every later test.+ const clientHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientHeight')+ afterEach(() => {+ if (clientHeight) Object.defineProperty(HTMLElement.prototype, 'clientHeight', clientHeight)+ vi.restoreAllMocks()+ })+it('shows the next payment split and how far ahead the loan is', async () => {loanSchedule.mockResolvedValue(schedule())@@ -83,6 +91,36 @@ describe('LoanScheduleCard', () => {expect(await screen.findByText(t('loans.behind', { amount: money(300) }))).toBeInTheDocument()})+ it('marks the current installment so the table can scroll to it', async () => {+ loanSchedule.mockResolvedValue(schedule())+ renderWithProviders(<LoanScheduleCard {...props} />)++ fireEvent.click(await screen.findByText(t('loans.showSchedule')))++ const current = await screen.findByRole('row', { current: 'step' })+ // next_payment is installment 2, so the first row must not be the marked one.+ expect(current).toHaveTextContent('2')+ expect(screen.getAllByRole('row', { current: 'step' })).toHaveLength(1)+ })++ it('scrolls the table so the current installment is in view', async () => {+ // jsdom has no layout, so stand in for it: the table shows 384px at a time+ // and the current row sits 792px down, the way installment 24 of a+ // mortgage does.+ Object.defineProperty(HTMLElement.prototype, 'clientHeight', { configurable: true, value: 384 })+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {+ return { top: this.tagName === 'TR' ? 792 : 0 } as DOMRect+ })+ loanSchedule.mockResolvedValue(schedule())+ renderWithProviders(<LoanScheduleCard {...props} />)++ fireEvent.click(await screen.findByText(t('loans.showSchedule')))+ const container = (await screen.findByRole('row', { current: 'step' })).closest('div')!++ // Centred: 792 - 384 / 2. Without this the table opens on installment 1.+ expect(container.scrollTop).toBe(600)+ })+it('opens the full schedule on demand', async () => {loanSchedule.mockResolvedValue(schedule())@@ -128,3 +166,4 @@ describe('LoanScheduleCard', () => {expect(await screen.findByRole('button', { name: t('loans.adjustAction') })).toBeInTheDocument()})})+diff --git a/frontend/src/components/loan-schedule-card.tsx b/frontend/src/components/loan-schedule-card.tsxindex 950d833d..93a55b6a 100644--- a/frontend/src/components/loan-schedule-card.tsx+++ b/frontend/src/components/loan-schedule-card.tsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { useEffect, useRef, useState } from 'react'import { useQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'@@ -9,6 +9,15 @@ import { formatCurrency } from '@/lib/format'/** Below this difference from the contract, the loan reads as on schedule. */const ON_SCHEDULE_TOLERANCE = 1+/**+ * Where the schedule should sit so a row reads as the current installment:+ * roughly centred, which keeps the installments already paid visible above it.+ * Clamped at zero so an early installment leaves the table at its top.+ */+function scheduleScrollTop(rowOffset: number, viewportHeight: number): number {+ return Math.max(0, Math.round(rowOffset - viewportHeight / 2))+}+/*** A loan's contract next to its real balance: next payment, what is left,* payoff by the contract and at the current pace, and the full schedule.@@ -35,6 +44,20 @@ export function LoanScheduleCard({queryKey: ['accounts', accountId, 'loan-schedule'],queryFn: () => accounts.loanSchedule(accountId),})+ const scheduleRef = useRef<HTMLDivElement>(null)+ const currentRowRef = useRef<HTMLTableRowElement>(null)+ const currentNumber = data?.next_payment?.number++ // A long contract opens on installment 1, which on a mortgage is hundreds of+ // rows above where the borrower actually is. Put the current one in view.+ useEffect(() => {+ const container = scheduleRef.current+ const row = currentRowRef.current+ if (!showSchedule || !container || !row) return+ const offset = row.getBoundingClientRect().top - container.getBoundingClientRect().top + container.scrollTop+ container.scrollTop = scheduleScrollTop(offset, container.clientHeight)+ }, [showSchedule, currentNumber])+if (!data) return nullconst money = (value: number) => mask(formatCurrency(value, data.currency, locale))@@ -141,7 +164,7 @@ export function LoanScheduleCard({</button></div>{showSchedule && (- <div className="max-h-96 overflow-auto border-t border-border">+ <div ref={scheduleRef} className="max-h-96 overflow-auto border-t border-border"><table className="w-full text-xs tabular-nums"><thead className="sticky top-0 bg-card text-muted-foreground"><tr>@@ -157,7 +180,9 @@ export function LoanScheduleCard({{data.installments.map((row) => (<trkey={row.number}- className={`border-t border-border ${row.number === data.next_payment?.number ? 'bg-primary/5 font-medium' : ''}`}+ ref={row.number === currentNumber ? currentRowRef : undefined}+ aria-current={row.number === currentNumber ? 'step' : undefined}+ className={`border-t border-border ${row.number === currentNumber ? 'bg-primary/5 font-medium' : ''}`}><td className="px-4 py-2">{row.number}</td><td className="px-2 py-2">{day(row.due_date)}</td>