refactor(patient): extract age calculation logic to shared utility

Move age calculation logic from multiple components to a shared utility function in person model
Add age display to patient entry form and update preview component to use shared utility
Remove redundant age field from select-dob component
This commit is contained in:
Khafid Prayoga
2025-12-10 09:49:30 +07:00
parent e3680d183e
commit 9918501f29
4 changed files with 75 additions and 82 deletions

No files matched your search

+43
View File
@@ -1,3 +1,5 @@
import { differenceInDays, differenceInMonths, differenceInYears, parseISO } from 'date-fns'
import { type Base, genBase } from './_base'
import type { PersonAddress } from './person-address'
import type { PersonContact } from './person-contact'
@@ -56,3 +58,44 @@ export function parseName(person: Person): string {
return fullName
}
export function calculateAge(birthDate: string | Date | undefined): string {
if (!birthDate) {
return 'Masukkan tanggal lahir'
}
try {
let dateObj: Date
if (typeof birthDate === 'string') {
dateObj = parseISO(birthDate)
} else {
dateObj = birthDate
}
const today = new Date()
// Calculate years, months, and days
const totalYears = differenceInYears(today, dateObj)
// Calculate remaining months after years
const yearsPassed = new Date(dateObj)
yearsPassed.setFullYear(yearsPassed.getFullYear() + totalYears)
const remainingMonths = differenceInMonths(today, yearsPassed)
// Calculate remaining days after years and months
const monthsPassed = new Date(yearsPassed)
monthsPassed.setMonth(monthsPassed.getMonth() + remainingMonths)
const remainingDays = differenceInDays(today, monthsPassed)
// Format the result
const parts = []
if (totalYears > 0) parts.push(`${totalYears} Tahun`)
if (remainingMonths > 0) parts.push(`${remainingMonths} Bulan`)
if (remainingDays > 0) parts.push(`${remainingDays} Hari`)
return parts.length > 0 ? parts.join(' ') : '0 Hari'
} catch {
return 'Masukkan tanggal lahir'
}
}