diff --git a/README.md b/README.md index b23618bf1..47c6625db 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ ## Informations - Numéro du module : 436302 -- Dernière mise à jour : 24/10/2023 +- Dernière mise à jour : 30/11/2023 - Éditeur : [Evarisk](https://evarisk.com) - Thème : Eldy Menu - Licence : GPLv3 @@ -11,9 +11,9 @@ ### Version -- Version : 9.13.0 +- Version : 9.14.0 - PHP : 7.4.33 -- Compatibilité : Dolibarr 16.0.0 - 18.0.1 +- Compatibilité : Dolibarr 16.0.0 - 18.0.3 - Saturne Framework : 1.2.0 ## Liens @@ -22,6 +22,7 @@ - Demo : [Demo Digirisk](https://demodoli.digirisk.com) - ID: demo - Password: demo - Documentation : [Wiki Digirisk](https://wiki.dolibarr.org/index.php/Module_DigiriskDolibarr) - Projet GitHub : [Projet Digirisk](https://github.com/Evarisk/Digirisk/projects?type=classic) +- Saturne Framework : [Télécharger Saturne](https://dolistore.com/fr/modules/1906-Saturne.html) - Forum : [Forum Digirisk](https://dolibarr.fr/forum/t/module-digirisk-document-unique/37119) - D'autres modules développés par Evarisk disponibles sur [Dolistore.com](https://dolistore.com) @@ -47,5 +48,6 @@ Gérez les risques de votre entreprise et créez votre Document Unique en toute - Dans le dossier "dolibarr/htdocs/custom" copier la ligne suivante : ``` git clone -b main https://github.com/Evarisk/Digirisk.git digiriskdolibarr +git clone -b main https://github.com/Evarisk/Saturne.git saturne ``` - Activer le module dans la liste des Modules/Applications installés diff --git a/admin/ticket/ticket.php b/admin/ticket/ticket.php index 790664de0..c55035f9e 100644 --- a/admin/ticket/ticket.php +++ b/admin/ticket/ticket.php @@ -228,6 +228,51 @@ setEventMessages($langs->transnoentities('QRCodeGenerated'), array()); } +if ($action == 'createTimeRange') { + $comparatorPost = GETPOST('comparator'); + $rangeNumberPost = GETPOST('range_value'); + $timeRangePost = GETPOST('time_range'); + $constraintLabel = GETPOST('range_label'); + + if (empty($rangeNumberPost)) { + setEventMessage($langs->trans('MissingRangeValue'), 'errors'); + header("Location: " . $_SERVER["PHP_SELF"]); + exit; + } + if (dol_strlen($constraintLabel) == 0) { + $constraintLabel = $langs->trans($langs->transnoentities(ucfirst($comparatorPost) . 'Than') . ' ' . $rangeNumberPost . ' ' . $langs->transnoentities(ucfirst($timeRangePost))); + } + + $accidentWorkStopTimeRangesJson = $conf->global->DIGIRISKDOLIBARR_TICKET_STATISTICS_ACCIDENT_TIME_RANGE; + $accidentWorkStopTimeRanges = json_decode($accidentWorkStopTimeRangesJson, true); + $accidentWorkStopTimeRanges[$constraintLabel] = $comparatorPost . ':' . $rangeNumberPost . ':' . $timeRangePost; + + $newTimeRangeJson = json_encode($accidentWorkStopTimeRanges); + + dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_STATISTICS_ACCIDENT_TIME_RANGE', $newTimeRangeJson, 'chaine', 0, '', $conf->entity); + + setEventMessages($langs->transnoentities('TimeRangeAdded'), array()); + + header("Location: " . $_SERVER["PHP_SELF"]); + exit; +} + +if ($action == 'deleteTimeRange') { + $constraintLabel = GETPOST('value'); + $accidentWorkStopTimeRangesJson = $conf->global->DIGIRISKDOLIBARR_TICKET_STATISTICS_ACCIDENT_TIME_RANGE; + $accidentWorkStopTimeRanges = json_decode($accidentWorkStopTimeRangesJson, true); + unset($accidentWorkStopTimeRanges[$constraintLabel]); + + $newTimeRangeJson = json_encode($accidentWorkStopTimeRanges); + + dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_STATISTICS_ACCIDENT_TIME_RANGE', $newTimeRangeJson, 'chaine', 0, '', $conf->entity); + + setEventMessages($langs->transnoentities('TimeRangeDeleted'), array()); + + header("Location: " . $_SERVER["PHP_SELF"]); + exit; +} + /* * View */ @@ -361,7 +406,7 @@ print ''; print ''; - if (getDolGlobalInt('DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS') > 0) { + if (dolibarr_get_const($db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', 0)) { print load_fiche_titre($langs->transnoentities("PublicInterfaceConfiguration"), '', ''); print '
'; @@ -792,6 +837,87 @@ print '' . $langs->transnoentities("TicketPublicInterfaceConfigDocumentation") . ' : ' . $langs->transnoentities('DigiriskDocumentation') . ''; } +print load_fiche_titre($langs->transnoentities("TicketStatistics"), '', ''); + +$comparators = [ + 'less' => $langs->trans('Inferior'), + 'more' => $langs->trans('Superior') +]; +$range = [ + 'days' => $langs->trans('Days'), + 'weeks' => $langs->trans('Weeks'), + 'months' => $langs->trans('Months'), + 'years' => $langs->trans('Years') +]; + +$accidentWorkStopTimeRangesJson = $conf->global->DIGIRISKDOLIBARR_TICKET_STATISTICS_ACCIDENT_TIME_RANGE; +$accidentWorkStopTimeRanges = json_decode($accidentWorkStopTimeRangesJson, true); + +print '
'; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +// Existing constraints +if (is_array($accidentWorkStopTimeRanges) && !empty($accidentWorkStopTimeRanges)) { + foreach ($accidentWorkStopTimeRanges as $rangeName => $rangeConstraint) { + if (strstr($rangeConstraint, ':')) { + $rangeConstraintDetails = explode(':', $rangeConstraint); + $rangeComparator = $rangeConstraintDetails[0] == 'less' ? $langs->trans('LessThan') : $langs->trans('MoreThan'); + $rangeNumber = $rangeConstraintDetails[1]; + $rangeUnit = $langs->trans(ucfirst($rangeConstraintDetails[2])); + } + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } +} + +// Add new constraint +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + // End of page llxFooter(); $db->close(); diff --git a/class/accident.class.php b/class/accident.class.php index c22185936..3476889ea 100644 --- a/class/accident.class.php +++ b/class/accident.class.php @@ -31,6 +31,7 @@ require_once __DIR__ . '/../lib/digiriskdolibarr_function.lib.php'; require_once __DIR__ . '/digiriskdocuments.class.php'; +require_once __DIR__ . '/digiriskdolibarrdashboard.class.php'; require_once __DIR__ . '/evaluator.class.php'; require_once __DIR__ . '/../core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_standard.php'; @@ -155,9 +156,8 @@ class Accident extends SaturneObject 'entity' => ['type' => 'integer', 'label' => 'Entity', 'enabled' => '1', 'position' => 30, 'notnull' => 1, 'visible' => 0,], 'date_creation' => ['type' => 'datetime', 'label' => 'DateCreation', 'enabled' => '1', 'position' => 40, 'notnull' => 1, 'visible' => 2,], 'tms' => ['type' => 'timestamp', 'label' => 'DateModification', 'enabled' => '1', 'position' => 50, 'notnull' => 0, 'visible' => 0,], - 'status' => ['type' => 'smallint', 'label' => 'Status', 'enabled' => '1', 'position' => 70, 'notnull' => 1, 'visible' => 2, 'index' => 0, 'arrayofkeyval' => [1 => 'InProgress', 2 => 'Locked']], + 'status' => ['type' => 'smallint', 'label' => 'Status', 'enabled' => '1', 'position' => 70, 'notnull' => 1, 'visible' => 2, 'index' => 0, 'arrayofkeyval' => [0 => 'StatusDraft', 1 => 'Validated', 2 => 'Locked']], 'label' => ['type' => 'varchar(255)', 'label' => 'Label', 'enabled' => '1', 'position' => 80, 'notnull' => 0, 'visible' => 1, 'searchall' => 1, 'css' => 'minwidth200', 'help' => "Help text", 'showoncombobox' => '1',], - 'fk_user_victim' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserVictim', 'enabled' => '1', 'position' => 81, 'notnull' => -1, 'visible' => 1,], 'fk_user_employer' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserEmployer', 'enabled' => '1', 'position' => 82, 'notnull' => -1, 'visible' => 1,], 'accident_type' => ['type' => 'text', 'label' => 'AccidentType', 'enabled' => '1', 'position' => 90, 'notnull' => -1, 'visible' => 1, 'css' => 'minwidth150',], 'fk_element' => ['type' => 'integer', 'label' => 'AccidentLocation', 'enabled' => '1', 'position' => 91, 'notnull' => -1, 'visible' => 1, 'css' => 'minwidth150',], @@ -169,8 +169,9 @@ class Accident extends SaturneObject 'photo' => ['type' => 'text', 'label' => 'Photo', 'enabled' => '1', 'position' => 120, 'notnull' => -1, 'visible' => 3,], 'external_accident' => ['type' => 'smallint', 'label' => 'ExternalAccident', 'enabled' => '1', 'position' => 130, 'notnull' => -1, 'visible' => 3, 'arrayofkeyval' => ['1' => 'No', '2' => 'Yes', '3' => 'Other'],], 'fk_project' => ['type' => 'integer', 'label' => 'FKProject', 'enabled' => '1', 'position' => 140, 'notnull' => 1, 'visible' => 0,], - 'fk_user_creat' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => '1', 'position' => 150, 'notnull' => 1, 'visible' => 0, 'foreignkey' => 'user.rowid',], - 'fk_user_modif' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => '1', 'position' => 160, 'notnull' => -1, 'visible' => 0,], + 'fk_ticket' => ['type' => 'integer:Ticket:ticket/class/ticket.class.php', 'label' => 'FkTicket', 'enabled' => '1', 'position' => 145, 'notnull' => -1, 'visible' => 1,], + 'fk_user_creat' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => '1', 'position' => 150, 'notnull' => 1, 'visible' => 0, 'foreignkey' => 'user.rowid',], + 'fk_user_modif' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => '1', 'position' => 160, 'notnull' => -1, 'visible' => 0,], ]; public $rowid; @@ -190,9 +191,9 @@ class Accident extends SaturneObject public $fk_user_creat; public $fk_user_modif; public $fk_element; - public $fk_standard; + public $fk_standard; + public $fk_ticket; public $fk_soc; - public $fk_user_victim; public $fk_user_employer; /** @@ -202,6 +203,10 @@ class Accident extends SaturneObject */ public function __construct(DoliDB $db) { + //Transform fk_user_victim into victim signatory for every accidents (backward compatibility) + if (empty(getDolGlobalInt("DIGIRISKDOLIBARR_ACCIDENT_REMOVE_FK_USER_VICTIM"))) { + $this->fields['fk_user_victim'] = ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserVictim', 'enabled' => '1', 'position' => 81, 'notnull' => -1, 'visible' => 1,]; + } return parent::__construct($db, $this->module, $this->element); } @@ -253,7 +258,7 @@ public function createFromClone(User $user, int $fromID, array $options): int $object->date_creation = dol_now(); } if (property_exists($object, 'status')) { - $object->status = self::STATUS_VALIDATED; + $object->status = self::STATUS_DRAFT; } if (empty($options['photos'])) { $object->photo = ''; @@ -303,6 +308,29 @@ public function createFromClone(User $user, int $fromID, array $options): int $accidentMetadata->fk_accident = $accidentId; $accidentMetadata->context = 'createfromclone'; $accidentMetadata->create($user); + } + if (!empty($options['categories'])) { + $cat = new Categorie($this->db); + $categories = $cat->containing($objectId, 'accident'); + if (is_array($categories) && !empty($categories)) { + $categoryIds = []; + foreach ($categories as $cat) { + $categoryIds[] = $cat->id; + } + $object->setCategories($categoryIds); + } + } + if (!empty($options['attendants'])) { + // Load signatory from source object. + $signatory = new SaturneSignature($this->db, $this->module, $this->element); + $signatories = $signatory->fetchSignatory('', $fromID, $this->element); + if (is_array($signatories) && !empty($signatories)) { + foreach ($signatories as $arrayRole) { + foreach ($arrayRole as $signatoryRole) { + $signatory->createFromClone($user, $signatoryRole->id, $accidentId); + } + } + } } } else { $error++; @@ -349,26 +377,27 @@ public function LibStatut(int $status, int $mode = 0): string global $langs; $this->labelStatus[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); - $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('InProgress'); + $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusDraft'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated'); $this->labelStatus[self::STATUS_LOCKED] = $langs->transnoentitiesnoconv('Locked'); $this->labelStatusShort[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); - $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('InProgress'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusDraft'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated'); $this->labelStatusShort[self::STATUS_LOCKED] = $langs->transnoentitiesnoconv('Locked'); } - $statusType = 'status' . $status; - - if ($status == self::STATUS_VALIDATED) { - $statusType = 'status4'; - } - if ($status == self::STATUS_LOCKED) { - $statusType = 'status6'; - } - if ($status == self::STATUS_DELETED) { - $statusType = 'status9'; - } + $statusType = 'status' . $status; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } + if ($status == self::STATUS_LOCKED) { + $statusType = 'status6'; + } + if ($status == self::STATUS_DELETED) { + $statusType = 'status9'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -385,6 +414,7 @@ public function load_dashboard(): array $arrayNbDaysWithoutAccident = $this->getNbDaysWithoutAccident(); $arrayNbAccidents = $this->getNbAccidents(); + $arrayNbAccidentsLast3Years = $this->getNbAccidentsLast3years(); $arrayNbWorkstopDays = $this->getNbWorkstopDays(); $arrayNbAccidentsByEmployees = $this->getNbAccidentsByEmployees(); $arrayNbPresquAccidents = $this->getNbPresquAccidents(); @@ -414,7 +444,7 @@ public function load_dashboard(): array ] ]; - $array['graphs'] = [$arrayNbAccidents]; + $array['graphs'] = [$arrayNbAccidents, $arrayNbAccidentsLast3Years]; return $array; } @@ -492,6 +522,78 @@ public function getNbAccidents(): array return $array; } + + /** + * Get number accidents for last 3 years + * + * @return array + * @throws Exception + */ + public function getNbAccidentsLast3years(): array + { + global $langs; + + // Graph Title parameters + $array['title'] = $langs->transnoentities('AccidentByYear'); + $array['picto'] = $this->picto; + + // Graph parameters + $array['width'] = '100%'; + $array['height'] = 400; + $array['type'] = 'bar'; + $array['showlegend'] = 1; + $array['dataset'] = 3; + + $array['labels'] = [ + 'pastlastyear' => [ + 'label' => date("Y",strtotime("-2 year")), + 'color' => '#9567aa' + ], + 'lastyear' => [ + 'label' => date("Y",strtotime("-1 year")), + 'color' => '#4f9ebe' + ], + 'currentyear' => [ + 'label' => date('Y'), + 'color' => '#fac461' + ], + ]; + + $arrayAccidents = []; + + $accidentList = $this->fetchAll(); + + if (is_array($accidentList) && !empty($accidentList)) { + foreach($accidentList as $accident) { + $accidentDate = getdate($accident->accident_date); + $yearKey = $accidentDate['year']; + $monthKey = $accidentDate['mon']; + $accidentsByYear[$yearKey][$monthKey - 1] += 1; + } + } + + for ($i = 1; $i < 13; $i++) { + $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i)); + $arrayAccidents[$i - 1] = array($month); + for ($j = 0; $j < 3; $j++) { + $arrayAccidents[$i - 1][date('Y') - 2 + $j] = 0; + } + } + + + foreach($accidentsByYear as $year => $accidentByYear) { + foreach($accidentByYear as $month => $accidentByMonth) { + $arrayAccidents[$month][$year] = $accidentByMonth; + } + } + + foreach($arrayAccidents as $arrayAccident) { + $array['data'][] = array_values($arrayAccident); + } + + return $array; + } + /** * Get number workstop days. * @@ -668,6 +770,24 @@ public function getGravityRate() { return $array; } + /** + * Get user victim object. + * + * @return User + */ + public function getUserVictim():User { + $user = new User($this->db); + $signatory = new SaturneSignature($this->db); + + $victimSignatory = $signatory->fetchSignatory('Victim', $this->id, 'accident'); + + if (is_array($victimSignatory) && !empty($victimSignatory)) { + $victimSignatory = array_shift($victimSignatory); + $user->fetch($victimSignatory->element_id); + } + return $user; + } + /** * Write information of trigger description * @@ -680,9 +800,9 @@ public function getTriggerDescription(SaturneObject $object): string require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php'; - $userVictim = new User($this->db); - $userEmployer = new User($this->db); - $userVictim->fetch($object->fk_user_victim); + $userEmployer = new User($this->db); + $userVictim = $this->getUserVictim(); + $userEmployer->fetch($object->fk_user_employer); //1 : Accident in DU / GP, 2 : Accident in society, 3 : Accident in another location diff --git a/class/accidentinvestigation.class.php b/class/accidentinvestigation.class.php index 94e7a28d1..06b32a447 100644 --- a/class/accidentinvestigation.class.php +++ b/class/accidentinvestigation.class.php @@ -65,7 +65,6 @@ class AccidentInvestigation extends SaturneObject public const STATUS_DRAFT = 0; public const STATUS_VALIDATED = 1; public const STATUS_LOCKED = 2; - public const STATUS_CLASSIFIED = 3; public const STATUS_ARCHIVED = 3; /** @@ -118,7 +117,7 @@ class AccidentInvestigation extends SaturneObject 'date_creation' => ['type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 40, 'notnull' => 1, 'visible' => 2,], 'tms' => ['type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 50, 'notnull' => 0, 'visible' => 0,], 'import_key' => ['type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => 0, 'index' => 0], - 'status' => ['type' => 'smallint', 'label' => 'Status', 'enabled' => 1, 'position' => 70, 'notnull' => 1, 'visible' => 2, 'noteditable' => 1, 'default' => 0, 'index' => 0, 'arrayofkeyval' => [0 => 'InProgress', 1 => 'Validated', 3 => 'Classified']], + 'status' => ['type' => 'smallint', 'label' => 'Status', 'enabled' => 1, 'position' => 70, 'notnull' => 1, 'visible' => 2, 'noteditable' => 1, 'default' => 0, 'index' => 0, 'arrayofkeyval' => [0 => 'StatusDraft', 1 => 'Validated', 2 => 'Locked', 3 => 'Archived']], 'seniority_in_position' => ['type' => 'varchar(255)', 'label' => 'SeniorityInPosition', 'enabled' => 1, 'position' => 80, 'notnull' => 0, 'visible' => 1, 'css' => 'maxwidth200'], 'date_start' => ['type' => 'datetime', 'label' => 'StartDate', 'enabled' => 1, 'position' => 90, 'notnull' => 0, 'visible' => 1,], 'date_end' => ['type' => 'datetime', 'label' => 'EndDate', 'enabled' => 1, 'position' => 100, 'notnull' => 0, 'visible' => 1,], @@ -437,24 +436,29 @@ public function LibStatut(int $status, int $mode = 0): string if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; - $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusDraft'); - $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated'); - $this->labelStatus[self::STATUS_CLASSIFIED] = $langs->transnoentitiesnoconv('Classified'); - $this->labelStatus[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); - - $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusDraft'); - $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated'); - $this->labelStatusShort[self::STATUS_CLASSIFIED] = $langs->transnoentitiesnoconv('Classified'); - $this->labelStatusShort[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); + $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusDraft'); + $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated'); + $this->labelStatus[self::STATUS_LOCKED] = $langs->transnoentitiesnoconv('Locked'); + $this->labelStatus[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived'); + $this->labelStatus[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); + + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusDraft'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated'); + $this->labelStatusShort[self::STATUS_LOCKED] = $langs->transnoentitiesnoconv('Locked'); + $this->labelStatusShort[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived'); + $this->labelStatusShort[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); } $statusType = 'status' . $status; if ($status == self::STATUS_VALIDATED) { $statusType = 'status4'; } - if ($status == self::STATUS_CLASSIFIED) { - $statusType = 'status8'; - } + if ($status == self::STATUS_LOCKED) { + $statusType = 'status6'; + } + if ($status == self::STATUS_ARCHIVED) { + $statusType = 'status8'; + } if ($status == self::STATUS_DELETED) { $statusType = 'status9'; } diff --git a/class/actions_digiriskdolibarr.class.php b/class/actions_digiriskdolibarr.class.php index afb198150..a7eff688b 100644 --- a/class/actions_digiriskdolibarr.class.php +++ b/class/actions_digiriskdolibarr.class.php @@ -61,6 +61,37 @@ public function __construct($db) $this->db = $db; } + /** + * Overloading the constructCategory function : replacing the parent's function with the one below + * + * @param array $parameters Hook metadatas (context, etc...) + * @param CommonObject $object The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...) + * @return int 0 < on error, 0 on success, 1 to replace standard code + */ + public function constructCategory($parameters, &$object) + { + $error = 0; // Error counter + + if (($parameters['currentcontext'] == 'category')) { + $tags = [ + 'accident' => [ + 'id' => 436302001, + 'code' => 'accident', + 'obj_class' => 'Accident', + 'obj_table' => 'digiriskdolibarr_accident', + ], + ]; + } + + if (!$error) { + $this->results = $tags; + return 0; // or return 1 to replace standard code + } else { + $this->errors[] = 'Error message'; + return -1; + } + } + /** * Overloading the printCommonFooter function : replacing the parent's function with the one below * @@ -164,6 +195,27 @@ public function printCommonFooter($parameters) jQuery('.fichehalfleft .div-table-responsive-no-min').append() fetchAll('', '', 0, 0, ['customsql' => 't.fk_ticket = ' . $object->id]); + $linkedAccidentList = ''; + if (is_array($linkedAccidents) && !empty($linkedAccidents)) { + foreach ($linkedAccidents as $linkedAccident) { + $linkedAccidentList .= $linkedAccident->getNomUrl(1) . '
'; + } + } + + $fieldLinkedAccidents = ''; + $fieldLinkedAccidents .= ''; + $fieldLinkedAccidents .= ''; + ?> + + fetch(GETPOST('projectid'), GETPOST('project_ref')); - } else { - $project->fetch(GETPOST('id'), GETPOST('ref')); + if (in_array($parameters['currentcontext'], ['projectcard', 'projectcontactcard', 'projecttaskcard', 'projecttaskscard', 'projecttasktime', 'projectOverview'])) { + if (GETPOSTISSET('projectid') || GETPOSTISSET('project_ref')) { + $project->fetch( GETPOST('projectid'), GETPOST('project_ref')); + $projectId = $project->id; + } else if (in_array($parameters['currentcontext'], ['projectcard', 'projectcontactcard', 'projecttaskscard'])) { + $projectId = GETPOST('id'); + } else { + $task->fetch(GETPOST('id')); + $projectId = $task->fk_project; } - $alltasks = $task->getTasksArray(null, null, $project->id, 0, 0, '', '-1', '', 0, 0, $extrafields); - if (is_array($alltasks) && !empty($alltasks)) { - $nbtasks = count($alltasks); - foreach ($alltasks as $tasksignle) { - $filter = ' AND fk_element = ' . $tasksignle->id; - $alltimespent = $task->fetchAllTimeSpentAllUsers($filter); - foreach ($alltimespent as $timespent) { - $totatconsumedtimeamount += convertSecondToTime($timespent->timespent_duration, 'allhourmin') * $timespent->timespent_thm; + $allTasks = $task->getTasksArray(null, null, $projectId, 0, 0, '', '-1', '', 0, 0, $extrafields); + if (is_array($allTasks) && !empty($allTasks)) { + $nbTasks = count($allTasks); + foreach ($allTasks as $taskSingle) { + $filter = ' AND fk_element = ' . $taskSingle->id; + $allTimespent = $task->fetchAllTimeSpentAllUsers($filter); + foreach ($allTimespent as $timespent) { + $totatConsumedTimeAmount += convertSecondToTime($timespent->timespent_duration, 'allhourmin') * $timespent->timespent_thm; } - $totatconsumedtime += $tasksignle->duration; - $totalprogress += $tasksignle->progress; - $totaltasksbudget += $tasksignle->budget_amount; + $totalConsumedTime += $taskSingle->duration; + $totalProgress += $taskSingle->progress; + $totalTasksBudget += $taskSingle->budget_amount; } } else { - $totatconsumedtime = 0; - $totatconsumedtimeamount = 0; - $nbtasks = 0; - $totalprogress = 0; - $totaltasksbudget = 0; + $totalConsumedTime = 0; + $totatConsumedTimeAmount = 0; + $nbTasks = 0; + $totalProgress = 0; + $totalTasksBudget = 0; } - $outTotatconsumedtime = ''; - $outTotatconsumedtimeamount = ''; - $outNbtasks = ''; - $outTotalprogress = ''; - $outTotaltasksbudget = ''; ?> + $outTotatConsumedTime = ''; + $outTotatConsumedTimeAmount = ''; + $outNbtasks = ''; + $outTotalProgress = ''; + $outTotalTasksBudget = ''; ?> '; + } elseif (preg_match('/categorycard/', $parameters['context']) && preg_match('/viewcat.php/', $_SERVER["PHP_SELF"])) { + global $user; + $id = GETPOST('id'); + $type = GETPOST('type'); + + // Load variable for pagination + $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; + $sortfield = GETPOST('sortfield', 'aZ09comma'); + $sortorder = GETPOST('sortorder', 'aZ09comma'); + $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); + if (empty($page) || $page == -1) { + $page = 0; + } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action + $offset = $limit * $page; + + if ($type == 'accident') { + require_once __DIR__ . '/' . $type . '.class.php'; + + $classname = ucfirst($type); + $object = new $classname($this->db); + + $arrayObjects = $object->fetchAll(); + if (is_array($arrayObjects) && !empty($arrayObjects)) { + foreach ($arrayObjects as $objectsingle) { + $array[$objectsingle->id] = $objectsingle->ref; + } + } + + $category = new Categorie($this->db); + $category->fetch($id); + $objectsInCateg = $category->getObjectsInCateg($type, 0, $limit, $offset); + + $out = '
'; + + $out .= ''; + $out .= ''; + $out .= ''; + + $out .= '
' . $langs->transnoentities("RangeLabel") . '' . $langs->transnoentities("Comparator") . '' . $langs->transnoentities("RangeNumber") . '' . $langs->transnoentities("TimeRange") . '' . $langs->transnoentities("Action") . '
'; + print $rangeName; + print ''; + print $rangeComparator; + print ''; + print $rangeNumber; + print ''; + print $rangeUnit; + print ''; + print ''; + print ''; + print ''; + print '
'; +print ''; +print ''; +print $form::selectarray('comparator', $comparators); +print ''; +print ''; +print ''; +print $form::selectarray('time_range', $range); +print ''; +print ''; +print '
'.$langs->trans('AccidentsLinked').''; + $fieldLinkedAccidents .= $linkedAccidentList; + $fieldLinkedAccidents .= '
' . $langs->trans('TotalConsumedTime') . '' . convertSecondToTime($totatconsumedtime, 'allhourmin') . '
' . $langs->trans('TotalConsumedTimeAmount') . '' . price($totatconsumedtimeamount, 0, $langs, 1, -1, 2, $conf->currency) . '
' . $langs->trans('NbTasks') . '' . $nbtasks . '
' . $langs->trans('TotalProgress') . '' . (($totalprogress) ? price2num($totalprogress/$nbtasks, 2) . ' %' : '0 %') . '
' . $langs->trans('TotalBudget') . '' . price($totaltasksbudget, 0, $langs, 1, -1, 2, $conf->currency) . '
' . $langs->trans('TotalConsumedTime') . '' . convertSecondToTime($totalConsumedTime, 'allhourmin') . '
' . $langs->trans('TotalConsumedTimeAmount') . '' . price($totatConsumedTimeAmount, 0, $langs, 1, -1, 2, $conf->currency) . '
' . $langs->trans('NbTasks') . '' . $nbTasks . '
' . $langs->trans('TotalProgress') . '' . (($totalProgress) ? price2num($totalProgress/$nbTasks, 2) . ' %' : '0 %') . '
' . $langs->trans('TotalBudget') . '' . price($totalTasksBudget, 0, $langs, 1, -1, 2, $conf->currency) . '
'; + $out .= ''; + $out .= ''; + $out .= '
'; + $out .= $langs->trans("Add". ucfirst($type) . "IntoCategory") . ' '; + $out .= $form->selectarray('element_id', $array, '', 1); + $out .= '
'; + $out .= ''; + + $out .= '
'; + + //$param = '&limit=' . $limit . '&id=' . $id . '&type=' . $type; + //$num = count($objectsInCateg); + //print_barre_liste($langs->trans(ucfirst($type)), $page, $_SERVER["PHP_SELF"], $param, '', '', '', $num, '', 'object_'.$type.'@digiquali', 0, '', '', $limit); + + $out .= load_fiche_titre($langs->transnoentities($classname), '', 'object_' . $object->picto); + $out .= ''; + $out .= ''; + + if (is_array($objectsInCateg) && !empty($objectsInCateg)) { + // Form to add record into a category + if (count($objectsInCateg) > 0) { + $i = 0; + foreach ($objectsInCateg as $element) { + $i++; + if ($i > $limit) break; + + $out .= ''; + $out .= ''; + // Link to delete from category + $out .= ''; + $out .= ''; + } + } else { + $out .= ''; + } + } + + $out .= '
'.$langs->trans("Ref").'
'; + $out .= $element->getNomUrl(1); + $out .= ''; + if ($user->rights->categorie->creer) { + $out .= ''; + $out .= $langs->trans("DeleteFromCat"); + $out .= img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); + $out .= ''; + } + $out .= '
'.$langs->trans("ThisCategoryHasNoItems").'
'; + } ?> + + + results = array('myreturn' => 999); @@ -460,8 +610,9 @@ public function printCommonFooter($parameters) */ public function doActions($parameters, $object, $action) { - global $db, $conf; + global $conf, $db; + $error = 0; /* print_r($parameters); print_r($object); echo "action: " . $action; */ if ($parameters['currentcontext'] == 'admincompany') { // do something only for the context 'somecontext1' or 'somecontext2' if ($action == 'update') { @@ -546,15 +697,47 @@ public function doActions($parameters, $object, $action) } } } - } - + } elseif (preg_match('/categorycard/', $parameters['context'])) { + global $langs, $user; + $id = GETPOST('id'); + $elementId = GETPOST('element_id'); + $type = GETPOST('type'); + if ($id > 0 && $elementId > 0 && ($type == 'accident' && $user->rights->digiriskdolibarr->$type->write)) { + + require_once __DIR__ . '/' . $type . '.class.php'; + $classname = ucfirst($type); + $newobject = new $classname($this->db); + + $newobject->fetch($elementId); + + if (GETPOST('action') == 'addintocategory') { + $result = $object->add_type($newobject, $type); + if ($result >= 0) { + setEventMessages($langs->trans("WasAddedSuccessfully", $newobject->ref), array()); + + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->trans("ObjectAlreadyLinkedToCategory"), array(), 'warnings'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } elseif (GETPOST('action') == 'delintocategory') { + $result = $object->del_type($newobject, $type); + if ($result < 0) { + dol_print_error('', $object->error); + } + $action = ''; + } + } + } if (!$error) { $this->results = array('myreturn' => 999); $this->resprints = 'A text to show'; return 0; // or return 1 to replace standard code } else { - $this->errors = $errors; - return -1; + $this->errors[] = 'Error message'; + return -1; } } @@ -571,14 +754,14 @@ public function emailElementlist($parameters) $value = array(); /* print_r($parameters); print_r($object); echo "action: " . $action; */ - if ($parameters['currentcontext'] == 'emailtemplates') { // do something only for the context 'somecontext1' or 'somecontext2' - if ($conf->digiriskdolibarr->enabled && $user->rights->digiriskdolibarr->preventionplan->read) { + if (isModEnabled('digiriskdolibarr') && $parameters['currentcontext'] == 'emailtemplates') { // do something only for the context 'somecontext1' or 'somecontext2' + if ($user->hasRight('digiriskdolibarr', 'preventionplan', 'read')) { $value['preventionplan'] = ' ' . dol_escape_htmltag($langs->trans('PreventionPlan')); } - if ($conf->digiriskdolibarr->enabled && $user->rights->digiriskdolibarr->firepermit->read) { + if ($user->hasRight('digiriskdolibarr', 'firepermit', 'read')) { $value['firepermit'] = ' ' . dol_escape_htmltag($langs->trans('FirePermit')); } - if ($conf->digiriskdolibarr->enabled && $user->rights->digiriskdolibarr->riskassessmentdocument->read) { + if ($user->hasRight('digiriskdolibarr', 'riskassessmentdocument', 'read')) { $value['riskassessmentdocument'] = ' ' . dol_escape_htmltag($langs->trans('RiskAssessmentDocument')); } } @@ -898,6 +1081,10 @@ public function SaturneAdminDocumentData(array $parameters): int 'documentType' => 'informationssharing', 'picto' => 'fontawesome_fa-comment-dots_fas_#d35968' ], + 'RegisterDocument' => [ + 'documentType' => 'registerdocument', + 'picto' => 'fontawesome_fa-ticket-alt_fas_#d35968' + ], 'ListingRisksAction' => [ 'documentType' => 'listingrisksaction', 'picto' => 'fontawesome_fa-images_fas_#d35968' @@ -1016,4 +1203,19 @@ public function saturneBannerTabCustomSubdir(array $parameters, object $object): } return 0; // or return 1 to replace standard code. } + + /** + * Add new actions buttons on CommonObject + * + * @param CommonObject $object The object to process (third party and product object) + */ + public function addMoreActionsButtons($parameters, &$object, &$action) + { + global $langs, $user; + + if ($parameters['currentcontext'] == 'ticketcard') { + print dolGetButtonAction('', img_picto('NewAccident', 'fa-user-injured') . ' ' . $langs->trans('NewAccident'), 'default', dol_buildpath('/digiriskdolibarr/view/accident/accident_card.php?action=create&fk_ticket=' . $object->id, 1), '', $user->rights->digiriskdolibarr->accident->write); + } + + } } diff --git a/class/digiriskdolibarrdocuments/registerdocument.class.php b/class/digiriskdolibarrdocuments/registerdocument.class.php new file mode 100644 index 000000000..7de890856 --- /dev/null +++ b/class/digiriskdolibarrdocuments/registerdocument.class.php @@ -0,0 +1,163 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file class/digiriskdocuments/registerdocument.class.php + * \ingroup digiriskdolibarr + * \brief This file is a class file for RegisterDocument + */ + +// Load DigiriskDolibarr libraries +require_once __DIR__ . '/../digiriskdocuments.class.php'; + +/** + * Class for RegisterDocument + */ +class RegisterDocument extends DigiriskDocuments +{ + /** + * @var string Module name. + */ + public $module = 'digiriskdolibarr'; + + /** + * @var string Element type of object. + */ + public $element = 'registerdocument'; + + /** + * Constructor. + * + * @param DoliDb $db Database handler. + */ + public function __construct(DoliDB $db) + { + parent::__construct($db, $this->module, $this->element); + } + + /** + * Function for JSON filling before saving in database + * + * @return false|string + * @throws Exception + */ + public function RegisterDocumentFillJSON() + { + global $conf; + + $resources = new DigiriskResources($this->db); + $digirisk_resources = $resources->fetchDigiriskResources(); + $json = array(); + + // *** JSON FILLING *** + if (!empty ($digirisk_resources)) { + $labour_doctor_contact = new Contact($this->db); + $result = $labour_doctor_contact->fetch($digirisk_resources['LabourDoctorContact']->id[0]); + if ($result > 0) { + $json['RegisterDocument']['occupational_health_service']['id'] = $labour_doctor_contact->id; + $json['RegisterDocument']['occupational_health_service']['name'] = $labour_doctor_contact->firstname . " " . $labour_doctor_contact->lastname; + $json['RegisterDocument']['occupational_health_service']['phone'] = $labour_doctor_contact->phone_pro; + } + + $labourInspectorContact = new Contact($this->db); + $result = $labourInspectorContact->fetch($digirisk_resources['LabourInspectorContact']->id[0]); + + if ($result > 0) { + $json['RegisterDocument']['detective_work']['id'] = $labourInspectorContact->id; + $json['RegisterDocument']['detective_work']['name'] = $labourInspectorContact->firstname . " " . $labourInspectorContact->lastname; + $json['RegisterDocument']['detective_work']['phone'] = $labourInspectorContact->phone_pro; + } + + $harassment_officer = new User($this->db); + $result = $harassment_officer->fetch($digirisk_resources['HarassmentOfficer']->id[0]); + + if ($result > 0) { + $json['RegisterDocument']['harassment_officer']['id'] = $harassment_officer->id; + $json['RegisterDocument']['harassment_officer']['name'] = $harassment_officer->getFullName($langs); + $json['RegisterDocument']['harassment_officer']['phone'] = $harassment_officer->office_phone; + } + + $harassment_officer_cse = new User($this->db); + $result = $harassment_officer_cse->fetch($digirisk_resources['HarassmentOfficerCSE']->id[0]); + + if ($result > 0) { + $json['RegisterDocument']['harassment_officer_cse']['id'] = $harassment_officer_cse->id; + $json['RegisterDocument']['harassment_officer_cse']['name'] = $harassment_officer_cse->getFullName($langs); + $json['RegisterDocument']['harassment_officer_cse']['phone'] = $harassment_officer_cse->office_phone; + } + + $json['RegisterDocument']['delegues_du_personnels_date'] = (dol_strlen($conf->global->DIGIRISKDOLIBARR_DP_ELECTION_DATE) > 0 && $conf->global->DIGIRISKDOLIBARR_DP_ELECTION_DATE != '--' ? $conf->global->DIGIRISKDOLIBARR_DP_ELECTION_DATE : ''); + $json['RegisterDocument']['delegues_du_personnels_titulaires'] = ''; + if (!empty ($digirisk_resources['TitularsDP']->id )) { + foreach ($digirisk_resources['TitularsDP']->id as $dp_titular) { + + $dp_titulars = new User($this->db); + $result = $dp_titulars->fetch($dp_titular); + if ($result > 0) { + $json['RegisterDocument']['delegues_du_personnels_titulaires'] .= $dp_titulars->firstname . " " . $dp_titulars->lastname . '
'; + $json['RegisterDocument']['delegues_du_personnels_titulairesFullName'] .= $dp_titulars->getNomUrl(1) . '
'; + } + } + } + + $json['RegisterDocument']['delegues_du_personnels_suppleants'] = ''; + if (!empty ($digirisk_resources['AlternatesDP']->id )) { + foreach ($digirisk_resources['AlternatesDP']->id as $dp_alternate) { + + $dp_alternates = new User($this->db); + $result = $dp_alternates->fetch($dp_alternate); + if ($result > 0) { + $json['RegisterDocument']['delegues_du_personnels_suppleants'] .= $dp_alternates->firstname . " " . $dp_alternates->lastname . '
'; + $json['RegisterDocument']['delegues_du_personnels_suppleantsFullName'] .= $dp_alternates->getNomUrl(1) . '
'; + } + } + } + + // CSE + $json['RegisterDocument']['membres_du_comite_entreprise_date'] = (dol_strlen($conf->global->DIGIRISKDOLIBARR_CSE_ELECTION_DATE) > 0 && $conf->global->DIGIRISKDOLIBARR_CSE_ELECTION_DATE != '--' ? $conf->global->DIGIRISKDOLIBARR_CSE_ELECTION_DATE : ''); + $json['RegisterDocument']['membres_du_comite_entreprise_titulaires'] = ''; + if (!empty ($digirisk_resources['TitularsCSE']->id )) { + foreach ($digirisk_resources['TitularsCSE']->id as $cse_titular) { + $cse_titulars = new User($this->db); + $result = $cse_titulars->fetch($cse_titular); + if ($result > 0) { + $json['RegisterDocument']['membres_du_comite_entreprise_titulaires'] .= $cse_titulars->firstname . " " . $cse_titulars->lastname . '
'; + $json['RegisterDocument']['membres_du_comite_entreprise_titulairesFullName'] .= $cse_titulars->getNomUrl(1) . '
'; + } + } + } + + $json['RegisterDocument']['membres_du_comite_entreprise_suppleants'] = ''; + if (!empty ($digirisk_resources['AlternatesCSE']->id )) { + foreach ($digirisk_resources['AlternatesCSE']->id as $cse_alternate) { + $cse_alternates = new User($this->db); + $result = $cse_alternates->fetch($cse_alternate); + if ($result > 0) { + $json['RegisterDocument']['membres_du_comite_entreprise_suppleants'] .= $cse_alternates->firstname . " " . $cse_alternates->lastname . '
'; + $json['RegisterDocument']['membres_du_comite_entreprise_suppleantsFullName'] .= $cse_alternates->getNomUrl(1) . '
'; + } + } + } + + $json = json_encode($json, JSON_UNESCAPED_UNICODE); + return $json; + } + else { + return -1; + } + } +} diff --git a/class/digiriskelement.class.php b/class/digiriskelement.class.php index ae44dabb8..70eaf7265 100644 --- a/class/digiriskelement.class.php +++ b/class/digiriskelement.class.php @@ -251,14 +251,17 @@ public function setCategories($categories) */ public function selectDigiriskElementList($selected = '', $htmlname = 'fk_element', $filter = [], $showempty = '1', $forcecombo = 0, $events = array(), $outputmode = 0, $limit = 0, $morecss = 'minwidth100', $current_element = 0, $multiple = false, $noroot = 0, $contextpage = '', $multientitymanaged = true, $hideref = false) { - global $form; + global $conf, $form, $langs; if (dol_strlen($filter['customsql'])) { $filter['customsql'] .= ' AND t.rowid != ' . ($this->id ?? 0); } - $objectList = saturne_fetch_all_object_type('digiriskelement', '', '', $limit, 0, $filter, 'AND', false, $multientitymanaged); - $digiriskElementsData = []; + $objectList = saturne_fetch_all_object_type('digiriskelement', '', '', $limit, 0, $filter, 'AND', false, $multientitymanaged); + $digiriskElementsData = []; + if ($noroot == 0) { + $digiriskElementsData[0] = $langs->trans('Root') . ' : ' . $conf->global->MAIN_INFO_SOCIETE_NOM ; + } if (is_array($objectList) && !empty($objectList)) { foreach ($objectList as $digiriskElement) { $digiriskElementsData[$digiriskElement->id] = ($hideref ? '' : $digiriskElement->ref . ' - ') . $digiriskElement->label; diff --git a/class/firepermit.class.php b/class/firepermit.class.php index ae5e819f1..276bbe067 100644 --- a/class/firepermit.class.php +++ b/class/firepermit.class.php @@ -289,14 +289,16 @@ public function LibStatut($status, $mode = 0): string global $langs; $langs->load("digiriskdolibarr@digiriskdolibarr"); - $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('InProgress'); + $this->labelStatus[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); + $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('InProgress'); $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('ValidatePendingSignature'); $this->labelStatus[self::STATUS_LOCKED] = $langs->trans('Locked'); $this->labelStatus[self::STATUS_ARCHIVED] = $langs->trans('Archived'); } $statusType = 'status' . $status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status3'; + if ($status == self::STATUS_DELETED) $statusType = 'status9'; + if ($status == self::STATUS_VALIDATED) $statusType = 'status3'; if ($status == self::STATUS_LOCKED) $statusType = 'status8'; if ($status == self::STATUS_ARCHIVED) $statusType = 'status8'; diff --git a/class/preventionplan.class.php b/class/preventionplan.class.php index 6a83518c1..78a4ba8ed 100644 --- a/class/preventionplan.class.php +++ b/class/preventionplan.class.php @@ -290,14 +290,16 @@ public function LibStatut($status, $mode = 0): string global $langs; $langs->load("digiriskdolibarr@digiriskdolibarr"); - $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('InProgress'); + $this->labelStatus[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); + $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('InProgress'); $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('ValidatePendingSignature'); $this->labelStatus[self::STATUS_LOCKED] = $langs->trans('Locked'); $this->labelStatus[self::STATUS_ARCHIVED] = $langs->trans('Archived'); } $statusType = 'status' . $status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status3'; + if ($status == self::STATUS_DELETED) $statusType = 'status9'; + if ($status == self::STATUS_VALIDATED) $statusType = 'status3'; if ($status == self::STATUS_LOCKED) $statusType = 'status8'; if ($status == self::STATUS_ARCHIVED) $statusType = 'status8'; diff --git a/class/riskanalysis/risk.class.php b/class/riskanalysis/risk.class.php index a9cb60a89..4ba9e8847 100644 --- a/class/riskanalysis/risk.class.php +++ b/class/riskanalysis/risk.class.php @@ -491,7 +491,7 @@ public function getRelatedTasks($risk) public function getTasksWithFkRisk() { $sql = "SELECT * FROM " . MAIN_DB_PREFIX . 'projet_task_extrafields' . ' WHERE fk_risk > 0'; - $tasksList = saturne_fetch_all_object_type('SaturneTask'); + $tasksList = saturne_fetch_all_object_type('SaturneTask', '', '', 0, 0, [], 'AND', false, false); $resql = $this->db->query($sql); diff --git a/class/ticketdigiriskstats.class.php b/class/ticketdigiriskstats.class.php index 987516c3e..ce901df07 100644 --- a/class/ticketdigiriskstats.class.php +++ b/class/ticketdigiriskstats.class.php @@ -27,6 +27,7 @@ require_once __DIR__ . '/digiriskstats.php'; require_once __DIR__ . '/digiriskelement.class.php'; +require_once __DIR__ . '/accident.class.php'; /** * Class to manage stats for tickets @@ -151,66 +152,148 @@ public function getAllByYear() return $this->_getAllByYear($sql); } - /** - * Return nb ticket by GP/UT and Ticket tags - * - * @param int $date_start Timestamp date start - * @param int $date_end Timestamp date end - * - * @return array Array of values - * @throws Exception - */ - public function getNbTicketByDigiriskElementAndTicketTags($date_start = 0, $date_end = 0) { - $digiriskelement = new DigiriskElement($this->db); - $categorie = new Categorie($this->db); - - $digiriskelement_flatlist = $digiriskelement->fetchDigiriskElementFlat(0); - if (is_array($digiriskelement_flatlist) && !empty($digiriskelement_flatlist)) { - foreach ($digiriskelement_flatlist as $digiriskelementobject) { - $digiriskelementlist[$digiriskelementobject['object']->id] = $digiriskelementobject['object']; - } - } + /** + * Return nb ticket by GP/UT and Ticket tags + * + * @param int $date_start Timestamp date start + * @param int $date_end Timestamp date end + * + * @return array Array of values + * @throws Exception + */ + public function getNbTicketByDigiriskElementAndTicketTags($date_start = 0, $date_end = 0) { + global $conf, $langs; - $digiriskelementlist = dol_sort_array($digiriskelementlist, 'ranks'); + $digiriskelement = new DigiriskElement($this->db); + $categorie = new Categorie($this->db); + $accident = new Accident($this->db); + $accidentWorkStop = new AccidentWorkStop($this->db); + $ticket = new Ticket($this->db); - $allCategories = $categorie->get_all_categories('ticket'); - if (is_array($allCategories) && !empty($allCategories)) { - foreach ($allCategories as $category) { - $arrayCats[$category->label] = array( - 'id' => $category->id, - 'name' => $category->label - ); - } - } + $digiriskelement_flatlist = $digiriskelement->fetchDigiriskElementFlat(0); + if (is_array($digiriskelement_flatlist) && !empty($digiriskelement_flatlist)) { + foreach ($digiriskelement_flatlist as $digiriskelementobject) { + $digiriskelementlist[$digiriskelementobject['object']->id] = $digiriskelementobject['object']; + } + } - if (is_array($digiriskelementlist) && !empty($digiriskelementlist)) { - if (is_array($arrayCats) && !empty($arrayCats)) { - if ($date_start > 0 && $date_end > 0) { - $filter = ' AND datec BETWEEN ' . "'" .dol_print_date($date_start, 'dayrfc') . "'" . ' AND ' . "'" . dol_print_date($date_end, 'dayrfc'). "'"; - } - foreach ($digiriskelementlist as $digiriskelement) { - foreach ($arrayCats as $key => $cat) { - $nbticket = 0; - $categorie->fetch($cat['id']); - $alltickets = getObjectsInCategDigirisk($categorie, 'ticket', 0, 0, 0, '', 'ASC', $filter); - if (is_array($alltickets) && !empty($alltickets)) { - foreach ($alltickets as $ticket) { - if (!empty($ticket->array_options['options_digiriskdolibarr_ticket_service']) && $ticket->array_options['options_digiriskdolibarr_ticket_service'] == $digiriskelement->id && $ticket->fk_statut != 9) { - $nbticket++; - } - } - } - $array[$digiriskelement->ref . ' - ' . $digiriskelement->label][html_entity_decode($key, ENT_QUOTES | ENT_HTML5)] = $nbticket; - } - } - } - } + $digiriskelementlist = dol_sort_array($digiriskelementlist, 'ranks'); + $mainCategoryObject = $categorie->rechercher($conf->global->DIGIRISKDOLIBARR_TICKET_MAIN_CATEGORY, '', 'ticket', true); + $allCategories = $mainCategoryObject[0]->get_filles(); - if (!empty($array)) { - return $array; - } else { - return -1; - } - } + $arrayReturn = []; + $ticketCategoriesCounter = []; + + //Creating columns labels + if (is_array($allCategories) && !empty($allCategories)) { + // Main categories + foreach($allCategories as $category) { + $labelsArray['labels'][$category->id] = $category->label; + + $categorie->fetch($category->id); + $alltickets[$category->id] = getObjectsInCategDigirisk($categorie, 'ticket', 0, 0, 0, '', 'ASC', $filter); + + if (is_array($alltickets[$category->id]) && !empty($alltickets[$category->id])) { + $ticketCategoriesCounter[$langs->trans('Register') . ' ' . $category->label] = count($alltickets[$category->id]); + } + + + $mainCategoriesIds[$category->id] = $category->id; + $childrenCategories = $category->get_filles(); + + + // Children categories + if (is_array($childrenCategories) && !empty($childrenCategories)) { + foreach($childrenCategories as $childCategory) { + $labelsArray['labels'][$childCategory->id] = $childCategory->label; + + $categorie->fetch($childCategory->id); + $alltickets[$childCategory->id] = getObjectsInCategDigirisk($categorie, 'ticket', 0, 0, 0, '', 'ASC', $filter); + + // Categories sub ranges + if ($childCategory->label == $langs->trans('AccidentWithDIAT')) { + $accidentWorkStopTimeRangesJson = $conf->global->DIGIRISKDOLIBARR_TICKET_STATISTICS_ACCIDENT_TIME_RANGE; + $accidentWorkStopTimeRanges = json_decode($accidentWorkStopTimeRangesJson, true); + if (is_array($accidentWorkStopTimeRanges) && !empty($accidentWorkStopTimeRanges)) { + foreach($accidentWorkStopTimeRanges as $accidentWorkStopTimeRangeLabel => $accidentWorkStopTimeRange) { + $labelsArray['labels'][$accidentWorkStopTimeRangeLabel] = $accidentWorkStopTimeRange; + } + } + } + } + } + } + $labelsArray['labels']['Total'] = $langs->trans('Total'); + } + + $allAccidentsWithFkTicket = $accident->fetchAll('', '', 0, 0, ['customsql' => 'fk_ticket > 0']); + + if (is_array($digiriskelementlist) && !empty($digiriskelementlist)) { + foreach($digiriskelementlist as $digiriskelement) { + $arrayKey = $digiriskelement->ref . ' - ' . $digiriskelement->label; + if (is_array($labelsArray['labels']) && !empty($labelsArray['labels'])) { + foreach($labelsArray['labels'] as $categoryId => $categoryLabel) { + $arrayReturn[$arrayKey][$categoryId] = 0; + + if (is_int($categoryId)) { + if (is_array($alltickets[$categoryId]) && !empty($alltickets[$categoryId])) { + foreach($alltickets[$categoryId] as $ticketsWithThisCategory) { + if ($ticketsWithThisCategory->array_options['options_digiriskdolibarr_ticket_service'] == $digiriskelement->id) { + $arrayReturn[$arrayKey][$categoryId] += 1; + } + } + } + } else if (strstr($categoryLabel, ':')) { + $accidentWorkStopTimeRangeDetails = explode(':', $categoryLabel); + $constraintMultiplicator = $accidentWorkStopTimeRangeDetails[2] == 'days' ? 1 : ($accidentWorkStopTimeRangeDetails[2] == 'years' ? 365 : 21); + $constraintInDays = $accidentWorkStopTimeRangeDetails[1]; + $constraintComparator = $accidentWorkStopTimeRangeDetails[0] == 'less' ? '<' : '>'; + + // Find accidents with filter and add it to counter + if (is_array($allAccidentsWithFkTicket) && !empty($allAccidentsWithFkTicket)) { + foreach($allAccidentsWithFkTicket as $accidentWithFkTicket) { + $ticket->fetch($accidentWithFkTicket->fk_ticket); + if ($ticket->array_options['options_digiriskdolibarr_ticket_service'] == $digiriskelement->id) { + $accidentWorkStopList = $accidentWorkStop->fetchFromParent($accidentWithFkTicket->id); + $accidentWorkStopDaysCounter = 0; + if (is_array($accidentWorkStopList) && !empty($accidentWorkStopList)) { + foreach ($accidentWorkStopList as $accidentWorkStop) { + $accidentWorkStopDaysCounter += $accidentWorkStop->workstop_days; + } + } + + // Turn constraint assertion (less:2:days) into executable logical condition + $condition = "\$result = \$accidentWorkStopDaysCounter $constraintComparator \$constraintInDays*$constraintMultiplicator;"; + eval($condition); + + if ($result) { + $arrayReturn[$arrayKey][$categoryId] += 1; + } + } + } + } + } + } + } + // Total for given digirisk element + foreach($arrayReturn[$arrayKey] as $digiriskElementCategoryId => $digiriskElementCategoriesCounter) { + if (in_array($digiriskElementCategoryId, $mainCategoriesIds)) { + $arrayReturn[$arrayKey]['Total'] += $digiriskElementCategoriesCounter; + } + } + } + } + + foreach($arrayReturn as $data) { + foreach($data as $categoryId => $categoryCounter) { + $totalArray['Total'][$categoryId] += $categoryCounter; + } + } + + // Array replace instead of array merge to avoid losing keys + $arrayReturn = array_replace($labelsArray, $arrayReturn, $totalArray); + + return [$arrayReturn, $ticketCategoriesCounter]; + } } diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/accidentinvestigationdocument/doc_accidentinvestigationdocument_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/accidentinvestigationdocument/doc_accidentinvestigationdocument_odt.modules.php index ee0a43050..f47928bc4 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/accidentinvestigationdocument/doc_accidentinvestigationdocument_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/accidentinvestigationdocument/doc_accidentinvestigationdocument_odt.modules.php @@ -202,13 +202,12 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $object = $moreParam['object']; $accident = new Accident($this->db); $accidentMetadata = new AccidentMetaData($this->db); - $victim = new User($this->db); $signatory = new SaturneSignature($this->db, $this->module, $object->element); $now = dol_now(); $accident->fetch($object->fk_accident); $accidentMetadata->fetch(0, '', 'AND status = 1 AND fk_accident = ' . $accident->id); - $victim->fetch($accident->fk_user_victim); + $victim = $accident->getUserVictim(); $actionTask = saturne_fetch_all_object_type('SaturneTask', '', '', 2, 0, ['customsql' => 'fk_task_parent = ' . $object->fk_task]); $curativeActionTask = array_shift($actionTask); diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/firepermitdocument/doc_firepermitdocument_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/firepermitdocument/doc_firepermitdocument_odt.modules.php index c35061e5d..b6e7073d0 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/firepermitdocument/doc_firepermitdocument_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/firepermitdocument/doc_firepermitdocument_odt.modules.php @@ -303,9 +303,10 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $objectDocument->DigiriskFillJSON(); - $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; + $previousObjectDocumentElement = $objectDocument->element; + $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; complete_substitutions_array($tmpArray, $outputLangs, $objectDocument); - $objectDocument->element = $objectDocument->element; + $objectDocument->element = $previousObjectDocumentElement; $arrayData = json_decode($objectDocument->json); $arrayData = (array) $arrayData->FirePermit; diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/informationssharing/doc_informationssharing_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/informationssharing/doc_informationssharing_odt.modules.php index 5be8ef24f..4c5c71442 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/informationssharing/doc_informationssharing_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/informationssharing/doc_informationssharing_odt.modules.php @@ -95,9 +95,10 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $objectDocument->DigiriskFillJSON(); - $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; - complete_substitutions_array($tmpArray, $outputLangs, $objectDocument); - $objectDocument->element = $objectDocument->element; + $previousObjectDocumentElement = $objectDocument->element; + $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; + complete_substitutions_array($tmpArray, $outputLangs, $objectDocument); + $objectDocument->element = $previousObjectDocumentElement; $moreParam['tmparray'] = $tmpArray; $moreParam['subDir'] = 'digiriskdolibarrdocuments/'; diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/legaldisplay/doc_legaldisplay_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/legaldisplay/doc_legaldisplay_odt.modules.php index 8d7cdf138..93c19574d 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/legaldisplay/doc_legaldisplay_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/legaldisplay/doc_legaldisplay_odt.modules.php @@ -97,9 +97,10 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $objectDocument->DigiriskFillJSON(); - $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; - complete_substitutions_array($tmpArray, $outputLangs, $objectDocument); - $objectDocument->element = $objectDocument->element; + $previousObjectDocumentElement = $objectDocument->element; + $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; + complete_substitutions_array($tmpArray, $outputLangs, $objectDocument); + $objectDocument->element = $previousObjectDocumentElement; $moreParam['tmparray'] = $tmpArray; $moreParam['subDir'] = 'digiriskdolibarrdocuments/'; diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/preventionplandocument/doc_preventionplandocument_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/preventionplandocument/doc_preventionplandocument_odt.modules.php index 497ca37d6..be61bb0c5 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/preventionplandocument/doc_preventionplandocument_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/preventionplandocument/doc_preventionplandocument_odt.modules.php @@ -274,9 +274,10 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $objectDocument->DigiriskFillJSON(); - $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; + $previousObjectDocumentElement = $objectDocument->element; + $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; complete_substitutions_array($tmpArray, $outputLangs, $objectDocument); - $objectDocument->element = $objectDocument->element; + $objectDocument->element = $previousObjectDocumentElement; $arrayData = json_decode($objectDocument->json); $arrayData = (array) $arrayData->PreventionPlan; diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/projectdocument/pdf_orque_projectdocument.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/projectdocument/pdf_orque_projectdocument.modules.php index 9bda0ac6a..91ecb34b0 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/projectdocument/pdf_orque_projectdocument.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/projectdocument/pdf_orque_projectdocument.modules.php @@ -670,7 +670,7 @@ protected function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $ $pdf->MultiCell($this->posxlabel - $this->posxriskassessment, 3, $outputlangs->transnoentities('RiskAssessment'), '', 'L'); $pdf->SetXY($this->posxlabel, $tab_top + 1); - $pdf->MultiCell($this->posxbudget - $this->posxlabel, 3, $outputlangs->transnoentities('Description'), 0, 'L'); + $pdf->MultiCell($this->posxbudget - $this->posxlabel, 3, $outputlangs->transnoentities('Label'), 0, 'L'); $pdf->SetXY($this->posxbudget, $tab_top + 1); $pdf->MultiCell($this->posxworkload - $this->posxbudget, 3, $outputlangs->transnoentities('Budget'), 0, 'R'); diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/doc_registerdocument_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/doc_registerdocument_odt.modules.php new file mode 100644 index 000000000..edc47a979 --- /dev/null +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/doc_registerdocument_odt.modules.php @@ -0,0 +1,376 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see https://www.gnu.org/ + */ + +/** + * \file core/modules/digiriskdolibarr/digiriskdocuments/registerdocument/doc_registerdocument_odt.modules.php + * \ingroup digiriskdolibarr + * \brief File of class to build ODT documents for digiriskdolibarr + */ + +require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/doc.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php'; + +// Load DigiriskDolibarr libraries +require_once __DIR__ . '/../../../../../class/accident.class.php'; +require_once __DIR__ . '/../../../../../class/evaluator.class.php'; +require_once __DIR__ . '/../../../../../class/digiriskelement.class.php'; + +// Load saturne libraries +require_once __DIR__ . '/../../../../../../saturne/core/modules/saturne/modules_saturne.php'; +require_once __DIR__ . '/../../../../../../saturne/class/saturnesignature.class.php'; + +/** + * Class to build documents using ODF templates generator + */ +class doc_registerdocument_odt extends SaturneDocumentModel +{ + /** + * @var array Minimum version of PHP required by module. + * e.g.: PHP ≥ 5.5 = array(5, 5) + */ + public $phpmin = [7, 4]; + + /** + * @var string Dolibarr version of the loaded document. + */ + public string $version = 'dolibarr'; + + /** + * @var string Module. + */ + public string $module = 'digiriskdolibarr'; + + /** + * @var string Document type. + */ + public string $document_type = 'registerdocument'; + + /** + * Constructor. + * + * @param DoliDB $db Database handler. + */ + public function __construct(DoliDB $db) + { + parent::__construct($db, $this->module, $this->document_type); + } + + /** + * Return description of a module. + * + * @param Translate $langs Lang object to use for output. + * @return string Description. + */ + public function info(Translate $langs): string + { + return parent::info($langs); + } + + + /** + * Fill all odt tags for segments lines. + * + * @param Odf $odfHandler Object builder odf library. + * @param Translate $outputLangs Lang object to use for output. + * @param array $moreParam More param (Object/user/etc). + * + * @return int 1 if OK, <=0 if KO. + * @throws Exception + */ + public function fillTagsLines(Odf $odfHandler, Translate $outputLangs, array $moreParam): int + { + global $conf, $moduleNameLowerCase, $langs; + + $ticket = new Ticket($this->db); + $accident = new Accident($this->db); + $digiriskElement = new DigiriskElement($this->db); + $accidentLesion = new AccidentLesion($this->db); + $accidentMetaData = new AccidentMetaData($this->db); + $userTmp = new User($this->db); + $thirdparty = new Societe($this->db); + $signatory = new SaturneSignature($this->db); + + // Replace tags of lines. + try { + $accidentList = $accident->fetchAll('', '', 0, 0, ['customsql' => 'fk_ticket > 0']); + $tempDir = $conf->$moduleNameLowerCase->multidir_output[$conf->entity ?? 1] . '/temp/'; + + $accidentTicketIds = ''; + + if (is_array($accidentList) && !empty($accidentList)) { + foreach ($accidentList as $accidentSingle) { + $accidentTicketIds .= $accidentSingle->fk_ticket . ', '; + } + $accidentTicketIds = rtrim($accidentTicketIds, ', '); + } + + // Get register first tab data. + $foundTagForLines = 1; + try { + $listLines = $odfHandler->setSegment('registers'); + } catch (OdfException $e) { + // We may arrive here if tags for lines not present into template. + $foundTagForLines = 0; + $listLines = ''; + dol_syslog($e->getMessage()); + } + + if ($foundTagForLines) { + if (is_array($accidentList) && !empty($accidentList)) { + foreach($accidentList as $accidentSingle) { + $ticket->fetch($accidentSingle->fk_ticket); + $digiriskElement->fetch($ticket->array_options['options_digiriskdolibarr_ticket_service']); + $accidentLesions = $accidentLesion->fetchAll('', '', 0, 0, ['customsql' => 't.fk_accident = ' . $accidentSingle->id]); + $accidentMetaData->fetch(0, '', ' AND fk_accident = ' . $accidentSingle->id . ' AND status = 1'); + $userTmp->fetch($accidentMetaData->fk_user_witness); + $thirdparty->fetch($accidentMetaData->fk_soc_responsible); + + $tmpArray['register_name'] = $ticket->ref; + $tmpArray['register_date'] = dol_print_date($ticket->datec, 'day'); + $tmpArray['register_fullname'] = $ticket->array_options['options_digiriskdolibarr_ticket_lastname'] . ' ' . $ticket->array_options['options_digiriskdolibarr_ticket_firstname']; + $tmpArray['register_datehour'] = dol_print_date($ticket->array_options['options_digiriskdolibarr_ticket_date'], 'day'); + $tmpArray['register_location'] = $digiriskElement->ref . ' ' . $digiriskElement->label; + $tmpArray['register_circumstances'] = $accidentSingle->description; + + $lesionNatures = ''; + $lesionLocation = ''; + if (is_array($accidentLesions) && !empty($accidentLesions)) { + foreach ($accidentLesions as $accidentLinkedLesion) { + $lesionNatures .= $langs->trans($accidentLinkedLesion->lesion_nature) . ' ,'; + $lesionLocation .= $langs->trans($accidentLinkedLesion->lesion_localization) . ' ,'; + } + } + $tmpArray['register_lesion_location'] = rtrim($lesionLocation, ','); + $tmpArray['register_lesion_nature'] = rtrim($lesionNatures, ','); + + $this->setTmpArrayVars($tmpArray, $listLines, $outputLangs); + + } + } + $odfHandler->mergeSegment($listLines); + } + + // Get register second tab data. + try { + $listLines = $odfHandler->setSegment('registers2'); + } catch (OdfException $e) { + // We may arrive here if tags for lines not present into template. + $foundTagForLines = 0; + $listLines = ''; + dol_syslog($e->getMessage()); + } + + if ($foundTagForLines) { + if (is_array($accidentList) && !empty($accidentList)) { + foreach ($accidentList as $accidentSingle) { + $ticket->fetch($accidentSingle->fk_ticket); + $tmpArray['register_name'] = $ticket->ref; + $digiriskElement->fetch($ticket->array_options['options_digiriskdolibarr_ticket_service']); + $accidentAttendants = $signatory->fetchSignatory('', $accidentSingle->id, 'accident'); + $accidentMetaData->fetch( + 0, + '', + ' AND fk_accident = ' . $accidentSingle->id . ' AND status = 1' + ); + $userTmp->fetch($accidentMetaData->fk_user_witness); + $thirdparty->fetch($accidentMetaData->fk_soc_responsible); + + $victimArray = $accidentAttendants['Victim']; + $careGiverArray = $accidentAttendants['Caregiver']; + + if (is_array($victimArray) && !empty($victimArray)) { + $victimData = array_shift($victimArray); + $encodedImage = explode(',', $victimData->signature)[1]; + $decodedImage = base64_decode($encodedImage); + file_put_contents($tempDir . 'signature' . $victimData->id . '.png', $decodedImage); + $tmpArray['register_victim_signature'] = $tempDir . 'signature' . $victimData->id . '.png'; + } else { + $tmpArray['register_victim_signature'] = ''; + } + if (is_array($careGiverArray) && !empty($careGiverArray)) { + $careGiverData = array_shift($careGiverArray); + $tmpArray['register_caregiver_fullname'] = dol_strtoupper($careGiverData->lastname) . ' ' . ucfirst($careGiverData->firstname); + $encodedImage = explode(',', $careGiverData->signature)[1]; + $decodedImage = base64_decode($encodedImage); + file_put_contents($tempDir . 'signature' . $careGiverData->id . '.png', $decodedImage); + $tmpArray['register_caregiver_signature'] = $tempDir . 'signature' . $careGiverData->id . '.png'; + } else { + $tmpArray['register_caregiver_fullname'] = ''; + $tmpArray['register_caregiver_signature'] = ''; + } + + $tmpArray['register_witnesses_data'] = $userTmp->getFullName($langs); + $tmpArray['register_external_society_implied'] = $thirdparty->getFullName($langs); + + $tmpArray['register_note'] = $ticket->note_public; + + $this->setTmpArrayVars($tmpArray, $listLines, $outputLangs); + } + } + $odfHandler->mergeSegment($listLines); + } + + // Get register second tab data. + try { + $listLines = $odfHandler->setSegment('caregivers'); + } catch (OdfException $e) { + // We may arrive here if tags for lines not present into template. + $foundTagForLines = 0; + $listLines = ''; + dol_syslog($e->getMessage()); + } + + if ($foundTagForLines) { + if (is_array($accidentList) && !empty($accidentList)) { + foreach($accidentList as $accidentSingle) { + $accidentCaregivers = $signatory->fetchSignatory('Caregiver', $accidentSingle->id, 'accident'); + + if (is_array($accidentCaregivers) && !empty($accidentCaregivers)) { + foreach($accidentCaregivers as $accidentCaregiver) { + $tmpArray['caregiver_id'] = $accidentCaregiver->id; + $tmpArray['caregiver_lastname'] = $accidentCaregiver->lastname; + $tmpArray['caregiver_firstname'] = $accidentCaregiver->firstname; + if ($accidentCaregiver->object_type == 'user') { + $userTmp->fetch($accidentCaregiver->fk_object); + $tmpArray['caregiver_qualification'] = $userTmp->job; + } else { + $tmpArray['caregiver_qualification'] = ''; + } + $encodedImage = explode(',', $accidentCaregiver->signature)[1]; + $decodedImage = base64_decode($encodedImage); + file_put_contents($tempDir . 'signature' . $accidentCaregiver->id . '.png', $decodedImage); + $tmpArray['caregiver_signature'] = $tempDir . 'signature' . $accidentCaregiver->id . '.png'; + + $this->setTmpArrayVars($tmpArray, $listLines, $outputLangs); + } + } else { + $tmpArray['caregiver_id'] = ''; + $tmpArray['caregiver_lastname'] = ''; + $tmpArray['caregiver_firstname'] = ''; + $tmpArray['caregiver_qualification'] = ''; + $tmpArray['caregiver_signature'] = ''; + $this->setTmpArrayVars($tmpArray, $listLines, $outputLangs); + } + } + } else { + $tmpArray['caregiver_id'] = ''; + $tmpArray['caregiver_lastname'] = ''; + $tmpArray['caregiver_firstname'] = ''; + $tmpArray['caregiver_qualification'] = ''; + $tmpArray['caregiver_signature'] = ''; + $this->setTmpArrayVars($tmpArray, $listLines, $outputLangs); + } + $odfHandler->mergeSegment($listLines); + } + + // Get register controllers. + try { + $listLines = $odfHandler->setSegment('controllers'); + } catch (OdfException $e) { + // We may arrive here if tags for lines not present into template. + $foundTagForLines = 0; + $listLines = ''; + dol_syslog($e->getMessage()); + } + + if ($foundTagForLines) { + if (isModEnabled('digiquali')) { + require_once __DIR__ . '/../../../../../../digiquali/class/control.class.php'; + $control = new Control($this->db); + $ticketControls = $control->fetchAllWithLeftJoin('DESC','t.control_date', 0,0, ['customsql' => 't.rowid = je.fk_target AND t.status = ' . $control::STATUS_LOCKED], 'AND', true, 'LEFT JOIN '. MAIN_DB_PREFIX .'element_element as je on je.sourcetype = "ticket" AND je.fk_source IN ('. $accidentTicketIds .') AND je.targettype = "digiquali_control" AND je.fk_target = t.rowid' ); + + if (is_array($ticketControls) && !empty($ticketControls)) { + foreach($ticketControls as $ticketControl) { + $ticketController = $signatory->fetchSignatory('Controller', $ticketControl->id, 'control'); + + if (is_array($ticketController) && !empty($ticketController)) { + $ticketController = array_shift($ticketController); + $tmpArray['register_controller_id'] = $ticketController->id; + $tmpArray['register_controller_lastname'] = $ticketController->lastname; + $tmpArray['register_controller_firstname'] = $ticketController->firstname; + $tmpArray['register_controller_society'] = $conf->global->MAIN_INFO_SOCIETE_NOM; + $tmpArray['register_controller_date'] = dol_print_date($ticketControl->control_date); + $encodedImage = explode(',', $ticketController->signature)[1]; + $decodedImage = base64_decode($encodedImage); + file_put_contents($tempDir . 'signature' . $ticketController->id . '.png', $decodedImage); + $tmpArray['register_controller_signature'] = $tempDir . 'signature' . $ticketController->id . '.png'; + + $tmpArray['register_controller_note'] = $ticketControl->note_public; + + $this->setTmpArrayVars($tmpArray, $listLines, $outputLangs); + } + } + } else { + $tmpArray['register_controller_id'] = ''; + $tmpArray['register_controller_lastname'] = ''; + $tmpArray['register_controller_firstname'] = ''; + $tmpArray['register_controller_society'] = ''; + $tmpArray['register_controller_date'] = ''; + $tmpArray['register_controller_signature'] = ''; + $tmpArray['register_controller_note'] = ''; + $this->setTmpArrayVars($tmpArray, $listLines, $outputLangs); + } + } + $odfHandler->mergeSegment($listLines); + } + + } catch (OdfException $e) { + $this->error = $e->getMessage(); + dol_syslog($this->error, LOG_WARNING); + return -1; + } + return 0; + } + + /** + * Function to build a document on disk. + * + * @param SaturneDocuments $objectDocument Object source to build document. + * @param Translate $outputLangs Lang object to use for output. + * @param string $srcTemplatePath Full path of source filename for generator using a template file. + * @param int $hideDetails Do not show line details. + * @param int $hideDesc Do not show desc. + * @param int $hideRef Do not show ref. + * @param array $moreParam More param (Object/user/etc). + * @return int 1 if OK, <=0 if KO. + * @throws Exception + */ + public function write_file(SaturneDocuments $objectDocument, Translate $outputLangs, string $srcTemplatePath, int $hideDetails = 0, int $hideDesc = 0, int $hideRef = 0, array $moreParam): int + { + global $langs; + + $evaluator = new Evaluator($this->db); + + $tmpArray = []; + $tmpArray['register_name'] = $langs->trans('RegisterDocument'); + + $moreParam['tmparray'] = $tmpArray; + $moreParam['subDir'] = 'digiriskdolibarrdocuments/'; + $moreParam['hideTemplateName'] = 1; + + $arrayNbEmployees = $evaluator->getNbEmployees(); + + $tmpArray['company_nb_employees'] = array_shift($arrayNbEmployees); + + $moreParam['tmparray'] = $tmpArray; + + return parent::write_file($objectDocument, $outputLangs, $srcTemplatePath, $hideDetails, $hideDesc, $hideRef, $moreParam); + } +} diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/index.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/index.php new file mode 100644 index 000000000..cd6990e24 --- /dev/null +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/index.php @@ -0,0 +1,2 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see https://www.gnu.org/ + */ + +/** + * \file core/modules/digiriskdolibarr/digiriskdolibarrdocuments/informationssharing/mod_informationssharing_gridr.php + * \ingroup digiriskdolibarr + * \brief File that contains the numbering module rules gridr + */ + +// Load Saturne libraries +require_once __DIR__ . '/../../../../../../saturne/core/modules/saturne/modules_saturne.php'; + +/** + * Class of file that contains the numbering module rules gridr + */ +class mod_registerdocument_gridr extends CustomModeleNumRefSaturne +{ + /** + * @var string Model name + */ + public string $name = 'Thiazzi'; + + public function __construct() + { + global $conf; + + $refMod = $conf->global->DIGIRISKDOLIBARR_REGISTERDOCUMENT_THIAZZI_ADDON; + if (dol_strlen($refMod)) { + $refModSplitted = preg_split('/\{/', $refMod); + if (is_array($refModSplitted) && !empty($refModSplitted)) { + $suffix = preg_replace('/}/', '', $refModSplitted[1]); + $this->prefix = $refModSplitted[0]; + $this->suffix = $suffix; + } + } + } +} diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/mod_registerdocument_standard.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/mod_registerdocument_standard.php new file mode 100644 index 000000000..f6c58bd12 --- /dev/null +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/registerdocument/mod_registerdocument_standard.php @@ -0,0 +1,41 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see https://www.gnu.org/ + */ + +/** + * \file core/modules/digiriskdolibarr/digiriskdocuments/registerdocument/mod_registerdocument_standard.php + * \ingroup digiriskdolibarr + * \brief File containing class for registerdocument numbering module Standard + */ + +require_once __DIR__ . '/../../../../../../saturne/core/modules/saturne/modules_saturne.php'; + +/** + * Class to manage registerdocument numbering rules Standard + */ +class mod_registerdocument_standard extends ModeleNumRefSaturne +{ + /** + * @var string document prefix + */ + public string $prefix = 'RD'; + + /** + * @var string model name + */ + public string $name = 'Hyrrokkin'; +} diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/riskassessmentdocument/doc_riskassessmentdocument_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/riskassessmentdocument/doc_riskassessmentdocument_odt.modules.php index c3418eb81..e7cfd4c0f 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/riskassessmentdocument/doc_riskassessmentdocument_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/riskassessmentdocument/doc_riskassessmentdocument_odt.modules.php @@ -285,9 +285,10 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $objectDocument->DigiriskFillJSON(); - $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; + $previousObjectDocumentElement = $objectDocument->element; + $objectDocument->element = $objectDocument->element . '@digiriskdolibarr'; complete_substitutions_array($tmpArray, $outputLangs, $objectDocument); - $objectDocument->element = $objectDocument->element; + $objectDocument->element = $previousObjectDocumentElement; $moreParam['tmparray'] = $tmpArray; $moreParam['objectDocument'] = $objectDocument; diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/ticketdocument/doc_ticketdocument_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/ticketdocument/doc_ticketdocument_odt.modules.php index e460348c5..c4ff35eca 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/ticketdocument/doc_ticketdocument_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/ticketdocument/doc_ticketdocument_odt.modules.php @@ -32,6 +32,7 @@ require_once __DIR__ . '/../../../../../class/digiriskelement.class.php'; // Load saturne libraries +require_once __DIR__ . '/../../../../../../saturne/lib/medias.lib.php'; require_once __DIR__ . '/../../../../../../saturne/core/modules/saturne/modules_saturne.php'; /** @@ -138,124 +139,104 @@ public function fillTagsLines(Odf $odfHandler, Translate $outputLangs, array $mo return 0; } - /** - * Function to build a document on disk. - * - * @param SaturneDocuments $objectDocument Object source to build document. - * @param Translate $outputLangs Lang object to use for output. - * @param string $srcTemplatePath Full path of source filename for generator using a template file. - * @param int $hideDetails Do not show line details. - * @param int $hideDesc Do not show desc. - * @param int $hideRef Do not show ref. - * @param array $moreParam More param (Object/user/etc). - * @return int 1 if OK, <=0 if KO. - * @throws Exception - */ - public function write_file(SaturneDocuments $objectDocument, Translate $outputLangs, string $srcTemplatePath, int $hideDetails = 0, int $hideDesc = 0, int $hideRef = 0, array $moreParam): int { - - $ticket = $moreParam['object']; - - $ticket->fetch_optionals(); - $digiriskelement = new DigiriskElement($this->db); - - $tmpArray['ref'] = $ticket->ref; - $tmpArray['lastname'] = $ticket->array_options['options_digiriskdolibarr_ticket_lastname']; - $tmpArray['firstname'] = $ticket->array_options['options_digiriskdolibarr_ticket_firstname']; - $tmpArray['phone_number'] = $ticket->array_options['options_digiriskdolibarr_ticket_phone']; - if ($ticket->array_options['options_digiriskdolibarr_ticket_service'] > 0) { - $digiriskelement->fetch($ticket->array_options['options_digiriskdolibarr_ticket_service']); - $tmpArray['service'] = $digiriskelement->ref . ' - ' . $digiriskelement->label; - } else { - $tmpArray['service'] = ''; - } - $tmpArray['location'] = $ticket->array_options['options_digiriskdolibarr_ticket_location']; - $tmpArray['declaration_date'] = dol_print_date( - $ticket->array_options['options_digiriskdolibarr_ticket_date'], - 'dayhoursec', - 'tzuser' - ); - $tmpArray['creation_date'] = dol_print_date($ticket->date_creation, 'dayhoursec', 'tzuser'); - $tmpArray['close_date'] = dol_print_date($ticket->date_close, 'dayhoursec', 'tzuser'); - $tmpArray['progress'] = !empty($ticket->progress) ? $ticket->progress . ' %' : '0 %'; - - $category = new Categorie($this->db); - $categories = $category->containing($ticket->id, Categorie::TYPE_TICKET); - if (!empty($categories)) { - foreach ($categories as $cat) { - $allcategories[] = $cat->label; - } - $tmpArray['categories'] = implode(', ', $allcategories); - } else { - $tmpArray['categories'] = ''; - } - - $tmpArray['status'] = $ticket->getLibStatut(); - - $user = new User($this->db); - $user->fetch($ticket->fk_user_assign); - $tmpArray['assigned_to'] = $user->firstname . ' ' . $user->lastname; - - - require_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php'; - - $photo_path = $conf->ticket->multidir_output[$conf->entity] . '/' . $ticket->ref; - $filearray = dol_dir_list($photo_path, "files", 0, '', '(\.odt|_preview.*\.png|\.pdf)$', 'date', 'desc', 1); - if ($photo_path) { - $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $photo_path); - $relativedir = preg_replace('/^[\\/]/', '', $relativedir); - } - - if (count($filearray)) { - $filearray = dol_sort_array($filearray, 'position'); - $thumb_name = getThumbName($filearray[0]['name']); - $tmpArray['photo'] = $photo_path . '/thumbs/' . $thumb_name; - } else { - $nophoto = '/public/theme/common/nophoto.png'; - $tmpArray['photo'] = DOL_DOCUMENT_ROOT . $nophoto; - } - - $tmpArray['subject'] = $ticket->subject; - $tmpArray['message'] = dol_htmlentitiesbr_decode(strip_tags($ticket->message, '
')); - $tmpArray['generation_date'] = dol_print_date(dol_now(), 'dayhoursec', 'tzuser'); - - $contactlistexternal = $ticket->liste_contact(-1, 'external'); - $contactlistinternal = $ticket->liste_contact(-1, 'internal'); - - $contactlist = array(); - - if (!empty($contactlistexternal) && is_array($contactlistexternal)) { - $contactlist = array_merge($contactlist, $contactlistexternal); - } - - if (!empty($contactlistinternal) && is_array($contactlistinternal)) { - $contactlist = array_merge($contactlist, $contactlistinternal); - } - - if (!empty($contactlist) && is_array($contactlist)) { - foreach ($contactlist as $contact) { - $tmpArray['contacts'] .= $contact['firstname'] . ' ' . $contact['lastname'] . ', '; - } - } else { - $tmpArray['contacts'] = ''; - } - - $moreParam['tmparray'] = $tmpArray; - $moreParam['objectDocument'] = $objectDocument; - $moreParam['subDir'] = 'digiriskdolibarrdocuments/'; - $moreParam['hideTemplateName'] = 1; - - if (preg_match('/event/', $srcTemplatePath)) { - $moreParam['additionalName'] = '_events'; - } - - return parent::write_file( - $objectDocument, - $outputLangs, - $srcTemplatePath, - $hideDetails, - $hideDesc, - $hideRef, - $moreParam - ); - } + /** + * Function to build a document on disk + * + * @param SaturneDocuments $objectDocument Object source to build document + * @param Translate $outputLangs Lang object to use for output + * @param string $srcTemplatePath Full path of source filename for generator using a template file + * @param int $hideDetails Do not show line details + * @param int $hideDesc Do not show desc + * @param int $hideRef Do not show ref + * @param array $moreParam More param (Object/user/etc) + * @return int 1 if OK, <=0 if KO + * @throws Exception + */ + public function write_file(SaturneDocuments $objectDocument, Translate $outputLangs, string $srcTemplatePath, int $hideDetails = 0, int $hideDesc = 0, int $hideRef = 0, array $moreParam): int + { + global $conf; + + $object = $moreParam['object']; + + $object->fetch_optionals(); + + $digiriskElement = new DigiriskElement($this->db); + $category = new Categorie($this->db); + $userTmp = new User($this->db); + + $tmpArray['ref'] = $object->ref; + $tmpArray['lastname'] = $object->array_options['options_digiriskdolibarr_ticket_lastname']; + $tmpArray['firstname'] = $object->array_options['options_digiriskdolibarr_ticket_firstname']; + $tmpArray['phone_number'] = $object->array_options['options_digiriskdolibarr_ticket_phone']; + if ($object->array_options['options_digiriskdolibarr_ticket_service'] > 0) { + $digiriskElement->fetch($object->array_options['options_digiriskdolibarr_ticket_service']); + $tmpArray['service'] = $digiriskElement->ref . ' - ' . $digiriskElement->label; + } else { + $tmpArray['service'] = ''; + } + $tmpArray['location'] = $object->array_options['options_digiriskdolibarr_ticket_location']; + $tmpArray['declaration_date'] = dol_print_date($object->array_options['options_digiriskdolibarr_ticket_date'],'dayhoursec','tzuser'); + $tmpArray['creation_date'] = dol_print_date($object->date_creation, 'dayhoursec', 'tzuser'); + $tmpArray['close_date'] = dol_print_date($object->date_close, 'dayhoursec', 'tzuser'); + $tmpArray['progress'] = !empty($object->progress) ? $object->progress . ' %' : '0 %'; + + $categories = $category->containing($object->id, Categorie::TYPE_TICKET); + if (!empty($categories)) { + foreach ($categories as $cat) { + $allCategories[] = $cat->label; + } + $tmpArray['categories'] = implode(', ', $allCategories); + } else { + $tmpArray['categories'] = ''; + } + + $tmpArray['status'] = $object->getLibStatut(); + + $userTmp->fetch($object->fk_user_assign); + $tmpArray['assigned_to'] = ucfirst($userTmp->firstname) . ' ' . strtoupper($userTmp->lastname); + + $photoPath = $conf->ticket->multidir_output[$conf->entity] . '/' . $object->ref; + $fileArray = dol_dir_list($photoPath, 'files', 0, '', '(\.odt|_preview.*\.png|\.pdf)$', 'date', 'desc', 1); + if (count($fileArray) && !empty($fileArray)) { + $fileArray = dol_sort_array($fileArray, 'position'); + $thumbName = saturne_get_thumb_name($fileArray[0]['name']); + $tmpArray['photo'] = $photoPath . '/thumbs/' . $thumbName; + } else { + $noPhoto = '/public/theme/common/nophoto.png'; + $tmpArray['photo'] = DOL_DOCUMENT_ROOT . $noPhoto; + } + + $tmpArray['subject'] = $object->subject; + $tmpArray['message'] = dol_htmlentitiesbr_decode(strip_tags($object->message, '
')); + $tmpArray['generation_date'] = dol_print_date(dol_now(), 'dayhoursec', 'tzuser'); + + $contactListExternal = $object->liste_contact(-1, 'external'); + $contactListInternal = $object->liste_contact(-1, 'internal'); + + $contactList = []; + if (!empty($contactListExternal) && is_array($contactListExternal)) { + $contactList = array_merge($contactList, $contactListExternal); + } + if (!empty($contactListInternal) && is_array($contactListInternal)) { + $contactList = array_merge($contactList, $contactListInternal); + } + if (!empty($contactList) && is_array($contactList)) { + foreach ($contactList as $contact) { + $tmpArray['contacts'] .= ucfirst($contact['firstname']) . ' ' . strtoupper($contact['lastname']) . ', '; + } + } else { + $tmpArray['contacts'] = ''; + } + + $moreParam['tmparray'] = $tmpArray; + $moreParam['objectDocument'] = $objectDocument; + $moreParam['subDir'] = 'digiriskdolibarrdocuments/'; + $moreParam['hideTemplateName'] = 1; + + if (preg_match('/event/', $srcTemplatePath)) { + $moreParam['additionalName'] = '_events'; + } + + return parent::write_file($objectDocument, $outputLangs, $srcTemplatePath, $hideDetails, $hideDesc, $hideRef, $moreParam); + } } diff --git a/core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_jarnsaxa.php b/core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_wright.php similarity index 83% rename from core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_jarnsaxa.php rename to core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_wright.php index 2d2af97ab..520c729bb 100644 --- a/core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_jarnsaxa.php +++ b/core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_wright.php @@ -17,29 +17,29 @@ */ /** - * \file core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_jarnsaxa.php + * \file core/modules/digiriskdolibarr/digiriskelement/accidentlesion/mod_accidentlesion_wright.php * \ingroup digiriskdolibarr - * \brief File that contains the numbering module rules jarnsaxa + * \brief File that contains the numbering module rules wright */ // Load Saturne libraries require_once __DIR__ . '/../../../../../../saturne/core/modules/saturne/modules_saturne.php'; /** - * Class of file that contains the numbering module rules jarnsaxa + * Class of file that contains the numbering module rules wright */ -class mod_accidentlesion_jarnsaxa extends CustomModeleNumRefSaturne +class mod_accidentlesion_wright extends CustomModeleNumRefSaturne { /** * @var string Model name */ - public string $name = 'Jarnsaxa'; + public string $name = 'Wright'; public function __construct() { global $conf; - $refMod = $conf->global->DIGIRISKDOLIBARR_ACCIDENTLESION_JARNSAXA_ADDON; + $refMod = $conf->global->DIGIRISKDOLIBARR_ACCIDENTLESION_WRIGHT_ADDON; if (dol_strlen($refMod)) { $refModSplitted = preg_split('/\{/', $refMod); if (is_array($refModSplitted) && !empty($refModSplitted)) { diff --git a/core/modules/modDigiriskDolibarr.class.php b/core/modules/modDigiriskDolibarr.class.php index aade1578b..88ca92329 100644 --- a/core/modules/modDigiriskDolibarr.class.php +++ b/core/modules/modDigiriskDolibarr.class.php @@ -380,7 +380,7 @@ public function __construct($db) $this->descriptionlong = "Digirisk"; $this->editor_name = 'Evarisk'; $this->editor_url = 'https://evarisk.com'; - $this->version = '9.13.0'; + $this->version = '9.14.0'; $this->const_name = 'MAIN_MODULE_' . strtoupper($this->name); $this->picto = 'digiriskdolibarr_color@digiriskdolibarr'; @@ -436,7 +436,9 @@ public function __construct($db) 'digiriskstandardview', 'accidentdocument', 'accidentagenda', - 'digiriskstandardagenda' + 'digiriskstandardagenda', + 'category', + 'categoryindex' ], 'tabs' => [ 'mycompany_admin' @@ -535,7 +537,14 @@ public function __construct($db) $i++ => ['DIGIRISKDOLIBARR_INFORMATIONSSHARING_CUSTOM_ADDON_ODT_PATH', 'chaine', 'DOL_DATA_ROOT' . (($conf->entity == 1 ) ? '/' : '/' . $conf->entity . '/') . 'ecm/digiriskdolibarr/informationssharing/', '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_INFORMATIONSSHARING_DEFAULT_MODEL', 'chaine', 'informationssharing_odt', '', 0, 'current'], - // CONST LISTING RISKS ACTION + // CONST REGISTER DOCUMENT + $i++ => ['DIGIRISKDOLIBARR_MAIN_AGENDA_ACTIONAUTO_REGISTERDOCUMENT_GENERATE', 'integer', 1, '', 0, 'current'], + $i++ => ['DIGIRISKDOLIBARR_REGISTERDOCUMENT_ADDON', 'chaine', 'mod_registerdocument_standard', '', 0, 'current'], + $i++ => ['DIGIRISKDOLIBARR_REGISTERDOCUMENT_ADDON_ODT_PATH', 'chaine', 'DOL_DOCUMENT_ROOT/custom/digiriskdolibarr/documents/doctemplates/registerdocument/', '', 0, 'current'], + $i++ => ['DIGIRISKDOLIBARR_REGISTERDOCUMENT_CUSTOM_ADDON_ODT_PATH', 'chaine', 'DOL_DATA_ROOT' . (($conf->entity == 1 ) ? '/' : '/' . $conf->entity . '/') . 'ecm/digiriskdolibarr/registerdocument/', '', 0, 'current'], + $i++ => ['DIGIRISKDOLIBARR_REGISTERDOCUMENT_DEFAULT_MODEL', 'chaine', 'registerdocument_odt', '', 0, 'current'], + + // CONST LISTING RISKS ACTION $i++ => ['DIGIRISKDOLIBARR_MAIN_AGENDA_ACTIONAUTO_LISTINGRISKSACTION_GENERATE', 'integer', 1, '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_LISTINGRISKSACTION_ADDON', 'chaine', 'mod_listingrisksaction_standard', '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_LISTINGRISKSACTION_ADDON_ODT_PATH', 'chaine', 'DOL_DOCUMENT_ROOT/custom/digiriskdolibarr/documents/doctemplates/listingrisksaction/', '', 0, 'current'], @@ -729,7 +738,8 @@ public function __construct($db) $i++ => ['DIGIRISKDOLIBARR_TICKET_LOCATION_VISIBLE', 'integer', 1, '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_TICKET_LOCATION_REQUIRED', 'integer', 0, '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_TICKET_DATE_VISIBLE', 'integer', 1, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_DATE_REQUIRED', 'integer', 1, '', 0, 'current'], + $i++ => ['DIGIRISKDOLIBARR_TICKET_DATE_REQUIRED', 'integer', 1, '', 0, 'current'], + $i++ => ['DIGIRISKDOLIBARR_TICKET_STATISTICS_ACCIDENT_TIME_RANGE', 'chaine', '{"'. $langs->transnoentities("WithoutWorkStop") .'":"less:1:days", "'. $langs->transnoentities("LessThanFourDays") .'":"less:4:days","'. $langs->transnoentities("LessThanTwentyOneDays") .'":"less:21:days","'. $langs->transnoentities("LessThanThreeMonth") .'":"less:3:months","'. $langs->transnoentities("LessThanSixMonths") .'":"less:6:months","'. $langs->transnoentities("LongTimeWorkStop") .'":"more:6:months"}', '', 0, 'current'], // CONST MODULE $i++ => ['DIGIRISKDOLIBARR_SUBPERMCATEGORY_FOR_DOCUMENTS', 'integer', 1, '', 0, 'current'], @@ -766,22 +776,6 @@ public function __construct($db) $i++ => ['DIGIRISKDOLIBARR_MANUAL_INPUT_NB_WORKED_HOURS', 'integer', 0, '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_SHOW_PATCH_NOTE', 'integer', 1, '', 0, 'current'], - //CONST TICKET & REGISTERS - $i++ => ['DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', 'integer', 0, '', 0, 0], - $i++ => ['DIGIRISKDOLIBARR_TICKET_CATEGORIES_CREATED', 'integer', 0, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_ENABLE_PUBLIC_INTERFACE', 'integer', 1, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_SHOW_COMPANY_LOGO', 'integer', 1, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_SUBMITTED_SEND_MAIL_TO', 'chaine', '', '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_PARENT_CATEGORY', 'integer', 0, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_MAIN_CATEGORY', 'integer', 0, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_PARENT_CATEGORY_LABEL', 'chaine', $langs->trans('Registre'), '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_CHILD_CATEGORY_LABEL', 'chaine', $langs->trans('Pertinence'), '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_PROJECT', 'integer', 0, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_SUCCESS_MESSAGE', 'chaine', $langs->trans('YouMustNotifyYourHierarchy'), '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_EMAIL_REQUIRED', 'integer', 0, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_SHOW_MULTI_ENTITY_SELECTOR_ON_TICKET_PUBLIC_INTERFACE', 'integer', 0, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_TICKET_DIGIRISKELEMENT_REQUIRED', 'integer', 1, '', 0, 'current'], - // CONST ACCIDENT $i++ => ['DIGIRISKDOLIBARR_MAIN_AGENDA_ACTIONAUTO_ACCIDENT_CREATE', 'integer', 1, '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_MAIN_AGENDA_ACTIONAUTO_ACCIDENT_MODIFY', 'integer', 1, '', 0, 'current'], @@ -826,7 +820,6 @@ public function __construct($db) // CONST DIGIRISK DOCUMENTS $i++ => ['DIGIRISKDOLIBARR_DOCUMENT_SHOW_PICTO_NAME', 'integer', 0, '', 0, 'current'], - $i++ => ['DIGIRISKDOLIBARR_DOCUMENT_SHOW_PICTO_NAME', 'integer', 0, '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_AUTOMATIC_PDF_GENERATION', 'integer', 0, '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_MANUAL_PDF_GENERATION', 'integer', 0, '', 0, 'current'], @@ -849,7 +842,7 @@ public function __construct($db) $i => ['DIGIRISKDOLIBARR_CUSTOM_NUM_REF_SET', 'integer', 0, '', 0, 'current'], ]; - if ( ! isset($conf->digiriskdolibarr) || ! isset($conf->digiriskdolibarr->enabled) ) { + if (!isModEnabled('digiriskdolibarr')) { $conf->digiriskdolibarr = new stdClass(); $conf->digiriskdolibarr->enabled = 0; } @@ -862,7 +855,7 @@ public function __construct($db) $this->tabs[] = ['data' => 'mycompany_admin:+social:'. $pictoDigirisk .$langs->trans('Social').':digiriskdolibarr@digiriskdolibarr:1:/custom/digiriskdolibarr/admin/socialconf.php']; // To add a new tab identified by code tabname1 $this->tabs[] = ['data' => 'thirdparty:+schedules:'. $pictoDigirisk .$langs->trans('Schedules').':digiriskdolibarr@digiriskdolibarr:1:/custom/saturne/view/saturne_schedules.php?id=__ID__&element_type=societe&module_name=societe']; // To add a new tab identified by code tabname1 $this->tabs[] = ['data' => 'user:+participation:'. $pictoDigirisk .$langs->trans('GP/UTParticipation').':digiriskdolibarr@digiriskdolibarr:1:/custom/digiriskdolibarr/view/digiriskelement/digiriskelement_evaluator.php?fromid=__ID__']; // To add a new tab identified by code tabname1 - $this->tabs[] = ['data' => 'user:+accidents:'. $pictoDigirisk .$langs->trans('Accidents').':digiriskdolibarr@digiriskdolibarr:1:/custom/digiriskdolibarr/view/accident/accident_list.php?fromiduser=__ID__']; // To add a new tab identified by code tabname1 + $this->tabs[] = ['data' => 'user:+accidents:'. $pictoDigirisk .$langs->trans('Accidents').':digiriskdolibarr@digiriskdolibarr:1:/custom/digiriskdolibarr/view/accident/accident_list.php?fromiduser=__ID__']; // To add a new tab identified by code tabname1 // Dictionaries $this->dictionaries = [ @@ -1058,7 +1051,25 @@ public function __construct($db) $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->digiriskdolibarr->level1->level2) $r++; - /* FIRE PERMIT PERMISSIONS */ + /* REGISTER DOCUMENT PERMISSIONS */ + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); // Permission id (must not be already used) + $this->rights[$r][1] = $langs->transnoentities('ReadObjects',$langs->transnoentities('RegisterDocumentsMin')); // Permission label + $this->rights[$r][4] = 'registerdocument'; // In php code, permission will be checked by test if ($user->rights->digiriskdolibarr->level1->level2) + $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->digiriskdolibarr->level1->level2) + $r++; + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); // Permission id (must not be already used) + $this->rights[$r][1] = $langs->transnoentities('CreateObjects', $langs->transnoentities('RegisterDocumentsMin')); // Permission label + $this->rights[$r][4] = 'registerdocument'; // In php code, permission will be checked by test if ($user->rights->digiriskdolibarr->level1->level2) + $this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->digiriskdolibarr->level1->level2) + $r++; + $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); // Permission id (must not be already used) + $this->rights[$r][1] = $langs->transnoentities('DeleteObjects', $langs->transnoentities('RegisterDocumentsMin')); // Permission label + $this->rights[$r][4] = 'registerdocument'; // In php code, permission will be checked by test if ($user->rights->digiriskdolibarr->level1->level2) + $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->digiriskdolibarr->level1->level2) + $r++; + + + /* FIRE PERMIT PERMISSIONS */ $this->rights[$r][0] = $this->numero . sprintf('%02d', $r + 1); // Permission id (must not be already used) $this->rights[$r][1] = $langs->transnoentities('ReadObjects',$langs->transnoentities('FirePermitsMin')); // Permission label $this->rights[$r][4] = 'firepermit'; // In php code, permission will be checked by test if ($user->rights->digiriskdolibarr->level1->level2) @@ -1363,20 +1374,35 @@ public function __construct($db) 'user' => 0, // 0=Menu for internal users, 1=external users, 2=both ]; - $this->menu[$r++] = [ - 'fk_menu' => 'fk_mainmenu=digiriskdolibarr,fk_leftmenu=digiriskaccident', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode - 'type' => 'left', // This is a Left menu entry - 'titre' => '' . $langs->transnoentities('AccidentInvestigation'), - 'mainmenu' => 'digiriskdolibarr', - 'leftmenu' => 'digiriskaccidentinvestigation', - 'url' => '/digiriskdolibarr/view/accidentinvestigation/accidentinvestigation_list.php', - 'langs' => 'digiriskdolibarr@digiriskdolibarr', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. - 'position' => 100 + $r, - 'enabled' => '$conf->digiriskdolibarr->enabled && $conf->saturne->enabled', // Define condition to show or hide menu entry. Use '$conf->digiriskdolibarr->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. - 'perms' => '$user->rights->digiriskdolibarr->lire && $user->rights->digiriskdolibarr->accidentinvestigation->read', // Use 'perms'=>'$user->rights->digiriskdolibarr->level1->level2' if you want your menu with a permission rules - 'target' => '', - 'user' => 0, // 0=Menu for internal users, 1=external users, 2=both - ]; + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=digiriskdolibarr,fk_leftmenu=digiriskaccident', + 'type' => 'left', + 'titre' => '' . $langs->transnoentities('Categories'), + 'mainmenu' => 'digiriskdolibarr', + 'leftmenu' => 'digiriskdolibarr_accidenttags', + 'url' => '/categories/index.php?type=accident', + 'langs' => 'digiriskdolibarr@digiriskdolibarr', + 'position' => 100 + $r, + 'enabled' => '$conf->digiriskdolibarr->enabled && $conf->categorie->enabled && $user->rights->digiriskdolibarr->accident->read', + 'perms' => '$user->rights->digiriskdolibarr->accident->read', + 'target' => '', + 'user' => 0, + ]; + + $this->menu[$r++] = [ + 'fk_menu' => 'fk_mainmenu=digiriskdolibarr', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'type' => 'left', // This is a Left menu entry + 'titre' => '' . $langs->transnoentities('AccidentInvestigation'), + 'mainmenu' => 'digiriskdolibarr', + 'leftmenu' => 'digiriskaccidentinvestigation', + 'url' => '/digiriskdolibarr/view/accidentinvestigation/accidentinvestigation_list.php', + 'langs' => 'digiriskdolibarr@digiriskdolibarr', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position' => 100 + $r, + 'enabled' => '$conf->digiriskdolibarr->enabled && $conf->saturne->enabled', // Define condition to show or hide menu entry. Use '$conf->digiriskdolibarr->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'perms' => '$user->rights->digiriskdolibarr->lire && $user->rights->digiriskdolibarr->accidentinvestigation->read', // Use 'perms'=>'$user->rights->digiriskdolibarr->level1->level2' if you want your menu with a permission rules + 'target' => '', + 'user' => 0, // 0=Menu for internal users, 1=external users, 2=both + ]; $this->menu[$r++] = [ 'fk_menu' => 'fk_mainmenu=digiriskdolibarr', // '' if this is a top menu. For left menu, use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode @@ -1584,6 +1610,24 @@ public function init($options = '') $langs->load("digiriskdolibarr@digiriskdolibarr"); + if (empty($conf->global->DIGIRISKDOLIBARR_ACCIDENT_REMOVE_FK_USER_VICTIM)) { + + require_once __DIR__ . '/../../class/accident.class.php'; + require_once __DIR__ . '/../../../saturne/class/saturnesignature.class.php'; + + $accident = new Accident($this->db); + $signatory = new SaturneSignature($this->db); + + $accidentList = $accident->fetchAll('','',0,0, ['customsql' => 'fk_user_victim > 0']); + + if (is_array($accidentList) && !empty($accidentList)) { + foreach($accidentList as $accidentSingle) { + $signatory->setSignatory($accidentSingle->id, 'accident', 'user', array($accidentSingle->fk_user_victim), 'Victim'); + } + } + dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_ACCIDENT_REMOVE_FK_USER_VICTIM', 1, 'integer', 0, '', $conf->entity); + } + $sql = []; // Load sql sub folders $sqlFolder = scandir(__DIR__ . '/../../sql'); @@ -1607,7 +1651,8 @@ public function init($options = '') delDocumentModel('riskassessmentdocument_odt', 'riskassessmentdocument'); delDocumentModel('ticketdocument_odt', 'ticketdocument'); delDocumentModel('orque_projectdocument', 'project'); - delDocumentModel('accidentinvestigationdocument_odt', 'accidentinvestigationdocument'); + delDocumentModel('accidentinvestigationdocument_odt', 'accidentinvestigationdocument'); + delDocumentModel('registerdocument_odt', 'registerdocument'); addDocumentModel('informationssharing_odt', 'informationssharing', 'ODT templates', 'DIGIRISKDOLIBARR_INFORMATIONSSHARING_ADDON_ODT_PATH'); addDocumentModel('legaldisplay_odt', 'legaldisplay', 'ODT templates', 'DIGIRISKDOLIBARR_LEGALDISPLAY_ADDON_ODT_PATH'); @@ -1621,7 +1666,8 @@ public function init($options = '') addDocumentModel('riskassessmentdocument_odt', 'riskassessmentdocument', 'ODT templates', 'DIGIRISKDOLIBARR_RISKASSESSMENTDOCUMENT_ADDON_ODT_PATH'); addDocumentModel('ticketdocument_odt', 'ticketdocument', 'ODT templates', 'DIGIRISKDOLIBARR_TICKETDOCUMENT_ADDON_ODT_PATH'); addDocumentModel('orque_projectdocument', 'project', 'orque'); - addDocumentModel('accidentinvestigationdocument_odt', 'accidentinvestigationdocument', 'ODT templates', 'DIGIRISKDOLIBARR_ACCIDENTINVESTIGATIONDOCUMENT_ADDON_ODT_PATH'); + addDocumentModel('accidentinvestigationdocument_odt', 'accidentinvestigationdocument', 'ODT templates', 'DIGIRISKDOLIBARR_ACCIDENTINVESTIGATIONDOCUMENT_ADDON_ODT_PATH'); + addDocumentModel('registerdocument_odt', 'registerdocument', 'ODT templates', 'DIGIRISKDOLIBARR_REGISTERDOCUMENT_ADDON_ODT_PATH'); if ( $conf->global->DIGIRISKDOLIBARR_DIGIRISKELEMENT_TRASH == 0 ) { require_once __DIR__ . '/../../class/digiriskelement/groupment.class.php'; diff --git a/core/tpl/accident/digiriskdolibarr_accident_lesion.tpl.php b/core/tpl/accident/digiriskdolibarr_accident_lesion.tpl.php new file mode 100644 index 000000000..16dbeda76 --- /dev/null +++ b/core/tpl/accident/digiriskdolibarr_accident_lesion.tpl.php @@ -0,0 +1,133 @@ +'; +print load_fiche_titre($langs->trans("AccidentLesionList"), '', ''); +print ''; + +global $forceall, $forcetoshowtitlelines; + +if (empty($forceall)) $forceall = 0; + +// Define colspan for the button 'Add' +$colspan = 3; // Columns: total ht + col edit + col delete + +// Accident Lines +$accidentlines = $accidentLesion->fetchAll('', '', 0, 0, ['customsql' => 't.fk_accident = ' . $object->id]); + +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +if (!empty($accidentlines) && $accidentlines > 0) { + foreach ($accidentlines as $key => $item) { + if ($action == 'editLesion' && $lineid == $key) { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + print ''; + + $coldisplay++; + //LesionLocalization -- Siège des lésions + print ''; + + $coldisplay++; + //LesionNature -- Nature des lésions + print ''; + + $coldisplay += $colspan; + print ''; + print ''; + + print ''; + } else { + print ''; + + $coldisplay++; + print ''; + + $coldisplay++; + print ''; + + $coldisplay += $colspan; + + //Actions buttons + if ($object->status == $object::STATUS_DRAFT) { + print ''; + } else { + print ''; + } + + print ''; + } + } + print ''; +} +if ($object->status == $object::STATUS_DRAFT && $permissiontoadd) { + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + print ''; + + $coldisplay++; + //LesionLocalization -- Siège des lésions + print ''; + + $coldisplay++; + //LesionNature -- Nature des lésions + print ''; + + $coldisplay += $colspan; + print ''; + print ''; + + print ''; +} +print '
' . $langs->trans('Ref.') . '' . $langs->trans('LesionLocalization') . '' . $langs->trans('LesionNature') . '' . $langs->trans('ActionsLine') . '
'; + print $item->ref; + print ''; + print saturne_select_dictionary('lesion_localization', 'c_lesion_localization', 'label', 'label', $item->lesion_localization); + print '' . ' ' . img_picto('', 'globe') . ''; + print ''; + print saturne_select_dictionary('lesion_nature', 'c_lesion_nature', 'label', 'label', $item->lesion_nature); + print '' . ' ' . img_picto('', 'globe') . ''; + print ''; + print ''; + print '   '; + print '
'; + print $item->ref; + print ''; + print $langs->transnoentities($item->lesion_localization); + print ''; + print $langs->transnoentities($item->lesion_nature); + print ''; + $coldisplay++; + print 'id . '" style="padding-right: 20px">'; + print 'id . '&token='. newToken(). '">'; + print img_delete(); + print ''; + print ''; + print '-'; + print '
'; + print $accidentLesion->getNextNumRef(); + print ''; + print saturne_select_dictionary('lesion_localization', 'c_lesion_localization', 'label'); + print '' . ' ' . img_picto('', 'globe') . ''; + print ''; + print saturne_select_dictionary('lesion_nature', 'c_lesion_nature', 'label'); + print '' . ' ' . img_picto('', 'globe') . ''; + print ''; + print ''; + print '
'; +print '
'; diff --git a/core/tpl/accident/digiriskdolibarr_accident_lesion_actions.tpl.php b/core/tpl/accident/digiriskdolibarr_accident_lesion_actions.tpl.php new file mode 100644 index 000000000..4cccabd9d --- /dev/null +++ b/core/tpl/accident/digiriskdolibarr_accident_lesion_actions.tpl.php @@ -0,0 +1,98 @@ +ref = $accidentLesion->getNextNumRef(); + $accidentLesion->date_creation = $object->db->idate($now); + $accidentLesion->entity = $conf->entity; + $accidentLesion->lesion_localization = $lesion_localization; + $accidentLesion->lesion_nature = $lesion_nature; + $accidentLesion->fk_accident = $parent_id; + +// Check parameters + if ($lesion_localization < 0) { + setEventMessages($langs->trans('ErrorFieldNotEmpty', $langs->transnoentitiesnoconv('LesionLocalization')), null, 'errors'); + $error++; + } + + if ($lesion_nature < 0) { + setEventMessages($langs->trans('ErrorFieldNotEmpty', $langs->transnoentitiesnoconv('LesionNature')), null, 'errors'); + $error++; + } + + if ( ! $error) { + $result = $accidentLesion->create($user, false); + if ($result > 0) { +// Creation accident lesion OK + setEventMessages($langs->trans('AddAccidentLesion') . ' ' . $object->ref, array()); + $urltogo = str_replace('__ID__', $result, $backtopage); + $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $id, $urltogo); // New method to autoselect project after a New on another form object creation + header("Location: " . $urltogo); + exit; + } else { +// Creation accident lesion KO + if ( ! empty($accidentLesion->errors)) setEventMessages(null, $accidentLesion->errors, 'errors'); + else setEventMessages($accidentLesion->error, null, 'errors'); + } + } +} + +// Action to update line +if ($action == 'updateLesion' && $permissiontoadd) { +// Get parameters + $lesion_localization = GETPOST('lesion_localization'); + $lesion_nature = GETPOST('lesion_nature'); + $parent_id = GETPOST('parent_id'); + + $accidentLesion->fetch($lineid); + +// Initialize object accident line + $accidentLesion->lesion_localization = $lesion_localization; + $accidentLesion->lesion_nature = $lesion_nature; + $accidentLesion->fk_accident = $parent_id; + + if ( ! $error) { + $result = $accidentLesion->update($user, false); + if ($result > 0) { +// Update accident lesion OK + setEventMessages($langs->trans('UpdateAccidentLesion') . ' ' . $object->ref, array()); + $urltogo = str_replace('__ID__', $result, $backtopage); + $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $parent_id, $urltogo); // New method to autoselect project after a New on another form object creation + header("Location: " . $urltogo); + exit; + } else { +// Update accident lesion KO + if ( ! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + } + } +} + +// Action to delete line +if ($action == 'deleteLesion' && $permissiontodelete) { + $accidentLesion->fetch($lineid); + $result = $accidentLesion->delete($user, false, false); + if ($result > 0) { +// Deletion accident lesion OK + setEventMessages($langs->trans('DeleteAccidentLesion') . ' ' . $object->ref, array()); + $urltogo = str_replace('__ID__', $result, $backtopage); + $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $parent_id, $urltogo); // New method to autoselect project after a New on another form object creation + header("Location: " . $urltogo); + exit; + } else { +// Deletion accident lesion KO + if (!empty($object->errors)) { + setEventMessages('', $object->errors, 'errors'); + } else { + setEventMessages($object->error, [], 'errors'); + } + } +} diff --git a/core/tpl/digiriskdolibarr_dashboard_ticket.tpl.php b/core/tpl/digiriskdolibarr_dashboard_ticket.tpl.php index ef065ad57..5c4e26235 100644 --- a/core/tpl/digiriskdolibarr_dashboard_ticket.tpl.php +++ b/core/tpl/digiriskdolibarr_dashboard_ticket.tpl.php @@ -71,7 +71,8 @@ foreach ($allCategories as $category) { $arrayCats[$category->label] = array( 'id' => $category->id, - 'name' => $category->label, + 'name' => $category->label, + 'color' => $category->color, 'photo' => show_category_image($category, $upload_dir, 1) ); } @@ -137,11 +138,13 @@ // Show dashboard if (!empty($dashboardlines)) { $openedDashBoard = ''; + $prevColor = ''; foreach ($dashboardlines['ticket'][$digiriskelement->id] as $key => $board) { + $prevColor = $board->color ?: $prevColor; if ($board->visible) { $openedDashBoard .= '
'; $openedDashBoard .= '
'; - $openedDashBoard .= ''; + $openedDashBoard .= ''; $openedDashBoard .= ($board->img) ?: ''; $openedDashBoard .= ''; $openedDashBoard .= '
'; diff --git a/core/tpl/digiriskdolibarr_projectcreation_action.tpl.php b/core/tpl/digiriskdolibarr_projectcreation_action.tpl.php index f177cc99a..ca84c0b1f 100644 --- a/core/tpl/digiriskdolibarr_projectcreation_action.tpl.php +++ b/core/tpl/digiriskdolibarr_projectcreation_action.tpl.php @@ -749,7 +749,7 @@ dolibarr_set_const($db, 'DIGIRISKDOLIBARR_SIGNATURE_SHOW_COMPANY_LOGO', dolibarr_get_const($db,'DIGIRISKDOLIBARR_SIGNATURE_SHOW_COMPANY_LOGO'), 'integer', 0, '', $conf->entity); //CONST TICKET & REGISTERS - dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', dolibarr_get_const($db,'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS'), 'integer', 0, '', $conf->entity); + dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', dolibarr_get_const($db,'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS'), 'integer', 0, '', 0); dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_CATEGORIES_CREATED', dolibarr_get_const($db,'DIGIRISKDOLIBARR_TICKET_CATEGORIES_CREATED'), 'integer', 0, '', $conf->entity); dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_ENABLE_PUBLIC_INTERFACE', dolibarr_get_const($db,'DIGIRISKDOLIBARR_TICKET_ENABLE_PUBLIC_INTERFACE'), 'integer', 0, '', $conf->entity); dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_SHOW_COMPANY_LOGO', dolibarr_get_const($db,'DIGIRISKDOLIBARR_TICKET_SHOW_COMPANY_LOGO'), 'integer', 0, '', $conf->entity); diff --git a/core/tpl/riskanalysis/risk/digiriskdolibarr_risklist_view.tpl.php b/core/tpl/riskanalysis/risk/digiriskdolibarr_risklist_view.tpl.php index 7ba07c810..718393275 100644 --- a/core/tpl/riskanalysis/risk/digiriskdolibarr_risklist_view.tpl.php +++ b/core/tpl/riskanalysis/risk/digiriskdolibarr_risklist_view.tpl.php @@ -645,11 +645,6 @@ -
@@ -658,17 +653,17 @@ trans('RiskAssessment'); ?>*
'0-47', 48 => '48-50', 51 => '51-80', 100 => '81-100'); if ( ! empty($defaultCotation)) : - foreach ($defaultCotation as $request) : - $evaluation->cotation = $request; ?> + foreach ($defaultCotation as $cotation => $shownCotation) : + $evaluation->cotation = $cotation; ?>
+ class="risk-evaluation-cotation cotation">
@@ -714,20 +709,6 @@ class="risk-evaluation-cotation cotation">
-
- 0) { - $evaluation->photo = $fileName; - $showOnlyFavorite = 1; - } else { - $showOnlyFavorite = 0; - } - print saturne_show_medias_linked('digiriskdolibarr', $conf->digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RA0', 'small', 1, 0, 0, 0, 50, 50, 0, 0, 0, '/riskassessment/tmp/RA0', $evaluation, 'photo', 0, 0, 0, $showOnlyFavorite); ?> -
+
+
+
trans('Medias'); ?>
+ + + + + + +
+ + + + + + + + digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RA0', 'small', 0, 0, 0, 0, $onPhone ? 40 : 50, $onPhone ? 40 : 50, 1, 0, 0, '/riskassessment/tmp/RA0'); + ?> +
+
+
-
-
trans('Medias'); ?>
- digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RK0', 'small', 0, 0, 0, 0, 150, 150, 1, 0, 0, '/riskassessment/tmp/RK0'); - ?> -
-
@@ -853,20 +854,20 @@ class="risk-evaluation-cotation cotation">
trans('RiskAssessment'); ?>*
- cotation = $request; ?> -
- + '0-47', 48 => '48-50', 51 => '51-80', 100 => '81-100'); + if ( ! empty($defaultCotation)) : + foreach ($defaultCotation as $cotation => $shownCotation) : + $evaluation->cotation = $cotation; ?> +
+
@@ -910,20 +911,6 @@ class="risk-evaluation-cotation cotation">
-
- 0) { - $evaluation->photo = $fileName; - $showOnlyFavorite = 1; - } else { - $showOnlyFavorite = 0; - } - print saturne_show_medias_linked('digiriskdolibarr', $conf->digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RA0', 'small', 1, 0, 0, 0, 50, 50, 0, 0, 0, '/riskassessment/tmp/RA0', $evaluation, 'photo', 0, 0, 0, $showOnlyFavorite); ?> -
+
+
+
trans('Medias'); ?>
+ + + + + + +
+ + + + + + + + digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RA0', 'small', 0, 0, 0, 0, $onPhone ? 40 : 50, $onPhone ? 40 : 50, 1, 0, 0, '/riskassessment/tmp/RA0'); + ?> +
+
+
global->DIGIRISKDOLIBARR_TASK_MANAGEMENT) : ?>
@@ -960,15 +978,6 @@ class="risk-evaluation-cotation cotation">
-
-
trans('Medias'); ?>
- '; - print saturne_show_medias_linked('digiriskdolibarr', $conf->digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RA0', 'small', 0, 0, 0, 0, 150, 150, 0, 0, 0, '/riskassessment/tmp/RA0', $evaluation); - print '
'; - ?> - method = $lastEvaluation->method ?: "standard" ; +$evaluation->method = $lastRiskAssessment->method ?: "standard" ; ?>
@@ -264,55 +269,51 @@
global->DIGIRISKDOLIBARR_ADVANCED_RISKASSESSMENT_METHOD) : ?> global->DIGIRISKDOLIBARR_MULTIPLE_RISKASSESSMENT_METHOD == 1 ) : ?> -
button-radius-2"> +
button-radius-2"> trans('SimpleEvaluation') ?>
-
button-radius-2"> +
button-radius-2"> trans('AdvancedEvaluation') ?>
-
button-radius-2"> +
button-radius-2"> trans('SimpleEvaluation') ?>
-
button-radius-2"> +
button-radius-2"> trans('AdvancedEvaluation') ?>
"> - "> + "> -
-
"> +
"> trans('RiskAssessment'); ?>*
- cotation = $request; ?> -
- + '0-47', 48 => '48-50', 51 => '51-80', 100 => '81-100'); + if ( ! empty($defaultCotation)) : + foreach ($defaultCotation as $cotation => $shownCotation) : + $evaluation->cotation = $cotation; ?> +
+
-
"> +
">

trans('SelectEvaluation') ?>

@@ -348,22 +349,7 @@ class="risk-evaluation-cotation cotation">
-
- 0) { - $evaluation->photo = $fileName; - $showOnlyFavorite = 1; - } else { - $showOnlyFavorite = 0; - } - print saturne_show_medias_linked('digiriskdolibarr', $conf->digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RA0/' . $risk->ref, 'small', 1, 0, 0, 0, 50, 50, 0, 0, 0, '/riskassessment/tmp/RA0/' . $risk->ref, $evaluation, 'photo', 0, 0, 0, $showOnlyFavorite); - ?> -
-
"> +
"> trans('CalculatedEvaluation'); ?>*
@@ -380,44 +366,65 @@ class="risk-evaluation-cotation cotation">
selectDate('', 'RiskAssessmentDateCreate0', 0, 0, 0, '', 1, 1); ?>
-
-
trans('Medias'); ?>
- '; - print saturne_show_medias_linked('digiriskdolibarr', $conf->digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RA0/' . $risk->ref, 'small', 0, 0, 0, 0, 150, 150, 0, 0, 0, '/riskassessment/tmp/RA0/' . $risk->ref, $evaluation); - print '
'; - ?> -
+
+
+
trans('Medias'); ?>
+ + + + + + +
+ + + + + + + digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/tmp/RA0/' . $risk->ref, 'small', 0, 0, 0, 0, $onPhone ? 40 : 50, $onPhone ? 40 : 50, 1, 0, 0, '/riskassessment/tmp/RA0/' . $risk->ref); + ?> +
+
+
- 0) : ?> -
+ 0) : ?> +

trans('LastRiskAssessment') . ' ' . $risk->ref; ?>

-
- cotation ?: 0; ?> +
+ cotation ?: 0; ?>
-
+
digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/' . $lastEvaluation->ref, 'small', 1, 0, 0, 0, 50, 50, 0, 0, 0, '/riskassessment/' . $lastEvaluation->ref . '/', $lastEvaluation, 'photo', 0, 0, 0, 1); + print saturne_show_medias_linked('digiriskdolibarr', $conf->digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/' . $lastRiskAssessment->ref, 'small', 1, 0, 0, 0, 50, 50, 0, 0, 0, '/riskassessment/' . $lastRiskAssessment->ref . '/', $lastRiskAssessment, 'photo', 0, 0, 0, 1); ?>
- ref; ?> + ref; ?> - global->DIGIRISKDOLIBARR_SHOW_RISKASSESSMENT_DATE && ( ! empty($lastEvaluation->date_riskassessment))) ? $lastEvaluation->date_riskassessment : $lastEvaluation->date_creation)); ?> + global->DIGIRISKDOLIBARR_SHOW_RISKASSESSMENT_DATE && ( ! empty($lastRiskAssessment->date_riskassessment))) ? $lastRiskAssessment->date_riskassessment : $lastRiskAssessment->date_creation)); ?> - fk_user_creat?:$user->id]; + fk_user_creat?:$user->id]; echo getNomUrlUser($userAuthor); ?>
- comment, 120); ?> + comment, 120); ?>
diff --git a/core/tpl/riskanalysis/riskassessment/digiriskdolibarr_riskassessment_view_edit_modal.tpl.php b/core/tpl/riskanalysis/riskassessment/digiriskdolibarr_riskassessment_view_edit_modal.tpl.php index e00fa5ecd..a179c86cc 100644 --- a/core/tpl/riskanalysis/riskassessment/digiriskdolibarr_riskassessment_view_edit_modal.tpl.php +++ b/core/tpl/riskanalysis/riskassessment/digiriskdolibarr_riskassessment_view_edit_modal.tpl.php @@ -46,12 +46,6 @@ "> - - -
@@ -60,20 +54,20 @@
"> trans('RiskAssessment'); ?>
- cotation = $request; ?> -
">
- + '0-47', 48 => '48-50', 51 => '51-80', 100 => '81-100'); + if ( ! empty($defaultCotation)) : + foreach ($defaultCotation as $cotation => $shownCotation) : + $evaluation->cotation = $cotation; ?> +
">
+
@@ -123,11 +117,6 @@ class="risk-evaluation-cotation cotationcotation ==
-
- digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/' . $lastEvaluation->ref, 'small', 1, 0, 0, 0, 50, 50, 0, 0, 0, '/riskassessment/' . $lastEvaluation->ref, $lastEvaluation, 'photo', 0, 0, 0, 1); - ?> -
"> trans('CalculatedEvaluation'); ?>
@@ -145,14 +134,36 @@ class="risk-evaluation-cotation cotationcotation == selectDate($lastEvaluation->date_riskassessment, 'RiskAssessmentDateEdit' . $lastEvaluation->id, 0, 0, 0, '', 1, 1); ?>
-
-
trans('Medias'); ?>
- '; - print saturne_show_medias_linked('digiriskdolibarr', $conf->digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/' . $lastEvaluation->ref, 'small', 0, 0, 0, 0, 150, 150, 1, 0, 0, '/riskassessment/' . $lastEvaluation->ref, $lastEvaluation); - print '
'; - ?> -
+
+
+
trans('Medias'); ?>
+ + + + + + +
+ + + + + + + digiriskdolibarr->multidir_output[$conf->entity] . '/riskassessment/' . $lastEvaluation->ref, 'small', 0, 0, 0, 0, $onPhone ? 40 : 50, $onPhone ? 40 : 50, 1, 0, 0, '/riskassessment/' . $lastEvaluation->ref, $lastEvaluation); + ?> +
+
+
diff --git a/core/tpl/riskanalysis/riskassessment/digiriskdolibarr_riskassessment_view_single.tpl.php b/core/tpl/riskanalysis/riskassessment/digiriskdolibarr_riskassessment_view_single.tpl.php index 36b44e69e..731d0d456 100644 --- a/core/tpl/riskanalysis/riskassessment/digiriskdolibarr_riskassessment_view_single.tpl.php +++ b/core/tpl/riskanalysis/riskassessment/digiriskdolibarr_riskassessment_view_single.tpl.php @@ -1,7 +1,7 @@ 0) : ?> -
+
-
+
comment, 120)); ?>
diff --git a/core/triggers/interface_99_modDigiriskdolibarr_DigiriskdolibarrTriggers.class.php b/core/triggers/interface_99_modDigiriskdolibarr_DigiriskdolibarrTriggers.class.php index 7cebc3d5b..9c3571e67 100644 --- a/core/triggers/interface_99_modDigiriskdolibarr_DigiriskdolibarrTriggers.class.php +++ b/core/triggers/interface_99_modDigiriskdolibarr_DigiriskdolibarrTriggers.class.php @@ -72,7 +72,7 @@ public function __construct($db) $this->name = preg_replace('/^Interface/i', '', get_class($this)); $this->family = "demo"; $this->description = "Digiriskdolibarr triggers."; - $this->version = '9.13.0'; + $this->version = '9.14.0'; $this->picto = 'digiriskdolibarr@digiriskdolibarr'; } @@ -114,6 +114,7 @@ public function runTrigger($action, $object, User $user, Translate $langs, Conf $action = str_replace('@DIGIRISKDOLIBARR', '', $action); $active = getDolGlobalInt('DIGIRISKDOLIBARR_MAIN_AGENDA_ACTIONAUTO_' . $action); + // Allowed triggers are a list of trigger from other module that should activate this file if (!isModEnabled('digiriskdolibarr') || !$active) { $allowedTriggers = ['COMPANY_DELETE', 'CONTACT_DELETE', 'TICKET_CREATE']; if (!in_array($action, $allowedTriggers)) { @@ -218,15 +219,18 @@ public function runTrigger($action, $object, User $user, Translate $langs, Conf } break; + case 'REGISTERDOCUMENT_GENERATE': case 'RISKASSESSMENTDOCUMENT_GENERATE' : case 'LEGALDISPLAY_GENERATE' : case 'INFORMATIONSSHARING_GENERATE' : + case 'REGISTERDOCUMENT_GENERATE' : case 'FIREPERMITDOCUMENT_GENERATE' : case 'PREVENTIONPLANDOCUMENT_GENERATE' : case 'LISTINGRISKSACTION_GENERATE' : case 'LISTINGRISKSPHOTO_GENERATE' : case 'WORKUNITDOCUMENT_GENERATE' : case 'GROUPMENTDOCUMENT_GENERATE' : + if ($object->parent_type == 'groupment' || $object->parent_type == 'workunit' || preg_match('/listingrisks/', $object->parent_type)) { $object->parent_type = 'digiriskelement'; } @@ -465,8 +469,6 @@ public function runTrigger($action, $object, User $user, Translate $langs, Conf $result = $actioncomm->create($user); break; } - } else { - setEventMessages($langs->trans('ErrorSetupEmail'), '', 'errors'); } } else { $langs->load("errors"); @@ -516,8 +518,6 @@ public function runTrigger($action, $object, User $user, Translate $langs, Conf $result = $actioncomm->create($user); break; } - } else { - setEventMessages($langs->trans('ErrorSetupEmail'), '', 'errors'); } } } else { diff --git a/documents/doctemplates/registerdocument/index.php b/documents/doctemplates/registerdocument/index.php new file mode 100644 index 000000000..cd6990e24 --- /dev/null +++ b/documents/doctemplates/registerdocument/index.php @@ -0,0 +1,2 @@ +i.json()).then(i=>{i=i[0].option.matrix[e];t.find(".risk-evaluation-calculated-cotation").find(".risk-evaluation-cotation").attr("data-scale",window.digiriskdolibarr.evaluation.getDynamicScale(i)),t.find(".risk-evaluation-calculated-cotation").find(".risk-evaluation-cotation span").text(i),t.find(".risk-evaluation-content").find(".risk-evaluation-seuil").val(i),window.digiriskdolibarr.risk.haveDataInInput(t)})}},window.digiriskdolibarr.evaluator={},window.digiriskdolibarr.evaluator.init=function(){window.digiriskdolibarr.evaluator.event()},window.digiriskdolibarr.evaluator.event=function(){$(document).on("click",".evaluator-create",window.digiriskdolibarr.evaluator.createEvaluator),$(document).on("change","#fk_user_employer",window.digiriskdolibarr.evaluator.selectUser)},window.digiriskdolibarr.evaluator.selectUser=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).closest(".modal-container"),t=s.find("#fk_user_employer").val();window.saturne.loader.display(s.find('input[name="evaluatorJob"]')),$.ajax({url:document.URL+"&action=getEvaluatorJob&token="+e,type:"POST",processData:!1,data:JSON.stringify({userID:t}),contentType:!1,success:function(i){s.find('input[name="evaluatorJob"]').val($(i).find('input[name="evaluatorJob"]').val()),s.find('input[name="evaluatorJob"]').removeClass("wpeo-loader")},error:function(i){}}),window.digiriskdolibarr.evaluator.haveDataInInput(s)},window.digiriskdolibarr.evaluator.haveDataInInput=function(i){i=i.parent().parent();i.hasClass("evaluator-add-modal")&&(0 div:nth-child(1)").text();$.ajax({url:document.URL+"&action=saveRisk&token="+e,type:"POST",processData:!1,data:JSON.stringify({riskID:t,category:s,comment:r,newParent:o}),contentType:!1,success:function(i){$(".wpeo-loader").removeClass("wpeo-loader");var e=$(".messageSuccessRiskEdit"),s=(o==a||n?($(".modal-active").removeClass("modal-active"),$(".risk-description-"+t).html($(i).find(".risk-description-"+t)),$(".risk-row-content-"+t).find(".risk-category .cell-risk").html($(i).find(".risk-row-content-"+t).find(".risk-category .cell-risk").children()),$(".risk-row-content-"+t).find(".risk-category").fadeOut(800),$(".risk-row-content-"+t).find(".risk-category").fadeIn(800),$(".risk-row-content-"+t).find(".risk-description-"+t).fadeOut(800),$(".risk-row-content-"+t).find(".risk-description-"+t).fadeIn(800)):$(".risk-row-content-"+t).fadeOut(800,function(){$(".fichecenter .opacitymedium.colorblack.paddingleft").html($(i).find("#searchFormListRisks .opacitymedium.colorblack.paddingleft"))}),""),s=(s=(s+=e.find(".valueForEditRisk1").val())+d)+e.find(".valueForEditRisk2").val();e.find("a").attr("href","#risk_row_"+t),e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")},error:function(i){var e=$(".messageErrorRiskEdit"),s="",s=(s=(s+=e.find(".valueForEditRisk1").val())+d)+e.find(".valueForEditRisk2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})},window.digiriskdolibarr.risk.unlinkSharedRisk=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).attr("value"),t=(window.saturne.loader.display($(this)),$(".risk_row_"+s).find(".risk-container > div:nth-child(1)").text());var a=document.URL.split(/#/);$.ajax({url:a[0]+"&action=unlinkSharedRisk&token="+e,type:"POST",processData:!1,data:JSON.stringify({riskID:s}),contentType:!1,success:function(i){$(".confirmquestions").html($(i).find(".confirmquestions").children()),$(".fichecenter.sharedrisklist .opacitymedium.colorblack.paddingleft").html($(i).find("#searchFormSharedListRisks .opacitymedium.colorblack.paddingleft"));var i=$(".messageSuccessRiskUnlinkShared"),e=($("#risk_row_"+s).fadeOut(800),""),e=(e=(e+=i.find(".valueForUnlinkSharedRisk1").val())+t)+i.find(".valueForUnlinkSharedRisk2").val();i.find(".notice-subtitle .text").text(e),i.removeClass("hidden")},error:function(i){var e=$(".messageErrorRiskUnlinkShared"),s="",s=(s=(s+=e.find(".valueForUnlinkSharedRisk1").val())+t)+e.find(".valueForUnlinkSharedRisk2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})},window.digiriskdolibarr.risk.sharedRiskBoxLoader=function(i){"Oui"==$(this).text()&&window.saturne.loader.display($("#searchFormSharedListRisks"))},window.digiriskdolibarr.evaluation={},window.digiriskdolibarr.evaluation.init=function(){window.digiriskdolibarr.evaluation.event()},window.digiriskdolibarr.evaluation.event=function(){$(document).on("click",".select-evaluation-method",window.digiriskdolibarr.evaluation.selectEvaluationMethod),$(document).on("click",".cotation-container .risk-evaluation-cotation.cotation",window.digiriskdolibarr.evaluation.selectSeuil),$(document).on("click",".risk-evaluation-create",window.digiriskdolibarr.evaluation.createEvaluation),$(document).on("click",".risk-evaluation-save",window.digiriskdolibarr.evaluation.saveEvaluation),$(document).on("click",".risk-evaluation-delete",window.digiriskdolibarr.evaluation.deleteEvaluation)},window.digiriskdolibarr.evaluation.selectEvaluationMethod=function(i){var e=$(this).closest(".modal-container");0"+e.split(/\(/)[0]+"("+(+s-1)+")"),s-1<1&&$(".fichecenter.risklist").html($(i).find("#searchFormListRisks")),t.removeClass("wpeo-loader"),""),e=(e=(e+=r.find(".valueForDeleteEvaluation1").val())+n)+r.find(".valueForDeleteEvaluation2").val();r.find(".notice-subtitle .text").text(e),r.removeClass("hidden")},error:function(i){var e="",e=(e=(e+=o.find(".valueForDeleteEvaluation1").val())+n)+o.find(".valueForDeleteEvaluation2").val();o.find(".notice-subtitle .text").text(e),o.removeClass("hidden")}})}},window.digiriskdolibarr.evaluation.saveEvaluation=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).closest(".risk-evaluation-edit-modal"),t=s.attr("value");var a=s.find(".risk-evaluation-comment textarea").val();let n=$(this).closest(".risk-row").find(".risk-evaluations-list-content").attr("value"),r=$(".risk-evaluation-ref-"+t).attr("value"),o=$(".risk-evaluation-list-modal-"+n),d=$("#risk_evaluation_list"+n).hasClass("modal-active");var a=window.digiriskdolibarr.risk.sanitizeBeforeRequest(a),l=s.find(".risk-evaluation-method").val(),c=s.find(".risk-evaluation-seuil").val(),k=s.find("#RiskAssessmentDateEdit"+t).val(),u=s.find(".risk-evaluation-photo .filename").val();let m=[];Object.values($(".table-cell.active.cell-"+t)).forEach(function(i){-1<$(i).data("seuil")&&(m[$(i).data("type")]=$(i).data("seuil"))}),window.saturne.loader.display($(this)),$.ajax({url:document.URL+"&action=saveEvaluation&token="+e,type:"POST",processData:!1,data:JSON.stringify({cotation:c,comment:a,method:l,photo:u,date:k,evaluationID:t,criteres:{gravite:m.gravite||0,occurrence:m.occurrence||0,protection:m.protection||0,formation:m.formation||0,exposition:m.exposition||0}}),contentType:!1,success:function(i){$("#risk_evaluation_edit"+t).removeClass("modal-active"),0<$(i).find(".risk-evaluation-container.risk-evaluation-container-"+t+":not(.last-risk-assessment)").length?((d?($(".risk-evaluation-ref-"+t+":not(.last-risk-assessment)").fadeOut(800),$(".risk-evaluation-ref-"+t+":not(.last-risk-assessment)")):($(".risk-evaluation-container-"+t+":not(.last-risk-assessment)").fadeOut(800),$(".risk-evaluation-container-"+t+":not(.last-risk-assessment)"))).fadeIn(800),o.find(".risk-evaluation-ref-"+t).replaceWith($(i).find(".risk-evaluation-ref-"+t)),$(".risk-evaluation-container.risk-evaluation-container-"+t+":not(.last-risk-assessment)").replaceWith($(i).find(".risk-evaluation-container.risk-evaluation-container-"+t+":not(.last-risk-assessment)")),$("#risk_evaluation_add"+n).html($(i).find("#risk_evaluation_add"+n).children())):($(".div-table-responsive").html($(i).find(".div-table-responsive").children()),(d?($(".risk-evaluation-ref-"+t+":not(.last-risk-assessment)").fadeOut(800),$(".risk-evaluation-ref-"+t+":not(.last-risk-assessment)")):($(".risk-evaluation-container-"+t+":not(.last-risk-assessment)").fadeOut(800),$(".risk-evaluation-container-"+t+":not(.last-risk-assessment)"))).fadeIn(800)),$(".wpeo-loader").removeClass("wpeo-loader");var i=$(".messageSuccessEvaluationEdit"),e=(s.find("#risk_evaluation_edit"+t).removeClass("modal-active"),""),e=(e=(e+=i.find(".valueForEditEvaluation1").val())+r)+i.find(".valueForEditEvaluation2").val();i.find("a").attr("href","#risk_row_"+n),i.find(".notice-subtitle .text").text(e),i.removeClass("hidden")},error:function(){var i=$(".messageErrorEvaluationEdit"),e="",e=(e=(e+=i.find(".valueForEditEvaluation1").val())+r)+i.find(".valueForEditEvaluation2").val();i.find(".notice-subtitle .text").text(e),i.removeClass("hidden")}})},window.digiriskdolibarr.risksign={},window.digiriskdolibarr.risksign.init=function(){window.digiriskdolibarr.risksign.event()},window.digiriskdolibarr.risksign.event=function(){$(document).on("click",".risksign-category-danger .item, .wpeo-table .risksign-category-danger .item",window.digiriskdolibarr.risksign.selectRiskSign),$(document).on("click",".risksign-create:not(.button-disable)",window.digiriskdolibarr.risksign.createRiskSign),$(document).on("click",".risksign-save",window.digiriskdolibarr.risksign.saveRiskSign),$(document).on("click",".risksign-unlink-shared",window.digiriskdolibarr.risksign.unlinkSharedRiskSign)},window.digiriskdolibarr.risksign.selectRiskSign=function(i){var e=$(this),e=(e.closest(".content").removeClass("active"),e.closest(".wpeo-dropdown").find(".dropdown-toggle span").hide(),e.closest(".wpeo-dropdown").find(".dropdown-toggle img").show(),e.closest(".wpeo-dropdown").find(".dropdown-toggle img").attr("src",e.find("img").attr("src")),e.closest(".wpeo-dropdown").find(".dropdown-toggle img").attr("aria-label",e.closest(".wpeo-tooltip-event").attr("aria-label")),e.closest(".fichecenter").find(".input-hidden-danger").val(e.data("id")),$(this).closest(".modal-container"));window.digiriskdolibarr.risksign.haveDataInInput(e)},window.digiriskdolibarr.risksign.haveDataInInput=function(i){i=i.parent().parent();i.hasClass("risksign-add-modal")&&0<=i.find('input[name="risksign_category_id"]').val()&&i.find(".button-disable").removeClass("button-disable")},window.digiriskdolibarr.risksign.createRiskSign=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).closest(".fichecenter").find(".risksign-content"),t=s.find(".risksign-category input").val(),s=s.find(".risksign-description textarea").val();window.saturne.loader.display($(".fichecenter.risksignlist")),$.ajax({url:document.URL+"&action=add&token="+e,type:"POST",data:JSON.stringify({riskSignCategory:t,riskSignDescription:s}),processData:!1,contentType:!1,success:function(i){$(".fichecenter.risksignlist").html($(i).find("#searchFormListRiskSigns"));var e=$(".messageSuccessRiskSignCreate");$(".fichecenter.risksignlist").removeClass("wpeo-loader"),e.html($(i).find(".risksign-create-success-notice")),e.removeClass("hidden")},error:function(i){var e=$(".messageErrorRiskCreate");e.html($(i).find(".risksign-create-error-notice")),e.removeClass("hidden")}})},window.digiriskdolibarr.risksign.saveRiskSign=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).attr("value");let t=$(this).closest(".risksign-container").find(".risksign-content"),a="";var n=t.find(".risksign-category input").val(),r=t.find(".risksign-description textarea").val();let o=$(".risksign_row_"+s).find(".risksign-container > div:nth-child(1)").text();window.saturne.loader.display(t),$.ajax({url:document.URL+"&action=saveRiskSign&token="+e,data:JSON.stringify({riskSignID:s,riskSignCategory:n,riskSignDescription:r}),type:"POST",processData:!1,contentType:!1,success:function(i){$(".fichecenter.risksignlist").html($(i).find("#searchFormListRiskSigns"));i=$(".messageSuccessRiskSignEdit");t.removeClass("wpeo-loader"),a=(a=(a+=i.find(".valueForEditRiskSign1").val())+o)+i.find(".valueForEditRiskSign2").val(),i.find(".notice-subtitle .text").text(a),i.removeClass("hidden")},error:function(){var i=$(".messageErrorRiskSignEdit");t.removeClass("wpeo-loader"),a=(a=(a+=i.find(".valueForEditRiskSign1").val())+o)+i.find(".valueForEditRiskSign2").val(),i.find(".notice-subtitle .text").text(a),i.removeClass("hidden")}})},window.digiriskdolibarr.risksign.unlinkSharedRiskSign=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).attr("value"),t=(window.saturne.loader.display($(this)),$(".risksign_row_"+s).find(".risksign-container > div:nth-child(1)").text());var a=document.URL.split(/#/);$.ajax({url:a[0]+"&action=unlinkSharedRiskSign&token="+e,type:"POST",processData:!1,data:JSON.stringify({risksignID:s}),contentType:!1,success:function(i){$(".fichecenter.sharedrisksignlist .opacitymedium.colorblack.paddingleft").html($(i).find("#searchFormSharedListRiskSigns .opacitymedium.colorblack.paddingleft"));var i=$(".messageSuccessRiskSignUnlinkShared"),e=($("#risksign_row_"+s).fadeOut(800),""),e=(e=(e+=i.find(".valueForUnlinkSharedRiskSign1").val())+t)+i.find(".valueForUnlinkSharedRiskSign2").val();i.find(".notice-subtitle .text").text(e),i.removeClass("hidden")},error:function(i){var e=$(".messageErrorRiskSignUnlinkShared"),s="",s=(s=(s+=e.find(".valueForUnlinkSharedRiskSign1").val())+t)+e.find(".valueForUnlinkSharedRiskSign2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask={},window.digiriskdolibarr.riskassessmenttask.init=function(){window.digiriskdolibarr.riskassessmenttask.event()},window.digiriskdolibarr.riskassessmenttask.event=function(){$(document).on("input",".riskassessment-task-label",window.digiriskdolibarr.riskassessmenttask.fillRiskAssessmentTaskLabel),$(document).on("click",".riskassessment-task-create",window.digiriskdolibarr.riskassessmenttask.createRiskAssessmentTask),$(document).on("click",".riskassessment-task-save",window.digiriskdolibarr.riskassessmenttask.saveRiskAssessmentTask),$(document).on("click",".riskassessment-task-delete",window.digiriskdolibarr.riskassessmenttask.deleteRiskAssessmentTask),$(document).on("click",".riskassessment-task-timespent-create",window.digiriskdolibarr.riskassessmenttask.createRiskAssessmentTaskTimeSpent),$(document).on("click",".riskassessment-task-timespent-save",window.digiriskdolibarr.riskassessmenttask.saveRiskAssessmentTaskTimeSpent),$(document).on("click",".riskassessment-task-timespent-delete",window.digiriskdolibarr.riskassessmenttask.deleteRiskAssessmentTaskTimeSpent),$(document).on("click",".riskassessment-task-progress-checkbox:not(.riskassessment-task-progress-checkbox-readonly)",window.digiriskdolibarr.riskassessmenttask.checkTaskProgress),$(document).on("change","#RiskassessmentTaskTimespentDatehour",window.digiriskdolibarr.riskassessmenttask.selectRiskassessmentTaskTimespentDateHour),$(document).on("change","#RiskassessmentTaskTimespentDatemin",window.digiriskdolibarr.riskassessmenttask.selectRiskassessmentTaskTimespentDateMin),$(document).on("keyup",".riskassessment-task-label",window.digiriskdolibarr.riskassessmenttask.checkRiskassessmentTaskLabelLength),$(document).on("click",".listingHeaderTaskTooltip",window.digiriskdolibarr.riskassessmenttask.redirectOnSharedTaskConfig)},window.digiriskdolibarr.riskassessmenttask.fillRiskAssessmentTaskLabel=function(i){var e=$(this).closest(".modal-container");window.digiriskdolibarr.riskassessmenttask.haveDataInInput(e)},window.digiriskdolibarr.riskassessmenttask.haveDataInInput=function(i){i=i.parent().parent();i.hasClass("riskassessment-task-add-modal")&&i.find('input[name="label"]').val().length&&i.find(".button-disable").removeClass("button-disable")},window.digiriskdolibarr.riskassessmenttask.createRiskAssessmentTask=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).closest(".riskassessment-task-add-modal"),t=s.find(".modal-risk").attr("value"),s=s.find(".riskassessment-task-container"),a=s.find(".riskassessment-task-label").val(),a=window.digiriskdolibarr.risk.sanitizeBeforeRequest(a),n=s.find("#RiskassessmentTaskDateStart"+t).val(),r=s.find("#RiskassessmentTaskDateStart"+t+"hour").val(),o=s.find("#RiskassessmentTaskDateStart"+t+"min").val(),d=s.find("#RiskassessmentTaskDateEnd"+t).val(),l=s.find("#RiskassessmentTaskDateEnd"+t+"hour").val(),c=s.find("#RiskassessmentTaskDateEnd"+t+"min").val(),s=s.find(".riskassessment-task-budget").val();window.saturne.loader.display($(this)),window.saturne.loader.display($(".riskassessment-tasks"+t)),$.ajax({url:document.URL+"&action=addRiskAssessmentTask&token="+e,type:"POST",data:JSON.stringify({tasktitle:a,dateStart:n,hourStart:r,minStart:o,dateEnd:d,hourEnd:l,minEnd:c,budget:s,riskToAssign:t}),processData:!1,contentType:!1,success:function(i){$(".tasks-list-container-"+t).replaceWith($(i).find(".tasks-list-container-"+t));var e=$(".messageSuccessTaskCreate");$(".riskassessment-tasks"+t).fadeOut(800),$(".riskassessment-tasks"+t).fadeIn(800),e.find("a").attr("href","#risk_row_"+t),e.html($(i).find(".task-create-success-notice")),e.removeClass("hidden")},error:function(i){$(".wpeo-loader").removeClass("wpeo-loader"),window.scrollTo(0,0);var i=JSON.parse(i.responseText),e=$(".messageErrorTaskCreate"),s=($("#risk_assessment_task_add"+t).removeClass("modal-active"),""),s=(s=(s+=e.find(".valueForCreateTask1").val())+e.find(".valueForCreateTask2").val())+" : "+i.message;e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask.deleteRiskAssessmentTask=function(i){var e=window.saturne.toolbox.getToken(),t=$(this).closest(".wpeo-table.riskassessment-tasks").attr("value"),a=$(this).closest(".riskassessment-task-single-content").attr("value"),s=$(this).closest(".riskassessment-task-container-"+a).find(".labelForDelete").val();let n=$(".messageSuccessTaskDelete"),r=$(".messageErrorTaskDelete");if(1!=confirm(s))return!1;{let s=$(".riskassessment-task-container-"+a).attr("value");window.saturne.loader.display($(".riskassessment-task-container-"+a)),$.ajax({url:document.URL+"&action=deleteRiskAssessmentTask&deletedRiskAssessmentTaskId="+a+"&token="+e,type:"POST",processData:!1,contentType:!1,success:function(i){console.log($(".riskassessment-task-listing-wrapper-"+t)),console.log(t),$(".riskassessment-task-listing-wrapper-"+t).replaceWith($(i).find(".riskassessment-task-listing-wrapper-"+t)),$(".riskassessment-tasks"+t).fadeOut(800),$(".riskassessment-tasks"+t).fadeIn(800);i="",i=(i=(i+=n.find(".valueForDeleteTask1").val())+s)+n.find(".valueForDeleteTask2").val();n.find("a").attr("href","#risk_row_"+t),n.find(".notice-subtitle .text").text(i),n.removeClass("hidden")},error:function(i){$(".wpeo-loader").removeClass("wpeo-loader"),window.scrollTo(0,0);var i=JSON.parse(i.responseText),e="",e=(e=(e=(e+=r.find(".valueForDeleteTask1").val())+s)+r.find(".valueForDeleteTask2").val())+" : "+i.message;r.find(".notice-subtitle .text").text(e),r.removeClass("hidden")}})}},window.digiriskdolibarr.riskassessmenttask.saveRiskAssessmentTask=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).attr("value");var t=$(this).closest(".modal-container"),a=$(this).closest(".modal-risk").attr("value");let n="";var r=t.find(".riskassessment-task-label"+s).val(),r=window.digiriskdolibarr.risk.sanitizeBeforeRequest(r);let o=$(".riskassessment-task-single-"+s+" .riskassessment-task-reference").attr("value"),d=0;t.find(".riskassessment-task-progress-checkbox"+s).is(":checked")&&(d=1);var l=t.find("#RiskassessmentTaskDateStartEdit"+s).val(),c=t.find("#RiskassessmentTaskDateStartEdit"+s+"hour").val(),k=t.find("#RiskassessmentTaskDateStartEdit"+s+"min").val(),u=t.find("#RiskassessmentTaskDateEndEdit"+s).val(),m=t.find("#RiskassessmentTaskDateEndEdit"+s+"hour").val(),v=t.find("#RiskassessmentTaskDateEndEdit"+s+"min").val(),t=t.find(".riskassessment-task-budget"+s).val();window.saturne.loader.display($(this)),window.saturne.loader.display($(".riskassessment-task-single-"+s)),$.ajax({url:document.URL+"&action=saveRiskAssessmentTask&token="+e,data:JSON.stringify({riskAssessmentTaskID:s,tasktitle:r,dateStart:l,hourStart:c,minStart:k,dateEnd:u,hourEnd:m,minEnd:v,budget:t,taskProgress:d}),type:"POST",processData:!1,contentType:!1,success:function(i){$("#risk_assessment_task_edit"+s).removeClass("modal-active"),$(".riskassessment-task-container-"+s).replaceWith($(i).find(".riskassessment-task-container-"+s).first());i=$(".messageSuccessTaskEdit");$(".riskassessment-tasks"+a).fadeOut(800),$(".riskassessment-tasks"+a).fadeIn(800),n=(n=(n+=i.find(".valueForEditTask1").val())+o)+i.find(".valueForEditTask2").val(),$(".wpeo-loader").removeClass("wpeo-loader"),$(".loader-spin").remove(),i.find("a").attr("href","#risk_row_"+a),i.find(".notice-subtitle .text").text(n),i.removeClass("hidden")},error:function(i){$(".wpeo-loader").removeClass("wpeo-loader"),window.scrollTo(0,0);var i=JSON.parse(i.responseText),e=$(".messageErrorTaskEdit");$("#risk_assessment_task_edit"+s).removeClass("modal-active"),$(".wpeo-loader").removeClass("wpeo-loader"),n=(n=(n=(n+=e.find(".valueForEditTask1").val())+o)+e.find(".valueForEditTask2").val()+" : ")+i.message,e.find(".notice-subtitle .text").text(n),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask.createRiskAssessmentTaskTimeSpent=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).attr("value");var t=$(this).closest(".riskassessment-task-edit-modal"),a=t.find(".riskassessment-task-timespent-container");let n=t.find("riskassessment-task-single").attr("value"),r="",o=t.find(".riskassessment-task-reference").attr("value"),d=$(".id-container").find(".riskassessment-total-task-timespent-"+s);var t=a.find("#RiskassessmentTaskTimespentDate"+s).val(),l=a.find("#RiskassessmentTaskTimespentDate"+s+"hour").val(),c=a.find("#RiskassessmentTaskTimespentDate"+s+"min").val(),k=a.find(".riskassessment-task-timespent-comment").val(),k=window.digiriskdolibarr.risk.sanitizeBeforeRequest(k),a=a.find(".riskassessment-task-timespent-duration").val();window.saturne.loader.display($(this)),window.saturne.loader.display($(".riskassessment-task-single-"+s)),$.ajax({url:document.URL+"&action=addRiskAssessmentTaskTimeSpent&token="+e,type:"POST",data:JSON.stringify({taskID:s,date:t,hour:l,min:c,comment:k,duration:a}),processData:!1,contentType:!1,success:function(i){var e=$(".messageSuccessTaskTimeSpentCreate"+s);$(".riskassessment-tasks"+n).fadeOut(800),$(".riskassessment-tasks"+n).fadeIn(800),r=(r=(r+=e.find(".valueForCreateTaskTimeSpent1").val())+o)+e.find(".valueForCreateTaskTimeSpent2").val(),$(".riskassessment-task-timespent-container").find(".riskassessment-task-timespent-list-"+s).replaceWith($(i).find(".riskassessment-task-timespent-container").find(".riskassessment-task-timespent-list-"+s)),$(".riskassessment-task-container-"+s).closest(".riskassessment-tasks").replaceWith($(i).find(".riskassessment-task-container-"+s).closest(".riskassessment-tasks")),$(".loader-spin").remove(),$(".wpeo-loader").removeClass("wpeo-loader"),e.find(".notice-subtitle .text").text(r),e.removeClass("hidden"),d.html($(i).find(".modal-content").find(".riskassessment-total-task-timespent-"+s).first())},error:function(i){$(this).closest(".risk-row-content-"+n).removeClass("wpeo-loader");var e=$(".messageErrorTaskTimeSpentCreate"+s);e.html($(i).find(".task-timespent-create-error-notice")),e.removeClass("hidden")},complete:function(){$("#risk_assessment_task_edit"+s+".wpeo-modal").addClass("modal-active")}})},window.digiriskdolibarr.riskassessmenttask.deleteRiskAssessmentTaskTimeSpent=function(i){var e=window.saturne.toolbox.getToken();let a=$(this).closest(".riskassessment-task-timespent-list").attr("value"),n=$(this).attr("value");var s=$(this).attr("value"),t=$(this).closest(".riskassessment-task-timespent-"+n).find(".labelForDelete").val();let r=$(".id-container").first().find(".riskassessment-total-task-timespent-"+a);if(1!=confirm(t))return!1;{let t=$(".riskassessment-task-container-"+a).attr("value");window.saturne.loader.display($(this)),$.ajax({url:document.URL+"&action=deleteRiskAssessmentTaskTimeSpent&deletedRiskAssessmentTaskTimeSpentId="+s+"&token="+e,type:"POST",processData:!1,contentType:!1,success:function(i){var e=$(".messageSuccessTaskTimeSpentDelete"+a),s=($(".riskassessment-task-timespent-"+n).fadeOut(800),""),s=(s=(s+=e.find(".valueForDeleteTaskTimeSpent1").val())+t)+e.find(".valueForDeleteTaskTimeSpent2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden"),r.html($(i).find(".modal-content").find(".riskassessment-total-task-timespent-"+a).first())},error:function(i){var e=$(".messageErrorTaskDeleteTimeSpent"+a),s="",s=(s=(s+=e.find(".valueForDeleteTaskTimeSpent1").val())+t)+e.find(".valueForDeleteTaskTimeSpent2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})}},window.digiriskdolibarr.riskassessmenttask.saveRiskAssessmentTaskTimeSpent=function(i){var e=window.saturne.toolbox.getToken();let s=$(this);var t=$(this).attr("value"),a=$(this).closest(".riskassessment-task-timespent-edit-modal").find(".riskassessment-task-timespent-container");let n=a.attr("value"),r="",o=$(".riskassessment-task-container-"+n).attr("value"),d=$(".id-container").first().find(".riskassessment-total-task-timespent-"+n);var l=a.find("#RiskassessmentTaskTimespentDateEdit"+t).val(),c=a.find("#RiskassessmentTaskTimespentDateEdit"+t+"hour").val(),k=a.find("#RiskassessmentTaskTimespentDateEdit"+t+"min").val(),u=a.find(".riskassessment-task-timespent-comment").val(),u=window.digiriskdolibarr.risk.sanitizeBeforeRequest(u),a=a.find(".riskassessment-task-timespent-duration").val();window.saturne.loader.display($(this)),window.saturne.loader.display($(".riskassessment-task-single-"+n)),$.ajax({url:document.URL+"&action=saveRiskAssessmentTaskTimeSpent&token="+e,data:JSON.stringify({riskAssessmentTaskTimeSpentID:t,taskID:n,date:l,hour:c,min:k,comment:u,duration:a}),type:"POST",processData:!1,contentType:!1,success:function(i){s.closest(".modal-active").removeClass("modal-active");var e=$(".messageSuccessTaskTimeSpentEdit"+n);$(".wpeo-loader").removeClass("wpeo-loader"),r=(r=(r+=e.find(".valueForEditTaskTimeSpent1").val())+o)+e.find(".valueForEditTaskTimeSpent2").val(),d.html($(i).find(".modal-content").find(".riskassessment-total-task-timespent-"+n).first()),$(".riskassessment-task-timespent-list-"+n).html($(i).find(".riskassessment-task-timespent-list-"+n).children()),e.find(".notice-subtitle .text").text(r),e.removeClass("hidden")},error:function(i){var e=$(".messageSuccessTaskTimeSpentEdit"+n);r=(r=(r+=e.find(".valueForEditTaskTimeSpent1").val())+o)+e.find(".valueForEditTaskTimeSpent2").val(),e.find(".notice-subtitle .text").text(r),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask.checkTaskProgress=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).closest(".risk-row").find(".riskassessment-task-container"),t=s.find(".riskassessment-task-single-content").attr("value");let a=$(this).closest(".riskassessment-tasks").attr("value"),n="",r=s.attr("value"),o="";s.find(".riskassessment-task-progress-checkbox"+t).hasClass("progress-checkbox-check")?(o=0,s.find(".riskassessment-task-progress-checkbox"+t).toggleClass("progress-checkbox-check").toggleClass("progress-checkbox-uncheck")):s.find(".riskassessment-task-progress-checkbox"+t).hasClass("progress-checkbox-uncheck")&&(o=1,s.find(".riskassessment-task-progress-checkbox"+t).toggleClass("progress-checkbox-uncheck").toggleClass("progress-checkbox-check")),window.saturne.loader.display($(".riskassessment-task-single-"+t));s=window.location.href.replace(/#.*/,"");$.ajax({url:s+"&action=checkTaskProgress&token="+e,data:JSON.stringify({riskAssessmentTaskID:t,taskProgress:o}),type:"POST",processData:!1,contentType:!1,success:function(i){$(".fichecenter.risklist").html($(i).find("#searchFormListRisks"));i=$(".messageSuccessTaskEdit");$(".riskassessment-tasks"+a).fadeOut(800),$(".riskassessment-tasks"+a).fadeIn(800),n=(n=(n+=i.find(".valueForEditTask1").val())+r)+i.find(".valueForEditTask2").val(),i.find(".notice-subtitle .text").text(n),i.removeClass("hidden")},error:function(i){var e=$(".messageErrorTaskEdit");n=(n=(n+=e.find(".valueForEditTask1").val())+r)+e.find(".valueForEditTask2").val(),e.find(".notice-subtitle .text").text(n),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask.selectRiskassessmentTaskTimespentDateHour=function(i){$(this).closest(".nowraponall").find(".select-riskassessmenttask-timespent-datehour").remove(),$(this).before('{$("#sendFileForm").load(document.URL+n+"ticket_id="+a+" #fileLinkedTable")})},window.digiriskdolibarr.ticket.removeFile=function(i){let e=$(this).attr("value");e=e.replace("_mini","");var s=$("#ticket_id").val(),t=window.saturne.toolbox.getQuerySeparator(document.URL);fetch(document.URL+t+"action=removefile&filetodelete="+e+"&ticket_id="+s,{method:"POST"}).then(i=>{$(this).parent().parent().hide()})},window.digiriskdolibarr.ticket.addDashBoardTicketInfo=function(){var i=window.saturne.toolbox.getToken(),e=$("#select2-boxcombo-container").attr("title"),s=e.split(" : ")[0],e=e.split(" : ")[2],t=window.saturne.toolbox.getQuerySeparator(document.URL);$.ajax({url:document.URL+t+"action=adddashboardinfo&token="+i,type:"POST",processData:!1,data:JSON.stringify({digiriskelementID:s,catID:e}),contentType:!1,success:function(i){window.location.reload()},error:function(){}})},window.digiriskdolibarr.ticket.closeDashBoardTicketInfo=function(){var i=window.saturne.toolbox.getToken();let e=$(this);var s=e.attr("data-digiriskelementid"),t=e.attr("data-catid"),a=window.saturne.toolbox.getQuerySeparator(document.URL);$.ajax({url:document.URL+a+"action=closedashboardinfo&token="+i,type:"POST",processData:!1,data:JSON.stringify({digiriskelementID:s,catID:t}),contentType:!1,success:function(i){e.closest(".box-flex-item").fadeOut(400),$(".add-widget-box").attr("style",""),$(".add-widget-box").html($(i).find(".add-widget-box").children())},error:function(){}})},window.digiriskdolibarr.ticket.checkValidEmail=function(){0==/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(this.value)?$(this).css("border","3px solid red"):$(this).css("border","3px solid green")},window.digiriskdolibarr.ticket.checkValidPhone=function(){0==/^(?:(?:(?:\+|00)\d{2}[\s]?(?:\(0\)[\s]?)?)|0){1}[1-9]{1}([\s.-]?)(?:\d{2}\1?){3}\d{2}$/.test(this.value)?$(this).css("border","3px solid red"):$(this).css("border","3px solid green")},window.digiriskdolibarr.digiriskusers={},window.digiriskdolibarr.digiriskusers.init=function(){window.digiriskdolibarr.digiriskusers.event()},window.digiriskdolibarr.digiriskusers.event=function(){$(document).on("input",".digirisk-users #firstname",window.digiriskdolibarr.digiriskusers.fillEmail),$(document).on("input",".digirisk-users #lastname",window.digiriskdolibarr.digiriskusers.fillEmail)},window.digiriskdolibarr.digiriskusers.fillEmail=function(i){var e=$(".digirisk-users #firstname").val(),s=$(".digirisk-users #lastname").val(),t=$(".input-domain-mail").val(),e=window.digiriskdolibarr.digiriskusers.removeDiacritics(e+"."+s+"@"+t).toLowerCase();$(".digirisk-users #email").val(e)},window.digiriskdolibarr.digiriskusers.removeDiacritics=function(i){for(var e="",s=i.normalize("NFD"),t=0,a=0;ti.json()).then(i=>{i=i[0].option.matrix[e];t.find(".risk-evaluation-calculated-cotation").find(".risk-evaluation-cotation").attr("data-scale",window.digiriskdolibarr.evaluation.getDynamicScale(i)),t.find(".risk-evaluation-calculated-cotation").find(".risk-evaluation-cotation span").text(i),t.find(".risk-evaluation-content").find(".risk-evaluation-seuil").val(i),window.digiriskdolibarr.risk.haveDataInInput(t)})}},window.digiriskdolibarr.evaluator={},window.digiriskdolibarr.evaluator.init=function(){window.digiriskdolibarr.evaluator.event()},window.digiriskdolibarr.evaluator.event=function(){$(document).on("click",".evaluator-create",window.digiriskdolibarr.evaluator.createEvaluator),$(document).on("change","#fk_user_employer",window.digiriskdolibarr.evaluator.selectUser)},window.digiriskdolibarr.evaluator.selectUser=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).closest(".modal-container"),t=s.find("#fk_user_employer").val();window.saturne.loader.display(s.find('input[name="evaluatorJob"]')),$.ajax({url:document.URL+"&action=getEvaluatorJob&token="+e,type:"POST",processData:!1,data:JSON.stringify({userID:t}),contentType:!1,success:function(i){s.find('input[name="evaluatorJob"]').val($(i).find('input[name="evaluatorJob"]').val()),s.find('input[name="evaluatorJob"]').removeClass("wpeo-loader")},error:function(i){}}),window.digiriskdolibarr.evaluator.haveDataInInput(s)},window.digiriskdolibarr.evaluator.haveDataInInput=function(i){i=i.parent().parent();i.hasClass("evaluator-add-modal")&&(0 div:nth-child(1)").text();$.ajax({url:document.URL+"&action=saveRisk&token="+e,type:"POST",processData:!1,data:JSON.stringify({riskID:t,category:s,comment:r,newParent:o}),contentType:!1,success:function(i){$(".wpeo-loader").removeClass("wpeo-loader");var e=$(".messageSuccessRiskEdit"),s=(o==a||n?($(".modal-active").removeClass("modal-active"),$(".risk-description-"+t).html($(i).find(".risk-description-"+t)),$(".risk-row-content-"+t).find(".risk-category .cell-risk").html($(i).find(".risk-row-content-"+t).find(".risk-category .cell-risk").children()),$(".risk-row-content-"+t).find(".risk-category").fadeOut(800),$(".risk-row-content-"+t).find(".risk-category").fadeIn(800),$(".risk-row-content-"+t).find(".risk-description-"+t).fadeOut(800),$(".risk-row-content-"+t).find(".risk-description-"+t).fadeIn(800)):$(".risk-row-content-"+t).fadeOut(800,function(){$(".fichecenter .opacitymedium.colorblack.paddingleft").html($(i).find("#searchFormListRisks .opacitymedium.colorblack.paddingleft"))}),""),s=(s=(s+=e.find(".valueForEditRisk1").val())+d)+e.find(".valueForEditRisk2").val();e.find("a").attr("href","#risk_row_"+t),e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")},error:function(i){var e=$(".messageErrorRiskEdit"),s="",s=(s=(s+=e.find(".valueForEditRisk1").val())+d)+e.find(".valueForEditRisk2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})},window.digiriskdolibarr.risk.unlinkSharedRisk=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).attr("value"),t=(window.saturne.loader.display($(this)),$(".risk_row_"+s).find(".risk-container > div:nth-child(1)").text());var a=document.URL.split(/#/);$.ajax({url:a[0]+"&action=unlinkSharedRisk&token="+e,type:"POST",processData:!1,data:JSON.stringify({riskID:s}),contentType:!1,success:function(i){$(".confirmquestions").html($(i).find(".confirmquestions").children()),$(".fichecenter.sharedrisklist .opacitymedium.colorblack.paddingleft").html($(i).find("#searchFormSharedListRisks .opacitymedium.colorblack.paddingleft"));var i=$(".messageSuccessRiskUnlinkShared"),e=($("#risk_row_"+s).fadeOut(800),""),e=(e=(e+=i.find(".valueForUnlinkSharedRisk1").val())+t)+i.find(".valueForUnlinkSharedRisk2").val();i.find(".notice-subtitle .text").text(e),i.removeClass("hidden")},error:function(i){var e=$(".messageErrorRiskUnlinkShared"),s="",s=(s=(s+=e.find(".valueForUnlinkSharedRisk1").val())+t)+e.find(".valueForUnlinkSharedRisk2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})},window.digiriskdolibarr.risk.sharedRiskBoxLoader=function(i){"Oui"==$(this).text()&&window.saturne.loader.display($("#searchFormSharedListRisks"))},window.digiriskdolibarr.evaluation={},window.digiriskdolibarr.evaluation.init=function(){window.digiriskdolibarr.evaluation.event()},window.digiriskdolibarr.evaluation.event=function(){$(document).on("click",".select-evaluation-method",window.digiriskdolibarr.evaluation.selectEvaluationMethod),$(document).on("click",".cotation-container .risk-evaluation-cotation.cotation",window.digiriskdolibarr.evaluation.selectSeuil),$(document).on("click",".risk-evaluation-create",window.digiriskdolibarr.evaluation.createEvaluation),$(document).on("click",".risk-evaluation-save",window.digiriskdolibarr.evaluation.saveEvaluation),$(document).on("click",".risk-evaluation-delete",window.digiriskdolibarr.evaluation.deleteEvaluation)},window.digiriskdolibarr.evaluation.selectEvaluationMethod=function(i){var e=$(this).closest(".modal-container");0"+e.split(/\(/)[0]+"("+(+s-1)+")"),s-1<1&&$(".fichecenter.risklist").html($(i).find("#searchFormListRisks")),t.removeClass("wpeo-loader"),""),e=(e=(e+=r.find(".valueForDeleteEvaluation1").val())+n)+r.find(".valueForDeleteEvaluation2").val();r.find(".notice-subtitle .text").text(e),r.removeClass("hidden")},error:function(i){var e="",e=(e=(e+=o.find(".valueForDeleteEvaluation1").val())+n)+o.find(".valueForDeleteEvaluation2").val();o.find(".notice-subtitle .text").text(e),o.removeClass("hidden")}})}},window.digiriskdolibarr.evaluation.saveEvaluation=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).closest(".risk-evaluation-edit-modal"),t=s.attr("value");var a=s.find(".risk-evaluation-comment textarea").val();let n=$(this).closest(".risk-row").find(".risk-evaluations-list-content").attr("value"),r=$(".risk-evaluation-ref-"+t).attr("value"),o=$(".risk-evaluation-list-modal-"+n),d=$("#risk_evaluation_list"+n).hasClass("modal-active");var a=window.digiriskdolibarr.risk.sanitizeBeforeRequest(a),l=s.find(".risk-evaluation-method").val(),c=s.find(".risk-evaluation-seuil").val(),k=s.find("#RiskAssessmentDateEdit"+t).val(),u=s.find(".risk-evaluation-photo .filename").val();let m=[];Object.values($(".table-cell.active.cell-"+t)).forEach(function(i){-1<$(i).data("seuil")&&(m[$(i).data("type")]=$(i).data("seuil"))}),window.saturne.loader.display($(this)),$.ajax({url:document.URL+"&action=saveEvaluation&token="+e,type:"POST",processData:!1,data:JSON.stringify({cotation:c,comment:a,method:l,photo:u,date:k,evaluationID:t,criteres:{gravite:m.gravite||0,occurrence:m.occurrence||0,protection:m.protection||0,formation:m.formation||0,exposition:m.exposition||0}}),contentType:!1,success:function(i){$("#risk_evaluation_edit"+t).removeClass("modal-active"),0<$(i).find(".risk-evaluation-container.risk-evaluation-container-"+t+":not(.last-risk-assessment)").length?((d?($(".risk-evaluation-ref-"+t+":not(.last-risk-assessment)").fadeOut(800),$(".risk-evaluation-ref-"+t+":not(.last-risk-assessment)")):($(".risk-evaluation-container-"+t+":not(.last-risk-assessment)").fadeOut(800),$(".risk-evaluation-container-"+t+":not(.last-risk-assessment)"))).fadeIn(800),o.find(".risk-evaluation-ref-"+t).replaceWith($(i).find(".risk-evaluation-ref-"+t)),$(".risk-evaluation-container.risk-evaluation-container-"+t+":not(.last-risk-assessment)").replaceWith($(i).find(".risk-evaluation-container.risk-evaluation-container-"+t+":not(.last-risk-assessment)")),$("#risk_evaluation_add"+n).html($(i).find("#risk_evaluation_add"+n).children())):($(".div-table-responsive").html($(i).find(".div-table-responsive").children()),(d?($(".risk-evaluation-ref-"+t+":not(.last-risk-assessment)").fadeOut(800),$(".risk-evaluation-ref-"+t+":not(.last-risk-assessment)")):($(".risk-evaluation-container-"+t+":not(.last-risk-assessment)").fadeOut(800),$(".risk-evaluation-container-"+t+":not(.last-risk-assessment)"))).fadeIn(800)),$(".wpeo-loader").removeClass("wpeo-loader");var i=$(".messageSuccessEvaluationEdit"),e=(s.find("#risk_evaluation_edit"+t).removeClass("modal-active"),""),e=(e=(e+=i.find(".valueForEditEvaluation1").val())+r)+i.find(".valueForEditEvaluation2").val();i.find("a").attr("href","#risk_row_"+n),i.find(".notice-subtitle .text").text(e),i.removeClass("hidden")},error:function(){var i=$(".messageErrorEvaluationEdit"),e="",e=(e=(e+=i.find(".valueForEditEvaluation1").val())+r)+i.find(".valueForEditEvaluation2").val();i.find(".notice-subtitle .text").text(e),i.removeClass("hidden")}})},window.digiriskdolibarr.risksign={},window.digiriskdolibarr.risksign.init=function(){window.digiriskdolibarr.risksign.event()},window.digiriskdolibarr.risksign.event=function(){$(document).on("click",".risksign-category-danger .item, .wpeo-table .risksign-category-danger .item",window.digiriskdolibarr.risksign.selectRiskSign),$(document).on("click",".risksign-create:not(.button-disable)",window.digiriskdolibarr.risksign.createRiskSign),$(document).on("click",".risksign-save",window.digiriskdolibarr.risksign.saveRiskSign),$(document).on("click",".risksign-unlink-shared",window.digiriskdolibarr.risksign.unlinkSharedRiskSign)},window.digiriskdolibarr.risksign.selectRiskSign=function(i){var e=$(this),e=(e.closest(".content").removeClass("active"),e.closest(".wpeo-dropdown").find(".dropdown-toggle span").hide(),e.closest(".wpeo-dropdown").find(".dropdown-toggle img").show(),e.closest(".wpeo-dropdown").find(".dropdown-toggle img").attr("src",e.find("img").attr("src")),e.closest(".wpeo-dropdown").find(".dropdown-toggle img").attr("aria-label",e.closest(".wpeo-tooltip-event").attr("aria-label")),e.closest(".fichecenter").find(".input-hidden-danger").val(e.data("id")),$(this).closest(".modal-container"));window.digiriskdolibarr.risksign.haveDataInInput(e)},window.digiriskdolibarr.risksign.haveDataInInput=function(i){i=i.parent().parent();i.hasClass("risksign-add-modal")&&0<=i.find('input[name="risksign_category_id"]').val()&&i.find(".button-disable").removeClass("button-disable")},window.digiriskdolibarr.risksign.createRiskSign=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).closest(".fichecenter").find(".risksign-content"),t=s.find(".risksign-category input").val(),s=s.find(".risksign-description textarea").val();window.saturne.loader.display($(".fichecenter.risksignlist")),$.ajax({url:document.URL+"&action=add&token="+e,type:"POST",data:JSON.stringify({riskSignCategory:t,riskSignDescription:s}),processData:!1,contentType:!1,success:function(i){$(".fichecenter.risksignlist").html($(i).find("#searchFormListRiskSigns"));var e=$(".messageSuccessRiskSignCreate");$(".fichecenter.risksignlist").removeClass("wpeo-loader"),e.html($(i).find(".risksign-create-success-notice")),e.removeClass("hidden")},error:function(i){var e=$(".messageErrorRiskCreate");e.html($(i).find(".risksign-create-error-notice")),e.removeClass("hidden")}})},window.digiriskdolibarr.risksign.saveRiskSign=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).attr("value");let t=$(this).closest(".risksign-container").find(".risksign-content"),a="";var n=t.find(".risksign-category input").val(),r=t.find(".risksign-description textarea").val();let o=$(".risksign_row_"+s).find(".risksign-container > div:nth-child(1)").text();window.saturne.loader.display(t),$.ajax({url:document.URL+"&action=saveRiskSign&token="+e,data:JSON.stringify({riskSignID:s,riskSignCategory:n,riskSignDescription:r}),type:"POST",processData:!1,contentType:!1,success:function(i){$(".fichecenter.risksignlist").html($(i).find("#searchFormListRiskSigns"));i=$(".messageSuccessRiskSignEdit");t.removeClass("wpeo-loader"),a=(a=(a+=i.find(".valueForEditRiskSign1").val())+o)+i.find(".valueForEditRiskSign2").val(),i.find(".notice-subtitle .text").text(a),i.removeClass("hidden")},error:function(){var i=$(".messageErrorRiskSignEdit");t.removeClass("wpeo-loader"),a=(a=(a+=i.find(".valueForEditRiskSign1").val())+o)+i.find(".valueForEditRiskSign2").val(),i.find(".notice-subtitle .text").text(a),i.removeClass("hidden")}})},window.digiriskdolibarr.risksign.unlinkSharedRiskSign=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).attr("value"),t=(window.saturne.loader.display($(this)),$(".risksign_row_"+s).find(".risksign-container > div:nth-child(1)").text());var a=document.URL.split(/#/);$.ajax({url:a[0]+"&action=unlinkSharedRiskSign&token="+e,type:"POST",processData:!1,data:JSON.stringify({risksignID:s}),contentType:!1,success:function(i){$(".fichecenter.sharedrisksignlist .opacitymedium.colorblack.paddingleft").html($(i).find("#searchFormSharedListRiskSigns .opacitymedium.colorblack.paddingleft"));var i=$(".messageSuccessRiskSignUnlinkShared"),e=($("#risksign_row_"+s).fadeOut(800),""),e=(e=(e+=i.find(".valueForUnlinkSharedRiskSign1").val())+t)+i.find(".valueForUnlinkSharedRiskSign2").val();i.find(".notice-subtitle .text").text(e),i.removeClass("hidden")},error:function(i){var e=$(".messageErrorRiskSignUnlinkShared"),s="",s=(s=(s+=e.find(".valueForUnlinkSharedRiskSign1").val())+t)+e.find(".valueForUnlinkSharedRiskSign2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask={},window.digiriskdolibarr.riskassessmenttask.init=function(){window.digiriskdolibarr.riskassessmenttask.event()},window.digiriskdolibarr.riskassessmenttask.event=function(){$(document).on("input",".riskassessment-task-label",window.digiriskdolibarr.riskassessmenttask.fillRiskAssessmentTaskLabel),$(document).on("click",".riskassessment-task-create",window.digiriskdolibarr.riskassessmenttask.createRiskAssessmentTask),$(document).on("click",".riskassessment-task-save",window.digiriskdolibarr.riskassessmenttask.saveRiskAssessmentTask),$(document).on("click",".riskassessment-task-delete",window.digiriskdolibarr.riskassessmenttask.deleteRiskAssessmentTask),$(document).on("click",".riskassessment-task-timespent-create",window.digiriskdolibarr.riskassessmenttask.createRiskAssessmentTaskTimeSpent),$(document).on("click",".riskassessment-task-timespent-save",window.digiriskdolibarr.riskassessmenttask.saveRiskAssessmentTaskTimeSpent),$(document).on("click",".riskassessment-task-timespent-delete",window.digiriskdolibarr.riskassessmenttask.deleteRiskAssessmentTaskTimeSpent),$(document).on("click",".riskassessment-task-progress-checkbox:not(.riskassessment-task-progress-checkbox-readonly)",window.digiriskdolibarr.riskassessmenttask.checkTaskProgress),$(document).on("change","#RiskassessmentTaskTimespentDatehour",window.digiriskdolibarr.riskassessmenttask.selectRiskassessmentTaskTimespentDateHour),$(document).on("change","#RiskassessmentTaskTimespentDatemin",window.digiriskdolibarr.riskassessmenttask.selectRiskassessmentTaskTimespentDateMin),$(document).on("keyup",".riskassessment-task-label",window.digiriskdolibarr.riskassessmenttask.checkRiskassessmentTaskLabelLength),$(document).on("click",".listingHeaderTaskTooltip",window.digiriskdolibarr.riskassessmenttask.redirectOnSharedTaskConfig)},window.digiriskdolibarr.riskassessmenttask.fillRiskAssessmentTaskLabel=function(i){var e=$(this).closest(".modal-container");window.digiriskdolibarr.riskassessmenttask.haveDataInInput(e)},window.digiriskdolibarr.riskassessmenttask.haveDataInInput=function(i){i=i.parent().parent();i.hasClass("riskassessment-task-add-modal")&&i.find('input[name="label"]').val().length&&i.find(".button-disable").removeClass("button-disable")},window.digiriskdolibarr.riskassessmenttask.createRiskAssessmentTask=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).closest(".riskassessment-task-add-modal"),t=s.find(".modal-risk").attr("value"),s=s.find(".riskassessment-task-container"),a=s.find(".riskassessment-task-label").val(),a=window.digiriskdolibarr.risk.sanitizeBeforeRequest(a),n=s.find("#RiskassessmentTaskDateStart"+t).val(),r=s.find("#RiskassessmentTaskDateStart"+t+"hour").val(),o=s.find("#RiskassessmentTaskDateStart"+t+"min").val(),d=s.find("#RiskassessmentTaskDateEnd"+t).val(),l=s.find("#RiskassessmentTaskDateEnd"+t+"hour").val(),c=s.find("#RiskassessmentTaskDateEnd"+t+"min").val(),s=s.find(".riskassessment-task-budget").val();window.saturne.loader.display($(this)),window.saturne.loader.display($(".riskassessment-tasks"+t)),$.ajax({url:document.URL+"&action=addRiskAssessmentTask&token="+e,type:"POST",data:JSON.stringify({tasktitle:a,dateStart:n,hourStart:r,minStart:o,dateEnd:d,hourEnd:l,minEnd:c,budget:s,riskToAssign:t}),processData:!1,contentType:!1,success:function(i){$(".tasks-list-container-"+t).replaceWith($(i).find(".tasks-list-container-"+t));var e=$(".messageSuccessTaskCreate");$(".riskassessment-tasks"+t).fadeOut(800),$(".riskassessment-tasks"+t).fadeIn(800),e.find("a").attr("href","#risk_row_"+t),e.html($(i).find(".task-create-success-notice")),e.removeClass("hidden")},error:function(i){$(".wpeo-loader").removeClass("wpeo-loader"),window.scrollTo(0,0);var i=JSON.parse(i.responseText),e=$(".messageErrorTaskCreate"),s=($("#risk_assessment_task_add"+t).removeClass("modal-active"),""),s=(s=(s+=e.find(".valueForCreateTask1").val())+e.find(".valueForCreateTask2").val())+" : "+i.message;e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask.deleteRiskAssessmentTask=function(i){var e=window.saturne.toolbox.getToken(),t=$(this).closest(".wpeo-table.riskassessment-tasks").attr("value"),a=$(this).closest(".riskassessment-task-single-content").attr("value"),s=$(this).closest(".riskassessment-task-container-"+a).find(".labelForDelete").val();let n=$(".messageSuccessTaskDelete"),r=$(".messageErrorTaskDelete");if(1!=confirm(s))return!1;{let s=$(".riskassessment-task-container-"+a).attr("value");window.saturne.loader.display($(".riskassessment-task-container-"+a)),$.ajax({url:document.URL+"&action=deleteRiskAssessmentTask&deletedRiskAssessmentTaskId="+a+"&token="+e,type:"POST",processData:!1,contentType:!1,success:function(i){console.log($(".riskassessment-task-listing-wrapper-"+t)),console.log(t),$(".riskassessment-task-listing-wrapper-"+t).replaceWith($(i).find(".riskassessment-task-listing-wrapper-"+t)),$(".riskassessment-tasks"+t).fadeOut(800),$(".riskassessment-tasks"+t).fadeIn(800);i="",i=(i=(i+=n.find(".valueForDeleteTask1").val())+s)+n.find(".valueForDeleteTask2").val();n.find("a").attr("href","#risk_row_"+t),n.find(".notice-subtitle .text").text(i),n.removeClass("hidden")},error:function(i){$(".wpeo-loader").removeClass("wpeo-loader"),window.scrollTo(0,0);var i=JSON.parse(i.responseText),e="",e=(e=(e=(e+=r.find(".valueForDeleteTask1").val())+s)+r.find(".valueForDeleteTask2").val())+" : "+i.message;r.find(".notice-subtitle .text").text(e),r.removeClass("hidden")}})}},window.digiriskdolibarr.riskassessmenttask.saveRiskAssessmentTask=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).attr("value");var t=$(this).closest(".modal-container"),a=$(this).closest(".modal-risk").attr("value");let n="";var r=t.find(".riskassessment-task-label"+s).val(),r=window.digiriskdolibarr.risk.sanitizeBeforeRequest(r);let o=$(".riskassessment-task-single-"+s+" .riskassessment-task-reference").attr("value"),d=0;t.find(".riskassessment-task-progress-checkbox"+s).is(":checked")&&(d=1);var l=t.find("#RiskassessmentTaskDateStartEdit"+s).val(),c=t.find("#RiskassessmentTaskDateStartEdit"+s+"hour").val(),k=t.find("#RiskassessmentTaskDateStartEdit"+s+"min").val(),u=t.find("#RiskassessmentTaskDateEndEdit"+s).val(),m=t.find("#RiskassessmentTaskDateEndEdit"+s+"hour").val(),v=t.find("#RiskassessmentTaskDateEndEdit"+s+"min").val(),t=t.find(".riskassessment-task-budget"+s).val();window.saturne.loader.display($(this)),window.saturne.loader.display($(".riskassessment-task-single-"+s)),$.ajax({url:document.URL+"&action=saveRiskAssessmentTask&token="+e,data:JSON.stringify({riskAssessmentTaskID:s,tasktitle:r,dateStart:l,hourStart:c,minStart:k,dateEnd:u,hourEnd:m,minEnd:v,budget:t,taskProgress:d}),type:"POST",processData:!1,contentType:!1,success:function(i){$("#risk_assessment_task_edit"+s).removeClass("modal-active"),$(".riskassessment-task-container-"+s).replaceWith($(i).find(".riskassessment-task-container-"+s).first());i=$(".messageSuccessTaskEdit");$(".riskassessment-tasks"+a).fadeOut(800),$(".riskassessment-tasks"+a).fadeIn(800),n=(n=(n+=i.find(".valueForEditTask1").val())+o)+i.find(".valueForEditTask2").val(),$(".wpeo-loader").removeClass("wpeo-loader"),$(".loader-spin").remove(),i.find("a").attr("href","#risk_row_"+a),i.find(".notice-subtitle .text").text(n),i.removeClass("hidden")},error:function(i){$(".wpeo-loader").removeClass("wpeo-loader"),window.scrollTo(0,0);var i=JSON.parse(i.responseText),e=$(".messageErrorTaskEdit");$("#risk_assessment_task_edit"+s).removeClass("modal-active"),$(".wpeo-loader").removeClass("wpeo-loader"),n=(n=(n=(n+=e.find(".valueForEditTask1").val())+o)+e.find(".valueForEditTask2").val()+" : ")+i.message,e.find(".notice-subtitle .text").text(n),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask.createRiskAssessmentTaskTimeSpent=function(i){var e=window.saturne.toolbox.getToken();let s=$(this).attr("value");var t=$(this).closest(".riskassessment-task-edit-modal"),a=t.find(".riskassessment-task-timespent-container");let n=t.find("riskassessment-task-single").attr("value"),r="",o=t.find(".riskassessment-task-reference").attr("value"),d=$(".id-container").find(".riskassessment-total-task-timespent-"+s);var t=a.find("#RiskassessmentTaskTimespentDate"+s).val(),l=a.find("#RiskassessmentTaskTimespentDate"+s+"hour").val(),c=a.find("#RiskassessmentTaskTimespentDate"+s+"min").val(),k=a.find(".riskassessment-task-timespent-comment").val(),k=window.digiriskdolibarr.risk.sanitizeBeforeRequest(k),a=a.find(".riskassessment-task-timespent-duration").val();window.saturne.loader.display($(this)),window.saturne.loader.display($(".riskassessment-task-single-"+s)),$.ajax({url:document.URL+"&action=addRiskAssessmentTaskTimeSpent&token="+e,type:"POST",data:JSON.stringify({taskID:s,date:t,hour:l,min:c,comment:k,duration:a}),processData:!1,contentType:!1,success:function(i){var e=$(".messageSuccessTaskTimeSpentCreate"+s);$(".riskassessment-tasks"+n).fadeOut(800),$(".riskassessment-tasks"+n).fadeIn(800),r=(r=(r+=e.find(".valueForCreateTaskTimeSpent1").val())+o)+e.find(".valueForCreateTaskTimeSpent2").val(),$(".riskassessment-task-timespent-container").find(".riskassessment-task-timespent-list-"+s).replaceWith($(i).find(".riskassessment-task-timespent-container").find(".riskassessment-task-timespent-list-"+s)),$(".riskassessment-task-container-"+s).closest(".riskassessment-tasks").replaceWith($(i).find(".riskassessment-task-container-"+s).closest(".riskassessment-tasks")),$(".loader-spin").remove(),$(".wpeo-loader").removeClass("wpeo-loader"),e.find(".notice-subtitle .text").text(r),e.removeClass("hidden"),d.html($(i).find(".modal-content").find(".riskassessment-total-task-timespent-"+s).first())},error:function(i){$(this).closest(".risk-row-content-"+n).removeClass("wpeo-loader");var e=$(".messageErrorTaskTimeSpentCreate"+s);e.html($(i).find(".task-timespent-create-error-notice")),e.removeClass("hidden")},complete:function(){$("#risk_assessment_task_edit"+s+".wpeo-modal").addClass("modal-active")}})},window.digiriskdolibarr.riskassessmenttask.deleteRiskAssessmentTaskTimeSpent=function(i){var e=window.saturne.toolbox.getToken();let a=$(this).closest(".riskassessment-task-timespent-list").attr("value"),n=$(this).attr("value");var s=$(this).attr("value"),t=$(this).closest(".riskassessment-task-timespent-"+n).find(".labelForDelete").val();let r=$(".id-container").first().find(".riskassessment-total-task-timespent-"+a);if(1!=confirm(t))return!1;{let t=$(".riskassessment-task-container-"+a).attr("value");window.saturne.loader.display($(this)),$.ajax({url:document.URL+"&action=deleteRiskAssessmentTaskTimeSpent&deletedRiskAssessmentTaskTimeSpentId="+s+"&token="+e,type:"POST",processData:!1,contentType:!1,success:function(i){var e=$(".messageSuccessTaskTimeSpentDelete"+a),s=($(".riskassessment-task-timespent-"+n).fadeOut(800),""),s=(s=(s+=e.find(".valueForDeleteTaskTimeSpent1").val())+t)+e.find(".valueForDeleteTaskTimeSpent2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden"),r.html($(i).find(".modal-content").find(".riskassessment-total-task-timespent-"+a).first())},error:function(i){var e=$(".messageErrorTaskDeleteTimeSpent"+a),s="",s=(s=(s+=e.find(".valueForDeleteTaskTimeSpent1").val())+t)+e.find(".valueForDeleteTaskTimeSpent2").val();e.find(".notice-subtitle .text").text(s),e.removeClass("hidden")}})}},window.digiriskdolibarr.riskassessmenttask.saveRiskAssessmentTaskTimeSpent=function(i){var e=window.saturne.toolbox.getToken();let s=$(this);var t=$(this).attr("value"),a=$(this).closest(".riskassessment-task-timespent-edit-modal").find(".riskassessment-task-timespent-container");let n=a.attr("value"),r="",o=$(".riskassessment-task-container-"+n).attr("value"),d=$(".id-container").first().find(".riskassessment-total-task-timespent-"+n);var l=a.find("#RiskassessmentTaskTimespentDateEdit"+t).val(),c=a.find("#RiskassessmentTaskTimespentDateEdit"+t+"hour").val(),k=a.find("#RiskassessmentTaskTimespentDateEdit"+t+"min").val(),u=a.find(".riskassessment-task-timespent-comment").val(),u=window.digiriskdolibarr.risk.sanitizeBeforeRequest(u),a=a.find(".riskassessment-task-timespent-duration").val();window.saturne.loader.display($(this)),window.saturne.loader.display($(".riskassessment-task-single-"+n)),$.ajax({url:document.URL+"&action=saveRiskAssessmentTaskTimeSpent&token="+e,data:JSON.stringify({riskAssessmentTaskTimeSpentID:t,taskID:n,date:l,hour:c,min:k,comment:u,duration:a}),type:"POST",processData:!1,contentType:!1,success:function(i){s.closest(".modal-active").removeClass("modal-active");var e=$(".messageSuccessTaskTimeSpentEdit"+n);$(".wpeo-loader").removeClass("wpeo-loader"),r=(r=(r+=e.find(".valueForEditTaskTimeSpent1").val())+o)+e.find(".valueForEditTaskTimeSpent2").val(),d.html($(i).find(".modal-content").find(".riskassessment-total-task-timespent-"+n).first()),$(".riskassessment-task-timespent-list-"+n).html($(i).find(".riskassessment-task-timespent-list-"+n).children()),e.find(".notice-subtitle .text").text(r),e.removeClass("hidden")},error:function(i){var e=$(".messageSuccessTaskTimeSpentEdit"+n);r=(r=(r+=e.find(".valueForEditTaskTimeSpent1").val())+o)+e.find(".valueForEditTaskTimeSpent2").val(),e.find(".notice-subtitle .text").text(r),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask.checkTaskProgress=function(i){var e=window.saturne.toolbox.getToken(),s=$(this).closest(".risk-row").find(".riskassessment-task-container"),t=s.find(".riskassessment-task-single-content").attr("value");let a=$(this).closest(".riskassessment-tasks").attr("value"),n="",r=s.attr("value"),o="";s.find(".riskassessment-task-progress-checkbox"+t).hasClass("progress-checkbox-check")?(o=0,s.find(".riskassessment-task-progress-checkbox"+t).toggleClass("progress-checkbox-check").toggleClass("progress-checkbox-uncheck")):s.find(".riskassessment-task-progress-checkbox"+t).hasClass("progress-checkbox-uncheck")&&(o=1,s.find(".riskassessment-task-progress-checkbox"+t).toggleClass("progress-checkbox-uncheck").toggleClass("progress-checkbox-check")),window.saturne.loader.display($(".riskassessment-task-single-"+t));s=window.location.href.replace(/#.*/,"");$.ajax({url:s+"&action=checkTaskProgress&token="+e,data:JSON.stringify({riskAssessmentTaskID:t,taskProgress:o}),type:"POST",processData:!1,contentType:!1,success:function(i){$(".fichecenter.risklist").html($(i).find("#searchFormListRisks"));i=$(".messageSuccessTaskEdit");$(".riskassessment-tasks"+a).fadeOut(800),$(".riskassessment-tasks"+a).fadeIn(800),n=(n=(n+=i.find(".valueForEditTask1").val())+r)+i.find(".valueForEditTask2").val(),i.find(".notice-subtitle .text").text(n),i.removeClass("hidden")},error:function(i){var e=$(".messageErrorTaskEdit");n=(n=(n+=e.find(".valueForEditTask1").val())+r)+e.find(".valueForEditTask2").val(),e.find(".notice-subtitle .text").text(n),e.removeClass("hidden")}})},window.digiriskdolibarr.riskassessmenttask.selectRiskassessmentTaskTimespentDateHour=function(i){$(this).closest(".nowraponall").find(".select-riskassessmenttask-timespent-datehour").remove(),$(this).before('{$("#sendFileForm").load(document.URL+n+"ticket_id="+a+" #fileLinkedTable")})},window.digiriskdolibarr.ticket.removeFile=function(i){let e=$(this).attr("value");e=e.replace("_mini","");var s=$("#ticket_id").val(),t=window.saturne.toolbox.getQuerySeparator(document.URL);fetch(document.URL+t+"action=removefile&filetodelete="+e+"&ticket_id="+s,{method:"POST"}).then(i=>{$(this).parent().parent().hide()})},window.digiriskdolibarr.ticket.addDashBoardTicketInfo=function(){var i=window.saturne.toolbox.getToken(),e=$("#select2-boxcombo-container").attr("title"),s=e.split(" : ")[0],e=e.split(" : ")[2],t=window.saturne.toolbox.getQuerySeparator(document.URL);$.ajax({url:document.URL+t+"action=adddashboardinfo&token="+i,type:"POST",processData:!1,data:JSON.stringify({digiriskelementID:s,catID:e}),contentType:!1,success:function(i){window.location.reload()},error:function(){}})},window.digiriskdolibarr.ticket.closeDashBoardTicketInfo=function(){var i=window.saturne.toolbox.getToken();let e=$(this);var s=e.attr("data-digiriskelementid"),t=e.attr("data-catid"),a=window.saturne.toolbox.getQuerySeparator(document.URL);$.ajax({url:document.URL+a+"action=closedashboardinfo&token="+i,type:"POST",processData:!1,data:JSON.stringify({digiriskelementID:s,catID:t}),contentType:!1,success:function(i){e.closest(".box-flex-item").fadeOut(400),$(".add-widget-box").attr("style",""),$(".add-widget-box").html($(i).find(".add-widget-box").children())},error:function(){}})},window.digiriskdolibarr.ticket.checkValidEmail=function(){0==/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(this.value)?$(this).css("border","3px solid red"):$(this).css("border","3px solid green")},window.digiriskdolibarr.ticket.checkValidPhone=function(){0==/^(?:(?:(?:\+|00)\d{2}[\s]?(?:\(0\)[\s]?)?)|0){1}[1-9]{1}([\s.-]?)(?:\d{2}\1?){3}\d{2}$/.test(this.value)?$(this).css("border","3px solid red"):$(this).css("border","3px solid green")},window.digiriskdolibarr.digiriskusers={},window.digiriskdolibarr.digiriskusers.init=function(){window.digiriskdolibarr.digiriskusers.event()},window.digiriskdolibarr.digiriskusers.event=function(){$(document).on("input",".digirisk-users #firstname",window.digiriskdolibarr.digiriskusers.fillEmail),$(document).on("input",".digirisk-users #lastname",window.digiriskdolibarr.digiriskusers.fillEmail)},window.digiriskdolibarr.digiriskusers.fillEmail=function(i){var e=$(".digirisk-users #firstname").val(),s=$(".digirisk-users #lastname").val(),t=$(".input-domain-mail").val(),e=window.digiriskdolibarr.digiriskusers.removeDiacritics(e+"."+s+"@"+t).toLowerCase();$(".digirisk-users #email").val(e)},window.digiriskdolibarr.digiriskusers.removeDiacritics=function(i){for(var e="",s=i.normalize("NFD"),t=0,a=0;ttous les participants et les signatures actuelles du document seront perdues.
Une nouvelle version du document sera généré par la suite.. AccidentInvestigationCreated = Création d'une enquête accident AccidentInvestigationModified = Modifcation d'une enquête accident AccidentInvestigationDeleted = Suppression d'une enquête accident AccidentInvestigationValidate = Validation d'une enquête accident AccidentInvestigationUnValidate = Réouverture d'une enquête accident -AccidentInvestigationArchive = Classification d'une enquête accident AccidentInvestigationLock = Verrouillage de l'enquête accident AccidentInvestigationSigned = Signature d'une enquête accident CloneWorkStop = Cloner les arrêts de travail ? @@ -572,6 +578,9 @@ ClonePhotos = Cloner les photos ? CloneFrom = Clone de AccidentInvestigationLinked = Enquête accident liée AccidentInvestigationRole = Les rôles de l'enquête accident +LesionsOrWorkStop = lésions ou arrêts de travail +AccidentsCategoriesArea = Espace des tags/catégories des accidents +AddAccidentIntoCategory = Assigner cette catégorie à l'accident # AccidentTooltip - Tooltip des accidents VictimActivityTooltip = Précisez l’activité ou la tâche de la victime au moment de l’accident, c’est-à-dire ce que faisait la victime @@ -1237,20 +1246,34 @@ TicketLocationVisibleHelp = Activer cette option pour afficher le TicketDateVisible = Afficher le champ Date pour créer un ticket TicketDateVisibleHelp = Activer cette option pour afficher le champ Date dans l'interface publique et le rendre obligatoire si nécessaire QRCodeGenerated = QRCode généré +FkTicket = Ticket lié + # Stats - Statistiques -TicketStatistics = Statistiques des tickets -ExportCSV = Export CSV -GenerateCSV = Générer le fichier CSV -SuccessGenerateCSV = Fichier CSV %s généré avec succès -ErrorMissingData = Erreur : impossible de générer le fichier CSV, les données envoyées au fichier sont incorrecte.
Veuillez vérifier que vous avez bien des GP/UT assignés à des tickets. -CSVFileExport = Export des registres au format CSV associé à des GP/UT -ThirdPartyHelp = Si le filtre "Tiers" est vide, aucun tiers n'est utilisé pour la recherche -GP/UTHelp = Par défaut, le filtre prend toutes les GP/UT -CategoryTicketHelp = Par défaut, le filtre prend toutes les catégories -CreatedByHelp = Si le filtre "Créer par" est vide, aucun utilisateur n'est utilisé pour la recherche -AssignedToHelp = Si le filtre "Assigné à" est vide, aucun utilisateur n'est utilisé pour la recherche -StatusHelp = Par défaut, le filtre prend tous les états
+TicketStatistics = Statistiques des tickets +ExportCSV = Export CSV +GenerateCSV = Générer le fichier CSV +SuccessGenerateCSV = Fichier CSV %s généré avec succès +ErrorMissingData = Erreur : impossible de générer le fichier CSV, les données envoyées au fichier sont incorrecte.
Veuillez vérifier que vous avez bien des GP/UT assignés à des tickets. +CSVFileExport = Export des registres au format CSV associé à des GP/UT +ThirdPartyHelp = Si le filtre "Tiers" est vide, aucun tiers n'est utilisé pour la recherche +GP/UTHelp = Par défaut, le filtre prend toutes les GP/UT +CategoryTicketHelp = Par défaut, le filtre prend toutes les catégories +CreatedByHelp = Si le filtre "Créer par" est vide, aucun utilisateur n'est utilisé pour la recherche +AssignedToHelp = Si le filtre "Assigné à" est vide, aucun utilisateur n'est utilisé pour la recherche +StatusHelp = Par défaut, le filtre prend tous les états
+ConcernedTimePeriod = Période prise en compte +LessThan = Moins de +MoreThan = Plus de +Comparator = Comparateur +RangeNumber = Quantité +TimeRange = Unité de temps +RangeLabel = Nom de la contrainte +Inferior = Inférieur à +Superior = Supérieur à +TimeRangeAdded = Contrainte ajoutée +TimeRangeDeleted = Contrainte supprimée + # Email - Email The = Le @@ -1278,6 +1301,11 @@ TicketSuccessMessageSet = Le message a bien été modifié DigiriskTemplateDocumentProject = Modèle de documents des fiches de projets de Digirisk DocumentModelOrque = Modèles de document de rapport prévisionnel sur les tâches de projets +# Register Document + +RegisterDocument = Registre des accidents bénins +RegisterDocumentsMin = registres des accidents bénins +registerdocument.odt = Registre des accidents bénins # # Tools - Outils diff --git a/lib/digiriskdolibarr_accident.lib.php b/lib/digiriskdolibarr_accident.lib.php index eafa4724c..23f5d5611 100644 --- a/lib/digiriskdolibarr_accident.lib.php +++ b/lib/digiriskdolibarr_accident.lib.php @@ -44,14 +44,10 @@ function accident_prepare_head(Accident $object): array $head[$h][0] = dol_buildpath('/digiriskdolibarr/view/accident/accident_metadata.php', 1) . '?id=' . $object->id; $head[$h][1] = $conf->browser->layout != 'phone' ? '' . $langs->trans('AccidentMetaData') : ''; $head[$h][2] = 'accidentMetadata'; - $h++; - - $head[$h][0] = dol_buildpath('/digiriskdolibarr/view/accident/accident_metadata_lesion.php', 1) . '?id=' . $object->id; - $head[$h][1] = $conf->browser->layout != 'phone' ? '' . $langs->trans('AccidentMetaDataLesion') : ''; - $head[$h][2] = 'accidentMetadataLesion'; } - $moreParams['attendantTableMode'] = 'simple'; + $moreParams['attendantTableMode'] = 'advanced'; + $moreParams['attendantTabName'] = $langs->trans('VictimAndCaregivers'); - return saturne_object_prepare_head($object, $head, $moreParams); + return saturne_object_prepare_head($object, $head, $moreParams, true); } diff --git a/lib/digiriskdolibarr_digiriskstandard.lib.php b/lib/digiriskdolibarr_digiriskstandard.lib.php index b8dca3cc9..bdf98b72a 100644 --- a/lib/digiriskdolibarr_digiriskstandard.lib.php +++ b/lib/digiriskdolibarr_digiriskstandard.lib.php @@ -59,6 +59,13 @@ function digiriskstandard_prepare_head(DigiriskStandard $object): array $h++; } + if ($user->rights->ticket->read) { + $head[$h][0] = dol_buildpath('/digiriskdolibarr/view/digiriskstandard/digiriskstandard_registerdocument.php', 1); + $head[$h][1] = $conf->browser->layout != 'phone' ? '' . $langs->trans('RegisterDocument') : ''; + $head[$h][2] = 'standardRegisterDocument'; + $h++; + } + if ($user->rights->digiriskdolibarr->listingrisksaction->read) { $head[$h][0] = dol_buildpath('/digiriskdolibarr/view/digiriskelement/digiriskelement_listingrisksaction.php', 1) . '?type=standard'; $head[$h][1] = $conf->browser->layout != 'phone' ? '' . $langs->trans('ListingRisksAction') : ''; diff --git a/lib/digiriskdolibarr_function.lib.php b/lib/digiriskdolibarr_function.lib.php index 1fd4dcc2f..723604043 100644 --- a/lib/digiriskdolibarr_function.lib.php +++ b/lib/digiriskdolibarr_function.lib.php @@ -2073,6 +2073,7 @@ function load_board($user, $cat, $digiriskelement) if ($allObjects > 0) { $response = new WorkboardResponse(); $response->id = $cat['id']; + $response->color = $cat['color']; $response->img = $cat['photo']; $response->label = $cat['name'] . ' : '; $response->url = DOL_URL_ROOT . '/ticket/list.php?search_options_digiriskdolibarr_ticket_service='.$digiriskelement->id.'&search_category_ticket_list='.$cat['id']; diff --git a/sql/accident/llx_categorie_accident.key.sql b/sql/accident/llx_categorie_accident.key.sql new file mode 100644 index 000000000..fc0ae1108 --- /dev/null +++ b/sql/accident/llx_categorie_accident.key.sql @@ -0,0 +1,20 @@ +-- Copyright (C) 2021-2023 EVARISK +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see https://www.gnu.org/licenses/. + +ALTER TABLE llx_categorie_accident ADD PRIMARY KEY pk_categorie_accident (fk_categorie, fk_accident); +ALTER TABLE llx_categorie_accident ADD INDEX idx_categorie_accident_fk_categorie (fk_categorie); +ALTER TABLE llx_categorie_accident ADD INDEX idx_categorie_accident_fk_accident (fk_accident); +ALTER TABLE llx_categorie_accident ADD CONSTRAINT fk_categorie_accident_rowid FOREIGN KEY (fk_categorie) REFERENCES llx_categorie (rowid); +ALTER TABLE llx_categorie_accident ADD CONSTRAINT llx_categorie_accident_digiriskdolibarr_accident_rowid FOREIGN KEY (fk_accident) REFERENCES llx_digiriskdolibarr_accident (rowid); diff --git a/sql/accident/llx_categorie_accident.sql b/sql/accident/llx_categorie_accident.sql new file mode 100644 index 000000000..7bd9b738f --- /dev/null +++ b/sql/accident/llx_categorie_accident.sql @@ -0,0 +1,20 @@ +-- Copyright (C) 2021-2023 EVARISK +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see https://www.gnu.org/licenses/. + +CREATE TABLE llx_categorie_accident( + fk_categorie integer NOT NULL, + fk_accident integer NOT NULL, + import_key varchar(14) +) ENGINE=innodb; diff --git a/sql/accident/llx_digiriskdolibarr_accident.sql b/sql/accident/llx_digiriskdolibarr_accident.sql index a5ca41db6..8866d3831 100644 --- a/sql/accident/llx_digiriskdolibarr_accident.sql +++ b/sql/accident/llx_digiriskdolibarr_accident.sql @@ -28,12 +28,12 @@ CREATE TABLE llx_digiriskdolibarr_accident( accident_type text, external_accident smallint DEFAULT 1, accident_location text, - fk_project integer, + fk_project integer, + fk_ticket integer, fk_user_creat integer NOT NULL, fk_user_modif integer, fk_element integer, fk_standard integer, fk_soc integer, - fk_user_victim integer, fk_user_employer integer ) ENGINE=innodb; diff --git a/sql/data.sql b/sql/data.sql index 292164942..916442a16 100644 --- a/sql/data.sql +++ b/sql/data.sql @@ -899,3 +899,7 @@ INSERT INTO llx_c_digiriskdolibarr_action_trigger (entity, elementtype, ref, lab INSERT INTO llx_c_digiriskdolibarr_action_trigger (entity, elementtype, ref, label, description, active, position) VALUES (0, 'task@digiriskdolibarr', 'TASK_TIMESPENT_CREATE', 'TaskTimeSpentCreated', 'Executed when a task timespent is created', 1, 700); INSERT INTO llx_c_digiriskdolibarr_action_trigger (entity, elementtype, ref, label, description, active, position) VALUES (0, 'task@digiriskdolibarr', 'TASK_TIMESPENT_MODIFY', 'TaskTimeSpentModified', 'Executed when a task timespent is modified', 1, 710); INSERT INTO llx_c_digiriskdolibarr_action_trigger (entity, elementtype, ref, label, description, active, position) VALUES (0, 'task@digiriskdolibarr', 'TASK_TIMESPENT_DELETE', 'TaskTimeSpentDeleted', 'Executed when a task timespent is deleted', 1, 720); + +-- 9.14.0 +INSERT INTO `llx_c_accident_attendants_role` (`rowid`, `entity`, `ref`, `label`, `description`, `active`, `position`) VALUES (1, 0, 'Victim', 'Victim', '', 1, 1); +INSERT INTO `llx_c_accident_attendants_role` (`rowid`, `entity`, `ref`, `label`, `description`, `active`, `position`) VALUES (2, 0, 'Caregiver', 'Caregiver', '', 1, 10); diff --git a/sql/llx_c_accident_attendants_role.sql b/sql/llx_c_accident_attendants_role.sql new file mode 100644 index 000000000..f0aa21429 --- /dev/null +++ b/sql/llx_c_accident_attendants_role.sql @@ -0,0 +1,24 @@ +-- Copyright (C) 2021-2023 EVARISK +-- +-- This program is free software: you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program. If not, see https://www.gnu.org/licenses/. + +CREATE TABLE llx_c_accident_attendants_role( + rowid integer AUTO_INCREMENT PRIMARY KEY NOT NULL, + entity integer default 1, + ref varchar(128), + label varchar(255), + description text, + active tinyint(4) DEFAULT 1, + position integer DEFAULT 0 +) ENGINE=innodb; diff --git a/sql/update.sql b/sql/update.sql index 4375e5426..44d78165d 100644 --- a/sql/update.sql +++ b/sql/update.sql @@ -235,3 +235,9 @@ INSERT INTO llx_c_accidentinvestigation_attendants_role SELECT * FROM llx_c_acci INSERT INTO llx_categorie_accidentinvestigation SELECT * FROM llx_categorie_accident_investigation; DROP TABLE llx_c_accident_investigation_attendants_role; DROP TABLE llx_categorie_accident_investigation; + +-- 9.14.0 +UPDATE llx_digiriskdolibarr_risk SET category = 21 WHERE category = 20; +UPDATE llx_digiriskdolibarr_risk SET category = 22 WHERE category = 21; +ALTER TABLE llx_digiriskdolibarr_accident ADD fk_ticket integer; +ALTER TABLE llx_digiriskdolibarr_accident DROP COLUMN fk_user_victim; diff --git a/view/accident/accident_card.php b/view/accident/accident_card.php index 046b3246c..6115d861d 100644 --- a/view/accident/accident_card.php +++ b/view/accident/accident_card.php @@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once __DIR__ . '/../../class/digiriskelement.class.php'; require_once __DIR__ . '/../../class/accident.class.php'; @@ -68,6 +70,7 @@ $object = new Accident($db); $signatory = new SaturneSignature($db, $object->module, $object->element); $objectline = new AccidentWorkStop($db); +$accidentLesion = new AccidentLesion($db); $contact = new Contact($db); $usertmp = new User($db); $thirdparty = new Societe($db); @@ -75,6 +78,7 @@ $digiriskelement = new DigiriskElement($db); $digiriskstandard = new DigiriskStandard($db); $project = new Project($db); +$ticket = new Ticket($db); // Load object $object->fetch($id); @@ -89,11 +93,12 @@ // Load numbering modules $numberingModules = [ - 'digiriskelement/' . $object->element => $conf->global->DIGIRISKDOLIBARR_ACCIDENT_ADDON, - 'digiriskelement/' . $objectline->element => $conf->global->DIGIRISKDOLIBARR_ACCIDENTWORKSTOP_ADDON, + 'digiriskelement/' . $object->element => $conf->global->DIGIRISKDOLIBARR_ACCIDENT_ADDON, + 'digiriskelement/' . $objectline->element => $conf->global->DIGIRISKDOLIBARR_ACCIDENTWORKSTOP_ADDON, + 'digiriskelement/' . $accidentLesion->element => $conf->global->DIGIRISKDOLIBARR_ACCIDENTLESION_ADDON, ]; -list($refAccidentMod, $refAccidentWorkStopMod) = saturne_require_objects_mod($numberingModules, $moduleNameLowerCase); +list($refAccidentMod, $refAccidentWorkStopMod, $refAccidentLesion) = saturne_require_objects_mod($numberingModules, $moduleNameLowerCase); $hookmanager->initHooks(['accidentcard', 'globalcard']); // Note that conf->hooks_modules contains array @@ -148,22 +153,24 @@ $accident_type = GETPOST('accident_type'); $external_accident = GETPOST('external_accident'); $accident_location = GETPOST('accident_location'); - $extSocietyId = GETPOST('fk_soc'); + $extSocietyId = GETPOST('fk_soc'); + $fkTicket = GETPOST('fk_ticket'); - // Initialize object accident + // Initialize object accident $now = dol_now(); $object->ref = $object->getNextNumRef(); $object->ref_ext = 'digirisk_' . $object->ref; $object->date_creation = $object->db->idate($now); $object->tms = $now; $object->import_key = ""; - $object->status = Accident::STATUS_VALIDATED; + $object->status = Accident::STATUS_DRAFT; $object->label = $label; $object->description = $description; $object->accident_type = $accident_type; $object->external_accident = $external_accident; $object->accident_location = $accident_location; - $object->fk_project = $conf->global->DIGIRISKDOLIBARR_ACCIDENT_PROJECT; + $object->fk_project = $conf->global->DIGIRISKDOLIBARR_ACCIDENT_PROJECT; + $object->fk_ticket = $fkTicket; $accident_date = dol_mktime(GETPOST('dateohour', 'int'), GETPOST('dateomin', 'int'), 0, GETPOST('dateomonth', 'int'), GETPOST('dateoday', 'int'), GETPOST('dateoyear', 'int')); @@ -196,7 +203,6 @@ break; } $object->fk_user_employer = $user_employer_id; - $object->fk_user_victim = $user_victim_id; $object->fk_user_creat = $user->id ?: 1; // Check parameters @@ -213,13 +219,10 @@ if (!$error) { $result = $object->create($user, false); if ($result > 0) { - // Removed while accidents have no document or attendants page -// if (empty($object->fk_user_employer)) { -// $usertmp->fetch('', $mysoc->managers, $mysoc->id, 0, $conf->entity); -// } else { -// $usertmp->fetch($object->fk_user_employer); -// } -// $signatory->setSignatory($object->id, 'accident', 'user', array($usertmp->id), 'Responsible'); + $usertmp->fetch($user_victim_id); + $signatory->setSignatory($object->id, 'accident', 'user', array($usertmp->id), 'Victim'); + $categories = GETPOST('categories', 'array'); + $object->setCategories($categories); // Creation Accident OK $urltogo = str_replace('__ID__', $result, $backtopage); @@ -242,7 +245,6 @@ // Action to update record if ($action == 'update' && $permissiontoadd) { // Get parameters - $user_victim_id = GETPOST('fk_user_victim'); $user_employer_id = GETPOST('fk_user_employer'); $digiriskelement_id = GETPOST('fk_element'); $label = GETPOST('label'); @@ -250,7 +252,8 @@ $accident_type = GETPOST('accident_type'); $external_accident = GETPOST('external_accident'); $accident_location = GETPOST('accident_location'); - $extSocietyId = GETPOST('fk_soc'); + $extSocietyId = GETPOST('fk_soc'); + $fkTicket = GETPOST('fk_ticket'); // Initialize object accident $now = dol_now(); @@ -260,7 +263,8 @@ $object->accident_type = $accident_type; $object->external_accident = $external_accident; $object->accident_location = $accident_location; - $object->fk_project = $conf->global->DIGIRISKDOLIBARR_ACCIDENT_PROJECT; + $object->fk_project = $conf->global->DIGIRISKDOLIBARR_ACCIDENT_PROJECT; + $object->fk_ticket = $fkTicket; $accident_date = dol_mktime(GETPOST('dateohour', 'int'), GETPOST('dateomin', 'int'), 0, GETPOST('dateomonth', 'int'), GETPOST('dateoday', 'int'), GETPOST('dateoyear', 'int')); @@ -292,21 +296,21 @@ $object->accident_location = $accident_location; break; } - $object->fk_user_victim = $user_victim_id; $object->fk_user_employer = $user_employer_id; $object->fk_user_creat = $user->id > 0 ? $user->id : 1; - // Check parameters - if ($user_victim_id < 0) { - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UserVictim')), [], 'errors'); - $error++; - } - if ($user_employer_id < 0) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UserEmployer')), [], 'errors'); $error++; } + if (isModEnabled('categorie')) { + $categories = GETPOST('categories', 'array'); + if (method_exists($object, 'setCategories')) { + $object->setCategories($categories); + } + } + if (!$error) { $result = $object->update($user); if ($result > 0) { @@ -474,7 +478,29 @@ } } - // Add file in accident workstop + // Action to set status STATUS_REOPENED + if ($action == 'confirm_setReopened') { + $object->fetch($id); + if ( ! $error) { + $result = $object->setDraft($user, false); + if ($result > 0) { + $object->verdict = null; + $result = $object->update($user); + // Set reopened OK + $urltogo = str_replace('__ID__', $result, $backtopage); + $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $id, $urltogo); // New method to autoselect project after a New on another form object creation + header('Location: ' . $urltogo); + exit; + } else { + // Set reopened KO + if ( ! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + } + } + } + + + // Add file in accident workstop if ($action == 'sendfile') { include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $objectlineid = GETPOST('objectlineid'); @@ -554,11 +580,13 @@ // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes') { - $options['label'] = GETPOST('clone_label'); - $options['workstop'] = GETPOST('clone_workstop'); - $options['lesion'] = GETPOST('clone_lesion'); - $options['metadata'] = GETPOST('clone_metadata'); - $options['photos'] = GETPOST('clone_photos'); + $options['label'] = GETPOST('clone_label'); + $options['workstop'] = GETPOST('clone_workstop'); + $options['lesion'] = GETPOST('clone_lesion'); + $options['metadata'] = GETPOST('clone_metadata'); + $options['photos'] = GETPOST('clone_photos'); + $options['categories'] = GETPOST('clone_categories'); + $options['attendants'] = GETPOST('clone_attendants'); if ($object->id > 0) { $result = $object->createFromClone($user, $object->id, $options); if ($result > 0) { @@ -574,7 +602,9 @@ // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen require_once DOL_DOCUMENT_ROOT . '/core/actions_addupdatedelete.inc.php'; - // Action confirm_lock, confirm_archive. + include_once __DIR__ . '/../../core/tpl/accident/digiriskdolibarr_accident_lesion_actions.tpl.php'; + + // Action confirm_lock, confirm_archive. require_once __DIR__ . '/../../../saturne/core/tpl/signature/signature_action_workflow.tpl.php'; // Actions set_thirdparty, set_project @@ -649,12 +679,12 @@ print ''; //FkElement -- Lieu de l'accident - DigiriskElement - print '' . $langs->trans("AccidentLocation") . ''; + print '' . $langs->trans("AccidentLocation") . ''; print $digiriskelement->selectDigiriskElementList((!empty(GETPOST('fromid')) ? GETPOST('fromid') : $object->fk_element), 'fk_element', ['customsql' => ' t.rowid NOT IN (' . implode(',', $deletedElements) . ')'], 0, 0, [], 0, 0, 'minwidth300'); print ''; //FkSoc -- Lieu de l'accident - Société extérieure - print '' . $langs->trans("AccidentLocation") . ''; + print '' . $langs->trans("AccidentLocation") . ''; print ''; //For external user force the company to user company if (!empty($user->socid)) { @@ -666,13 +696,13 @@ print ''; //AccidentLocation -- lieu de l'accident - print '' . $langs->trans("AccidentLocation") . ''; + print '' . $langs->trans("AccidentLocation") . ''; $doleditor = new DolEditor('accident_location', GETPOST('accident_location'), '', 90, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_3, '90%'); $doleditor->Create(); print ''; //Accident Date -- Date de l'accident - print ''; + print ''; print $form->selectDate(GETPOST('dateo') ? dol_mktime(GETPOST('dateohour', 'int'),GETPOST('dateomin', 'int'),0,GETPOST('dateomonth', 'int'), GETPOST('dateoday', 'int'), GETPOST('dateoyear', 'int')) : dol_now('tzuser'), 'dateo', 1, 1, 0, '', 1); print ''; @@ -682,6 +712,20 @@ $doleditor->Create(); print ''; + //Fk Ticket -- Fk Ticket + print ''; + print $form->selectTicketsList(GETPOST('fk_ticket'), 'fk_ticket', '', 0, '', 1, 0, '1', 0, 'minwidth300'); + print ''; + + // Categories + if (!empty($conf->categorie->enabled)) { + print ''.$langs->trans("Categories").''; + $categoryArborescence = $form->select_all_categories('accident', '', 'parent', 64, 0, 1); + print img_picto('', 'category', 'class="pictofixedwidth"').$form->multiselectarray('categories', $categoryArborescence, GETPOST('categories', 'array'), '', 0, 'quatrevingtpercent maxwidth300 widthcentpercentminusx'); + print ''; + print ""; + } + // Other attributes // include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; @@ -731,15 +775,6 @@ print ' '; print ''; - //User Victim -- Utilisateur victime de l'accient - $userlist = $form->select_dolusers(( ! empty($object->fk_user_victim) ? $object->fk_user_victim : $user->id), '', 0, null, 0, '', '', $conf->entity, 0, 0, 'AND u.statut = 1', 0, '', 'minwidth300', 0, 1); - print ''; - print '' . img_picto('', 'user') . ' ' . $form->editfieldkey('UserVictim', 'UserVictim_id', '', $object, 0) . ''; - print ''; - print $form->selectarray('fk_user_victim', $userlist, ( ! empty($object->fk_user_victim) ? $object->fk_user_victim : $user->id), $langs->trans('SelectUser'), null, null, null, "40%", 0, 0, '', 'minwidth300', 1); - print ' '; - print ''; - //AccidentType print '' . $langs->trans("AccidentType") . ''; print $form->selectarray('accident_type', array('0' => $langs->trans('WorkAccidentStatement'), '1' => $langs->trans('CommutingAccident')), $object->accident_type, 0, 0, 0, '', 0, 0, 0, '', 'minwidth300', 1); @@ -784,6 +819,28 @@ $doleditor->Create(); print ''; + //Fk Ticket -- Fk Ticket + print ''; + print $form->selectTicketsList($object->fk_ticket ?: GETPOST('fk_ticket'), 'fk_ticket', '', 0, '', 1, 0, '1', 0, 'minwidth300'); + print ''; + + // Tags-Categories + if ($conf->categorie->enabled) { + print ''.$langs->trans("Categories").''; + $categoryArborescence = $form->select_all_categories('accident', '', 'parent', 64, 0, 1); + $c = new Categorie($db); + $cats = $c->containing($object->id, 'accident'); + $arrayselected = array(); + if (is_array($cats)) { + foreach ($cats as $cat) { + $arrayselected[] = $cat->id; + } + } + print img_picto('', 'category', 'class="pictofixedwidth"').$form->multiselectarray('categories', $categoryArborescence, $arrayselected, '', 0, 'maxwidth500 widthcentpercentminusx'); + print ''; + print ""; + } + // Other attributes include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; print ''; @@ -801,6 +858,8 @@ if ((empty($action) || ($action != 'create' && $action != 'edit'))) { $counter = 0; + $userVictim = $object->getUserVictim(); + $morecssGauge = 'inline-block floatright'; $move_title_gauge = 1; @@ -821,9 +880,12 @@ $arrayAccident[] = $object->accident_location; break; } - $arrayAccident[] = $object->fk_user_victim; + $arrayAccident[] = $userVictim->id; - $maxnumber = count($arrayAccident); + $accidentLesions = $accidentLesion->fetchAll('', '', 0, 0, ['customsql' => 't.fk_accident = ' . $object->id]); + $arrayAccident[] = (is_array($accidentLesions) && !empty($accidentLesions)) ? count($accidentLesions) : ''; + + $maxnumber = count($arrayAccident); foreach ($arrayAccident as $arrayAccidentData) { if (dol_strlen($arrayAccidentData) > 0 ) { @@ -862,16 +924,30 @@ // Clone confirmation if (($action == 'clone' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { $formQuestionClone = [ - ['type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans('NewLabelForClone', $langs->transnoentities('The' . ucfirst($object->element))), 'value' => $langs->trans('CopyOf') . ' ' . $object->ref, 'size' => 24], - ['type' => 'checkbox', 'name' => 'clone_workstop', 'label' => $langs->trans('CloneWorkStop'), 'value' => 1], - ['type' => 'checkbox', 'name' => 'clone_metadata', 'label' => $langs->trans('CloneMetadata'), 'value' => 1], - ['type' => 'checkbox', 'name' => 'clone_lesion', 'label' => $langs->trans('CloneLesion'), 'value' => 1], - ['type' => 'checkbox', 'name' => 'clone_photos', 'label' => $langs->trans('ClonePhotos'), 'value' => 1] + ['type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans('NewLabelForClone', $langs->transnoentities('The' . ucfirst($object->element))), 'value' => $langs->trans('CopyOf') . ' ' . $object->ref, 'size' => 24], + ['type' => 'checkbox', 'name' => 'clone_workstop', 'label' => $langs->trans('CloneWorkStop'), 'value' => 1], + ['type' => 'checkbox', 'name' => 'clone_metadata', 'label' => $langs->trans('CloneMetadata'), 'value' => 1], + ['type' => 'checkbox', 'name' => 'clone_lesion', 'label' => $langs->trans('CloneLesion'), 'value' => 1], + ['type' => 'checkbox', 'name' => 'clone_photos', 'label' => $langs->trans('ClonePhotos'), 'value' => 1], + ['type' => 'checkbox', 'name' => 'clone_categories', 'label' => $langs->trans('CloneCategories'), 'value' => 1], + ['type' => 'checkbox', 'name' => 'clone_attendants', 'label' => $langs->trans('CloneAttendants'), 'value' => 1] ]; $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('CloneObject', $langs->transnoentities('The' . ucfirst($object->element))), $langs->trans('ConfirmCloneObject', $langs->transnoentities('The' . ucfirst($object->element))), 'confirm_clone', $formQuestionClone, 'yes', 'actionButtonClone', 350, 600); } + // SetValidated confirmation + if (($action == 'setValidated' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { + $questionConfirmInfo = $langs->trans('ConfirmValidateObject', $langs->trans('TheAccident'), $langs->transnoentities('LesionsOrWorkStop')); + $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('ValidateObject', $langs->trans('TheAccident')), $questionConfirmInfo, 'confirm_validate', '', 'yes', 'actionButtonValidate', 250); + } + + // SetReOpen confirmation + if (($action == 'setReOpen' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { + $questionConfirmInfo = $langs->trans('ConfirmReOpenObject', $langs->trans('TheAccident')); + $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('ReOpenObject', $langs->trans('TheAccident')), $questionConfirmInfo, 'confirm_setReopened', '', 'yes', 'actionButtonReOpen', 250); + } + // Confirmation to lock if (($action == 'lock' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('LockObject', $langs->transnoentities('The' . ucfirst($object->element))), $langs->trans('ConfirmLockObject', $langs->transnoentities('The' . ucfirst($object->element))), 'confirm_lock', '', 'yes', 'actionButtonLock', 350, 600); @@ -904,7 +980,6 @@ unset($object->fields['accident_location']); unset($object->fields['fk_soc']); unset($object->fields['fk_user_employer']); - unset($object->fields['fk_user_victim']); unset($object->fields['fk_element']); //Label -- Libellé @@ -931,10 +1006,7 @@ print $form->textwithpicto($langs->trans("UserVictim"), $langs->trans("GaugeCounter"), 1, 'info'); print ''; print ''; - $usertmp->fetch($object->fk_user_victim); - if ($usertmp > 0) { - print $usertmp->getNomUrl(1); - } + print $userVictim->getNomUrl(1); print ''; //Accident type -- Type de l'accident @@ -990,11 +1062,22 @@ print $object->description; print ''; + //Fk Ticket -- Fk Ticket + print ''; + print $langs->trans('FkTicket'); + print ''; + print ''; + if ($object->fk_ticket > 0) { + $ticket->fetch($object->fk_ticket); + print $ticket->getNomUrl(1); + } + print ''; + print ' '; print ''; $pathPhotos = $conf->digiriskdolibarr->multidir_output[$conf->entity] . '/accident/' . $object->ref . '/photos'; ?> - status <= Accident::STATUS_VALIDATED) ? '' : 'style="display:none"' ?>> + status <= Accident::STATUS_DRAFT) ? '' : 'style="display:none"' ?>>
'; - // Accident Lines - $accidentWorkstops = $objectline->fetchFromParent($object->id); + // Accident lesions + include_once __DIR__ . '/../../core/tpl/accident/digiriskdolibarr_accident_lesion.tpl.php'; - if (($object->status == Accident::STATUS_VALIDATED) || (!empty($accidentWorkstops))) { - // ACCIDENT LINES - print '
'; - print load_fiche_titre($langs->trans("AccidentRiskList"), '', ''); - print ''; - - // Define colspan for the button 'Add' - $colspan = 3; // Columns: total ht + col edit + col delete - $img_extensions = ['png', 'jpg', 'jpeg']; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + // Accident Lines + $accidentWorkstops = $objectline->fetchFromParent($object->id); - if ( ! empty($accidentWorkstops) && $accidentWorkstops > 0) { - foreach ($accidentWorkstops as $key => $item) { - //action edit - if (($action == 'editline' || $subaction == 'editline') && $lineid == $key) { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print ''; - print ''; - - $coldisplay++; - print ''; - - $coldisplay++; - print ''; - - $coldisplay++; - print ''; - - $coldisplay++; - print ''; - - $coldisplay += $colspan; - print ''; - print ''; - print ''; - //action view - } elseif ($item->status == 1) { - print ''; - - $coldisplay++; - print ''; - - $coldisplay++; - print ''; - - $coldisplay++; - print ''; - - $coldisplay++; - print ''; - - $coldisplay += $colspan; - - //Actions buttons - if ($object->status == Accident::STATUS_VALIDATED) { - print ''; - } else { - print ''; - } - print ''; - } - } - print ''; - } - } + // ACCIDENT LINES + print '
'; + print load_fiche_titre($langs->trans("AccidentRiskList"), '', ''); + print '
' . $langs->trans('Ref.') . '' . '' . $langs->trans('WorkStopDays') . ' *' . '' . $langs->trans('DateStartWorkStop') . '' . $langs->trans('DateEndWorkStop') . '' . $langs->trans('WorkStopDocument') . '' . $langs->trans('ActionsLine') . '
'; - print $item->ref; - print ''; - print ''; - print ''; - print $form->selectDate($item->date_start_workstop, 'datestart', 1, 1, 0, '', 1); - print ''; - print $form->selectDate($item->date_end_workstop, 'dateend', 1, 1, 0, '', 1); - print ''; - print ''; - print ''; - print ''; - print '   '; - print '
'; - print $item->ref; - print ''; - print $item->workstop_days; - print ''; - print dol_print_date($item->date_start_workstop, 'dayhour'); - print ''; - print dol_print_date($item->date_end_workstop, 'dayhour'); - print ''; - $is_link = dol_is_url($item->declaration_link); - print ($is_link ? '' : '') . $item->declaration_link . ($is_link ? '' : '') ; - print ''; - $coldisplay++; - print 'id . '" style="padding-right: 20px">'; - print 'id . '&token=' . newToken() . '">'; - print img_delete(); - print ''; - print ''; - print '-'; - print '
'; + + // Define colspan for the button 'Add' + $colspan = 3; // Columns: total ht + col edit + col delete + $img_extensions = ['png', 'jpg', 'jpeg']; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + if ( ! empty($accidentWorkstops) && $accidentWorkstops > 0) { + foreach ($accidentWorkstops as $key => $item) { + //action edit + if (($action == 'editline' || $subaction == 'editline') && $lineid == $key) { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + print ''; + + $coldisplay++; + print ''; + + $coldisplay++; + print ''; + + $coldisplay++; + print ''; + + $coldisplay++; + print ''; + + $coldisplay += $colspan; + print ''; + print ''; + print ''; + //action view + } elseif ($item->status == 1) { + print ''; + + $coldisplay++; + print ''; + + $coldisplay++; + print ''; + + $coldisplay++; + print ''; + + $coldisplay++; + print ''; + + $coldisplay += $colspan; + + //Actions buttons + if ($object->status == Accident::STATUS_DRAFT) { + print ''; + } else { + print ''; + } + print ''; + } + } + print ''; + } //action create - if ($object->status == Accident::STATUS_VALIDATED && $permissiontoadd && $action != 'editline') { + if ($object->status == Accident::STATUS_DRAFT && $permissiontoadd && $action != 'editline') { print ''; print ''; print ''; diff --git a/view/accident/accident_list.php b/view/accident/accident_list.php index 7cd0f0dd4..6237124c0 100644 --- a/view/accident/accident_list.php +++ b/view/accident/accident_list.php @@ -72,6 +72,7 @@ $digiriskelement = new DigiriskElement($db); $digiriskstandard = new DigiriskStandard($db); $project = new Project($db); +$accidentLesion = new AccidentLesion($db); $offset = $limit * $page; $pageprev = $page - 1; @@ -286,13 +287,10 @@ if (is_array($extrafields->attributes[$accident->table_element]['label']) && count($extrafields->attributes[$accident->table_element]['label'])) $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $accident->table_element . "_extrafields as ef on (t.rowid = ef.fk_object)"; if ($accident->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (" . getEntity($accident->element) . ")"; else $sql .= " WHERE 1 = 1"; -$sql .= ' AND status != 0'; +$sql .= ' AND status != ' . $accident::STATUS_DELETED; if ($fromid > 0) { $sql .= ' AND fk_element =' . $fromid; -} elseif ($fromiduser > 0){ - $sql .= " AND fk_user_victim = " . $fromiduser; } -$sql .= ' AND status >= 0'; foreach ($search as $key => $val) { if ($key == 'status' && $search[$key] == -1) continue; @@ -357,6 +355,8 @@ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$arrayfields['Victim'] = array('label' => 'Victim', 'checked' => 1); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_' . $accident->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields @@ -366,6 +366,8 @@ print '
' . $langs->trans('Ref.') . '' . '' . $langs->trans('WorkStopDays') . ' *' . '' . $langs->trans('DateStartWorkStop') . '' . $langs->trans('DateEndWorkStop') . '' . $langs->trans('WorkStopDocument') . '' . $langs->trans('ActionsLine') . '
'; + print $item->ref; + print ''; + print ''; + print ''; + print $form->selectDate($item->date_start_workstop, 'datestart', 1, 1, 0, '', 1); + print ''; + print $form->selectDate($item->date_end_workstop, 'dateend', 1, 1, 0, '', 1); + print ''; + print ''; + print ''; + print ''; + print '   '; + print '
'; + print $item->ref; + print ''; + print $item->workstop_days; + print ''; + print dol_print_date($item->date_start_workstop, 'dayhour'); + print ''; + print dol_print_date($item->date_end_workstop, 'dayhour'); + print ''; + $is_link = dol_is_url($item->declaration_link); + print ($is_link ? '' : '') . $item->declaration_link . ($is_link ? '' : '') ; + print ''; + $coldisplay++; + print 'id . '" style="padding-right: 20px">'; + print 'id . '&token=' . newToken() . '">'; + print img_delete(); + print ''; + print ''; + print '-'; + print '
' . "\n"; print ''; +$accident->fields['Custom']['Victim'] = $arrayfields['Victim'] ; + // We manually add progress field here because it is a redundant information that doesn't need to be stored in db $accident->fields['progress'] = ['type' => 'integer:', 'label' => 'Progress', 'enabled' => '1', 'position' => 70, 'notnull' => 0, 'visible' => 2, 'index' => 0,]; $arrayfields['t.progress'] = ['label' => 'Progress', 'checked' => 1, 'enabled' => 0, 'position' => 70, 'disablesort' => 1]; @@ -378,13 +380,18 @@ if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_' . $key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); elseif (strpos($val['type'], 'integer:') === 0) { - if ($key == 'fk_user_victim' && $fromiduser > 0) { - $search[$key] = $fromiduser; - } print $accident->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } elseif ( ! preg_match('/^(date|timestamp)/', $val['type'])) print ''; print ''; } + if ($key == 'Custom') { + foreach ($val as $resource) { + if ($resource['checked']) { + print ''; + } + } + } } // Extra fields @@ -413,8 +420,22 @@ $cssforfield .= ($cssforfield ? ' ' : '') . 'center'; } if ( ! empty($arrayfields['t.' . $key]['checked'])) { + if (preg_match('/Victim/', $arrayfields['t.' . $key]['label'])) { + $disablesort = 1; + } else { + $disablesort = 0; + } print getTitleFieldOfList($arrayfields['t.' . $key]['label'], 0, $_SERVER['PHP_SELF'], 't.' . $key, '', $param, ($cssforfield ? 'class="' . $cssforfield . '"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield . ' ' : ''), $disablesort) . "\n"; } + if ($key == 'Custom') { + foreach ($val as $resource) { + if ($resource['checked']) { + print ''; + } + } + } } // Extra fields @@ -447,6 +468,7 @@ // Store properties in $accidentdocument $accident->setVarsFromFetchObj($obj); + $userVictim = $accident->getUserVictim(); $json = json_decode($accident->json, false, 512, JSON_UNESCAPED_UNICODE)->Accident; @@ -486,7 +508,10 @@ $arrayAccident[] = $accident->accident_location; break; } - $arrayAccident[] = $accident->fk_user_victim; + $arrayAccident[] = $userVictim->id; + + $accidentLesions = $accidentLesion->fetchAll('', '', 0, 0, ['customsql' => 't.fk_accident = ' . $accident->id]); + $arrayAccident[] = (is_array($accidentLesions) && !empty($accidentLesions)) ? count($accidentLesions) : ''; $maxnumber = count($arrayAccident); @@ -513,11 +538,6 @@ if ($usertmp > 0) { print getNomUrlUser($usertmp, 1, 'blank', 0, 0, 0, 0, '', '', -1, 0); } - } elseif ($key == 'fk_user_victim') { - $usertmp->fetch($accident->fk_user_victim); - if ($usertmp > 0) { - print getNomUrlUser($usertmp, 1, 'blank', 0, 0, 0, 0, '', '', -1, 0); - } } elseif ($key == 'accident_type') { if ($accident->accident_type == 0) { print $langs->trans('WorkAccidentStatement'); @@ -553,7 +573,20 @@ $totalarray['val']['t.' . $key] += $accident->$key; } } - } + if ($key == 'Custom') { + foreach ($val as $name => $resource) { + if ($resource['checked']) { + print ''; + } + } + } + + } // Action column print ''; diff --git a/view/digiriskelement/digiriskelement_risk.php b/view/digiriskelement/digiriskelement_risk.php index 2ab881b50..b20591276 100644 --- a/view/digiriskelement/digiriskelement_risk.php +++ b/view/digiriskelement/digiriskelement_risk.php @@ -205,6 +205,12 @@ digirisk_header($title, $helpUrl); +if ($conf->browser->layout == 'phone') { + $onPhone = 1; +} else { + $onPhone = 0; +} + print '
'; if ($sharedrisks) { diff --git a/view/digiriskstandard/digiriskstandard_registerdocument.php b/view/digiriskstandard/digiriskstandard_registerdocument.php new file mode 100644 index 000000000..2430e6ab2 --- /dev/null +++ b/view/digiriskstandard/digiriskstandard_registerdocument.php @@ -0,0 +1,143 @@ + + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file view/digiriskstandard/digiriskstandard_registerdocument.php + * \ingroup digiriskdolibarr + * \brief Page to view registerdocument + */ + +// Load DigiriskDolibarr environment +if (file_exists('../digiriskdolibarr.main.inc.php')) { + require_once __DIR__ . '/../digiriskdolibarr.main.inc.php'; +} elseif (file_exists('../../digiriskdolibarr.main.inc.php')) { + require_once __DIR__ . '/../../digiriskdolibarr.main.inc.php'; +} else { + die('Include of digiriskdolibarr main fails'); +} + +require_once DOL_DOCUMENT_ROOT . '/core/lib/images.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; +require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; + +require_once __DIR__ . '/../../class/digiriskstandard.class.php'; +require_once __DIR__ . '/../../class/digiriskresources.class.php'; +require_once __DIR__ . '/../../class/digiriskdolibarrdocuments/registerdocument.class.php'; +require_once __DIR__ . '/../../lib/digiriskdolibarr_digiriskstandard.lib.php'; +require_once __DIR__ . '/../../lib/digiriskdolibarr_function.lib.php'; + +global $db, $conf, $langs, $hookmanager, $user; + +// Load translation files required by the page +saturne_load_langs(['other']); + +// Get parameters +$action = GETPOST('action', 'aZ09'); +$subaction = GETPOST('subaction', 'aZ09'); + +// Initialize technical objects +$object = new DigiriskStandard($db); +$document = new RegisterDocument($db); +$contact = new Contact($db); +$project = new Project($db); + +$hookmanager->initHooks(array('digiriskelementregisterdocument', 'digiriskstandardview', 'globalcard')); // Note that conf->hooks_modules contains array + +$object->fetch($conf->global->DIGIRISKDOLIBARR_ACTIVE_STANDARD); + +$upload_dir = $conf->digiriskdolibarr->multidir_output[isset($conf->entity) ? $conf->entity : 1]; + +// Security check - Protection if external user +$permissiontoread = $user->rights->digiriskdolibarr->digiriskstandard->read && $user->rights->digiriskdolibarr->registerdocument->read; +$permissiontoadd = $user->rights->digiriskdolibarr->registerdocument->write; +$permissiontodelete = $user->rights->digiriskdolibarr->registerdocument->delete; +saturne_check_access($permissiontoread); + +/* + * Actions + */ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +if (empty($reshook)) { + $error = 0; + $previousRef = $object->ref; + $object->ref = ''; + $removeDocumentFromName = 1; + + // Actions builddoc, forcebuilddoc, remove_file. + require_once __DIR__ . '/../../../saturne/core/tpl/documents/documents_action.tpl.php'; + + // Action to generate pdf from odt file + require_once __DIR__ . '/../../../saturne/core/tpl/documents/saturne_manual_pdf_generation_action.tpl.php'; + + $object->ref = $previousRef; +} + +/* + * View + */ + +$title = $langs->trans('RegisterDocument'); +$helpUrl = 'FR:Module_Digirisk#Soci.C3.A9t.C3.A9.2FOrganisation'; + +digirisk_header($title, $helpUrl); ?> + +
+ +fetch_optionals(); + +saturne_get_fiche_head($object, 'standardRegisterDocument', $title); + +// Object card +// ------------------------------------------------------------ +// Project +$morehtmlref = '
'; +$project->fetch($conf->global->DIGIRISKDOLIBARR_DU_PROJECT); +$morehtmlref .= $langs->trans('Project') . ' : ' . getNomUrlProject($project, 1, 'blank', 1); +$morehtmlref .= '
'; + +$moduleNameLowerCase = 'mycompany'; +saturne_banner_tab($object,'ref','none', 0, 'ref', 'ref', $morehtmlref, true); +$moduleNameLowerCase = 'digiriskdolibarr'; + +print '
'; +print '
'; + print ''; + print $langs->trans($resource['label']); + print ''; + + if ($resource['label'] == 'Victim') { + print getNomUrlUser($userVictim, 1, 'blank', 0, 0, 0, 0, '', '', -1, 0); + } + print ''; if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined diff --git a/view/accident/accident_metadata_lesion.php b/view/accident/accident_metadata_lesion.php index 4f475dcd4..fef63f616 100644 --- a/view/accident/accident_metadata_lesion.php +++ b/view/accident/accident_metadata_lesion.php @@ -102,102 +102,7 @@ exit; } - // Action to add line - if ($action == 'addLine' && $permissiontoadd) { - // Get parameters - $lesion_localization = GETPOST('lesion_localization'); - $lesion_nature = GETPOST('lesion_nature'); - $parent_id = GETPOST('parent_id'); - $error = 0; - - // Initialize object accident line - $now = dol_now(); - $objectline->ref = $objectline->getNextNumRef(); - $objectline->date_creation = $object->db->idate($now); - $objectline->entity = $conf->entity; - $objectline->lesion_localization = $lesion_localization; - $objectline->lesion_nature = $lesion_nature; - $objectline->fk_accident = $parent_id; - - // Check parameters - if ($lesion_localization < 0) { - setEventMessages($langs->trans('ErrorFieldNotEmpty', $langs->transnoentitiesnoconv('LesionLocalization')), null, 'errors'); - $error++; - } - - if ($lesion_nature < 0) { - setEventMessages($langs->trans('ErrorFieldNotEmpty', $langs->transnoentitiesnoconv('LesionNature')), null, 'errors'); - $error++; - } - - if ( ! $error) { - $result = $objectline->create($user, false); - if ($result > 0) { - // Creation accident lesion OK - setEventMessages($langs->trans('AddAccidentLesion') . ' ' . $object->ref, array()); - $urltogo = str_replace('__ID__', $result, $backtopage); - $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $id, $urltogo); // New method to autoselect project after a New on another form object creation - header("Location: " . $urltogo); - exit; - } else { - // Creation accident lesion KO - if ( ! empty($objectline->errors)) setEventMessages(null, $objectline->errors, 'errors'); - else setEventMessages($objectline->error, null, 'errors'); - } - } - } - - // Action to update line - if ($action == 'updateLine' && $permissiontoadd) { - // Get parameters - $lesion_localization = GETPOST('lesion_localization'); - $lesion_nature = GETPOST('lesion_nature'); - $parent_id = GETPOST('parent_id'); - - $objectline->fetch($lineid); - - // Initialize object accident line - $objectline->lesion_localization = $lesion_localization; - $objectline->lesion_nature = $lesion_nature; - $objectline->fk_accident = $parent_id; - - if ( ! $error) { - $result = $objectline->update($user, false); - if ($result > 0) { - // Update accident lesion OK - setEventMessages($langs->trans('UpdateAccidentLesion') . ' ' . $object->ref, array()); - $urltogo = str_replace('__ID__', $result, $backtopage); - $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $parent_id, $urltogo); // New method to autoselect project after a New on another form object creation - header("Location: " . $urltogo); - exit; - } else { - // Update accident lesion KO - if ( ! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); - } - } - } - - // Action to delete line - if ($action == 'deleteline' && $permissiontodelete) { - $objectline->fetch($lineid); - $result = $objectline->delete($user, false, false); - if ($result > 0) { - // Deletion accident lesion OK - setEventMessages($langs->trans('DeleteAccidentLesion') . ' ' . $object->ref, array()); - $urltogo = str_replace('__ID__', $result, $backtopage); - $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $parent_id, $urltogo); // New method to autoselect project after a New on another form object creation - header("Location: " . $urltogo); - exit; - } else { - // Deletion accident lesion KO - if (!empty($object->errors)) { - setEventMessages('', $object->errors, 'errors'); - } else { - setEventMessages($object->error, [], 'errors'); - } - } - } + include_once __DIR__ . '/../../core/tpl/accident/digiriskdolibarr_accident_lesion_actions.tpl.php'; // Actions set_thirdparty, set_project require_once __DIR__ . '/../../../saturne/core/tpl/actions/banner_actions.tpl.php'; @@ -222,138 +127,7 @@ saturne_banner_tab($object, 'id', '', 1, 'rowid', 'ref', $moreHtmlRef, dol_strlen($object->photo) > 0, $moreParams); -// ACCIDENT LESION -print '
'; -print load_fiche_titre($langs->trans("AccidentLesionList"), '', ''); -print ''; - -global $forceall, $forcetoshowtitlelines; - -if (empty($forceall)) $forceall = 0; - -// Define colspan for the button 'Add' -$colspan = 3; // Columns: total ht + col edit + col delete - -// Accident Lines -$accidentlines = $objectline->fetchAll('', '', 0, 0, ['customsql' => 't.fk_accident = ' . $object->id]); - -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; - -if (!empty($accidentlines) && $accidentlines > 0) { - foreach ($accidentlines as $key => $item) { - if ($action == 'editline' && $lineid == $key) { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print ''; - print ''; - - $coldisplay++; - //LesionLocalization -- Siège des lésions - print ''; - - $coldisplay++; - //LesionNature -- Nature des lésions - print ''; - - $coldisplay += $colspan; - print ''; - print ''; - - print ''; - } else { - print ''; - - $coldisplay++; - print ''; - - $coldisplay++; - print ''; - - $coldisplay += $colspan; - - //Actions buttons - if ($object->status == 1) { - print ''; - } else { - print ''; - } - - print ''; - } - } - print ''; -} -if ($object->status == 1 && $permissiontoadd) { - print ''; - print ''; - print ''; - print ''; - print ''; - - print ''; - print ''; - - $coldisplay++; - //LesionLocalization -- Siège des lésions - print ''; - - $coldisplay++; - //LesionNature -- Nature des lésions - print ''; - - $coldisplay += $colspan; - print ''; - print ''; - - print ''; -} -print '
' . $langs->trans('Ref.') . '' . $langs->trans('LesionLocalization') . '' . $langs->trans('LesionNature') . '' . $langs->trans('ActionsLine') . '
'; - print $item->ref; - print ''; - print saturne_select_dictionary('lesion_localization', 'c_lesion_localization', 'label', 'label', $item->lesion_localization); - print '' . ' ' . img_picto('', 'globe') . ''; - print ''; - print saturne_select_dictionary('lesion_nature', 'c_lesion_nature', 'label', 'label', $item->lesion_nature); - print '' . ' ' . img_picto('', 'globe') . ''; - print ''; - print ''; - print '   '; - print '
'; - print $item->ref; - print ''; - print $langs->transnoentities($item->lesion_localization); - print ''; - print $langs->transnoentities($item->lesion_nature); - print ''; - $coldisplay++; - print 'id . '" style="padding-right: 20px">'; - print 'id . '&token='. newToken(). '">'; - print img_delete(); - print ''; - print ''; - print '-'; - print '
'; - print $objectline->getNextNumRef(); - print ''; - print saturne_select_dictionary('lesion_localization', 'c_lesion_localization', 'label'); - print '' . ' ' . img_picto('', 'globe') . ''; - print ''; - print saturne_select_dictionary('lesion_nature', 'c_lesion_nature', 'label'); - print '' . ' ' . img_picto('', 'globe') . ''; - print ''; - print ''; - print '
'; -print '
'; +include_once __DIR__ . '/../../core/tpl/accident/digiriskdolibarr_accident_lesion.tpl.php'; print dol_get_fiche_end(); // End of page diff --git a/view/accidentinvestigation/accidentinvestigation_card.php b/view/accidentinvestigation/accidentinvestigation_card.php index 29fc52b4f..10b5e544c 100644 --- a/view/accidentinvestigation/accidentinvestigation_card.php +++ b/view/accidentinvestigation/accidentinvestigation_card.php @@ -70,7 +70,6 @@ $project = new Project($db); $task = new Task($db); $signatory = new SaturneSignature($db, $object->module, $object->element); -$victim = new User($db); $numRefConf = strtoupper($task->element) . '_ADDON'; @@ -185,30 +184,6 @@ exit(); } - if ($action == 'confirm_archive') { - $modelList = saturne_get_list_of_models($db, 'accidentinvestigationdocument'); - if (!empty($modelList)) { - asort($modelList); - $modelList = array_filter($modelList, 'saturne_remove_index'); - if (is_array($modelList)) { - $models = array_keys($modelList); - } - } - - $moreParams['object'] = $object; - $moreParams['user'] = $user; - $moreParams['zone'] = 'private'; - $moreParams['specimen'] = 0; - $result = $document->generateDocument((!empty($models) ? $models[0] : ''), $langs, 0, 0, 0, $moreParams); - - if ($result > 0) { - setEventMessages('AccidentInvestigationClassified', []); - } else { - setEventMessages($document->error, [], 'errors'); - $action = ''; - } - } - // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen require_once DOL_DOCUMENT_ROOT . '/core/actions_addupdatedelete.inc.php'; @@ -303,9 +278,10 @@ } else if ($id > 0 || (!empty($ref) && empty($action))) { $object->fetch($id); $accident->fetch($object->fk_accident); - $victim->fetch($accident->fk_user_victim); - saturne_get_fiche_head($object, 'card', $title); + $victim = $accident->getUserVictim(); + + saturne_get_fiche_head($object, 'card', $title); saturne_banner_tab($object); $formConfirm = ''; @@ -314,38 +290,17 @@ if (($action == 'set_draft' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('ReOpenObject', $langs->transnoentities('The' . ucfirst($object->element))), $langs->trans('ConfirmReOpenObject', $langs->transnoentities('The' . ucfirst($object->element)), $langs->transnoentities('The' . ucfirst($object->element))), 'confirm_setdraft', '', 'yes', 'actionButtonInProgress', 350, 600); } - // New version confirmation - if (($action == 'set_new_version' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { - $imgPath = dol_buildpath('custom/saturne/img/formconfirm/object_version_versioning.png', 1); - $img = img_picto($langs->trans('NewVersion'), $imgPath, '', 1); - $formQuestion = [ - ['type' => 'other', 'name' => 'lock_validation', 'label' => '' . img_picto('', 'info') . ' ' . $langs->trans('ConfirmReOpenInvestigation'). ''], - ['type' => 'other', 'name' => 'OK', 'label' => '', 'value' => $img, 'moreattr' => 'readonly'], - ]; - - $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('NewVersionObject', $langs->transnoentities('The' . ucfirst($object->element))), '', 'confirm_setdraft', $formQuestion, 'yes', 'actionButtonNewVersion', 650, 600); - } // Validate confirmation if (($action == 'set_validate' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { - $imgPath = dol_buildpath('custom/saturne/img/formconfirm/object_version_draft.png', 1); - $img = img_picto($langs->trans('Validate'), $imgPath, '', 1); - $formQuestion = [ - ['type' => 'other', 'name' => 'lock_validation', 'label' => '' . img_picto('', 'info') . ' ' . $langs->trans('ConfirmValidateObject', $langs->transnoentities('The' . ucfirst($object->element)), $langs->transnoentities('The' . ucfirst($object->element))) . ''], - ['type' => 'other', 'name' => 'OK', 'label' => '', 'value' => $img, 'moreattr' => 'readonly'], - ]; - - $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('ValidateObject', $langs->transnoentities('The' . ucfirst($object->element))), '', 'confirm_set_validate', $formQuestion, 'yes', 'actionButtonValidate', 650, 600); + $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('ValidateObject', $langs->transnoentities('The' . ucfirst($object->element))), $langs->trans('ConfirmValidateObject', $langs->transnoentities('The' . ucfirst($object->element)), $langs->transnoentities('The' . ucfirst($object->element))), 'confirm_set_validate', '', 'yes', 'actionButtonValidate', 350, 600); } + // Lock confirmation + if (($action == 'lock' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { + $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('LockObject', $langs->transnoentities('The' . ucfirst($object->element))), $langs->trans('ConfirmLockObject', $langs->transnoentities('The' . ucfirst($object->element))), 'confirm_lock', '', 'yes', 'actionButtonLock', 350, 600); + } // Archive confirmation if (($action == 'set_archive' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { - $imgPath = dol_buildpath('custom/saturne/img/formconfirm/object_version_validate.png', 1); - $img = img_picto($langs->trans('Versioning'), $imgPath, '', 1); - $formQuestion = [ - ['type' => 'other', 'name' => 'lock_validation', 'label' => '' . img_picto('', 'info') . ' ' . $langs->trans('ConfirmVersionObject', $langs->transnoentities('The' . ucfirst($object->element))). ''], - ['type' => 'other', 'name' => 'OK', 'label' => '', 'value' => $img, 'moreattr' => 'readonly'], - ]; - - $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('VersionObject', $langs->transnoentities('The' . ucfirst($object->element))), '', 'confirm_archive', $formQuestion, 'yes', 'actionButtonArchive', 650, 600); + $formConfirm .= $form->formconfirm($_SERVER['PHP_SELF'] . '?id=' . $object->id, $langs->trans('ArchiveObject', $langs->transnoentities('The' . ucfirst($object->element))), $langs->trans('ConfirmArchiveObject', $langs->transnoentities('The' . ucfirst($object->element))), 'confirm_archive', '', 'yes', 'actionButtonArchive', 350, 600); } // Clone confirmation if (($action == 'clone' && (empty($conf->use_javascript_ajax) || !empty($conf->dol_use_jmobile))) || (!empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))) { @@ -442,6 +397,16 @@ print '' . $displayButton . ''; } + // Lock. + $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('Lock'); + if ($object->status == AccidentInvestigation::STATUS_VALIDATED && $allSigned) { + print '' . $displayButton . ''; + } else if ($object->status < AccidentInvestigation::STATUS_VALIDATED) { + print '' . $displayButton . ''; + } else { + print '' . $displayButton . ''; + } + // Send email. $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('SendMail') . ' '; if ($object->status >= AccidentInvestigation::STATUS_VALIDATED) { @@ -450,20 +415,12 @@ print '' . $displayButton . ''; } - // Versioning. - $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('Versioning'); - if ($object->status == AccidentInvestigation::STATUS_VALIDATED && $allSigned) { + // Archive. + $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('Archive'); + if ($object->status == AccidentInvestigation::STATUS_LOCKED) { print '' . $displayButton . ''; } else { - print '' . $displayButton . ''; - } - - // New version. - $displayButton = $onPhone ? '' : '' . ' ' . $langs->trans('NewVersion'); - if ($object->status == AccidentInvestigation::STATUS_ARCHIVED) { - print '' . $displayButton . ''; - } else { - print '' . $displayButton . ''; + print '' . $displayButton . ''; } // Clone. @@ -490,8 +447,7 @@ $fileDir = $upload_dir . '/' . $dirFiles; $urlSource = $_SERVER['PHP_SELF'] . '?id=' . $object->id; - print saturne_show_documents('digiriskdolibarr:' . ucfirst('AccidentInvestigation') . 'Document', $dirFiles, $fileDir, $urlSource, $permissiontoadd, 0, $conf->global->DIGIRISKDOLIBARR_ACCIDENTINVESTIGATIONDOCUMENT_DEFAULT_MODEL, 1, 0, 0, 0, 0, '', '', $langs->defaultlang, '', $object, 0, 'remove_file', 0, $langs->trans('DocumentGeneratedWithVersioning')); - + print saturne_show_documents('digiriskdolibarr:' . ucfirst('AccidentInvestigation') . 'Document', $dirFiles, $fileDir, $urlSource, $permissiontoadd, 0, $conf->global->DIGIRISKDOLIBARR_ACCIDENTINVESTIGATIONDOCUMENT_DEFAULT_MODEL, 1, 0, 0, 0, 0, '', '', $langs->defaultlang, '', $object, 0, 'remove_file', (($object->status > $object::STATUS_VALIDATED) ? 1 : 0), $langs->trans('ObjectMustBeLockedToGenerate', ucfirst($langs->transnoentities('The' . ucfirst($object->element))))); print '
'; $moreHtmlCenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', dol_buildpath('/saturne/view/saturne_agenda.php', 1) . '?id=' . $object->id . '&module_name=digiriskdolibarr&object_type=' . $object->element); diff --git a/view/digiriskelement/digiriskelement_card.php b/view/digiriskelement/digiriskelement_card.php index a55a66532..3b5b3dd6e 100644 --- a/view/digiriskelement/digiriskelement_card.php +++ b/view/digiriskelement/digiriskelement_card.php @@ -298,8 +298,15 @@ include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; if ($id != $conf->global->DIGIRISKDOLIBARR_DIGIRISKELEMENT_TRASH) { - print '
' . $langs->trans("ParentElement") . ''; - print $object->selectDigiriskElementList($object->fk_parent, 'fk_parent', ['customsql' => 'element_type="groupment" AND t.rowid NOT IN (' . implode(',', $deletedElements) . ')'], 0, 0, [], 0, 0, 'minwidth100', GETPOST('id'), false); + $children = $object->fetchDigiriskElementFlat($id); + $childrenElements = []; + if (is_array($children) && !empty($children)) { + foreach ($children as $key => $value) { + $childrenElements[$key] .= $key; + } + } + print '
' . $langs->trans("ParentElement") . ''; + print $object->selectDigiriskElementList($object->fk_parent, 'fk_parent', ['customsql' => 'element_type="groupment" AND t.rowid NOT IN (' . implode(',', $deletedElements) . ',' . implode(',', $childrenElements) . ')'], 0, 0, [], 0, 0, 'minwidth100', GETPOST('id')); } print '
' . "\n"; + +print '
'; +print '
'; + +print dol_get_fiche_end(); + +// Document Generation -- Génération des documents +$dirFiles = 'registerdocument'; +$filedir = $upload_dir . '/' . $dirFiles ; +$urlsource = $_SERVER["PHP_SELF"]; +$modulepart = 'digiriskdolibarr:RegisterDocument'; + +if ($permissiontoadd || $permissiontoread) { + $genallowed = 1; +} + +print saturne_show_documents($modulepart, $dirFiles, $filedir, $urlsource, 1,1, '', 1, 0, 0, 0, 0, '', 0, '', empty($soc->default_lang) ? '' : $soc->default_lang, $object); + +// End of page +llxFooter(); +$db->close(); diff --git a/view/firepermit/firepermit_card.php b/view/firepermit/firepermit_card.php index e65cf6634..3dbd36d2f 100644 --- a/view/firepermit/firepermit_card.php +++ b/view/firepermit/firepermit_card.php @@ -690,6 +690,7 @@ print $htmltext; print ''; print $form->selectcontacts((empty(GETPOST('ext_society', 'int')) ? -1 : GETPOST('ext_society', 'int')), $extSocietyResponsibleId, 'ext_society_responsible', 1, '', '', 1, 'minwidth100imp widthcentpercentminusxx maxwidth400'); + print ''; print ''; //Labour inspector Society -- Entreprise Inspecteur du travail @@ -821,7 +822,8 @@ print $htmltext; print ''; print $form->selectcontacts($extSociety->id, dol_strlen($contact->email) ? $extSocietyResponsibleId : -1, 'ext_society_responsible', '', 0, '', 1, 'minwidth100imp widthcentpercentminusxx maxwidth400'); - print ''; + print 'id) ? '' : $extSociety->id)) . '" target="_blank">'; + print ''; if (is_array($objectResources['LabourInspector']) && $objectResources['LabourInspector'] > 0) { $labourInspectorSociety = array_shift($objectResources['LabourInspector']); diff --git a/view/firepermit/firepermit_list.php b/view/firepermit/firepermit_list.php index 1d7953796..4602a3804 100644 --- a/view/firepermit/firepermit_list.php +++ b/view/firepermit/firepermit_list.php @@ -246,9 +246,9 @@ $sql .= " FROM " . MAIN_DB_PREFIX . $object->table_element . " as t"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $object->table_element . "_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (" . getEntity($object->element) . ")"; -else $sql .= " WHERE 1 = 1"; -$sql .= ' AND status != 0'; +if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (" . getEntity($object->element) . ")"; +else $sql .= " WHERE 1 = 1"; +$sql .= ' AND status != -1'; foreach ($search as $key => $val) { diff --git a/view/preventionplan/preventionplan_card.php b/view/preventionplan/preventionplan_card.php index b32f3998c..10f96e8b6 100644 --- a/view/preventionplan/preventionplan_card.php +++ b/view/preventionplan/preventionplan_card.php @@ -693,6 +693,7 @@ print $htmltext; print ''; print $form->selectcontacts((empty(GETPOST('ext_society', 'int')) ? -1 : GETPOST('ext_society', 'int')), $extSocietyResponsibleId, 'ext_society_responsible', 1, '', '', 1, 'minwidth100imp widthcentpercentminusxx maxwidth400'); + print ''; print ''; // CSSCT Intervention @@ -839,7 +840,8 @@ print $htmltext; print ''; print $form->selectcontacts($extSociety->id, dol_strlen($contact->email) ? $extSocietyResponsibleId : -1, 'ext_society_responsible', '', 0, '', 1, 'minwidth100imp widthcentpercentminusxx maxwidth400'); - print ''; + print 'id) ? '' : $extSociety->id)) . '" target="_blank">'; + print ''; // CSSCT Intervention print ''; diff --git a/view/preventionplan/preventionplan_list.php b/view/preventionplan/preventionplan_list.php index 5e93367c4..0b6f4c032 100644 --- a/view/preventionplan/preventionplan_list.php +++ b/view/preventionplan/preventionplan_list.php @@ -281,9 +281,9 @@ $sql .= " FROM " . MAIN_DB_PREFIX . $object->table_element . " as t"; if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $object->table_element . "_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (" . getEntity($object->element) . ")"; -else $sql .= " WHERE 1 = 1"; -$sql .= ' AND status !=0'; +if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (" . getEntity($object->element) . ")"; +else $sql .= " WHERE 1 = 1"; +$sql .= ' AND status != -1'; foreach ($search as $key => $val) { @@ -348,10 +348,10 @@ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; -$arrayfields['MasterWorker'] = array('label' => 'MasterWorker', 'checked' => 1); -$arrayfields['ExtSociety'] = array('label' => 'ExtSociety', 'checked' => 1); -$arrayfields['ExtSocietyResponsible'] = array('label' => 'ExtSocietyResponsible', 'checked' => 1); -$arrayfields['ExtSocietyAttendant'] = array('label' => 'ExtSocietyAttendant', 'checked' => 1); +$arrayfields['MasterWorker'] = array('label' => 'MasterWorker', 'checked' => 1); +$arrayfields['ExtSociety'] = array('label' => 'ExtSociety', 'checked' => 1); +$arrayfields['ExtSocietyResponsible'] = array('label' => 'ExtSocietyResponsible', 'checked' => 1); +$arrayfields['ExtSocietyAttendant'] = array('label' => 'ExtSocietyAttendant', 'checked' => 1); print_barre_liste($form->textwithpicto($title, $texthelp), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -362,10 +362,10 @@ print '' . "\n"; print ''; -$object->fields['Custom']['MasterWorker'] = $arrayfields['MasterWorker'] ; -$object->fields['Custom']['ExtSociety'] = $arrayfields['ExtSociety']; -$object->fields['Custom']['ExtSocietyResponsible'] = $arrayfields['ExtSocietyResponsible']; -$object->fields['Custom']['ExtSocietyAttendant'] = $arrayfields['ExtSocietyAttendant'] ; +$object->fields['Custom']['MasterWorker'] = $arrayfields['MasterWorker'] ; +$object->fields['Custom']['ExtSociety'] = $arrayfields['ExtSociety']; +$object->fields['Custom']['ExtSocietyResponsible'] = $arrayfields['ExtSocietyResponsible']; +$object->fields['Custom']['ExtSocietyAttendant'] = $arrayfields['ExtSocietyAttendant'] ; foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); diff --git a/view/ticket/ticketstatscsv.php b/view/ticket/ticketstatscsv.php index c01aedc76..efc08c3af 100644 --- a/view/ticket/ticketstatscsv.php +++ b/view/ticket/ticketstatscsv.php @@ -21,20 +21,14 @@ * \brief Page with tickets statistics CSV */ -// Load Dolibarr environment -$res = 0; -// Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) -if ( ! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res = @include $_SERVER["CONTEXT_DOCUMENT_ROOT"] . "/main.inc.php"; -// Try main.inc.php into web root detected using web root calculated from SCRIPT_FILENAME -$tmp = empty($_SERVER['SCRIPT_FILENAME']) ? '' : $_SERVER['SCRIPT_FILENAME']; $tmp2 = realpath(__FILE__); $i = strlen($tmp) - 1; $j = strlen($tmp2) - 1; -while ($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i] == $tmp2[$j]) { $i--; $j--; } -if ( ! $res && $i > 0 && file_exists(substr($tmp, 0, ($i + 1)) . "/main.inc.php")) $res = @include substr($tmp, 0, ($i + 1)) . "/main.inc.php"; -if ( ! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php")) $res = @include dirname(substr($tmp, 0, ($i + 1))) . "/main.inc.php"; -// Try main.inc.php using relative path -if ( ! $res && file_exists("../../main.inc.php")) $res = @include "../../main.inc.php"; -if ( ! $res && file_exists("../../../main.inc.php")) $res = @include "../../../main.inc.php"; -if ( ! $res && file_exists("../../../../main.inc.php")) $res = @include "../../../../main.inc.php"; -if ( ! $res) die("Include of main fails"); +// Load DigiriskDolibarr environment +if (file_exists('../../digiriskdolibarr.main.inc.php')) { + require_once __DIR__ . '/../../digiriskdolibarr.main.inc.php'; +} elseif (file_exists('../../../digiriskdolibarr.main.inc.php')) { + require_once __DIR__ . '/../../../digiriskdolibarr.main.inc.php'; +} else { + die('Include of digiriskdolibarr main fails'); +} // Global variables definitions global $conf, $db, $langs, $user; @@ -46,7 +40,7 @@ require_once __DIR__ . '/../../class/ticketdigiriskstats.class.php'; // Load translation files required by the page -$langs->loadLangs(array('other')); +saturne_load_langs(); // Get parameters $action = GETPOST('action', 'aZ09'); @@ -55,19 +49,20 @@ $stats = new TicketDigiriskStats($db); // Security check -if (!$user->rights->ticket->read) { - accessforbidden(); -} +$permissiontoread = $user->rights->ticket->read; $upload_dir = $conf->digiriskdolibarr->multidir_output[$conf->entity]; $upload_dir = $upload_dir . '/ticketstats/'; dol_mkdir($upload_dir); +saturne_check_access($permissiontoread); + /* * Action */ if ($action == 'generate_csv') { + $categorie = new Categorie($db); // Open a file in write mode ('w') $now = dol_now(); $filename = dol_print_date($now, 'dayxcard') . '_ticketstats.csv'; @@ -78,18 +73,49 @@ $fp = fopen($upload_dir . $filename, 'w'); - $data = $stats->getNbTicketByDigiriskElementAndTicketTags((!empty($daterange) ? $date_start : 0), (!empty($daterange) ? $date_end : 0)); - if (is_array($data) && !empty($data)) { + list($data, $ticketCategoriesCounter) = $stats->getNbTicketByDigiriskElementAndTicketTags((!empty($daterange) ? $date_start : 0), (!empty($daterange) ? $date_end : 0)); + + fputcsv($fp, [$langs->transnoentities('ConcernedTimePeriod') . ' : ' . dol_print_date($date_start) . ' ' . $langs->trans('To') . ' ' . dol_print_date($date_end)]); + + fputcsv($fp, []); + fputcsv($fp, []); + fputcsv($fp, []); + + if (is_array($ticketCategoriesCounter) && !empty($ticketCategoriesCounter)) { + foreach($ticketCategoriesCounter as $ticketCategoryName => $ticketCategoryCounter) { + fputcsv($fp, [$ticketCategoryName => $ticketCategoryName . ' : ' . $ticketCategoryCounter]); + } + } + + fputcsv($fp, []); + fputcsv($fp, []); + fputcsv($fp, []); + + if (is_array($data) && !empty($data)) { + // Loop through file pointer and a line - $arrayCat = array_keys(reset($data)); - array_unshift($arrayCat, $langs->trans('GP/UT')); - fputcsv($fp, $arrayCat); + $arrayCat = array_keys($data['labels']); + + foreach($arrayCat as $categoryId) { + if (is_int($categoryId)) { + $categorie->fetch($categoryId); + $arrayCatWithLabels[$categoryId] = $categorie->label; + } else { + $arrayCatWithLabels[$categoryId] = $categoryId; + } + } + + unset($data['labels']); + + array_unshift($arrayCatWithLabels, $langs->trans('GP/UT')); + fputcsv($fp, $arrayCatWithLabels); $i = 0; foreach ($data as $row) { array_unshift($row, array_keys($data)[$i]); fputcsv($fp, $row); $i++; } + fclose($fp); setEventMessages($langs->trans('SuccessGenerateCSV', $filename), null); } else {