Compare commits

..

3 Commits

Author SHA1 Message Date
tristan 1cfbfb0120 feat : wip 2026-02-16 14:43:37 +01:00
gitea-actions 2a9b047913 chore: bump version to v0.1.7
Auto Tag Develop / tag (push) Successful in 4s
Build Release Artefact / build (push) Successful in 1m18s
2026-02-16 07:19:12 +00:00
tristan 76f1363457 [#321] Gestion des rôles dans l'application (#2)
Auto Tag Develop / tag (push) Successful in 6s
| Numéro du ticket | Titre du ticket |
|------------------|-----------------|
|        #321          |        Gestion des rôles dans l'application         |

## Description de la PR
[#321] Gestion des rôles dans l'application

## Modification du .env

## Check list

- [x] Pas de régression
- [ ] TU/TI/TF rédigée
- [x] TU/TI/TF OK
- [ ] CHANGELOG modifié

Reviewed-on: #2
Co-authored-by: tristan <tristan@yuno.malio.fr>
Co-committed-by: tristan <tristan@yuno.malio.fr>
2026-02-16 07:19:05 +00:00
28 changed files with 1811 additions and 41 deletions
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourcePerFileMappings">
<file url="file://$APPLICATION_CONFIG_DIR$/consoles/db/9cad43df-2147-4989-b7a4-443067034884/console_3.sql" value="9cad43df-2147-4989-b7a4-443067034884" />
</component>
</project>
+1 -1
View File
@@ -1,2 +1,2 @@
parameters:
app.version: '0.1.6'
app.version: '0.1.7'
+10
View File
@@ -31,6 +31,11 @@
"create": "Impossible de créer l'absence.",
"update": "Impossible de mettre à jour l'absence.",
"delete": "Impossible de supprimer l'absence."
},
"user": {
"create": "Impossible de créer l'utilisateur.",
"update": "Impossible de mettre à jour l'utilisateur.",
"delete": "Impossible de supprimer l'utilisateur."
}
},
"success": {
@@ -57,6 +62,11 @@
"create": "Absence créée.",
"update": "Absence mise à jour.",
"delete": "Absence supprimée."
},
"user": {
"create": "Utilisateur créé.",
"update": "Utilisateur mis à jour.",
"delete": "Utilisateur supprimé."
}
}
}
+45 -35
View File
@@ -6,41 +6,50 @@
<img src="/malio.png" alt="Logo" class="w-auto"/>
</div>
<nav class="flex-1 px-4 pb-6">
<NuxtLink
to="/"
class="flex items-center gap-3 px-4 pb-3 pt-6 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600 border-t border-secondary-500"
active-class="bg-primary-50 text-primary-600"
>
Tableau de bord
</NuxtLink>
<NuxtLink
to="/calendar"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Calendrier
</NuxtLink>
<NuxtLink
to="/employees"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Employés
</NuxtLink>
<NuxtLink
to="/sites"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Sites
</NuxtLink>
<NuxtLink
to="/absence-types"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Types d'absence
</NuxtLink>
<template v-if="isAdmin">
<NuxtLink
to="/"
class="flex items-center gap-3 px-4 pb-3 pt-6 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600 border-t border-secondary-500"
active-class="bg-primary-50 text-primary-600"
>
Tableau de bord
</NuxtLink>
<NuxtLink
to="/calendar"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Calendrier
</NuxtLink>
<NuxtLink
to="/employees"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Employés
</NuxtLink>
<NuxtLink
to="/sites"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Sites
</NuxtLink>
<NuxtLink
to="/users"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Utilisateurs
</NuxtLink>
<NuxtLink
to="/absence-types"
class="flex items-center gap-3 px-4 py-3 text-md font-semibold text-neutral-700 hover:bg-primary-50 hover:text-primary-600"
active-class="bg-primary-50 text-primary-600"
>
Types d'absence
</NuxtLink>
</template>
</nav>
<div class="flex flex-col gap-2 items-center p-4">
@@ -65,6 +74,7 @@
<script setup lang="ts">
const auth = useAuthStore()
const {version} = useAppVersion()
const isAdmin = computed(() => auth.user?.roles?.includes('ROLE_ADMIN') ?? false)
const handleLogout = async () => {
await auth.logout()
+12
View File
@@ -0,0 +1,12 @@
export default defineNuxtRouteMiddleware(async () => {
const auth = useAuthStore()
if (!auth.checked) {
await auth.ensureSession()
}
const isAdmin = auth.user?.roles?.includes('ROLE_ADMIN')
if (!isAdmin) {
return navigateTo('/')
}
})
+464
View File
@@ -0,0 +1,464 @@
<template>
<div>
<div class="flex items-center justify-between pb-12">
<h1 class="text-4xl font-bold text-primary-500">Utilisateurs</h1>
<button
type="button"
class="rounded-lg bg-primary-500 px-4 py-2 text-md font-semibold text-white hover:bg-secondary-500"
@click="openCreate"
>
Ajouter un utilisateur
</button>
</div>
<div
v-if="!isLoading && users.length === 0"
class="rounded-lg border border-neutral-200 bg-white p-6 text-md text-neutral-600"
>
Aucun utilisateur pour le moment.
</div>
<div v-else class="max-h-[80vh] overflow-auto rounded-lg border border-neutral-200 bg-white">
<div class="grid grid-cols-[1fr_1fr_140px_1fr_140px] gap-4 border-b border-neutral-200 bg-tertiary-500 px-6 py-3 text-md font-semibold text-neutral-700">
<span class="text-left">Utilisateur</span>
<span class="text-left">Employé</span>
<span class="text-left">Accès</span>
<span class="text-left">Sites</span>
<span class="text-right">Actions</span>
</div>
<div v-if="isLoading" class="px-6 py-4 text-md text-neutral-500">
Chargement...
</div>
<div v-else>
<div
v-for="user in users"
:key="user.id"
class="grid grid-cols-[1fr_1fr_140px_1fr_140px] items-center gap-4 border-b border-neutral-100 px-6 py-3 text-md text-neutral-800 last:border-b-0"
>
<span class="text-left">{{ user.username }}</span>
<span class="text-left">
{{ user.employee ? `${user.employee.firstName} ${user.employee.lastName}` : '-' }}
</span>
<span class="text-left text-sm text-neutral-600">
{{ getAccessLabel(user) }}
</span>
<span class="text-left text-sm text-neutral-600">
{{ getSiteLabels(user) }}
</span>
<div class="flex justify-end">
<button
type="button"
class="rounded-md border border-neutral-200 px-2 py-1 text-md font-semibold text-neutral-700 hover:bg-neutral-100"
@click="openEdit(user)"
>
Modifier
</button>
</div>
</div>
</div>
</div>
<AppDrawer
v-model="isDrawerOpen"
:title="editingUser ? 'Modifier un utilisateur' : 'Ajouter un utilisateur'"
>
<form class="space-y-4" @submit.prevent="handleSubmit">
<div>
<label class="text-md font-semibold text-neutral-700" for="username">
Nom d'utilisateur <span class="text-red-600">*</span>
</label>
<input
id="username"
v-model="form.username"
type="text"
:class="usernameFieldClass"
/>
<p v-if="showUsernameError" class="mt-1 text-sm text-red-600">
Le nom d'utilisateur est obligatoire.
</p>
</div>
<div>
<label class="text-md font-semibold text-neutral-700" for="password">
Mot de passe
<span v-if="!editingUser" class="text-red-600">*</span>
</label>
<input
id="password"
v-model="form.password"
type="password"
:class="passwordFieldClass"
/>
<p v-if="editingUser" class="mt-1 text-sm text-neutral-500">
Laisse vide pour ne pas changer le mot de passe.
</p>
<p v-else-if="showPasswordError" class="mt-1 text-sm text-red-600">
Le mot de passe est obligatoire.
</p>
</div>
<div>
<p class="text-md font-semibold text-neutral-700">Accès</p>
<div class="mt-2 flex flex-wrap gap-2">
<button
type="button"
class="rounded-full border px-3 py-1 text-sm font-semibold"
:class="form.accessMode === 'admin' ? 'border-primary-500 bg-primary-50 text-primary-700' : 'border-neutral-200 text-neutral-700'"
@click="selectAccessMode('admin')"
>
Admin
</button>
<button
type="button"
class="rounded-full border px-3 py-1 text-sm font-semibold"
:class="form.accessMode === 'self' ? 'border-primary-500 bg-primary-50 text-primary-700' : 'border-neutral-200 text-neutral-700'"
@click="selectAccessMode('self')"
>
Accès personnel
</button>
<button
type="button"
class="rounded-full border px-3 py-1 text-sm font-semibold"
:class="form.accessMode === 'sites' ? 'border-primary-500 bg-primary-50 text-primary-700' : 'border-neutral-200 text-neutral-700'"
@click="selectAccessMode('sites')"
>
Sites
</button>
</div>
<p class="mt-2 text-sm text-neutral-500">
{{
form.accessMode === 'admin'
? 'Donne accès à tout.'
: form.accessMode === 'self'
? "Donne accès uniquement à ses propres données."
: 'Donne accès aux employés des sites sélectionnés.'
}}
</p>
</div>
<div v-if="form.accessMode === 'self'">
<label class="text-md font-semibold text-neutral-700" for="employee">
Employé lié
</label>
<select
id="employee"
v-model="form.employeeId"
class="mt-2 w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-md text-neutral-900"
>
<option value="">Aucun</option>
<option v-for="employee in employees" :key="employee.id" :value="employee.id">
{{ employee.firstName }} {{ employee.lastName }}
</option>
</select>
<p v-if="showSelfEmployeeError" class="mt-1 text-sm text-red-600">
Sélectionne un employé.
</p>
</div>
<div v-if="form.accessMode === 'sites'">
<p class="text-md font-semibold text-neutral-700">Sites autorisés</p>
<div class="mt-2 grid gap-2 sm:grid-cols-2">
<label
v-for="site in sites"
:key="site.id"
class="flex items-center gap-2 rounded-md border border-neutral-200 px-3 py-2 text-sm text-neutral-700 cursor-pointer"
>
<input
type="checkbox"
class="cursor-pointer"
:checked="form.siteIds.includes(site.id)"
@change="toggleSite(site.id)"
/>
<span>{{ site.name }}</span>
</label>
</div>
<p v-if="showSitesError" class="mt-1 text-sm text-red-600">
Sélectionne au moins un site.
</p>
</div>
<div class="flex justify-end gap-3 pt-2">
<button
type="button"
class="rounded-lg border border-neutral-200 px-4 py-2 text-md font-semibold text-neutral-700 hover:bg-neutral-100"
@click="closeDrawer"
>
Annuler
</button>
<button
type="submit"
class="rounded-lg bg-primary-500 px-4 py-2 text-md font-semibold text-white hover:bg-secondary-500"
:class="submitButtonClass"
>
Enregistrer
</button>
</div>
</form>
</AppDrawer>
</div>
</template>
<script setup lang="ts">
import type { Employee } from '~/services/dto/employee'
import type { Site } from '~/services/dto/site'
import type { User } from '~/services/dto/user'
import type { UserSiteRole } from '~/services/user-site-roles'
import { listEmployees } from '~/services/employees'
import { listSites } from '~/services/sites'
import { createUser, listUsers, updateUser } from '~/services/users'
import { createUserSiteRole, deleteUserSiteRole, listUserSiteRoles } from '~/services/user-site-roles'
definePageMeta({ middleware: ['admin'] })
const users = ref<User[]>([])
const employees = ref<Employee[]>([])
const sites = ref<Site[]>([])
const userSiteRoles = ref<UserSiteRole[]>([])
const isLoading = ref(false)
const isDrawerOpen = ref(false)
const isSubmitting = ref(false)
const editingUser = ref<User | null>(null)
const form = reactive({
username: '',
password: '',
accessMode: 'admin' as 'admin' | 'self' | 'sites',
employeeId: '' as number | '',
siteIds: [] as number[]
})
const validationTouched = reactive({
username: false,
password: false,
sites: false,
selfEmployee: false
})
const isUsernameValid = computed(() => form.username.trim() !== '')
const isPasswordValid = computed(() =>
editingUser.value ? true : form.password.trim() !== ''
)
const isFormValid = computed(() => isUsernameValid.value && isPasswordValid.value)
const isSitesValid = computed(() => form.siteIds.length > 0)
const isSelfEmployeeValid = computed(() => form.employeeId !== '')
const showUsernameError = computed(
() => validationTouched.username && !isUsernameValid.value
)
const showPasswordError = computed(
() => validationTouched.password && !isPasswordValid.value
)
const showSitesError = computed(
() => validationTouched.sites && form.accessMode === 'sites' && !isSitesValid.value
)
const showSelfEmployeeError = computed(
() =>
validationTouched.selfEmployee &&
form.accessMode === 'self' &&
!isSelfEmployeeValid.value
)
const userAccessById = computed(() => {
const rolesByUser = new Map<number, UserSiteRole[]>()
for (const role of userSiteRoles.value) {
const userId = role.user?.id
if (!userId) continue
const list = rolesByUser.get(userId) ?? []
list.push(role)
rolesByUser.set(userId, list)
}
return rolesByUser
})
const getAccessLabel = (user: User) => {
if (user.roles.includes('ROLE_ADMIN')) return 'Admin'
if (user.roles.includes('ROLE_SELF')) return 'Self'
const siteRoles = userAccessById.value.get(user.id) ?? []
return siteRoles.length > 0 ? 'Sites' : 'Aucun'
}
const getSiteLabels = (user: User) => {
const siteRoles = userAccessById.value.get(user.id) ?? []
if (siteRoles.length === 0) return '-'
const names = siteRoles
.map((role) => role.site?.name)
.filter((name): name is string => Boolean(name))
return names.length > 0 ? names.join(', ') : 'Sites sélectionnés'
}
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-primary-200'
const usernameFieldClass = computed(() => {
if (showUsernameError.value) {
return `${baseInputClass} border-red-500`
}
return `${baseInputClass} border-neutral-300`
})
const passwordFieldClass = computed(() => {
if (showPasswordError.value) {
return `${baseInputClass} border-red-500`
}
return `${baseInputClass} border-neutral-300`
})
const submitButtonClass = computed(() => {
if (isSubmitting.value || !isFormValid.value) {
return 'opacity-50 cursor-not-allowed'
}
return ''
})
const loadData = async () => {
isLoading.value = true
try {
const [usersData, employeesData, sitesData, userSiteRolesData] = await Promise.all([
listUsers(),
listEmployees(),
listSites(),
listUserSiteRoles()
])
users.value = usersData
employees.value = employeesData
sites.value = sitesData
userSiteRoles.value = userSiteRolesData
} finally {
isLoading.value = false
}
}
onMounted(loadData)
const resetForm = () => {
form.username = ''
form.password = ''
form.employeeId = ''
form.accessMode = 'admin'
form.siteIds = []
editingUser.value = null
validationTouched.username = false
validationTouched.password = false
validationTouched.sites = false
validationTouched.selfEmployee = false
}
const openCreate = () => {
resetForm()
isDrawerOpen.value = true
}
const openEdit = (user: User) => {
resetForm()
editingUser.value = user
form.username = user.username
form.password = ''
if (user.roles.includes('ROLE_ADMIN')) {
selectAccessMode('admin')
} else if (user.roles.includes('ROLE_SELF')) {
selectAccessMode('self')
} else {
selectAccessMode('sites')
}
form.employeeId = user.employee?.id ?? ''
const siteRoles = userAccessById.value.get(user.id) ?? []
form.siteIds = siteRoles.map((role) => role.site?.id).filter((id): id is number => typeof id === 'number')
isDrawerOpen.value = true
}
const closeDrawer = () => {
isDrawerOpen.value = false
resetForm()
}
const selectAccessMode = (mode: 'admin' | 'self' | 'sites') => {
form.accessMode = mode
if (mode !== 'sites') {
form.siteIds = []
}
}
const toggleSite = (siteId: number) => {
if (form.siteIds.includes(siteId)) {
form.siteIds = form.siteIds.filter((existing) => existing !== siteId)
} else {
form.siteIds = [...form.siteIds, siteId]
}
}
const handleSubmit = async () => {
if (isSubmitting.value) return
validationTouched.username = true
validationTouched.password = true
validationTouched.sites = true
validationTouched.selfEmployee = true
if (!isFormValid.value) return
if (form.accessMode === 'sites' && !isSitesValid.value) return
if (form.accessMode === 'self' && !isSelfEmployeeValid.value) return
isSubmitting.value = true
try {
const roles =
form.accessMode === 'admin'
? ['ROLE_ADMIN']
: form.accessMode === 'self'
? ['ROLE_SELF']
: []
const employeeId =
form.accessMode === 'self' ? (form.employeeId === '' ? null : Number(form.employeeId)) : null
if (editingUser.value) {
await updateUser(editingUser.value.id, {
username: form.username,
plainPassword: form.password.trim() ? form.password : undefined,
roles,
employeeId
})
const existingSiteRoles = userAccessById.value.get(editingUser.value.id) ?? []
if (existingSiteRoles.length > 0) {
await Promise.all(existingSiteRoles.map((role) => deleteUserSiteRole(role.id)))
}
if (form.accessMode === 'sites' && form.siteIds.length > 0) {
await Promise.all(
form.siteIds.map((siteId) =>
createUserSiteRole({
userId: editingUser.value!.id,
siteId,
role: 'SITE_ACCESS'
})
)
)
}
} else {
const created = await createUser({
username: form.username,
plainPassword: form.password,
roles,
employeeId
})
if (form.accessMode === 'sites' && form.siteIds.length > 0) {
await Promise.all(
form.siteIds.map((siteId) =>
createUserSiteRole({
userId: created.id,
siteId,
role: 'SITE_ACCESS'
})
)
)
}
}
closeDrawer()
await loadData()
} finally {
isSubmitting.value = false
}
}
</script>
+1
View File
@@ -1,4 +1,5 @@
export type UserData = {
id: number
username: string
roles: string[]
}
+8
View File
@@ -0,0 +1,8 @@
import type { Employee } from './employee'
export type User = {
id: number
username: string
roles: string[]
employee?: Employee | null
}
+38
View File
@@ -0,0 +1,38 @@
import { extractItems } from '~/utils/api'
export const createUserSiteRole = async (payload: {
userId: number
siteId: number
role: string
}) => {
const api = useApi()
return api.post('/user_site_roles', {
user: `/api/users/${payload.userId}`,
site: `/api/sites/${payload.siteId}`,
role: payload.role
}, {
toast: false
})
}
export type UserSiteRole = {
id: number
user: { id: number }
site: { id: number; name?: string }
role: string
}
export const listUserSiteRoles = async () => {
const api = useApi()
const data = await api.get<UserSiteRole[] | { 'hydra:member'?: UserSiteRole[] }>(
'/user_site_roles',
{},
{ toast: false }
)
return extractItems<UserSiteRole>(data)
}
export const deleteUserSiteRole = async (id: number) => {
const api = useApi()
return api.delete(`/user_site_roles/${id}`, {}, { toast: false })
}
+57
View File
@@ -0,0 +1,57 @@
import type { User } from './dto/user'
import { extractItems } from '~/utils/api'
export const listUsers = async () => {
const api = useApi()
const data = await api.get<User[] | { 'hydra:member'?: User[] }>(
'/users',
{},
{ toast: false }
)
return extractItems<User>(data)
}
export const createUser = async (payload: {
username: string
plainPassword: string
roles: string[]
employeeId?: number | null
}) => {
const api = useApi()
return api.post<User>(
'/users',
{
username: payload.username,
plainPassword: payload.plainPassword,
roles: payload.roles,
employee: payload.employeeId ? `/api/employees/${payload.employeeId}` : null
},
{
toastSuccessKey: 'success.user.create',
toastErrorKey: 'errors.user.create'
}
)
}
export const updateUser = async (id: number, payload: {
username: string
plainPassword?: string
roles: string[]
employeeId?: number | null
}) => {
const api = useApi()
const body: Record<string, unknown> = {
username: payload.username,
roles: payload.roles,
employee: payload.employeeId ? `/api/employees/${payload.employeeId}` : null
}
if (payload.plainPassword) {
body.plainPassword = payload.plainPassword
}
return api.patch<User>(`/users/${id}`, body, {
toastSuccessKey: 'success.user.update',
toastErrorKey: 'errors.user.update'
})
}
+33
View File
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260211120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Create user_site_roles table';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE TABLE user_site_roles (id SERIAL NOT NULL, user_id INT NOT NULL, site_id INT NOT NULL, role VARCHAR(50) NOT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_USER_SITE_ROLES_USER ON user_site_roles (user_id)');
$this->addSql('CREATE INDEX IDX_USER_SITE_ROLES_SITE ON user_site_roles (site_id)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_USER_SITE_ROLES_USER_SITE_ROLE ON user_site_roles (user_id, site_id, role)');
$this->addSql('ALTER TABLE user_site_roles ADD CONSTRAINT FK_USER_SITE_ROLES_USER FOREIGN KEY (user_id) REFERENCES users (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
$this->addSql('ALTER TABLE user_site_roles ADD CONSTRAINT FK_USER_SITE_ROLES_SITE FOREIGN KEY (site_id) REFERENCES sites (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE user_site_roles DROP CONSTRAINT FK_USER_SITE_ROLES_USER');
$this->addSql('ALTER TABLE user_site_roles DROP CONSTRAINT FK_USER_SITE_ROLES_SITE');
$this->addSql('DROP TABLE user_site_roles');
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260212120000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Link users to employees (one-to-one)';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE users ADD employee_id INT DEFAULT NULL');
$this->addSql('CREATE UNIQUE INDEX UNIQ_USERS_EMPLOYEE ON users (employee_id)');
$this->addSql('ALTER TABLE users ADD CONSTRAINT FK_USERS_EMPLOYEE FOREIGN KEY (employee_id) REFERENCES employees (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE users DROP CONSTRAINT FK_USERS_EMPLOYEE');
$this->addSql('DROP INDEX UNIQ_USERS_EMPLOYEE');
$this->addSql('ALTER TABLE users DROP COLUMN employee_id');
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260216100000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Create work_hours table';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE TABLE work_hours (id SERIAL NOT NULL, employee_id INT NOT NULL, work_date DATE NOT NULL, morning_from VARCHAR(5) DEFAULT NULL, morning_to VARCHAR(5) DEFAULT NULL, afternoon_from VARCHAR(5) DEFAULT NULL, afternoon_to VARCHAR(5) DEFAULT NULL, evening_from VARCHAR(5) DEFAULT NULL, evening_to VARCHAR(5) DEFAULT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_WORK_HOURS_EMPLOYEE ON work_hours (employee_id)');
$this->addSql('CREATE INDEX IDX_WORK_HOURS_DATE ON work_hours (work_date)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_WORK_HOURS_EMPLOYEE_DATE ON work_hours (employee_id, work_date)');
$this->addSql('ALTER TABLE work_hours ADD CONSTRAINT FK_WORK_HOURS_EMPLOYEE FOREIGN KEY (employee_id) REFERENCES employees (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE work_hours DROP CONSTRAINT FK_WORK_HOURS_EMPLOYEE');
$this->addSql('DROP TABLE work_hours');
}
}
+2 -1
View File
@@ -18,7 +18,8 @@ use App\State\AbsencePrintProvider;
new QueryParameter(key: 'from', required: true),
new QueryParameter(key: 'to', required: true),
new QueryParameter(key: 'sites', required: false),
]
],
security: "is_granted('ROLE_ADMIN')"
),
]
)]
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace App\ApiResource;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Post;
use App\State\WorkHourBulkUpsertProcessor;
#[ApiResource(
operations: [
new Post(
uriTemplate: '/work-hours/bulk-upsert',
security: "is_granted('ROLE_USER')",
output: WorkHourBulkUpsertResult::class,
processor: WorkHourBulkUpsertProcessor::class
),
]
)]
final class WorkHourBulkUpsert
{
public string $workDate = '';
/**
* @var list<array{
* employeeId:int,
* morningFrom?:?string,
* morningTo?:?string,
* afternoonFrom?:?string,
* afternoonTo?:?string,
* eveningFrom?:?string,
* eveningTo?:?string
* }>
*/
public array $entries = [];
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\ApiResource;
final class WorkHourBulkUpsertResult
{
public int $processed = 0;
public int $created = 0;
public int $updated = 0;
public int $deleted = 0;
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Doctrine;
use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use App\Entity\User;
use App\Entity\WorkHour;
use App\Security\EmployeeScopeService;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;
final readonly class WorkHourCollectionExtension implements QueryCollectionExtensionInterface
{
public function __construct(
private Security $security,
private EmployeeScopeService $employeeScopeService,
) {}
public function applyToCollection(
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
?Operation $operation = null,
array $context = []
): void {
// N'applique le filtrage qu'à la ressource WorkHour.
if (WorkHour::class !== $resourceClass) {
return;
}
$user = $this->security->getUser();
if (!$user instanceof User) {
// Pas d'utilisateur => aucune ligne renvoyée.
$queryBuilder->andWhere('1 = 0');
return;
}
$rootAlias = $queryBuilder->getRootAliases()[0];
$employeeAlias = 'employee_scope';
$queryBuilder->leftJoin(sprintf('%s.employee', $rootAlias), $employeeAlias)
->addSelect($employeeAlias)
;
// Filtrage SQL par scope (admin/self/site) avant retour API.
$this->employeeScopeService->applyEmployeeScope($queryBuilder, $employeeAlias, 'work_hour_scope', $user);
}
}
+3 -1
View File
@@ -20,7 +20,9 @@ use Symfony\Component\Serializer\Attribute\Groups;
],
denormalizationContext: [
'datetime_format' => 'Y-m-d',
]
],
paginationEnabled: false,
security: "is_granted('ROLE_ADMIN')",
)]
#[ApiFilter(DateFilter::class, properties: ['startDate', 'endDate'])]
#[ApiFilter(SearchFilter::class, properties: ['employee.site' => 'exact'])]
+5 -1
View File
@@ -8,7 +8,11 @@ use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(normalizationContext: ['groups' => ['absence_type:read']])]
#[ApiResource(
normalizationContext: ['groups' => ['absence_type:read']],
paginationEnabled: false,
security: "is_granted('ROLE_ADMIN')"
)]
#[ORM\Entity]
#[ORM\Table(name: 'absence_types')]
class AbsenceType
+3 -1
View File
@@ -11,7 +11,9 @@ use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
normalizationContext: ['groups' => ['employee:read', 'site:read']],
denormalizationContext: ['groups' => ['employee:write']]
denormalizationContext: ['groups' => ['employee:write']],
paginationEnabled: false,
security: "is_granted('ROLE_ADMIN')"
)]
#[ORM\Entity]
#[ORM\Table(name: 'employees')]
+5 -1
View File
@@ -8,7 +8,11 @@ use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(normalizationContext: ['groups' => ['site:read']])]
#[ApiResource(
normalizationContext: ['groups' => ['site:read']],
paginationEnabled: false,
security: "is_granted('ROLE_ADMIN')"
)]
#[ORM\Entity]
#[ORM\Table(name: 'sites')]
class Site
+108
View File
@@ -4,12 +4,20 @@ declare(strict_types=1);
namespace App\Entity;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use App\State\CurrentUserProvider;
use App\State\UserPasswordHasherProcessor;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
@@ -19,6 +27,29 @@ use Symfony\Component\Security\Core\User\UserInterface;
security: "is_granted('ROLE_USER')",
provider: CurrentUserProvider::class
),
new GetCollection(
normalizationContext: ['groups' => ['user:read', 'employee:read', 'site:read']],
security: "is_granted('ROLE_ADMIN')"
),
new Get(
uriTemplate: '/users/{id}',
normalizationContext: ['groups' => ['user:read', 'employee:read', 'site:read']],
security: "is_granted('ROLE_ADMIN')"
),
new Post(
denormalizationContext: ['groups' => ['user:write']],
normalizationContext: ['groups' => ['user:read']],
security: "is_granted('ROLE_ADMIN')",
processor: UserPasswordHasherProcessor::class
),
new Patch(
uriTemplate: '/users/{id}',
paginationEnabled: false,
normalizationContext: ['groups' => ['user:read']],
denormalizationContext: ['groups' => ['user:write']],
security: "is_granted('ROLE_ADMIN')",
processor: UserPasswordHasherProcessor::class
),
]
)]
#[ORM\Entity]
@@ -29,17 +60,40 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
#[Groups(['user:read'])]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 180)]
#[Groups(['user:read', 'user:write'])]
private string $username = '';
#[ORM\Column(type: 'json')]
#[Groups(['user:write'])]
private array $roles = [];
#[ORM\Column(type: 'string')]
private string $password = '';
#[Groups(['user:write'])]
private string $plainPassword = '';
#[ApiProperty(readableLink: true)]
#[ORM\OneToOne(targetEntity: Employee::class)]
#[ORM\JoinColumn(nullable: true, unique: true)]
#[Groups(['user:read', 'user:write'])]
private ?Employee $employee = null;
/**
* @var Collection<int, UserSiteRole>
*/
#[ORM\OneToMany(mappedBy: 'user', targetEntity: UserSiteRole::class, orphanRemoval: true)]
private Collection $siteRoles;
public function __construct()
{
$this->siteRoles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
@@ -65,6 +119,7 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
/**
* @return list<string>
*/
#[Groups(['user:read'])]
public function getRoles(): array
{
$roles = $this->roles;
@@ -95,5 +150,58 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface
return $this;
}
public function getPlainPassword(): string
{
return $this->plainPassword;
}
public function setPlainPassword(string $plainPassword): self
{
$this->plainPassword = $plainPassword;
return $this;
}
public function getEmployee(): ?Employee
{
return $this->employee;
}
public function setEmployee(?Employee $employee): self
{
$this->employee = $employee;
return $this;
}
/**
* @return Collection<int, UserSiteRole>
*/
public function getSiteRoles(): Collection
{
return $this->siteRoles;
}
public function addSiteRole(UserSiteRole $siteRole): self
{
if (!$this->siteRoles->contains($siteRole)) {
$this->siteRoles->add($siteRole);
$siteRole->setUser($this);
}
return $this;
}
public function removeSiteRole(UserSiteRole $siteRole): self
{
if ($this->siteRoles->removeElement($siteRole)) {
if ($siteRole->getUser() === $this) {
$siteRole->setUser(null);
}
}
return $this;
}
public function eraseCredentials(): void {}
}
+101
View File
@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace App\Entity;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new GetCollection(
uriTemplate: '/user_site_roles',
normalizationContext: ['groups' => ['user_site_role:read', 'site:read', 'user:read']],
security: "is_granted('ROLE_ADMIN')"
),
new Post(
uriTemplate: '/user_site_roles',
denormalizationContext: ['groups' => ['user_site_role:write']],
security: "is_granted('ROLE_ADMIN')"
),
new Delete(
uriTemplate: '/user_site_roles/{id}',
security: "is_granted('ROLE_ADMIN')"
),
],
paginationEnabled: false,
)]
#[ORM\Entity()]
#[ORM\Table(name: 'user_site_roles')]
#[ORM\UniqueConstraint(name: 'uniq_user_site_role', fields: ['user', 'site', 'role'])]
class UserSiteRole
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
#[Groups(['user_site_role:read'])]
private ?int $id = null;
#[ApiProperty(readableLink: true)]
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'siteRoles')]
#[ORM\JoinColumn(nullable: false)]
#[Groups(['user_site_role:read', 'user_site_role:write'])]
private ?User $user = null;
#[ApiProperty(readableLink: true)]
#[ORM\ManyToOne(targetEntity: Site::class)]
#[ORM\JoinColumn(nullable: false)]
#[Groups(['user_site_role:read', 'user_site_role:write'])]
private ?Site $site = null;
#[ORM\Column(type: 'string', length: 50)]
#[Groups(['user_site_role:read', 'user_site_role:write'])]
private string $role = '';
public function getId(): ?int
{
return $this->id;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getSite(): ?Site
{
return $this->site;
}
public function setSite(?Site $site): self
{
$this->site = $site;
return $this;
}
public function getRole(): string
{
return $this->role;
}
public function setRole(string $role): self
{
$this->role = $role;
return $this;
}
}
+178
View File
@@ -0,0 +1,178 @@
<?php
declare(strict_types=1);
namespace App\Entity;
use ApiPlatform\Doctrine\Orm\Filter\DateFilter;
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new GetCollection(
paginationEnabled: false,
normalizationContext: ['groups' => ['work_hour:read', 'employee:read', 'site:read']],
security: "is_granted('ROLE_USER')"
),
new Get(
normalizationContext: ['groups' => ['work_hour:read', 'employee:read', 'site:read']],
security: "is_granted('WORK_HOUR_VIEW', object)"
),
],
)]
#[ApiFilter(DateFilter::class, properties: ['workDate'])]
#[ApiFilter(SearchFilter::class, properties: ['employee' => 'exact', 'employee.site' => 'exact'])]
#[ORM\Entity]
#[ORM\Table(name: 'work_hours')]
#[ORM\UniqueConstraint(name: 'uniq_work_hours_employee_date', fields: ['employee', 'workDate'])]
class WorkHour
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
#[Groups(['work_hour:read'])]
private ?int $id = null;
#[ApiProperty(readableLink: true)]
#[ORM\ManyToOne(targetEntity: Employee::class)]
#[ORM\JoinColumn(nullable: false)]
#[Groups(['work_hour:read'])]
private ?Employee $employee = null;
#[ORM\Column(type: 'date_immutable')]
#[Groups(['work_hour:read'])]
private DateTimeInterface $workDate;
#[ORM\Column(type: 'string', length: 5, nullable: true)]
#[Groups(['work_hour:read'])]
private ?string $morningFrom = null;
#[ORM\Column(type: 'string', length: 5, nullable: true)]
#[Groups(['work_hour:read'])]
private ?string $morningTo = null;
#[ORM\Column(type: 'string', length: 5, nullable: true)]
#[Groups(['work_hour:read'])]
private ?string $afternoonFrom = null;
#[ORM\Column(type: 'string', length: 5, nullable: true)]
#[Groups(['work_hour:read'])]
private ?string $afternoonTo = null;
#[ORM\Column(type: 'string', length: 5, nullable: true)]
#[Groups(['work_hour:read'])]
private ?string $eveningFrom = null;
#[ORM\Column(type: 'string', length: 5, nullable: true)]
#[Groups(['work_hour:read'])]
private ?string $eveningTo = null;
public function getId(): ?int
{
return $this->id;
}
public function getEmployee(): ?Employee
{
return $this->employee;
}
public function setEmployee(?Employee $employee): self
{
$this->employee = $employee;
return $this;
}
public function getWorkDate(): DateTimeInterface
{
return $this->workDate;
}
public function setWorkDate(DateTimeInterface $workDate): self
{
$this->workDate = $workDate;
return $this;
}
public function getMorningFrom(): ?string
{
return $this->morningFrom;
}
public function setMorningFrom(?string $morningFrom): self
{
$this->morningFrom = $morningFrom;
return $this;
}
public function getMorningTo(): ?string
{
return $this->morningTo;
}
public function setMorningTo(?string $morningTo): self
{
$this->morningTo = $morningTo;
return $this;
}
public function getAfternoonFrom(): ?string
{
return $this->afternoonFrom;
}
public function setAfternoonFrom(?string $afternoonFrom): self
{
$this->afternoonFrom = $afternoonFrom;
return $this;
}
public function getAfternoonTo(): ?string
{
return $this->afternoonTo;
}
public function setAfternoonTo(?string $afternoonTo): self
{
$this->afternoonTo = $afternoonTo;
return $this;
}
public function getEveningFrom(): ?string
{
return $this->eveningFrom;
}
public function setEveningFrom(?string $eveningFrom): self
{
$this->eveningFrom = $eveningFrom;
return $this;
}
public function getEveningTo(): ?string
{
return $this->eveningTo;
}
public function setEveningTo(?string $eveningTo): self
{
$this->eveningTo = $eveningTo;
return $this;
}
}
+99
View File
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace App\Security;
use App\Entity\Employee;
use App\Entity\User;
use Doctrine\ORM\QueryBuilder;
class EmployeeScopeService
{
public const string SITE_ACCESS_ROLE = 'SITE_ACCESS';
/**
* Règle métier centrale d'accès à un employé.
* - Admin : accès global
* - Self : uniquement son employé lié
* - Site : uniquement les employés des sites autorisés.
*/
public function canAccessEmployee(User $user, Employee $employee): bool
{
if (in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return true;
}
if (in_array('ROLE_SELF', $user->getRoles(), true)) {
return $user->getEmployee()?->getId() === $employee->getId();
}
$employeeSiteId = $employee->getSite()?->getId();
if (!$employeeSiteId) {
return false;
}
return in_array($employeeSiteId, $this->getAllowedSiteIds($user), true);
}
/**
* Retourne la liste des sites accessibles via user_site_roles.
*
* @return list<int>
*/
public function getAllowedSiteIds(User $user): array
{
$siteIds = [];
foreach ($user->getSiteRoles() as $siteRole) {
if (self::SITE_ACCESS_ROLE !== $siteRole->getRole()) {
continue;
}
$siteId = $siteRole->getSite()?->getId();
if ($siteId) {
$siteIds[] = $siteId;
}
}
return array_values(array_unique($siteIds));
}
/**
* Applique le scope directement sur un QueryBuilder Doctrine.
* Cette méthode est utilisée pour filtrer les collections SQL
* avant sérialisation (plus sûr et plus performant).
*/
public function applyEmployeeScope(QueryBuilder $qb, string $employeeAlias, string $paramPrefix, User $user): void
{
if (in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return;
}
if (in_array('ROLE_SELF', $user->getRoles(), true)) {
$employeeId = $user->getEmployee()?->getId();
if (!$employeeId) {
$qb->andWhere('1 = 0');
return;
}
$qb->andWhere(sprintf('%s.id = :%s_employee_id', $employeeAlias, $paramPrefix))
->setParameter(sprintf('%s_employee_id', $paramPrefix), $employeeId)
;
return;
}
$siteIds = $this->getAllowedSiteIds($user);
if ([] === $siteIds) {
$qb->andWhere('1 = 0');
return;
}
$qb->andWhere(sprintf('%s.site IN (:%s_site_ids)', $employeeAlias, $paramPrefix))
->setParameter(sprintf('%s_site_ids', $paramPrefix), $siteIds)
;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\User;
use App\Entity\WorkHour;
use App\Security\EmployeeScopeService;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class WorkHourVoter extends Voter
{
public const string VIEW = 'WORK_HOUR_VIEW';
public const string EDIT = 'WORK_HOUR_EDIT';
public function __construct(
private readonly Security $security,
private readonly EmployeeScopeService $employeeScopeService,
) {}
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, [self::VIEW, self::EDIT], true) && $subject instanceof WorkHour;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
{
// On ne traite que des utilisateurs applicatifs authentifiés.
$user = $this->security->getUser();
if (!$user instanceof User) {
return false;
}
if (!$subject instanceof WorkHour) {
return false;
}
$employee = $subject->getEmployee();
if (null === $employee) {
return false;
}
// Délégation de la règle au service de scope unique (évite la duplication).
return $this->employeeScopeService->canAccessEmployee($user, $employee);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\State;
use ApiPlatform\Doctrine\Common\State\PersistProcessor;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\User;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
final readonly class UserPasswordHasherProcessor implements ProcessorInterface
{
public function __construct(
private PersistProcessor $persistProcessor,
private UserPasswordHasherInterface $passwordHasher
) {}
public function process(
mixed $data,
Operation $operation,
array $uriVariables = [],
array $context = []
): mixed {
if ($data instanceof User && '' !== $data->getPlainPassword()) {
$hashed = $this->passwordHasher->hashPassword($data, $data->getPlainPassword());
$data->setPassword($hashed);
$data->setPlainPassword('');
}
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
}
}
+384
View File
@@ -0,0 +1,384 @@
<?php
declare(strict_types=1);
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\ApiResource\WorkHourBulkUpsert;
use App\ApiResource\WorkHourBulkUpsertResult;
use App\Entity\Employee;
use App\Entity\User;
use App\Entity\WorkHour;
use App\Security\EmployeeScopeService;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
final readonly class WorkHourBulkUpsertProcessor implements ProcessorInterface
{
public function __construct(
private EntityManagerInterface $entityManager,
private Security $security,
private EmployeeScopeService $employeeScopeService,
) {}
public function process(
mixed $data,
Operation $operation,
array $uriVariables = [],
array $context = []
): WorkHourBulkUpsertResult {
// Endpoint dédié au bulk: on refuse tout autre payload.
if (!$data instanceof WorkHourBulkUpsert) {
throw new BadRequestHttpException('Invalid payload.');
}
$user = $this->security->getUser();
if (!$user instanceof User) {
throw new AccessDeniedHttpException('Authentication required.');
}
$workDate = DateTimeImmutable::createFromFormat('Y-m-d', $data->workDate);
if (!$workDate || $workDate->format('Y-m-d') !== $data->workDate) {
throw new UnprocessableEntityHttpException('workDate must use Y-m-d format.');
}
if ([] === $data->entries) {
throw new UnprocessableEntityHttpException('entries must contain at least one employee.');
}
// Vérifie que tous les employés envoyés sont dans le scope de l'utilisateur courant.
$employeeIds = $this->extractEmployeeIds($data->entries);
$employeesById = $this->loadAccessibleEmployees($employeeIds, $user);
if (count($employeesById) !== count($employeeIds)) {
throw new AccessDeniedHttpException('At least one employee is unknown or outside your scope.');
}
$existingByEmployeeId = $this->loadExistingWorkHours($workDate, array_values($employeesById));
$result = new WorkHourBulkUpsertResult();
foreach ($data->entries as $entry) {
$employeeId = (int) $entry['employeeId'];
$employee = $employeesById[$employeeId] ?? null;
if (!$employee) {
throw new AccessDeniedHttpException(sprintf('Employee %d is outside your scope.', $employeeId));
}
$normalized = $this->normalizeEntry($entry, $employeeId);
$existing = $existingByEmployeeId[$employeeId] ?? null;
if ($this->isEntryEmpty($normalized)) {
// Convention choisie: une ligne vide supprime l'enregistrement existant.
if ($existing) {
$this->entityManager->remove($existing);
++$result->deleted;
}
++$result->processed;
continue;
}
if ($existing) {
$workHour = $existing;
++$result->updated;
} else {
// Upsert: création si aucune ligne n'existe pour (employé, date).
$workHour = new WorkHour()
->setEmployee($employee)
->setWorkDate($workDate)
;
$this->entityManager->persist($workHour);
++$result->created;
}
$this->hydrateWorkHour($workHour, $normalized);
++$result->processed;
}
$this->entityManager->flush();
return $result;
}
/**
* @param list<array<string, mixed>> $entries
*
* @return list<int>
*/
private function extractEmployeeIds(array $entries): array
{
$ids = [];
foreach ($entries as $index => $entry) {
if (!is_array($entry) || !array_key_exists('employeeId', $entry)) {
throw new UnprocessableEntityHttpException(sprintf('entries[%d].employeeId is required.', $index));
}
$employeeId = (int) $entry['employeeId'];
if ($employeeId <= 0) {
throw new UnprocessableEntityHttpException(sprintf('entries[%d].employeeId must be a positive integer.', $index));
}
if (isset($ids[$employeeId])) {
throw new UnprocessableEntityHttpException(sprintf('Employee %d appears multiple times in the same bulk payload.', $employeeId));
}
$ids[$employeeId] = $employeeId;
}
return array_values($ids);
}
/**
* @param list<int> $employeeIds
*
* @return array<int, Employee>
*/
private function loadAccessibleEmployees(array $employeeIds, User $user): array
{
if ([] === $employeeIds) {
return [];
}
$qb = $this->entityManager
->getRepository(Employee::class)
->createQueryBuilder('e')
->andWhere('e.id IN (:ids)')
->setParameter('ids', $employeeIds)
;
$this->employeeScopeService->applyEmployeeScope($qb, 'e', 'bulk_scope', $user);
/** @var list<Employee> $employees */
$employees = $qb->getQuery()->getResult();
$byId = [];
foreach ($employees as $employee) {
$employeeId = $employee->getId();
if ($employeeId) {
$byId[$employeeId] = $employee;
}
}
return $byId;
}
/**
* @param list<Employee> $employees
*
* @return array<int, WorkHour>
*/
private function loadExistingWorkHours(DateTimeImmutable $workDate, array $employees): array
{
if ([] === $employees) {
return [];
}
$qb = $this->entityManager
->getRepository(WorkHour::class)
->createQueryBuilder('w')
->leftJoin('w.employee', 'e')
->addSelect('e')
->andWhere('w.workDate = :workDate')
->andWhere('w.employee IN (:employees)')
->setParameter('workDate', $workDate)
->setParameter('employees', $employees)
;
/** @var list<WorkHour> $workHours */
$workHours = $qb->getQuery()->getResult();
$byEmployeeId = [];
foreach ($workHours as $workHour) {
$employeeId = $workHour->getEmployee()?->getId();
if ($employeeId) {
$byEmployeeId[$employeeId] = $workHour;
}
}
return $byEmployeeId;
}
/**
* @param array<string, mixed> $entry
*
* @return array{
* morningFrom:?string,
* morningTo:?string,
* afternoonFrom:?string,
* afternoonTo:?string,
* eveningFrom:?string,
* eveningTo:?string
* }
*/
private function normalizeEntry(array $entry, int $employeeId): array
{
$normalized = [
'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'),
];
$this->validateRanges($normalized, $employeeId);
return $normalized;
}
private function normalizeTime(mixed $value, int $employeeId, string $field): ?string
{
if (null === $value || '' === $value) {
return null;
}
if (!is_string($value)) {
throw new UnprocessableEntityHttpException(sprintf(
'Employee %d: %s must be a string in HH:MM format.',
$employeeId,
$field
));
}
$time = trim($value);
if (!preg_match('/^(?:[01]\d|2[0-3]):[0-5]\d$/', $time)) {
throw new UnprocessableEntityHttpException(sprintf(
'Employee %d: %s must use HH:MM format.',
$employeeId,
$field
));
}
return $time;
}
/**
* @param array{
* morningFrom:?string,
* morningTo:?string,
* afternoonFrom:?string,
* afternoonTo:?string,
* eveningFrom:?string,
* eveningTo:?string
* } $entry
*/
private function validateRanges(array $entry, int $employeeId): void
{
$ranges = [
'morning' => [$entry['morningFrom'], $entry['morningTo']],
'afternoon' => [$entry['afternoonFrom'], $entry['afternoonTo']],
'evening' => [$entry['eveningFrom'], $entry['eveningTo']],
];
$normalizedRanges = [];
foreach ($ranges as $label => [$from, $to]) {
// On force des paires from/to complètes par créneau.
if ((null === $from) xor (null === $to)) {
throw new UnprocessableEntityHttpException(sprintf(
'Employee %d: %s range must contain both from and to.',
$employeeId,
$label
));
}
if (null === $from || null === $to) {
continue;
}
$fromMinutes = $this->toMinutes($from);
$toMinutes = $this->toMinutes($to);
if ($fromMinutes >= $toMinutes) {
throw new UnprocessableEntityHttpException(sprintf(
'Employee %d: %s from must be earlier than to.',
$employeeId,
$label
));
}
$normalizedRanges[] = [
'label' => $label,
'from' => $fromMinutes,
'to' => $toMinutes,
];
}
usort(
$normalizedRanges,
static fn (array $rangeA, array $rangeB): int => $rangeA['from'] <=> $rangeB['from']
);
$previous = null;
foreach ($normalizedRanges as $range) {
// Empêche deux créneaux qui se chevauchent sur une même journée.
if (null !== $previous && $range['from'] < $previous['to']) {
throw new UnprocessableEntityHttpException(sprintf(
'Employee %d: %s overlaps %s.',
$employeeId,
$range['label'],
$previous['label']
));
}
$previous = $range;
}
}
/**
* @param array{
* morningFrom:?string,
* morningTo:?string,
* afternoonFrom:?string,
* afternoonTo:?string,
* eveningFrom:?string,
* eveningTo:?string
* } $entry
*/
private function isEntryEmpty(array $entry): bool
{
return null === $entry['morningFrom']
&& null === $entry['morningTo']
&& null === $entry['afternoonFrom']
&& null === $entry['afternoonTo']
&& null === $entry['eveningFrom']
&& null === $entry['eveningTo'];
}
/**
* @param array{
* morningFrom:?string,
* morningTo:?string,
* afternoonFrom:?string,
* afternoonTo:?string,
* eveningFrom:?string,
* eveningTo:?string
* } $entry
*/
private function hydrateWorkHour(WorkHour $workHour, array $entry): void
{
$workHour
->setMorningFrom($entry['morningFrom'])
->setMorningTo($entry['morningTo'])
->setAfternoonFrom($entry['afternoonFrom'])
->setAfternoonTo($entry['afternoonTo'])
->setEveningFrom($entry['eveningFrom'])
->setEveningTo($entry['eveningTo'])
;
}
private function toMinutes(string $time): int
{
[$hours, $minutes] = array_map('intval', explode(':', $time, 2));
return ($hours * 60) + $minutes;
}
}