Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
export interface RegionDistribution {
region: string
total_amount: number
percentage: number
otherRegions?: string[]
}
export async function getRegionDistribution(taxType: string, year: number): Promise<RegionDistribution[]> {
const params = new URLSearchParams({
tax_type: taxType,
year: String(year),
})
const res = await fetch(`/api/regions/distribution?${params}`)
if (!res.ok) throw new Error('Erreur lors du chargement de la distribution régionale')
const data = await res.json()
// S'assurer que les montants sont des nombres
const normalized = data.data.map((item: any) => ({
region: item.region,
total_amount: parseFloat(item.total_amount) || 0,
percentage: parseFloat(item.percentage) || 0,
}))
return normalized
}
export function prepareChartData(data: RegionDistribution[], topCount: number = 9): RegionDistribution[] {
// Trier par montant décroissant
const sorted = [...data].sort((a, b) => b.total_amount - a.total_amount)
// Calculer le total pour les pourcentages
const totalAmount = sorted.reduce((sum, item) => sum + item.total_amount, 0)
// Garder les N premières régions et recalculer les pourcentages
const topN: RegionDistribution[] = sorted.slice(0, topCount).map(item => ({
region: item.region,
total_amount: item.total_amount,
percentage: totalAmount > 0 ? (item.total_amount / totalAmount) * 100 : 0,
}))
// Regrouper les autres
const others = sorted.slice(topCount)
const othersTotal = others.reduce((sum, item) => sum + item.total_amount, 0)
const othersPercentage = totalAmount > 0 ? (othersTotal / totalAmount) * 100 : 0
// Créer le tableau final avec "Autres" si nécessaire
const result: RegionDistribution[] = [...topN]
if (others.length > 0) {
result.push({
region: 'Autres',
total_amount: othersTotal,
percentage: othersPercentage,
otherRegions: others.map(item => item.region),
})
}
return result
}