feat : modification de la gestion des jours fériés
All checks were successful
Auto Tag Develop / tag (push) Successful in 6s

This commit is contained in:
2026-04-16 15:52:19 +02:00
parent 13c71abddc
commit a8fe244b5c
42 changed files with 1752 additions and 167 deletions

View File

@@ -9,6 +9,9 @@ use DateTimeImmutable;
final readonly class EmployeeContractChangeRequest
{
/**
* @param null|array<int, int> $workDaysHours iso-day → minutes
*/
public function __construct(
public ?ContractNature $contractNature,
public ?DateTimeImmutable $contractStartDate,
@@ -16,6 +19,7 @@ final readonly class EmployeeContractChangeRequest
public ?bool $contractPaidLeaveSettled,
public ?string $contractComment,
public ?bool $isDriver = null,
public ?array $workDaysHours = null,
) {}
public function hasPeriodChangeRequest(): bool

View File

@@ -20,6 +20,7 @@ final class EmployeeContractChangeRequestFactory
contractPaidLeaveSettled: $employee->getContractPaidLeaveSettled(),
contractComment: $employee->getContractComment(),
isDriver: $employee->getIsDriverInput(),
workDaysHours: $employee->getWorkDaysHoursInput(),
);
}

View File

@@ -12,6 +12,9 @@ use DateTimeImmutable;
final class EmployeeContractPeriodBuilder
{
/**
* @param null|array<int, int> $workDaysHours iso-day → minutes
*/
public function build(
Employee $employee,
Contract $contract,
@@ -19,6 +22,7 @@ final class EmployeeContractPeriodBuilder
?DateTimeImmutable $endDate,
ContractNature $nature,
bool $isDriver = false,
?array $workDaysHours = null,
): EmployeeContractPeriod {
return new EmployeeContractPeriod()
->setEmployee($employee)
@@ -27,6 +31,7 @@ final class EmployeeContractPeriodBuilder
->setEndDate($endDate)
->setContractNature($nature)
->setIsDriver($isDriver)
->setWorkDaysHours($workDaysHours)
;
}
}

View File

@@ -29,15 +29,17 @@ final readonly class EmployeeContractPeriodManager implements EmployeeContractPe
?DateTimeImmutable $endDate,
ContractNature $nature,
bool $isDriver = false,
?array $workDaysHours = null,
): void {
$this->periodValidator->assertPeriodDates($startDate, $endDate, $nature);
$this->periodValidator->assertWorkDaysHours($contract, $nature, $workDaysHours);
$covered = $this->periodRepository->findOneCoveringDate($employee, $startDate);
if (null !== $covered) {
return;
}
$this->persistNewPeriod($employee, $contract, $startDate, $endDate, $nature, $isDriver);
$this->persistNewPeriod($employee, $contract, $startDate, $endDate, $nature, $isDriver, $workDaysHours);
$this->entityManager->flush();
}
@@ -75,8 +77,10 @@ final readonly class EmployeeContractPeriodManager implements EmployeeContractPe
ContractNature $nature,
?EmployeeContractPeriod $todayPeriod,
bool $isDriver = false,
?array $workDaysHours = null,
): void {
$this->periodValidator->assertPeriodDates($startDate, $endDate, $nature);
$this->periodValidator->assertWorkDaysHours($contract, $nature, $workDaysHours);
if (null !== $todayPeriod) {
$this->periodValidator->assertNextStartDateCompatible($startDate, $todayPeriod);
@@ -86,10 +90,13 @@ final readonly class EmployeeContractPeriodManager implements EmployeeContractPe
}
}
$this->persistNewPeriod($employee, $contract, $startDate, $endDate, $nature, $isDriver);
$this->persistNewPeriod($employee, $contract, $startDate, $endDate, $nature, $isDriver, $workDaysHours);
$this->entityManager->flush();
}
/**
* @param null|array<int, int> $workDaysHours
*/
private function persistNewPeriod(
Employee $employee,
Contract $contract,
@@ -97,8 +104,9 @@ final readonly class EmployeeContractPeriodManager implements EmployeeContractPe
?DateTimeImmutable $endDate,
ContractNature $nature,
bool $isDriver = false,
?array $workDaysHours = null,
): void {
$period = $this->periodBuilder->build($employee, $contract, $startDate, $endDate, $nature, $isDriver);
$period = $this->periodBuilder->build($employee, $contract, $startDate, $endDate, $nature, $isDriver, $workDaysHours);
$this->entityManager->persist($period);
}
}

View File

@@ -12,6 +12,9 @@ use DateTimeImmutable;
interface EmployeeContractPeriodManagerInterface
{
/**
* @param null|array<int, int> $workDaysHours iso-day → minutes
*/
public function ensureContractPeriodExists(
Employee $employee,
Contract $contract,
@@ -19,6 +22,7 @@ interface EmployeeContractPeriodManagerInterface
?DateTimeImmutable $endDate,
ContractNature $nature,
bool $isDriver = false,
?array $workDaysHours = null,
): void;
public function closeCurrentPeriod(
@@ -29,6 +33,9 @@ interface EmployeeContractPeriodManagerInterface
bool $isAlreadyEnded = false
): void;
/**
* @param null|array<int, int> $workDaysHours iso-day → minutes
*/
public function createNextPeriod(
Employee $employee,
Contract $contract,
@@ -37,5 +44,6 @@ interface EmployeeContractPeriodManagerInterface
ContractNature $nature,
?EmployeeContractPeriod $todayPeriod,
bool $isDriver = false,
?array $workDaysHours = null,
): void;
}

View File

@@ -4,8 +4,10 @@ declare(strict_types=1);
namespace App\Service\Contracts;
use App\Entity\Contract;
use App\Entity\EmployeeContractPeriod;
use App\Enum\ContractNature;
use App\Enum\TrackingMode;
use DateTimeImmutable;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
@@ -60,4 +62,63 @@ final class EmployeeContractPeriodValidator
throw new UnprocessableEntityHttpException('contractStartDate must be after current contract end date.');
}
}
/**
* Validates the per-period work schedule (`workDaysHours`) against the contract.
*
* Mandatory for non-standard TIME contracts (weeklyHours ∉ {35, 39}, non-INTERIM,
* non-Forfait). Forbidden on standard/forfait/interim contracts (ambiguity).
* When provided, sum of minutes MUST equal weeklyHours × 60.
*
* @param null|array<int, int> $workDaysHours
*/
public function assertWorkDaysHours(?Contract $contract, ContractNature $nature, ?array $workDaysHours): void
{
if (null === $contract) {
return;
}
$trackingMode = $contract->getTrackingMode();
$weeklyHours = $contract->getWeeklyHours();
$isStandard = 35 === $weeklyHours || 39 === $weeklyHours;
$isForfait = TrackingMode::PRESENCE->value === $trackingMode;
$isInterim = ContractNature::INTERIM === $nature;
if ($isForfait || $isInterim || $isStandard) {
if (null !== $workDaysHours && [] !== $workDaysHours) {
throw new UnprocessableEntityHttpException('workDaysHours must not be provided for Forfait, Interim or 35h/39h contracts.');
}
return;
}
if (null === $workDaysHours || [] === $workDaysHours) {
throw new UnprocessableEntityHttpException('workDaysHours is required for non-standard contracts.');
}
$totalMinutes = 0;
foreach ($workDaysHours as $isoDay => $minutes) {
if (!is_int($isoDay) && !(is_string($isoDay) && ctype_digit($isoDay))) {
throw new UnprocessableEntityHttpException('workDaysHours keys must be iso weekdays 1-5 (Mon-Fri) as integers.');
}
$iso = (int) $isoDay;
if ($iso < 1 || $iso > 5) {
throw new UnprocessableEntityHttpException('workDaysHours keys must be iso weekdays 1-5 (Mon-Fri).');
}
if (!is_int($minutes) || $minutes < 0) {
throw new UnprocessableEntityHttpException('workDaysHours values must be non-negative integer minutes.');
}
$totalMinutes += $minutes;
}
$expectedMinutes = ($weeklyHours ?? 0) * 60;
if ($totalMinutes !== $expectedMinutes) {
throw new UnprocessableEntityHttpException(sprintf(
'workDaysHours total must equal contract weekly hours: got %d min, expected %d min.',
$totalMinutes,
$expectedMinutes
));
}
}
}

View File

@@ -23,6 +23,20 @@ readonly class EmployeeContractResolver
return $period?->getContract();
}
/**
* @return null|array<int, int> workDaysHours (iso day → minutes) for the contract period active on $date
*/
public function resolveWorkDaysMinutesForEmployeeAndDate(Employee $employee, DateTimeImmutable $date): ?array
{
$period = $this->periodRepository->findOneCoveringDate($employee, $date);
$raw = $period?->getWorkDaysHours();
if (null === $raw) {
return null;
}
return $this->normalizeWorkDaysMinutes($raw);
}
public function resolveIsDriverForEmployeeAndDate(Employee $employee, DateTimeImmutable $date): bool
{
$period = $this->periodRepository->findOneCoveringDate($employee, $date);
@@ -84,6 +98,57 @@ readonly class EmployeeContractResolver
return $period?->getContractNatureEnum() ?? ContractNature::CDI;
}
/**
* @param list<Employee> $employees
* @param list<string> $days
*
* @return array<int, array<string, null|array<int, int>>>
*/
public function resolveWorkDaysMinutesForEmployeesAndDays(array $employees, array $days): array
{
$resolved = [];
if ([] === $employees || [] === $days) {
return $resolved;
}
foreach ($employees as $employee) {
$employeeId = $employee->getId();
if (!$employeeId) {
continue;
}
foreach ($days as $day) {
$resolved[$employeeId][$day] = null;
}
}
$from = new DateTimeImmutable(min($days));
$to = new DateTimeImmutable(max($days));
$periods = $this->periodRepository->findByEmployeesAndDateRange($employees, $from, $to);
foreach ($periods as $period) {
$employeeId = $period->getEmployee()?->getId();
if (!$employeeId) {
continue;
}
$raw = $period->getWorkDaysHours();
if (null === $raw) {
continue;
}
$normalized = $this->normalizeWorkDaysMinutes($raw);
$start = $period->getStartDate()->format('Y-m-d');
$end = $period->getEndDate()?->format('Y-m-d') ?? '9999-12-31';
foreach ($days as $day) {
if ($day < $start || $day > $end) {
continue;
}
$resolved[$employeeId][$day] = $normalized;
}
}
return $resolved;
}
/**
* @param list<Employee> $employees
* @param list<string> $days
@@ -177,4 +242,23 @@ readonly class EmployeeContractResolver
return $resolved;
}
/**
* @param array<int|string, mixed> $raw
*
* @return array<int, int>
*/
private function normalizeWorkDaysMinutes(array $raw): array
{
$result = [];
foreach ($raw as $key => $value) {
$iso = (int) $key;
if ($iso < 1 || $iso > 5) {
continue;
}
$result[$iso] = (int) $value;
}
return $result;
}
}

View File

@@ -16,6 +16,8 @@ use App\Repository\AbsenceRepository;
use App\Repository\WorkHourRepository;
use App\Service\Contracts\EmployeeContractResolver;
use App\Service\WorkHours\AbsenceSegmentsResolver;
use App\Service\WorkHours\DailyReferenceMinutesResolver;
use App\Service\WorkHours\HolidayVirtualHoursResolver;
use App\Service\WorkHours\WorkedHoursCreditPolicy;
use DateTimeImmutable;
@@ -29,6 +31,8 @@ final readonly class RttRecoveryComputationService
private AbsenceSegmentsResolver $absenceSegmentsResolver,
private WorkedHoursCreditPolicy $workedHoursCreditPolicy,
private EmployeeContractResolver $contractResolver,
private DailyReferenceMinutesResolver $dailyReferenceResolver,
private HolidayVirtualHoursResolver $holidayVirtualHoursResolver,
string $rttStartDate = '',
) {
$this->rttStartDate = '' !== $rttStartDate ? new DateTimeImmutable($rttStartDate) : null;
@@ -126,6 +130,7 @@ final readonly class RttRecoveryComputationService
$contractsByDate = $this->contractResolver->resolveForEmployeesAndDays([$employee], $days);
$naturesByDate = $this->contractResolver->resolveNaturesForEmployeesAndDays([$employee], $days);
$workDaysByDate = $this->contractResolver->resolveWorkDaysMinutesForEmployeesAndDays([$employee], $days);
$employeeId = (int) $employee->getId();
$workHours = $this->workHourRepository->findByDateRangeAndEmployees($periodFrom, $periodTo, [$employee]);
@@ -137,7 +142,8 @@ final readonly class RttRecoveryComputationService
$metricsByDate[$dateKey] = $this->computeMetrics($workHour);
}
$creditedByDate = [];
$creditedByDate = [];
$hasAbsenceByDate = [];
foreach ($absences as $absence) {
$start = $absence->getStartDate()->format('Y-m-d');
$end = $absence->getEndDate()->format('Y-m-d');
@@ -148,7 +154,10 @@ final readonly class RttRecoveryComputationService
}
[$absentMorning, $absentAfternoon] = $this->absenceSegmentsResolver->resolveForDate($absence, $date);
$creditedByDate[$date] = ($creditedByDate[$date] ?? 0)
if ($absentMorning || $absentAfternoon) {
$hasAbsenceByDate[$date] = true;
}
$creditedByDate[$date] = ($creditedByDate[$date] ?? 0)
+ $this->workedHoursCreditPolicy->computeCreditedMinutes($absence, $date, $absentMorning, $absentAfternoon);
}
}
@@ -188,14 +197,22 @@ final readonly class RttRecoveryComputationService
$dailyWorkedMinutes = [];
$employeeContractsByDate = [];
foreach ($weekDays as $date) {
$employeeContractsByDate[$date] = $contractsByDate[$employeeId][$date] ?? null;
$contractAtDate = $contractsByDate[$employeeId][$date] ?? null;
$employeeContractsByDate[$date] = $contractAtDate;
if ($limitDate instanceof DateTimeImmutable && new DateTimeImmutable($date) > $limitDate) {
continue;
}
$metrics = $metricsByDate[$date] ?? new WorkMetrics();
$metrics->addCreditedMinutes($creditedByDate[$date] ?? 0);
$weeklyTotalMinutes += $metrics->totalMinutes;
$dailyWorkedMinutes[$date] = $metrics->totalMinutes;
$effectiveMinutes = $this->holidayVirtualHoursResolver->resolveEffectiveDailyMinutes(
$contractAtDate,
new DateTimeImmutable($date),
$metrics->totalMinutes,
$hasAbsenceByDate[$date] ?? false,
$workDaysByDate[$employeeId][$date] ?? null,
);
$weeklyTotalMinutes += $effectiveMinutes;
$dailyWorkedMinutes[$date] = $effectiveMinutes;
}
if ([] === $weekDays) {
@@ -437,16 +454,6 @@ final readonly class RttRecoveryComputationService
private function resolveDailyReferenceMinutes(?int $weeklyHours, int $isoWeekDay): int
{
if ($isoWeekDay >= 6 || null === $weeklyHours || $weeklyHours <= 0) {
return 0;
}
if (39 === $weeklyHours) {
return 5 === $isoWeekDay ? 7 * 60 : 8 * 60;
}
if (35 === $weeklyHours) {
return 7 * 60;
}
return (int) round(($weeklyHours * 60) / 5);
return $this->dailyReferenceResolver->resolve($weeklyHours, $isoWeekDay);
}
}

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Service\WorkHours;
final readonly class DailyReferenceMinutesResolver
{
/**
* Returns the contractual expected minutes for a given weekday.
*
* - Saturday/Sunday: always 0
* - If $workDaysMinutes is provided (per-employee schedule on `EmployeeContractPeriod`),
* it takes precedence: returns the minutes for that iso day if scheduled, 0 otherwise.
* - Else 35h: 7h every weekday
* - Else 39h: 8h Mon-Thu, 7h Fri
* - Else other positive values: weeklyHours/5 per weekday
* - Else null/<=0 weeklyHours: 0
*
* @param int $isoWeekDay 1 = Monday ... 7 = Sunday
* @param null|array<int, int> $workDaysMinutes iso-day → minutes (1=Mon, ..., 5=Fri)
*/
public function resolve(?int $weeklyHours, int $isoWeekDay, ?array $workDaysMinutes = null): int
{
if ($isoWeekDay >= 6) {
return 0;
}
if (null !== $workDaysMinutes) {
return (int) ($workDaysMinutes[$isoWeekDay] ?? 0);
}
if (null === $weeklyHours || $weeklyHours <= 0) {
return 0;
}
if (39 === $weeklyHours) {
return 5 === $isoWeekDay ? 7 * 60 : 8 * 60;
}
if (35 === $weeklyHours) {
return 7 * 60;
}
return (int) round(($weeklyHours * 60) / 5);
}
}

View File

@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace App\Service\WorkHours;
use App\Entity\Contract;
use App\Entity\Employee;
use App\Enum\TrackingMode;
use App\Service\Contracts\EmployeeContractResolver;
use App\Service\PublicHolidayServiceInterface;
use DateTimeImmutable;
use Throwable;
/**
* Applies the business rule: a public holiday from Monday to Friday, for any
* non-Forfait contract, credits the contractually expected daily hours.
* If the employee has also entered hours that day, the effective total is the
* max between entered minutes and the contractual reference.
*/
final readonly class HolidayVirtualHoursResolver
{
public function __construct(
private DailyReferenceMinutesResolver $dailyReferenceResolver,
private PublicHolidayServiceInterface $publicHolidayService,
private EmployeeContractResolver $contractResolver,
) {}
/**
* Returns the effective daily minutes to count for RTT and weekly total
* aggregation, applying the holiday credit when applicable.
*
* If an absence is declared on the day, the absence dictates the credit
* (via WorkedHoursCreditPolicy) and the holiday virtual rule is bypassed —
* $actualMinutes already includes the absence credit.
*
* @param null|array<int, int> $workDaysMinutes per-employee schedule (iso day → minutes)
*/
public function resolveEffectiveDailyMinutes(
?Contract $contract,
DateTimeImmutable $date,
int $actualMinutes,
bool $hasAbsenceOnDate = false,
?array $workDaysMinutes = null,
): int {
$reference = $this->resolveVirtualCredit($contract, $date, $hasAbsenceOnDate, $workDaysMinutes);
if (0 === $reference) {
return $actualMinutes;
}
return max($actualMinutes, $reference);
}
/**
* Returns the virtual credit (reference minutes) alone — 0 if the rule
* does not apply (weekend, non-holiday, Forfait contract, absence declared,
* or employee schedule indicates a non-working day). Used by the frontend.
*
* @param null|array<int, int> $workDaysMinutes per-employee schedule (iso day → minutes)
*/
public function resolveVirtualCredit(
?Contract $contract,
DateTimeImmutable $date,
bool $hasAbsenceOnDate = false,
?array $workDaysMinutes = null,
): int {
if ($hasAbsenceOnDate) {
return 0;
}
$isoDay = (int) $date->format('N');
if ($isoDay >= 6) {
return 0;
}
if (null === $contract) {
return 0;
}
if (TrackingMode::PRESENCE->value === $contract->getTrackingMode()) {
return 0;
}
if (!$this->isPublicHoliday($date)) {
return 0;
}
return $this->dailyReferenceResolver->resolve($contract->getWeeklyHours(), $isoDay, $workDaysMinutes);
}
/**
* Convenience helper: resolves the schedule internally for a single employee/date.
* Used by callers that have an Employee in hand (e.g. DayContext, LeaveRecap).
*/
public function resolveVirtualCreditForEmployee(
Employee $employee,
DateTimeImmutable $date,
bool $hasAbsenceOnDate = false,
): int {
$contract = $this->contractResolver->resolveForEmployeeAndDate($employee, $date);
$workDaysMinutes = $this->contractResolver->resolveWorkDaysMinutesForEmployeeAndDate($employee, $date);
return $this->resolveVirtualCredit($contract, $date, $hasAbsenceOnDate, $workDaysMinutes);
}
private function isPublicHoliday(DateTimeImmutable $date): bool
{
try {
$holidays = $this->publicHolidayService->getHolidaysDayByYears('metropole', $date->format('Y'));
} catch (Throwable) {
return false;
}
return isset($holidays[$date->format('Y-m-d')]);
}
}

View File

@@ -14,6 +14,7 @@ final readonly class WorkedHoursCreditPolicy
{
public function __construct(
private EmployeeContractResolver $contractResolver,
private DailyReferenceMinutesResolver $dailyReferenceResolver,
) {}
/**
@@ -38,9 +39,11 @@ final readonly class WorkedHoursCreditPolicy
return 0;
}
$weekday = (int) $workDate->format('N');
// On applique la règle de crédit dépendante du contrat (35h / 39h / fallback).
$dayMinutes = $this->resolveContractDayMinutes($contract?->getWeeklyHours(), $weekday);
$weekday = (int) $workDate->format('N');
$workDaysMinutes = $this->contractResolver->resolveWorkDaysMinutesForEmployeeAndDate($employee, $workDate);
// Quand un planning est configuré sur la période (contrats non-standards),
// il prime : jour non programmé = 0 crédit, sinon on utilise les minutes prévues.
$dayMinutes = $this->resolveContractDayMinutes($contract?->getWeeklyHours(), $weekday, $workDaysMinutes);
if ($dayMinutes <= 0) {
return 0;
}
@@ -74,34 +77,14 @@ final readonly class WorkedHoursCreditPolicy
return 0.0;
}
public function resolveContractDayMinutes(?int $weeklyHours, int $isoWeekDay): int
/**
* Single source of truth = {@see DailyReferenceMinutesResolver}. Weekend=0,
* schedule precedence, 35h/39h fixed rules, fallback = weeklyHours/5.
*
* @param null|array<int, int> $workDaysMinutes planning iso-day → minutes (priorité absolue si fourni)
*/
public function resolveContractDayMinutes(?int $weeklyHours, int $isoWeekDay, ?array $workDaysMinutes = null): int
{
// Week-end non travaillé dans cette politique.
if ($isoWeekDay >= 6) {
return 0;
}
// Règle fixe: 35h => 7h/jour.
if (35 === $weeklyHours) {
return 7 * 60;
}
// Règle fixe: 39h => 8h lundi-jeudi, 7h le vendredi.
if (39 === $weeklyHours) {
return 5 === $isoWeekDay ? 7 * 60 : 8 * 60;
}
// Cas spécifique métier: contrat 4h/semaine réparti sur 2 jours => 2h/jour.
if (4 === $weeklyHours) {
return 2 * 60;
}
// Contrat non renseigné/invalide: aucun crédit.
if (null === $weeklyHours || $weeklyHours <= 0) {
return 0;
}
// Fallback générique: répartition homogène sur 5 jours ouvrés.
return (int) round(($weeklyHours * 60) / 5);
return $this->dailyReferenceResolver->resolve($weeklyHours, $isoWeekDay, $workDaysMinutes);
}
}