| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355 |
- <?php
- /**
- * Orchestration de création d'utilisateur Lucca
- *
- * Point REST pour automatiser l'intégration des collaborateurs dans Lucca
- * Basé sur le workflow documenté dans orchestrat.php
- *
- * Méthode : POST
- * Body JSON : Fiche collaborateur candidate
- * {
- * "demande_status": "Confirmé RH",
- * "demande_login": "prenom.nom@sipa-automobiles.fr",
- * "firstName": "Prénom",
- * "lastName": "Nom",
- * "mail": "prenom.nom@sipa-automobiles.fr",
- * "dtContractStart": "2025-11-09T00:00:00",
- * "legalEntityId": 1,
- * "departmentId": 2,
- * "cultureID": 1036,
- * "rolePrincipalId": 4,
- * "employeeNumber": "MAT12345",
- * "managerId": 1919,
- * "birthDate": "1990-05-15T00:00:00",
- * "calendarId": null,
- * "habilitedRoles": [{"id": 3}],
- * ... autres champs optionnels
- * }
- *
- * Réponse :
- * {
- * "success": true,
- * "action": "user_created" | "user_already_exists" | "status_rejected",
- * "lucca_status": "user created in Lucca" | "user already exists in Lucca" | "status not confirmed",
- * "lucca_user_id": 123,
- * "lucca_log": {...},
- * "user_data": {...}
- * }
- */
- // Activation du débogage
- ini_set('display_errors', 1);
- ini_set('display_startup_errors', 1);
- error_reporting(E_ALL);
- /**
- * Envoie une réponse JSON avec le code HTTP approprié
- */
- function json_response(int $statusCode, array $payload): void {
- http_response_code($statusCode);
- header('Content-Type: application/json; charset=utf-8');
- echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
- exit;
- }
- /**
- * Crée une entrée de log pour la traçabilité
- */
- function create_log_entry(string $action_type, string $user_identifier, string $result, string $message, $user_id = null): array {
- return [
- 'date' => date('Y-m-d H:i:s'),
- 'action_type' => $action_type,
- 'user_identifier' => $user_identifier,
- 'result' => $result,
- 'message' => $message,
- 'lucca_user_id' => $user_id
- ];
- }
- // Charge le client API Lucca
- require_once __DIR__ . '/../lucca_client.php';
- // ==========================================
- // RÉCEPTION DES DONNÉES
- // ==========================================
- // Récupère le JSON en entrée
- $input = json_decode(file_get_contents("php://input"), true);
- // Vérification que le JSON est valide
- if (!is_array($input)) {
- json_response(400, [
- "success" => false,
- "error" => "Invalid JSON",
- "message" => "Request body must contain valid JSON"
- ]);
- }
- // ==========================================
- // ÉTAPE 1 : VÉRIFICATION DU STATUT
- // ==========================================
- if (!isset($input['demande_status'])) {
- json_response(400, [
- "success" => false,
- "error" => "Missing demande_status",
- "message" => "Field 'demande_status' is required to determine if the request should be processed"
- ]);
- }
- // Vérifier si le statut est "Confirmé RH"
- if ($input['demande_status'] !== 'Confirmé RH') {
- $log = create_log_entry(
- 'status_check',
- $input['demande_login'] ?? 'unknown',
- 'rejected',
- "Status is '{$input['demande_status']}', expected 'Confirmé RH'"
- );
-
- json_response(200, [
- "success" => false,
- "action" => "status_rejected",
- "lucca_status" => "status not confirmed",
- "message" => "Request not processed: status must be 'Confirmé RH'",
- "current_status" => $input['demande_status'],
- "lucca_log" => $log
- ]);
- }
- // ==========================================
- // ÉTAPE 2 : VÉRIFICATION D'EXISTENCE
- // ==========================================
- if (!isset($input['demande_login']) || empty($input['demande_login'])) {
- json_response(400, [
- "success" => false,
- "error" => "Missing demande_login",
- "message" => "Field 'demande_login' is required to check if user exists"
- ]);
- }
- $login = $input['demande_login'];
- // Appel GET /users pour vérifier l'existence
- $check_result = lucca_request('GET', '/api/v3/users', [
- 'login' => $login,
- 'fields' => 'id,name,login,mail,dtContractStart,dtContractEnd',
- 'limit' => 1
- ], null, 60, false);
- // Erreur de connexion
- if (!empty($check_result['error']) || $check_result['code'] === 0) {
- $log = create_log_entry(
- 'check_existence',
- $login,
- 'error',
- "API connection error: " . ($check_result['error'] ?? 'No response from server')
- );
-
- json_response(503, [
- "success" => false,
- "action" => "connection_error",
- "lucca_status" => "user check failed",
- "message" => "Unable to verify if user exists in Lucca",
- "details" => $check_result['error'] ?? "No response from server",
- "lucca_log" => $log
- ]);
- }
- // Erreur API autre que 200
- if ($check_result['code'] !== 200) {
- $log = create_log_entry(
- 'check_existence',
- $login,
- 'error',
- "API error {$check_result['code']}: " . ($check_result['lucca_error'] ?? $check_result['error_message'] ?? 'Unknown error')
- );
-
- json_response($check_result['code'], [
- "success" => false,
- "action" => "api_error",
- "lucca_status" => "user check failed",
- "message" => "Error checking user existence",
- "error_details" => lucca_format_error($check_result),
- "lucca_log" => $log
- ]);
- }
- // Vérifier si un utilisateur existe déjà
- $existing_users = $check_result['data']['data']['items'] ?? [];
- if (!empty($existing_users)) {
- // Utilisateur existe déjà
- $existing_user = $existing_users[0];
- $user_id = $existing_user['id'] ?? null;
-
- $log = create_log_entry(
- 'check_existence',
- $login,
- 'found',
- "User already exists in Lucca (active or inactive)",
- $user_id
- );
-
- json_response(200, [
- "success" => true,
- "action" => "user_already_exists",
- "lucca_status" => "user already exists in Lucca",
- "lucca_user_id" => $user_id,
- "message" => "User with this login already exists in Lucca",
- "existing_user" => $existing_user,
- "lucca_log" => $log
- ]);
- }
- // ==========================================
- // ÉTAPE 3 : CRÉATION DE L'UTILISATEUR
- // ==========================================
- // Validation des champs requis pour la création
- $required_fields = [
- 'firstName', 'lastName', 'login', 'mail', 'dtContractStart',
- 'legalEntityId', 'departmentId', 'cultureID', 'rolePrincipalId',
- 'employeeNumber', 'managerId', 'birthDate', 'calendarId', 'habilitedRoles'
- ];
- $missing_fields = [];
- foreach ($required_fields as $field) {
- if (!array_key_exists($field, $input)) {
- $missing_fields[] = $field;
- }
- }
- if (!empty($missing_fields)) {
- $log = create_log_entry(
- 'validation',
- $login,
- 'error',
- "Missing required fields: " . implode(', ', $missing_fields)
- );
-
- json_response(400, [
- "success" => false,
- "action" => "validation_error",
- "lucca_status" => "user creation failed",
- "message" => "Missing required fields for user creation",
- "missing_fields" => $missing_fields,
- "lucca_log" => $log
- ]);
- }
- // Préparation du body pour la création
- $body = [];
- // Champs obligatoires
- $mandatory_fields = [
- 'firstName', 'lastName', 'login', 'mail', 'dtContractStart',
- 'legalEntityId', 'departmentId', 'cultureID', 'rolePrincipalId',
- 'employeeNumber', 'managerId', 'birthDate', 'calendarId', 'habilitedRoles'
- ];
- foreach ($mandatory_fields as $field) {
- $body[$field] = $input[$field];
- }
- // Champs optionnels
- $optional_fields = [
- 'dtContractEnd', 'cspId', 'nationalityId', 'seniorityDate',
- 'insuranceNumber', 'address', 'directLine', 'jobTitle', 'gender',
- 'personalEmail', 'personalMobile', 'professionalMobile',
- 'allowsElectronicPayslip', 'quote', 'personalCard', 'corporateCard',
- 'bankName', 'rib', 'iban', 'bic', 'frenchCarTaxHorsePower',
- 'frenchMotocyclesTaxHorsePower', 'unitSellPrice', 'modifiedAt',
- 'picture', 'userWorkCycles', 'manager2Id', 'profile_figgo',
- 'fullTimeEquivalent', 'theoreticalRemuneration', 'extendedData',
- 'applicationData'
- ];
- foreach ($optional_fields as $field) {
- if (array_key_exists($field, $input)) {
- $body[$field] = $input[$field];
- }
- }
- // Champs d'axes dynamiques (userAxisValues_X)
- foreach ($input as $key => $value) {
- if (preg_match('/^userAxisValues_\d+$/', $key)) {
- $body[$key] = $value;
- }
- }
- // Appel POST /users pour créer l'utilisateur
- $create_result = lucca_request('POST', '/api/v3/users', [], $body, 60, false);
- // ==========================================
- // ÉTAPE 4 : HISTORISATION & TRAÇABILITÉ
- // ==========================================
- // Erreur de connexion
- if (!empty($create_result['error']) || $create_result['code'] === 0) {
- $log = create_log_entry(
- 'create_user',
- $login,
- 'error',
- "Connection error: " . ($create_result['error'] ?? 'No response from server')
- );
-
- json_response(503, [
- "success" => false,
- "action" => "connection_error",
- "lucca_status" => "user creation failed",
- "message" => "Unable to create user in Lucca",
- "details" => $create_result['error'] ?? "No response from server",
- "lucca_log" => $log
- ]);
- }
- // Erreur de création (code non 200/201)
- if ($create_result['code'] !== 200 && $create_result['code'] !== 201) {
- $error_message = $create_result['lucca_error']
- ?? $create_result['error_message']
- ?? $create_result['data']['title']
- ?? 'Unknown error';
-
- $log = create_log_entry(
- 'create_user',
- $login,
- 'error',
- "Creation failed (HTTP {$create_result['code']}): " . $error_message
- );
-
- json_response($create_result['code'], [
- "success" => false,
- "action" => "creation_failed",
- "lucca_status" => "user creation failed",
- "message" => "Failed to create user in Lucca",
- "error_details" => lucca_format_error($create_result),
- "lucca_log" => $log
- ]);
- }
- // ==========================================
- // SUCCÈS - UTILISATEUR CRÉÉ
- // ==========================================
- $created_user = $create_result['data']['data'] ?? $create_result['data'] ?? [];
- $user_id = $created_user['id'] ?? null;
- $log = create_log_entry(
- 'create_user',
- $login,
- 'success',
- "User successfully created in Lucca",
- $user_id
- );
- json_response(201, [
- "success" => true,
- "action" => "user_created",
- "lucca_status" => "user created in Lucca",
- "lucca_user_id" => $user_id,
- "message" => "User successfully created in Lucca",
- "user_data" => $created_user,
- "lucca_log" => $log
- ]);
|