evaluation.class.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  4. * Copyright (C) 2021 Greg Rastklan <greg.rastklan@atm-consulting.fr>
  5. * Copyright (C) 2021 Jean-Pascal BOUDET <jean-pascal.boudet@atm-consulting.fr>
  6. * Copyright (C) 2021 Grégory BLEMAND <gregory.blemand@atm-consulting.fr>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. */
  21. /**
  22. * \file htdocs/hrm/class/evaluation.class.php
  23. * \ingroup hrm
  24. * \brief This file is a CRUD class file for Evaluation (Create/Read/Update/Delete)
  25. */
  26. // Put here all includes required by your class file
  27. require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
  28. require_once DOL_DOCUMENT_ROOT . '/hrm/class/evaluationdet.class.php';
  29. //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  30. //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  31. /**
  32. * Class for Evaluation
  33. */
  34. class Evaluation extends CommonObject
  35. {
  36. /**
  37. * @var string ID of module.
  38. */
  39. public $module = 'hrm';
  40. /**
  41. * @var string ID to identify managed object.
  42. */
  43. public $element = 'evaluation';
  44. /**
  45. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  46. */
  47. public $table_element = 'hrm_evaluation';
  48. /**
  49. * @var int Does this object support multicompany module ?
  50. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  51. */
  52. public $ismultientitymanaged = 0;
  53. /**
  54. * @var int Does object support extrafields ? 0=No, 1=Yes
  55. */
  56. public $isextrafieldmanaged = 1;
  57. /**
  58. * @var string String with name of icon for evaluation. Must be the part after the 'object_' into object_evaluation.png
  59. */
  60. public $picto = 'label';
  61. const STATUS_DRAFT = 0;
  62. const STATUS_VALIDATED = 1;
  63. const STATUS_CANCELED = 9;
  64. const STATUS_CLOSED = 6;
  65. /**
  66. * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  67. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  68. * 'label' the translation key.
  69. * 'picto' is code of a picto to show before value in forms
  70. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  71. * 'position' is the sort order of field.
  72. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  73. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  74. * 'noteditable' says if field is not editable (1 or 0)
  75. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  76. * 'index' if we want an index in database.
  77. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  78. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  79. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  80. * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
  81. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  82. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  83. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  84. * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
  85. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  86. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  87. *
  88. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  89. */
  90. // BEGIN MODULEBUILDER PROPERTIES
  91. /**
  92. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  93. */
  94. public $fields=array(
  95. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
  96. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Reference of object"),
  97. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
  98. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3,),
  99. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0,),
  100. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0,),
  101. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
  102. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
  103. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php:0', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
  104. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php:0', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
  105. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
  106. 'status' => array('type'=>'smallint', 'label'=>'Status', 'enabled'=>'1', 'position'=>1000, 'notnull'=>1, 'default'=>0, 'visible'=>5, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Draft', '1'=>'Validated', '6' => 'Closed'),),
  107. 'date_eval' => array('type'=>'date', 'label'=>'DateEval', 'enabled'=>'1', 'position'=>502, 'notnull'=>1, 'visible'=>1,),
  108. 'fk_user' => array('type'=>'integer:User:user/class/user.class.php:0', 'label'=>'Employee', 'enabled'=>'1', 'position'=>504, 'notnull'=>1, 'visible'=>1, 'picto'=>'user', 'css'=>'maxwidth300 widthcentpercentminusxx', 'csslist'=>'tdoverflowmax150'),
  109. 'fk_job' => array('type'=>'integer:Job:/hrm/class/job.class.php', 'label'=>'JobProfile', 'enabled'=>'1', 'position'=>505, 'notnull'=>1, 'visible'=>1, 'picto'=>'jobprofile', 'css'=>'maxwidth300 widthcentpercentminusxx', 'csslist'=>'tdoverflowmax150'),
  110. );
  111. public $rowid;
  112. public $ref;
  113. public $label;
  114. public $description;
  115. public $note_public;
  116. public $note_private;
  117. public $date_creation;
  118. public $tms;
  119. public $fk_user_creat;
  120. public $fk_user_modif;
  121. public $import_key;
  122. public $status;
  123. public $date_eval;
  124. public $fk_user;
  125. public $fk_job;
  126. // END MODULEBUILDER PROPERTIES
  127. // If this object has a subtable with lines
  128. /**
  129. * @var string Name of subtable line
  130. */
  131. public $table_element_line = 'hrm_evaluationdet';
  132. /**
  133. * @var string Field with ID of parent key if this object has a parent
  134. */
  135. public $fk_element = 'fk_evaluation';
  136. /**
  137. * @var string Name of subtable class that manage subtable lines
  138. */
  139. public $class_element_line = 'EvaluationLine';
  140. // /**
  141. // * @var array List of child tables. To test if we can delete object.
  142. // */
  143. // protected $childtables = array();
  144. // /**
  145. // * @var array List of child tables. To know object to delete on cascade.
  146. // * If name matches '@ClassNAme:FilePathClass;ParentFkFieldName' it will
  147. // * call method deleteByParentField(parentId, ParentFkFieldName) to fetch and delete child object
  148. // */
  149. protected $childtablesoncascade = array('@EvaluationLine:hrm/class/evaluationdet.class.php:fk_evaluation');
  150. /**
  151. * @var EvaluationLine[] Array of subtable lines
  152. */
  153. public $lines = array();
  154. /**
  155. * Constructor
  156. *
  157. * @param DoliDb $db Database handler
  158. */
  159. public function __construct(DoliDB $db)
  160. {
  161. global $conf, $langs, $user;
  162. $this->db = $db;
  163. if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
  164. $this->fields['rowid']['visible'] = 0;
  165. }
  166. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  167. $this->fields['entity']['enabled'] = 0;
  168. }
  169. if (!$user->hasRight('hrm', 'evaluation', 'readall')) {
  170. $this->fields['fk_user']['type'].= ':rowid IN('.$this->db->sanitize(implode(", ", $user->getAllChildIds(1))).')';
  171. }
  172. $this->date_eval = dol_now();
  173. // Unset fields that are disabled
  174. foreach ($this->fields as $key => $val) {
  175. if (isset($val['enabled']) && empty($val['enabled'])) {
  176. unset($this->fields[$key]);
  177. }
  178. }
  179. // Translate some data of arrayofkeyval
  180. if (is_object($langs)) {
  181. foreach ($this->fields as $key => $val) {
  182. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  183. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  184. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  185. }
  186. }
  187. }
  188. }
  189. }
  190. /**
  191. * Create object into database
  192. *
  193. * @param User $user User that creates
  194. * @param bool $notrigger false=launch triggers after, true=disable triggers
  195. * @return int Return integer <0 if KO, Id of created object if OK
  196. */
  197. public function create(User $user, $notrigger = false)
  198. {
  199. $resultcreate = $this->createCommon($user, $notrigger);
  200. if ($resultcreate > 0) {
  201. require_once DOL_DOCUMENT_ROOT . '/hrm/class/skillrank.class.php';
  202. $skillRank = new SkillRank($this->db);
  203. $TRequiredRanks = $skillRank->fetchAll('ASC', 't.rowid', 0, 0, array('customsql' => 'fk_object='.$this->fk_job." AND objecttype='job'"));
  204. if (is_array($TRequiredRanks) && !empty($TRequiredRanks)) {
  205. $this->lines = array();
  206. foreach ($TRequiredRanks as $required) {
  207. $line = new EvaluationLine($this->db);
  208. $line->fk_evaluation = $resultcreate;
  209. $line->fk_skill = $required->fk_skill;
  210. $line->required_rank = $required->rankorder;
  211. $line->fk_rank = 0;
  212. $res = $line->create($user, $notrigger);
  213. if ($res > 0) {
  214. $this->lines[] = $line;
  215. }
  216. }
  217. }
  218. }
  219. return $resultcreate;
  220. }
  221. /**
  222. * Clone an object into another one
  223. *
  224. * @param User $user User that creates
  225. * @param int $fromid Id of object to clone
  226. * @return mixed New object created, <0 if KO
  227. */
  228. public function createFromClone(User $user, $fromid)
  229. {
  230. global $langs, $extrafields;
  231. $error = 0;
  232. dol_syslog(__METHOD__, LOG_DEBUG);
  233. $object = new self($this->db);
  234. $this->db->begin();
  235. // Load source object
  236. $result = $object->fetchCommon($fromid);
  237. if ($result > 0 && !empty($object->table_element_line)) {
  238. $object->fetchLines();
  239. }
  240. // get lines so they will be clone
  241. //foreach($this->lines as $line)
  242. // $line->fetch_optionals();
  243. // Reset some properties
  244. unset($object->id);
  245. unset($object->fk_user_creat);
  246. unset($object->import_key);
  247. // Clear fields
  248. if (property_exists($object, 'ref')) {
  249. $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  250. }
  251. if (property_exists($object, 'label')) {
  252. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  253. }
  254. if (property_exists($object, 'status')) {
  255. $object->status = self::STATUS_DRAFT;
  256. }
  257. if (property_exists($object, 'date_creation')) {
  258. $object->date_creation = dol_now();
  259. }
  260. if (property_exists($object, 'date_modification')) {
  261. $object->date_modification = null;
  262. }
  263. // ...
  264. // Clear extrafields that are unique
  265. if (is_array($object->array_options) && count($object->array_options) > 0) {
  266. $extrafields->fetch_name_optionals_label($this->table_element);
  267. foreach ($object->array_options as $key => $option) {
  268. $shortkey = preg_replace('/options_/', '', $key);
  269. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  270. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  271. unset($object->array_options[$key]);
  272. }
  273. }
  274. }
  275. // Create clone
  276. $object->context['createfromclone'] = 'createfromclone';
  277. $result = $object->createCommon($user);
  278. if ($result < 0) {
  279. $error++;
  280. $this->error = $object->error;
  281. $this->errors = $object->errors;
  282. }
  283. if (!$error) {
  284. // copy internal contacts
  285. if ($this->copy_linked_contact($object, 'internal') < 0) {
  286. $error++;
  287. }
  288. }
  289. if (!$error) {
  290. // copy external contacts if same company
  291. if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
  292. if ($this->copy_linked_contact($object, 'external') < 0) {
  293. $error++;
  294. }
  295. }
  296. }
  297. unset($object->context['createfromclone']);
  298. // End
  299. if (!$error) {
  300. $this->db->commit();
  301. return $object;
  302. } else {
  303. $this->db->rollback();
  304. return -1;
  305. }
  306. }
  307. /**
  308. * Load object in memory from the database
  309. *
  310. * @param int $id Id object
  311. * @param string $ref Ref
  312. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  313. */
  314. public function fetch($id, $ref = null)
  315. {
  316. $result = $this->fetchCommon($id, $ref);
  317. if ($result > 0 && !empty($this->table_element_line)) {
  318. $this->fetchLines();
  319. }
  320. return $result;
  321. }
  322. /**
  323. * Load object lines in memory from the database
  324. *
  325. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  326. */
  327. public function fetchLines()
  328. {
  329. $this->lines = array();
  330. $result = $this->fetchLinesCommon();
  331. return $result;
  332. }
  333. /**
  334. * Load list of objects in memory from the database.
  335. *
  336. * @param string $sortorder Sort Order
  337. * @param string $sortfield Sort field
  338. * @param int $limit limit
  339. * @param int $offset Offset
  340. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  341. * @param string $filtermode Filter mode (AND or OR)
  342. * @return array|int int <0 if KO, array of pages if OK
  343. */
  344. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  345. {
  346. global $conf;
  347. dol_syslog(__METHOD__, LOG_DEBUG);
  348. $records = array();
  349. $sql = 'SELECT ';
  350. $sql .= $this->getFieldList('t');
  351. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  352. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  353. $sql .= ' WHERE t.entity IN ('.getEntity($this->element).')';
  354. } else {
  355. $sql .= ' WHERE 1 = 1';
  356. }
  357. // Manage filter
  358. $sqlwhere = array();
  359. if (count($filter) > 0) {
  360. foreach ($filter as $key => $value) {
  361. if ($key == 't.rowid') {
  362. $sqlwhere[] = $key.'='.$value;
  363. } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  364. $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
  365. } elseif ($key == 'customsql') {
  366. $sqlwhere[] = $value;
  367. } elseif (strpos($value, '%') === false) {
  368. $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
  369. } else {
  370. $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
  371. }
  372. }
  373. }
  374. if (count($sqlwhere) > 0) {
  375. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  376. }
  377. if (!empty($sortfield)) {
  378. $sql .= $this->db->order($sortfield, $sortorder);
  379. }
  380. if (!empty($limit)) {
  381. $sql .= ' '.$this->db->plimit($limit, $offset);
  382. }
  383. $resql = $this->db->query($sql);
  384. if ($resql) {
  385. $num = $this->db->num_rows($resql);
  386. $i = 0;
  387. while ($i < ($limit ? min($limit, $num) : $num)) {
  388. $obj = $this->db->fetch_object($resql);
  389. $record = new self($this->db);
  390. $record->setVarsFromFetchObj($obj);
  391. $records[$record->id] = $record;
  392. $i++;
  393. }
  394. $this->db->free($resql);
  395. return $records;
  396. } else {
  397. $this->errors[] = 'Error '.$this->db->lasterror();
  398. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  399. return -1;
  400. }
  401. }
  402. /**
  403. * Update object into database
  404. *
  405. * @param User $user User that modifies
  406. * @param bool $notrigger false=launch triggers after, true=disable triggers
  407. * @return int Return integer <0 if KO, >0 if OK
  408. */
  409. public function update(User $user, $notrigger = false)
  410. {
  411. return $this->updateCommon($user, $notrigger);
  412. }
  413. /**
  414. * Delete object in database
  415. *
  416. * @param User $user User that deletes
  417. * @param bool $notrigger false=launch triggers after, true=disable triggers
  418. * @return int Return integer <0 if KO, >0 if OK
  419. */
  420. public function delete(User $user, $notrigger = false)
  421. {
  422. return $this->deleteCommon($user, $notrigger);
  423. //return $this->deleteCommon($user, $notrigger, 1);
  424. }
  425. /**
  426. * Delete a line of object in database
  427. *
  428. * @param User $user User that delete
  429. * @param int $idline Id of line to delete
  430. * @param bool $notrigger false=launch triggers after, true=disable triggers
  431. * @return int >0 if OK, <0 if KO
  432. */
  433. public function deleteLine(User $user, $idline, $notrigger = false)
  434. {
  435. if ($this->status < 0) {
  436. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  437. return -2;
  438. }
  439. return $this->deleteLineCommon($user, $idline, $notrigger);
  440. }
  441. /**
  442. * Validate object
  443. *
  444. * @param User $user User making status change
  445. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  446. * @return int Return integer <=0 if OK, 0=Nothing done, >0 if KO
  447. */
  448. public function validate($user, $notrigger = 0)
  449. {
  450. global $conf, $langs;
  451. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  452. $error = 0;
  453. // Protection
  454. if ($this->status == self::STATUS_VALIDATED) {
  455. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  456. return 0;
  457. }
  458. $now = dol_now();
  459. $this->db->begin();
  460. // Define new ref
  461. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  462. $num = $this->getNextNumRef();
  463. } else {
  464. $num = $this->ref;
  465. }
  466. $this->newref = $num;
  467. if (!empty($num)) {
  468. // Validate
  469. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  470. $sql .= " SET ref = '".$this->db->escape($num)."',";
  471. $sql .= " status = ".self::STATUS_VALIDATED;
  472. if (!empty($this->fields['date_validation'])) {
  473. $sql .= ", date_validation = '".$this->db->idate($now)."'";
  474. }
  475. if (!empty($this->fields['fk_user_valid'])) {
  476. $sql .= ", fk_user_valid = ".((int) $user->id);
  477. }
  478. $sql .= " WHERE rowid = ".((int) $this->id);
  479. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  480. $resql = $this->db->query($sql);
  481. if (!$resql) {
  482. dol_print_error($this->db);
  483. $this->error = $this->db->lasterror();
  484. $error++;
  485. }
  486. if (!$error && !$notrigger) {
  487. // Call trigger
  488. $result = $this->call_trigger('HRM_EVALUATION_VALIDATE', $user);
  489. if ($result < 0) {
  490. $error++;
  491. }
  492. // End call triggers
  493. }
  494. }
  495. if (!$error) {
  496. $this->oldref = $this->ref;
  497. // Rename directory if dir was a temporary ref
  498. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  499. // Now we rename also files into index
  500. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'evaluation/".$this->db->escape($this->newref)."'";
  501. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'evaluation/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  502. $resql = $this->db->query($sql);
  503. if (!$resql) {
  504. $error++;
  505. $this->error = $this->db->lasterror();
  506. }
  507. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'evaluation/".$this->db->escape($this->newref)."'";
  508. $sql .= " WHERE filepath = 'evaluation/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  509. $resql = $this->db->query($sql);
  510. if (!$resql) {
  511. $error++;
  512. $this->error = $this->db->lasterror();
  513. }
  514. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  515. $oldref = dol_sanitizeFileName($this->ref);
  516. $newref = dol_sanitizeFileName($num);
  517. $dirsource = $conf->hrm->dir_output.'/evaluation/'.$oldref;
  518. $dirdest = $conf->hrm->dir_output.'/evaluation/'.$newref;
  519. if (!$error && file_exists($dirsource)) {
  520. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  521. if (@rename($dirsource, $dirdest)) {
  522. dol_syslog("Rename ok");
  523. // Rename docs starting with $oldref with $newref
  524. $listoffiles = dol_dir_list($conf->hrm->dir_output.'/evaluation/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  525. foreach ($listoffiles as $fileentry) {
  526. $dirsource = $fileentry['name'];
  527. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  528. $dirsource = $fileentry['path'].'/'.$dirsource;
  529. $dirdest = $fileentry['path'].'/'.$dirdest;
  530. @rename($dirsource, $dirdest);
  531. }
  532. }
  533. }
  534. }
  535. }
  536. // Set new ref and current status
  537. if (!$error) {
  538. $this->ref = $num;
  539. $this->status = self::STATUS_VALIDATED;
  540. }
  541. if (!$error) {
  542. $this->db->commit();
  543. return 1;
  544. } else {
  545. $this->db->rollback();
  546. return -1;
  547. }
  548. }
  549. /**
  550. * Get the last evaluation by date for the user assigned
  551. *
  552. * @param int $fk_user ID of user we need to get last eval
  553. * @return Evaluation|null
  554. */
  555. public function getLastEvaluationForUser($fk_user)
  556. {
  557. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."hrm_evaluation ";
  558. $sql.= "WHERE fk_user=".((int) $fk_user)." ";
  559. $sql.= "ORDER BY date_eval DESC ";
  560. $sql.= "LIMIT 1 ";
  561. $res = $this->db->query($sql);
  562. if (!$res) {
  563. dol_print_error($this->db);
  564. }
  565. $Tab = $this->db->fetch_object($res);
  566. if (empty($Tab)) {
  567. return null;
  568. } else {
  569. $evaluation = new Evaluation($this->db);
  570. $evaluation->fetch($Tab->rowid);
  571. return $evaluation;
  572. }
  573. }
  574. /**
  575. * Set draft status
  576. *
  577. * @param User $user Object user that modify
  578. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  579. * @return int Return integer <0 if KO, >0 if OK
  580. */
  581. public function setDraft($user, $notrigger = 0)
  582. {
  583. // Protection
  584. if ($this->status <= self::STATUS_DRAFT) {
  585. return 0;
  586. }
  587. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'HRM_EVALUATION_UNVALIDATE');
  588. }
  589. /**
  590. * Set cancel status
  591. *
  592. * @param User $user Object user that modify
  593. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  594. * @return int Return integer <0 if KO, 0=Nothing done, >0 if OK
  595. */
  596. public function cancel($user, $notrigger = 0)
  597. {
  598. // Protection
  599. if ($this->status != self::STATUS_VALIDATED) {
  600. return 0;
  601. }
  602. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'HRM_EVALUATION_CANCEL');
  603. }
  604. /**
  605. * Set back to validated status
  606. *
  607. * @param User $user Object user that modify
  608. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  609. * @return int Return integer <0 if KO, 0=Nothing done, >0 if OK
  610. */
  611. public function reopen($user, $notrigger = 0)
  612. {
  613. // Protection
  614. if ($this->status != self::STATUS_CANCELED) {
  615. return 0;
  616. }
  617. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'HRM_EVALUATION_REOPEN');
  618. }
  619. /**
  620. * Return a link to the object card (with optionaly the picto)
  621. *
  622. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  623. * @param string $option On what the link point to ('nolink', ...)
  624. * @param int $notooltip 1=Disable tooltip
  625. * @param string $morecss Add more css on link
  626. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  627. * @return string String with URL
  628. */
  629. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  630. {
  631. global $conf, $langs, $hookmanager;
  632. if (!empty($conf->dol_no_mouse_hover)) {
  633. $notooltip = 1; // Force disable tooltips
  634. }
  635. $result = '';
  636. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Evaluation").'</u>';
  637. if (isset($this->status)) {
  638. $label .= ' '.$this->getLibStatut(5);
  639. }
  640. $label .= '<br>';
  641. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  642. $url = dol_buildpath('/hrm/evaluation_card.php', 1).'?id='.$this->id;
  643. if ($option != 'nolink') {
  644. // Add param to save lastsearch_values or not
  645. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  646. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  647. $add_save_lastsearch_values = 1;
  648. }
  649. if ($add_save_lastsearch_values) {
  650. $url .= '&save_lastsearch_values=1';
  651. }
  652. }
  653. $linkclose = '';
  654. if (empty($notooltip)) {
  655. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  656. $label = $langs->trans("ShowEvaluation");
  657. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  658. }
  659. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  660. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  661. } else {
  662. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  663. }
  664. if ($option == 'nolink') {
  665. $linkstart = '<span';
  666. } else {
  667. $linkstart = '<a href="'.$url.'"';
  668. }
  669. $linkstart .= $linkclose.'>';
  670. if ($option == 'nolink') {
  671. $linkend = '</span>';
  672. } else {
  673. $linkend = '</a>';
  674. }
  675. $result .= $linkstart;
  676. if (empty($this->showphoto_on_popup)) {
  677. if ($withpicto) {
  678. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  679. }
  680. } else {
  681. if ($withpicto) {
  682. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  683. list($class, $module) = explode('@', $this->picto);
  684. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  685. $filearray = dol_dir_list($upload_dir, "files");
  686. $filename = $filearray[0]['name'];
  687. if (!empty($filename)) {
  688. $pospoint = strpos($filearray[0]['name'], '.');
  689. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  690. if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
  691. $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
  692. } else {
  693. $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
  694. }
  695. $result .= '</div>';
  696. } else {
  697. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  698. }
  699. }
  700. }
  701. if ($withpicto != 2) {
  702. $result .= $this->ref;
  703. }
  704. $result .= $linkend;
  705. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  706. global $action, $hookmanager;
  707. $hookmanager->initHooks(array('evaluationdao'));
  708. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  709. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  710. if ($reshook > 0) {
  711. $result = $hookmanager->resPrint;
  712. } else {
  713. $result .= $hookmanager->resPrint;
  714. }
  715. return $result;
  716. }
  717. /**
  718. * Return the label of the status
  719. *
  720. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  721. * @return string Label of status
  722. */
  723. public function getLibStatut($mode = 0)
  724. {
  725. return $this->LibStatut($this->status, $mode);
  726. }
  727. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  728. /**
  729. * Return the status
  730. *
  731. * @param int $status Id status
  732. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  733. * @return string Label of status
  734. */
  735. public function LibStatut($status, $mode = 0)
  736. {
  737. // phpcs:enable
  738. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  739. global $langs;
  740. //$langs->load("hrm");
  741. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  742. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
  743. $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('Closed');
  744. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  745. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
  746. $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('Closed');
  747. }
  748. $statusType = 'status'.$status;
  749. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  750. if ($status == self::STATUS_CANCELED) {
  751. $statusType = 'status6';
  752. }
  753. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  754. }
  755. /**
  756. * Load the info information in the object
  757. *
  758. * @param int $id Id of object
  759. * @return void
  760. */
  761. public function info($id)
  762. {
  763. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  764. $sql .= ' fk_user_creat, fk_user_modif';
  765. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  766. $sql .= ' WHERE t.rowid = '.((int) $id);
  767. $result = $this->db->query($sql);
  768. if ($result) {
  769. if ($this->db->num_rows($result)) {
  770. $obj = $this->db->fetch_object($result);
  771. $this->id = $obj->rowid;
  772. $this->user_creation_id = $obj->fk_user_creat;
  773. $this->user_modification_id = $obj->fk_user_modif;
  774. $this->date_creation = $this->db->jdate($obj->datec);
  775. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  776. }
  777. $this->db->free($result);
  778. } else {
  779. dol_print_error($this->db);
  780. }
  781. }
  782. /**
  783. * Initialise object with example values
  784. * Id must be 0 if object instance is a specimen
  785. *
  786. * @return void
  787. */
  788. public function initAsSpecimen()
  789. {
  790. // Set here init that are not commonf fields
  791. // $this->property1 = ...
  792. // $this->property2 = ...
  793. $this->initAsSpecimenCommon();
  794. }
  795. /**
  796. * Create an array of lines
  797. *
  798. * @return array|int array of lines if OK, <0 if KO
  799. */
  800. public function getLinesArray()
  801. {
  802. $this->lines = array();
  803. $objectline = new EvaluationLine($this->db);
  804. $result = $objectline->fetchAll('ASC', '', 0, 0, array('customsql'=>'fk_evaluation = '.$this->id));
  805. if (is_numeric($result)) {
  806. $this->error = $objectline->error;
  807. $this->errors = $objectline->errors;
  808. return $result;
  809. } else {
  810. $this->lines = $result;
  811. return $this->lines;
  812. }
  813. }
  814. /**
  815. * Returns the reference to the following non used object depending on the active numbering module.
  816. *
  817. * @return string Object free reference
  818. */
  819. public function getNextNumRef()
  820. {
  821. global $langs, $conf;
  822. $langs->load("hrm");
  823. if (!getDolGlobalString('HRMTEST_EVALUATION_ADDON')) {
  824. $conf->global->HRMTEST_EVALUATION_ADDON = 'mod_evaluation_standard';
  825. }
  826. if (getDolGlobalString('HRMTEST_EVALUATION_ADDON')) {
  827. $mybool = false;
  828. $file = getDolGlobalString('HRMTEST_EVALUATION_ADDON') . ".php";
  829. $classname = $conf->global->HRMTEST_EVALUATION_ADDON;
  830. // Include file with class
  831. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  832. foreach ($dirmodels as $reldir) {
  833. $dir = dol_buildpath($reldir."core/modules/hrm/");
  834. // Load file with numbering class (if found)
  835. $mybool |= @include_once $dir.$file;
  836. }
  837. if ($mybool === false) {
  838. dol_print_error('', "Failed to include file ".$file);
  839. return '';
  840. }
  841. if (class_exists($classname)) {
  842. $obj = new $classname();
  843. $numref = $obj->getNextValue($this);
  844. if ($numref != '' && $numref != '-1') {
  845. return $numref;
  846. } else {
  847. $this->error = $obj->error;
  848. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  849. return "";
  850. }
  851. } else {
  852. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  853. return "";
  854. }
  855. } else {
  856. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  857. return "";
  858. }
  859. }
  860. /**
  861. * Create a document onto disk according to template module.
  862. *
  863. * @param string $modele Force template to use ('' to not force)
  864. * @param Translate $outputlangs objet lang a utiliser pour traduction
  865. * @param int $hidedetails Hide details of lines
  866. * @param int $hidedesc Hide description
  867. * @param int $hideref Hide ref
  868. * @param null|array $moreparams Array to provide more information
  869. * @return int 0 if KO, 1 if OK
  870. */
  871. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  872. {
  873. global $conf, $langs;
  874. $result = 0;
  875. $langs->load("hrm");
  876. if (!dol_strlen($modele)) {
  877. $modele = 'standard';
  878. if (!empty($this->model_pdf)) {
  879. $modele = $this->model_pdf;
  880. } elseif (getDolGlobalString('EVALUATION_ADDON_PDF')) {
  881. $modele = $conf->global->EVALUATION_ADDON_PDF;
  882. }
  883. }
  884. $modelpath = "core/modules/hrm/doc/";
  885. if (!empty($modele)) {
  886. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  887. }
  888. return $result;
  889. }
  890. /**
  891. * Action executed by scheduler
  892. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  893. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  894. *
  895. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  896. */
  897. public function doScheduledJob()
  898. {
  899. global $conf, $langs;
  900. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  901. $error = 0;
  902. $this->output = '';
  903. $this->error = '';
  904. dol_syslog(__METHOD__, LOG_DEBUG);
  905. $now = dol_now();
  906. $this->db->begin();
  907. // ...
  908. $this->db->commit();
  909. return $error;
  910. }
  911. /**
  912. * Return clicable link of object (with eventually picto)
  913. *
  914. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  915. * @param array $arraydata Array of data
  916. * @return string HTML Code for Kanban thumb.
  917. */
  918. public function getKanbanView($option = '', $arraydata = null)
  919. {
  920. global $selected, $langs;
  921. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  922. $return = '<div class="box-flex-item box-flex-grow-zero">';
  923. $return .= '<div class="info-box info-box-sm">';
  924. $return .= '<span class="info-box-icon bg-infobox-action">';
  925. $return .= img_picto('', $this->picto);
  926. $return .= '</span>';
  927. $return .= '<div class="info-box-content">';
  928. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'</span>';
  929. $return .= '<input class="fright" id="cb'.$this->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  930. if (!empty($arraydata['user'])) {
  931. $return .= '<br><span class="info-box-label ">'.$arraydata['user'].'</span>';
  932. }
  933. if (!empty($arraydata['job'])) {
  934. $return .= '<br><span class="info-box-label ">'.$arraydata['job'].'</span>';
  935. }
  936. if (method_exists($this, 'getLibStatut')) {
  937. $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
  938. }
  939. $return .= '</div>';
  940. $return .= '</div>';
  941. $return .= '</div>';
  942. return $return;
  943. }
  944. }