orchestratCode.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. /**
  3. * Orchestration de création d'utilisateur Lucca
  4. *
  5. * Point REST pour automatiser l'intégration des collaborateurs dans Lucca
  6. * Basé sur le workflow documenté dans orchestrat.php
  7. *
  8. * Méthode : POST
  9. * Body JSON : Fiche collaborateur candidate
  10. * {
  11. * "demande_status": "Confirmé RH",
  12. * "demande_login": "prenom.nom@sipa-automobiles.fr",
  13. * "firstName": "Prénom",
  14. * "lastName": "Nom",
  15. * "mail": "prenom.nom@sipa-automobiles.fr",
  16. * "dtContractStart": "2025-11-09T00:00:00",
  17. * "legalEntityId": 1,
  18. * "departmentId": 2,
  19. * "cultureID": 1036,
  20. * "rolePrincipalId": 4,
  21. * "employeeNumber": "MAT12345",
  22. * "managerId": 1919,
  23. * "birthDate": "1990-05-15T00:00:00",
  24. * "calendarId": null,
  25. * "habilitedRoles": [{"id": 3}],
  26. * ... autres champs optionnels
  27. * }
  28. *
  29. * Réponse :
  30. * {
  31. * "success": true,
  32. * "action": "user_created" | "user_already_exists" | "status_rejected",
  33. * "lucca_status": "user created in Lucca" | "user already exists in Lucca" | "status not confirmed",
  34. * "lucca_user_id": 123,
  35. * "lucca_log": {...},
  36. * "user_data": {...}
  37. * }
  38. */
  39. // Activation du débogage
  40. ini_set('display_errors', 1);
  41. ini_set('display_startup_errors', 1);
  42. error_reporting(E_ALL);
  43. /**
  44. * Envoie une réponse JSON avec le code HTTP approprié
  45. */
  46. function json_response(int $statusCode, array $payload): void {
  47. http_response_code($statusCode);
  48. header('Content-Type: application/json; charset=utf-8');
  49. echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
  50. exit;
  51. }
  52. /**
  53. * Crée une entrée de log pour la traçabilité
  54. */
  55. function create_log_entry(string $action_type, string $user_identifier, string $result, string $message, $user_id = null): array {
  56. return [
  57. 'date' => date('Y-m-d H:i:s'),
  58. 'action_type' => $action_type,
  59. 'user_identifier' => $user_identifier,
  60. 'result' => $result,
  61. 'message' => $message,
  62. 'lucca_user_id' => $user_id
  63. ];
  64. }
  65. // Charge le client API Lucca
  66. require_once __DIR__ . '/../lucca_client.php';
  67. // ==========================================
  68. // RÉCEPTION DES DONNÉES
  69. // ==========================================
  70. // Récupère le JSON en entrée
  71. $input = json_decode(file_get_contents("php://input"), true);
  72. // Vérification que le JSON est valide
  73. if (!is_array($input)) {
  74. json_response(400, [
  75. "success" => false,
  76. "error" => "Invalid JSON",
  77. "message" => "Request body must contain valid JSON"
  78. ]);
  79. }
  80. // ==========================================
  81. // ÉTAPE 1 : VÉRIFICATION DU STATUT
  82. // ==========================================
  83. if (!isset($input['demande_status'])) {
  84. json_response(400, [
  85. "success" => false,
  86. "error" => "Missing demande_status",
  87. "message" => "Field 'demande_status' is required to determine if the request should be processed"
  88. ]);
  89. }
  90. // Vérifier si le statut est "Confirmé RH"
  91. if ($input['demande_status'] !== 'Confirmé RH') {
  92. $log = create_log_entry(
  93. 'status_check',
  94. $input['demande_login'] ?? 'unknown',
  95. 'rejected',
  96. "Status is '{$input['demande_status']}', expected 'Confirmé RH'"
  97. );
  98. json_response(200, [
  99. "success" => false,
  100. "action" => "status_rejected",
  101. "lucca_status" => "status not confirmed",
  102. "message" => "Request not processed: status must be 'Confirmé RH'",
  103. "current_status" => $input['demande_status'],
  104. "lucca_log" => $log
  105. ]);
  106. }
  107. // ==========================================
  108. // ÉTAPE 2 : VÉRIFICATION D'EXISTENCE
  109. // ==========================================
  110. if (!isset($input['demande_login']) || empty($input['demande_login'])) {
  111. json_response(400, [
  112. "success" => false,
  113. "error" => "Missing demande_login",
  114. "message" => "Field 'demande_login' is required to check if user exists"
  115. ]);
  116. }
  117. $login = $input['demande_login'];
  118. // Appel GET /users pour vérifier l'existence
  119. $check_result = lucca_request('GET', '/api/v3/users', [
  120. 'login' => $login,
  121. 'fields' => 'id,name,login,mail,dtContractStart,dtContractEnd',
  122. 'limit' => 1
  123. ], null, 60, false);
  124. // Erreur de connexion
  125. if (!empty($check_result['error']) || $check_result['code'] === 0) {
  126. $log = create_log_entry(
  127. 'check_existence',
  128. $login,
  129. 'error',
  130. "API connection error: " . ($check_result['error'] ?? 'No response from server')
  131. );
  132. json_response(503, [
  133. "success" => false,
  134. "action" => "connection_error",
  135. "lucca_status" => "user check failed",
  136. "message" => "Unable to verify if user exists in Lucca",
  137. "details" => $check_result['error'] ?? "No response from server",
  138. "lucca_log" => $log
  139. ]);
  140. }
  141. // Erreur API autre que 200
  142. if ($check_result['code'] !== 200) {
  143. $log = create_log_entry(
  144. 'check_existence',
  145. $login,
  146. 'error',
  147. "API error {$check_result['code']}: " . ($check_result['lucca_error'] ?? $check_result['error_message'] ?? 'Unknown error')
  148. );
  149. json_response($check_result['code'], [
  150. "success" => false,
  151. "action" => "api_error",
  152. "lucca_status" => "user check failed",
  153. "message" => "Error checking user existence",
  154. "error_details" => lucca_format_error($check_result),
  155. "lucca_log" => $log
  156. ]);
  157. }
  158. // Vérifier si un utilisateur existe déjà
  159. $existing_users = $check_result['data']['data']['items'] ?? [];
  160. if (!empty($existing_users)) {
  161. // Utilisateur existe déjà
  162. $existing_user = $existing_users[0];
  163. $user_id = $existing_user['id'] ?? null;
  164. $log = create_log_entry(
  165. 'check_existence',
  166. $login,
  167. 'found',
  168. "User already exists in Lucca (active or inactive)",
  169. $user_id
  170. );
  171. json_response(200, [
  172. "success" => true,
  173. "action" => "user_already_exists",
  174. "lucca_status" => "user already exists in Lucca",
  175. "lucca_user_id" => $user_id,
  176. "message" => "User with this login already exists in Lucca",
  177. "existing_user" => $existing_user,
  178. "lucca_log" => $log
  179. ]);
  180. }
  181. // ==========================================
  182. // ÉTAPE 3 : CRÉATION DE L'UTILISATEUR
  183. // ==========================================
  184. // Validation des champs requis pour la création
  185. $required_fields = [
  186. 'firstName', 'lastName', 'login', 'mail', 'dtContractStart',
  187. 'legalEntityId', 'departmentId', 'cultureID', 'rolePrincipalId',
  188. 'employeeNumber', 'managerId', 'birthDate', 'calendarId', 'habilitedRoles'
  189. ];
  190. $missing_fields = [];
  191. foreach ($required_fields as $field) {
  192. if (!array_key_exists($field, $input)) {
  193. $missing_fields[] = $field;
  194. }
  195. }
  196. if (!empty($missing_fields)) {
  197. $log = create_log_entry(
  198. 'validation',
  199. $login,
  200. 'error',
  201. "Missing required fields: " . implode(', ', $missing_fields)
  202. );
  203. json_response(400, [
  204. "success" => false,
  205. "action" => "validation_error",
  206. "lucca_status" => "user creation failed",
  207. "message" => "Missing required fields for user creation",
  208. "missing_fields" => $missing_fields,
  209. "lucca_log" => $log
  210. ]);
  211. }
  212. // Préparation du body pour la création
  213. $body = [];
  214. // Champs obligatoires
  215. $mandatory_fields = [
  216. 'firstName', 'lastName', 'login', 'mail', 'dtContractStart',
  217. 'legalEntityId', 'departmentId', 'cultureID', 'rolePrincipalId',
  218. 'employeeNumber', 'managerId', 'birthDate', 'calendarId', 'habilitedRoles'
  219. ];
  220. foreach ($mandatory_fields as $field) {
  221. $body[$field] = $input[$field];
  222. }
  223. // Champs optionnels
  224. $optional_fields = [
  225. 'dtContractEnd', 'cspId', 'nationalityId', 'seniorityDate',
  226. 'insuranceNumber', 'address', 'directLine', 'jobTitle', 'gender',
  227. 'personalEmail', 'personalMobile', 'professionalMobile',
  228. 'allowsElectronicPayslip', 'quote', 'personalCard', 'corporateCard',
  229. 'bankName', 'rib', 'iban', 'bic', 'frenchCarTaxHorsePower',
  230. 'frenchMotocyclesTaxHorsePower', 'unitSellPrice', 'modifiedAt',
  231. 'picture', 'userWorkCycles', 'manager2Id', 'profile_figgo',
  232. 'fullTimeEquivalent', 'theoreticalRemuneration', 'extendedData',
  233. 'applicationData'
  234. ];
  235. foreach ($optional_fields as $field) {
  236. if (array_key_exists($field, $input)) {
  237. $body[$field] = $input[$field];
  238. }
  239. }
  240. // Champs d'axes dynamiques (userAxisValues_X)
  241. foreach ($input as $key => $value) {
  242. if (preg_match('/^userAxisValues_\d+$/', $key)) {
  243. $body[$key] = $value;
  244. }
  245. }
  246. // Appel POST /users pour créer l'utilisateur
  247. $create_result = lucca_request('POST', '/api/v3/users', [], $body, 60, false);
  248. // ==========================================
  249. // ÉTAPE 4 : HISTORISATION & TRAÇABILITÉ
  250. // ==========================================
  251. // Erreur de connexion
  252. if (!empty($create_result['error']) || $create_result['code'] === 0) {
  253. $log = create_log_entry(
  254. 'create_user',
  255. $login,
  256. 'error',
  257. "Connection error: " . ($create_result['error'] ?? 'No response from server')
  258. );
  259. json_response(503, [
  260. "success" => false,
  261. "action" => "connection_error",
  262. "lucca_status" => "user creation failed",
  263. "message" => "Unable to create user in Lucca",
  264. "details" => $create_result['error'] ?? "No response from server",
  265. "lucca_log" => $log
  266. ]);
  267. }
  268. // Erreur de création (code non 200/201)
  269. if ($create_result['code'] !== 200 && $create_result['code'] !== 201) {
  270. $error_message = $create_result['lucca_error']
  271. ?? $create_result['error_message']
  272. ?? $create_result['data']['title']
  273. ?? 'Unknown error';
  274. $log = create_log_entry(
  275. 'create_user',
  276. $login,
  277. 'error',
  278. "Creation failed (HTTP {$create_result['code']}): " . $error_message
  279. );
  280. json_response($create_result['code'], [
  281. "success" => false,
  282. "action" => "creation_failed",
  283. "lucca_status" => "user creation failed",
  284. "message" => "Failed to create user in Lucca",
  285. "error_details" => lucca_format_error($create_result),
  286. "lucca_log" => $log
  287. ]);
  288. }
  289. // ==========================================
  290. // SUCCÈS - UTILISATEUR CRÉÉ
  291. // ==========================================
  292. $created_user = $create_result['data']['data'] ?? $create_result['data'] ?? [];
  293. $user_id = $created_user['id'] ?? null;
  294. $log = create_log_entry(
  295. 'create_user',
  296. $login,
  297. 'success',
  298. "User successfully created in Lucca",
  299. $user_id
  300. );
  301. json_response(201, [
  302. "success" => true,
  303. "action" => "user_created",
  304. "lucca_status" => "user created in Lucca",
  305. "lucca_user_id" => $user_id,
  306. "message" => "User successfully created in Lucca",
  307. "user_data" => $created_user,
  308. "lucca_log" => $log
  309. ]);