action.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. <?php
  2. /** EMPLOYEE / FICHE EMPLOYé **/
  3. //Récuperation d'une liste de fiche employé
  4. Action::register('employee_search',function(&$response){
  5. global $_,$myUser;
  6. User::check_access('employee','read');
  7. require_once(__DIR__.SLASH.'Employee.class.php');
  8. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  9. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  10. // OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
  11. $query = 'SELECT main.*, '.Employee::joinString('man').'
  12. FROM '.Employee::tableName().' main
  13. LEFT JOIN '.Employee::tableName().' man ON man.id = main.manager WHERE 1';
  14. $data = array();
  15. //Recherche simple
  16. if(!empty($_['filters']['keyword'])){
  17. $query .= ' AND (main.name LIKE ? OR main.birthname LIKE ? OR main.firstname LIKE ?)';
  18. $data[] = '%'.$_['filters']['keyword'].'%';
  19. $data[] = '%'.$_['filters']['keyword'].'%';
  20. $data[] = '%'.$_['filters']['keyword'].'%';
  21. }
  22. $query .= ' AND main.state = ?';
  23. $data[] = Employee::ACTIVE;
  24. //Droits de visibilité sur la fiche :
  25. // - L'admin configure dans tous les cas
  26. // - Le créateur de la fiche si pas de manager renseigné
  27. // - Le manager si renseigné
  28. if(!$myUser->can('employee','configure')){
  29. $myEmployee = Employee::load(array('account'=>$myUser->login));
  30. $hierarchy = array();
  31. foreach(Employee::subordinates($myEmployee) as $subordinate){
  32. $hierarchy[] = $subordinate->id;
  33. $data[] = $subordinate->id;
  34. }
  35. $hierarchy[] = $myEmployee->id;
  36. $data[] = $myEmployee->id;
  37. if(empty($hierarchy)) $hierarchy[] = 0;
  38. $query .= ' AND (main.manager IN ('.implode(',',array_fill(0,count($hierarchy),'?')).') OR (main.manager IN (NULL,"") AND main.creator=?))';
  39. $data[] = $myUser->login;
  40. }
  41. //Recherche avancée
  42. if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('main.photo','main.birthName','main.name','main.firstname','main.job','main.jobDescription','man.account','main.workplace','main.hardware','main.date'),$query,$data);
  43. //Tri des colonnes
  44. if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.birthName','main.name','main.firstname','main.job','main.jobDescription','main.manager','main.workplace','main.hardware','main.date'),$query,$data);
  45. //Pagination
  46. $itemPerPage = 20;
  47. if($_['export'] == 'true') $itemPerPage = 5000;
  48. $response['pagination'] = Employee::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');
  49. $employees = Employee::staticQuery($query,$data,true,1);
  50. $hardwares = Dictionnary::slugToArray('employee_employee_hardware',true);
  51. $jobs = Dictionnary::slugToArray('employee_employee_job',true);
  52. $response['rows'] = array();
  53. foreach($employees as $employee){
  54. $row = $employee->toArray();
  55. $row['photo'] = $employee->photo();
  56. $row['jobDescription'] = html_entity_decode($row['jobDescription']);
  57. $row['comment'] = html_entity_decode($row['comment']);
  58. $row['hardware'] = array();
  59. $employeeHardwares = json_decode($employee->hardware,true);
  60. if(is_array($employeeHardwares)){
  61. foreach($employeeHardwares as $id){
  62. if(isset($hardwares[$id])) $row['hardware'][] = $hardwares[$id]->label;
  63. }
  64. }
  65. $row['hardware'] = implode(', ',$row['hardware']);
  66. if(!empty($row['manager'])){
  67. $manager = $employee->join('manager');
  68. $row['manager'] = $manager->toArray();
  69. $row['manager']['photo'] = $manager->photo();
  70. }
  71. $user = User::byLogin($row['account']);
  72. $row['account'] = $user->toArray();
  73. $row['account']['fullname'] = $user->fullname();
  74. $row['account']['avatar'] = $user->getAvatar();
  75. $row['job']= !empty($row['job']) && isset($jobs[$row['job']]) ? $jobs[$row['job']] : new Dictionnary();
  76. if($_['export'] == 'true'){
  77. $row['created'] = date('d-m-Y',$row['created']);
  78. $row['updated'] = date('d-m-Y',$row['updated']);
  79. $row['jobDescription'] = strip_tags(str_replace(array('<br>','<br/>','<p>'),PHP_EOL,$row['jobDescription']));
  80. $row['comment'] = strip_tags(str_replace(array('<br>','<br/>','<p>'),PHP_EOL,$row['comment']));
  81. $row['job'] = $row['job']->label;
  82. }
  83. if($row['birthName'] == $row['name']) unset($row['birthName']);
  84. $response['rows'][] = $row;
  85. }
  86. if($_['export'] == 'true'){
  87. if(empty($response['rows'])) $response['rows'][] = array('Vide'=>'Aucune données');
  88. $fieldsMapping = array();
  89. foreach (Employee::fields(false) as $key => $value)
  90. $fieldsMapping[$value['label']] = $key;
  91. $stream = Excel::exportArray($response['rows'],$fieldsMapping ,'Export');
  92. File::downloadStream($stream,'export-employes-'.date('d-m-Y').'.xlsx');
  93. exit();
  94. }
  95. });
  96. //Ajout ou modification d'élément fiche employé
  97. Action::register('employee_save',function(&$response){
  98. global $_,$conf,$myUser;
  99. User::check_access('employee','edit');
  100. require_once(__DIR__.SLASH.'Employee.class.php');
  101. $item = Employee::provide();
  102. if($item->id!=0 && !$myUser->can('employee','configure')){
  103. $myEmployee = Employee::load(array('account'=>$myUser->login));
  104. if(!$myEmployee->can($item,'edit')) throw new Exception('Vous n\'avez pas la permission d\'enregistrer cette fiche');
  105. }
  106. $item->birthName = mb_strtoupper($_['birthName']);
  107. $item->name = mb_strtoupper($_['name']);
  108. $item->firstname = ucfirst(mb_strtolower($_['firstname']));
  109. if(!empty($_['job']) && is_numeric($_['job'])) $item->job = $_['job'];
  110. $item->jobDescription = $_['jobDescription'];
  111. if(!empty($_['statute']) && is_numeric($_['statute'])) $item->statute = $_['statute'];
  112. if(!empty($_['manager']) && is_numeric($_['manager'])) $item->manager = $_['manager'];
  113. $item->workplace = $_['workplace'];
  114. if(!empty($_['account'])) $item->account = $_['account'];
  115. if(isset($_['hardware'])) $item->hardware = json_encode($_['hardware']);
  116. $item->comment = $_['comment'];
  117. $item->state = Employee::ACTIVE;
  118. $item->save();
  119. //Ajout upload Photo
  120. if(!empty($_['photo']))
  121. File::save_component('photo', 'employee/employee/'.$item->id.'/photo.{{extension}}');
  122. //Ajout upload Pièces jointes
  123. if(!empty($_['attachments']))
  124. File::save_component('attachments', 'employee/employee/'.$item->id.'/attachments/{{label}}');
  125. $response = $item->toArray();
  126. //Envois d'une notification si la fiche vient d'être créée
  127. if($_['id']==''){
  128. $recipients = explode(',',$conf->get('employee_save_recipients'));
  129. if($recipients && !empty($recipients)){
  130. Plugin::callHook('emit_notification',array(array(
  131. 'label' => 'Une fiche employé à été créé par '.$myUser->fullname().' pour '.$item->firstname.' '.$item->name,
  132. 'html' => 'Une fiche employé à été créé par '.$myUser->fullname().' pour '.$item->firstname.' '.$item->name.', cliquez <a href="'.ROOT_URL.'index.php?module=employee&page=sheet.employee&id='.$item->id.'">ici pour en savoir plus</a>',
  133. 'meta' => array('link' => ROOT_URL.'index.php?module=employee&page=sheet.employee&id='.$item->id),
  134. 'type' => 'employee',
  135. 'recipients' => $recipients //contient logins
  136. )));
  137. }
  138. }
  139. });
  140. //Suppression d'élement fiche employé
  141. Action::register('employee_delete',function(&$response){
  142. global $_,$myUser;
  143. User::check_access('employee','delete');
  144. require_once(__DIR__.SLASH.'Employee.class.php');
  145. if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
  146. $item = Employee::provide();
  147. if($item->id==0) return $response;
  148. if(!$myUser->can('employee','configure')){
  149. $myEmployee = Employee::load(array('account'=>$myUser->login));
  150. if(!$myEmployee->can($item,'edit')) throw new Exception('Vous n\'avez pas la permission d\'enregistrer cette fiche');
  151. }
  152. $item->state = Employee::INACTIVE;
  153. $item->save();
  154. });
  155. //Employee : Gestion upload Photo
  156. Action::register('employee_employee_photo',function(&$response){
  157. File::handle_component(array(
  158. 'namespace' => 'employee', //stockés dans file/employee/*.*
  159. 'access' => 'employee', // crud sur employee,
  160. 'extension' => 'jpg,png,bmp,gif,jpeg', // extensions
  161. 'size' => '10000000', // taille max
  162. 'limit' => '1', // nb max de fichiers
  163. 'storage' => 'employee/employee/{{data.id}}/photo.*' //chemin complet vers le fichier stocké
  164. ),$response);
  165. });
  166. //Employee : Gestion upload Pièces jointes
  167. Action::register('employee_employee_attachments',function(&$response){
  168. File::handle_component(array(
  169. 'namespace' => 'employee', //stockés dans file/employee/*.*
  170. 'access' => 'employee', // crud sur employee,
  171. 'extension' => 'pdf,docx,doc,xlsx,xls,msg,vcard,vcf,png,jpg,jpeg,bmp,gif,ppt,pptx,txt,eml', // extensions
  172. 'size' => '1000000000', // taille max
  173. 'storage' => 'employee/employee/{{data.id}}/attachments/*' //chemin complet vers le fichier stocké
  174. ),$response);
  175. });
  176. //Sauvegarde des configurations de Fiche employé
  177. Action::register('employee_setting_save',function(&$response){
  178. global $_,$conf;
  179. User::check_access('employee','configure');
  180. //Si input file "multiple", possibilité de normaliser le
  181. //tableau $_FILES récupéré avec la fonction => normalize_php_files();
  182. foreach(Configuration::setting('employee') as $key=>$value){
  183. if(!is_array($value)) continue;
  184. $allowed[] = $key;
  185. }
  186. foreach ($_['fields'] as $key => $value) {
  187. if(in_array($key, $allowed))
  188. $conf->put($key,$value);
  189. }
  190. });
  191. /* COMPOSANT*/
  192. //recherche autocomplete
  193. Action::register('employee_autocomplete',function(&$response){
  194. global $myUser,$_;
  195. require_once(__DIR__.SLASH.'Employee.class.php');
  196. if (!$myUser->connected()) throw new Exception("Vous devez être connecté", 401);
  197. $response['rows'] = array();
  198. $data = array("%".$_['keyword']."%","%".$_['keyword']."%");
  199. //retourne en priorité les matchs à 100%, pour les match keyword%, puis les autres
  200. $query = 'SELECT c.* FROM '.Employee::tableName().' c WHERE (c.name LIKE ? OR c.firstname LIKE ?) ';
  201. $query .= ' LIMIT 10';
  202. $devices = Employee::staticQuery($query,$data,true);
  203. foreach($devices as $item){
  204. $response['rows'][] = array(
  205. 'label'=>html_entity_decode($item->fullname(), ENT_QUOTES),
  206. 'id'=>$item->id,
  207. );
  208. }
  209. });
  210. //Récuperation valeur composant depuis l'uid
  211. Action::register('employee_by_uid',function(&$response){
  212. global $myUser,$_;
  213. if (!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  214. require_once(__DIR__.SLASH.'Employee.class.php');
  215. $response['items'] = array();
  216. $query = 'SELECT main.* FROM '.Employee::tableName().' main WHERE main.id IN(';
  217. $query .= implode(',', array_fill(0, count($_['items']), '?'));
  218. $query .= ')';
  219. foreach(Employee::staticQuery($query,$_['items'],true) as $item) {
  220. $row = array(); //on ne met pas toArray car certaines infos sont confidentielles
  221. $row['label'] = html_entity_decode($item->fullname(), ENT_QUOTES);
  222. $row['id'] = $item->id;
  223. $row['job'] = $item->id;
  224. $response['items'][$row['id']] = $row;
  225. }
  226. });
  227. /** EMPLOYEEWORKTIME / TEMPS DE TRAVAIL EMPOYé **/
  228. //Récuperation d'une liste de temps de travail empoyé
  229. Action::register('employee_employee_work_time_search',function(&$response){
  230. global $_;
  231. User::check_access('employee','read');
  232. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  233. $employeeworktimes = EmployeeWorkTime::loadAll();
  234. $response['rows'] = array();
  235. foreach($employeeworktimes as $employeeworktime){
  236. $row = $employeeworktime->toArray();
  237. $row['recovertype'] = EmployeeWorkTime::recovertypes($row['recovertype']);
  238. $hourByDay = json_decode($row['hourByDay']);
  239. $row['hourByDay'] = array();
  240. for($i=1;$i<8;$i++){
  241. $row['hourByDay'][] = array('day'=>day_name($i),'hours'=>isset($hourByDay[$i-1])? $hourByDay[$i-1] :0 );
  242. }
  243. $response['rows'][] = $row;
  244. }
  245. });
  246. //Ajout ou modification d'élément temps de travail empoyé
  247. Action::register('employee_employee_work_time_save',function(&$response){
  248. global $_;
  249. User::check_access('employee','configure');
  250. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  251. $item = EmployeeWorkTime::provide();
  252. $item->label = $_['label'];
  253. $item->hourByWeek = $_['hourByWeek'];
  254. $item->dayByYear = $_['dayByYear'];
  255. $item->hourByDay = $_['hourByDay'];
  256. $item->recovertype = $_['recovertype'];
  257. $item->save();
  258. $response = $item->toArray();
  259. });
  260. //Récuperation ou edition d'élément temps de travail empoyé
  261. Action::register('employee_employee_work_time_edit',function(&$response){
  262. global $_;
  263. User::check_access('employee','configure');
  264. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  265. $response = EmployeeWorkTime::getById($_['id'],0)->toArray();
  266. });
  267. //Suppression d'élement temps de travail empoyé
  268. Action::register('employee_employee_work_time_delete',function(&$response){
  269. global $_;
  270. User::check_access('employee','configure');
  271. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  272. if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
  273. EmployeeWorkTime::deleteById($_['id']);
  274. });
  275. /** EMPLOYEECONTRACT / CONTRAT EMPLOYé **/
  276. //Récuperation d'une liste de contrat employé
  277. Action::register('employee_employee_contract_search',function(&$response){
  278. global $_,$myUser;
  279. User::check_access('employee','read');
  280. if(!isset($_['employee'])) throw new Exception('Identifiant employé manquant');
  281. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  282. require_once(__ROOT__.SLASH.'plugin/employee/Employee.class.php');
  283. require_once(__ROOT__.SLASH.'plugin/employee/EmployeeWorkTime.class.php');
  284. $employee = Employee::getById($_['employee']);
  285. if(!$employee) throw new Exception('Employé inexistant');
  286. if(!$myUser->can('employee','configure')){
  287. $myEmployee = Employee::load(array('account'=>$myUser->login));
  288. if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de consulter des contrats pour cette fiche');
  289. }
  290. // OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
  291. $query = 'SELECT main.*,main.id as id, '.Employee::joinString('Employee').', '.EmployeeWorkTime::joinString('EmployeeWorkTime').' FROM '.EmployeeContract::tableName().' main LEFT JOIN '.Employee::tableName().' Employee ON main.employee=Employee.id LEFT JOIN '.EmployeeWorkTime::tableName().' EmployeeWorkTime ON main.worktime=EmployeeWorkTime.id WHERE 1';
  292. $data = array();
  293. //Recherche simple
  294. $query .= ' AND main.employee = ?';
  295. $data[] = $employee->id;
  296. //Recherche avancée
  297. if(isset($_['filters']['advanced'])) filter_secure_query($_['filters']['advanced'],array('main.employee','main.start','main.end','main.type','main.statute','main.salary','main.worktime','main.comment'),$query,$data);
  298. //Tri des colonnes
  299. if(isset($_['sort'])) sort_secure_query($_['sort'],array('main.employee','main.start','main.end','main.type','main.statute','main.salary','main.worktime','main.comment'),$query,$data);
  300. $query .= ' ORDER BY main.start DESC,main.end DESC' ;
  301. //Pagination
  302. //Par défaut pour une recherche, 20 items, pour un export 5000 max
  303. $itemPerPage = !empty($_['itemPerPage']) ? $_['itemPerPage'] : 20;
  304. //force le nombre de page max a 50 coté serveur
  305. $itemPerPage = $itemPerPage>50 ? 50 : $itemPerPage;
  306. $response['pagination'] = EmployeeContract::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');
  307. $employeecontracts = EmployeeContract::staticQuery($query,$data,true,1);
  308. $typeList = Dictionnary::slugToArray('employee_employeecontract_type',true);
  309. $statuteList = Dictionnary::slugToArray('employee_employeecontract_statute',true);
  310. $response['rows'] = array();
  311. foreach($employeecontracts as $employeecontract){
  312. $row = $employeecontract->toArray();
  313. $row['employee'] = $employeecontract->join('employee')->toArray();
  314. $row['worktime'] = $employeecontract->join('worktime')->toArray();
  315. $row['start-readable'] = date('d/m/Y',$row['start']);
  316. if(!empty($row['end'])) $row['end-readable'] = date('d/m/Y',$row['end']);
  317. $row['type'] = isset($typeList[$row['type']]) ? $typeList[$row['type']] : new Dictionnary();
  318. $row['statute'] = isset($statuteList[$row['statute']]) ? $statuteList[$row['statute']] : new Dictionnary();
  319. $row['comment'] = html_entity_decode($row['comment']);
  320. $response['rows'][] = $row;
  321. }
  322. });
  323. //Ajout ou modification d'élément contrat employé
  324. Action::register('employee_employee_contract_save',function(&$response){
  325. global $_,$myUser;
  326. User::check_access('employee','edit');
  327. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  328. require_once(__DIR__.SLASH.'Employee.class.php');
  329. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  330. $item = EmployeeContract::provide('id',1);
  331. $employee = $item->join('employee');
  332. if($item->id!=0 && !$myUser->can('employee','configure')){
  333. $myEmployee = Employee::load(array('account'=>$myUser->login));
  334. if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission d\'enregistrer des contrats pour cette fiche');
  335. }
  336. $item->employee = $_['employee'];
  337. $item->start = timestamp_date($_['start']);
  338. $item->end = timestamp_date($_['end']);
  339. if(!empty($item->start) && !empty($item->end) && $item->start>$item->end) throw new Exception("La date de départ ne peut pas être inférieure à la date d'arrivée");
  340. //Vérification qu'aucun autre contrat n'est actif si celui si est le "en cours"
  341. if(empty($item->end) || $item->end > time() ){
  342. $currentContract = Employee::getById($_['employee'])->currentContract();
  343. if($currentContract->id!=0 && $currentContract->id!=$item->id ) throw new Exception('Vous ne pouvez enregistrer deux contrats actifs en même temps, veuillez vérifier les dates de départ et d\'arrivée');
  344. }
  345. if(!empty($_['type']) && is_numeric($_['type'])) $item->type = $_['type'];
  346. if(!empty($_['statute']) && is_numeric($_['statute'])) $item->statute = $_['statute'];
  347. $item->salary = $_['salary'];
  348. $item->worktime = $_['worktime'];
  349. $item->comment = $_['comment'];
  350. $item->save();
  351. $response = $item->toArray();
  352. });
  353. //Edition d'élément contrat employé
  354. Action::register('employee_employee_contract_edit',function(&$response){
  355. global $_,$myUser;
  356. User::check_access('employee','read');
  357. require_once(__DIR__.SLASH.'Employee.class.php');
  358. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  359. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  360. $item = EmployeeContract::provide('id',1);
  361. $employee = $item->join('employee');
  362. if($item->id!=0 && !$myUser->can('employee','configure')){
  363. $myEmployee = Employee::load(array('account'=>$myUser->login));
  364. if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de consulter les contrats pour cette fiche');
  365. }
  366. if($item->id==0){
  367. $item->start = time();
  368. $item->end = '';
  369. }
  370. $row = $item->toArray();
  371. $row['start'] = date('d/m/Y',$row['start']);
  372. if(!empty($row['end'])) {
  373. $row['end'] = date('d/m/Y',$row['end']);
  374. }else{
  375. $row['end'] = '';
  376. }
  377. $response = $row;
  378. });
  379. //Suppression d'élement contrat employé
  380. Action::register('employee_employee_contract_delete',function(&$response){
  381. global $_,$myUser;
  382. User::check_access('employee','delete');
  383. require_once(__DIR__.SLASH.'Employee.class.php');
  384. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  385. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  386. if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
  387. $item = EmployeeContract::provide('id',1);
  388. $employee = $item->join('employee');
  389. if($item->id!=0 && !$myUser->can('employee','configure')){
  390. $myEmployee = Employee::load(array('account'=>$myUser->login));
  391. if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de supprimer cette fiche');
  392. }
  393. EmployeeContract::deleteById($item->id);
  394. });
  395. ?>