action.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. $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->date = timestamp_date($_['date']);
  117. $item->comment = $_['comment'];
  118. $item->state = Employee::ACTIVE;
  119. $item->save();
  120. //Ajout upload Photo
  121. if(!empty($_['photo']))
  122. File::save_component('photo', 'employee/employee/'.$item->id.'/photo.{{extension}}');
  123. //Ajout upload Pièces jointes
  124. if(!empty($_['attachments']))
  125. File::save_component('attachments', 'employee/employee/'.$item->id.'/attachments/{{label}}');
  126. $response = $item->toArray();
  127. //Envois d'une notification si la fiche vient d'être créée
  128. if($_['id']==''){
  129. $recipients = explode(',',$conf->get('employee_save_recipients'));
  130. if($recipients && !empty($recipients)){
  131. Plugin::callHook('emit_notification',array(array(
  132. 'label' => 'Une fiche employé à été créé par '.$myUser->fullname().' pour '.$item->firstname.' '.$item->name,
  133. '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>',
  134. 'meta' => array('link' => ROOT_URL.'index.php?module=employee&page=sheet.employee&id='.$item->id),
  135. 'type' => 'employee',
  136. 'recipients' => $recipients //contient logins
  137. )));
  138. }
  139. }
  140. });
  141. //Suppression d'élement fiche employé
  142. Action::register('employee_delete',function(&$response){
  143. global $_,$myUser;
  144. User::check_access('employee','delete');
  145. require_once(__DIR__.SLASH.'Employee.class.php');
  146. if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
  147. $item = Employee::provide();
  148. if($item->id==0) return $response;
  149. if(!$myUser->can('employee','configure')){
  150. $myEmployee = Employee::load(array('account'=>$myUser->login));
  151. if(!$myEmployee->can($item,'edit')) throw new Exception('Vous n\'avez pas la permission d\'enregistrer cette fiche');
  152. }
  153. $item->state = Employee::INACTIVE;
  154. $item->save();
  155. });
  156. //Employee : Gestion upload Photo
  157. Action::register('employee_employee_photo',function(&$response){
  158. File::handle_component(array(
  159. 'namespace' => 'employee', //stockés dans file/employee/*.*
  160. 'access' => 'employee', // crud sur employee,
  161. 'extension' => 'jpg,png,bmp,gif,jpeg', // extensions
  162. 'size' => '10000000', // taille max
  163. 'limit' => '1', // nb max de fichiers
  164. 'storage' => 'employee/employee/{{data.id}}/photo.*' //chemin complet vers le fichier stocké
  165. ),$response);
  166. });
  167. //Employee : Gestion upload Pièces jointes
  168. Action::register('employee_employee_attachments',function(&$response){
  169. File::handle_component(array(
  170. 'namespace' => 'employee', //stockés dans file/employee/*.*
  171. 'access' => 'employee', // crud sur employee,
  172. 'extension' => 'pdf,docx,doc,xlsx,xls,msg,vcard,vcf,png,jpg,jpeg,bmp,gif,ppt,pptx,txt,eml', // extensions
  173. 'size' => '1000000000', // taille max
  174. 'storage' => 'employee/employee/{{data.id}}/attachments/*' //chemin complet vers le fichier stocké
  175. ),$response);
  176. });
  177. //Sauvegarde des configurations de Fiche employé
  178. Action::register('employee_setting_save',function(&$response){
  179. global $_,$conf;
  180. User::check_access('employee','configure');
  181. //Si input file "multiple", possibilité de normaliser le
  182. //tableau $_FILES récupéré avec la fonction => normalize_php_files();
  183. foreach(Configuration::setting('employee') as $key=>$value){
  184. if(!is_array($value)) continue;
  185. $allowed[] = $key;
  186. }
  187. foreach ($_['fields'] as $key => $value) {
  188. if(in_array($key, $allowed))
  189. $conf->put($key,$value);
  190. }
  191. });
  192. /* COMPOSANT*/
  193. //recherche autocomplete
  194. Action::register('employee_autocomplete',function(&$response){
  195. global $myUser,$_;
  196. require_once(__DIR__.SLASH.'Employee.class.php');
  197. if (!$myUser->connected()) throw new Exception("Vous devez être connecté", 401);
  198. $response['rows'] = array();
  199. $data = array("%".$_['keyword']."%","%".$_['keyword']."%");
  200. //retourne en priorité les matchs à 100%, pour les match keyword%, puis les autres
  201. $query = 'SELECT c.* FROM '.Employee::tableName().' c WHERE (c.name LIKE ? OR c.firstname LIKE ?) ';
  202. $query .= ' LIMIT 10';
  203. $devices = Employee::staticQuery($query,$data,true);
  204. foreach($devices as $item){
  205. $response['rows'][] = array(
  206. 'label'=>html_entity_decode($item->fullname(), ENT_QUOTES),
  207. 'id'=>$item->id,
  208. );
  209. }
  210. });
  211. //Récuperation valeur composant depuis l'uid
  212. Action::register('employee_by_uid',function(&$response){
  213. global $myUser,$_;
  214. if (!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  215. require_once(__DIR__.SLASH.'Employee.class.php');
  216. $response['items'] = array();
  217. $query = 'SELECT main.* FROM '.Employee::tableName().' main WHERE main.id IN(';
  218. $query .= implode(',', array_fill(0, count($_['items']), '?'));
  219. $query .= ')';
  220. foreach(Employee::staticQuery($query,$_['items'],true) as $item) {
  221. $row = array(); //on ne met pas toArray car certaines infos sont confidentielles
  222. $row['label'] = html_entity_decode($item->fullname(), ENT_QUOTES);
  223. $row['id'] = $item->id;
  224. $row['job'] = $item->id;
  225. $response['items'][$row['id']] = $row;
  226. }
  227. });
  228. /** EMPLOYEEWORKTIME / TEMPS DE TRAVAIL EMPOYé **/
  229. //Récuperation d'une liste de temps de travail empoyé
  230. Action::register('employee_employee_work_time_search',function(&$response){
  231. global $_;
  232. User::check_access('employee','read');
  233. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  234. $employeeworktimes = EmployeeWorkTime::loadAll();
  235. $response['rows'] = array();
  236. foreach($employeeworktimes as $employeeworktime){
  237. $row = $employeeworktime->toArray();
  238. $row['recovertype'] = EmployeeWorkTime::recovertypes($row['recovertype']);
  239. $hourByDay = json_decode($row['hourByDay']);
  240. $row['hourByDay'] = array();
  241. for($i=1;$i<8;$i++){
  242. $row['hourByDay'][] = array('day'=>day_name($i),'hours'=>isset($hourByDay[$i])? $hourByDay[$i-1] :0 );
  243. }
  244. $response['rows'][] = $row;
  245. }
  246. });
  247. //Ajout ou modification d'élément temps de travail empoyé
  248. Action::register('employee_employee_work_time_save',function(&$response){
  249. global $_;
  250. User::check_access('employee','configure');
  251. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  252. $item = EmployeeWorkTime::provide();
  253. $item->label = $_['label'];
  254. $item->hourByWeek = $_['hourByWeek'];
  255. $item->dayByYear = $_['dayByYear'];
  256. $item->hourByDay = $_['hourByDay'];
  257. $item->recovertype = $_['recovertype'];
  258. $item->save();
  259. $response = $item->toArray();
  260. });
  261. //Récuperation ou edition d'élément temps de travail empoyé
  262. Action::register('employee_employee_work_time_edit',function(&$response){
  263. global $_;
  264. User::check_access('employee','configure');
  265. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  266. $response = EmployeeWorkTime::getById($_['id'],0)->toArray();
  267. });
  268. //Suppression d'élement temps de travail empoyé
  269. Action::register('employee_employee_work_time_delete',function(&$response){
  270. global $_;
  271. User::check_access('employee','configure');
  272. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  273. if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
  274. EmployeeWorkTime::deleteById($_['id']);
  275. });
  276. /** EMPLOYEECONTRACT / CONTRAT EMPLOYé **/
  277. //Récuperation d'une liste de contrat employé
  278. Action::register('employee_employee_contract_search',function(&$response){
  279. global $_,$myUser;
  280. User::check_access('employee','read');
  281. if(!isset($_['employee'])) throw new Exception('Identifiant employé manquant');
  282. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  283. require_once(__ROOT__.SLASH.'plugin/employee/Employee.class.php');
  284. require_once(__ROOT__.SLASH.'plugin/employee/EmployeeWorkTime.class.php');
  285. $employee = Employee::getById($_['employee']);
  286. if(!$employee) throw new Exception('Employé inexistant');
  287. if(!$myUser->can('employee','configure')){
  288. $myEmployee = Employee::load(array('account'=>$myUser->login));
  289. if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de consulter des contrats pour cette fiche');
  290. }
  291. // OPTIONS DE RECHERCHE, A ACTIVER POUR UNE RECHERCHE AVANCEE
  292. $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';
  293. $data = array();
  294. //Recherche simple
  295. $query .= ' AND main.employee = ?';
  296. $data[] = $employee->id;
  297. //Recherche avancée
  298. 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);
  299. //Tri des colonnes
  300. 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);
  301. $query .= ' ORDER BY main.start DESC,main.end DESC' ;
  302. //Pagination
  303. //Par défaut pour une recherche, 20 items, pour un export 5000 max
  304. $itemPerPage = !empty($_['itemPerPage']) ? $_['itemPerPage'] : 20;
  305. //force le nombre de page max a 50 coté serveur
  306. $itemPerPage = $itemPerPage>50 ? 50 : $itemPerPage;
  307. $response['pagination'] = EmployeeContract::paginate($itemPerPage,(!empty($_['page'])?$_['page']:0),$query,$data,'main');
  308. $employeecontracts = EmployeeContract::staticQuery($query,$data,true,1);
  309. $typeList = Dictionnary::slugToArray('employee_employeecontract_type',true);
  310. $statuteList = Dictionnary::slugToArray('employee_employeecontract_statute',true);
  311. $response['rows'] = array();
  312. foreach($employeecontracts as $employeecontract){
  313. $row = $employeecontract->toArray();
  314. $row['employee'] = $employeecontract->join('employee')->toArray();
  315. $row['worktime'] = $employeecontract->join('worktime')->toArray();
  316. $row['start-readable'] = date('d/m/Y',$row['start']);
  317. if(!empty($row['end'])) $row['end-readable'] = date('d/m/Y',$row['end']);
  318. $row['type'] = isset($typeList[$row['type']]) ? $typeList[$row['type']] : new Dictionnary();
  319. $row['statute'] = isset($statuteList[$row['statute']]) ? $statuteList[$row['statute']] : new Dictionnary();
  320. $row['comment'] = html_entity_decode($row['comment']);
  321. $response['rows'][] = $row;
  322. }
  323. });
  324. //Ajout ou modification d'élément contrat employé
  325. Action::register('employee_employee_contract_save',function(&$response){
  326. global $_,$myUser;
  327. User::check_access('employee','edit');
  328. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  329. require_once(__DIR__.SLASH.'Employee.class.php');
  330. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  331. $item = EmployeeContract::provide('id',1);
  332. $employee = $item->join('employee');
  333. if($item->id!=0 && !$myUser->can('employee','configure')){
  334. $myEmployee = Employee::load(array('account'=>$myUser->login));
  335. if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission d\'enregistrer des contrats pour cette fiche');
  336. }
  337. $item->employee = $_['employee'];
  338. $item->start = timestamp_date($_['start']);
  339. $item->end = timestamp_date($_['end']);
  340. 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");
  341. //Vérification qu'aucun autre contrat n'est actif si celui si est le "en cours"
  342. if(empty($item->end) || $item->end > time() ){
  343. $currentContract = Employee::getById($_['employee'])->currentContract();
  344. 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');
  345. }
  346. if(!empty($_['type']) && is_numeric($_['type'])) $item->type = $_['type'];
  347. if(!empty($_['statute']) && is_numeric($_['statute'])) $item->statute = $_['statute'];
  348. $item->salary = $_['salary'];
  349. $item->worktime = $_['worktime'];
  350. $item->comment = $_['comment'];
  351. $item->save();
  352. $response = $item->toArray();
  353. });
  354. //Edition d'élément contrat employé
  355. Action::register('employee_employee_contract_edit',function(&$response){
  356. global $_,$myUser;
  357. User::check_access('employee','read');
  358. require_once(__DIR__.SLASH.'Employee.class.php');
  359. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  360. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  361. $item = EmployeeContract::provide('id',1);
  362. $employee = $item->join('employee');
  363. if($item->id!=0 && !$myUser->can('employee','configure')){
  364. $myEmployee = Employee::load(array('account'=>$myUser->login));
  365. if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de consulter les contrats pour cette fiche');
  366. }
  367. if($item->id==0){
  368. $item->start = time();
  369. $item->end = '';
  370. }
  371. $row = $item->toArray();
  372. $row['start'] = date('d/m/Y',$row['start']);
  373. if(!empty($row['end'])) {
  374. $row['end'] = date('d/m/Y',$row['end']);
  375. }else{
  376. $row['end'] = '';
  377. }
  378. $response = $row;
  379. });
  380. //Suppression d'élement contrat employé
  381. Action::register('employee_employee_contract_delete',function(&$response){
  382. global $_,$myUser;
  383. User::check_access('employee','delete');
  384. require_once(__DIR__.SLASH.'Employee.class.php');
  385. require_once(__DIR__.SLASH.'EmployeeContract.class.php');
  386. require_once(__DIR__.SLASH.'EmployeeWorkTime.class.php');
  387. if(empty($_['id']) || !is_numeric($_['id'])) throw new Exception("Identifiant incorrect");
  388. $item = EmployeeContract::provide('id',1);
  389. $employee = $item->join('employee');
  390. if($item->id!=0 && !$myUser->can('employee','configure')){
  391. $myEmployee = Employee::load(array('account'=>$myUser->login));
  392. if(!$myEmployee->can($employee,'edit')) throw new Exception('Vous n\'avez pas la permission de supprimer cette fiche');
  393. }
  394. EmployeeContract::deleteById($item->id);
  395. });
  396. ?>