|
| 1 | +import { Grant } from "../../../../middle-layer/types/Grant"; |
| 2 | + |
| 3 | +export type YearAmount = { |
| 4 | + year: number; |
| 5 | + [key: string]: number; |
| 6 | +}; |
| 7 | + |
| 8 | +/** |
| 9 | + * Aggregates total grant amounts by year, optionally grouped by a secondary key. |
| 10 | + * |
| 11 | + * @param grants - Array of grants. |
| 12 | + * @param groupBy - Optional secondary grouping key (e.g., "status" or "organization"). |
| 13 | + * @returns Array of { year, [groupValue]: amount }. |
| 14 | + */ |
| 15 | +export function aggregateMoneyGrantsByYear( |
| 16 | + grants: Grant[], |
| 17 | + groupBy?: keyof Grant |
| 18 | +): YearAmount[] { |
| 19 | + const grouped: Record<number, Record<string, number>> = {}; |
| 20 | + |
| 21 | + for (const grant of grants) { |
| 22 | + const year = new Date(grant.application_deadline).getUTCFullYear(); |
| 23 | + const groupValue = groupBy ? String(grant[groupBy] ?? "Unknown") : "All"; |
| 24 | + |
| 25 | + grouped[year] ??= {}; |
| 26 | + grouped[year][groupValue] = (grouped[year][groupValue] ?? 0) + grant.amount; |
| 27 | + } |
| 28 | + |
| 29 | + return Object.entries(grouped) |
| 30 | + .map(([year, groups]) => ({ |
| 31 | + year: Number(year), |
| 32 | + ...groups, |
| 33 | + })) |
| 34 | + .sort((a, b) => a.year - b.year); |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Aggregates distinct grant counts by year, optionally grouped by a secondary key. |
| 39 | + * |
| 40 | + * @param grants - Array of grants. |
| 41 | + * @param groupBy - Optional secondary grouping key (e.g., "status" or "organization"). |
| 42 | + * @returns Array of { year, [groupValue]: count }. |
| 43 | + */ |
| 44 | +export function aggregateCountGrantsByYear( |
| 45 | + grants: Grant[], |
| 46 | + groupBy?: keyof Grant |
| 47 | +): YearAmount[] { |
| 48 | + const grouped: Record<number, Record<string, Set<number>>> = {}; |
| 49 | + |
| 50 | + for (const grant of grants) { |
| 51 | + const year = new Date(grant.application_deadline).getUTCFullYear(); |
| 52 | + const groupValue = groupBy ? String(grant[groupBy] ?? "Unknown") : "All"; |
| 53 | + |
| 54 | + grouped[year] ??= {}; |
| 55 | + grouped[year][groupValue] ??= new Set<number>(); |
| 56 | + grouped[year][groupValue].add(grant.grantId); |
| 57 | + } |
| 58 | + |
| 59 | + return Object.entries(grouped) |
| 60 | + .map(([year, groups]) => { |
| 61 | + const counts: Record<string, number> = {}; |
| 62 | + for (const [key, ids] of Object.entries(groups)) { |
| 63 | + counts[key] = ids.size; |
| 64 | + } |
| 65 | + return { year: Number(year), ...counts }; |
| 66 | + }) |
| 67 | + .sort((a, b) => a.year - b.year); |
| 68 | +} |
0 commit comments