FrenchTaxService.kt

// EV Supervision Lite — built by Kevin Vavelin, Codetics
// https://codetics.fr
// Copyright (c) 2026 Kevin Vavelin, Codetics
// SPDX-License-Identifier: LicenseRef-Codetics-Attribution-1.0

package fr.codetics.ev_server.services.fiscal

import fr.codetics.ev_server.core.AppPrincipal
import fr.codetics.ev_server.core.Csv
import fr.codetics.ev_server.core.ensure
import fr.codetics.ev_server.core.msg
import fr.codetics.ev_server.models.entities.StationKey
import fr.codetics.ev_server.models.organization.CarData
import fr.codetics.ev_server.repositories.ConnectorRepository
import fr.codetics.ev_server.repositories.StationRepository
import fr.codetics.ev_server.services.fleet.ChargePlace
import fr.codetics.ev_server.services.fleet.FleetLedger
import fr.codetics.ev_server.services.fleet.Ledger
import fr.codetics.ev_server.services.fleet.LedgerRow
import fr.codetics.ev_server.services.fleet.Period
import fr.codetics.ev_server.services.organization.Entry
import java.math.BigDecimal
import java.math.RoundingMode
import java.time.LocalDate
import java.time.YearMonth
import java.util.UUID
import org.springframework.stereotype.Service
import tools.jackson.databind.PropertyNamingStrategies
import tools.jackson.databind.annotation.JsonNaming

/** Payroll lines of one employee: benefit in kind for workplace charging, and reimbursement of home charging. */
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
data class EmployeeTaxLine(
    val userId: UUID,
    val name: String,
    val email: String,
    val employeeNumber: String?,
    val costCenter: String?,
    val workplaceSessions: Int,
    val workplaceKwh: BigDecimal,
    /** Value of the electricity taken at work: the price of the sessions, else kWh × the reference price given. */
    val workplaceValue: BigDecimal,
    /** Benefit in kind to declare: zero while the workplace tolerance applies. */
    val workplaceBenefit: BigDecimal,
    val homeSessions: Int,
    val homeKwh: BigDecimal,
    /** kWh charged at home × the price of a kWh paid by the employee. */
    val homeReimbursement: BigDecimal,
    /** Share of the reimbursement free of contributions (justified costs of a company car). */
    val homeExempt: BigDecimal,
    /** Share to submit to contributions, or to split between business and private use. */
    val homeSubjectToContributions: BigDecimal,
    val companyCar: String?,
    /** Message keys explaining the rules applied, translated for the reader. */
    val notes: List<String>,
)

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
data class VehicleTaxLine(
    val vehicleId: UUID,
    val name: String,
    val licensePlate: String?,
    val energy: String,
    val usage: String?,
    val driverName: String?,
    val availableSince: LocalDate?,
    val ecoScoreEligible: Boolean?,
    val workplaceKwh: BigDecimal,
    val homeKwh: BigDecimal,
    val publicKwh: BigDecimal,
    /** Abatement on the flat-rate benefit in kind of the car, if it applies, and its yearly ceiling. */
    val abatementRate: BigDecimal?,
    val abatementCeiling: BigDecimal?,
    /** Whether the electricity paid by the employer counts in the car's benefit in kind. */
    val electricityInBenefit: Boolean,
    val notes: List<String>,
)

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
data class VatLine(
    val month: String,
    val sessions: Int,
    val energyKwh: BigDecimal,
    val amountIncludingVat: BigDecimal,
    val vatAmount: BigDecimal,
    val amountExcludingVat: BigDecimal,
)

/** Electricity delivered by one charging point open to the public in a quarter, for the TIRUERT/IRICC return. */
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
data class RenewableEnergyLine(
    val quarter: String,
    val stationId: String,
    val stationName: String,
    val connectorId: Int,
    val current: String,
    val sessions: Int,
    val energyKwh: BigDecimal,
    /** Sessions whose start and stop meter values were signed by the charging station. */
    val signedSessions: Int,
)

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
data class TaxObligation(val key: String, val title: String, val description: String, val deadline: String?, val source: String)

@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
data class FrenchTaxReport(
    val from: LocalDate,
    val to: LocalDate,
    val currency: String,
    val rules: FrenchTaxRules,
    val employees: List<EmployeeTaxLine>,
    val vehicles: List<VehicleTaxLine>,
    val vat: List<VatLine>,
    val renewableEnergy: List<RenewableEnergyLine>,
    val obligations: List<TaxObligation>,
    val disclaimer: String,
)

/**
 * Prepares the French declarations linked to charging: payroll (benefits in kind and reimbursements),
 * VAT collected on charging sold, and the electricity of public charging points for TIRUERT/IRICC.
 */
@Service
class FrenchTaxService(
    private val ledgers: FleetLedger,
    private val stations: StationRepository,
    private val connectors: ConnectorRepository,
) {
    fun report(user: AppPrincipal, period: Period, referencePriceKwh: BigDecimal? = null): FrenchTaxReport {
        ensure(referencePriceKwh == null || (referencePriceKwh.signum() >= 0 && referencePriceKwh <= BigDecimal(10))) {
            msg("fiscal.reference_price")
        }
        ensure(period.from.year == period.to.year) { msg("fiscal.single_year") }
        val rules = FrenchTaxRules.of(period.from.year)
        val ledger = ledgers.load(user, period)
        return FrenchTaxReport(
            period.from,
            period.to,
            ledger.currency,
            rules,
            employees(ledger, rules, referencePriceKwh),
            vehicles(ledger, rules),
            vat(ledger, rules),
            renewableEnergy(user, ledger),
            obligations(),
            msg("fiscal.disclaimer"),
        )
    }

    private fun employees(ledger: Ledger, rules: FrenchTaxRules, referencePrice: BigDecimal?): List<EmployeeTaxLine> {
        val zone = ledger.period.zone
        // Home charging belongs to the employee whose home it is, whoever's badge started it.
        val homeOwner = { row: LedgerRow -> row.transaction.siteId?.let { ledger.sites[it]?.data?.employeeHomeUserId } }
        val workplace = ledger.rows.filter { it.place == ChargePlace.WORKPLACE }.groupBy { it.userId }
        val home = ledger.rows.filter { it.place == ChargePlace.HOME }.groupBy { homeOwner(it) ?: it.userId }
        return ledger.visibleEmployees().mapNotNull { employee ->
            val atWork = workplace[employee.id].orEmpty()
            val atHome = home[employee.id].orEmpty()
            if (atWork.isEmpty() && atHome.isEmpty()) return@mapNotNull null
            val notes = linkedSetOf<String>()

            val workValue = atWork.sumOf { row -> row.transaction.price ?: referencePrice?.let { row.energyKwh * it } ?: BigDecimal.ZERO }
            if (atWork.any { it.transaction.price == null } && referencePrice == null) notes += "fiscal.note.workplace_unvalued"
            val taxableWork =
                atWork.filter { it.transaction.startedAt.atZone(zone).toLocalDate().isAfter(rules.workplaceChargingExemptUntil) }
            val workBenefit =
                taxableWork.sumOf { row -> row.transaction.price ?: referencePrice?.let { row.energyKwh * it } ?: BigDecimal.ZERO }
            if (atWork.isNotEmpty()) {
                notes += if (taxableWork.isEmpty()) "fiscal.note.workplace_tolerance" else "fiscal.note.workplace_taxable"
            }

            val companyCar = ledger.cars.values.firstOrNull { it.data.companyCar() && it.data.userId == employee.id }
            var reimbursement = BigDecimal.ZERO
            var exempt = BigDecimal.ZERO
            atHome.forEach { row ->
                val site = row.transaction.siteId?.let(ledger.sites::get)
                val price = site?.data?.homeElectricityPriceKwh
                val amount = price?.let { row.energyKwh * it } ?: row.transaction.price ?: BigDecimal.ZERO
                if (price == null) notes += "fiscal.note.home_price_missing"
                reimbursement += amount
                val car = row.vehicleId?.let(ledger.cars::get) ?: companyCar
                val day = row.transaction.startedAt.atZone(zone).toLocalDate()
                when {
                    car == null || !car.data.companyCar() -> notes += "fiscal.note.home_personal_car"
                    car.data.energy == "PHEV" -> notes += "fiscal.note.home_phev_split"
                    day.isAfter(rules.companyCarElectricityExcludedUntil) -> notes += "fiscal.note.home_after_tolerance"
                    else -> {
                        exempt += amount
                        notes += "fiscal.note.home_company_car_exempt"
                    }
                }
            }
            EmployeeTaxLine(
                employee.id,
                employee.displayName,
                employee.email,
                employee.employeeNumber,
                employee.costCenter,
                atWork.size,
                kwh(atWork.sumOf { it.energyKwh }),
                money(workValue),
                money(workBenefit),
                atHome.size,
                kwh(atHome.sumOf { it.energyKwh }),
                money(reimbursement),
                money(exempt),
                money(reimbursement - exempt),
                companyCar?.name,
                notes.map(::msg),
            )
        }
    }

    private fun vehicles(ledger: Ledger, rules: FrenchTaxRules): List<VehicleTaxLine> {
        val byVehicle = ledger.rows.groupBy { it.vehicleId }
        return ledger.visibleCars().filter { it.data.companyCar() }.map { car ->
            val rows = byVehicle[car.id].orEmpty()
            val notes = mutableListOf<String>()
            val abatement = abatement(car, rules, notes)
            val electricityInBenefit =
                car.data.energy == "PHEV" || ledger.period.to.isAfter(rules.companyCarElectricityExcludedUntil)
            notes += if (electricityInBenefit) "fiscal.note.vehicle_electricity_counted" else "fiscal.note.vehicle_electricity_excluded"
            VehicleTaxLine(
                car.id,
                car.name,
                car.data.licensePlate,
                car.data.energy,
                car.data.usage,
                car.data.userId?.let { ledger.employees[it]?.displayName },
                car.data.availableSince,
                car.data.ecoScoreEligible,
                kwh(rows.filter { it.place == ChargePlace.WORKPLACE }.sumOf { it.energyKwh }),
                kwh(rows.filter { it.place == ChargePlace.HOME }.sumOf { it.energyKwh }),
                kwh(rows.filter { it.place == ChargePlace.PUBLIC }.sumOf { it.energyKwh }),
                abatement?.let { rules.electricCarAbatementRate },
                abatement?.let { rules.electricCarAbatementCeiling },
                electricityInBenefit,
                notes.map(::msg),
            )
        }
    }

    /** The 70 % abatement: 100 % electric cars only; since February 2025, only models meeting the eco-score. */
    private fun abatement(car: Entry<CarData>, rules: FrenchTaxRules, notes: MutableList<String>): Boolean? {
        if (car.data.usage != "FUNCTION") {
            notes += "fiscal.note.vehicle_no_private_use"
            return null
        }
        if (car.data.energy != "BEV") {
            notes += "fiscal.note.vehicle_phev_no_abatement"
            return null
        }
        val since = car.data.availableSince
        if (since == null) {
            notes += "fiscal.note.vehicle_date_missing"
            return null
        }
        if (!since.isBefore(rules.ecoScoreRequiredSince) && car.data.ecoScoreEligible != true) {
            notes += if (car.data.ecoScoreEligible == false) "fiscal.note.vehicle_eco_score_failed" else "fiscal.note.vehicle_eco_score_unknown"
            return null
        }
        notes += "fiscal.note.vehicle_abatement"
        return true
    }

    /** VAT collected on charging sold; prices of sessions include VAT (prices shown to consumers in France). */
    private fun vat(ledger: Ledger, rules: FrenchTaxRules): List<VatLine> {
        val zone = ledger.period.zone
        val priced = ledger.rows.filter { it.transaction.price != null && (it.transaction.currency ?: ledger.currency) == ledger.currency }
        return generateSequence(YearMonth.from(ledger.period.from)) { it.plusMonths(1) }
            .takeWhile { !it.isAfter(YearMonth.from(ledger.period.to)) }
            .map { month ->
                val rows = priced.filter { YearMonth.from(it.transaction.startedAt.atZone(zone)) == month }
                val gross = money(rows.sumOf { it.cost })
                val net = gross.divide(BigDecimal.ONE + rules.vatRate, 2, RoundingMode.HALF_UP)
                VatLine(month.toString(), rows.size, kwh(rows.sumOf { it.energyKwh }), gross, gross - net, net)
            }
            .toList()
    }

    private fun renewableEnergy(user: AppPrincipal, ledger: Ledger): List<RenewableEnergyLine> {
        val stationCache = mutableMapOf<String, Pair<String, Boolean>>()
        val connectorTypes =
            connectors.findAllByKeyTenantId(user.tenantId).associate { (it.key.stationId to it.key.connectorId) to it.type }
        val station = { id: String ->
            stationCache.getOrPut(id) {
                stations.findById(StationKey(user.tenantId, id)).map { it.name to it.publicStation }.orElse(id to false)
            }
        }
        return ledger.rows
            .filter { it.place == ChargePlace.PUBLIC || station(it.transaction.stationId).second }
            .groupBy {
                val date = it.transaction.startedAt.atZone(ledger.period.zone)
                Triple("${date.year}-T${(date.monthValue - 1) / 3 + 1}", it.transaction.stationId, it.transaction.connectorId)
            }
            .map { (key, rows) ->
                val (quarter, stationId, connectorId) = key
                RenewableEnergyLine(
                    quarter,
                    stationId,
                    station(stationId).first,
                    connectorId,
                    if (connectorTypes[stationId to connectorId] in DC_CONNECTORS) "DC" else "AC",
                    rows.size,
                    kwh(rows.sumOf { it.energyKwh }),
                    rows.count { it.transaction.signedMeterStart != null && it.transaction.signedMeterStop != null },
                )
            }
            .sortedWith(compareBy({ it.quarter }, { it.stationId }, { it.connectorId }))
    }

    private fun obligations() =
        listOf(
            TaxObligation(
                "dsn",
                msg("fiscal.obligation.dsn.title"),
                msg("fiscal.obligation.dsn.description"),
                msg("fiscal.obligation.dsn.deadline"),
                FrenchTaxRules.SOURCES[0].url,
            ),
            TaxObligation(
                "vat",
                msg("fiscal.obligation.vat.title"),
                msg("fiscal.obligation.vat.description"),
                null,
                FrenchTaxRules.SOURCES[4].url,
            ),
            TaxObligation(
                "iricc",
                msg("fiscal.obligation.iricc.title"),
                msg("fiscal.obligation.iricc.description"),
                msg("fiscal.obligation.iricc.deadline"),
                FrenchTaxRules.SOURCES[5].url,
            ),
            TaxObligation(
                "einvoicing",
                msg("fiscal.obligation.einvoicing.title"),
                msg("fiscal.obligation.einvoicing.description"),
                "2027-09-01",
                FrenchTaxRules.SOURCES[6].url,
            ),
        )

    fun payrollExport(user: AppPrincipal, period: Period, referencePriceKwh: BigDecimal?) =
        report(user, period, referencePriceKwh).let { report ->
            Csv.download(
                "paie-recharge-${period.from}-${period.to}",
                listOf(
                    "matricule", "salarie", "email", "centre_de_cout", "debut", "fin", "recharge_travail_kwh",
                    "recharge_travail_valeur", "avantage_en_nature", "recharge_domicile_kwh", "remboursement_domicile",
                    "remboursement_exonere", "remboursement_soumis", "vehicule_de_fonction", "regles",
                ),
                report.employees.asSequence().map {
                    listOf(
                        it.employeeNumber, it.name, it.email, it.costCenter, report.from, report.to, it.workplaceKwh,
                        it.workplaceValue, it.workplaceBenefit, it.homeKwh, it.homeReimbursement, it.homeExempt,
                        it.homeSubjectToContributions, it.companyCar, it.notes.joinToString(" | "),
                    )
                },
            )
        }

    fun vatExport(user: AppPrincipal, period: Period) =
        report(user, period).let { report ->
            Csv.download(
                "tva-recharge-${period.from}-${period.to}",
                listOf("mois", "sessions", "energie_kwh", "montant_ttc", "tva", "montant_ht", "taux_tva"),
                report.vat.asSequence().map {
                    listOf(it.month, it.sessions, it.energyKwh, it.amountIncludingVat, it.vatAmount, it.amountExcludingVat, report.rules.vatRate)
                },
            )
        }

    fun renewableEnergyExport(user: AppPrincipal, period: Period) =
        report(user, period).let { report ->
            Csv.download(
                "electricite-points-publics-${period.from}-${period.to}",
                listOf("trimestre", "borne", "nom", "point", "courant", "sessions", "energie_kwh", "sessions_signees"),
                report.renewableEnergy.asSequence().map {
                    listOf(it.quarter, it.stationId, it.stationName, it.connectorId, it.current, it.sessions, it.energyKwh, it.signedSessions)
                },
            )
        }

    private fun kwh(value: BigDecimal) = value.setScale(3, RoundingMode.HALF_UP)

    private fun money(value: BigDecimal) = value.setScale(2, RoundingMode.HALF_UP)

    private companion object {
        val DC_CONNECTORS = setOf("CCS", "CHAdeMO")
    }
}