changement au niveau de requetes adaptés aux collaborateurs AD

This commit is contained in:
2025-08-27 09:40:17 +02:00
parent 9fb0c0a27f
commit ed4a7c02ca
29 changed files with 1741 additions and 548 deletions

View File

@@ -1,100 +1,293 @@
<?php
// (headers, connexion, lecture FormData ou JSON — pareil que précédemment)
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }
header("Content-Type: application/json");
ob_clean();
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: http://localhost:5173");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
$host="192.168.0.4"; $dbname="DemandeConge"; $username="wpuser"; $password="-2b/)ru5/Bi8P[7_";
$conn = new mysqli($host,$username,$password,$dbname);
if ($conn->connect_error) { echo json_encode(["success"=>false,"message"=>"Erreur DB: ".$conn->connect_error]); exit(); }
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// Lecture JSON (support FormData via $_POST['data'])
if (isset($_POST['data'])) {
$data = json_decode($_POST['data'], true);
// Debug
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Connexion DB
$host = "192.168.0.4";
$dbname = "DemandeConge";
$username = "wpuser";
$password = "-2b/)ru5/Bi8P[7_";
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode(["success"=>false,"message"=>"Erreur DB: ".$e->getMessage()]);
exit;
}
// Lecture JSON brut
$input = file_get_contents('php://input');
$data = json_decode($input, true);
// 🔎 Debug pour vérifier ce qui arrive
error_log("📥 Payload reçu : " . print_r($data, true));
if (!$data) {
echo json_encode(["success"=>false,"message"=>"JSON invalide","raw"=>$input]);
exit;
}
// Vérification des champs obligatoires
$required = ['DateDebut','DateFin','Repartition','NombreJours','Email','Nom'];
foreach ($required as $f) {
if (!array_key_exists($f, $data)) {
echo json_encode([
"success"=>false,
"message"=>"Donnée manquante : $f",
"debug"=>$data
]);
exit;
}
}
$dateDebut = $data['DateDebut'];
$dateFin = $data['DateFin'];
$commentaire = $data['Commentaire'] ?? '';
$numDays = (float)$data['NombreJours'];
$userEmail = $data['Email'];
$userName = $data['Nom'];
$statut = 'En attente';
$currentDate = date('Y-m-d H:i:s');
// 🔎 Identifier si c'est un CollaborateurAD ou un User
$stmt = $pdo->prepare("SELECT id FROM CollaborateurAD WHERE email = :email LIMIT 1");
$stmt->execute([':email'=>$userEmail]);
$collabAD = $stmt->fetch(PDO::FETCH_ASSOC);
$isAD = false;
$employeeId = null;
$collaborateurId = null;
if ($collabAD) {
$isAD = true;
$collaborateurId = (int)$collabAD['id'];
} else {
$input = file_get_contents('php://input');
$data = json_decode($input, true);
}
if ($data === null) {
echo json_encode(["success"=>false,"message"=>"JSON invalide"]); $conn->close(); exit();
$stmt = $pdo->prepare("SELECT ID FROM Users WHERE Email = :email LIMIT 1");
$stmt->execute([':email'=>$userEmail]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
echo json_encode(["success"=>false,"message"=>"Aucun collaborateur trouvé pour $userEmail"]);
exit;
}
$employeeId = (int)$user['ID'];
}
// Vérifs minimales
if (!isset($data['EmployeeId'],$data['DateDebut'],$data['DateFin'],$data['Repartition'],$data['NombreJours'])) {
echo json_encode(["success"=>false,"message"=>"Données manquantes"]); $conn->close(); exit();
}
$employeeId = (int)$data['EmployeeId'];
$dateDebut = $data['DateDebut'];
$dateFin = $data['DateFin'];
$commentaire= $data['Commentaire'] ?? '';
$numDays = (float)$data['NombreJours'];
$statut = 'En attente';
$currentDate= date('Y-m-d H:i:s');
// 1) Construire la liste d'IDs pour TypeCongeId (CSV) (compatibilité)
// 🔎 Résoudre les IDs des types de congés
$typeIds = [];
foreach ($data['Repartition'] as $rep) {
$code = $rep['TypeConge']; // CP, RTT, ABS ou texte libre
$code = $rep['TypeConge'];
switch ($code) {
case 'CP': $name = 'Congé payé'; break;
case 'RTT': $name = 'RTT'; break;
case 'ABS': $name = 'Congé maladie'; break;
default: $name = $code; break;
default: $name = $code; break;
}
$s = $pdo->prepare("SELECT Id FROM TypeConge WHERE Nom = :nom LIMIT 1");
$s->execute([':nom'=>$name]);
if ($r = $s->fetch(PDO::FETCH_ASSOC)) {
$typeIds[] = $r['Id'];
}
$s = $conn->prepare("SELECT Id FROM TypeConge WHERE Nom = ?");
$s->bind_param("s", $name);
$s->execute();
$res = $s->get_result();
if ($r = $res->fetch_assoc()) $typeIds[] = $r['Id'];
$s->close();
}
if (empty($typeIds)) { echo json_encode(["success"=>false,"message"=>"Aucun type valide"]); $conn->close(); exit(); }
if (empty($typeIds)) {
echo json_encode(["success"=>false,"message"=>"Aucun type de congé valide"]);
exit;
}
$typeCongeIdCsv = implode(',', $typeIds);
// 2) Insertion unique dans DemandeConge
$insert = $conn->prepare("INSERT INTO DemandeConge (EmployeeId, DateDebut, DateFin, TypeCongeId, Statut, DateDemande, Commentaire, Validateur, NombreJours) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$validParam = '';
$insert->bind_param("isssssssd", $employeeId, $dateDebut, $dateFin, $typeCongeIdCsv, $statut, $currentDate, $commentaire, $validParam, $numDays);
if (!$insert->execute()) {
echo json_encode(["success"=>false,"message"=>"Erreur insert DemandeConge: ".$insert->error]);
$insert->close(); $conn->close(); exit();
}
$demandeId = $conn->insert_id;
$insert->close();
// Insertion DemandeConge
$sql = "INSERT INTO DemandeConge
(EmployeeId, CollaborateurADId, DateDebut, DateFin, TypeCongeId, Statut, DateDemande, Commentaire, Validateur, NombreJours)
VALUES (:eid, :cid, :dd, :df, :tc, :st, :cd, :com, :val, :nj)";
// 3) INSÉRER la répartition réelle dans DemandeCongeType (une ligne par type)
$insertType = $conn->prepare("INSERT INTO DemandeCongeType (DemandeCongeId, TypeCongeId, NombreJours) VALUES (?, ?, ?)");
if (!$insertType) {
echo json_encode(["success"=>false,"message"=>"Erreur préparation DemandeCongeType: ".$conn->error]); $conn->close(); exit();
}
$stmt = $pdo->prepare($sql);
$stmt->execute([
':eid'=> $isAD ? 0 : $employeeId,
':cid'=> $isAD ? $collaborateurId : null,
':dd'=>$dateDebut,
':df'=>$dateFin,
':tc'=>$typeCongeIdCsv,
':st'=>$statut,
':cd'=>$currentDate,
':com'=>$commentaire,
':val'=>'',
':nj'=>$numDays
]);
$demandeId = $pdo->lastInsertId();
// ✅ Insertion DemandeCongeType
$sql = "INSERT INTO DemandeCongeType (DemandeCongeId, TypeCongeId, NombreJours) VALUES (:did, :tid, :nj)";
$stmt = $pdo->prepare($sql);
foreach ($data['Repartition'] as $rep) {
$code = $rep['TypeConge'];
$jours = (float)$rep['NombreJours'];
$code = $rep['TypeConge'];
switch ($code) {
case 'CP': $name = 'Congé payé'; break;
case 'RTT': $name = 'RTT'; break;
case 'ABS': $name = 'Congé maladie'; break;
default: $name = $code; break;
default: $name = $code; break;
}
$s = $conn->prepare("SELECT Id FROM TypeConge WHERE Nom = ?");
$s->bind_param("s", $name);
$s->execute();
$res = $s->get_result();
if ($r = $res->fetch_assoc()) {
$typeId = (int)$r['Id'];
$insertType->bind_param("iid", $demandeId, $typeId, $jours); // i,i,d
$insertType->execute();
$s = $pdo->prepare("SELECT Id FROM TypeConge WHERE Nom = :nom LIMIT 1");
$s->execute([':nom'=>$name]);
if ($r = $s->fetch(PDO::FETCH_ASSOC)) {
$stmt->execute([
':did'=>$demandeId,
':tid'=>$r['Id'],
':nj'=>$jours
]);
}
$s->close();
}
$insertType->close();
echo json_encode(["success"=>true,"message"=>"Demande soumise", "request_id"=>$demandeId]);
$conn->close();
?>
// ✅ Récupérer les validateurs selon hiérarchie
if ($isAD) {
$stmt = $pdo->prepare("
SELECT c.email
FROM HierarchieValidationAD hv
JOIN CollaborateurAD c ON hv.SuperieurId = c.id
WHERE hv.CollaborateurId = :id
");
$stmt->execute([':id'=>$collaborateurId]);
} else {
$stmt = $pdo->prepare("
SELECT u.Email
FROM HierarchieValidation hv
JOIN Users u ON hv.SuperieurId = u.ID
WHERE hv.EmployeId = :id
");
$stmt->execute([':id'=>$employeeId]);
}
$managers = $stmt->fetchAll(PDO::FETCH_COLUMN);
# =============================================================
# 📧 AUTH Microsoft Graph (client_credentials)
# =============================================================
$tenantId = "9840a2a0-6ae1-4688-b03d-d2ec291be0f9";
$clientId = "4bb4cc24-bac3-427c-b02c-5d14fc67b561";
$clientSecret = "gvf8Q~545Bafn8yYsgjW~QG_P1lpzaRe6gJNgb2t";
$url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
$data = [
"client_id" => $clientId,
"scope" => "https://graph.microsoft.com/.default",
"client_secret" => $clientSecret,
"grant_type" => "client_credentials"
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/x-www-form-urlencoded"
]);
$response = curl_exec($ch);
curl_close($ch);
$tokenData = json_decode($response, true);
if (!isset($tokenData['access_token'])) {
echo json_encode(["success" => false, "message" => "Impossible de générer un token Graph", "debug"=>$tokenData]);
exit;
}
$accessToken = $tokenData['access_token'];
# =============================================================
# 📧 Fonction envoi mail
# =============================================================
function sendMailGraph($accessToken, $fromEmail, $toEmail, $subject, $bodyHtml) {
$url = "https://graph.microsoft.com/v1.0/users/$fromEmail/sendMail";
$mailData = [
"message" => [
"subject" => $subject,
"body" => [
"contentType" => "HTML",
"content" => $bodyHtml
],
"toRecipients" => [
["emailAddress" => ["address" => $toEmail]]
]
],
"saveToSentItems" => "false"
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $accessToken",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($mailData));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 200 && $httpCode < 300) {
return true;
} else {
error_log("❌ Erreur envoi mail: $response");
return false;
}
}
# =============================================================
# 📧 Envoi automatique des emails
# =============================================================
$fromEmail = "noreply@ensup.eu";
# Mail au collaborateur
sendMailGraph(
$accessToken,
$fromEmail,
$userEmail,
"Confirmation de votre demande de congés",
"
Bonjour {$userName},<br/><br/>
Votre demande du <b>{$dateDebut}</b> au <b>{$dateFin}</b>
({$numDays} jour(s)) a bien été enregistrée.<br/>
Elle est en attente de validation par votre manager.<br/><br/>
Merci.
"
);
# Mail aux managers
foreach ($managers as $managerEmail) {
sendMailGraph(
$accessToken,
$fromEmail,
$managerEmail,
"Nouvelle demande de congé - {$userName}",
"
Bonjour,<br/><br/>
{$userName} a soumis une demande de congé :<br/>
- Du <b>{$dateDebut}</b> au <b>{$dateFin}</b> ({$numDays} jour(s))<br/>
- Commentaire : " . (!empty($commentaire) ? $commentaire : "Aucun") . "<br/><br/>
Merci de valider cette demande.
"
);
}
# ✅ Réponse finale
echo json_encode([
"success"=>true,
"message"=>"Demande soumise",
"request_id"=>$demandeId,
"managers"=>$managers
]);