diff --git a/CLAUDE.md b/CLAUDE.md index 9a5b5a8..56201ed 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -108,6 +108,24 @@ - **Verrou** : si le report de l'exercice courant est `is_locked`, le paiement rétroactif est **refusé** (`assertReportNotLocked`) — la RH doit déverrouiller d'abord. - Portée limitée à N-1 (chaîne de recalcul = 1 étape). Si la ligne courante n'existe pas encore, le fallback provider couvre l'affichage (cf. ci-dessus). +## Contingent heures supplémentaires payées +- Suivi par **année civile** (Janv–Déc) des heures supp payées vs plafond légal (350 h + chauffeur / 220 h autres), non-forfait uniquement. +- **Heures payées** = `base25 + base50` (hors bonus). **Mapping** : paiements RTT stockés par + exercice → `annéeCivile = mois ≥ 6 ? exercice − 1 : exercice` ; année civile Y = exercice Y + (mois 1–5) + exercice Y+1 (mois 6–12). Cœur partagé pur `OvertimePaidContingentCalculator`. +- **Plafond** résolu sur `isDriver` du **contrat courant**. +- **Fiche employé** : encart header `Total H.payés {année} : X h / plafond h` (année civile + courante, rouge si dépassement), via `GET /employees/{id}/overtime-contingent`. Encart + volontairement indépendant de la phase sélectionnée (toujours l'année civile courante). +- **Export PDF** (`GET /overtime-contingent/print?year=&siteIds=`, `ROLE_USER`, + `findScoped`) : groupé par site (`displayOrder`), tri `displayOrder → nom → prénom`, + colonnes Janv–Déc + `Total payé / payable`. Drawer liste employés : sélecteur année + + sites (vide = périmètre complet). Exclut les FORFAIT (contrat courant). +- ⚠️ Bug latent consigné : `SalaryRecapPrintProvider` rattache mal les paiements RTT des mois + Juin–Déc (requête par année civile sur un stockage par exercice). Hors périmètre. +- Doc : `doc/overtime-contingent.md`. + ## Vue contrat (sélecteur de phase) - Picker `Vue contrat` en haut de la fiche employé (`pages/employees/[id].vue`). Caché si l'employé n'a qu'une phase. - Phase = groupe d'`EmployeeContractPeriod` consécutifs partageant la signature `(contract.type, weeklyHours, isDriver)`. Résolu par `App\Service\Contracts\EmployeeContractPhaseResolver`. diff --git a/config/version.yaml b/config/version.yaml index d880ed1..d0439a9 100644 --- a/config/version.yaml +++ b/config/version.yaml @@ -1,2 +1,2 @@ parameters: - app.version: '0.1.114' + app.version: '0.1.115' diff --git a/doc/overtime-contingent.md b/doc/overtime-contingent.md new file mode 100644 index 0000000..8abdbdf --- /dev/null +++ b/doc/overtime-contingent.md @@ -0,0 +1,33 @@ +# Contingent d'heures supplémentaires payées + +## Objectif +Suivre, par année civile (Janv–Déc), les heures supplémentaires payées de chaque employé +non-forfait (chauffeurs inclus) face au plafond légal annuel. + +## Règles +- **Heures payées** = `base25 + base50` (en minutes), hors majoration (bonus). +- **Plafond** : 350 h pour les chauffeurs (contrat courant `isDriver`), 220 h sinon. +- **Périmètre** : non-forfait uniquement (FORFAIT exclus, ni RTT ni heures supp payées). + +## Mapping exercice → année civile +Les paiements RTT (`EmployeeRttPayment`) sont stockés par **exercice** (`year` = Juin N-1 → +Mai N) + `month` (1–12). L'année civile d'un paiement : + + annéeCivile = month >= 6 ? exerciseYear - 1 : exerciseYear + +Donc l'année civile **Y** agrège : exercice `Y` (mois 1–5) + exercice `Y+1` (mois 6–12). + +## Implémentation +- Cœur partagé : `App\Service\WorkHours\OvertimePaidContingentCalculator` (pur). +- Repo : `EmployeeRttPaymentRepository::findByEmployeesAndYears`. +- Fiche employé : `GET /employees/{id}/overtime-contingent?year=YYYY` → encart header + (`Total H.payés {année} : X h / plafond h`, rouge si dépassement, année civile courante). +- Export PDF : `GET /overtime-contingent/print?year=&siteIds=` (`ROLE_USER`, périmètre + `findScoped`), groupé par site (`displayOrder`), tri `displayOrder → nom → prénom`, + colonnes Janv–Déc + colonne `Total payé / payable`. Builder + `OvertimeContingentExportBuilder`, template `overtime-contingent/print.html.twig`. + +## Hors périmètre / connu +- Bug latent récap salaire : `SalaryRecapPrintProvider` requête `findByYearAndMonth` avec + l'année civile alors que le stockage est par exercice (mauvais rattachement des paiements + des mois Juin–Déc sur le récap mensuel). À corriger séparément. diff --git a/frontend/composables/useEmployeeDetailPage.ts b/frontend/composables/useEmployeeDetailPage.ts index 05ec0b6..cc52dc3 100644 --- a/frontend/composables/useEmployeeDetailPage.ts +++ b/frontend/composables/useEmployeeDetailPage.ts @@ -2,12 +2,14 @@ import type { Employee } from '~/services/dto/employee' import { CONTRACT_TYPES } from '~/services/dto/contract' import { getEmployee } from '~/services/employees' import { useEmployeeContractPhase } from '~/composables/useEmployeeContractPhase' +import { getEmployeeOvertimeContingent, type OvertimeContingent } from '~/services/employee-overtime-contingent' export const useEmployeeDetailPage = () => { const route = useRoute() const employee = ref(null) const isLoading = ref(false) const activeTab = ref<'contract' | 'leave' | 'rtt' | 'mileage' | 'formation' | 'bonus' | 'observation'>('contract') + const overtimeContingent = ref(null) const phase = useEmployeeContractPhase(employee) @@ -28,6 +30,18 @@ export const useEmployeeDetailPage = () => { return contract.name || '-' }) + const loadOvertimeContingent = async () => { + if (!employee.value || !showRttTab.value) { + overtimeContingent.value = null + return + } + try { + overtimeContingent.value = await getEmployeeOvertimeContingent(employee.value.id) + } catch { + overtimeContingent.value = null + } + } + const loadEmployee = async () => { const idParam = Array.isArray(route.params.id) ? route.params.id[0] : route.params.id const employeeId = Number(idParam) @@ -71,6 +85,7 @@ export const useEmployeeDetailPage = () => { // qui proviennent du récap congés — nécessaire même quand on ouvre un autre onglet. await leave.loadLeaveData() } + await loadOvertimeContingent() } finally { isLoading.value = false } @@ -94,6 +109,18 @@ export const useEmployeeDetailPage = () => { if (presence === undefined || presence === null) return '' return ` (${formatDays(presence)} présence)` }) + const overtimeContingentLabel = computed(() => { + if (!showRttTab.value) return '' + const c = overtimeContingent.value + if (!c) return '' + const h = c.paidMinutes / 60 + const hStr = Number.isInteger(h) ? String(h) : (Math.round(h * 10) / 10).toFixed(1).replace('.', ',') + return `Total H.payés ${c.year} : ${hStr} h / ${c.capHours} h` + }) + const overtimeContingentExceeded = computed(() => { + const c = overtimeContingent.value + return c ? c.paidMinutes > c.capHours * 60 : false + }) const rtt = useEmployeeRtt(employee, loadEmployee, phase.selectedPhase) const mileage = useEmployeeMileage(employee, loadEmployee) const formation = useEmployeeFormation(employee, loadEmployee) @@ -147,6 +174,8 @@ export const useEmployeeDetailPage = () => { employeeContractWorkLabel, forfaitRemainingDaysLabel, nonForfaitPresenceLabel, + overtimeContingentLabel, + overtimeContingentExceeded, ...phase, ...contract, ...leave, diff --git a/frontend/data/documentation-content.ts b/frontend/data/documentation-content.ts index 5bf87b2..58c7432 100644 --- a/frontend/data/documentation-content.ts +++ b/frontend/data/documentation-content.ts @@ -643,6 +643,18 @@ export const documentationSections: DocSection[] = [ { type: 'note', content: 'Export « Contingent H.nuit » : depuis la liste des employés, bouton Export → « Contingent H.nuit » + année. Génère un PDF A4 paysage avec une ligne par employé (groupés par site) et une colonne par mois, chacune avec le total d\'heures de nuit (travail entre 21h et 6h) et le nombre de nuits (jours où au moins 4h ont été travaillées de nuit). Les conducteurs utilisent leurs heures de nuit saisies.' }, ], }, + { + id: 'contingent-heures-supp', + title: 'Export Contingent H.supp.', + requiredLevel: 'admin', + blocks: [ + { type: 'paragraph', content: 'L\'encart « Total H.payés {année} : X h / plafond h », affiché dans l\'en-tête de la fiche d\'un employé non-forfait, indique le total d\'heures supplémentaires payées sur l\'année civile en cours face au plafond légal. Il passe en rouge si ce plafond est dépassé.' }, + { type: 'list', content: 'Plafond chauffeur (contrat courant « conducteur ») : 350 h\nPlafond autres salariés non-forfait : 220 h\nSeuls les employés non-forfait disposent de cet encart (FORFAIT exclus)' }, + { type: 'paragraph', content: 'L\'export PDF « Contingent H.supp. » est accessible depuis la liste des employés, via le bouton Export → option « Contingent H.supp. ». Choisissez l\'année civile (par défaut l\'année courante) et éventuellement des sites ; sans sélection de site, tous les sites de votre périmètre sont inclus.' }, + { type: 'list', content: 'PDF A4 paysage, une ligne par employé non-forfait, groupé par site\nTri : ordre d\'affichage du site, puis nom, puis prénom\nColonnes : Janv à Déc (heures payées par mois) + colonne « Total payé / payable »\nLes employés FORFAIT n\'apparaissent pas dans cet export' }, + { type: 'note', content: 'Les heures prises en compte sont les bases payées (25 % et 50 % confondus), hors majorations. Le contingent est calculé sur l\'année civile (janvier–décembre), indépendamment de l\'exercice RTT (juin–mai) : un paiement RTT saisi pour le mois de juin est rattaché à l\'année civile précédente.' }, + ], + }, { id: 'impression-absences', title: 'Impression absences', diff --git a/frontend/pages/employees/[id].vue b/frontend/pages/employees/[id].vue index 6d6b993..573fd8d 100644 --- a/frontend/pages/employees/[id].vue +++ b/frontend/pages/employees/[id].vue @@ -28,6 +28,11 @@

{{ contractNatureLabel(employee.currentContractNature) }} {{ employeeContractWorkLabel }}{{ forfaitRemainingDaysLabel }}{{ nonForfaitPresenceLabel }}

{{ employee.site?.name ?? '-' }}

+

{{ overtimeContingentLabel }}

@@ -300,6 +305,8 @@ const { employeeContractWorkLabel, forfaitRemainingDaysLabel, nonForfaitPresenceLabel, + overtimeContingentLabel, + overtimeContingentExceeded, contractForm, createContractForm, isContractDrawerOpen, diff --git a/frontend/pages/employees/index.vue b/frontend/pages/employees/index.vue index d79eb47..5db81ac 100644 --- a/frontend/pages/employees/index.vue +++ b/frontend/pages/employees/index.vue @@ -240,6 +240,22 @@ />
+
+ + +
+
('') +const exportChoice = ref<'leave-recap' | 'salary-recap' | 'yearly-hours' | 'night-contingent' | 'overtime-contingent' | ''>('') const exportYear = ref(new Date().getFullYear()) const exportMonth = ref(new Date().getMonth() + 1) const exportSalaryMonth = ref(`${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`) +const exportSiteIds = ref([]) const exportTypeOptions = [ { label: 'Récap. congés', value: 'leave-recap' }, { label: 'Récap. salaire', value: 'salary-recap' }, { label: 'Heures annuelles', value: 'yearly-hours' }, - { label: 'Contingent H.nuit', value: 'night-contingent' } + { label: 'Contingent H.nuit', value: 'night-contingent' }, + { label: 'Contingent H.supp.', value: 'overtime-contingent' } ] const exportYearOptions = computed(() => { const current = new Date().getFullYear() @@ -315,11 +333,14 @@ const isExportValid = computed(() => { if (exportChoice.value === 'night-contingent') { return exportYear.value > 0 } + if (exportChoice.value === 'overtime-contingent') { + return exportYear.value > 0 + } return true }) const onExportChoiceChange = (value: string | number | null) => { - exportChoice.value = (value === null ? '' : String(value)) as 'leave-recap' | 'salary-recap' | 'yearly-hours' | 'night-contingent' | '' + exportChoice.value = (value === null ? '' : String(value)) as 'leave-recap' | 'salary-recap' | 'yearly-hours' | 'night-contingent' | 'overtime-contingent' | '' } const { printPdf } = usePdfPrinter() const sitesInitialized = ref(false) @@ -619,6 +640,7 @@ const openExportDrawer = () => { exportYear.value = now.getFullYear() exportMonth.value = now.getMonth() + 1 exportSalaryMonth.value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}` + exportSiteIds.value = [] isExportDrawerOpen.value = true } @@ -634,6 +656,9 @@ const handleExportValidate = async () => { await printPdf(`/yearly-hours/print-all?year=${exportYear.value}&month=${exportMonth.value}`) } else if (choice === 'night-contingent') { await printPdf(`/night-hours-contingent/print?year=${exportYear.value}`) + } else if (choice === 'overtime-contingent') { + const siteParam = exportSiteIds.value.length > 0 ? `&siteIds=${exportSiteIds.value.join(',')}` : '' + await printPdf(`/overtime-contingent/print?year=${exportYear.value}${siteParam}`) } } diff --git a/frontend/services/employee-overtime-contingent.ts b/frontend/services/employee-overtime-contingent.ts new file mode 100644 index 0000000..628deac --- /dev/null +++ b/frontend/services/employee-overtime-contingent.ts @@ -0,0 +1,13 @@ +export interface OvertimeContingent { + year: number + paidMinutes: number + capHours: number + isDriver: boolean +} + +export const getEmployeeOvertimeContingent = async (employeeId: number, year?: number) => { + const api = useApi() + const query: Record = {} + if (year) query.year = year + return api.get(`/employees/${employeeId}/overtime-contingent`, query, { toast: false }) +} diff --git a/src/ApiResource/EmployeeOvertimeContingent.php b/src/ApiResource/EmployeeOvertimeContingent.php new file mode 100644 index 0000000..eceda1a --- /dev/null +++ b/src/ApiResource/EmployeeOvertimeContingent.php @@ -0,0 +1,27 @@ + $months clé 1..12 -> minutes base payées + */ + public function __construct( + public readonly int $employeeId, + public readonly string $employeeName, + public readonly array $months, + public readonly int $totalMinutes, + public readonly int $capHours, + ) {} +} diff --git a/src/Repository/EmployeeRttPaymentRepository.php b/src/Repository/EmployeeRttPaymentRepository.php index e5ed8c2..60084a2 100644 --- a/src/Repository/EmployeeRttPaymentRepository.php +++ b/src/Repository/EmployeeRttPaymentRepository.php @@ -12,7 +12,7 @@ use Doctrine\Persistence\ManagerRegistry; /** * @extends ServiceEntityRepository */ -final class EmployeeRttPaymentRepository extends ServiceEntityRepository +class EmployeeRttPaymentRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { @@ -60,4 +60,31 @@ final class EmployeeRttPaymentRepository extends ServiceEntityRepository ->getResult() ; } + + /** + * Paiements de plusieurs employés sur plusieurs exercices (fetch groupé, + * évite le N+1 sur l'export PDF). Jointure employé chargée. + * + * @param list $employees + * @param list $years années d'exercice + * + * @return EmployeeRttPayment[] + */ + public function findByEmployeesAndYears(array $employees, array $years): array + { + if ([] === $employees || [] === $years) { + return []; + } + + return $this->createQueryBuilder('p') + ->andWhere('p.employee IN (:employees)') + ->andWhere('p.year IN (:years)') + ->setParameter('employees', $employees) + ->setParameter('years', $years) + ->innerJoin('p.employee', 'e') + ->addSelect('e') + ->getQuery() + ->getResult() + ; + } } diff --git a/src/Service/WorkHours/OvertimeContingentExportBuilder.php b/src/Service/WorkHours/OvertimeContingentExportBuilder.php new file mode 100644 index 0000000..94b76c3 --- /dev/null +++ b/src/Service/WorkHours/OvertimeContingentExportBuilder.php @@ -0,0 +1,65 @@ + $employees + * + * @return list + */ + public function buildRows(array $employees, int $civilYear): array + { + // Année civile Y = exercice Y (mois 1-5) + exercice Y+1 (mois 6-12). + $payments = $this->rttPaymentRepository->findByEmployeesAndYears( + $employees, + [$civilYear, $civilYear + 1], + ); + + $byEmployee = []; + foreach ($payments as $payment) { + $employeeId = $payment->getEmployee()?->getId(); + if (null === $employeeId) { + continue; + } + $byEmployee[$employeeId][] = $payment; + } + + $rows = []; + foreach ($employees as $employee) { + $employeeId = $employee->getId(); + if (null === $employeeId) { + continue; + } + + $employeePayments = $byEmployee[$employeeId] ?? []; + $months = $this->calculator->monthlyBaseMinutes($employeePayments, $civilYear); + + $rows[] = new OvertimeContingentRow( + employeeId: $employeeId, + employeeName: trim($employee->getLastName().' '.$employee->getFirstName()), + months: $months, + totalMinutes: array_sum($months), + capHours: $this->calculator->capHours($employee->getIsDriver()), + ); + } + + return $rows; + } +} diff --git a/src/Service/WorkHours/OvertimePaidContingentCalculator.php b/src/Service/WorkHours/OvertimePaidContingentCalculator.php new file mode 100644 index 0000000..c521786 --- /dev/null +++ b/src/Service/WorkHours/OvertimePaidContingentCalculator.php @@ -0,0 +1,54 @@ + Mai N + mois) + * en agrégats par ANNEE CIVILE (Janv-Déc). Heures payées = base25 + base50, + * hors majoration (bonus). Plafond : 350 h chauffeur, 220 h autres. + */ +final readonly class OvertimePaidContingentCalculator +{ + public const int CAP_HOURS_DRIVER = 350; + public const int CAP_HOURS_DEFAULT = 220; + + /** + * @param iterable $payments paiements d'un employé + * (typiquement exercices civilYear et civilYear+1) + * + * @return array clé 1..12 -> minutes base payées (base25+base50) + */ + public function monthlyBaseMinutes(iterable $payments, int $civilYear): array + { + $months = array_fill(1, 12, 0); + + foreach ($payments as $payment) { + $month = $payment->getMonth(); + $paymentCivilYear = $month >= 6 ? $payment->getYear() - 1 : $payment->getYear(); + if ($paymentCivilYear !== $civilYear) { + continue; + } + + $months[$month] += $payment->getBase25Minutes() + $payment->getBase50Minutes(); + } + + return $months; + } + + /** + * @param iterable $payments + */ + public function totalBaseMinutes(iterable $payments, int $civilYear): int + { + return array_sum($this->monthlyBaseMinutes($payments, $civilYear)); + } + + public function capHours(bool $isDriver): int + { + return $isDriver ? self::CAP_HOURS_DRIVER : self::CAP_HOURS_DEFAULT; + } +} diff --git a/src/State/EmployeeOvertimeContingentProvider.php b/src/State/EmployeeOvertimeContingentProvider.php new file mode 100644 index 0000000..3af8ab6 --- /dev/null +++ b/src/State/EmployeeOvertimeContingentProvider.php @@ -0,0 +1,60 @@ +employeeRepository->find($employeeId); + if (!$employee instanceof Employee) { + throw new NotFoundHttpException('Employee not found.'); + } + + $request = $this->requestStack->getCurrentRequest(); + $year = (int) $request?->query->get('year', (string) (int) new DateTimeImmutable('now')->format('Y')); + if ($year < 2000 || $year > 2100) { + throw new UnprocessableEntityHttpException('year must be between 2000 and 2100.'); + } + + // Année civile Y = exercice Y (mois 1-5) + exercice Y+1 (mois 6-12). + $payments = array_merge( + $this->rttPaymentRepository->findByEmployeeAndYear($employee, $year), + $this->rttPaymentRepository->findByEmployeeAndYear($employee, $year + 1), + ); + + $output = new EmployeeOvertimeContingent(); + $output->year = $year; + $output->paidMinutes = $this->calculator->totalBaseMinutes($payments, $year); + $output->isDriver = $employee->getIsDriver(); + $output->capHours = $this->calculator->capHours($output->isDriver); + + return $output; + } +} diff --git a/src/State/OvertimeContingentPrintProvider.php b/src/State/OvertimeContingentPrintProvider.php new file mode 100644 index 0000000..20d3ab2 --- /dev/null +++ b/src/State/OvertimeContingentPrintProvider.php @@ -0,0 +1,169 @@ +security->getUser(); + if (!$user instanceof User) { + throw new AccessDeniedHttpException('Authentication required.'); + } + + $request = $this->requestStack->getCurrentRequest(); + if (!$request) { + return new Response('Missing request.', Response::HTTP_BAD_REQUEST); + } + + $year = (int) $request->query->get('year', (string) (int) new DateTimeImmutable('now')->format('Y')); + if ($year < 2000 || $year > 2100) { + throw new UnprocessableEntityHttpException('year must be between 2000 and 2100.'); + } + + $from = new DateTimeImmutable(sprintf('%d-01-01', $year)); + $to = new DateTimeImmutable(sprintf('%d-12-31', $year)); + + // Filtre sites optionnel (vide = tout le perimetre). + $rawSiteIds = (string) $request->query->get('siteIds', ''); + $siteIds = array_values(array_filter(array_map('intval', array_filter(explode(',', $rawSiteIds), 'strlen')))); + + // Perimetre selon le profil : admin -> tous, chef de site -> ses sites. + $employees = $this->employeeRepository->findScoped($user); + + $today = new DateTimeImmutable('today'); + $bySite = []; + $siteMeta = []; + foreach ($employees as $employee) { + if (!$this->hasContractInRange($employee, $from, $to)) { + continue; + } + // Exclure les forfait (contrat courant). + $currentContract = $this->contractResolver->resolveForEmployeeAndDate($employee, $today); + if (null !== $currentContract && ContractType::FORFAIT === $currentContract->getType()) { + continue; + } + $site = $employee->getSite(); + if (null === $site) { + continue; + } + $siteId = $site->getId(); + if ([] !== $siteIds && !in_array($siteId, $siteIds, true)) { + continue; + } + $bySite[$siteId][] = $employee; + $siteMeta[$siteId] ??= [ + 'name' => $site->getName(), + 'order' => $site->getDisplayOrder(), + 'color' => $site->getColor(), + ]; + } + + uasort($siteMeta, static function (array $a, array $b): int { + return [$a['order'], $a['name']] <=> [$b['order'], $b['name']]; + }); + + $groups = []; + foreach ($siteMeta as $siteId => $meta) { + $siteEmployees = $bySite[$siteId]; + // Meme tri que le calendrier : displayOrder, puis nom, puis prenom. + usort($siteEmployees, static function (Employee $a, Employee $b): int { + return [$a->getDisplayOrder(), $a->getLastName(), $a->getFirstName()] + <=> [$b->getDisplayOrder(), $b->getLastName(), $b->getFirstName()]; + }); + + $rows = $this->exportBuilder->buildRows($siteEmployees, $year); + + $renderRows = []; + foreach ($rows as $row) { + $cells = []; + for ($m = 1; $m <= 12; ++$m) { + $cells[] = $row->months[$m] > 0 ? $this->formatMinutes($row->months[$m]) : '—'; + } + $renderRows[] = [ + 'employeeName' => $row->employeeName, + 'cells' => $cells, + 'totalHours' => $this->formatMinutes($row->totalMinutes), + 'capHours' => $row->capHours, + 'exceeded' => $row->totalMinutes > $row->capHours * 60, + ]; + } + + $groups[] = ['siteName' => $meta['name'], 'siteColor' => $meta['color'], 'rows' => $renderRows]; + } + + $options = new Options(); + $options->set('isRemoteEnabled', true); + $dompdf = new Dompdf($options); + + $html = $this->twig->render('overtime-contingent/print.html.twig', [ + 'groups' => $groups, + 'year' => $year, + 'exportedAt' => new DateTimeImmutable('now')->format('d/m/Y H:i'), + ]); + + $dompdf->loadHtml($html); + $dompdf->setPaper('A4', 'landscape'); + $dompdf->render(); + + $filename = sprintf('contingent_heures_supp_%d.pdf', $year); + + return new Response($dompdf->output(), Response::HTTP_OK, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => sprintf('attachment; filename="%s"', $filename), + ]); + } + + private function hasContractInRange(Employee $employee, DateTimeImmutable $from, DateTimeImmutable $to): bool + { + $fromDay = $from->format('Y-m-d'); + $toDay = $to->format('Y-m-d'); + + foreach ($employee->getContractPeriods() as $period) { + $start = $period->getStartDate()->format('Y-m-d'); + $end = $period->getEndDate()?->format('Y-m-d'); + if ($start <= $toDay && (null === $end || $end >= $fromDay)) { + return true; + } + } + + return false; + } + + private function formatMinutes(int $minutes): string + { + $h = intdiv($minutes, 60); + $m = $minutes % 60; + + return sprintf('%dh%02d', $h, $m); + } +} diff --git a/templates/night-hours-contingent/print.html.twig b/templates/night-hours-contingent/print.html.twig index 0bd98a6..d562d7c 100644 --- a/templates/night-hours-contingent/print.html.twig +++ b/templates/night-hours-contingent/print.html.twig @@ -19,7 +19,7 @@ -

Contingent heures de nuit — {{ year }}

+

Contingent heures de nuit — Année civile {{ year }}

Édité le {{ exportedAt }}
{% set months = ['Janv', 'Févr', 'Mars', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sept', 'Oct', 'Nov', 'Déc'] %} diff --git a/templates/overtime-contingent/print.html.twig b/templates/overtime-contingent/print.html.twig new file mode 100644 index 0000000..9063703 --- /dev/null +++ b/templates/overtime-contingent/print.html.twig @@ -0,0 +1,54 @@ + + + + + + + +

Contingent heures supplémentaires payées — Année civile {{ year }}

+
Édité le {{ exportedAt }}
+ + {% set months = ['Janv', 'Févr', 'Mars', 'Avr', 'Mai', 'Juin', 'Juil', 'Août', 'Sept', 'Oct', 'Nov', 'Déc'] %} + + + + + + {% for m in months %} + + {% endfor %} + + + + + {% for group in groups %} + + + + {% for row in group.rows %} + + + {% for cell in row.cells %} + + {% endfor %} + + + {% endfor %} + {% endfor %} + +
Nom{{ m }}Total payé / payable
{{ group.siteName }}
{{ row.employeeName }}{{ cell }}{{ row.totalHours }} / {{ row.capHours }} h
+ + diff --git a/tests/Service/WorkHours/OvertimeContingentExportBuilderTest.php b/tests/Service/WorkHours/OvertimeContingentExportBuilderTest.php new file mode 100644 index 0000000..d9213b8 --- /dev/null +++ b/tests/Service/WorkHours/OvertimeContingentExportBuilderTest.php @@ -0,0 +1,75 @@ +setLastName('Martin')->setFirstName('Luc'); + $idRef = new ReflectionProperty(Employee::class, 'id'); + $idRef->setValue($driverEmp, 7); + + // Paiement : exercice 2027, mois 9 -> civil 2026, mois 9 ; base 100+20. + $payment = new EmployeeRttPayment() + ->setEmployee($driverEmp) + ->setYear(2027)->setMonth(9) + ->setBase25Minutes(100)->setBase50Minutes(20) + ; + + $repo = $this->createStub(EmployeeRttPaymentRepository::class); + $repo->method('findByEmployeesAndYears')->willReturn([$payment]); + + $builder = new OvertimeContingentExportBuilder($repo, new OvertimePaidContingentCalculator()); + + $rows = $builder->buildRows([$driverEmp], 2026); + + self::assertCount(1, $rows); + self::assertSame(7, $rows[0]->employeeId); + self::assertSame('Martin Luc', $rows[0]->employeeName); + self::assertSame(120, $rows[0]->months[9]); + self::assertSame(0, $rows[0]->months[1]); + self::assertSame(120, $rows[0]->totalMinutes); + self::assertSame(350, $rows[0]->capHours); // chauffeur + } + + public function testEmployeeWithNoPaymentsYieldsZeroRow(): void + { + $emp = new Employee(); + $emp->setLastName('Durand')->setFirstName('Alice'); + $idRef = new ReflectionProperty(Employee::class, 'id'); + $idRef->setValue($emp, 99); + + $repo = $this->createStub(EmployeeRttPaymentRepository::class); + $repo->method('findByEmployeesAndYears')->willReturn([]); + + $builder = new OvertimeContingentExportBuilder($repo, new OvertimePaidContingentCalculator()); + $rows = $builder->buildRows([$emp], 2026); + + self::assertCount(1, $rows); + self::assertSame(0, $rows[0]->totalMinutes); + self::assertSame(0, $rows[0]->months[6]); + self::assertSame(220, $rows[0]->capHours); // non-driver + } +} diff --git a/tests/Service/WorkHours/OvertimePaidContingentCalculatorTest.php b/tests/Service/WorkHours/OvertimePaidContingentCalculatorTest.php new file mode 100644 index 0000000..3a5019d --- /dev/null +++ b/tests/Service/WorkHours/OvertimePaidContingentCalculatorTest.php @@ -0,0 +1,88 @@ += 6 -> civil 2025). + // Mars 2026 stocké en exercice 2026 (mois 3 < 6 -> civil 2026). + // Septembre 2026 stocké en exercice 2027 (mois 9 >= 6 -> civil 2026). + // March 2026 payment has a large bonus (999 min) that must be excluded. + $payments = [ + $this->payment(2026, 9, 120, 0), // civil 2025 -> exclu de 2026 + $this->payment(2026, 3, 60, 30, 999), // civil 2026 -> mois 3, bonus ignoré + $this->payment(2027, 9, 100, 20), // civil 2026 -> mois 9 + ]; + + $months = $calc->monthlyBaseMinutes($payments, 2026); + + self::assertSame(90, $months[3]); // 60 + 30 (bonus 999 excluded) + self::assertSame(120, $months[9]); // 100 + 20 + self::assertSame(0, $months[1]); + self::assertSame(0, $months[8]); + self::assertSame(210, $calc->totalBaseMinutes($payments, 2026)); // bonus ignoré + } + + public function testMonth5BelongsToExerciseYearAndMonth6ToPreviousCalendarYear(): void + { + $calc = new OvertimePaidContingentCalculator(); + + $payments = [ + $this->payment(2026, 5, 50, 0), // mai -> civil 2026 + $this->payment(2026, 6, 70, 0), // juin -> civil 2025 + ]; + + self::assertSame(50, $calc->totalBaseMinutes($payments, 2026)); + self::assertSame(70, $calc->totalBaseMinutes($payments, 2025)); + } + + public function testCapHours(): void + { + $calc = new OvertimePaidContingentCalculator(); + + self::assertSame(350, $calc->capHours(true)); + self::assertSame(220, $calc->capHours(false)); + } + + public function testEmptyPaymentsYieldsZeros(): void + { + $calc = new OvertimePaidContingentCalculator(); + $months = $calc->monthlyBaseMinutes([], 2026); + + self::assertSame(0, $months[1]); + self::assertSame(0, $months[12]); + self::assertSame(0, array_sum($months)); + self::assertSame(0, $calc->totalBaseMinutes([], 2026)); + } + + private function payment( + int $exerciseYear, + int $month, + int $base25, + int $base50, + int $bonus25 = 0, + int $bonus50 = 0, + ): EmployeeRttPayment { + return new EmployeeRttPayment() + ->setYear($exerciseYear) + ->setMonth($month) + ->setBase25Minutes($base25) + ->setBase50Minutes($base50) + ->setBonus25Minutes($bonus25) + ->setBonus50Minutes($bonus50) + ; + } +}