Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ae42c70d50 | ||
| 812215f5f6 | |||
|
|
36fe9ae54c | ||
| 6395ffbe1c | |||
|
|
b5e7395760 | ||
| 380c72c242 | |||
|
|
107417a571 | ||
| 5ff7e356be | |||
|
|
635e24e9e1 | ||
| 4d90f2cb42 | |||
|
|
9261cb5b1a | ||
| b68fef61c4 | |||
|
|
5cced46254 | ||
| 07b84a2512 | |||
|
|
ca26b7f934 | ||
| 9cf978f0f2 |
6
.idea/sqldialects.xml
generated
6
.idea/sqldialects.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="file://$PROJECT_DIR$/sirh.sql" dialect="GenericSQL" />
|
||||
</component>
|
||||
</project>
|
||||
134
AGENTS.md
134
AGENTS.md
@@ -1,6 +1,6 @@
|
||||
# AGENTS.md
|
||||
|
||||
État des lieux opérationnel du projet SIRH (backend + frontend), à utiliser comme base sur les prochaines interventions.
|
||||
État des lieux opérationnel du projet SIRH (backend + frontend), mis à jour après les évolutions sur heures/absences/validations.
|
||||
|
||||
## 1) Stack et structure
|
||||
|
||||
@@ -25,81 +25,107 @@ Arborescence clé:
|
||||
|
||||
### Contrats
|
||||
- Entité: `Contract`
|
||||
- Champs principaux: `name`, `trackingMode`, `weeklyHours`, `isActive`
|
||||
- Champs principaux: `name`, `trackingMode`, `weeklyHours`, `isActive`, `type`
|
||||
- `trackingMode`:
|
||||
- `TIME`: suivi par heures
|
||||
- `PRESENCE`: suivi présence demi-journées/journées
|
||||
- `TIME`: suivi en heures
|
||||
- `PRESENCE`: suivi en demi-journées/journées
|
||||
- Enums backend:
|
||||
- `App\Enum\TrackingMode`
|
||||
- `App\Enum\ContractType` (`FORFAIT`, `35H`, `39H`, `INTERIM`, `CUSTOM`)
|
||||
- `Contract::getType()` est exposé en API (`contract:read`, `employee:read`)
|
||||
- `App\Enum\ContractType` (`FORFAIT`, `THIRTY_FIVE_HOURS`, `THIRTY_NINE_HOURS`, `INTERIM`, `CUSTOM`)
|
||||
- Historique de contrat par employé:
|
||||
- table `employee_contract_periods`
|
||||
- résolu par `App\Service\Contracts\EmployeeContractResolver`
|
||||
|
||||
### Heures / absences
|
||||
- Les absences sont découpées en enregistrements journaliers (pas de période unique stockée).
|
||||
- Une ligne d’heures validée est verrouillée côté métier.
|
||||
- Règles de crédit absence (`countAsWorkedHours=true`) gérées dans `WorkedHoursCreditPolicy`:
|
||||
- contrats présence: crédit en unités de présence
|
||||
- contrats temps: crédit en minutes selon règles contrat (35h, 39h, 4h, fallback)
|
||||
- Les absences sont stockées en **lignes journalières** (découpage automatique dans `AbsenceWriteProcessor`).
|
||||
- Les absences `countAsWorkedHours=true` créditent:
|
||||
- minutes (contrats TIME)
|
||||
- unités de présence (contrats PRESENCE)
|
||||
- Les absences AM/PM effacent les plages horaires concernées.
|
||||
|
||||
## 4) Écrans principaux
|
||||
## 4) Validations (important)
|
||||
|
||||
### Page Heures (`frontend/pages/hours.vue`)
|
||||
- Vue Jour + Vue Semaine (semaine réservée admin)
|
||||
- Toolbar dédiée: `frontend/components/hours/HoursToolbar.vue`
|
||||
- Vue jour: `frontend/components/hours/HoursDayView.vue`
|
||||
- Vue semaine: `frontend/components/hours/HoursWeekView.vue`
|
||||
- Logique page: `frontend/composables/useHoursPage.ts`
|
||||
### Validation RH (admin)
|
||||
- Champ: `work_hours.is_valid`
|
||||
- Endpoint API Platform standard: `PATCH /api/work_hours/{id}`
|
||||
- Gérée côté front par `updateWorkHourValidation`.
|
||||
|
||||
### Points UX déjà en place
|
||||
- Toolbar semaine: raccourcis semaine précédente / actuelle / suivante
|
||||
- Légende absences affichée dans la toolbar (admin + vue semaine)
|
||||
- Cellules semaine avec absence: couleur du type d’absence (plus rouge fixe)
|
||||
- Pour user non-admin: restrictions d’édition selon validations/absences
|
||||
### Validation site (chef de site)
|
||||
- Champ: `work_hours.is_site_valid`
|
||||
- Endpoint dédié: `PATCH /api/work_hours/{id}/site-validation`
|
||||
- Processor: `src/State/WorkHourSiteValidationProcessor.php`
|
||||
- Autorisé uniquement aux utilisateurs "Sites" (ni `ROLE_ADMIN`, ni `ROLE_SELF`) dans leur scope site.
|
||||
|
||||
## 5) API / calculs hebdo
|
||||
### Règles de verrouillage
|
||||
- `is_valid=true`: ligne verrouillée pour tout le monde (admin inclus pour saisie heures/absence; peut toujours décocher validation RH).
|
||||
- `is_site_valid=true`:
|
||||
- non-admin: ligne verrouillée (heures + absences)
|
||||
- admin: ligne éditable
|
||||
- Toute modification de ligne (heures/présence/absence) remet:
|
||||
- `is_site_valid=false`
|
||||
- `is_valid=false`
|
||||
|
||||
## 5) Page Heures (front)
|
||||
|
||||
- Page: `frontend/pages/hours.vue`
|
||||
- Composable principal: `frontend/composables/useHoursPage.ts`
|
||||
- Composants:
|
||||
- `frontend/components/hours/HoursToolbar.vue`
|
||||
- `frontend/components/hours/HoursDayView.vue`
|
||||
- `frontend/components/hours/HoursWeekView.vue`
|
||||
|
||||
### Comportement par profil (vue jour)
|
||||
- Admin:
|
||||
- colonne RH avec checkbox
|
||||
- badge `Site validé` affiché près du site
|
||||
- Chef de site:
|
||||
- colonne `Validation site` avec checkbox
|
||||
- colonne RH en lecture (`Validé`/`-`)
|
||||
- Employé:
|
||||
- colonne `Validation site` en lecture
|
||||
- colonne RH en lecture
|
||||
|
||||
## 6) Résumé hebdo / calculs
|
||||
|
||||
- Provider: `src/State/WorkHourWeeklySummaryProvider.php`
|
||||
- DTOs:
|
||||
- `src/Dto/WorkHours/WeeklySummaryRow.php`
|
||||
- `src/Dto/WorkHours/WeeklyDaySummary.php`
|
||||
- Le résumé hebdo renvoie notamment:
|
||||
- `trackingMode`
|
||||
- `contractName`
|
||||
- `contractType`
|
||||
- détails journaliers (jour/nuit/total, présence, absence label/couleur)
|
||||
- Inclut: contrat résolu par jour, absences, crédits, jour/nuit/total, majorations, récup.
|
||||
|
||||
### Heures supp
|
||||
- Règles métier:
|
||||
- contrats <= 35h: tranche 25% de 35h à 43h, puis 50% au-delà
|
||||
- contrats >= 39h: tranche 25% de 39h à 43h, puis 50% au-delà
|
||||
- contrats `INTERIM`: pas de bonus 25/50 ni récup
|
||||
Règles majorations:
|
||||
- Contrats <= 35h: +25% de 35h à 43h, +50% au-delà
|
||||
- Contrats >= 39h: +25% de 39h à 43h, +50% au-delà
|
||||
- `INTERIM`: pas de 25% / 50% / récup
|
||||
|
||||
## 6) Conventions techniques
|
||||
## 7) Migrations sensibles
|
||||
|
||||
- Favoriser DTO explicites plutôt que tableaux associatifs bruts.
|
||||
- Utiliser les interfaces repository dans providers/processors testés.
|
||||
- Centraliser les règles métier dans services/providers backend plutôt que dupliquer côté front.
|
||||
- Front: éviter les calculs métier lourds; consommer les champs API déjà calculés.
|
||||
- `migrations/Version20260226183000.php`
|
||||
- ajoute `work_hours.is_site_valid BOOLEAN NOT NULL DEFAULT FALSE`
|
||||
- non destructive (pas de perte de données)
|
||||
|
||||
## 7) Tests et qualité
|
||||
## 8) Points de vigilance prod
|
||||
|
||||
- Les TU backend passent actuellement via `make test`.
|
||||
- Le build frontend passe via `npm run build`.
|
||||
- À chaque évolution métier:
|
||||
- mettre à jour les tests provider/processor/service impactés
|
||||
- maintenir la cohérence des DTO TypeScript (`frontend/services/dto/*`)
|
||||
- Toujours exécuter migration avant déploiement code backend/front lié.
|
||||
- Après déploiement backend, si route manquante côté runtime:
|
||||
- `php bin/console cache:clear && php bin/console cache:warmup`
|
||||
- Vérifier présence route:
|
||||
- `/api/work_hours/{id}/site-validation` (PATCH)
|
||||
|
||||
## 8) Fichiers sensibles (à lire avant modif)
|
||||
## 9) Conventions techniques
|
||||
|
||||
- Favoriser DTO explicites plutôt que tableaux associatifs.
|
||||
- Garder règles métier dans backend (providers/processors/services), front orienté affichage/interaction.
|
||||
- Maintenir alignement backend DTO PHP / frontend DTO TS (`frontend/services/dto/*`).
|
||||
- Mettre à jour TU si signature constructor/service change.
|
||||
|
||||
## 10) Fichiers à lire avant modification
|
||||
|
||||
- `src/State/WorkHourBulkUpsertProcessor.php`
|
||||
- `src/State/AbsenceWriteProcessor.php`
|
||||
- `src/State/WorkHourSiteValidationProcessor.php`
|
||||
- `src/State/WorkHourWeeklySummaryProvider.php`
|
||||
- `src/Service/WorkHours/WorkedHoursCreditPolicy.php`
|
||||
- `src/State/AbsenceWriteProcessor.php`
|
||||
- `src/State/WorkHourBulkUpsertProcessor.php`
|
||||
- `frontend/composables/useHoursPage.ts`
|
||||
- `frontend/components/hours/HoursDayView.vue`
|
||||
- `frontend/components/hours/HoursWeekView.vue`
|
||||
|
||||
## 9) Décisions de conception actuelles
|
||||
|
||||
- Les absences sont stockées par jour (facilite verrouillage/édition fine).
|
||||
- Les règles de calcul (crédits, majorations, récup) sont portées côté backend.
|
||||
- Le front reste centré sur l’affichage/interaction et réutilise les données enrichies de l’API.
|
||||
|
||||
@@ -2,11 +2,18 @@
|
||||
Application de gestion des absences employée
|
||||
|
||||
## Importer un dump de prod en dev
|
||||
Sur adminer fait un export bdd :
|
||||
- Sortie : enregistrer
|
||||
- Format : SQL
|
||||
- Tables : DROP+CREATE, Incrément automatique, Déclencheurs
|
||||
- Données : INSERT
|
||||
|
||||
Supprime la bdd et créer la bdd :
|
||||
```shell
|
||||
docker compose exec -T db psql -U root -d sirh -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
|
||||
```
|
||||
|
||||
Remplie la base avec le dump :
|
||||
```shell
|
||||
docker compose exec -T db psql -U root -d sirh < sirh.sql
|
||||
```
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
parameters:
|
||||
app.version: '0.1.10'
|
||||
app.version: '0.1.18'
|
||||
|
||||
@@ -54,6 +54,48 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<p class="text-md font-semibold text-neutral-700">
|
||||
Type de contrat <span class="text-red-600">*</span>
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-4 rounded-md border border-neutral-300 px-3 py-2">
|
||||
<div v-for="nature in contractNatures" :key="nature.value" class="flex items-center gap-2">
|
||||
<label class="text-md" :for="`print-contract-nature-${nature.value}`">{{ nature.label }}</label>
|
||||
<input
|
||||
:id="`print-contract-nature-${nature.value}`"
|
||||
v-model="printForm.contractNatures"
|
||||
:value="nature.value"
|
||||
type="checkbox"
|
||||
class="h-4 w-4"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="showContractNaturesError" class="text-sm text-red-600">
|
||||
Sélectionne au moins un type de contrat.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<p class="text-md font-semibold text-neutral-700">
|
||||
Temps de travail <span class="text-red-600">*</span>
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-4 rounded-md border border-neutral-300 px-3 py-2">
|
||||
<div v-for="workContract in workContracts" :key="workContract.id" class="flex items-center gap-2">
|
||||
<label class="text-md" :for="`print-work-contract-${workContract.id}`">{{ workContract.name }}</label>
|
||||
<input
|
||||
:id="`print-work-contract-${workContract.id}`"
|
||||
v-model="printForm.workContractIds"
|
||||
:value="workContract.id"
|
||||
type="checkbox"
|
||||
class="h-4 w-4"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="showWorkContractsError" class="text-sm text-red-600">
|
||||
Sélectionne au moins un temps de travail.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-3 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
@@ -84,13 +126,27 @@ type SiteOption = {
|
||||
color: string
|
||||
}
|
||||
|
||||
type ContractNatureOption = {
|
||||
value: 'CDI' | 'CDD' | 'INTERIM'
|
||||
label: string
|
||||
}
|
||||
|
||||
type WorkContractOption = {
|
||||
id: number
|
||||
name: string
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
sites: SiteOption[]
|
||||
contractNatures: ContractNatureOption[]
|
||||
workContracts: WorkContractOption[]
|
||||
printForm: {
|
||||
from: string
|
||||
to: string
|
||||
siteIds: number[]
|
||||
contractNatures: Array<'CDI' | 'CDD' | 'INTERIM'>
|
||||
workContractIds: number[]
|
||||
}
|
||||
}>()
|
||||
|
||||
@@ -110,19 +166,36 @@ const printForm = toRef(props, 'printForm')
|
||||
const validationTouched = reactive({
|
||||
from: false,
|
||||
to: false,
|
||||
sites: false
|
||||
sites: false,
|
||||
contractNatures: false,
|
||||
workContracts: false
|
||||
})
|
||||
|
||||
const isFromValid = computed(() => printForm.value.from.trim() !== '')
|
||||
const isToValid = computed(() => printForm.value.to.trim() !== '')
|
||||
const isSitesValid = computed(() => printForm.value.siteIds.length > 0)
|
||||
const isContractNaturesValid = computed(() => {
|
||||
if (props.contractNatures.length === 0) return true
|
||||
return printForm.value.contractNatures.length > 0
|
||||
})
|
||||
const isWorkContractsValid = computed(() => {
|
||||
if (props.workContracts.length === 0) return true
|
||||
return printForm.value.workContractIds.length > 0
|
||||
})
|
||||
const isFormValid = computed(
|
||||
() => isFromValid.value && isToValid.value && isSitesValid.value
|
||||
() =>
|
||||
isFromValid.value &&
|
||||
isToValid.value &&
|
||||
isSitesValid.value &&
|
||||
isContractNaturesValid.value &&
|
||||
isWorkContractsValid.value
|
||||
)
|
||||
|
||||
const showFromError = computed(() => validationTouched.from && !isFromValid.value)
|
||||
const showToError = computed(() => validationTouched.to && !isToValid.value)
|
||||
const showSitesError = computed(() => validationTouched.sites && !isSitesValid.value)
|
||||
const showContractNaturesError = computed(() => validationTouched.contractNatures && !isContractNaturesValid.value)
|
||||
const showWorkContractsError = computed(() => validationTouched.workContracts && !isWorkContractsValid.value)
|
||||
|
||||
const baseInputClass =
|
||||
'mt-2 w-full rounded-md border px-3 py-2 text-md text-neutral-900'
|
||||
@@ -150,6 +223,8 @@ const handleSubmit = () => {
|
||||
validationTouched.from = true
|
||||
validationTouched.to = true
|
||||
validationTouched.sites = true
|
||||
validationTouched.contractNatures = true
|
||||
validationTouched.workContracts = true
|
||||
if (!isFormValid.value) return
|
||||
emit('submit')
|
||||
}
|
||||
@@ -166,6 +241,8 @@ watch(
|
||||
validationTouched.from = false
|
||||
validationTouched.to = false
|
||||
validationTouched.sites = false
|
||||
validationTouched.contractNatures = false
|
||||
validationTouched.workContracts = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
77
frontend/components/PeriodStepperPicker.vue
Normal file
77
frontend/components/PeriodStepperPicker.vue
Normal file
@@ -0,0 +1,77 @@
|
||||
<template>
|
||||
<div class="relative inline-flex h-10 items-center overflow-hidden rounded-md border border-primary-500 bg-white" :class="widthClass">
|
||||
<input
|
||||
ref="nativeInput"
|
||||
:value="pickerValue"
|
||||
:type="pickerType"
|
||||
class="pointer-events-none absolute inset-0 h-full w-full opacity-0"
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
@input="onPickerInput"
|
||||
@change="onPickerInput"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 px-3 text-lg font-semibold text-primary-500 hover:bg-tertiary-500 active:bg-tertiary-500 active:scale-[0.96]"
|
||||
:aria-label="prevAriaLabel"
|
||||
@click="emit('prev')"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 flex-1 border-x border-primary-500 px-4 text-sm font-semibold text-primary-500 text-center hover:bg-tertiary-500 active:bg-tertiary-500"
|
||||
@click="openPicker"
|
||||
>
|
||||
{{ label }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 px-3 text-lg font-semibold text-primary-500 hover:bg-tertiary-500 active:bg-tertiary-500 active:scale-[0.96]"
|
||||
:aria-label="nextAriaLabel"
|
||||
@click="emit('next')"
|
||||
>
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const props = withDefaults(defineProps<{
|
||||
label: string
|
||||
pickerType: 'date' | 'week' | 'month'
|
||||
pickerValue: string
|
||||
widthClass?: string
|
||||
prevAriaLabel?: string
|
||||
nextAriaLabel?: string
|
||||
}>(), {
|
||||
widthClass: 'w-[320px]',
|
||||
prevAriaLabel: 'Précédent',
|
||||
nextAriaLabel: 'Suivant'
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'prev'): void
|
||||
(e: 'next'): void
|
||||
(e: 'pick', value: string): void
|
||||
}>()
|
||||
|
||||
const nativeInput = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const openPicker = () => {
|
||||
const input = nativeInput.value
|
||||
if (!input) return
|
||||
if (typeof input.showPicker === 'function') {
|
||||
input.showPicker()
|
||||
return
|
||||
}
|
||||
input.focus()
|
||||
input.click()
|
||||
}
|
||||
|
||||
const onPickerInput = (event: Event) => {
|
||||
const value = (event.target as HTMLInputElement).value
|
||||
if (!value) return
|
||||
emit('pick', value)
|
||||
}
|
||||
</script>
|
||||
@@ -6,21 +6,19 @@
|
||||
:style="{ gridTemplateColumns: dayGridCols }"
|
||||
>
|
||||
<span>Nom</span>
|
||||
<span class="pl-4">Début matin</span>
|
||||
<span class="pr-2">Fin matin</span>
|
||||
<span class="pl-2">Début après-midi</span>
|
||||
<span class="pr-2">Fin après-midi</span>
|
||||
<span class="pl-2">Début soir</span>
|
||||
<span class="pr-2">Fin soir</span>
|
||||
<span class="pl-2">Absence</span>
|
||||
<span class="pl-2">Absence</span>
|
||||
<span class="pl-4">Début matin</span>
|
||||
<span class="pr-2">Fin matin</span>
|
||||
<span class="pl-2">Début après-midi</span>
|
||||
<span class="pr-2">Fin après-midi</span>
|
||||
<span class="pl-2">Début soir</span>
|
||||
<span class="pr-2">Fin soir</span>
|
||||
<span class="pl-2">Jour</span>
|
||||
<span>Nuit</span>
|
||||
<span>Total</span>
|
||||
<span class="inline-flex items-center gap-2">
|
||||
<span v-if="isAdmin">Valider</span>
|
||||
<span v-else>Validation RH</span>
|
||||
<span v-if="isAdmin" class="inline-flex items-center gap-2">
|
||||
<span>Valider</span>
|
||||
<input
|
||||
v-if="isAdmin"
|
||||
ref="bulkValidationInput"
|
||||
:checked="isBulkValidationChecked"
|
||||
type="checkbox"
|
||||
@@ -28,6 +26,20 @@
|
||||
@change="onBulkValidationChange"
|
||||
/>
|
||||
</span>
|
||||
<span v-else-if="isSiteManager" class="inline-flex items-center gap-2">
|
||||
<span>Site</span>
|
||||
<input
|
||||
ref="bulkSiteValidationInput"
|
||||
:checked="isBulkSiteValidationChecked"
|
||||
type="checkbox"
|
||||
class="h-4 w-4"
|
||||
:class="canBulkToggleSiteValidation ? 'cursor-pointer' : 'cursor-not-allowed opacity-50'"
|
||||
:disabled="!canBulkToggleSiteValidation"
|
||||
@change="onBulkSiteValidationChange"
|
||||
/>
|
||||
</span>
|
||||
<span v-else>Site <Icon name="mdi:check-bold" class="ml-1"/></span>
|
||||
<span v-if="!isAdmin">RH <Icon name="mdi:check-bold" class="ml-1"/></span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
@@ -41,82 +53,92 @@
|
||||
{{ employee.firstName }} {{ employee.lastName }}
|
||||
<span class="font-normal text-neutral-600">({{ contractLabel(employee) }})</span>
|
||||
</p>
|
||||
<p class="text-neutral-500 truncate">{{ employee.site?.name ?? 'Sans site' }}</p>
|
||||
<p class="text-neutral-500 truncate inline-flex items-center gap-2">
|
||||
<span>{{ employee.site?.name ?? 'Sans site' }}</span>
|
||||
<span
|
||||
v-if="isAdmin && (rows[employee.id]?.isSiteValid ?? false)"
|
||||
class="rounded-full bg-green-500 flex justify-center item-center text-white p-0.5"
|
||||
title="Validation site"
|
||||
>
|
||||
<Icon name="mdi:check"/>
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="pl-4">
|
||||
<div class="pl-2 min-w-0 self-stretch flex flex-col gap-1 justify-between py-0.5">
|
||||
<p
|
||||
class="w-full min-w-0 rounded-md px-2 py-1 text-xs truncate"
|
||||
:class="getRowAbsenceLabel(employee.id) ? 'text-white' : 'invisible'"
|
||||
:title="getRowAbsenceLabel(employee.id) || ''"
|
||||
:style="getRowAbsenceStyle(employee.id)"
|
||||
>
|
||||
{{ getRowAbsenceLabel(employee.id) || '—' }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="self-start text-left text-xs font-semibold underline"
|
||||
:class="isHoliday || isRowLocked(employee.id) || !hasContractAtSelectedDate(employee.id) ? 'text-neutral-400 cursor-not-allowed' : 'text-primary-500 cursor-pointer'"
|
||||
:disabled="isHoliday || isRowLocked(employee.id) || !hasContractAtSelectedDate(employee.id)"
|
||||
@click="onAbsenceClick(employee.id)"
|
||||
>
|
||||
Modifier
|
||||
</button>
|
||||
</div>
|
||||
<div class="pl-4">
|
||||
<TimeSelect
|
||||
v-if="isTimeTracking(employee)"
|
||||
v-model="rows[employee.id].morningFrom"
|
||||
:disabled="isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'AM'))"
|
||||
:disabled="!hasContractAtSelectedDate(employee.id) || isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'AM'))"
|
||||
/>
|
||||
<input
|
||||
v-else-if="isPresenceTracking(employee)"
|
||||
v-model="rows[employee.id].isPresentMorning"
|
||||
type="checkbox"
|
||||
class="cursor-pointer h-4 w-4"
|
||||
:disabled="isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'AM'))"
|
||||
:disabled="!hasContractAtSelectedDate(employee.id) || isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'AM'))"
|
||||
/>
|
||||
</div>
|
||||
<div class="pr-2">
|
||||
<TimeSelect
|
||||
v-if="isTimeTracking(employee)"
|
||||
v-model="rows[employee.id].morningTo"
|
||||
:disabled="isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'AM'))"
|
||||
:disabled="!hasContractAtSelectedDate(employee.id) || isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'AM'))"
|
||||
/>
|
||||
</div>
|
||||
<div class="pl-2">
|
||||
<TimeSelect
|
||||
v-if="isTimeTracking(employee)"
|
||||
v-model="rows[employee.id].afternoonFrom"
|
||||
:disabled="isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'PM'))"
|
||||
:disabled="!hasContractAtSelectedDate(employee.id) || isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'PM'))"
|
||||
/>
|
||||
<input
|
||||
v-else-if="isPresenceTracking(employee)"
|
||||
v-model="rows[employee.id].isPresentAfternoon"
|
||||
type="checkbox"
|
||||
class="cursor-pointer h-4 w-4"
|
||||
:disabled="isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'PM'))"
|
||||
:disabled="!hasContractAtSelectedDate(employee.id) || isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'PM'))"
|
||||
/>
|
||||
</div>
|
||||
<div class="pr-2">
|
||||
<TimeSelect
|
||||
v-if="isTimeTracking(employee)"
|
||||
v-model="rows[employee.id].afternoonTo"
|
||||
:disabled="isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'PM'))"
|
||||
:disabled="!hasContractAtSelectedDate(employee.id) || isRowLocked(employee.id) || (!isAdmin && isHalfLockedByAbsence(employee.id, 'PM'))"
|
||||
/>
|
||||
</div>
|
||||
<div class="pl-2">
|
||||
<TimeSelect
|
||||
v-if="isTimeTracking(employee)"
|
||||
v-model="rows[employee.id].eveningFrom"
|
||||
:disabled="isRowLocked(employee.id) || (!isAdmin && isEveningLockedByAbsence(employee.id))"
|
||||
:disabled="!hasContractAtSelectedDate(employee.id) || isRowLocked(employee.id) || (!isAdmin && isEveningLockedByAbsence(employee.id))"
|
||||
/>
|
||||
</div>
|
||||
<div class="pr-2">
|
||||
<TimeSelect
|
||||
v-if="isTimeTracking(employee)"
|
||||
v-model="rows[employee.id].eveningTo"
|
||||
:disabled="isRowLocked(employee.id) || (!isAdmin && isEveningLockedByAbsence(employee.id))"
|
||||
:disabled="!hasContractAtSelectedDate(employee.id) || isRowLocked(employee.id) || (!isAdmin && isEveningLockedByAbsence(employee.id))"
|
||||
/>
|
||||
</div>
|
||||
<div class="pl-2 min-w-0 self-stretch flex flex-col justify-between py-0.5">
|
||||
<p
|
||||
class="w-full min-w-0 text-sm text-neutral-700 truncate"
|
||||
:class="getRowAbsenceLabel(employee.id) ? '' : 'invisible'"
|
||||
:title="getRowAbsenceLabel(employee.id) || ''"
|
||||
>
|
||||
{{ getRowAbsenceLabel(employee.id) || '—' }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="self-start text-left text-xs font-semibold underline"
|
||||
:class="isRowLocked(employee.id) ? 'text-neutral-400 cursor-not-allowed' : 'text-primary-500 cursor-pointer'"
|
||||
:disabled="isRowLocked(employee.id)"
|
||||
@click="onAbsenceClick(employee.id)"
|
||||
>
|
||||
Modifier
|
||||
</button>
|
||||
</div>
|
||||
<div class="pl-2 text-sm font-semibold text-neutral-700">
|
||||
<div v-if="isTimeTracking(employee)">{{ formatMinutes(getRowMetrics(employee.id).dayMinutes) }}</div>
|
||||
</div>
|
||||
@@ -127,15 +149,29 @@
|
||||
<div v-if="isTimeTracking(employee)">{{ formatMinutes(getRowMetrics(employee.id).totalMinutes) }}</div>
|
||||
<div v-else>{{ getPresenceDayValue(employee.id) }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div v-if="isAdmin">
|
||||
<input
|
||||
v-if="isAdmin"
|
||||
:checked="rows[employee.id]?.isValid ?? false"
|
||||
type="checkbox"
|
||||
class="h-4 w-4 cursor-pointer"
|
||||
@change="onToggleValidation(employee.id, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span v-else-if="rows[employee.id]?.isValid" class="text-xs font-semibold text-neutral-700">Validé</span>
|
||||
</div>
|
||||
<div v-else>
|
||||
<input
|
||||
v-if="isSiteManager"
|
||||
:checked="rows[employee.id]?.isSiteValid ?? false"
|
||||
type="checkbox"
|
||||
class="h-4 w-4 cursor-pointer"
|
||||
:disabled="!canToggleSiteValidation(employee.id) || isSiteValidationPending(employee.id)"
|
||||
@change="onToggleSiteValidation(employee.id, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span v-else-if="rows[employee.id]?.isSiteValid" class="text-xs font-semibold text-neutral-700">Validé</span>
|
||||
<span v-else class="text-xs text-neutral-500">-</span>
|
||||
</div>
|
||||
<div v-if="!isAdmin">
|
||||
<span v-if="rows[employee.id]?.isValid" class="text-xs font-semibold text-neutral-700">Validé</span>
|
||||
<span v-else class="text-xs text-neutral-500">-</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -149,25 +185,37 @@ import type { HourRow } from './types'
|
||||
|
||||
const rows = defineModel<Record<number, HourRow>>('rows', { required: true })
|
||||
const bulkValidationInput = ref<HTMLInputElement | null>(null)
|
||||
const bulkSiteValidationInput = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const props = defineProps<{
|
||||
employees: Employee[]
|
||||
isAdmin: boolean
|
||||
isSiteManager: boolean
|
||||
dayGridCols: string
|
||||
isHoliday: boolean
|
||||
contractLabel: (employee: Employee) => string
|
||||
isTimeTracking: (employee: Employee) => boolean
|
||||
isPresenceTracking: (employee: Employee) => boolean
|
||||
isRowLocked: (employeeId: number) => boolean
|
||||
isHalfLockedByAbsence: (employeeId: number, half: 'AM' | 'PM') => boolean
|
||||
isEveningLockedByAbsence: (employeeId: number) => boolean
|
||||
hasContractAtSelectedDate: (employeeId: number) => boolean
|
||||
isValidationPending: (employeeId: number) => boolean
|
||||
isSiteValidationPending: (employeeId: number) => boolean
|
||||
canToggleValidation: (employeeId: number) => boolean
|
||||
canToggleSiteValidation: (employeeId: number) => boolean
|
||||
isBulkValidationChecked: boolean
|
||||
isBulkValidationIndeterminate: boolean
|
||||
isBulkSiteValidationChecked: boolean
|
||||
isBulkSiteValidationIndeterminate: boolean
|
||||
canBulkToggleSiteValidation: boolean
|
||||
onToggleValidation: (employeeId: number, checked: boolean) => void
|
||||
onToggleValidationBulk: (checked: boolean) => void
|
||||
onToggleSiteValidation: (employeeId: number, checked: boolean) => void
|
||||
onToggleValidationBulk: (checked: boolean) => Promise<void> | void
|
||||
onToggleSiteValidationBulk: (checked: boolean) => Promise<void> | void
|
||||
getRowMetrics: (employeeId: number) => { dayMinutes: number; nightMinutes: number; totalMinutes: number }
|
||||
getRowAbsenceLabel: (employeeId: number) => string
|
||||
getRowAbsenceStyle: (employeeId: number) => { backgroundColor: string } | undefined
|
||||
getPresenceDayValue: (employeeId: number) => string
|
||||
onAbsenceClick: (employeeId: number) => void
|
||||
formatMinutes: (minutes: number) => string
|
||||
@@ -177,6 +225,14 @@ const onBulkValidationChange = (event: Event) => {
|
||||
props.onToggleValidationBulk((event.target as HTMLInputElement).checked)
|
||||
}
|
||||
|
||||
const onBulkSiteValidationChange = (event: Event) => {
|
||||
props.onToggleSiteValidationBulk((event.target as HTMLInputElement).checked)
|
||||
}
|
||||
|
||||
const onToggleSiteValidation = (employeeId: number, checked: boolean) => {
|
||||
props.onToggleSiteValidation(employeeId, checked)
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.isBulkValidationIndeterminate,
|
||||
(isIndeterminate) => {
|
||||
@@ -185,4 +241,13 @@ watch(
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.isBulkSiteValidationIndeterminate,
|
||||
(isIndeterminate) => {
|
||||
if (!bulkSiteValidationInput.value) return
|
||||
bulkSiteValidationInput.value.indeterminate = isIndeterminate
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
</script>
|
||||
|
||||
@@ -64,41 +64,17 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="relative inline-flex h-10 w-[320px] items-center overflow-hidden rounded-md border border-primary-500 bg-white">
|
||||
<input
|
||||
ref="nativeDateInput"
|
||||
:value="pickerValue"
|
||||
:type="viewMode === 'week' ? 'week' : 'date'"
|
||||
class="pointer-events-none absolute inset-0 h-full w-full opacity-0"
|
||||
tabindex="-1"
|
||||
aria-hidden="true"
|
||||
@input="onPickerInput"
|
||||
@change="onPickerInput"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 px-3 text-lg font-semibold text-primary-500 hover:bg-tertiary-500 active:bg-tertiary-500 active:scale-[0.96] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
|
||||
aria-label="Période précédente"
|
||||
@click="emit('shift-date', -1)"
|
||||
>
|
||||
‹
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 flex-1 border-x border-primary-500 px-4 text-sm font-semibold text-primary-500 text-center hover:bg-tertiary-500 active:bg-tertiary-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
|
||||
@click="openDatePicker"
|
||||
>
|
||||
{{ formattedSelectedDate }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="h-10 px-3 text-lg font-semibold text-primary-500 hover:bg-tertiary-500 active:bg-tertiary-500 active:scale-[0.96] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/40"
|
||||
aria-label="Période suivante"
|
||||
@click="emit('shift-date', 1)"
|
||||
>
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
<PeriodStepperPicker
|
||||
width-class="w-[320px]"
|
||||
:label="formattedSelectedDate"
|
||||
:picker-type="viewMode === 'week' ? 'week' : 'date'"
|
||||
:picker-value="pickerValue"
|
||||
prev-aria-label="Période précédente"
|
||||
next-aria-label="Période suivante"
|
||||
@prev="emit('shift-date', -1)"
|
||||
@next="emit('shift-date', 1)"
|
||||
@pick="onPickerValue"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="isAdmin" class="inline-flex h-10 overflow-hidden rounded-md border border-primary-500 bg-white">
|
||||
@@ -145,6 +121,7 @@ import type { Site } from '~/services/dto/site'
|
||||
import type { AbsenceType } from '~/services/dto/absence-type'
|
||||
import EmployeeNameFilterInput from '~/components/EmployeeNameFilterInput.vue'
|
||||
import SiteFilterSelector from '~/components/SiteFilterSelector.vue'
|
||||
import PeriodStepperPicker from '~/components/PeriodStepperPicker.vue'
|
||||
import { weekInputValueToYmd, ymdToWeekInputValue } from '~/utils/date'
|
||||
|
||||
const selectedDate = defineModel<string>('selectedDate', { required: true })
|
||||
@@ -172,7 +149,6 @@ const emit = defineEmits<{
|
||||
(e: 'shift-date', value: number): void
|
||||
}>()
|
||||
|
||||
const nativeDateInput = ref<HTMLInputElement | null>(null)
|
||||
const pickerValue = computed(() => {
|
||||
if (viewMode.value === 'week') return ymdToWeekInputValue(selectedDate.value)
|
||||
return selectedDate.value
|
||||
@@ -186,19 +162,7 @@ const viewModeButtonClass = (mode: 'day' | 'week') => {
|
||||
return 'bg-white text-primary-500 hover:bg-tertiary-500'
|
||||
}
|
||||
|
||||
const openDatePicker = () => {
|
||||
const input = nativeDateInput.value
|
||||
if (!input) return
|
||||
if (typeof input.showPicker === 'function') {
|
||||
input.showPicker()
|
||||
return
|
||||
}
|
||||
input.focus()
|
||||
input.click()
|
||||
}
|
||||
|
||||
const onPickerInput = (event: Event) => {
|
||||
const value = (event.target as HTMLInputElement).value
|
||||
const onPickerValue = (value: string) => {
|
||||
if (!value) return
|
||||
|
||||
if (viewMode.value === 'week') {
|
||||
|
||||
@@ -8,5 +8,6 @@ export type HourRow = {
|
||||
eveningTo: string
|
||||
isPresentMorning: boolean
|
||||
isPresentAfternoon: boolean
|
||||
isSiteValid: boolean
|
||||
isValid: boolean
|
||||
}
|
||||
|
||||
@@ -1,15 +1,36 @@
|
||||
<template>
|
||||
<div ref="root" class="relative w-full">
|
||||
<button
|
||||
<div
|
||||
ref="trigger"
|
||||
type="button"
|
||||
class="w-full flex justify-between rounded-md border border-neutral-300 bg-white px-3 py-2 text-left text-sm text-neutral-900 focus:outline-none focus:border-primary-500 disabled:cursor-not-allowed disabled:bg-neutral-100 disabled:text-neutral-500"
|
||||
:disabled="props.disabled"
|
||||
@click="toggleOpen"
|
||||
class="w-full flex items-center rounded-md border border-neutral-300 px-2 text-sm text-neutral-900 focus-within:border-primary-500"
|
||||
:class="props.disabled ? 'cursor-not-allowed border-neutral-300 bg-neutral-200 text-neutral-500' : 'bg-white'"
|
||||
>
|
||||
{{ displayValue }}
|
||||
<Icon name="mdi:chevron-down" class="self-center"/>
|
||||
</button>
|
||||
<input
|
||||
ref="inputRef"
|
||||
v-model="inputValue"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
:placeholder="placeholder"
|
||||
:disabled="props.disabled"
|
||||
class="h-9 w-full bg-transparent px-1 outline-none disabled:cursor-not-allowed disabled:bg-neutral-200 disabled:text-neutral-500"
|
||||
@focus="openMenu"
|
||||
@keydown.down.prevent="openMenuAndFocusFirst"
|
||||
@keydown.enter.prevent="commitInput"
|
||||
@keydown.esc.prevent="closeMenu"
|
||||
@input="onInput($event)"
|
||||
@blur="onInputBlur"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
tabindex="-1"
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded text-neutral-600 hover:bg-tertiary-500 disabled:cursor-not-allowed disabled:bg-neutral-200 disabled:text-neutral-500"
|
||||
:disabled="props.disabled"
|
||||
@mousedown.prevent
|
||||
@click="toggleOpen"
|
||||
>
|
||||
<Icon name="mdi:chevron-down" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
@@ -18,15 +39,11 @@
|
||||
class="fixed z-[120] overflow-y-auto rounded-md border border-neutral-300 bg-white shadow-sm"
|
||||
:style="menuStyle"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="block w-full px-2 py-2 text-left text-sm hover:bg-tertiary-500"
|
||||
@click="selectValue('')"
|
||||
>
|
||||
<button type="button" class="block w-full px-2 py-2 text-left text-sm hover:bg-tertiary-500" @click="selectValue('')">
|
||||
{{ placeholder }}
|
||||
</button>
|
||||
<button
|
||||
v-for="slot in timeSlots"
|
||||
v-for="slot in filteredTimeSlots"
|
||||
:key="slot"
|
||||
type="button"
|
||||
class="block w-full px-2 py-2 text-left text-sm hover:bg-tertiary-500"
|
||||
@@ -34,6 +51,9 @@
|
||||
>
|
||||
{{ slot }}
|
||||
</button>
|
||||
<p v-if="filteredTimeSlots.length === 0" class="px-2 py-2 text-sm text-neutral-500">
|
||||
Aucun résultat
|
||||
</p>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -55,7 +75,9 @@ const emit = defineEmits<{
|
||||
const root = ref<HTMLElement | null>(null)
|
||||
const trigger = ref<HTMLElement | null>(null)
|
||||
const menu = ref<HTMLElement | null>(null)
|
||||
const inputRef = ref<HTMLInputElement | null>(null)
|
||||
const isOpen = ref(false)
|
||||
const inputValue = ref('')
|
||||
const menuStyle = ref<Record<string, string>>({
|
||||
top: '0px',
|
||||
left: '0px',
|
||||
@@ -73,7 +95,31 @@ const timeSlots = computed(() => {
|
||||
return slots
|
||||
})
|
||||
|
||||
const displayValue = computed(() => props.modelValue || props.placeholder)
|
||||
const filteredTimeSlots = computed(() => {
|
||||
const query = inputValue.value.trim()
|
||||
if (!query) return timeSlots.value
|
||||
return timeSlots.value.filter((slot) => slot.includes(query))
|
||||
})
|
||||
|
||||
const applyTimeMask = (value: string): string => {
|
||||
const digits = value.replace(/\D/g, '').slice(0, 4)
|
||||
if (digits.length <= 2) return digits
|
||||
return `${digits.slice(0, 2)}:${digits.slice(2)}`
|
||||
}
|
||||
|
||||
const normalizeTypedTime = (value: string): string | null => {
|
||||
const trimmed = value.trim()
|
||||
if (trimmed === '') return ''
|
||||
|
||||
// Accepte HH:MM ou H:MM puis normalise en HH:MM.
|
||||
const match = trimmed.match(/^(\d{1,2}):(\d{2})$/)
|
||||
if (!match) return null
|
||||
const hours = Number(match[1])
|
||||
const minutes = Number(match[2])
|
||||
if (!Number.isInteger(hours) || !Number.isInteger(minutes)) return null
|
||||
if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null
|
||||
return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
const updateMenuPosition = () => {
|
||||
const triggerEl = trigger.value
|
||||
@@ -103,10 +149,57 @@ const toggleOpen = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const openMenu = () => {
|
||||
if (props.disabled) return
|
||||
if (!isOpen.value) {
|
||||
isOpen.value = true
|
||||
nextTick(updateMenuPosition)
|
||||
}
|
||||
}
|
||||
|
||||
const openMenuAndFocusFirst = () => {
|
||||
openMenu()
|
||||
}
|
||||
|
||||
const closeMenu = () => {
|
||||
isOpen.value = false
|
||||
}
|
||||
|
||||
const commitInput = () => {
|
||||
const normalized = normalizeTypedTime(inputValue.value)
|
||||
if (normalized === null) {
|
||||
inputValue.value = props.modelValue
|
||||
closeMenu()
|
||||
return
|
||||
}
|
||||
emit('update:modelValue', normalized)
|
||||
inputValue.value = normalized
|
||||
closeMenu()
|
||||
}
|
||||
|
||||
const onInput = (event: Event) => {
|
||||
const target = event.target as HTMLInputElement
|
||||
const masked = applyTimeMask(target.value)
|
||||
if (masked !== inputValue.value) {
|
||||
inputValue.value = masked
|
||||
}
|
||||
openMenu()
|
||||
}
|
||||
|
||||
const onInputBlur = () => {
|
||||
// Laisse le temps au click menu de passer avant fermeture.
|
||||
setTimeout(() => {
|
||||
if (menu.value?.contains(document.activeElement)) return
|
||||
commitInput()
|
||||
}, 50)
|
||||
}
|
||||
|
||||
const selectValue = (value: string) => {
|
||||
if (props.disabled) return
|
||||
emit('update:modelValue', value)
|
||||
inputValue.value = value
|
||||
isOpen.value = false
|
||||
nextTick(() => inputRef.value?.focus())
|
||||
}
|
||||
|
||||
const onDocumentClick = (event: MouseEvent) => {
|
||||
@@ -139,6 +232,14 @@ watch(() => props.disabled, (disabled) => {
|
||||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(value) => {
|
||||
inputValue.value = value
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('click', onDocumentClick)
|
||||
})
|
||||
|
||||
@@ -10,11 +10,15 @@ import type { HourRow } from '~/components/hours/types'
|
||||
import { listScopedEmployees } from '~/services/employees'
|
||||
import { listAbsenceTypes } from '~/services/absence-types'
|
||||
import { createAbsence, deleteAbsence, listAbsences, updateAbsence } from '~/services/absences'
|
||||
import { listPublicHolidays } from '~/services/public-holidays'
|
||||
import {
|
||||
bulkUpdateWorkHourSiteValidation,
|
||||
bulkUpdateWorkHourValidation,
|
||||
bulkUpsertWorkHours,
|
||||
getWorkHourDayContext,
|
||||
getWeeklyWorkHourSummary,
|
||||
listWorkHoursByDate,
|
||||
updateWorkHourSiteValidation,
|
||||
updateWorkHourValidation
|
||||
} from '~/services/work-hours'
|
||||
import {
|
||||
@@ -34,6 +38,8 @@ export const useHoursPage = () => {
|
||||
const auth = useAuthStore()
|
||||
const toast = useToast()
|
||||
const isAdmin = computed(() => auth.user?.roles?.includes('ROLE_ADMIN') ?? false)
|
||||
const isSelfUser = computed(() => auth.user?.roles?.includes('ROLE_SELF') ?? false)
|
||||
const isSiteManager = computed(() => !isAdmin.value && !isSelfUser.value)
|
||||
const viewMode = ref<'day' | 'week'>('day')
|
||||
|
||||
const selectedDate = ref(getTodayYmd())
|
||||
@@ -46,6 +52,7 @@ export const useHoursPage = () => {
|
||||
const weeklySummary = ref<WeeklyWorkHourSummary | null>(null)
|
||||
const absenceTypes = ref<AbsenceType[]>([])
|
||||
const absences = ref<Absence[]>([])
|
||||
const publicHolidaysByYear = ref<Record<number, Record<string, string>>>({})
|
||||
const isAbsenceDrawerOpen = ref(false)
|
||||
const isAbsenceSubmitting = ref(false)
|
||||
const editingAbsence = ref<Absence | null>(null)
|
||||
@@ -62,10 +69,12 @@ export const useHoursPage = () => {
|
||||
const isWeekLoading = ref(false)
|
||||
const isSubmitting = ref(false)
|
||||
const validatingRowIds = ref<number[]>([])
|
||||
const siteValidatingRowIds = ref<number[]>([])
|
||||
|
||||
const dayGridCols = computed(() => {
|
||||
const metricCol = '0.4fr'
|
||||
return `1.2fr repeat(6, 1fr) 0.8fr ${metricCol} ${metricCol} ${metricCol} ${metricCol}`
|
||||
const validationCols = isAdmin.value ? `${metricCol}` : `${metricCol} ${metricCol}`
|
||||
return `1.2fr 0.6fr repeat(6, 0.8fr) ${metricCol} ${metricCol} ${metricCol} ${validationCols}`
|
||||
})
|
||||
|
||||
const weekGridCols = '1.6fr repeat(7, 1fr) repeat(6, 0.6fr)'
|
||||
@@ -118,27 +127,72 @@ export const useHoursPage = () => {
|
||||
})
|
||||
|
||||
const isValidationPending = (employeeId: number) => validatingRowIds.value.includes(employeeId)
|
||||
const isSiteValidationPending = (employeeId: number) => siteValidatingRowIds.value.includes(employeeId)
|
||||
const canToggleValidation = (employeeId: number) => !!rows.value[employeeId]?.workHourId
|
||||
const canToggleSiteValidation = (employeeId: number) => {
|
||||
if (!isSiteManager.value) return false
|
||||
const row = rows.value[employeeId]
|
||||
if (!row?.workHourId) return false
|
||||
// Une validation RH fige la ligne côté chef de site.
|
||||
if (row.isValid) return false
|
||||
return true
|
||||
}
|
||||
|
||||
const validatableEmployeeIds = computed(() => {
|
||||
return employees.value
|
||||
const canCreateValidationRowFromAbsence = (employeeId: number) => {
|
||||
const row = rows.value[employeeId]
|
||||
if (row?.workHourId) return false
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
return !!dayRow?.absenceLabel && hasContractAtSelectedDate(employeeId)
|
||||
}
|
||||
|
||||
const canCreateSiteValidationRowFromAbsence = (employeeId: number) => {
|
||||
const row = rows.value[employeeId]
|
||||
if (row?.workHourId) return false
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
return !!dayRow?.absenceLabel && hasContractAtSelectedDate(employeeId)
|
||||
}
|
||||
|
||||
const bulkValidatableEmployeeIds = computed(() => {
|
||||
return visibleEmployees.value
|
||||
.map((employee) => employee.id)
|
||||
.filter((employeeId) => canToggleValidation(employeeId))
|
||||
.filter((employeeId) => canToggleValidation(employeeId) || canCreateValidationRowFromAbsence(employeeId))
|
||||
})
|
||||
|
||||
const isBulkValidationChecked = computed(() => {
|
||||
const ids = validatableEmployeeIds.value
|
||||
const ids = bulkValidatableEmployeeIds.value
|
||||
if (ids.length === 0) return false
|
||||
return ids.every((employeeId) => rows.value[employeeId]?.isValid ?? false)
|
||||
})
|
||||
|
||||
const isBulkValidationIndeterminate = computed(() => {
|
||||
const ids = validatableEmployeeIds.value
|
||||
const ids = bulkValidatableEmployeeIds.value
|
||||
if (ids.length === 0) return false
|
||||
const checkedCount = ids.filter((employeeId) => rows.value[employeeId]?.isValid ?? false).length
|
||||
return checkedCount > 0 && checkedCount < ids.length
|
||||
})
|
||||
|
||||
const bulkSiteValidatableEmployeeIds = computed(() => {
|
||||
if (!isSiteManager.value) return []
|
||||
return visibleEmployees.value
|
||||
.map((employee) => employee.id)
|
||||
.filter((employeeId) => canToggleSiteValidation(employeeId) || canCreateSiteValidationRowFromAbsence(employeeId))
|
||||
})
|
||||
|
||||
const isBulkSiteValidationChecked = computed(() => {
|
||||
const ids = bulkSiteValidatableEmployeeIds.value
|
||||
if (ids.length === 0) return false
|
||||
return ids.every((employeeId) => rows.value[employeeId]?.isSiteValid ?? false)
|
||||
})
|
||||
|
||||
const isBulkSiteValidationIndeterminate = computed(() => {
|
||||
const ids = bulkSiteValidatableEmployeeIds.value
|
||||
if (ids.length === 0) return false
|
||||
const checkedCount = ids.filter((employeeId) => rows.value[employeeId]?.isSiteValid ?? false).length
|
||||
return checkedCount > 0 && checkedCount < ids.length
|
||||
})
|
||||
|
||||
const canBulkToggleSiteValidation = computed(() => bulkSiteValidatableEmployeeIds.value.length > 0)
|
||||
|
||||
const dayContextByEmployeeId = computed(() => {
|
||||
const map = new Map<number, WorkHourDayContext['rows'][number]>()
|
||||
for (const row of dayContext.value?.rows ?? []) {
|
||||
@@ -203,6 +257,19 @@ export const useHoursPage = () => {
|
||||
return formatDateLongFr(parsed)
|
||||
})
|
||||
|
||||
const selectedYear = computed(() => {
|
||||
const parsed = parseYmd(selectedDate.value)
|
||||
return parsed ? parsed.getFullYear() : null
|
||||
})
|
||||
|
||||
const selectedHolidayLabel = computed(() => {
|
||||
const year = selectedYear.value
|
||||
if (!year) return ''
|
||||
return publicHolidaysByYear.value[year]?.[selectedDate.value] ?? ''
|
||||
})
|
||||
|
||||
const isSelectedDateHoliday = computed(() => selectedHolidayLabel.value !== '')
|
||||
|
||||
const weekDayHeaders = computed(() => {
|
||||
const days = weeklySummary.value?.days ?? []
|
||||
return days.map((date) => ({ date, label: formatWeekDayHeaderFr(date) }))
|
||||
@@ -273,12 +340,19 @@ export const useHoursPage = () => {
|
||||
eveningTo: '',
|
||||
isPresentMorning: false,
|
||||
isPresentAfternoon: false,
|
||||
isSiteValid: false,
|
||||
isValid: false
|
||||
})
|
||||
|
||||
const isPresenceTracking = (employee: Employee) => employee.contract?.trackingMode === TRACKING_MODES.PRESENCE
|
||||
const isTimeTracking = (employee: Employee) => !isPresenceTracking(employee)
|
||||
const isRowLocked = (employeeId: number) => rows.value[employeeId]?.isValid ?? false
|
||||
const isRowLocked = (employeeId: number) => {
|
||||
const row = rows.value[employeeId]
|
||||
if (!row) return false
|
||||
if (row.isValid) return true
|
||||
if (!isAdmin.value && row.isSiteValid) return true
|
||||
return false
|
||||
}
|
||||
|
||||
const contractLabel = (employee: Employee) => {
|
||||
const contract = employee.contract
|
||||
@@ -371,6 +445,10 @@ export const useHoursPage = () => {
|
||||
|
||||
const getRowAbsenceLabel = (employeeId: number) => {
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
if (dayRow && dayRow.hasContractAtDate === false) {
|
||||
return 'Contrat non démarré'
|
||||
}
|
||||
if (isSelectedDateHoliday.value) return 'Férié'
|
||||
if (!dayRow?.absenceLabel) return ''
|
||||
if (dayRow.absenceHalf === 'AM' || dayRow.absenceHalf === 'PM') {
|
||||
const halfLabel = dayRow.absenceHalf === 'AM' ? 'Matin' : 'ap.-m.'
|
||||
@@ -379,21 +457,38 @@ export const useHoursPage = () => {
|
||||
return `${dayRow.absenceLabel} (journée)`
|
||||
}
|
||||
|
||||
const getRowAbsenceStyle = (employeeId: number) => {
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
if (!dayRow?.absenceLabel) return undefined
|
||||
return { backgroundColor: dayRow.absenceColor || '#dc2626' }
|
||||
}
|
||||
|
||||
const getPresenceDayValue = (employeeId: number) => {
|
||||
const row = rows.value[employeeId]
|
||||
const basePresence = (row?.isPresentMorning ? 0.5 : 0) + (row?.isPresentAfternoon ? 0.5 : 0)
|
||||
const creditedPresence = dayContextByEmployeeId.value.get(employeeId)?.creditedPresenceUnits ?? 0
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
const absentMorning = dayRow?.absentMorning ?? false
|
||||
const absentAfternoon = dayRow?.absentAfternoon ?? false
|
||||
const basePresence = ((row?.isPresentMorning && !absentMorning) ? 0.5 : 0) + ((row?.isPresentAfternoon && !absentAfternoon) ? 0.5 : 0)
|
||||
const creditedPresence = dayRow?.creditedPresenceUnits ?? 0
|
||||
const total = Math.min(1, basePresence + creditedPresence)
|
||||
return Number.isInteger(total) ? String(total) : total.toFixed(1)
|
||||
}
|
||||
|
||||
const hasContractAtSelectedDate = (employeeId: number) => {
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
if (!dayRow) return true
|
||||
return dayRow.hasContractAtDate !== false
|
||||
}
|
||||
|
||||
const isHalfLockedByAbsence = (employeeId: number, half: 'AM' | 'PM') => {
|
||||
if (!hasContractAtSelectedDate(employeeId)) return true
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
if (!dayRow) return false
|
||||
return half === 'AM' ? dayRow.absentMorning : dayRow.absentAfternoon
|
||||
}
|
||||
|
||||
const isEveningLockedByAbsence = (employeeId: number) => {
|
||||
if (!hasContractAtSelectedDate(employeeId)) return true
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
if (!dayRow) return false
|
||||
return dayRow.absentAfternoon
|
||||
@@ -425,6 +520,7 @@ export const useHoursPage = () => {
|
||||
eveningTo: workHour?.eveningTo ?? '',
|
||||
isPresentMorning: workHour?.isPresentMorning ?? false,
|
||||
isPresentAfternoon: workHour?.isPresentAfternoon ?? false,
|
||||
isSiteValid: workHour?.isSiteValid ?? false,
|
||||
isValid: workHour?.isValid ?? false
|
||||
}
|
||||
}
|
||||
@@ -436,6 +532,18 @@ export const useHoursPage = () => {
|
||||
absenceTypes.value = await listAbsenceTypes()
|
||||
}
|
||||
|
||||
const loadPublicHolidaysForSelectedYear = async () => {
|
||||
const year = selectedYear.value
|
||||
if (!year) return
|
||||
if (publicHolidaysByYear.value[year]) return
|
||||
|
||||
const holidays = await listPublicHolidays('metropole', year)
|
||||
publicHolidaysByYear.value = {
|
||||
...publicHolidaysByYear.value,
|
||||
[year]: holidays
|
||||
}
|
||||
}
|
||||
|
||||
const loadAbsences = async () => {
|
||||
absences.value = await listAbsences({
|
||||
from: selectedDate.value,
|
||||
@@ -445,6 +553,9 @@ export const useHoursPage = () => {
|
||||
}
|
||||
|
||||
const openAbsenceDrawer = (employeeId: number) => {
|
||||
if (!hasContractAtSelectedDate(employeeId)) return
|
||||
if (isSelectedDateHoliday.value) return
|
||||
|
||||
const existing = absences.value.find((absence) => {
|
||||
if (absence.employee?.id !== employeeId) return false
|
||||
const start = absence.startDate.slice(0, 10)
|
||||
@@ -571,56 +682,273 @@ export const useHoursPage = () => {
|
||||
options: { toast?: boolean } = {}
|
||||
) => {
|
||||
const row = rows.value[employeeId]
|
||||
if (!row?.workHourId || isValidationPending(employeeId)) return
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
if (!row?.workHourId && checked) {
|
||||
const employee = employees.value.find((item) => item.id === employeeId)
|
||||
const hasAbsence = !!dayRow?.absenceLabel
|
||||
const canCreateFromAbsence = !!employee && hasAbsence && hasContractAtSelectedDate(employeeId)
|
||||
|
||||
if (canCreateFromAbsence) {
|
||||
await bulkUpsertWorkHours({
|
||||
workDate: selectedDate.value,
|
||||
entries: [{
|
||||
employeeId,
|
||||
morningFrom: null,
|
||||
morningTo: null,
|
||||
afternoonFrom: null,
|
||||
afternoonTo: null,
|
||||
eveningFrom: null,
|
||||
eveningTo: null,
|
||||
isPresentMorning: false,
|
||||
isPresentAfternoon: false
|
||||
}]
|
||||
}, { toast: false })
|
||||
|
||||
await loadWorkHours()
|
||||
}
|
||||
}
|
||||
|
||||
const updatedRow = rows.value[employeeId]
|
||||
if (!updatedRow?.workHourId) {
|
||||
if (options.toast !== false) {
|
||||
toast.error({
|
||||
title: 'Validation impossible',
|
||||
message: 'La ligne doit contenir des heures ou une absence.'
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (isValidationPending(employeeId)) return
|
||||
|
||||
validatingRowIds.value = [...validatingRowIds.value, employeeId]
|
||||
try {
|
||||
await updateWorkHourValidation(row.workHourId, checked, { toast: options.toast })
|
||||
row.isValid = checked
|
||||
await updateWorkHourValidation(updatedRow.workHourId, checked, { toast: options.toast })
|
||||
updatedRow.isValid = checked
|
||||
} finally {
|
||||
validatingRowIds.value = validatingRowIds.value.filter((id) => id !== employeeId)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleValidationBulk = async (checked: boolean) => {
|
||||
const employeeIds = validatableEmployeeIds.value
|
||||
if (employeeIds.length === 0) return
|
||||
const toggleSiteValidation = async (
|
||||
employeeId: number,
|
||||
checked: boolean,
|
||||
options: { toast?: boolean } = {}
|
||||
) => {
|
||||
const row = rows.value[employeeId]
|
||||
const dayRow = dayContextByEmployeeId.value.get(employeeId)
|
||||
if (!row?.workHourId && checked) {
|
||||
const employee = employees.value.find((item) => item.id === employeeId)
|
||||
const hasAbsence = !!dayRow?.absenceLabel
|
||||
const canCreateFromAbsence = !!employee && hasAbsence && hasContractAtSelectedDate(employeeId)
|
||||
|
||||
let successCount = 0
|
||||
let failedCount = 0
|
||||
if (canCreateFromAbsence) {
|
||||
await bulkUpsertWorkHours({
|
||||
workDate: selectedDate.value,
|
||||
entries: [{
|
||||
employeeId,
|
||||
morningFrom: null,
|
||||
morningTo: null,
|
||||
afternoonFrom: null,
|
||||
afternoonTo: null,
|
||||
eveningFrom: null,
|
||||
eveningTo: null,
|
||||
isPresentMorning: false,
|
||||
isPresentAfternoon: false
|
||||
}]
|
||||
}, { toast: false })
|
||||
|
||||
for (const employeeId of employeeIds) {
|
||||
if (isValidationPending(employeeId)) continue
|
||||
try {
|
||||
await toggleValidation(employeeId, checked, { toast: false })
|
||||
successCount += 1
|
||||
} catch {
|
||||
failedCount += 1
|
||||
await loadWorkHours()
|
||||
}
|
||||
}
|
||||
|
||||
if (failedCount === 0) {
|
||||
toast.success({
|
||||
title: 'Succès',
|
||||
message: checked
|
||||
? `${successCount} ligne(s) validée(s).`
|
||||
: `${successCount} validation(s) retirée(s).`
|
||||
const updatedRow = rows.value[employeeId]
|
||||
if (!updatedRow?.workHourId) {
|
||||
if (options.toast !== false) {
|
||||
toast.error({
|
||||
title: 'Validation impossible',
|
||||
message: 'La ligne doit contenir des heures ou une absence.'
|
||||
})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (isSiteValidationPending(employeeId)) return
|
||||
if (!canToggleSiteValidation(employeeId)) return
|
||||
|
||||
siteValidatingRowIds.value = [...siteValidatingRowIds.value, employeeId]
|
||||
try {
|
||||
await updateWorkHourSiteValidation(updatedRow.workHourId, checked, { toast: options.toast })
|
||||
updatedRow.isSiteValid = checked
|
||||
} finally {
|
||||
siteValidatingRowIds.value = siteValidatingRowIds.value.filter((id) => id !== employeeId)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleValidationBulk = async (checked: boolean) => {
|
||||
const employeeIds = bulkValidatableEmployeeIds.value
|
||||
if (employeeIds.length === 0) return
|
||||
|
||||
const pendingIds = new Set(validatingRowIds.value)
|
||||
const availableEmployeeIds = employeeIds.filter((employeeId) => !pendingIds.has(employeeId))
|
||||
if (availableEmployeeIds.length === 0) return
|
||||
|
||||
if (checked) {
|
||||
const toCreateIds = availableEmployeeIds.filter((employeeId) => canCreateValidationRowFromAbsence(employeeId))
|
||||
if (toCreateIds.length > 0) {
|
||||
await bulkUpsertWorkHours({
|
||||
workDate: selectedDate.value,
|
||||
entries: toCreateIds.map((employeeId) => ({
|
||||
employeeId,
|
||||
morningFrom: null,
|
||||
morningTo: null,
|
||||
afternoonFrom: null,
|
||||
afternoonTo: null,
|
||||
eveningFrom: null,
|
||||
eveningTo: null,
|
||||
isPresentMorning: false,
|
||||
isPresentAfternoon: false
|
||||
}))
|
||||
}, { toast: false })
|
||||
|
||||
await loadWorkHours()
|
||||
}
|
||||
}
|
||||
|
||||
const targetEmployeeIds = availableEmployeeIds.filter((employeeId) => canToggleValidation(employeeId))
|
||||
if (targetEmployeeIds.length === 0) {
|
||||
toast.error({
|
||||
title: 'Validation impossible',
|
||||
message: 'Aucune ligne ne peut être validée.'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (successCount === 0) {
|
||||
validatingRowIds.value = Array.from(new Set([...validatingRowIds.value, ...targetEmployeeIds]))
|
||||
|
||||
try {
|
||||
const result = await bulkUpdateWorkHourValidation({
|
||||
workDate: selectedDate.value,
|
||||
isValid: checked,
|
||||
employeeIds: targetEmployeeIds
|
||||
}, { toast: false })
|
||||
|
||||
await loadWorkHours()
|
||||
|
||||
if (result.updated === 0) {
|
||||
toast.error({
|
||||
title: 'Erreur',
|
||||
message: 'Aucune ligne mise à jour.'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (result.skipped > 0) {
|
||||
toast.success({
|
||||
title: 'Succès partiel',
|
||||
message: `${result.updated} mise(s) à jour, ${result.skipped} ignorée(s).`
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
toast.success({
|
||||
title: 'Succès',
|
||||
message: checked
|
||||
? `${result.updated} ligne(s) validée(s).`
|
||||
: `${result.updated} validation(s) retirée(s).`
|
||||
})
|
||||
} catch {
|
||||
toast.error({
|
||||
title: 'Erreur',
|
||||
message: 'Impossible de mettre à jour les validations.'
|
||||
})
|
||||
} finally {
|
||||
validatingRowIds.value = validatingRowIds.value.filter((id) => !targetEmployeeIds.includes(id))
|
||||
}
|
||||
}
|
||||
|
||||
const toggleSiteValidationBulk = async (checked: boolean) => {
|
||||
if (!isSiteManager.value) return
|
||||
|
||||
const employeeIds = bulkSiteValidatableEmployeeIds.value
|
||||
if (employeeIds.length === 0) return
|
||||
|
||||
const pendingIds = new Set(siteValidatingRowIds.value)
|
||||
const availableEmployeeIds = employeeIds.filter((employeeId) => !pendingIds.has(employeeId))
|
||||
if (availableEmployeeIds.length === 0) return
|
||||
|
||||
if (checked) {
|
||||
const toCreateIds = availableEmployeeIds.filter((employeeId) => canCreateSiteValidationRowFromAbsence(employeeId))
|
||||
if (toCreateIds.length > 0) {
|
||||
await bulkUpsertWorkHours({
|
||||
workDate: selectedDate.value,
|
||||
entries: toCreateIds.map((employeeId) => ({
|
||||
employeeId,
|
||||
morningFrom: null,
|
||||
morningTo: null,
|
||||
afternoonFrom: null,
|
||||
afternoonTo: null,
|
||||
eveningFrom: null,
|
||||
eveningTo: null,
|
||||
isPresentMorning: false,
|
||||
isPresentAfternoon: false
|
||||
}))
|
||||
}, { toast: false })
|
||||
|
||||
await loadWorkHours()
|
||||
}
|
||||
}
|
||||
|
||||
const targetEmployeeIds = availableEmployeeIds.filter((employeeId) => canToggleSiteValidation(employeeId))
|
||||
if (targetEmployeeIds.length === 0) {
|
||||
toast.error({
|
||||
title: 'Validation impossible',
|
||||
message: 'Aucune ligne ne peut être validée côté site.'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
toast.error({
|
||||
title: 'Erreur',
|
||||
message: `${successCount} mise(s) à jour, ${failedCount} en échec.`
|
||||
})
|
||||
siteValidatingRowIds.value = Array.from(new Set([...siteValidatingRowIds.value, ...targetEmployeeIds]))
|
||||
|
||||
try {
|
||||
const result = await bulkUpdateWorkHourSiteValidation({
|
||||
workDate: selectedDate.value,
|
||||
isSiteValid: checked,
|
||||
employeeIds: targetEmployeeIds
|
||||
}, { toast: false })
|
||||
|
||||
await loadWorkHours()
|
||||
|
||||
if (result.updated === 0) {
|
||||
toast.error({
|
||||
title: 'Erreur',
|
||||
message: 'Aucune ligne site mise à jour.'
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (result.skipped > 0) {
|
||||
toast.success({
|
||||
title: 'Succès partiel',
|
||||
message: `${result.updated} mise(s) à jour, ${result.skipped} ignorée(s).`
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
toast.success({
|
||||
title: 'Succès',
|
||||
message: checked
|
||||
? `${result.updated} validation(s) site enregistrée(s).`
|
||||
: `${result.updated} validation(s) site retirée(s).`
|
||||
})
|
||||
} catch {
|
||||
toast.error({
|
||||
title: 'Erreur',
|
||||
message: 'Impossible de mettre à jour les validations site.'
|
||||
})
|
||||
} finally {
|
||||
siteValidatingRowIds.value = siteValidatingRowIds.value.filter((id) => !targetEmployeeIds.includes(id))
|
||||
}
|
||||
}
|
||||
|
||||
const loadEmployees = async () => {
|
||||
@@ -659,6 +987,7 @@ export const useHoursPage = () => {
|
||||
const loadPage = async () => {
|
||||
isLoading.value = true
|
||||
try {
|
||||
await loadPublicHolidaysForSelectedYear()
|
||||
await loadEmployees()
|
||||
await loadAbsenceTypes()
|
||||
await refreshByDate()
|
||||
@@ -694,6 +1023,7 @@ export const useHoursPage = () => {
|
||||
}, { immediate: true })
|
||||
|
||||
watch(selectedDate, async () => {
|
||||
await loadPublicHolidaysForSelectedYear()
|
||||
await refreshByDate()
|
||||
})
|
||||
|
||||
@@ -702,7 +1032,9 @@ export const useHoursPage = () => {
|
||||
|
||||
isSubmitting.value = true
|
||||
try {
|
||||
const entries = employees.value.map((employee) => {
|
||||
const entries = employees.value
|
||||
.filter((employee) => hasContractAtSelectedDate(employee.id))
|
||||
.map((employee) => {
|
||||
const employeeId = employee.id
|
||||
const row = rows.value[employeeId] ?? emptyRow()
|
||||
if (isPresenceTracking(employee)) {
|
||||
@@ -730,7 +1062,11 @@ export const useHoursPage = () => {
|
||||
isPresentMorning: false,
|
||||
isPresentAfternoon: false
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
if (entries.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
await bulkUpsertWorkHours({
|
||||
workDate: selectedDate.value,
|
||||
@@ -745,6 +1081,8 @@ export const useHoursPage = () => {
|
||||
|
||||
return {
|
||||
isAdmin,
|
||||
isSelfUser,
|
||||
isSiteManager,
|
||||
viewMode,
|
||||
selectedDate,
|
||||
employeeFilter,
|
||||
@@ -767,6 +1105,7 @@ export const useHoursPage = () => {
|
||||
weekGridCols,
|
||||
saveButtonClass,
|
||||
formattedSelectedDate,
|
||||
isSelectedDateHoliday,
|
||||
weekDayHeaders,
|
||||
shortcutButtonClass,
|
||||
weekShortcutButtonClass,
|
||||
@@ -784,14 +1123,23 @@ export const useHoursPage = () => {
|
||||
isRowLocked,
|
||||
isHalfLockedByAbsence,
|
||||
isEveningLockedByAbsence,
|
||||
hasContractAtSelectedDate,
|
||||
isValidationPending,
|
||||
isSiteValidationPending,
|
||||
canToggleValidation,
|
||||
canToggleSiteValidation,
|
||||
isBulkValidationChecked,
|
||||
isBulkValidationIndeterminate,
|
||||
isBulkSiteValidationChecked,
|
||||
isBulkSiteValidationIndeterminate,
|
||||
canBulkToggleSiteValidation,
|
||||
toggleValidation,
|
||||
toggleSiteValidation,
|
||||
toggleValidationBulk,
|
||||
toggleSiteValidationBulk,
|
||||
getRowMetrics,
|
||||
getRowAbsenceLabel,
|
||||
getRowAbsenceStyle,
|
||||
getPresenceDayValue,
|
||||
openAbsenceDrawer,
|
||||
submitAbsence,
|
||||
|
||||
@@ -170,6 +170,10 @@
|
||||
import type { AbsenceType } from '~/services/dto/absence-type'
|
||||
import { createAbsenceType, deleteAbsenceType, listAbsenceTypes, updateAbsenceType } from '~/services/absence-types'
|
||||
|
||||
useHead({
|
||||
title: 'Types d\'absences'
|
||||
})
|
||||
|
||||
const isDrawerOpen = ref(false)
|
||||
const isSubmitting = ref(false)
|
||||
const isLoading = ref(false)
|
||||
|
||||
@@ -30,22 +30,17 @@
|
||||
<div class="w-80">
|
||||
<EmployeeNameFilterInput v-model="employeeFilter"/>
|
||||
</div>
|
||||
<select
|
||||
v-model="selectedMonth"
|
||||
class="h-10 rounded-md border border-neutral-300 bg-white px-3 text-md text-neutral-900"
|
||||
>
|
||||
<option v-for="month in months" :key="month.value" :value="month.value">
|
||||
{{ month.label }}
|
||||
</option>
|
||||
</select>
|
||||
<select
|
||||
v-model="selectedYear"
|
||||
class="h-10 rounded-md border border-neutral-300 bg-white px-3 text-md text-neutral-900"
|
||||
>
|
||||
<option v-for="year in years" :key="year" :value="year">
|
||||
{{ year }}
|
||||
</option>
|
||||
</select>
|
||||
<PeriodStepperPicker
|
||||
width-class="w-[260px]"
|
||||
:label="selectedMonthLabel"
|
||||
picker-type="month"
|
||||
:picker-value="monthPickerValue"
|
||||
prev-aria-label="Mois précédent"
|
||||
next-aria-label="Mois suivant"
|
||||
@prev="shiftMonth(-1)"
|
||||
@next="shiftMonth(1)"
|
||||
@pick="onMonthPickerValue"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-6 py-2">
|
||||
@@ -86,6 +81,8 @@
|
||||
<AbsencePrintDrawer
|
||||
v-model="isPrintOpen"
|
||||
:sites="sites"
|
||||
:contract-natures="contractNatureOptions"
|
||||
:work-contracts="workContractOptions"
|
||||
:print-form="printForm"
|
||||
@submit="handlePrint"
|
||||
@cancel="closePrint"
|
||||
@@ -109,8 +106,13 @@ import CalendarGrid from '~/components/CalendarGrid.vue'
|
||||
import AbsenceFormDrawer from '~/components/AbsenceFormDrawer.vue'
|
||||
import AbsencePrintDrawer from '~/components/AbsencePrintDrawer.vue'
|
||||
import EmployeeNameFilterInput from '~/components/EmployeeNameFilterInput.vue'
|
||||
import PeriodStepperPicker from '~/components/PeriodStepperPicker.vue'
|
||||
import SiteFilterSelector from '~/components/SiteFilterSelector.vue'
|
||||
|
||||
useHead({
|
||||
title: 'Calendrier'
|
||||
})
|
||||
|
||||
// Données principales affichées dans la grille.
|
||||
const employees = ref<Employee[]>([])
|
||||
const sites = computed(() => {
|
||||
@@ -189,8 +191,8 @@ const months = [
|
||||
{value: 11, label: 'Décembre'}
|
||||
]
|
||||
|
||||
const years = Array.from({length: 5}, (unusedValue, index) => now.getFullYear() - 2 + index)
|
||||
|
||||
const selectedMonthLabel = computed(() => `${months[selectedMonth.value]?.label ?? ''}`)
|
||||
const monthPickerValue = computed(() => `${selectedYear.value}-${String(selectedMonth.value + 1).padStart(2, '0')}`)
|
||||
|
||||
// Infos de calendrier calculées.
|
||||
const daysInMonth = computed(() => getDaysInMonth(selectedYear.value, selectedMonth.value))
|
||||
@@ -217,7 +219,25 @@ const form = reactive({
|
||||
const printForm = reactive({
|
||||
from: '',
|
||||
to: '',
|
||||
siteIds: [] as number[]
|
||||
siteIds: [] as number[],
|
||||
contractNatures: [] as Array<'CDI' | 'CDD' | 'INTERIM'>,
|
||||
workContractIds: [] as number[]
|
||||
})
|
||||
|
||||
const contractNatureOptions = [
|
||||
{ value: 'CDI' as const, label: 'CDI' },
|
||||
{ value: 'CDD' as const, label: 'CDD' },
|
||||
{ value: 'INTERIM' as const, label: 'Intérim' }
|
||||
]
|
||||
|
||||
const workContractOptions = computed(() => {
|
||||
const byId = new Map<number, { id: number; name: string }>()
|
||||
for (const employee of employees.value) {
|
||||
const contract = employee.contract
|
||||
if (!contract?.id) continue
|
||||
byId.set(contract.id, { id: contract.id, name: contract.name })
|
||||
}
|
||||
return Array.from(byId.values()).sort((a, b) => a.name.localeCompare(b.name, 'fr'))
|
||||
})
|
||||
|
||||
// Remet le formulaire à zéro.
|
||||
@@ -245,6 +265,8 @@ const openPrint = () => {
|
||||
printForm.from = monthStart
|
||||
printForm.to = monthEnd
|
||||
printForm.siteIds = [...selectedSiteIds.value]
|
||||
printForm.contractNatures = contractNatureOptions.map((item) => item.value)
|
||||
printForm.workContractIds = workContractOptions.value.map((item) => item.id)
|
||||
isPrintOpen.value = true
|
||||
}
|
||||
|
||||
@@ -290,6 +312,22 @@ const addMonths = (date: Date, months: number) => {
|
||||
return next
|
||||
}
|
||||
|
||||
const shiftMonth = (delta: number) => {
|
||||
const next = new Date(selectedYear.value, selectedMonth.value + delta, 1)
|
||||
selectedYear.value = next.getFullYear()
|
||||
selectedMonth.value = next.getMonth()
|
||||
}
|
||||
|
||||
const onMonthPickerValue = (value: string) => {
|
||||
if (!value) return
|
||||
const [yearStr, monthStr] = value.split('-')
|
||||
const year = Number(yearStr)
|
||||
const month = Number(monthStr)
|
||||
if (!Number.isInteger(year) || !Number.isInteger(month) || month < 1 || month > 12) return
|
||||
selectedYear.value = year
|
||||
selectedMonth.value = month - 1
|
||||
}
|
||||
|
||||
// Limite l'intervalle d'impression à 2 mois max.
|
||||
const enforcePrintRange = () => {
|
||||
if (!printForm.from) return
|
||||
@@ -653,6 +691,12 @@ const handlePrint = async () => {
|
||||
if (printForm.siteIds.length > 0) {
|
||||
params.set('sites', printForm.siteIds.join(','))
|
||||
}
|
||||
if (printForm.contractNatures.length > 0) {
|
||||
params.set('contractNatures', printForm.contractNatures.join(','))
|
||||
}
|
||||
if (printForm.workContractIds.length > 0) {
|
||||
params.set('workContracts', printForm.workContractIds.join(','))
|
||||
}
|
||||
await printPdf(`/absences/print?${params.toString()}`)
|
||||
isPrintOpen.value = false
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-primary-500 px-4 py-2 text-md font-semibold text-white hover:bg-secondary-500"
|
||||
@click="isDrawerOpen = true"
|
||||
@click="openCreate"
|
||||
>
|
||||
Ajouter un employé
|
||||
</button>
|
||||
@@ -32,10 +32,11 @@
|
||||
<div v-else class="flex-1 min-h-0 rounded-lg border border-neutral-200 bg-white overflow-hidden">
|
||||
<div class="h-full overflow-auto">
|
||||
<div class="min-w-[900px]">
|
||||
<div class="grid grid-cols-[120px_1fr_1fr_220px_200px] gap-4 border-b border-neutral-200 bg-tertiary-500 px-6 py-3 text-md font-semibold text-neutral-700 sticky top-0 z-10">
|
||||
<div class="grid grid-cols-[120px_1fr_1fr_180px_180px_200px] gap-4 border-b border-neutral-200 bg-tertiary-500 px-6 py-3 text-md font-semibold text-neutral-700 sticky top-0 z-10">
|
||||
<span class="text-left">Prénom</span>
|
||||
<span class="text-left">Nom</span>
|
||||
<span class="text-left">Site</span>
|
||||
<span class="text-left">Nature</span>
|
||||
<span class="text-left">Contrat</span>
|
||||
<span class="text-right">Actions</span>
|
||||
</div>
|
||||
@@ -46,7 +47,7 @@
|
||||
<div
|
||||
v-for="employee in filteredEmployees"
|
||||
:key="employee.id"
|
||||
class="grid grid-cols-[120px_1fr_1fr_220px_200px] items-center gap-4 border-b border-neutral-100 px-6 py-3 text-md text-neutral-800 last:border-b-0"
|
||||
class="grid grid-cols-[120px_1fr_1fr_180px_180px_200px] items-center gap-4 border-b border-neutral-100 px-6 py-3 text-md text-neutral-800 last:border-b-0"
|
||||
>
|
||||
<span>{{ employee.firstName }}</span>
|
||||
<span>{{ employee.lastName }}</span>
|
||||
@@ -57,6 +58,7 @@
|
||||
>
|
||||
{{ employee.site?.name ?? '-' }}
|
||||
</span>
|
||||
<span>{{ contractNatureLabel(employee.currentContractNature) }}</span>
|
||||
<span>{{ employee.contract?.name ?? '-' }}</span>
|
||||
<div class="flex items-center justify-end gap-2">
|
||||
<button
|
||||
@@ -128,24 +130,72 @@
|
||||
Le site est obligatoire.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-md font-semibold text-neutral-700" for="contract">
|
||||
Contrat <span class="text-red-600">*</span>
|
||||
</label>
|
||||
<select
|
||||
id="contract"
|
||||
v-model="form.contractId"
|
||||
:class="contractFieldClass"
|
||||
>
|
||||
<option value="">Sélectionner un contrat</option>
|
||||
<option v-for="contract in contracts" :key="contract.id" :value="contract.id">
|
||||
{{ contract.name }}
|
||||
</option>
|
||||
</select>
|
||||
<p v-if="showContractError" class="mt-1 text-sm text-red-600">
|
||||
Le contrat est obligatoire.
|
||||
</p>
|
||||
</div>
|
||||
<template v-if="!editingEmployee">
|
||||
<div>
|
||||
<label class="text-md font-semibold text-neutral-700" for="contract-nature">
|
||||
Type de contrat <span class="text-red-600">*</span>
|
||||
</label>
|
||||
<select
|
||||
id="contract-nature"
|
||||
v-model="form.contractNature"
|
||||
:class="contractNatureFieldClass"
|
||||
>
|
||||
<option value="CDI">CDI</option>
|
||||
<option value="CDD">CDD</option>
|
||||
<option value="INTERIM">Intérim</option>
|
||||
</select>
|
||||
<p v-if="showContractNatureError" class="mt-1 text-sm text-red-600">
|
||||
Le type de contrat est obligatoire.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-md font-semibold text-neutral-700" for="contract">
|
||||
Temps de travail <span class="text-red-600">*</span>
|
||||
</label>
|
||||
<select
|
||||
id="contract"
|
||||
v-model="form.contractId"
|
||||
:class="contractFieldClass"
|
||||
>
|
||||
<option value="">Sélectionner un contrat</option>
|
||||
<option v-for="contract in contracts" :key="contract.id" :value="contract.id">
|
||||
{{ contract.name }}
|
||||
</option>
|
||||
</select>
|
||||
<p v-if="showContractError" class="mt-1 text-sm text-red-600">
|
||||
Le temps de travail est obligatoire.
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="text-md font-semibold text-neutral-700" for="contract-start-date">
|
||||
Début contrat <span class="text-red-600">*</span>
|
||||
</label>
|
||||
<input
|
||||
id="contract-start-date"
|
||||
v-model="form.contractStartDate"
|
||||
type="date"
|
||||
:class="contractStartDateFieldClass"
|
||||
/>
|
||||
<p v-if="showContractStartDateError" class="mt-1 text-sm text-red-600">
|
||||
La date de début est obligatoire.
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="requiresContractEndDate">
|
||||
<label class="text-md font-semibold text-neutral-700" for="contract-end-date">
|
||||
Fin contrat
|
||||
<span v-if="requiresContractEndDate" class="text-red-600">*</span>
|
||||
</label>
|
||||
<input
|
||||
id="contract-end-date"
|
||||
v-model="form.contractEndDate"
|
||||
type="date"
|
||||
:class="contractEndDateFieldClass"
|
||||
/>
|
||||
<p v-if="showContractEndDateError" class="mt-1 text-sm text-red-600">
|
||||
La date de fin est obligatoire pour un CDD ou un intérim.
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
<div class="flex justify-end gap-3 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
@@ -175,6 +225,9 @@ import { listContracts } from '~/services/contracts'
|
||||
import { createEmployee, deleteEmployee, listEmployees, updateEmployee } from '~/services/employees'
|
||||
import { listSites } from '~/services/sites'
|
||||
import SiteFilterSelector from '~/components/SiteFilterSelector.vue'
|
||||
useHead({
|
||||
title: 'Employés'
|
||||
})
|
||||
|
||||
const isDrawerOpen = ref(false)
|
||||
const isSubmitting = ref(false)
|
||||
@@ -209,26 +262,54 @@ const filteredEmployees = computed(() => {
|
||||
})
|
||||
})
|
||||
|
||||
const contractNatureLabel = (value?: 'CDI' | 'CDD' | 'INTERIM') => {
|
||||
if (value === 'CDD') return 'CDD'
|
||||
if (value === 'INTERIM') return 'Intérim'
|
||||
return 'CDI'
|
||||
}
|
||||
|
||||
const form = reactive({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
siteId: '' as number | '',
|
||||
contractId: '' as number | ''
|
||||
contractId: '' as number | '',
|
||||
contractNature: 'CDI' as 'CDI' | 'CDD' | 'INTERIM',
|
||||
contractStartDate: '',
|
||||
contractEndDate: ''
|
||||
})
|
||||
|
||||
const validationTouched = reactive({
|
||||
firstName: false,
|
||||
lastName: false,
|
||||
siteId: false,
|
||||
contractId: false
|
||||
contractId: false,
|
||||
contractNature: false,
|
||||
contractStartDate: false,
|
||||
contractEndDate: false
|
||||
})
|
||||
|
||||
const isFirstNameValid = computed(() => form.firstName.trim() !== '')
|
||||
const isLastNameValid = computed(() => form.lastName.trim() !== '')
|
||||
const isSiteValid = computed(() => form.siteId !== '')
|
||||
const isContractValid = computed(() => form.contractId !== '')
|
||||
const isContractNatureValid = computed(() => ['CDI', 'CDD', 'INTERIM'].includes(form.contractNature))
|
||||
const isContractStartDateValid = computed(() => form.contractStartDate !== '')
|
||||
const requiresContractEndDate = computed(() => form.contractNature === 'CDD' || form.contractNature === 'INTERIM')
|
||||
const isContractEndDateValid = computed(() => {
|
||||
if (!requiresContractEndDate.value) return true
|
||||
return form.contractEndDate !== ''
|
||||
})
|
||||
const isFormValid = computed(
|
||||
() => isFirstNameValid.value && isLastNameValid.value && isSiteValid.value && isContractValid.value
|
||||
() =>
|
||||
isFirstNameValid.value &&
|
||||
isLastNameValid.value &&
|
||||
isSiteValid.value &&
|
||||
(editingEmployee.value
|
||||
? true
|
||||
: (isContractValid.value &&
|
||||
isContractNatureValid.value &&
|
||||
isContractStartDateValid.value &&
|
||||
isContractEndDateValid.value))
|
||||
)
|
||||
|
||||
const showFirstNameError = computed(
|
||||
@@ -243,6 +324,15 @@ const showSiteError = computed(
|
||||
const showContractError = computed(
|
||||
() => validationTouched.contractId && !isContractValid.value
|
||||
)
|
||||
const showContractNatureError = computed(
|
||||
() => !editingEmployee.value && validationTouched.contractNature && !isContractNatureValid.value
|
||||
)
|
||||
const showContractStartDateError = computed(
|
||||
() => !editingEmployee.value && validationTouched.contractStartDate && !isContractStartDateValid.value
|
||||
)
|
||||
const showContractEndDateError = computed(
|
||||
() => !editingEmployee.value && validationTouched.contractEndDate && !isContractEndDateValid.value
|
||||
)
|
||||
|
||||
const baseInputClass =
|
||||
'mt-2 w-full rounded-md border px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-secondary-500/20'
|
||||
@@ -274,6 +364,26 @@ const contractFieldClass = computed(() => {
|
||||
}
|
||||
return `${baseClass} border-neutral-300`
|
||||
})
|
||||
const contractNatureFieldClass = computed(() => {
|
||||
const baseClass =
|
||||
'mt-2 w-full rounded-md border bg-white px-3 py-2 text-md text-neutral-900'
|
||||
if (showContractNatureError.value) {
|
||||
return `${baseClass} border-red-500`
|
||||
}
|
||||
return `${baseClass} border-neutral-300`
|
||||
})
|
||||
const contractStartDateFieldClass = computed(() => {
|
||||
if (showContractStartDateError.value) {
|
||||
return `${baseInputClass} border-red-500`
|
||||
}
|
||||
return `${baseInputClass} border-neutral-300`
|
||||
})
|
||||
const contractEndDateFieldClass = computed(() => {
|
||||
if (showContractEndDateError.value) {
|
||||
return `${baseInputClass} border-red-500`
|
||||
}
|
||||
return `${baseInputClass} border-neutral-300`
|
||||
})
|
||||
|
||||
const submitButtonClass = computed(() => {
|
||||
if (isSubmitting.value || !isFormValid.value) {
|
||||
@@ -301,6 +411,9 @@ const loadContracts = async () => {
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([loadEmployees(), loadSites(), loadContracts()])
|
||||
if (form.contractStartDate === '') {
|
||||
form.contractStartDate = new Date().toISOString().slice(0, 10)
|
||||
}
|
||||
})
|
||||
|
||||
watch(sites, (nextSites) => {
|
||||
@@ -321,7 +434,12 @@ const handleSubmit = async () => {
|
||||
validationTouched.firstName = true
|
||||
validationTouched.lastName = true
|
||||
validationTouched.siteId = true
|
||||
validationTouched.contractId = true
|
||||
if (!editingEmployee.value) {
|
||||
validationTouched.contractId = true
|
||||
validationTouched.contractNature = true
|
||||
validationTouched.contractStartDate = true
|
||||
validationTouched.contractEndDate = true
|
||||
}
|
||||
if (!isFormValid.value) return
|
||||
|
||||
isSubmitting.value = true
|
||||
@@ -331,14 +449,17 @@ const handleSubmit = async () => {
|
||||
firstName: form.firstName,
|
||||
lastName: form.lastName,
|
||||
siteId: form.siteId === '' ? null : Number(form.siteId),
|
||||
contractId: Number(form.contractId)
|
||||
contractId: editingEmployee.value.contract?.id ?? Number(form.contractId)
|
||||
})
|
||||
} else {
|
||||
await createEmployee({
|
||||
firstName: form.firstName,
|
||||
lastName: form.lastName,
|
||||
siteId: form.siteId === '' ? null : Number(form.siteId),
|
||||
contractId: Number(form.contractId)
|
||||
contractId: Number(form.contractId),
|
||||
contractNature: form.contractNature,
|
||||
contractStartDate: form.contractStartDate,
|
||||
contractEndDate: requiresContractEndDate.value ? form.contractEndDate : null
|
||||
})
|
||||
}
|
||||
|
||||
@@ -346,6 +467,9 @@ const handleSubmit = async () => {
|
||||
form.lastName = ''
|
||||
form.siteId = ''
|
||||
form.contractId = ''
|
||||
form.contractNature = 'CDI'
|
||||
form.contractStartDate = new Date().toISOString().slice(0, 10)
|
||||
form.contractEndDate = ''
|
||||
editingEmployee.value = null
|
||||
isDrawerOpen.value = false
|
||||
await loadEmployees()
|
||||
@@ -360,6 +484,15 @@ watch(isDrawerOpen, (isOpen) => {
|
||||
validationTouched.lastName = false
|
||||
validationTouched.siteId = false
|
||||
validationTouched.contractId = false
|
||||
validationTouched.contractNature = false
|
||||
validationTouched.contractStartDate = false
|
||||
validationTouched.contractEndDate = false
|
||||
}
|
||||
})
|
||||
|
||||
watch(requiresContractEndDate, (required) => {
|
||||
if (!required) {
|
||||
form.contractEndDate = ''
|
||||
}
|
||||
})
|
||||
|
||||
@@ -368,7 +501,18 @@ const openEdit = (employee: Employee) => {
|
||||
form.firstName = employee.firstName
|
||||
form.lastName = employee.lastName
|
||||
form.siteId = employee.site?.id ?? ''
|
||||
form.contractId = employee.contract?.id ?? ''
|
||||
isDrawerOpen.value = true
|
||||
}
|
||||
|
||||
const openCreate = () => {
|
||||
editingEmployee.value = null
|
||||
form.firstName = ''
|
||||
form.lastName = ''
|
||||
form.siteId = ''
|
||||
form.contractId = ''
|
||||
form.contractNature = 'CDI'
|
||||
form.contractStartDate = new Date().toISOString().slice(0, 10)
|
||||
form.contractEndDate = ''
|
||||
isDrawerOpen.value = true
|
||||
}
|
||||
|
||||
|
||||
@@ -33,32 +33,43 @@
|
||||
Aucun employé accessible.
|
||||
</div>
|
||||
|
||||
<div v-else class="flex flex-1 min-h-0 flex-col gap-4">
|
||||
<div class="flex-1 min-h-0 flex flex-col">
|
||||
<div v-else class="flex min-h-0 flex-col gap-4">
|
||||
<div class="min-h-0 flex flex-col max-h-[calc(100vh-300px)]">
|
||||
<HoursDayView
|
||||
v-if="viewMode === 'day'"
|
||||
v-model:rows="rows"
|
||||
:employees="visibleEmployees"
|
||||
:is-admin="isAdmin"
|
||||
:is-site-manager="isSiteManager"
|
||||
:day-grid-cols="dayGridCols"
|
||||
:is-holiday="isSelectedDateHoliday"
|
||||
:contract-label="contractLabel"
|
||||
:is-time-tracking="isTimeTracking"
|
||||
:is-presence-tracking="isPresenceTracking"
|
||||
:is-row-locked="isRowLocked"
|
||||
:is-half-locked-by-absence="isHalfLockedByAbsence"
|
||||
:is-evening-locked-by-absence="isEveningLockedByAbsence"
|
||||
:has-contract-at-selected-date="hasContractAtSelectedDate"
|
||||
:is-validation-pending="isValidationPending"
|
||||
:is-site-validation-pending="isSiteValidationPending"
|
||||
:can-toggle-validation="canToggleValidation"
|
||||
:can-toggle-site-validation="canToggleSiteValidation"
|
||||
:is-bulk-validation-checked="isBulkValidationChecked"
|
||||
:is-bulk-validation-indeterminate="isBulkValidationIndeterminate"
|
||||
:is-bulk-site-validation-checked="isBulkSiteValidationChecked"
|
||||
:is-bulk-site-validation-indeterminate="isBulkSiteValidationIndeterminate"
|
||||
:can-bulk-toggle-site-validation="canBulkToggleSiteValidation"
|
||||
:on-toggle-validation="toggleValidation"
|
||||
:on-toggle-site-validation="toggleSiteValidation"
|
||||
:on-toggle-validation-bulk="toggleValidationBulk"
|
||||
:on-toggle-site-validation-bulk="toggleSiteValidationBulk"
|
||||
:get-row-metrics="getRowMetrics"
|
||||
:get-row-absence-label="getRowAbsenceLabel"
|
||||
:get-row-absence-style="getRowAbsenceStyle"
|
||||
:get-presence-day-value="getPresenceDayValue"
|
||||
:on-absence-click="openAbsenceDrawer"
|
||||
:format-minutes="formatMinutes"
|
||||
class="max-h-full"
|
||||
class="max-h-[calc(100vh-300px)]"
|
||||
/>
|
||||
|
||||
<HoursWeekView
|
||||
@@ -68,7 +79,7 @@
|
||||
:weekly-summary="filteredWeeklySummary"
|
||||
:week-day-headers="weekDayHeaders"
|
||||
:format-minutes="formatMinutes"
|
||||
class="max-h-full"
|
||||
class="max-h-[calc(100vh-300px)]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -105,6 +116,7 @@
|
||||
<script setup lang="ts">
|
||||
const {
|
||||
isAdmin,
|
||||
isSiteManager,
|
||||
viewMode,
|
||||
selectedDate,
|
||||
employeeFilter,
|
||||
@@ -123,6 +135,7 @@ const {
|
||||
isWeekLoading,
|
||||
isSubmitting,
|
||||
dayGridCols,
|
||||
isSelectedDateHoliday,
|
||||
weekGridCols,
|
||||
saveButtonClass,
|
||||
formattedSelectedDate,
|
||||
@@ -143,14 +156,23 @@ const {
|
||||
isRowLocked,
|
||||
isHalfLockedByAbsence,
|
||||
isEveningLockedByAbsence,
|
||||
hasContractAtSelectedDate,
|
||||
isValidationPending,
|
||||
isSiteValidationPending,
|
||||
canToggleValidation,
|
||||
canToggleSiteValidation,
|
||||
isBulkValidationChecked,
|
||||
isBulkValidationIndeterminate,
|
||||
isBulkSiteValidationChecked,
|
||||
isBulkSiteValidationIndeterminate,
|
||||
canBulkToggleSiteValidation,
|
||||
toggleValidation,
|
||||
toggleSiteValidation,
|
||||
toggleValidationBulk,
|
||||
toggleSiteValidationBulk,
|
||||
getRowMetrics,
|
||||
getRowAbsenceLabel,
|
||||
getRowAbsenceStyle,
|
||||
getPresenceDayValue,
|
||||
openAbsenceDrawer,
|
||||
submitAbsence,
|
||||
@@ -159,4 +181,8 @@ const {
|
||||
formatMinutes,
|
||||
handleSave
|
||||
} = useHoursPage()
|
||||
|
||||
useHead({
|
||||
title: 'Heures'
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -3,5 +3,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
useHead({
|
||||
title: 'Tableau de bord'
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -49,6 +49,9 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
definePageMeta({layout: 'auth'})
|
||||
useHead({
|
||||
title: 'Connexion'
|
||||
})
|
||||
|
||||
const router = useRouter()
|
||||
const auth = useAuthStore()
|
||||
|
||||
@@ -123,6 +123,10 @@
|
||||
import type { Site } from '~/services/dto/site'
|
||||
import { createSite, deleteSite, listSites, updateSite, updateSiteOrder } from '~/services/sites'
|
||||
|
||||
useHead({
|
||||
title: 'Sites'
|
||||
})
|
||||
|
||||
const isDrawerOpen = ref(false)
|
||||
const isSubmitting = ref(false)
|
||||
const isLoading = ref(false)
|
||||
|
||||
@@ -209,6 +209,9 @@ import { createUser, listUsers, updateUser } from '~/services/users'
|
||||
import { createUserSiteRole, deleteUserSiteRole, listUserSiteRoles } from '~/services/user-site-roles'
|
||||
|
||||
definePageMeta({ middleware: ['admin'] })
|
||||
useHead({
|
||||
title: 'Utilisateurs'
|
||||
})
|
||||
|
||||
const users = ref<User[]>([])
|
||||
const employees = ref<Employee[]>([])
|
||||
|
||||
@@ -7,5 +7,8 @@ export type Employee = {
|
||||
lastName: string
|
||||
site: Site
|
||||
contract?: Contract | null
|
||||
currentContractNature?: 'CDI' | 'CDD' | 'INTERIM'
|
||||
currentContractStartDate?: string | null
|
||||
currentContractEndDate?: string | null
|
||||
displayOrder?: number
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ export type WorkHour = {
|
||||
eveningTo?: string | null
|
||||
isPresentMorning?: boolean
|
||||
isPresentAfternoon?: boolean
|
||||
isSiteValid?: boolean
|
||||
isValid?: boolean
|
||||
}
|
||||
|
||||
@@ -67,7 +68,9 @@ export type WeeklyWorkHourSummary = {
|
||||
|
||||
export type WorkHourDayContextRow = {
|
||||
employeeId: number
|
||||
hasContractAtDate: boolean
|
||||
absenceLabel?: string | null
|
||||
absenceColor?: string | null
|
||||
absenceHalf?: 'AM' | 'PM' | null
|
||||
absentMorning: boolean
|
||||
absentAfternoon: boolean
|
||||
|
||||
@@ -26,13 +26,19 @@ export const createEmployee = async (payload: {
|
||||
lastName: string
|
||||
siteId?: number | null
|
||||
contractId: number
|
||||
contractNature?: 'CDI' | 'CDD' | 'INTERIM'
|
||||
contractStartDate?: string
|
||||
contractEndDate?: string | null
|
||||
}) => {
|
||||
const api = useApi()
|
||||
return api.post<Employee>('/employees', {
|
||||
firstName: payload.firstName,
|
||||
lastName: payload.lastName,
|
||||
site: payload.siteId ? `/api/sites/${payload.siteId}` : null,
|
||||
contract: `/api/contracts/${payload.contractId}`
|
||||
contract: `/api/contracts/${payload.contractId}`,
|
||||
contractNature: payload.contractNature,
|
||||
contractStartDate: payload.contractStartDate,
|
||||
contractEndDate: payload.contractEndDate ?? null
|
||||
}, {
|
||||
toastSuccessKey: 'success.employee.create',
|
||||
toastErrorKey: 'errors.employee.create'
|
||||
@@ -46,6 +52,9 @@ export const updateEmployee = async (
|
||||
lastName: string
|
||||
siteId?: number | null
|
||||
contractId: number
|
||||
contractNature?: 'CDI' | 'CDD' | 'INTERIM'
|
||||
contractStartDate?: string
|
||||
contractEndDate?: string | null
|
||||
displayOrder?: number
|
||||
}
|
||||
) => {
|
||||
@@ -55,6 +64,9 @@ export const updateEmployee = async (
|
||||
lastName: payload.lastName,
|
||||
site: payload.siteId ? `/api/sites/${payload.siteId}` : null,
|
||||
contract: `/api/contracts/${payload.contractId}`,
|
||||
contractNature: payload.contractNature,
|
||||
contractStartDate: payload.contractStartDate,
|
||||
contractEndDate: payload.contractEndDate ?? null,
|
||||
displayOrder: payload.displayOrder
|
||||
}, {
|
||||
toastSuccessKey: 'success.employee.update',
|
||||
|
||||
@@ -23,7 +23,7 @@ export const listWorkHoursByDate = async (workDate: string) => {
|
||||
export const bulkUpsertWorkHours = async (payload: {
|
||||
workDate: string
|
||||
entries: WorkHourEntryPayload[]
|
||||
}) => {
|
||||
}, options?: { toast?: boolean }) => {
|
||||
const api = useApi()
|
||||
return api.post<{
|
||||
processed: number
|
||||
@@ -34,6 +34,7 @@ export const bulkUpsertWorkHours = async (payload: {
|
||||
'/work-hours/bulk-upsert',
|
||||
payload,
|
||||
{
|
||||
toast: options?.toast ?? true,
|
||||
toastSuccessMessage: 'Horaires enregistrés.',
|
||||
toastErrorMessage: "Impossible d'enregistrer les horaires."
|
||||
}
|
||||
@@ -57,6 +58,69 @@ export const updateWorkHourValidation = async (
|
||||
)
|
||||
}
|
||||
|
||||
export const bulkUpdateWorkHourValidation = async (payload: {
|
||||
workDate: string
|
||||
isValid: boolean
|
||||
employeeIds: number[]
|
||||
}, options?: { toast?: boolean }) => {
|
||||
const api = useApi()
|
||||
return api.post<{
|
||||
requested: number
|
||||
updated: number
|
||||
skipped: number
|
||||
updatedEmployeeIds: number[]
|
||||
skippedEmployeeIds: number[]
|
||||
}>(
|
||||
'/work-hours/bulk-validation',
|
||||
payload,
|
||||
{
|
||||
toast: options?.toast ?? true,
|
||||
toastSuccessMessage: payload.isValid ? 'Validations enregistrées.' : 'Validations retirées.',
|
||||
toastErrorMessage: "Impossible de mettre à jour les validations."
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export const updateWorkHourSiteValidation = async (
|
||||
id: number,
|
||||
isSiteValid: boolean,
|
||||
options?: { toast?: boolean }
|
||||
) => {
|
||||
const api = useApi()
|
||||
return api.patch<WorkHour>(
|
||||
`/work_hours/${id}/site-validation`,
|
||||
{ isSiteValid },
|
||||
{
|
||||
toast: options?.toast ?? true,
|
||||
toastSuccessMessage: isSiteValid ? 'Validation site enregistrée.' : 'Validation site retirée.',
|
||||
toastErrorMessage: "Impossible de mettre à jour la validation site."
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export const bulkUpdateWorkHourSiteValidation = async (payload: {
|
||||
workDate: string
|
||||
isSiteValid: boolean
|
||||
employeeIds: number[]
|
||||
}, options?: { toast?: boolean }) => {
|
||||
const api = useApi()
|
||||
return api.post<{
|
||||
requested: number
|
||||
updated: number
|
||||
skipped: number
|
||||
updatedEmployeeIds: number[]
|
||||
skippedEmployeeIds: number[]
|
||||
}>(
|
||||
'/work-hours/site-bulk-validation',
|
||||
payload,
|
||||
{
|
||||
toast: options?.toast ?? true,
|
||||
toastSuccessMessage: payload.isSiteValid ? 'Validations site enregistrées.' : 'Validations site retirées.',
|
||||
toastErrorMessage: "Impossible de mettre à jour les validations site."
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export const getWeeklyWorkHourSummary = async (weekStart: string) => {
|
||||
const api = useApi()
|
||||
return api.get<WeeklyWorkHourSummary>(
|
||||
|
||||
26
migrations/Version20260226183000.php
Normal file
26
migrations/Version20260226183000.php
Normal file
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
final class Version20260226183000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add site validation flag to work hours';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE work_hours ADD is_site_valid BOOLEAN DEFAULT FALSE NOT NULL');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE work_hours DROP is_site_valid');
|
||||
}
|
||||
}
|
||||
33
migrations/Version20260226203000.php
Normal file
33
migrations/Version20260226203000.php
Normal file
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
final class Version20260226203000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add contract nature to employee contract periods';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql("ALTER TABLE employee_contract_periods ADD contract_nature VARCHAR(20) DEFAULT 'CDI' NOT NULL");
|
||||
$this->addSql("
|
||||
UPDATE employee_contract_periods p
|
||||
SET contract_nature = 'INTERIM'
|
||||
FROM contracts c
|
||||
WHERE p.contract_id = c.id
|
||||
AND LOWER(c.name) LIKE '%interim%'
|
||||
");
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE employee_contract_periods DROP contract_nature');
|
||||
}
|
||||
}
|
||||
82
migrations/Version20260226210000.php
Normal file
82
migrations/Version20260226210000.php
Normal file
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
use Doctrine\Migrations\Exception\IrreversibleMigration;
|
||||
|
||||
final class Version20260226210000 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Reassign legacy INTERIM contract to a TIME 35h contract and remove legacy INTERIM contract row';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql(
|
||||
<<<'SQL'
|
||||
DO $$
|
||||
DECLARE
|
||||
legacy_interim_contract_id INT;
|
||||
target_time_35h_contract_id INT;
|
||||
BEGIN
|
||||
-- Contrat legacy "Intérim" (ancien modèle).
|
||||
SELECT c.id
|
||||
INTO legacy_interim_contract_id
|
||||
FROM contracts c
|
||||
WHERE LOWER(c.name) LIKE '%interim%'
|
||||
ORDER BY c.id
|
||||
LIMIT 1;
|
||||
|
||||
-- Si déjà supprimé, on ne fait rien.
|
||||
IF legacy_interim_contract_id IS NULL THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- Contrat cible: suivi horaire 35h.
|
||||
SELECT c.id
|
||||
INTO target_time_35h_contract_id
|
||||
FROM contracts c
|
||||
WHERE c.tracking_mode = 'TIME'
|
||||
AND c.weekly_hours = 35
|
||||
AND c.id <> legacy_interim_contract_id
|
||||
ORDER BY
|
||||
CASE WHEN LOWER(c.name) = '35h' THEN 0 ELSE 1 END,
|
||||
c.id
|
||||
LIMIT 1;
|
||||
|
||||
IF target_time_35h_contract_id IS NULL THEN
|
||||
RAISE EXCEPTION 'No TIME 35h contract found to replace legacy INTERIM contract id=%', legacy_interim_contract_id;
|
||||
END IF;
|
||||
|
||||
-- Ré-assigne l'historique de périodes.
|
||||
UPDATE employee_contract_periods
|
||||
SET contract_id = target_time_35h_contract_id
|
||||
WHERE contract_id = legacy_interim_contract_id;
|
||||
|
||||
-- Ré-assigne le pointeur actuel employé (compat legacy / affichage).
|
||||
UPDATE employees
|
||||
SET contract_id = target_time_35h_contract_id
|
||||
WHERE contract_id = legacy_interim_contract_id;
|
||||
|
||||
-- Garde-fou FK avant suppression.
|
||||
IF EXISTS (SELECT 1 FROM employee_contract_periods p WHERE p.contract_id = legacy_interim_contract_id)
|
||||
OR EXISTS (SELECT 1 FROM employees e WHERE e.contract_id = legacy_interim_contract_id) THEN
|
||||
RAISE EXCEPTION 'Legacy INTERIM contract id=% is still referenced', legacy_interim_contract_id;
|
||||
END IF;
|
||||
|
||||
DELETE FROM contracts WHERE id = legacy_interim_contract_id;
|
||||
END $$;
|
||||
SQL
|
||||
);
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
throw new IrreversibleMigration('This migration performs data reassignment and contract deletion.');
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,8 @@ use App\State\AbsencePrintProvider;
|
||||
new QueryParameter(key: 'from', required: true),
|
||||
new QueryParameter(key: 'to', required: true),
|
||||
new QueryParameter(key: 'sites', required: false),
|
||||
new QueryParameter(key: 'contractNatures', required: false),
|
||||
new QueryParameter(key: 'workContracts', required: false),
|
||||
],
|
||||
security: "is_granted('ROLE_ADMIN')"
|
||||
),
|
||||
|
||||
31
src/ApiResource/WorkHourBulkSiteValidation.php
Normal file
31
src/ApiResource/WorkHourBulkSiteValidation.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\ApiResource;
|
||||
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Post;
|
||||
use App\State\WorkHourBulkSiteValidationProcessor;
|
||||
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new Post(
|
||||
uriTemplate: '/work-hours/site-bulk-validation',
|
||||
security: "is_granted('ROLE_USER')",
|
||||
output: WorkHourBulkValidationResult::class,
|
||||
processor: WorkHourBulkSiteValidationProcessor::class
|
||||
),
|
||||
]
|
||||
)]
|
||||
final class WorkHourBulkSiteValidation
|
||||
{
|
||||
public string $workDate = '';
|
||||
|
||||
public bool $isSiteValid = false;
|
||||
|
||||
/**
|
||||
* @var list<int>
|
||||
*/
|
||||
public array $employeeIds = [];
|
||||
}
|
||||
31
src/ApiResource/WorkHourBulkValidation.php
Normal file
31
src/ApiResource/WorkHourBulkValidation.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\ApiResource;
|
||||
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use ApiPlatform\Metadata\Post;
|
||||
use App\State\WorkHourBulkValidationProcessor;
|
||||
|
||||
#[ApiResource(
|
||||
operations: [
|
||||
new Post(
|
||||
uriTemplate: '/work-hours/bulk-validation',
|
||||
security: "is_granted('ROLE_ADMIN')",
|
||||
output: WorkHourBulkValidationResult::class,
|
||||
processor: WorkHourBulkValidationProcessor::class
|
||||
),
|
||||
]
|
||||
)]
|
||||
final class WorkHourBulkValidation
|
||||
{
|
||||
public string $workDate = '';
|
||||
|
||||
public bool $isValid = false;
|
||||
|
||||
/**
|
||||
* @var list<int>
|
||||
*/
|
||||
public array $employeeIds = [];
|
||||
}
|
||||
22
src/ApiResource/WorkHourBulkValidationResult.php
Normal file
22
src/ApiResource/WorkHourBulkValidationResult.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\ApiResource;
|
||||
|
||||
final class WorkHourBulkValidationResult
|
||||
{
|
||||
public int $requested = 0;
|
||||
public int $updated = 0;
|
||||
public int $skipped = 0;
|
||||
|
||||
/**
|
||||
* @var list<int>
|
||||
*/
|
||||
public array $updatedEmployeeIds = [];
|
||||
|
||||
/**
|
||||
* @var list<int>
|
||||
*/
|
||||
public array $skippedEmployeeIds = [];
|
||||
}
|
||||
@@ -26,6 +26,7 @@ final class WorkHourDayContext
|
||||
* @var list<array{
|
||||
* employeeId:int,
|
||||
* absenceLabel:?string,
|
||||
* absenceColor:?string,
|
||||
* absenceHalf:?string,
|
||||
* absentMorning:bool,
|
||||
* absentAfternoon:bool,
|
||||
|
||||
@@ -8,7 +8,9 @@ final class DayContextRow
|
||||
{
|
||||
public function __construct(
|
||||
public int $employeeId,
|
||||
public bool $hasContractAtDate = true,
|
||||
public ?string $absenceLabel = null,
|
||||
public ?string $absenceColor = null,
|
||||
public ?string $absenceHalf = null,
|
||||
public bool $absentMorning = false,
|
||||
public bool $absentAfternoon = false,
|
||||
@@ -18,6 +20,7 @@ final class DayContextRow
|
||||
|
||||
public function addAbsence(
|
||||
?string $label,
|
||||
?string $color,
|
||||
bool $morning,
|
||||
bool $afternoon,
|
||||
int $creditedMinutes,
|
||||
@@ -34,6 +37,14 @@ final class DayContextRow
|
||||
$this->absenceLabel = 'Absences multiples';
|
||||
}
|
||||
|
||||
// Si plusieurs types d'absence différents sont fusionnés sur la même journée,
|
||||
// on retire la couleur métier spécifique.
|
||||
if (null === $this->absenceColor) {
|
||||
$this->absenceColor = $color;
|
||||
} elseif ($color !== $this->absenceColor) {
|
||||
$this->absenceColor = null;
|
||||
}
|
||||
|
||||
// AM/PM seulement pour les demi-journées, null pour journée complète.
|
||||
$this->absenceHalf = $this->resolveHalfLabel($this->absentMorning, $this->absentAfternoon);
|
||||
// Cumule les minutes créditées par les absences "comptées comme travaillées".
|
||||
@@ -45,7 +56,9 @@ final class DayContextRow
|
||||
/**
|
||||
* @return array{
|
||||
* employeeId:int,
|
||||
* hasContractAtDate:bool,
|
||||
* absenceLabel:?string,
|
||||
* absenceColor:?string,
|
||||
* absenceHalf:?string,
|
||||
* absentMorning:bool,
|
||||
* absentAfternoon:bool,
|
||||
@@ -57,7 +70,9 @@ final class DayContextRow
|
||||
{
|
||||
return [
|
||||
'employeeId' => $this->employeeId,
|
||||
'hasContractAtDate' => $this->hasContractAtDate,
|
||||
'absenceLabel' => $this->absenceLabel,
|
||||
'absenceColor' => $this->absenceColor,
|
||||
'absenceHalf' => $this->absenceHalf,
|
||||
'absentMorning' => $this->absentMorning,
|
||||
'absentAfternoon' => $this->absentAfternoon,
|
||||
|
||||
@@ -6,9 +6,12 @@ namespace App\Entity;
|
||||
|
||||
use ApiPlatform\Metadata\ApiProperty;
|
||||
use ApiPlatform\Metadata\ApiResource;
|
||||
use App\Enum\ContractNature;
|
||||
use App\Repository\EmployeeRepository;
|
||||
use App\State\EmployeeWriteProcessor;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
|
||||
@@ -56,9 +59,25 @@ class Employee
|
||||
#[ORM\Column(type: 'datetime_immutable')]
|
||||
private DateTimeImmutable $createdAt;
|
||||
|
||||
/**
|
||||
* @var Collection<int, EmployeeContractPeriod>
|
||||
*/
|
||||
#[ORM\OneToMany(mappedBy: 'employee', targetEntity: EmployeeContractPeriod::class)]
|
||||
private Collection $contractPeriods;
|
||||
|
||||
#[Groups(['employee:write'])]
|
||||
private ?string $contractNature = null;
|
||||
|
||||
#[Groups(['employee:write'])]
|
||||
private ?string $contractStartDate = null;
|
||||
|
||||
#[Groups(['employee:write'])]
|
||||
private ?string $contractEndDate = null;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->createdAt = new DateTimeImmutable();
|
||||
$this->createdAt = new DateTimeImmutable();
|
||||
$this->contractPeriods = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function getId(): ?int
|
||||
@@ -130,4 +149,81 @@ class Employee
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getContractNature(): ?string
|
||||
{
|
||||
return $this->contractNature;
|
||||
}
|
||||
|
||||
public function setContractNature(?string $contractNature): self
|
||||
{
|
||||
$this->contractNature = $contractNature;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getContractStartDate(): ?string
|
||||
{
|
||||
return $this->contractStartDate;
|
||||
}
|
||||
|
||||
public function setContractStartDate(?string $contractStartDate): self
|
||||
{
|
||||
$this->contractStartDate = $contractStartDate;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getContractEndDate(): ?string
|
||||
{
|
||||
return $this->contractEndDate;
|
||||
}
|
||||
|
||||
public function setContractEndDate(?string $contractEndDate): self
|
||||
{
|
||||
$this->contractEndDate = $contractEndDate;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
#[Groups(['employee:read'])]
|
||||
public function getCurrentContractNature(): string
|
||||
{
|
||||
return $this->resolveCurrentContractPeriod()?->getContractNatureEnum()->value ?? ContractNature::CDI->value;
|
||||
}
|
||||
|
||||
#[Groups(['employee:read'])]
|
||||
public function getCurrentContractStartDate(): ?string
|
||||
{
|
||||
return $this->resolveCurrentContractPeriod()?->getStartDate()->format('Y-m-d');
|
||||
}
|
||||
|
||||
#[Groups(['employee:read'])]
|
||||
public function getCurrentContractEndDate(): ?string
|
||||
{
|
||||
return $this->resolveCurrentContractPeriod()?->getEndDate()?->format('Y-m-d');
|
||||
}
|
||||
|
||||
private function resolveCurrentContractPeriod(): ?EmployeeContractPeriod
|
||||
{
|
||||
$today = new DateTimeImmutable('today');
|
||||
$current = null;
|
||||
|
||||
foreach ($this->contractPeriods as $period) {
|
||||
if ($period->getStartDate() > $today) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$endDate = $period->getEndDate();
|
||||
if (null !== $endDate && $endDate < $today) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (null === $current || $period->getStartDate() > $current->getStartDate()) {
|
||||
$current = $period;
|
||||
}
|
||||
}
|
||||
|
||||
return $current;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use App\Enum\ContractNature;
|
||||
use App\Repository\EmployeeContractPeriodRepository;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
@@ -19,7 +20,7 @@ class EmployeeContractPeriod
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Employee::class)]
|
||||
#[ORM\ManyToOne(targetEntity: Employee::class, inversedBy: 'contractPeriods')]
|
||||
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
|
||||
private ?Employee $employee = null;
|
||||
|
||||
@@ -33,6 +34,9 @@ class EmployeeContractPeriod
|
||||
#[ORM\Column(type: 'date_immutable', nullable: true)]
|
||||
private ?DateTimeImmutable $endDate = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 20, options: ['default' => ContractNature::CDI->value])]
|
||||
private string $contractNature = ContractNature::CDI->value;
|
||||
|
||||
#[ORM\Column(type: 'datetime_immutable')]
|
||||
private DateTimeImmutable $createdAt;
|
||||
|
||||
@@ -95,6 +99,24 @@ class EmployeeContractPeriod
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getContractNature(): string
|
||||
{
|
||||
return $this->contractNature;
|
||||
}
|
||||
|
||||
public function getContractNatureEnum(): ContractNature
|
||||
{
|
||||
return ContractNature::tryFrom($this->contractNature) ?? ContractNature::CDI;
|
||||
}
|
||||
|
||||
public function setContractNature(ContractNature|string $contractNature): self
|
||||
{
|
||||
$value = $contractNature instanceof ContractNature ? $contractNature->value : $contractNature;
|
||||
$this->contractNature = ContractNature::tryFrom($value)?->value ?? ContractNature::CDI->value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCreatedAt(): DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
|
||||
@@ -13,6 +13,7 @@ use ApiPlatform\Metadata\Get;
|
||||
use ApiPlatform\Metadata\GetCollection;
|
||||
use ApiPlatform\Metadata\Patch;
|
||||
use App\Repository\WorkHourRepository;
|
||||
use App\State\WorkHourSiteValidationProcessor;
|
||||
use DateTimeInterface;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Serializer\Attribute\Groups;
|
||||
@@ -33,6 +34,13 @@ use Symfony\Component\Serializer\Attribute\Groups;
|
||||
denormalizationContext: ['groups' => ['work_hour:validate']],
|
||||
security: "is_granted('ROLE_ADMIN')"
|
||||
),
|
||||
new Patch(
|
||||
uriTemplate: '/work_hours/{id}/site-validation',
|
||||
normalizationContext: ['groups' => ['work_hour:read', 'employee:read', 'site:read']],
|
||||
denormalizationContext: ['groups' => ['work_hour:site_validate']],
|
||||
security: "is_granted('ROLE_USER')",
|
||||
processor: WorkHourSiteValidationProcessor::class
|
||||
),
|
||||
],
|
||||
)]
|
||||
#[ApiFilter(DateFilter::class, properties: ['workDate'])]
|
||||
@@ -94,6 +102,10 @@ class WorkHour
|
||||
#[Groups(['work_hour:read', 'work_hour:validate'])]
|
||||
private bool $isValid = false;
|
||||
|
||||
#[ORM\Column(type: 'boolean', options: ['default' => false])]
|
||||
#[Groups(['work_hour:read', 'work_hour:site_validate'])]
|
||||
private bool $isSiteValid = false;
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
@@ -245,4 +257,21 @@ class WorkHour
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function isSiteValid(): bool
|
||||
{
|
||||
return $this->isSiteValid;
|
||||
}
|
||||
|
||||
public function getIsSiteValid(): bool
|
||||
{
|
||||
return $this->isSiteValid;
|
||||
}
|
||||
|
||||
public function setIsSiteValid(bool $isSiteValid): self
|
||||
{
|
||||
$this->isSiteValid = $isSiteValid;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
||||
17
src/Enum/ContractNature.php
Normal file
17
src/Enum/ContractNature.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enum;
|
||||
|
||||
enum ContractNature: string
|
||||
{
|
||||
case CDI = 'CDI';
|
||||
case CDD = 'CDD';
|
||||
case INTERIM = 'INTERIM';
|
||||
|
||||
public function requiresEndDate(): bool
|
||||
{
|
||||
return self::CDD === $this || self::INTERIM === $this;
|
||||
}
|
||||
}
|
||||
@@ -21,4 +21,6 @@ interface WorkHourReadRepositoryInterface
|
||||
public function findOneByEmployeeAndDate(Employee $employee, DateTimeInterface $date): ?WorkHour;
|
||||
|
||||
public function hasValidatedInRange(Employee $employee, DateTimeInterface $from, DateTimeInterface $to): bool;
|
||||
|
||||
public function hasSiteValidatedInRange(Employee $employee, DateTimeInterface $from, DateTimeInterface $to): bool;
|
||||
}
|
||||
|
||||
@@ -85,6 +85,8 @@ final class EmployeeRepository extends ServiceEntityRepository implements Employ
|
||||
$qb = $this->createQueryBuilder('e')
|
||||
->leftJoin('e.site', 's')
|
||||
->addSelect('s')
|
||||
->leftJoin('e.contract', 'c')
|
||||
->addSelect('c')
|
||||
->orderBy('s.displayOrder', 'ASC')
|
||||
->addOrderBy('s.name', 'ASC')
|
||||
->addOrderBy('e.displayOrder', 'ASC')
|
||||
|
||||
@@ -102,6 +102,26 @@ final class WorkHourRepository extends ServiceEntityRepository implements WorkHo
|
||||
return ((int) $qb->getQuery()->getSingleScalarResult()) > 0;
|
||||
}
|
||||
|
||||
public function hasSiteValidatedInRange(Employee $employee, DateTimeInterface $from, DateTimeInterface $to): bool
|
||||
{
|
||||
$fromDate = DateTimeImmutable::createFromInterface($from);
|
||||
$toDate = DateTimeImmutable::createFromInterface($to);
|
||||
|
||||
$qb = $this->createQueryBuilder('w')
|
||||
->select('COUNT(w.id)')
|
||||
->andWhere('w.employee = :employee')
|
||||
->andWhere('w.workDate >= :from')
|
||||
->andWhere('w.workDate <= :to')
|
||||
->andWhere('w.isSiteValid = :isSiteValid')
|
||||
->setParameter('employee', $employee)
|
||||
->setParameter('from', $fromDate)
|
||||
->setParameter('to', $toDate)
|
||||
->setParameter('isSiteValid', true)
|
||||
;
|
||||
|
||||
return ((int) $qb->getQuery()->getSingleScalarResult()) > 0;
|
||||
}
|
||||
|
||||
public function findOneByEmployeeAndDate(Employee $employee, DateTimeInterface $date): ?WorkHour
|
||||
{
|
||||
$workDate = DateTimeImmutable::createFromInterface($date);
|
||||
@@ -114,7 +134,7 @@ final class WorkHourRepository extends ServiceEntityRepository implements WorkHo
|
||||
->setMaxResults(1)
|
||||
;
|
||||
|
||||
/** @var null|WorkHour $workHour */
|
||||
// @var null|WorkHour $workHour
|
||||
return $qb->getQuery()->getOneOrNullResult();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,9 @@ namespace App\Service\Contracts;
|
||||
|
||||
use App\Entity\Contract;
|
||||
use App\Entity\Employee;
|
||||
use App\Enum\ContractNature;
|
||||
use App\Repository\EmployeeContractPeriodRepository;
|
||||
use DateTimeImmutable;
|
||||
use LogicException;
|
||||
|
||||
readonly class EmployeeContractResolver
|
||||
{
|
||||
@@ -18,17 +18,16 @@ readonly class EmployeeContractResolver
|
||||
|
||||
public function resolveForEmployeeAndDate(Employee $employee, DateTimeImmutable $date): ?Contract
|
||||
{
|
||||
$period = $this->periodRepository->findOneCoveringDate($employee, $date);
|
||||
$contract = $period?->getContract();
|
||||
if (null === $contract) {
|
||||
throw new LogicException(sprintf(
|
||||
'Missing contract period for employee %d on %s.',
|
||||
$employee->getId() ?? 0,
|
||||
$date->format('Y-m-d')
|
||||
));
|
||||
}
|
||||
$period = $this->periodRepository->findOneCoveringDate($employee, $date);
|
||||
|
||||
return $contract;
|
||||
return $period?->getContract();
|
||||
}
|
||||
|
||||
public function resolveNatureForEmployeeAndDate(Employee $employee, DateTimeImmutable $date): ContractNature
|
||||
{
|
||||
$period = $this->periodRepository->findOneCoveringDate($employee, $date);
|
||||
|
||||
return $period?->getContractNatureEnum() ?? ContractNature::CDI;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,6 +74,22 @@ readonly class EmployeeContractResolver
|
||||
}
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<Employee> $employees
|
||||
* @param list<string> $days
|
||||
*
|
||||
* @return array<int, array<string, ContractNature>>
|
||||
*/
|
||||
public function resolveNaturesForEmployeesAndDays(array $employees, array $days): array
|
||||
{
|
||||
$resolved = [];
|
||||
if ([] === $employees || [] === $days) {
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
foreach ($employees as $employee) {
|
||||
$employeeId = $employee->getId();
|
||||
if (!$employeeId) {
|
||||
@@ -82,13 +97,27 @@ readonly class EmployeeContractResolver
|
||||
}
|
||||
|
||||
foreach ($days as $day) {
|
||||
if (null === ($resolved[$employeeId][$day] ?? null)) {
|
||||
throw new LogicException(sprintf(
|
||||
'Missing contract period for employee %d on %s.',
|
||||
$employeeId,
|
||||
$day
|
||||
));
|
||||
$resolved[$employeeId][$day] = ContractNature::CDI;
|
||||
}
|
||||
}
|
||||
|
||||
$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;
|
||||
}
|
||||
|
||||
$start = $period->getStartDate()->format('Y-m-d');
|
||||
$end = $period->getEndDate()?->format('Y-m-d') ?? '9999-12-31';
|
||||
$nature = $period->getContractNatureEnum();
|
||||
foreach ($days as $day) {
|
||||
if ($day < $start || $day > $end) {
|
||||
continue;
|
||||
}
|
||||
$resolved[$employeeId][$day] = $nature;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
103
src/Service/WorkHours/WorkHourBulkValidationExecutor.php
Normal file
103
src/Service/WorkHours/WorkHourBulkValidationExecutor.php
Normal file
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\WorkHours;
|
||||
|
||||
use App\ApiResource\WorkHourBulkValidationResult;
|
||||
use App\Entity\User;
|
||||
use App\Entity\WorkHour;
|
||||
use App\Repository\EmployeeRepository;
|
||||
use App\Repository\WorkHourRepository;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
final readonly class WorkHourBulkValidationExecutor
|
||||
{
|
||||
public function __construct(
|
||||
private EntityManagerInterface $entityManager,
|
||||
private EmployeeRepository $employeeRepository,
|
||||
private WorkHourRepository $workHourRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $employeeIds
|
||||
* @param callable(?WorkHour, int): bool $shouldSkip
|
||||
* @param callable(WorkHour, int): void $applyUpdate
|
||||
*/
|
||||
public function execute(
|
||||
User $user,
|
||||
string $workDateValue,
|
||||
array $employeeIds,
|
||||
callable $shouldSkip,
|
||||
callable $applyUpdate
|
||||
): WorkHourBulkValidationResult {
|
||||
$workDate = DateTimeImmutable::createFromFormat('Y-m-d', $workDateValue);
|
||||
if (!$workDate || $workDate->format('Y-m-d') !== $workDateValue) {
|
||||
throw new UnprocessableEntityHttpException('workDate must use Y-m-d format.');
|
||||
}
|
||||
|
||||
$normalizedEmployeeIds = $this->normalizeEmployeeIds($employeeIds);
|
||||
if ([] === $normalizedEmployeeIds) {
|
||||
throw new UnprocessableEntityHttpException('employeeIds must contain at least one employee.');
|
||||
}
|
||||
|
||||
$employeesById = $this->employeeRepository->findAccessibleByIds($normalizedEmployeeIds, $user);
|
||||
if (count($employeesById) !== count($normalizedEmployeeIds)) {
|
||||
throw new AccessDeniedHttpException('At least one employee is unknown or outside your scope.');
|
||||
}
|
||||
|
||||
$existingByEmployeeId = $this->workHourRepository
|
||||
->findByDateAndEmployeesIndexedByEmployeeId($workDate, array_values($employeesById))
|
||||
;
|
||||
|
||||
$result = new WorkHourBulkValidationResult();
|
||||
$result->requested = count($normalizedEmployeeIds);
|
||||
|
||||
foreach ($normalizedEmployeeIds as $employeeId) {
|
||||
$workHour = $existingByEmployeeId[$employeeId] ?? null;
|
||||
if (null === $workHour || $shouldSkip($workHour, $employeeId)) {
|
||||
++$result->skipped;
|
||||
$result->skippedEmployeeIds[] = $employeeId;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$applyUpdate($workHour, $employeeId);
|
||||
++$result->updated;
|
||||
$result->updatedEmployeeIds[] = $employeeId;
|
||||
}
|
||||
|
||||
if ($result->updated > 0) {
|
||||
$this->entityManager->flush();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<mixed> $employeeIds
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
private function normalizeEmployeeIds(array $employeeIds): array
|
||||
{
|
||||
$normalized = [];
|
||||
foreach ($employeeIds as $index => $rawId) {
|
||||
$employeeId = (int) $rawId;
|
||||
if ($employeeId <= 0) {
|
||||
throw new UnprocessableEntityHttpException(sprintf('employeeIds[%d] must be a positive integer.', $index));
|
||||
}
|
||||
|
||||
if (isset($normalized[$employeeId])) {
|
||||
throw new UnprocessableEntityHttpException(sprintf('Employee %d appears multiple times in payload.', $employeeId));
|
||||
}
|
||||
|
||||
$normalized[$employeeId] = $employeeId;
|
||||
}
|
||||
|
||||
return array_values($normalized);
|
||||
}
|
||||
}
|
||||
@@ -60,11 +60,6 @@ final readonly class WorkedHoursCreditPolicy
|
||||
bool $absentMorning,
|
||||
bool $absentAfternoon
|
||||
): float {
|
||||
$type = $absence->getType();
|
||||
if (!$type?->getCountAsWorkedHours()) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$employee = $absence->getEmployee();
|
||||
if (null === $employee) {
|
||||
return 0.0;
|
||||
@@ -74,9 +69,14 @@ final readonly class WorkedHoursCreditPolicy
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$halfUnits = ($absentMorning ? 1 : 0) + ($absentAfternoon ? 1 : 0);
|
||||
// Règle forfait:
|
||||
// - demi-journée d'absence => 0.5 travaillé
|
||||
// - journée complète d'absence => 0 travaillé
|
||||
if ($absentMorning xor $absentAfternoon) {
|
||||
return 0.5;
|
||||
}
|
||||
|
||||
return $halfUnits * 0.5;
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
public function resolveContractDayMinutes(?int $weeklyHours, int $isoWeekDay): int
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\State;
|
||||
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProviderInterface;
|
||||
use App\Enum\ContractNature;
|
||||
use App\Enum\HalfDay;
|
||||
use App\Repository\AbsenceRepository;
|
||||
use App\Repository\EmployeeRepository;
|
||||
@@ -53,9 +54,11 @@ class AbsencePrintProvider implements ProviderInterface
|
||||
$fromDate = DateTimeImmutable::createFromFormat('Y-m-d', $from);
|
||||
$toDate = DateTimeImmutable::createFromFormat('Y-m-d', $to);
|
||||
|
||||
$siteIds = $this->parseIds($request->query->get('sites'));
|
||||
$siteIds = $this->parseIds($request->query->get('sites'));
|
||||
$workContractIds = $this->parseIds($request->query->get('workContracts'));
|
||||
$contractNatures = $this->parseContractNatures($request->query->get('contractNatures'));
|
||||
|
||||
$employees = $this->loadEmployees($siteIds);
|
||||
$employees = $this->loadEmployees($siteIds, $contractNatures, $workContractIds);
|
||||
$absences = $this->loadAbsences($fromDate, $toDate, $employees);
|
||||
|
||||
$days = $this->buildDays($fromDate, $toDate);
|
||||
@@ -108,9 +111,19 @@ class AbsencePrintProvider implements ProviderInterface
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
|
||||
private function loadEmployees(array $siteIds): array
|
||||
private function loadEmployees(array $siteIds, array $contractNatures, array $workContractIds): array
|
||||
{
|
||||
return $this->employeeRepository->findForPrintBySiteIds($siteIds);
|
||||
$employees = $this->employeeRepository->findForPrintBySiteIds($siteIds);
|
||||
|
||||
return array_values(array_filter($employees, static function ($employee) use ($contractNatures, $workContractIds): bool {
|
||||
$employeeNature = (string) $employee->getCurrentContractNature();
|
||||
$employeeContractId = $employee->getContract()?->getId();
|
||||
|
||||
$natureMatches = [] === $contractNatures || in_array($employeeNature, $contractNatures, true);
|
||||
$contractMatches = [] === $workContractIds || (null !== $employeeContractId && in_array($employeeContractId, $workContractIds, true));
|
||||
|
||||
return $natureMatches && $contractMatches;
|
||||
}));
|
||||
}
|
||||
|
||||
private function loadAbsences(DateTimeImmutable $from, DateTimeImmutable $to, array $employees): array
|
||||
@@ -209,4 +222,24 @@ class AbsencePrintProvider implements ProviderInterface
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function parseContractNatures(?string $value): array
|
||||
{
|
||||
if (null === $value || '' === trim($value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$values = [];
|
||||
foreach (explode(',', $value) as $part) {
|
||||
$nature = strtoupper(trim($part));
|
||||
if (null !== ContractNature::tryFrom($nature)) {
|
||||
$values[] = $nature;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($values));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use App\Entity\Absence;
|
||||
use App\Entity\Employee;
|
||||
use App\Entity\User;
|
||||
use App\Enum\HalfDay;
|
||||
use App\Repository\Contract\AbsenceReadRepositoryInterface;
|
||||
use App\Repository\Contract\WorkHourReadRepositoryInterface;
|
||||
@@ -16,7 +17,9 @@ use DateInterval;
|
||||
use DatePeriod;
|
||||
use DateTime;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeInterface;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
@@ -26,6 +29,7 @@ final readonly class AbsenceWriteProcessor implements ProcessorInterface
|
||||
private EntityManagerInterface $entityManager,
|
||||
private AbsenceReadRepositoryInterface $absenceRepository,
|
||||
private WorkHourReadRepositoryInterface $workHourRepository,
|
||||
private Security $security,
|
||||
) {}
|
||||
|
||||
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
|
||||
@@ -39,8 +43,11 @@ final readonly class AbsenceWriteProcessor implements ProcessorInterface
|
||||
return $data;
|
||||
}
|
||||
|
||||
$user = $this->security->getUser();
|
||||
$isAdmin = $user instanceof User && in_array('ROLE_ADMIN', $user->getRoles(), true);
|
||||
|
||||
if ($operation instanceof DeleteOperationInterface) {
|
||||
if ($this->workHourRepository->hasValidatedInRange($employee, $data->getStartDate(), $data->getEndDate())) {
|
||||
if ($this->isLockedByValidation($employee, $data->getStartDate(), $data->getEndDate(), $isAdmin)) {
|
||||
throw new ConflictHttpException('Impossible de modifier une absence sur une période validée.');
|
||||
}
|
||||
|
||||
@@ -58,7 +65,7 @@ final readonly class AbsenceWriteProcessor implements ProcessorInterface
|
||||
$from = DateTimeImmutable::createFromInterface($segments[0]['date']);
|
||||
$to = DateTimeImmutable::createFromInterface($segments[count($segments) - 1]['date']);
|
||||
|
||||
if ($this->workHourRepository->hasValidatedInRange($employee, $from, $to)) {
|
||||
if ($this->isLockedByValidation($employee, $from, $to, $isAdmin)) {
|
||||
throw new ConflictHttpException('Impossible de modifier une absence sur une période validée.');
|
||||
}
|
||||
|
||||
@@ -178,6 +185,19 @@ final readonly class AbsenceWriteProcessor implements ProcessorInterface
|
||||
return DateTime::createFromImmutable($date);
|
||||
}
|
||||
|
||||
private function isLockedByValidation(Employee $employee, DateTimeInterface $from, DateTimeInterface $to, bool $isAdmin): bool
|
||||
{
|
||||
if ($this->workHourRepository->hasValidatedInRange($employee, $from, $to)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($isAdmin) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->workHourRepository->hasSiteValidatedInRange($employee, $from, $to);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{date: DateTimeImmutable, startHalf: HalfDay, endHalf: HalfDay} $segment
|
||||
*/
|
||||
@@ -193,6 +213,8 @@ final readonly class AbsenceWriteProcessor implements ProcessorInterface
|
||||
$workHour
|
||||
->setMorningFrom(null)
|
||||
->setMorningTo(null)
|
||||
->setIsSiteValid(false)
|
||||
->setIsValid(false)
|
||||
;
|
||||
|
||||
return;
|
||||
@@ -205,6 +227,8 @@ final readonly class AbsenceWriteProcessor implements ProcessorInterface
|
||||
->setAfternoonTo(null)
|
||||
->setEveningFrom(null)
|
||||
->setEveningTo(null)
|
||||
->setIsSiteValid(false)
|
||||
->setIsValid(false)
|
||||
;
|
||||
|
||||
return;
|
||||
@@ -218,6 +242,8 @@ final readonly class AbsenceWriteProcessor implements ProcessorInterface
|
||||
->setAfternoonTo(null)
|
||||
->setEveningFrom(null)
|
||||
->setEveningTo(null)
|
||||
->setIsSiteValid(false)
|
||||
->setIsValid(false)
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,10 +10,12 @@ use ApiPlatform\State\ProcessorInterface;
|
||||
use App\Entity\Contract;
|
||||
use App\Entity\Employee;
|
||||
use App\Entity\EmployeeContractPeriod;
|
||||
use App\Enum\ContractNature;
|
||||
use App\Repository\EmployeeContractPeriodRepository;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
final readonly class EmployeeWriteProcessor implements ProcessorInterface
|
||||
{
|
||||
@@ -49,27 +51,46 @@ final readonly class EmployeeWriteProcessor implements ProcessorInterface
|
||||
return $result;
|
||||
}
|
||||
|
||||
$today = new DateTimeImmutable('today');
|
||||
$today = new DateTimeImmutable('today');
|
||||
$requestedContractNature = $this->resolveContractNature($data->getContractNature());
|
||||
$requestedStartDate = $this->parseOptionalYmd($data->getContractStartDate(), 'contractStartDate');
|
||||
$requestedEndDate = $this->parseOptionalYmd($data->getContractEndDate(), 'contractEndDate');
|
||||
|
||||
if ($isNew) {
|
||||
$this->ensureContractPeriodExists($data, $currentContract, $today);
|
||||
$startDate = $requestedStartDate ?? new DateTimeImmutable('1970-01-01');
|
||||
$nature = $requestedContractNature ?? ContractNature::CDI;
|
||||
$this->assertPeriodDates($startDate, $requestedEndDate, $nature);
|
||||
$this->ensureContractPeriodExists($data, $currentContract, $startDate, $requestedEndDate, $nature);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
if ($this->isSameContract($previousContract, $currentContract)) {
|
||||
$hasPeriodChangeRequest = null !== $requestedContractNature || null !== $requestedStartDate || null !== $requestedEndDate;
|
||||
if ($this->isSameContract($previousContract, $currentContract) && !$hasPeriodChangeRequest) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$startDate = $requestedStartDate ?? $today;
|
||||
$todayPeriod = $this->periodRepository->findOneCoveringDate($data, $today);
|
||||
if (null !== $todayPeriod && null === $todayPeriod->getEndDate() && $todayPeriod->getStartDate() === $today) {
|
||||
$nature = $requestedContractNature ?? $todayPeriod?->getContractNatureEnum() ?? ContractNature::CDI;
|
||||
$endDate = $requestedEndDate;
|
||||
$this->assertPeriodDates($startDate, $endDate, $nature);
|
||||
|
||||
if (
|
||||
null !== $todayPeriod
|
||||
&& null === $todayPeriod->getEndDate()
|
||||
&& $todayPeriod->getStartDate()->format('Y-m-d') === $startDate->format('Y-m-d')
|
||||
) {
|
||||
$todayPeriod->setContract($currentContract);
|
||||
$todayPeriod->setContractNature($nature);
|
||||
$todayPeriod->setEndDate($endDate);
|
||||
$this->entityManager->flush();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
$this->periodRepository->closeOpenPeriods($data, $today->modify('-1 day'));
|
||||
$this->createPeriod($data, $currentContract, $today);
|
||||
$this->periodRepository->closeOpenPeriods($data, $startDate->modify('-1 day'));
|
||||
$this->createPeriod($data, $currentContract, $startDate, $endDate, $nature);
|
||||
$this->entityManager->flush();
|
||||
|
||||
return $result;
|
||||
@@ -96,26 +117,80 @@ final readonly class EmployeeWriteProcessor implements ProcessorInterface
|
||||
return $first->getId() === $second->getId();
|
||||
}
|
||||
|
||||
private function ensureContractPeriodExists(Employee $employee, Contract $contract, DateTimeImmutable $startDate): void
|
||||
{
|
||||
private function ensureContractPeriodExists(
|
||||
Employee $employee,
|
||||
Contract $contract,
|
||||
DateTimeImmutable $startDate,
|
||||
?DateTimeImmutable $endDate,
|
||||
ContractNature $nature,
|
||||
): void {
|
||||
$covered = $this->periodRepository->findOneCoveringDate($employee, $startDate);
|
||||
if (null !== $covered) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->createPeriod($employee, $contract, $startDate);
|
||||
$this->createPeriod($employee, $contract, $startDate, $endDate, $nature);
|
||||
$this->entityManager->flush();
|
||||
}
|
||||
|
||||
private function createPeriod(Employee $employee, Contract $contract, DateTimeImmutable $startDate): void
|
||||
{
|
||||
private function createPeriod(
|
||||
Employee $employee,
|
||||
Contract $contract,
|
||||
DateTimeImmutable $startDate,
|
||||
?DateTimeImmutable $endDate,
|
||||
ContractNature $nature,
|
||||
): void {
|
||||
$period = new EmployeeContractPeriod()
|
||||
->setEmployee($employee)
|
||||
->setContract($contract)
|
||||
->setStartDate($startDate)
|
||||
->setEndDate(null)
|
||||
->setEndDate($endDate)
|
||||
->setContractNature($nature)
|
||||
;
|
||||
|
||||
$this->entityManager->persist($period);
|
||||
}
|
||||
|
||||
private function resolveContractNature(?string $raw): ?ContractNature
|
||||
{
|
||||
if (null === $raw || '' === trim($raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ContractNature::tryFrom(trim($raw))
|
||||
?? throw new UnprocessableEntityHttpException('contractNature must be one of CDI, CDD, INTERIM.');
|
||||
}
|
||||
|
||||
private function parseOptionalYmd(?string $raw, string $field): ?DateTimeImmutable
|
||||
{
|
||||
if (null === $raw || '' === trim($raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$value = trim($raw);
|
||||
$date = DateTimeImmutable::createFromFormat('Y-m-d', $value);
|
||||
if (!$date || $date->format('Y-m-d') !== $value) {
|
||||
throw new UnprocessableEntityHttpException(sprintf('%s must use Y-m-d format.', $field));
|
||||
}
|
||||
|
||||
return $date;
|
||||
}
|
||||
|
||||
private function assertPeriodDates(
|
||||
DateTimeImmutable $startDate,
|
||||
?DateTimeImmutable $endDate,
|
||||
ContractNature $nature
|
||||
): void {
|
||||
if (null !== $endDate && $endDate < $startDate) {
|
||||
throw new UnprocessableEntityHttpException('contractEndDate cannot be before contractStartDate.');
|
||||
}
|
||||
|
||||
if ($nature->requiresEndDate() && null === $endDate) {
|
||||
throw new UnprocessableEntityHttpException('contractEndDate is required for CDD and INTERIM.');
|
||||
}
|
||||
|
||||
if (ContractNature::CDI === $nature && null !== $endDate) {
|
||||
throw new UnprocessableEntityHttpException('contractEndDate must be empty for CDI.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
54
src/State/WorkHourBulkSiteValidationProcessor.php
Normal file
54
src/State/WorkHourBulkSiteValidationProcessor.php
Normal file
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\State;
|
||||
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use App\ApiResource\WorkHourBulkSiteValidation;
|
||||
use App\ApiResource\WorkHourBulkValidationResult;
|
||||
use App\Entity\User;
|
||||
use App\Entity\WorkHour;
|
||||
use App\Service\WorkHours\WorkHourBulkValidationExecutor;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
||||
|
||||
final readonly class WorkHourBulkSiteValidationProcessor implements ProcessorInterface
|
||||
{
|
||||
public function __construct(
|
||||
private Security $security,
|
||||
private WorkHourBulkValidationExecutor $executor,
|
||||
) {}
|
||||
|
||||
public function process(
|
||||
mixed $data,
|
||||
Operation $operation,
|
||||
array $uriVariables = [],
|
||||
array $context = []
|
||||
): WorkHourBulkValidationResult {
|
||||
if (!$data instanceof WorkHourBulkSiteValidation) {
|
||||
throw new BadRequestHttpException('Invalid payload.');
|
||||
}
|
||||
|
||||
$user = $this->security->getUser();
|
||||
if (!$user instanceof User) {
|
||||
throw new AccessDeniedHttpException('Authentication required.');
|
||||
}
|
||||
|
||||
if (in_array('ROLE_ADMIN', $user->getRoles(), true) || in_array('ROLE_SELF', $user->getRoles(), true)) {
|
||||
throw new AccessDeniedHttpException('Only site managers can bulk update site validation.');
|
||||
}
|
||||
|
||||
return $this->executor->execute(
|
||||
user: $user,
|
||||
workDateValue: $data->workDate,
|
||||
employeeIds: $data->employeeIds,
|
||||
shouldSkip: static fn (WorkHour $workHour): bool => $workHour->isValid() || $workHour->isSiteValid() === $data->isSiteValid,
|
||||
applyUpdate: static function (WorkHour $workHour) use ($data): void {
|
||||
$workHour->setIsSiteValid($data->isSiteValid);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use App\ApiResource\WorkHourBulkUpsertResult;
|
||||
use App\Entity\User;
|
||||
use App\Entity\WorkHour;
|
||||
use App\Enum\TrackingMode;
|
||||
use App\Repository\Contract\AbsenceReadRepositoryInterface;
|
||||
use App\Repository\EmployeeRepository;
|
||||
use App\Repository\WorkHourRepository;
|
||||
use App\Service\Contracts\EmployeeContractResolver;
|
||||
@@ -28,6 +29,7 @@ final readonly class WorkHourBulkUpsertProcessor implements ProcessorInterface
|
||||
private Security $security,
|
||||
private EmployeeRepository $employeeRepository,
|
||||
private WorkHourRepository $workHourRepository,
|
||||
private AbsenceReadRepositoryInterface $absenceRepository,
|
||||
private EmployeeContractResolver $contractResolver,
|
||||
) {}
|
||||
|
||||
@@ -67,6 +69,13 @@ final readonly class WorkHourBulkUpsertProcessor implements ProcessorInterface
|
||||
$existingByEmployeeId = $this->workHourRepository
|
||||
->findByDateAndEmployeesIndexedByEmployeeId($workDate, array_values($employeesById))
|
||||
;
|
||||
$absenceByEmployeeId = [];
|
||||
foreach ($this->absenceRepository->findByDateAndEmployees($workDate, array_values($employeesById)) as $absence) {
|
||||
$absenceEmployeeId = $absence->getEmployee()?->getId();
|
||||
if ($absenceEmployeeId) {
|
||||
$absenceByEmployeeId[$absenceEmployeeId] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$result = new WorkHourBulkUpsertResult();
|
||||
|
||||
@@ -77,10 +86,18 @@ final readonly class WorkHourBulkUpsertProcessor implements ProcessorInterface
|
||||
throw new AccessDeniedHttpException(sprintf('Employee %d is outside your scope.', $employeeId));
|
||||
}
|
||||
|
||||
$contract = $this->contractResolver->resolveForEmployeeAndDate($employee, $workDate);
|
||||
$contract = $this->contractResolver->resolveForEmployeeAndDate($employee, $workDate);
|
||||
if (null === $contract) {
|
||||
throw new UnprocessableEntityHttpException(sprintf(
|
||||
'Employee %d has no active contract on %s.',
|
||||
$employeeId,
|
||||
$data->workDate
|
||||
));
|
||||
}
|
||||
$isPresenceTracking = TrackingMode::PRESENCE->value === $contract?->getTrackingMode();
|
||||
$normalized = $this->normalizeEntry($entry, $employeeId, $isPresenceTracking);
|
||||
$existing = $existingByEmployeeId[$employeeId] ?? null;
|
||||
$isAdmin = in_array('ROLE_ADMIN', $user->getRoles(), true);
|
||||
|
||||
if ($existing?->isValid()) {
|
||||
if (!$this->isSameAsExisting($existing, $normalized)) {
|
||||
@@ -95,11 +112,42 @@ final readonly class WorkHourBulkUpsertProcessor implements ProcessorInterface
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$isAdmin && $existing?->isSiteValid()) {
|
||||
if (!$this->isSameAsExisting($existing, $normalized)) {
|
||||
throw new UnprocessableEntityHttpException(sprintf(
|
||||
'Employee %d: site validated work hour cannot be modified.',
|
||||
$employeeId
|
||||
));
|
||||
}
|
||||
|
||||
++$result->processed;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Si aucune donnée n'a changé, on ne touche pas la ligne:
|
||||
// cela évite de perdre les validations existantes (site/RH) sur un simple enregistrement.
|
||||
if (null !== $existing && $this->isSameAsExisting($existing, $normalized)) {
|
||||
++$result->processed;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->isEntryEmpty($normalized)) {
|
||||
// Convention choisie: une ligne vide supprime l'enregistrement existant.
|
||||
if ($existing) {
|
||||
$this->entityManager->remove($existing);
|
||||
++$result->deleted;
|
||||
} elseif (($absenceByEmployeeId[$employeeId] ?? false) === true) {
|
||||
// Si une absence existe ce jour, on garde une ligne technique pour pouvoir valider la journée.
|
||||
$workHour = new WorkHour()
|
||||
->setEmployee($employee)
|
||||
->setWorkDate($workDate)
|
||||
;
|
||||
$this->hydrateWorkHour($workHour, $normalized);
|
||||
$this->entityManager->persist($workHour);
|
||||
$existingByEmployeeId[$employeeId] = $workHour;
|
||||
++$result->created;
|
||||
}
|
||||
|
||||
++$result->processed;
|
||||
@@ -187,14 +235,16 @@ final readonly class WorkHourBulkUpsertProcessor implements ProcessorInterface
|
||||
}
|
||||
|
||||
return [
|
||||
'morningFrom' => $this->normalizeTime($entry['morningFrom'] ?? null, $employeeId, 'morningFrom'),
|
||||
'morningTo' => $this->normalizeTime($entry['morningTo'] ?? null, $employeeId, 'morningTo'),
|
||||
'afternoonFrom' => $this->normalizeTime($entry['afternoonFrom'] ?? null, $employeeId, 'afternoonFrom'),
|
||||
'afternoonTo' => $this->normalizeTime($entry['afternoonTo'] ?? null, $employeeId, 'afternoonTo'),
|
||||
'eveningFrom' => $this->normalizeTime($entry['eveningFrom'] ?? null, $employeeId, 'eveningFrom'),
|
||||
'eveningTo' => $this->normalizeTime($entry['eveningTo'] ?? null, $employeeId, 'eveningTo'),
|
||||
'isPresentMorning' => false,
|
||||
'isPresentAfternoon' => false,
|
||||
'morningFrom' => $this->normalizeTime($entry['morningFrom'] ?? null, $employeeId, 'morningFrom'),
|
||||
'morningTo' => $this->normalizeTime($entry['morningTo'] ?? null, $employeeId, 'morningTo'),
|
||||
'afternoonFrom' => $this->normalizeTime($entry['afternoonFrom'] ?? null, $employeeId, 'afternoonFrom'),
|
||||
'afternoonTo' => $this->normalizeTime($entry['afternoonTo'] ?? null, $employeeId, 'afternoonTo'),
|
||||
'eveningFrom' => $this->normalizeTime($entry['eveningFrom'] ?? null, $employeeId, 'eveningFrom'),
|
||||
'eveningTo' => $this->normalizeTime($entry['eveningTo'] ?? null, $employeeId, 'eveningTo'),
|
||||
// On conserve aussi la présence si envoyée (cas forfait affiché côté UI),
|
||||
// même si le contrat résolu ce jour est en suivi horaire.
|
||||
'isPresentMorning' => $this->normalizePresence($entry['isPresentMorning'] ?? false, $employeeId, 'isPresentMorning'),
|
||||
'isPresentAfternoon' => $this->normalizePresence($entry['isPresentAfternoon'] ?? false, $employeeId, 'isPresentAfternoon'),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -284,6 +334,8 @@ final readonly class WorkHourBulkUpsertProcessor implements ProcessorInterface
|
||||
->setEveningTo($entry['eveningTo'])
|
||||
->setIsPresentMorning($entry['isPresentMorning'])
|
||||
->setIsPresentAfternoon($entry['isPresentAfternoon'])
|
||||
// Toute modification invalide la validation chef de site.
|
||||
->setIsSiteValid(false)
|
||||
// Toute modification utilisateur repasse la ligne en attente de validation RH.
|
||||
->setIsValid(false)
|
||||
;
|
||||
|
||||
54
src/State/WorkHourBulkValidationProcessor.php
Normal file
54
src/State/WorkHourBulkValidationProcessor.php
Normal file
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\State;
|
||||
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use App\ApiResource\WorkHourBulkValidation;
|
||||
use App\ApiResource\WorkHourBulkValidationResult;
|
||||
use App\Entity\User;
|
||||
use App\Entity\WorkHour;
|
||||
use App\Service\WorkHours\WorkHourBulkValidationExecutor;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
||||
|
||||
final readonly class WorkHourBulkValidationProcessor implements ProcessorInterface
|
||||
{
|
||||
public function __construct(
|
||||
private Security $security,
|
||||
private WorkHourBulkValidationExecutor $executor,
|
||||
) {}
|
||||
|
||||
public function process(
|
||||
mixed $data,
|
||||
Operation $operation,
|
||||
array $uriVariables = [],
|
||||
array $context = []
|
||||
): WorkHourBulkValidationResult {
|
||||
if (!$data instanceof WorkHourBulkValidation) {
|
||||
throw new BadRequestHttpException('Invalid payload.');
|
||||
}
|
||||
|
||||
$user = $this->security->getUser();
|
||||
if (!$user instanceof User) {
|
||||
throw new AccessDeniedHttpException('Authentication required.');
|
||||
}
|
||||
|
||||
if (!in_array('ROLE_ADMIN', $user->getRoles(), true)) {
|
||||
throw new AccessDeniedHttpException('Only admins can bulk validate work hours.');
|
||||
}
|
||||
|
||||
return $this->executor->execute(
|
||||
user: $user,
|
||||
workDateValue: $data->workDate,
|
||||
employeeIds: $data->employeeIds,
|
||||
shouldSkip: static fn (WorkHour $workHour): bool => $workHour->isValid() === $data->isValid,
|
||||
applyUpdate: static function (WorkHour $workHour) use ($data): void {
|
||||
$workHour->setIsValid($data->isValid);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use App\Dto\WorkHours\DayContextRow;
|
||||
use App\Entity\User;
|
||||
use App\Repository\Contract\AbsenceReadRepositoryInterface;
|
||||
use App\Repository\Contract\EmployeeScopedRepositoryInterface;
|
||||
use App\Service\Contracts\EmployeeContractResolver;
|
||||
use App\Service\WorkHours\AbsenceSegmentsResolver;
|
||||
use App\Service\WorkHours\WorkedHoursCreditPolicy;
|
||||
use DateTimeImmutable;
|
||||
@@ -26,6 +27,7 @@ final readonly class WorkHourDayContextProvider implements ProviderInterface
|
||||
private RequestStack $requestStack,
|
||||
private EmployeeScopedRepositoryInterface $employeeRepository,
|
||||
private AbsenceReadRepositoryInterface $absenceRepository,
|
||||
private EmployeeContractResolver $contractResolver,
|
||||
private AbsenceSegmentsResolver $absenceSegmentsResolver,
|
||||
private WorkedHoursCreditPolicy $workedHoursCreditPolicy,
|
||||
) {}
|
||||
@@ -50,7 +52,10 @@ final readonly class WorkHourDayContextProvider implements ProviderInterface
|
||||
}
|
||||
|
||||
// On initialise toutes les lignes, même sans absence ce jour-là.
|
||||
$rowsByEmployeeId[$employeeId] = new DayContextRow(employeeId: $employeeId);
|
||||
$rowsByEmployeeId[$employeeId] = new DayContextRow(
|
||||
employeeId: $employeeId,
|
||||
hasContractAtDate: null !== $this->contractResolver->resolveForEmployeeAndDate($employee, $workDate)
|
||||
);
|
||||
}
|
||||
|
||||
$dateKey = $workDate->format('Y-m-d');
|
||||
@@ -72,6 +77,7 @@ final readonly class WorkHourDayContextProvider implements ProviderInterface
|
||||
$creditedPresenceUnits = $this->workedHoursCreditPolicy->computeCreditedPresenceUnits($absence, $dateKey, $absentMorning, $absentAfternoon);
|
||||
$rowsByEmployeeId[$employeeId]->addAbsence(
|
||||
label: $absence->getType()?->getLabel(),
|
||||
color: $absence->getType()?->getColor(),
|
||||
morning: $absentMorning,
|
||||
afternoon: $absentAfternoon,
|
||||
creditedMinutes: $creditedMinutes,
|
||||
|
||||
54
src/State/WorkHourSiteValidationProcessor.php
Normal file
54
src/State/WorkHourSiteValidationProcessor.php
Normal file
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\State;
|
||||
|
||||
use ApiPlatform\Metadata\Operation;
|
||||
use ApiPlatform\State\ProcessorInterface;
|
||||
use App\Entity\User;
|
||||
use App\Entity\WorkHour;
|
||||
use App\Security\EmployeeScopeService;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
final readonly class WorkHourSiteValidationProcessor implements ProcessorInterface
|
||||
{
|
||||
public function __construct(
|
||||
private Security $security,
|
||||
private EmployeeScopeService $employeeScopeService,
|
||||
private EntityManagerInterface $entityManager,
|
||||
) {}
|
||||
|
||||
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): WorkHour
|
||||
{
|
||||
if (!$data instanceof WorkHour) {
|
||||
throw new AccessDeniedHttpException('Invalid payload.');
|
||||
}
|
||||
|
||||
$user = $this->security->getUser();
|
||||
if (!$user instanceof User) {
|
||||
throw new AccessDeniedHttpException('Authentication required.');
|
||||
}
|
||||
|
||||
// Réservé aux profils "Sites" (ni admin, ni self).
|
||||
if (in_array('ROLE_ADMIN', $user->getRoles(), true) || in_array('ROLE_SELF', $user->getRoles(), true)) {
|
||||
throw new AccessDeniedHttpException('Only site managers can update site validation.');
|
||||
}
|
||||
|
||||
$siteId = $data->getEmployee()?->getSite()?->getId();
|
||||
if (!$siteId) {
|
||||
throw new AccessDeniedHttpException('Employee site is required.');
|
||||
}
|
||||
|
||||
$allowedSiteIds = $this->employeeScopeService->getAllowedSiteIds($user);
|
||||
if (!in_array($siteId, $allowedSiteIds, true)) {
|
||||
throw new AccessDeniedHttpException('Employee is outside your site scope.');
|
||||
}
|
||||
|
||||
$this->entityManager->flush();
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ use App\Entity\Contract;
|
||||
use App\Entity\Employee;
|
||||
use App\Entity\User;
|
||||
use App\Entity\WorkHour;
|
||||
use App\Enum\ContractNature;
|
||||
use App\Enum\ContractType;
|
||||
use App\Enum\TrackingMode;
|
||||
use App\Repository\Contract\AbsenceReadRepositoryInterface;
|
||||
@@ -113,8 +114,9 @@ final readonly class WorkHourWeeklySummaryProvider implements ProviderInterface
|
||||
*/
|
||||
private function buildRows(array $employees, array $workHours, array $absences, array $days, string $anchorDateYmd): array
|
||||
{
|
||||
$contractsByEmployeeDate = $this->contractResolver->resolveForEmployeesAndDays($employees, $days);
|
||||
$metricsByEmployeeDate = [];
|
||||
$contractsByEmployeeDate = $this->contractResolver->resolveForEmployeesAndDays($employees, $days);
|
||||
$contractNaturesByEmployeeDate = $this->contractResolver->resolveNaturesForEmployeesAndDays($employees, $days);
|
||||
$metricsByEmployeeDate = [];
|
||||
foreach ($workHours as $workHour) {
|
||||
$employeeId = $workHour->getEmployee()?->getId();
|
||||
if (!$employeeId) {
|
||||
@@ -133,6 +135,8 @@ final readonly class WorkHourWeeklySummaryProvider implements ProviderInterface
|
||||
$creditedByEmployeeDate = [];
|
||||
$creditedPresenceByEmployeeDate = [];
|
||||
$absenceByEmployeeDate = [];
|
||||
$absentMorningByEmployeeDate = [];
|
||||
$absentAfternoonByEmployeeDate = [];
|
||||
$absenceLabelByEmployeeDate = [];
|
||||
$absenceColorByEmployeeDate = [];
|
||||
foreach ($absences as $absence) {
|
||||
@@ -151,7 +155,9 @@ final readonly class WorkHourWeeklySummaryProvider implements ProviderInterface
|
||||
|
||||
[$absentMorning, $absentAfternoon] = $this->absenceSegmentsResolver->resolveForDate($absence, $date);
|
||||
if ($absentMorning || $absentAfternoon) {
|
||||
$absenceByEmployeeDate[$employeeId][$date] = true;
|
||||
$absenceByEmployeeDate[$employeeId][$date] = true;
|
||||
$absentMorningByEmployeeDate[$employeeId][$date] = ($absentMorningByEmployeeDate[$employeeId][$date] ?? false) || $absentMorning;
|
||||
$absentAfternoonByEmployeeDate[$employeeId][$date] = ($absentAfternoonByEmployeeDate[$employeeId][$date] ?? false) || $absentAfternoon;
|
||||
if (!isset($absenceLabelByEmployeeDate[$employeeId][$date])) {
|
||||
$absenceLabelByEmployeeDate[$employeeId][$date] = $absence->getType()?->getLabel();
|
||||
}
|
||||
@@ -182,6 +188,9 @@ final readonly class WorkHourWeeklySummaryProvider implements ProviderInterface
|
||||
$weekAnchorContract = $contractsByEmployeeDate[$employeeId][$anchorDateYmd]
|
||||
?? $contractsByEmployeeDate[$employeeId][$days[0]]
|
||||
?? null;
|
||||
$weekAnchorContractNature = $contractNaturesByEmployeeDate[$employeeId][$anchorDateYmd]
|
||||
?? $contractNaturesByEmployeeDate[$employeeId][$days[0]]
|
||||
?? ContractNature::CDI;
|
||||
$employeeContractsByDate = [];
|
||||
foreach ($days as $date) {
|
||||
$employeeContractsByDate[$date] = $contractsByEmployeeDate[$employeeId][$date] ?? null;
|
||||
@@ -197,8 +206,10 @@ final readonly class WorkHourWeeklySummaryProvider implements ProviderInterface
|
||||
$metrics->addCreditedMinutes($creditedMinutes);
|
||||
$present = null;
|
||||
if ($isPresenceTracking) {
|
||||
$morning = ($entry['isPresentMorning'] ?? false) ? 0.5 : 0.0;
|
||||
$afternoon = ($entry['isPresentAfternoon'] ?? false) ? 0.5 : 0.0;
|
||||
$absentMorning = $absentMorningByEmployeeDate[$employeeId][$date] ?? false;
|
||||
$absentAfternoon = $absentAfternoonByEmployeeDate[$employeeId][$date] ?? false;
|
||||
$morning = (($entry['isPresentMorning'] ?? false) && !$absentMorning) ? 0.5 : 0.0;
|
||||
$afternoon = (($entry['isPresentAfternoon'] ?? false) && !$absentAfternoon) ? 0.5 : 0.0;
|
||||
$creditedPresence = $creditedPresenceByEmployeeDate[$employeeId][$date] ?? 0.0;
|
||||
$present = min(1.0, $morning + $afternoon + $creditedPresence);
|
||||
}
|
||||
@@ -223,7 +234,7 @@ final readonly class WorkHourWeeklySummaryProvider implements ProviderInterface
|
||||
}
|
||||
|
||||
$isWeekPresenceTracking = TrackingMode::PRESENCE->value === $weekAnchorContract?->getTrackingMode();
|
||||
$disableOvertimeBonuses = $this->hasDisabledOvertimeBonuses($weekAnchorContract);
|
||||
$disableOvertimeBonuses = $this->hasDisabledOvertimeBonuses($weekAnchorContract, $weekAnchorContractNature);
|
||||
$overtimeReferenceMinutes = $this->computeWeeklyOvertimeReferenceMinutes($days, $employeeContractsByDate);
|
||||
$overtime25StartMinutes = $this->computeWeeklyOvertime25StartMinutes($days, $employeeContractsByDate);
|
||||
$weeklyOvertimeTotalMinutes = $isWeekPresenceTracking
|
||||
@@ -407,8 +418,12 @@ final readonly class WorkHourWeeklySummaryProvider implements ProviderInterface
|
||||
return (int) round($trancheMinutes * 0.5);
|
||||
}
|
||||
|
||||
private function hasDisabledOvertimeBonuses(?Contract $contract): bool
|
||||
private function hasDisabledOvertimeBonuses(?Contract $contract, ContractNature $contractNature): bool
|
||||
{
|
||||
if (ContractNature::INTERIM === $contractNature) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$type = ContractType::resolve(
|
||||
$contract?->getName(),
|
||||
$contract?->getTrackingMode(),
|
||||
|
||||
@@ -10,6 +10,7 @@ use App\Entity\Absence;
|
||||
use App\Entity\AbsenceType;
|
||||
use App\Entity\Contract;
|
||||
use App\Entity\Employee;
|
||||
use App\Entity\User;
|
||||
use App\Enum\HalfDay;
|
||||
use App\Repository\Contract\AbsenceReadRepositoryInterface;
|
||||
use App\Repository\Contract\WorkHourReadRepositoryInterface;
|
||||
@@ -17,6 +18,7 @@ use App\State\AbsenceWriteProcessor;
|
||||
use DateTime;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
|
||||
|
||||
@@ -32,7 +34,8 @@ final class AbsenceWriteProcessorTest extends TestCase
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
$absenceRepository = $this->createMock(AbsenceReadRepositoryInterface::class);
|
||||
$workHourRepository = $this->createMock(WorkHourReadRepositoryInterface::class);
|
||||
$this->processor = new AbsenceWriteProcessor($entityManager, $absenceRepository, $workHourRepository);
|
||||
$security = $this->createAdminSecurityStub();
|
||||
$this->processor = new AbsenceWriteProcessor($entityManager, $absenceRepository, $workHourRepository, $security);
|
||||
|
||||
$absence = $this->buildAbsence('2026-02-16', '2026-02-18', HalfDay::AM, HalfDay::PM);
|
||||
|
||||
@@ -59,7 +62,8 @@ final class AbsenceWriteProcessorTest extends TestCase
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
$absenceRepository = $this->createStub(AbsenceReadRepositoryInterface::class);
|
||||
$workHourRepository = $this->createMock(WorkHourReadRepositoryInterface::class);
|
||||
$this->processor = new AbsenceWriteProcessor($entityManager, $absenceRepository, $workHourRepository);
|
||||
$security = $this->createAdminSecurityStub();
|
||||
$this->processor = new AbsenceWriteProcessor($entityManager, $absenceRepository, $workHourRepository, $security);
|
||||
|
||||
$absence = $this->buildAbsence('2026-02-16', '2026-02-16', HalfDay::AM, HalfDay::PM);
|
||||
|
||||
@@ -79,7 +83,8 @@ final class AbsenceWriteProcessorTest extends TestCase
|
||||
$entityManager = $this->createMock(EntityManagerInterface::class);
|
||||
$absenceRepository = $this->createStub(AbsenceReadRepositoryInterface::class);
|
||||
$workHourRepository = $this->createMock(WorkHourReadRepositoryInterface::class);
|
||||
$this->processor = new AbsenceWriteProcessor($entityManager, $absenceRepository, $workHourRepository);
|
||||
$security = $this->createAdminSecurityStub();
|
||||
$this->processor = new AbsenceWriteProcessor($entityManager, $absenceRepository, $workHourRepository, $security);
|
||||
|
||||
$absence = $this->buildAbsence('2026-02-16', '2026-02-16', HalfDay::AM, HalfDay::PM);
|
||||
|
||||
@@ -100,7 +105,8 @@ final class AbsenceWriteProcessorTest extends TestCase
|
||||
$entityManager = $this->createStub(EntityManagerInterface::class);
|
||||
$absenceRepository = $this->createStub(AbsenceReadRepositoryInterface::class);
|
||||
$workHourRepository = $this->createStub(WorkHourReadRepositoryInterface::class);
|
||||
$this->processor = new AbsenceWriteProcessor($entityManager, $absenceRepository, $workHourRepository);
|
||||
$security = $this->createAdminSecurityStub();
|
||||
$this->processor = new AbsenceWriteProcessor($entityManager, $absenceRepository, $workHourRepository, $security);
|
||||
|
||||
$absence = $this->buildAbsence('2026-02-16', '2026-02-16', HalfDay::PM, HalfDay::AM);
|
||||
|
||||
@@ -121,6 +127,17 @@ final class AbsenceWriteProcessorTest extends TestCase
|
||||
->setStartDate(new DateTime($startDate))
|
||||
->setEndDate(new DateTime($endDate))
|
||||
->setStartHalf($startHalf)
|
||||
->setEndHalf($endHalf);
|
||||
->setEndHalf($endHalf)
|
||||
;
|
||||
}
|
||||
|
||||
private function createAdminSecurityStub(): Security
|
||||
{
|
||||
$security = $this->createStub(Security::class);
|
||||
$security->method('getUser')->willReturn(
|
||||
new User()->setUsername('admin')->setRoles(['ROLE_ADMIN'])
|
||||
);
|
||||
|
||||
return $security;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,7 @@ final class WorkHourDayContextProviderTest extends TestCase
|
||||
$this->requestStack,
|
||||
$this->employeeRepository,
|
||||
$this->absenceRepository,
|
||||
$this->buildResolverStub(),
|
||||
new AbsenceSegmentsResolver(),
|
||||
new WorkedHoursCreditPolicy($this->buildResolverStub())
|
||||
);
|
||||
@@ -71,6 +72,7 @@ final class WorkHourDayContextProviderTest extends TestCase
|
||||
$this->requestStack,
|
||||
$this->employeeRepository,
|
||||
$this->absenceRepository,
|
||||
$this->buildResolverStub(),
|
||||
new AbsenceSegmentsResolver(),
|
||||
new WorkedHoursCreditPolicy($this->buildResolverStub())
|
||||
);
|
||||
@@ -95,6 +97,7 @@ final class WorkHourDayContextProviderTest extends TestCase
|
||||
$this->requestStack,
|
||||
$this->employeeRepository,
|
||||
$this->absenceRepository,
|
||||
$this->buildResolverStub(),
|
||||
new AbsenceSegmentsResolver(),
|
||||
new WorkedHoursCreditPolicy($this->buildResolverStub())
|
||||
);
|
||||
|
||||
@@ -135,7 +135,7 @@ final class WorkHourWeeklySummaryProviderTest extends TestCase
|
||||
self::assertSame(210, $result->rows[0]->weeklyOvertime50Minutes);
|
||||
self::assertSame(1230, $result->rows[0]->weeklyRecoveryMinutes);
|
||||
|
||||
self::assertSame(1.0, $result->rows[1]->weeklyPresenceCount);
|
||||
self::assertSame(0.0, $result->rows[1]->weeklyPresenceCount);
|
||||
self::assertTrue($result->rows[1]->daily[0]->hasAbsence);
|
||||
self::assertSame('Congé', $result->rows[1]->daily[0]->absenceLabel);
|
||||
self::assertSame('#000', $result->rows[1]->daily[0]->absenceColor);
|
||||
|
||||
Reference in New Issue
Block a user