diagram.services.tsx 2,04 ko
Newer Older
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
}