diff --git a/README.md b/README.md index 56fd94d28..1fe2595b7 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ ## Informations - Numéro du module : 436302 -- Dernière mise à jour : 24/06/2024 +- Dernière mise à jour : 12/12/2024 - Éditeur : [Evarisk](https://evarisk.com) - Thème : Eldy Menu - Licence : GPLv3 @@ -11,10 +11,10 @@ ### Version -- Version : 10.2.1 +- Version : 20.0.0 - PHP : 7.4.33 -- Compatibilité : Dolibarr 16.0.0 - 20.0.0 -- Saturne Framework : 1.5.1 +- Compatibilité : Dolibarr 20.0.0 - 20.0.2 +- Saturne Framework : 1.7.0 ## Liens diff --git a/admin/config/riskassessmentdocument.php b/admin/config/riskassessmentdocument.php index a18387bb3..1623f1731 100644 --- a/admin/config/riskassessmentdocument.php +++ b/admin/config/riskassessmentdocument.php @@ -162,7 +162,7 @@ // Configuration header $head = digiriskdolibarr_admin_prepare_head(); -print dol_get_fiche_head($head, 'riskassessmentdocument', $title, -1, "digiriskdolibarr_color@digiriskdolibarr"); +print dol_get_fiche_head($head, 'riskassessmentdocument', $title, -1, 'digiriskdolibarr_color@digiriskdolibarr'); // Risks @@ -449,7 +449,7 @@ ], 'ShowSharedRiskSigns' => [ 'name' => 'ShowSharedRiskSigns', - 'description' => $langs->trans('ShowSharedRiskSignsDescription') . (!$areRisksSharable ? '
' . img_picto('danger', 'fa-exclamation-triangle') . $langs->trans('DisabledSharedElement') : ''), + 'description' => $langs->trans('ShowSharedRiskSignsDescription') . (!$areRisksSignsSharable ? '
' . img_picto('danger', 'fa-exclamation-triangle') . $langs->trans('DisabledSharedElement') : ''), 'code' => 'DIGIRISKDOLIBARR_SHOW_SHARED_RISKSIGNS', 'disabled' => !$areRisksSignsSharable diff --git a/admin/event.php b/admin/event.php index 37bf9941b..3a39a560e 100644 --- a/admin/event.php +++ b/admin/event.php @@ -108,10 +108,9 @@ // Configuration header $head = digiriskdolibarr_admin_prepare_head(); -print dol_get_fiche_head($head, 'event', '', -1, $module->picto); +print dol_get_fiche_head($head, 'event', '', -1, "digiriskdolibarr_color@digiriskdolibarr"); print load_fiche_titre(' ' . $langs->trans('ConfTrigger'), '', ''); -print '
'; print ''; print ''; diff --git a/admin/securityconf.php b/admin/securityconf.php index 2645ec078..8aca506ba 100644 --- a/admin/securityconf.php +++ b/admin/securityconf.php @@ -435,14 +435,15 @@ print ''; print ''; print ''; // * Phone number - Numéro de téléphone * - print ''; print ''; + // Use signatory + print ''; + print ''; + print ''; + + // Show category description + print ''; + print ''; + print ''; + if (isModEnabled('multicompany')) { //Page de sélection de l'entité print ''; @@ -445,7 +471,7 @@ print ''; // GP/UT Visible and Required - print ''; + print ''; print ''; @@ -453,7 +479,7 @@ print ajax_constantonoff('DIGIRISKDOLIBARR_TICKET_DIGIRISKELEMENT_REQUIRED'); print ''; print ''; print ''; @@ -471,7 +497,7 @@ print ''; // Firstname Visible and Required - print ''; + print ''; print ''; @@ -479,12 +505,12 @@ print ajax_constantonoff('DIGIRISKDOLIBARR_TICKET_FIRSTNAME_REQUIRED'); print ''; print ''; print ''; // Lastname Visible and Required - print ''; + print ''; print ''; @@ -492,7 +518,7 @@ print ajax_constantonoff('DIGIRISKDOLIBARR_TICKET_LASTNAME_REQUIRED'); print ''; print ''; print ''; diff --git a/class/accident.class.php b/class/accident.class.php index ba59e243e..62c1ed6d9 100644 --- a/class/accident.class.php +++ b/class/accident.class.php @@ -412,28 +412,49 @@ public function LibStatut(int $status, int $mode = 0): string */ public function load_dashboard(): array { - global $conf, $langs; + global $langs, $conf; + + $confName = dol_strtoupper($this->module) . '_DASHBOARD_CONFIG'; + $dashboardConfig = json_decode(getDolUserString($confName)); + $array = ['graphs' => [], 'disabledGraphs' => []]; + + $join = ' LEFT JOIN ' . MAIN_DB_PREFIX . $this->table_element . ' as a ON a.rowid = t.fk_accident'; + $accidentsWithWorkStops = saturne_fetch_all_object_type('AccidentWorkStop', 'DESC', 't.rowid', 0, 0, [], 'AND', false, true, false, $join); + $accidents = $this->fetchAll('', '', 0, 0, ['customsql' => ' t.status > ' . self::STATUS_DRAFT]); + + if (empty($accidents) && !is_array($accidents)) { + $accidents = []; + } + if (empty($accidentsWithWorkStops) && !is_array($accidentsWithWorkStops)) { + $accidentsWithWorkStops = []; + } + + $arrayNbDaysWithoutAccident = $this->getNbDaysWithoutAccident($accidents); + $arrayNbWorkstopDays = $this->getNbWorkstopDays($accidentsWithWorkStops); - $arrayNbDaysWithoutAccident = $this->getNbDaysWithoutAccident(); - $arrayNbAccidents = $this->getNbAccidents(); - $arrayNbAccidentsLast3Years = $this->getNbAccidentsLast3years(); - $arrayNbWorkstopDays = $this->getNbWorkstopDays(); - $arrayNbAccidentsByEmployees = $this->getNbAccidentsByEmployees(); $arrayNbPresquAccidents = $this->getNbPresquAccidents(); $arrayNbAccidentInvestigations = $this->getNbAccidentInvestigations(); - $arrayFrequencyIndex = $this->getFrequencyIndex(); - $arrayFrequencyRate = $this->getFrequencyRate(); - //$arrayGravityIndex = $this->getGravityIndex(); - $arrayGravityRate = $this->getGravityRate(); + + $evaluator = new Evaluator($this->db); + $employees = $evaluator->getNbEmployees(); + $arrayNbAccidentsByEmployees = $this->getNbAccidentsByEmployees($accidents, $accidentsWithWorkStops, $employees); + $arrayFrequencyIndex = $this->getFrequencyIndex($accidentsWithWorkStops, $employees); + $arrayFrequencyRate = $this->getFrequencyRate($accidentsWithWorkStops); + $arrayGravityRate = $this->getGravityRate($accidentsWithWorkStops); $array['widgets'] = [ 'accident' => [ + 'title' => $langs->transnoentities('Accidents'), + 'picto' => 'fas fa-user-injured', + 'pictoColor' => '#F39B1F', 'label' => [$langs->transnoentities('DayWithoutAccident') ?? '', $langs->transnoentities('WorkStopDays') ?? '', $langs->transnoentities('NbAccidentsByEmployees') ?? '', $langs->transnoentities('NbPresquAccidents') ?? '', $langs->transnoentities('NbAccidentInvestigations') ?? ''], 'content' => [$arrayNbDaysWithoutAccident['daywithoutaccident'] ?? 0, $arrayNbWorkstopDays['nbworkstopdays'] ?? 0, $arrayNbAccidentsByEmployees['nbaccidentsbyemployees'] ?? 0, $arrayNbPresquAccidents['nbpresquaccidents'] ?? 0, $arrayNbAccidentInvestigations['nbaccidentinvestigations'] ?? 0], - 'picto' => 'fas fa-user-injured', 'widgetName' => $langs->transnoentities('Accident') ], 'accidentrateindicator' => [ + 'title' => $langs->transnoentities('Frequency'), + 'picto' => 'fas fa-chart-bar', + 'pictoColor' => '#9735FF', 'label' => [$langs->transnoentities('FrequencyIndex') ?? '', $langs->transnoentities('FrequencyRate') ?? '', $langs->transnoentities('GravityRate') ?? ''], 'content' => [$arrayFrequencyIndex['frequencyindex'] ?? 0, $arrayFrequencyRate['frequencyrate'] ?? 0, $arrayGravityRate['gravityrate'] ?? 0], 'tooltip' => [ @@ -441,46 +462,56 @@ public function load_dashboard(): array (($conf->global->DIGIRISKDOLIBARR_NB_WORKED_HOURS > 0 && $conf->global->DIGIRISKDOLIBARR_MANUAL_INPUT_NB_WORKED_HOURS) ? $langs->transnoentities('FrequencyRateTooltip') . '
' . $langs->transnoentities('NbWorkedHoursTooltip') : $langs->transnoentities('FrequencyRateTooltip')), (($conf->global->DIGIRISKDOLIBARR_NB_WORKED_HOURS > 0 && $conf->global->DIGIRISKDOLIBARR_MANUAL_INPUT_NB_WORKED_HOURS) ? $langs->transnoentities('GravityRateTooltip') . '
' . $langs->transnoentities('NbWorkedHoursTooltip') : $langs->transnoentities('GravityRateTooltip')) ], - 'picto' => 'fas fa-chart-bar', 'widgetName' => $langs->transnoentities('AccidentRateIndicator') ] ]; - $array['graphs'] = [$arrayNbAccidents, $arrayNbAccidentsLast3Years]; + if (empty($dashboardConfig->graphs->AccidentRepartition->hide)) { + $array['graphs'][] = $this->getNbAccidents($accidents, $accidentsWithWorkStops); + } else { + $array['disabledGraphs']['AccidentRepartition'] = $langs->transnoentities('AccidentRepartition'); + } + if (empty($dashboardConfig->graphs->AccidentByYear->hide)) { + $array['graphs'][] = $this->getNbAccidentsLast3years($accidents); + } else { + $array['disabledGraphs']['AccidentByYear'] = $langs->transnoentities('AccidentByYear'); + } return $array; } - /** - * Get number days without accident. - * - * @return array - * @throws Exception - */ - public function getNbDaysWithoutAccident() { - // Number days without accident - $lastAccident = $this->fetchAll('DESC', 'accident_date', 1, 0 ); - if (is_array($lastAccident) && !empty($lastAccident)) { - $lastTimeAccident = dol_now() - reset($lastAccident)->accident_date; - $array['daywithoutaccident'] = abs(round($lastTimeAccident / 86400)); - } else { - $array['daywithoutaccident'] = 'N/A'; - } - return $array; - } + /** + * Get number days without accident + * + * @param array $accidents Array of accidents + * @return array + */ + public function getNbDaysWithoutAccident(array $accidents = []): array + { + $lastAccident = end($accidents); + if ($lastAccident != null) { + $lastTimeAccident = dol_now() - $lastAccident->accident_date; + $array['daywithoutaccident'] = abs(round($lastTimeAccident / 86400)); + } else { + $array['daywithoutaccident'] = 'N/A'; + } + return $array; + } /** * Get number accidents * + * @param array $accidents Array of accidents + * @param array $accidentsWithWorkStops Array of accidents with work stops * @return array - * @throws Exception */ - public function getNbAccidents(): array + public function getNbAccidents(array $accidents = [], array $accidentsWithWorkStops = []): array { global $conf, $langs; // Graph Title parameters $array['title'] = $langs->transnoentities('AccidentRepartition'); + $array['name'] = 'AccidentRepartition'; $array['picto'] = $this->picto; // Graph parameters @@ -501,25 +532,8 @@ public function getNbAccidents(): array ], ]; - $nbAccidents = 0; - $nbAccidentsWithoutDIAT = 0; - $accidents = $this->fetchAll('','',0,0,['customsql' => ' t.status > 0 ']); - if (is_array($accidents) && !empty($accidents)) { - $accidentWorkStop = new AccidentWorkStop($this->db); - foreach ($accidents as $accident) { - $accidentWorkStops = $accidentWorkStop->fetchFromParent($accident->id); - if (is_array($accidentWorkStops) && !empty($accidentWorkStops)) { - $nbAccidents += 1; - } else { - $nbAccidentsWithoutDIAT += 1; - } - } - $array['data']['accidents'] = $nbAccidents; - $array['data']['accidentswithoutDIAT'] = $nbAccidentsWithoutDIAT; - } else { - $array['data']['accidents'] = 0; - $array['data']['accidentswithoutDIAT'] = 0; - } + $array['data']['accidents'] = count($accidentsWithWorkStops); + $array['data']['accidentswithoutDIAT'] = count($accidents) - $array['data']['accidents']; return $array; } @@ -527,15 +541,16 @@ public function getNbAccidents(): array /** * Get number accidents for last 3 years * + * @param array $accidents Array of accidents * @return array - * @throws Exception */ - public function getNbAccidentsLast3years(): array + public function getNbAccidentsLast3years(array $accidents = []): array { global $langs; // Graph Title parameters $array['title'] = $langs->transnoentities('AccidentByYear'); + $array['name'] = 'AccidentByYear'; $array['picto'] = $this->picto; // Graph parameters @@ -562,12 +577,14 @@ public function getNbAccidentsLast3years(): array $accidentsByYear = []; $accidentsArray = []; - $accidents = $this->fetchAll('', '', 0, 0, ['customsql' => 't.status > 0']); if (is_array($accidents) && !empty($accidents)) { foreach($accidents as $accident) { $accidentDate = dol_getdate($accident->accident_date); $yearKey = $accidentDate['year']; $monthKey = $accidentDate['mon']; + if (!isset($accidentsByYear[$yearKey][$monthKey - 1])) { + $accidentsByYear[$yearKey][$monthKey - 1] = 0; + } $accidentsByYear[$yearKey][$monthKey - 1] += 1; } @@ -593,181 +610,157 @@ public function getNbAccidentsLast3years(): array return $array; } - /** - * Get number workstop days. - * - * @return array - * @throws Exception - */ - public function getNbWorkstopDays() { - // Number workstop days - $allaccidents = $this->fetchAll(); - if (is_array($allaccidents) && !empty($allaccidents)) { - $accidentworkstop = new AccidentWorkStop($this->db); - foreach ($allaccidents as $accident) { - $allaccidentworkstop = $accidentworkstop->fetchFromParent($accident->id); - if (is_array($allaccidentworkstop) && !empty($allaccidentworkstop)) { - foreach ($allaccidentworkstop as $accidentworkstop) { - if ($accidentworkstop->id > 0) { - $nbworkstopdays += $accidentworkstop->workstop_days; - } - } - } - } - $array['nbworkstopdays'] = $nbworkstopdays ?: 0; - } else { - $array['nbworkstopdays'] = 0; - } - return $array; - } + /** + * Get number workstop days + * + * @param array $accidentsWithWorkStops Array of accidents with work stops + * @return array + */ + public function getNbWorkstopDays(array $accidentsWithWorkStops = []): array + { + $nbWorkStopDays = 0; + if (!empty($accidentsWithWorkStops)) { + foreach ($accidentsWithWorkStops as $accidentsWithWorkStop) { + $nbWorkStopDays += $accidentsWithWorkStop->workstop_days; + } + } + $array['nbworkstopdays'] = $nbWorkStopDays; - /** - * Get number accidents by employees. - * - * @return array - * @throws Exception - */ - public function getNbAccidentsByEmployees() { - $evaluator = new Evaluator($this->db); - - // Number accidents by employees - $arrayNbAccidents = $this->getNbAccidents(); - $arrayNbEmployees = $evaluator->getNbEmployees(); - if ($arrayNbEmployees['nbemployees'] > 0) { - $nbaccidentsbyemployees = ($arrayNbAccidents['data']['accidents'] + $arrayNbAccidents['data']['accidentswithoutDIAT']) / $arrayNbEmployees['nbemployees']; - if ($nbaccidentsbyemployees > 0) { - $array['nbaccidentsbyemployees'] = price2Num($nbaccidentsbyemployees, 2); - } else { - $array['nbaccidentsbyemployees'] = 'N/A'; - } - } else { - $array['nbaccidentsbyemployees'] = 'N/A'; - } - return $array; - } + return $array; + } - /** - * Get number presqu'accidents. - * - * @return array - * @throws Exception - */ - public function getNbPresquAccidents() { - global $langs; + /** + * Get number accidents by employees + * + * @param array $accidents Array of accidents + * @param array $accidentsWithWorkStops Array of accidents with work stops + * @param array $employees Array of employees + * @return array + */ + public function getNbAccidentsByEmployees(array $accidents = [], array $accidentsWithWorkStops = [], array $employees = []): array + { + $arrayNbAccidents = $this->getNbAccidents($accidents, $accidentsWithWorkStops); + if ($employees['nbemployees'] > 0 && ($arrayNbAccidents['data']['accidents'] + $arrayNbAccidents['data']['accidentswithoutDIAT']) > 0) { + $nbAccidentsByEmployees = ($arrayNbAccidents['data']['accidents'] + $arrayNbAccidents['data']['accidentswithoutDIAT']) / $employees['nbemployees']; + $array['nbaccidentsbyemployees'] = price2Num($nbAccidentsByEmployees, 2); + } else { + $array['nbaccidentsbyemployees'] = 'N/A'; + } + return $array; + } - $category = new Categorie($this->db); + /** + * Get number presqu'accidents + * + * @return array + * @throws Exception + */ + public function getNbPresquAccidents(): array + { + global $langs; - // Number accidents presqu'accidents - $category->fetch(0, $langs->transnoentities('PresquAccident')); - $alltickets = $category->getObjectsInCateg(Categorie::TYPE_TICKET); - if (is_array($alltickets) && !empty($alltickets)) { - $array['nbpresquaccidents'] = count($alltickets); - } else { - $array['nbpresquaccidents'] = 'N/A'; - } - return $array; - } + $category = new Categorie($this->db); - /** - * Get number accident investigations. - * - * @return array - * @throws Exception - */ - public function getNbAccidentInvestigations() { - // Number accident investigations - $allaccidents = $this->fetchAll(); - if (is_array($allaccidents) && !empty($allaccidents)) { - $accidentmetadata = new AccidentMetaData($this->db); - foreach ($allaccidents as $accident) { - $filter = ' AND t.fk_accident = ' . $accident->id . ' AND t.status = 1 AND t.accident_investigation = 1'; - $result = $accidentmetadata->fetch(0, '', $filter); - if ($result > 0) { - $nbaccidentinvestigations += 1; - } - } - if ($nbaccidentinvestigations > 0) { - $array['nbaccidentinvestigations'] = $nbaccidentinvestigations; - } else { - $array['nbaccidentinvestigations'] = 'N/A'; - } - } else { - $array['nbaccidentinvestigations'] = 'N/A'; - } - return $array; - } + $category->fetch(0, $langs->transnoentities('PresquAccident')); + $tickets = $category->getObjectsInCateg(Categorie::TYPE_TICKET); + if (!empty($tickets) && is_array($tickets)) { + $array['nbpresquaccidents'] = count($tickets); + } else { + $array['nbpresquaccidents'] = 'N/A'; + } + return $array; + } - /** - * Get frequency index (number accidents with DIAT by employees) x 1000. - * - * @return array - * @throws Exception - */ - public function getFrequencyIndex() { - $evaluator = new Evaluator($this->db); - - // (Number accidents with DIAT by employees) x 1 000 - $arrayNbAccidents = $this->getNbAccidents(); - $arrayNbEmployees = $evaluator->getNbEmployees(); - if ($arrayNbEmployees['nbemployees'] > 0) { - $frequencyindex = ($arrayNbAccidents['data']['accidents']/$arrayNbEmployees['nbemployees']) * 1000; - if ($frequencyindex > 0) { - $array['frequencyindex'] = price2Num($frequencyindex, 2); - } else { - $array['frequencyindex'] = 'N/A'; - } - } else { - $array['frequencyindex'] = 'N/A'; - } - return $array; - } + /** + * Get number accident investigations + * + * @param array $moreParam More param (Object/user/etc) + * @return array + * @throws Exception + */ + public function getNbAccidentInvestigations(array $moreParam = []): array + { + require_once __DIR__ . '/accidentinvestigation.class.php'; - /** - * Get frequency rate (number accidents with DIAT by working hours) x 1 000 000. - * - * @return array - * @throws Exception - */ - public function getFrequencyRate() { - // (Number accidents with DIAT by working hours) x 1 000 000 - $arrayNbAccidents = $this->getNbAccidents(); - $total_workhours = getWorkedHours(); - - if ($total_workhours > 0) { - $frequencyrate = ($arrayNbAccidents['data']['accidents']/$total_workhours) * 1000000; - if ($frequencyrate > 0) { - $array['frequencyrate'] = price2Num($frequencyrate, 5); - } else { - $array['frequencyrate'] = 'N/A'; - } - } else { - $array['frequencyrate'] = 'N/A'; - } - return $array; - } + $accidentInvestigation = new AccidentInvestigation($this->db); + if (isset($moreParam['filter']) && strpos($moreParam['filter'], 't.entity') !== false) { + $accidentInvestigation->ismultientitymanaged = 0; + } + $accidentInvestigations = $accidentInvestigation->fetchAll('', '', 0, 0, ['customsql' => ' t.status > ' . AccidentInvestigation::STATUS_DRAFT . ($moreParam['filter'] ?? '')]); + if (!empty($accidentInvestigations) && is_array($accidentInvestigations)) { + $array['nbaccidentinvestigations'] = count($accidentInvestigations); + } else { + $array['nbaccidentinvestigations'] = 'N/A'; + } + return $array; + } - /** - * Get gravity rate (number workstop days by working hours) x 1 000. - * - * @return array - * @throws Exception - */ - public function getGravityRate() { - // (Number workstop days by working hours) x 1 000 - $arrayNbWorkstopDays = $this->getNbWorkstopDays(); - $total_workhours = getWorkedHours(); - if ($total_workhours > 0) { - $gravityrate = ($arrayNbWorkstopDays['nbworkstopdays']/$total_workhours) * 1000; - if ($gravityrate > 0) { - $array['gravityrate'] = price2Num($gravityrate, 5); - } else { - $array['gravityrate'] = 'N/A'; - } - } else { - $array['gravityrate'] = 'N/A'; - } - return $array; - } + /** + * Get frequency index (number accidents with DIAT by employees) x 1000 + * + * @param array $accidentsWithWorkStops Array of accidents with work stops + * @param array $employees Array of employees + * @return array + */ + public function getFrequencyIndex(array $accidentsWithWorkStops = [], array $employees = []): array + { + if ($employees['nbemployees'] > 0) { + $frequencyIndex = (count($accidentsWithWorkStops) / $employees['nbemployees']) * 1000; + if ($frequencyIndex > 0) { + $array['frequencyindex'] = price2Num($frequencyIndex, 2); + } else { + $array['frequencyindex'] = 'N/A'; + } + } else { + $array['frequencyindex'] = 'N/A'; + } + return $array; + } + + /** + * Get frequency rate (number accidents with DIAT by working hours) x 1 000 000 + * + * @param array $accidentsWithWorkStops Array of accidents with work stops + * @return array + */ + public function getFrequencyRate(array $accidentsWithWorkStops = []): array + { + $workHours = getWorkedHours(); + if ($workHours > 0) { + $frequencyRate = (count($accidentsWithWorkStops) / $workHours) * 1000000; + if ($frequencyRate > 0) { + $array['frequencyrate'] = price2Num($frequencyRate, 2); + } else { + $array['frequencyrate'] = 'N/A'; + } + } else { + $array['frequencyrate'] = 'N/A'; + } + return $array; + } + + /** + * Get gravity rate (number workstop days by working hours) x 1 000 + * + * @param array $accidentsWithWorkStops Array of accidents with work stops + * @return array + */ + public function getGravityRate(array $accidentsWithWorkStops = []): array + { + $arrayNbWorkstopDays = $this->getNbWorkstopDays($accidentsWithWorkStops); + $workHours = getWorkedHours(); + if ($workHours > 0) { + $gravityRate = ($arrayNbWorkstopDays['nbworkstopdays'] / $workHours) * 1000; + if ($gravityRate > 0) { + $array['gravityrate'] = price2Num($gravityRate, 5); + } else { + $array['gravityrate'] = 'N/A'; + } + } else { + $array['gravityrate'] = 'N/A'; + } + return $array; + } /** * Get user victim object. @@ -830,7 +823,7 @@ public function getTriggerDescription(SaturneObject $object): string } $ret = parent::getTriggerDescription($object); - $ret .= $langs->trans('UserVictim') . ' : ' . $userVictim->firstname . $userVictim->lastname . '
'; + $ret .= $userVictim->id > 0 ? $langs->trans('UserVictim') . ' : ' . $userVictim->firstname . $userVictim->lastname . '
' : ''; $ret .= $langs->trans('UserEmployer') . ' : ' . $userEmployer->firstname . $userEmployer->lastname . '
'; $ret .= $langs->trans('AccidentLocation') . ' : ' . $accidentLocation . '
'; $ret .= $langs->trans('AccidentType') . ' : ' . ($object->accident_type ? $langs->trans('CommutingAccident') : $langs->trans('WorkAccidentStatement')) . '
'; diff --git a/class/actions_digiriskdolibarr.class.php b/class/actions_digiriskdolibarr.class.php index 2861266b8..6d7c1a7e8 100644 --- a/class/actions_digiriskdolibarr.class.php +++ b/class/actions_digiriskdolibarr.class.php @@ -200,7 +200,7 @@ public function printCommonFooter($parameters) array_options['options_digiriskdolibarr_ticket_service']) && $object->array_options['options_digiriskdolibarr_ticket_service'] > 0) { require_once __DIR__ . '/digiriskelement.class.php'; @@ -208,12 +208,15 @@ public function printCommonFooter($parameters) $digiriskElement = new DigiriskElement($db); $digiriskElement->fetch($object->array_options['options_digiriskdolibarr_ticket_service']); - $selectDictionnary = $digiriskElement->getNomUrl(1, 'blank', 0, '', -1, 1); ?> + $selectDictionnary = $digiriskElement->getNomUrl(1, 'blank', 0, '', -1, 1); - - + + fetch(GETPOST('id')); - $task->fetch_optionals(); - - $risk_id = $task->array_options['options_fk_risk']; - $preventionplan_id = $task->array_options['options_fk_preventionplan']; - $firepermit_id = $task->array_options['options_fk_firepermit']; - $accident_id = $task->array_options['options_fk_accident']; - $accidentinvestigation_id = $task->array_options['options_fk_accidentinvestigation']; - - $risk->fetch($risk_id); - $preventionplan->fetch($preventionplan_id); - $firepermit->fetch($firepermit_id); - $accident->fetch($accident_id); - $accidentinvestigation->fetch($accidentinvestigation_id); - - $pictoDigirisk = img_picto('', 'digiriskdolibarr_color@digiriskdolibarr', 'class="pictofixedwidth"'); + $signatory = new SaturneSignature($db, 'digiriskdolibarr', $object->element); + $signatories = $signatory->fetchSignatory('Attendant', $object->id, $object->element); + if (is_array($signatories) && !empty($signatories)) { + $signatory = array_shift($signatories); + if (dol_strlen( $signatory->signature_url ) > 0) { + $picto = img_picto('', 'digiriskdolibarr_color@digiriskdolibarr', 'class="pictoModule"'); + $signatureUrl = dol_buildpath('custom/saturne/public/signature/add_signature.php?track_id=' . $signatory->signature_url . '&entity=' . $conf->entity . '&module_name=digiriskdolibarr&object_type=' . $object->element . '&document_type=TicketDocument', 3); + + $out = ''; + $out .= ''; + $out .= ''; ?> + 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - fetch_name_optionals_label($task->table_element); - $alltasks = $task->getTasksArray(null, null, 0, 0, 0, '', '-1', '', 0, 0, $extrafields); - - if (is_array($alltasks) && !empty($alltasks)) { - foreach ($alltasks as $tasksingle) { - $risk_id = $tasksingle->options_fk_risk; - $preventionplan_id = $tasksingle->options_fk_preventionplan; - $firepermit_id = $tasksingle->options_fk_firepermit; - $accident_id = $tasksingle->options_fk_accident; - $accidentinvestigation_id = $tasksingle->options_fk_accidentinvestigation; - - $risk->fetch($risk_id); - $preventionplan->fetch($preventionplan_id); - $firepermit->fetch($firepermit_id); - $accident->fetch($accident_id); - $accidentinvestigation->fetch($accidentinvestigation_id); - if (strpos($parameters['context'], 'projecttaskcard') !== false) { - if (!empty($risk_id) && $risk_id > 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - 0) { ?> - - fetch( GETPOST('projectid'), GETPOST('project_ref')); - $projectId = $project->id; - } else if (preg_match('/projectcard|projectcontactcard|projecttaskscard/', $parameters['context'])) { + if (preg_match('/projectcard|projectcontactcard|projecttaskscard/', $parameters['context'])) { $projectId = GETPOST('id'); + } else if (GETPOSTISSET('projectid') || GETPOSTISSET('ref')) { + $project->fetch( GETPOST('projectid'), GETPOST('ref')); + $projectId = $project->id; } else { $task->fetch(GETPOST('id')); $projectId = $task->fk_project; @@ -512,14 +395,7 @@ public function printCommonFooter($parameters) print ''; } - if (true) { - $this->results = array('myreturn' => 999); - $this->resprints = 'A text to show'; - return 0; // or return 1 to replace standard code - } else { - $this->errors[] = 'Error message'; - return -1; - } + return 0; // or return 1 to replace standard code } /** @@ -549,7 +425,7 @@ public function doActions($parameters, $object, $action) } } } else if (strpos($parameters['context'], 'ticketcard') !== false) { - if ($action == 'builddoc' && preg_match('/\bticketdocument_odt\b/', GETPOST('model'))) { + if ($action == 'builddoc' && preg_match('/\/(ticketdocument)\/|\/(digiriskdolibarr)\//', GETPOST('model'))) { require_once __DIR__ . '/digiriskdolibarrdocuments/ticketdocument.class.php'; $document = new TicketDocument($this->db); @@ -558,7 +434,7 @@ public function doActions($parameters, $object, $action) $permissiontoadd = $user->rights->ticket->write; } - if ($action == 'remove_file' && preg_match('/\bticketdocument\b/', GETPOST('file'))) { + if ($action == 'remove_file' && preg_match('/\/(ticketdocument)\/|\/(digiriskdolibarr)\//', GETPOST('file'))) { $upload_dir = $conf->digiriskdolibarr->multidir_output[$conf->entity ?? 1]; $permissiontodelete = $user->rights->ticket->delete; } @@ -693,6 +569,7 @@ public function printFieldListFrom($parameters, $object) { global $conf, $user, $langs; + $sql = ''; /* print_r($parameters); print_r($object); echo "action: " . $action; */ if (preg_match('/ticketlist|thirdpartyticket|projectticket/', $parameters['context'])) { // do something only for the context 'somecontext1' or 'somecontext2' $searchCategoryTicketList = GETPOST('search_category_ticket_list'); @@ -701,13 +578,8 @@ public function printFieldListFrom($parameters, $object) } } - if (true) { - $this->resprints = $sql; - return 0; // or return 1 to replace standard code - } else { - $this->errors[] = 'Error message'; - return -1; - } + $this->resprints = $sql; + return 0; // or return 1 to replace standard code } @@ -720,12 +592,10 @@ public function printFieldListFrom($parameters, $object) */ public function printFieldListWhere($parameters, $object) { - global $conf, $user, $langs; - - /* print_r($parameters); print_r($object); echo "action: " . $action; */ - if (preg_match('/ticketlist|thirdpartyticket|projectticket/', $parameters['context'])) { // do something only for the context 'somecontext1' or 'somecontext2' + if (preg_match('/ticketlist|thirdpartyticket|projectticket/', $parameters['context'])) { $searchCategoryTicketSqlList = array(); $searchCategoryTicketList = GETPOST('search_category_ticket_list'); + $sql = ''; if (is_array($searchCategoryTicketList) && !empty($searchCategoryTicketList)) { foreach ($searchCategoryTicketList as $searchCategoryTicket) { if (intval($searchCategoryTicket) == -2) { @@ -748,24 +618,11 @@ public function printFieldListWhere($parameters, $object) if (!empty($searchCategoryTicketList)) { $sql .= " GROUP BY t.rowid"; } - } - if (strpos($parameters['context'], 'userlist') !== false) { - $user->fetchAll('','','','',['login' => 'USERAPI']); - - if (is_array($user->users) && !empty($user->users)) { - $userIds = implode(',', array_keys($user->users)); - $sql .= ' AND u.rowid NOT IN (' . $userIds . ')'; - } + $this->resprints = $sql; } - if (true) { - $this->resprints = $sql; - return 0; // or return 1 to replace standard code - } else { - $this->errors[] = 'Error message'; - return -1; - } + return 0; // or return 1 to replace standard code } @@ -804,13 +661,8 @@ public function printFieldPreListTitle($parameters, $object) } } - if (true) { - $this->resprints = $moreforfilter; - return 0; // or return 1 to replace standard code - } else { - $this->errors[] = 'Error message'; - return -1; - } + $this->resprints = $moreforfilter ?? ''; + return 0; // or return 1 to replace standard code } /** @@ -824,6 +676,7 @@ public function printFieldListSearchParam($parameters, $object) { global $conf, $db, $user, $langs; + $param = ''; /* print_r($parameters); print_r($object); echo "action: " . $action; */ if (preg_match('/ticketlist|thirdpartyticket|projectticket/', $parameters['context'])) { // do something only for the context 'somecontext1' or 'somecontext2' $searchCategoryTicketList = GETPOST('search_category_ticket_list'); @@ -845,6 +698,60 @@ public function printFieldListSearchParam($parameters, $object) } } + /** + * Overloading the formObjectOptions function : replacing the parent's function with the one below + * + * @param array $parameters Hook metadata (context, etc...) + * @return int 0 < on error, 0 on success, 1 to replace standard code + * @throws Exception + */ + public function formObjectOptions(array $parameters, $object, $action): int + { + global $extrafields, $langs; + + if (strpos($parameters['context'], 'projecttaskcard') !== false) { + $picto = img_picto('', 'digiriskdolibarr_color@digiriskdolibarr', 'class="pictoModule"'); + $extraFieldsNames = ['fk_risk', 'fk_preventionplan', 'fk_firepermit', 'fk_accident', 'fk_accidentinvestigation']; + foreach ($extraFieldsNames as $extraFieldsName) { + $extrafields->attributes['projet_task']['label'][$extraFieldsName] = $picto . $langs->transnoentities($extrafields->attributes['projet_task']['label'][$extraFieldsName]); + } + } + + if (strpos($parameters['context'], 'ticketcard') !== false) { + $picto = img_picto('', 'digiriskdolibarr_color@digiriskdolibarr', 'class="pictoModule"'); + foreach ($extrafields->attributes['ticket']['label'] as $key => $value) { + if (strpos($key, 'digiriskdolibarr_ticket') === false) { + continue; // Goes to the next element if ‘digiriskdolibarr_ticket’ is not found + } + $extrafields->attributes['ticket']['label'][$key] = $picto . $langs->transnoentities($value); + } + } + + return 0; // or return 1 to replace standard code + } + + /** + * Overloading the printFieldListOption function : replacing the parent's function with the one below + * + * @param array $parameters Hook metadata (context, etc...) + * @param CommonObject $object Current object + * @return int 0 < on error, 0 on success, 1 to replace standard code + */ + public function printFieldListOption(array $parameters, $object): int + { + global $extrafields, $langs; + + if (preg_match('/tasklist|projecttaskscard/', $parameters['context'])) { + $picto = img_picto('', 'digiriskdolibarr_color@digiriskdolibarr', 'class="pictoModule"'); + $extraFieldsNames = ['fk_risk', 'fk_preventionplan', 'fk_firepermit', 'fk_accident', 'fk_accidentinvestigation']; + foreach ($extraFieldsNames as $extraFieldsName) { + $extrafields->attributes['projet_task']['label'][$extraFieldsName] = $picto . $langs->transnoentities($extrafields->attributes['projet_task']['label'][$extraFieldsName]); + } + } + + return 0; // or return 1 to replace standard code + } + /** * Overloading the saturneBannerTab function : replacing the parent's function with the one below * @@ -1072,7 +979,7 @@ public function saturneBannerTabCustomSubdir(array $parameters, object $object): if (preg_match('/digiriskelementview|digiriskstandardview|digiriskstandardagenda|digiriskelementagenda|digiriskelementdocument/', $parameters['context'])) { require_once __DIR__ . '/../lib/digiriskdolibarr_function.lib.php'; if ($object->element == 'digiriskelement') { - $this->results = ['subdir' => $object->element_type . '/'. $object->ref]; + $this->results = ['subdir' => $object->element_type . '/'. $object->ref, 'photoLimit' => 1]; } elseif ($object->element == 'digiriskstandard') { $this->results = ['modulepart' => 'mycompany', 'dir' => $conf->mycompany->dir_output, 'subdir' => 'logos', 'photoLimit' => 1]; } diff --git a/class/digiriskdocuments.class.php b/class/digiriskdocuments.class.php index 8189a397b..9a7be0334 100644 --- a/class/digiriskdocuments.class.php +++ b/class/digiriskdocuments.class.php @@ -210,21 +210,21 @@ public function fillRiskData(Odf $odfHandler, $object, Translate $outputLangs, $ array_pop($digiriskElementIds); foreach ($digiriskElementIds as $key => $digiriskElementId) { - $nomElement .= str_repeat(' - ', count($digiriskElementIds) + 1 - $key) . $activeDigiriskElements[$digiriskElementId]->ref . ' - ' . $activeDigiriskElements[$digiriskElementId]->label . chr(0x0A) . chr(0x0A); + $nomElement .= '
' . str_repeat(' - ', count($digiriskElementIds) + 1 - $key) . $activeDigiriskElements[$digiriskElementId]->ref . ' - ' . $activeDigiriskElements[$digiriskElementId]->label . chr(0x0A) . chr(0x0A); } } } if ($conf->global->DIGIRISKDOLIBARR_SHOW_RISK_ORIGIN) { - $nomElement .= (!empty($conf->global->DIGIRISKDOLIBARR_SHOW_SHARED_RISKS) ? 'S' . $element->entity : '') . ' - ' . $element->ref . ' - ' . $element->label; + $nomElement .= '
' . (!empty($conf->global->DIGIRISKDOLIBARR_SHOW_SHARED_RISKS) ? 'S' . $element->entity : '') . ' - ' . $element->ref . ' - ' . $element->label; if ($line->fk_element != $line->appliedOn) { - $nomElement .= ($dash > 0 ? ' - ' : '') . $langs->trans('AppliedOn') . ' ' . $linked_element->ref . ' - ' . $linked_element->label; + $nomElement .= '
' . $langs->trans('AppliedOn') . ' ' . $linked_element->ref . ' - ' . $linked_element->label; } } else { if ($linked_element->id > 0) { - $nomElement .= ($dash > 0 ? ' - ' : '') . $linked_element->ref . ' - ' . $linked_element->label; + $nomElement .= '
' . ($dash > 0 ? ' - ' : '') . $linked_element->ref . ' - ' . $linked_element->label; } else { - $nomElement .= ($dash > 0 ? ' - ' : '') . $element->ref . ' - ' . $element->label; + $nomElement .= '
' . ($dash > 0 ? ' - ' : '') . $element->ref . ' - ' . $element->label; } } @@ -290,6 +290,7 @@ public function fillRiskData(Odf $odfHandler, $object, Translate $outputLangs, $ if ($task_progress == 100) { if ($conf->global->DIGIRISKDOLIBARR_WORKUNITDOCUMENT_SHOW_TASK_DONE > 0) { + (($related_task->label) ? $tmparray['actionPreventionCompleted'] .= $langs->trans('Label') . ' : ' . $related_task->label . "\n" : ''); if (!getDolGlobalInt('DIGIRISKDOLIBARR_TASK_HIDE_REF_IN_DOCUMENT')) { (($related_task->ref) ? $tmparray['actionPreventionCompleted'] .= $langs->trans('Ref') . ' : ' . $related_task->ref . "\n" : ''); } @@ -313,13 +314,13 @@ public function fillRiskData(Odf $odfHandler, $object, Translate $outputLangs, $ $tmparray['actionPreventionCompleted'] .= $langs->trans('Budget') . ' : ' . price($related_task->budget_amount, 0, $langs, 1, 0, 0, $conf->currency) . "\n"; } (($AllInitiales) ? $tmparray['actionPreventionCompleted'] .= $langs->trans('ContactsAction') . ' : ' . $AllInitiales . "\n" : ''); - (($related_task->label) ? $tmparray['actionPreventionCompleted'] .= $langs->trans('Label') . ' : ' . $related_task->label . "\n" : ''); (($related_task->description) ? $tmparray['actionPreventionCompleted'] .= $langs->trans('Description') . ' : ' . $related_task->description . "\n" : ''); $tmparray['actionPreventionCompleted'] .= "\n"; } else { $tmparray['actionPreventionCompleted'] = $langs->transnoentities('ActionPreventionCompletedTaskDone'); } } else { + (($related_task->label) ? $tmparray['actionPreventionUncompleted'] .= $langs->trans('Label') . ' : ' . $related_task->label . "\n" : ''); if (!getDolGlobalInt('DIGIRISKDOLIBARR_TASK_HIDE_REF_IN_DOCUMENT')) { (($related_task->ref) ? $tmparray['actionPreventionUncompleted'] .= $langs->trans('Ref') . ' : ' . $related_task->ref . "\n" : ''); } @@ -345,7 +346,6 @@ public function fillRiskData(Odf $odfHandler, $object, Translate $outputLangs, $ } $tmparray['actionPreventionUncompleted'] .= $langs->trans('DigiriskProgress') . ' : ' . ($task_progress ?: 0) . ' %' . "\n"; (($AllInitiales) ? $tmparray['actionPreventionUncompleted'] .= $langs->trans('ContactsAction') . ' : ' . $AllInitiales . "\n" : ''); - (($related_task->label) ? $tmparray['actionPreventionUncompleted'] .= $langs->trans('Label') . ' : ' . $related_task->label . "\n" : ''); (($related_task->description) ? $tmparray['actionPreventionUncompleted'] .= $langs->trans('Description') . ' : ' . $related_task->description . "\n" : ''); $tmparray['actionPreventionUncompleted'] .= "\n"; } diff --git a/class/digiriskdolibarrdashboard.class.php b/class/digiriskdolibarrdashboard.class.php index f399880b9..69002b83c 100644 --- a/class/digiriskdolibarrdashboard.class.php +++ b/class/digiriskdolibarrdashboard.class.php @@ -52,25 +52,26 @@ public function load_dashboard(array $moreParams = []): array { $dashboardDatas = [ ['type' => 'RiskAssessmentDocument', 'classPath' => '/digiriskdolibarrdocuments/riskassessmentdocument.class.php'], + ['type' => 'Risk', 'classPath' => '/riskanalysis/risk.class.php'], ['type' => 'Accident', 'classPath' => '/accident.class.php'], ['type' => 'Evaluator', 'classPath' => '/evaluator.class.php'], ['type' => 'DigiriskResources', 'classPath' => '/digiriskresources.class.php'], ['type' => 'DigiriskElement', 'classPath' => '/digiriskelement.class.php'], ['type' => 'SaturneTask', 'classPath' => '/../../saturne/class/task/saturnetask.class.php'], - ['type' => 'Risk', 'classPath' => '/riskanalysis/risk.class.php'], - ['type' => 'TicketDashboard', 'classPath' => '/ticketdashboard.class.php'] + ['type' => 'TicketDashboard', 'classPath' => '/ticketdashboard.class.php'], + ['type' => 'TicketStatsDashboard', 'classPath' => '/ticketstatsdashboard.class.php'] ]; foreach ($dashboardDatas as $dashboardData) { require_once __DIR__ . $dashboardData['classPath']; if ($dashboardData['type'] != 'TicketDashboard') { $className = new $dashboardData['type']($this->db); } else { - $className = new TicketDashboard($this->db, $moreParams['join'], $moreParams['where']); + $className = new TicketDashboard($this->db, $moreParams['join'] ?? '', $moreParams['where'] ?? ''); } if ($dashboardData['type'] != 'SaturneTask') { - $array[$dashboardData['type']] = array_key_exists('Load' . $dashboardData['type'], $moreParams) ? $className->load_dashboard() : []; + $array[$dashboardData['type']] = array_key_exists('Load' . $dashboardData['type'], $moreParams) && $moreParams['Load' . $dashboardData['type']] ? $className->load_dashboard() : []; } else { - $array[$dashboardData['type']] = array_key_exists('Load' . $dashboardData['type'], $moreParams) ? $className->load_dashboard(getDolGlobalInt('DIGIRISKDOLIBARR_DU_PROJECT')) : []; + $array[$dashboardData['type']] = array_key_exists('Load' . $dashboardData['type'], $moreParams) && $moreParams['Load' . $dashboardData['type']] ? $className->load_dashboard(getDolGlobalInt('DIGIRISKDOLIBARR_DU_PROJECT')) : []; } } @@ -137,7 +138,7 @@ protected function _getAllByYear(string $sql): array $result[$i]['year'] = $row->year; $result[$i]['nb'] = $row->nb; if ($i > 0 && $row->nb > 0) { - $result[$i - 1]['avg'] = ($result[$i - 1]['nb']) / $row->nb * 100; + $result[$i - 1]['avg'] = -($row->nb - ($result[$i - 1]['nb'])) / $row->nb * 100; } $i++; } diff --git a/class/digiriskdolibarrdocuments/informationssharing.class.php b/class/digiriskdolibarrdocuments/informationssharing.class.php index bfcdb6574..94a122e02 100644 --- a/class/digiriskdolibarrdocuments/informationssharing.class.php +++ b/class/digiriskdolibarrdocuments/informationssharing.class.php @@ -57,7 +57,7 @@ public function __construct(DoliDB $db) */ public function InformationsSharingFillJSON() { - global $conf; + global $conf, $langs; $resources = new DigiriskResources($this->db); $digirisk_resources = $resources->fetchDigiriskResources(); @@ -87,6 +87,7 @@ public function InformationsSharingFillJSON() if ($result > 0) { $json['InformationsSharing']['harassment_officer']['id'] = $harassment_officer->id; + $json['InformationsSharing']['harassment_officer']['name'] = $harassment_officer->getFullName($langs); $json['InformationsSharing']['harassment_officer']['phone'] = $harassment_officer->office_phone; } @@ -102,6 +103,7 @@ public function InformationsSharingFillJSON() $json['InformationsSharing']['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['InformationsSharing']['delegues_du_personnels_titulaires'] = ''; + $json['InformationsSharing']['delegues_du_personnels_titulairesFullName'] = ''; if (!empty ($digirisk_resources['TitularsDP']->id )) { foreach ($digirisk_resources['TitularsDP']->id as $dp_titular) { @@ -115,6 +117,7 @@ public function InformationsSharingFillJSON() } $json['InformationsSharing']['delegues_du_personnels_suppleants'] = ''; + $json['InformationsSharing']['delegues_du_personnels_suppleantsFullName'] = ''; if (!empty ($digirisk_resources['AlternatesDP']->id )) { foreach ($digirisk_resources['AlternatesDP']->id as $dp_alternate) { @@ -130,6 +133,7 @@ public function InformationsSharingFillJSON() // CSE $json['InformationsSharing']['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['InformationsSharing']['membres_du_comite_entreprise_titulaires'] = ''; + $json['InformationsSharing']['membres_du_comite_entreprise_titulairesFullName'] = ''; if (!empty ($digirisk_resources['TitularsCSE']->id )) { foreach ($digirisk_resources['TitularsCSE']->id as $cse_titular) { $cse_titulars = new User($this->db); @@ -142,6 +146,7 @@ public function InformationsSharingFillJSON() } $json['InformationsSharing']['membres_du_comite_entreprise_suppleants'] = ''; + $json['InformationsSharing']['membres_du_comite_entreprise_suppleantsFullName'] = ''; if (!empty ($digirisk_resources['AlternatesCSE']->id )) { foreach ($digirisk_resources['AlternatesCSE']->id as $cse_alternate) { $cse_alternates = new User($this->db); diff --git a/class/digiriskdolibarrdocuments/legaldisplay.class.php b/class/digiriskdolibarrdocuments/legaldisplay.class.php index cc7e56aab..663404e69 100644 --- a/class/digiriskdolibarrdocuments/legaldisplay.class.php +++ b/class/digiriskdolibarrdocuments/legaldisplay.class.php @@ -236,7 +236,10 @@ public function LegalDisplayFillJSON() { $json['LegalDisplay']['derogation_schedule']['permanent'] = $conf->global->DIGIRISKDOLIBARR_DEROGATION_SCHEDULE_PERMANENT; $json['LegalDisplay']['derogation_schedule']['occasional'] = $conf->global->DIGIRISKDOLIBARR_DEROGATION_SCHEDULE_OCCASIONAL; $json['LegalDisplay']['collective_agreement']['title_of_the_applicable_collective_agreement'] = $conf->global->DIGIRISKDOLIBARR_COLLECTIVE_AGREEMENT_TITLE; - $json['LegalDisplay']['collective_agreement']['title_of_the_applicable_collective_agreement'] = $conf->global->DIGIRISKDOLIBARR_COLLECTIVE_AGREEMENT_TITLE . ' - ' . $this->getIDCCByCode($conf->global->DIGIRISKDOLIBARR_COLLECTIVE_AGREEMENT_TITLE)->libelle; + $idcc = $this->getIDCCByCode($conf->global->DIGIRISKDOLIBARR_COLLECTIVE_AGREEMENT_TITLE); + if (!empty($idcc)) { + $json['LegalDisplay']['collective_agreement']['title_of_the_applicable_collective_agreement'] .= ' - ' . $idcc->libelle; + } $json['LegalDisplay']['collective_agreement']['location_and_access_terms_of_the_agreement'] = $conf->global->DIGIRISKDOLIBARR_COLLECTIVE_AGREEMENT_LOCATION; $json['LegalDisplay']['DUER']['how_access_to_duer'] = $conf->global->DIGIRISKDOLIBARR_DUER_LOCATION; $json['LegalDisplay']['rules']['location'] = $conf->global->DIGIRISKDOLIBARR_RULES_LOCATION; diff --git a/class/digiriskdolibarrdocuments/riskassessmentdocument.class.php b/class/digiriskdolibarrdocuments/riskassessmentdocument.class.php index c1215b33e..830706ee0 100644 --- a/class/digiriskdolibarrdocuments/riskassessmentdocument.class.php +++ b/class/digiriskdolibarrdocuments/riskassessmentdocument.class.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2021-2024 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 @@ -31,12 +31,12 @@ class RiskAssessmentDocument extends DigiriskDocuments { /** - * @var string Module name. + * @var string Module name */ public $module = 'digiriskdolibarr'; /** - * @var string Element type of object. + * @var string Element type of object */ public $element = 'riskassessmentdocument'; @@ -46,9 +46,9 @@ class RiskAssessmentDocument extends DigiriskDocuments public string $picto = 'fontawesome_fa-file-alt_fas_#d35968'; /** - * Constructor. + * Constructor * - * @param DoliDb $db Database handler. + * @param DoliDb $db Database handler */ public function __construct(DoliDB $db) { @@ -115,102 +115,59 @@ public function load_dashboard(): array { global $langs; - $arrayLastGenerateDate = $this->getLastGenerateDate(); - $arrayNextGenerateDate = $this->getNextGenerateDate(); - $arrayNbDaysBeforeNextGenerateDate = $this->getNbDaysBeforeNextGenerateDate(); - - if (empty($arrayNbDaysBeforeNextGenerateDate['nbdaysbeforenextgeneratedate'])) { - $arrayNbDaysAfterNextGenerateDate = $this->getNbDaysAfterNextGenerateDate(); - $arrayNbDaysBeforeNextGenerateDate = ['nbdaysbeforenextgeneratedate' => 'N/A']; - } else { - $arrayNbDaysAfterNextGenerateDate = ['nbdaysafternextgeneratedate' => 'N/A']; - } + $arrayGetGenerationDateInfos = $this->getGenerationDateInfos(); $array['widgets'] = [ 'riskassessmentdocument' => [ - 'label' => [$langs->transnoentities('LastGenerateDate') ?? '', $langs->transnoentities('NextGenerateDate') ?? '', $langs->transnoentities('NbDaysBeforeNextGenerateDate') ?? '', $langs->transnoentities('NbDaysAfterNextGenerateDate') ?? ''], - 'content' => [$arrayLastGenerateDate['lastgeneratedate'] ?? 0, $arrayNextGenerateDate['nextgeneratedate'] ?? 0, $arrayNbDaysBeforeNextGenerateDate['nbdaysbeforenextgeneratedate'] ?? 0, $arrayNbDaysAfterNextGenerateDate['nbdaysafternextgeneratedate'] ?? 0], - 'picto' => 'fas fa-info-circle', - 'widgetName' => $langs->transnoentities('RiskAssessmentDocument') + 'title' => $langs->transnoentities('RiskAssessmentDocument'), + 'picto' => 'fas fa-book', + 'pictoColor' => '#0D8AFF', + 'label' => [$langs->transnoentities('NextGenerateDate') ?? '', $langs->transnoentities('LastGenerateDate') ?? '', $langs->transnoentities('DelayGenerateDate') ?? ''], + 'content' => [$arrayGetGenerationDateInfos['nextgeneratedate'], $arrayGetGenerationDateInfos['lastgeneratedate'], $arrayGetGenerationDateInfos['delaygeneratedate']], + 'picto' => 'fas fa-info-circle', + 'moreContent' => ['', $arrayGetGenerationDateInfos['moreContent'] ?? ''], + 'widgetName' => $langs->transnoentities('RiskAssessmentDocument') ] ]; return $array; } - /** - * Get last riskassessmentdocument generate date. - * - * @return array - * @throws Exception - */ - public function getLastGenerateDate() - { - // Last riskassessmentdocument generate date - $filter = array('customsql' => "t.type='riskassessmentdocument'"); - $riskassessmentdocumentarray = $this->fetchAll('desc', 't.rowid', 1, 0, $filter, 'AND'); - if ( ! empty($riskassessmentdocumentarray) && $riskassessmentdocumentarray > 0 && is_array($riskassessmentdocumentarray)) { - $riskassessmentdocument = array_shift($riskassessmentdocumentarray); - $array['lastgeneratedate'] = dol_print_date($riskassessmentdocument->date_creation, 'day'); - } else { - $array['lastgeneratedate'] = 'N/A'; - } - return $array; - } - - /** - * Get next riskassessmentdocument generate date. - * - * @return array - * @throws Exception - */ - public function getNextGenerateDate() - { - // Next riskassessmentdocument generate date - $filter = array('customsql' => "t.type='riskassessmentdocument'"); - $riskassessmentdocumentarray = $this->fetchAll('desc', 't.rowid', 1, 0, $filter, 'AND'); - if ( ! empty($riskassessmentdocumentarray) && $riskassessmentdocumentarray > 0 && is_array($riskassessmentdocumentarray)) { - $riskassessmentdocument = array_shift($riskassessmentdocumentarray); - $array['nextgeneratedate'] = dol_print_date(dol_time_plus_duree($riskassessmentdocument->date_creation, '1', 'y'), 'day'); - } else { - $array['nextgeneratedate'] = 'N/A'; - } - return $array; - } + /** + * Get generation date infos + * + * @param array $moreParam More param (Object/user/etc) + * + * @return array + * @throws Exception + */ + public function getGenerationDateInfos(array $moreParam = []): array + { + global $langs; - /** - * Get number days before next riskassessmentdocument generate date. - * - * @return array - * @throws Exception - */ - public function getNbDaysBeforeNextGenerateDate() - { - // Number days before next riskassessmentdocument generate date - $arrayNextGenerateDate = $this->getNextGenerateDate(); - if ($arrayNextGenerateDate['nextgeneratedate'] > 0) { - $array['nbdaysbeforenextgeneratedate'] = num_between_day(dol_now(), dol_stringtotime($arrayNextGenerateDate['nextgeneratedate']), 1); - } else { - $array['nbdaysbeforenextgeneratedate'] = 'N/A'; - } - return $array; - } + $filter = ['customsql' => 't.type = "' . $this->element . '"' . ($moreParam['filter'] ?? '')]; + $riskAssessmentDocuments = $this->fetchAll('desc', 't.rowid', 1, 0, $filter); + if (!empty($riskAssessmentDocuments) && is_array($riskAssessmentDocuments)) { + $riskAssessmentDocument = array_shift($riskAssessmentDocuments); + $now = dol_now(); + $nextGenerateTimeStamp = dol_time_plus_duree($riskAssessmentDocument->date_creation, '1', 'y'); + $nextGenerateDate = dol_print_date($nextGenerateTimeStamp, 'day'); + $lastGenerateDate = dol_print_date($riskAssessmentDocument->date_creation, 'day'); + $nbDaysAfterNextGenerateDate = num_between_day($now, $nextGenerateTimeStamp, 1); + $nbDaysBeforeNextGenerateDate = num_between_day($nextGenerateTimeStamp, $now, 1); + + $array['nextgeneratedate'] = img_picto('', 'fontawesome_fa-calendar_far_#263C5C80', 'class="pictofixedwidth"') . $nextGenerateDate; + $array['nextgeneratedate'] .= ' ' . (!empty($nbDaysAfterNextGenerateDate) ? $nbDaysAfterNextGenerateDate . ' ' . $langs->transnoentities('Days') : ''); + $array['lastgeneratedate'] = img_picto('', 'fontawesome_fa-calendar_far_#263C5C80', 'class="pictofixedwidth"') . $lastGenerateDate; + $array['delaygeneratedate'] = !empty($nbDaysBeforeNextGenerateDate) ? $nbDaysBeforeNextGenerateDate . ' ' . $langs->transnoentities('Days') : $langs->transnoentities('NoDelay'); + } else { + $array['nextgeneratedate'] = 'N/A'; + $array['lastgeneratedate'] = 'N/A'; + $array['delaygeneratedate'] = 'N/A'; + } - /** - * Get number days after next riskassessmentdocument generate date. - * - * @return array - * @throws Exception - */ - public function getNbDaysAfterNextGenerateDate() - { - // Number days after next riskassessmentdocument generate date - $arrayNextGenerateDate = $this->getNextGenerateDate(); - if ($arrayNextGenerateDate['nextgeneratedate'] > 0) { - $array['nbdaysafternextgeneratedate'] = num_between_day(dol_stringtotime($arrayNextGenerateDate['nextgeneratedate']), dol_now(), 1); - } else { - $array['nbdaysafternextgeneratedate'] = 'N/A'; - } - return $array; - } + $array['moreContent'] = $this->showUrlOfLastGeneratedDocument($this->module, $this->element, 'odt', 'fontawesome_fa-file-word_far_#0D8AFF', $moreParam['entity'] ?? 1); + $array['moreContent'] .= $this->showUrlOfLastGeneratedDocument($this->module, $this->element, 'pdf', 'fontawesome_fa-file-pdf_far_#FB4B54', $moreParam['entity'] ?? 1); + return $array; + } } diff --git a/class/digiriskelement.class.php b/class/digiriskelement.class.php index b1bfa04bd..633a0503a 100644 --- a/class/digiriskelement.class.php +++ b/class/digiriskelement.class.php @@ -136,7 +136,7 @@ public function create(User $user, bool $notrigger = false): int { global $conf; if (empty($this->ref)) { - $type = 'DIGIRISKDOLIBARR_' . strtoupper($this->element_type) . '_ADDON'; + $type = 'DIGIRISKDOLIBARR_' . dol_strtoupper($this->element_type) . '_ADDON'; $objectMod = $conf->global->$type; $numberingModules = [ 'digiriskelement/' . $this->element_type => $objectMod @@ -367,6 +367,30 @@ public function getMultiEntityTrashList() } } + /** + * Return SQL filter for trash exclusion + * + * @return string + * @throws Exception + */ + public function getTrashExclusionSqlFilter(): string + { + $filter = ''; + $digiriskElementTrashs = $this->getMultiEntityTrashList(); + if (!empty($digiriskElementTrashs) && is_array($digiriskElementTrashs)) { + $filter = '('; + foreach (array_keys($digiriskElementTrashs) as $digiriskElementTrash) { + $filter .= $digiriskElementTrash . ', '; + } + if (preg_match('/, /', $filter)) { + $filter = rtrim($filter, ', '); + } + $filter .= ')'; + } + + return $filter; + } + /** * Return list of parent ids for an element * @@ -400,7 +424,7 @@ public function getActiveDigiriskElements(int $multiEntityManagement = 0, array $this->ismultientitymanaged = 0; } - $digiriskElements = $this->fetchAll('', '', 0, 0, ['customsql' => 'status = ' . self::STATUS_VALIDATED . $moreParams['filter']]); + $digiriskElements = $this->fetchAll('', '', 0, 0, ['customsql' => 'status = ' . self::STATUS_VALIDATED . ($moreParams['filter'] ?? '')]); $trashList = $this->getMultiEntityTrashList(); if (is_array($trashList) && !empty($trashList)) { foreach($trashList as $trashElementID) { @@ -539,10 +563,22 @@ public function getTriggerDescription(SaturneObject $object): string */ public function load_dashboard(): array { - $getDigiriskElementListsByDepth = $this->getDigiriskElementListsByDepth(); - $getRisksByDigiriskElement = $this->getRisksByDigiriskElement(); + global $langs; + + $confName = strtoupper($this->module) . '_DASHBOARD_CONFIG'; + $dashboardConfig = json_decode(getDolUserString($confName)); + $array = ['graphs' => [], 'disabledGraphs' => []]; - $array['graphs'] = [$getDigiriskElementListsByDepth, $getRisksByDigiriskElement]; + if (empty($dashboardConfig->graphs->DigiriskElementsRepartitionByDepth->hide)) { + $array['graphs'][] = $this->getDigiriskElementListsByDepth(); + } else { + $array['disabledGraphs']['DigiriskElementsRepartitionByDepth'] = $langs->transnoentities('DigiriskElementsRepartitionByDepth'); + } + if (empty($dashboardConfig->graphs->RisksRepartitionByDigiriskElement->hide)) { + $array['graphs'][] = $this->getRisksByDigiriskElement(); + } else { + $array['disabledGraphs']['RisksRepartitionByDigiriskElement'] = $langs->transnoentities('RisksRepartitionByDigiriskElement'); + } return $array; } @@ -561,6 +597,7 @@ public function getRisksByDigiriskElement(string $riskType = 'risk'): array // Graph Title parameters $array['title'] = $langs->transnoentities('RisksRepartitionByDigiriskElement'); + $array['name'] = 'RisksRepartitionByDigiriskElement'; $array['picto'] = $this->picto; // Graph parameters @@ -613,6 +650,7 @@ public function getDigiriskElementListsByDepth(): array // Graph Title parameters $array['title'] = $langs->transnoentities('DigiriskElementsRepartitionByDepth', getDolGlobalInt('DIGIRISKDOLIBARR_DIGIRISKELEMENT_DEPTH_GRAPH')); + $array['name'] = 'DigiriskElementsRepartitionByDepth'; $array['picto'] = $this->picto; // Graph parameters diff --git a/class/digiriskresources.class.php b/class/digiriskresources.class.php index e71f9c868..8cc3ea958 100644 --- a/class/digiriskresources.class.php +++ b/class/digiriskresources.class.php @@ -301,7 +301,7 @@ public function fetchDigiriskResources() $allLinks = array(); if (!empty ($links) && $links > 0) { foreach ($links as $link) { - if ($allLinks[$link->ref]->ref == $link->ref) { + if (isset($allLinks[$link->ref]) && $allLinks[$link->ref]->ref == $link->ref) { array_push($allLinks[$link->ref]->id, $link->element_id); } else { $allLinks[$link->ref] = new stdClass(); @@ -329,9 +329,11 @@ public function load_dashboard(): array $array['widgets'] = [ 'society' => [ + 'title' => $langs->transnoentities('Society'), + 'picto' => 'fas fa-building', + 'pictoColor' => '#FB4B54', 'label' => [$langs->transnoentities('SiretNumber') ?? ''], 'content' => [$arraySiretNumber['siretnumber'] ?? 0], - 'picto' => 'fas fa-building', 'widgetName' => $langs->transnoentities('Society') ] ]; diff --git a/class/evaluator.class.php b/class/evaluator.class.php index 1ce18b023..2bb75a0a5 100644 --- a/class/evaluator.class.php +++ b/class/evaluator.class.php @@ -142,10 +142,12 @@ public function load_dashboard(): array $array['widgets'] = [ 'evaluator' => [ + 'title' => $langs->transnoentities('Employees'), + 'picto' => 'fas fa-user', + 'pictoColor' => '#32E592', 'label' => [$langs->transnoentities('NbEmployeesInvolved') ?? '', $langs->transnoentities('NbEmployees') ?? ''], 'content' => [$arrayNbEmployeesInvolved['nbemployeesinvolved'] ?? 0, $arrayNbEmployees['nbemployees'] ?? 0], 'tooltip' => [$langs->transnoentities('NbEmployeesInvolvedTooltip'), (($conf->global->DIGIRISKDOLIBARR_NB_EMPLOYEES > 0 && $conf->global->DIGIRISKDOLIBARR_MANUAL_INPUT_NB_EMPLOYEES) ? $langs->transnoentities('NbEmployeesConfTooltip') : $langs->transnoentities('NbEmployeesTooltip'))], - 'picto' => 'fas fa-user-check', 'widgetName' => $langs->transnoentities('Evaluator') ] ]; @@ -156,12 +158,13 @@ public function load_dashboard(): array /** * Get number employees involved. * - * @return array + * @param array $moreParam More param (Object/user/etc) + * @return array * @throws Exception */ - public function getNbEmployeesInvolved() { + public function getNbEmployeesInvolved(array $moreParam = []) { // Number employees involved - $allevaluators = $this->fetchAll('','', 0, 0, array(), 'AND', 'fk_user'); + $allevaluators = $this->fetchAll('','', 0, 0, ['customsql' => ($moreParam['filter'] ?? '')], 'AND', 'fk_user'); if (is_array($allevaluators) && !empty($allevaluators)) { $array['nbemployeesinvolved'] = count($allevaluators); } else { @@ -170,29 +173,29 @@ public function getNbEmployeesInvolved() { return $array; } - /** - * Get number employees. - * - * @return array - * @throws Exception - */ - public function getNbEmployees() { - global $conf; - - // Number employees - if ($conf->global->DIGIRISKDOLIBARR_NB_EMPLOYEES > 0 && $conf->global->DIGIRISKDOLIBARR_MANUAL_INPUT_NB_EMPLOYEES) { - $array['nbemployees'] = $conf->global->DIGIRISKDOLIBARR_NB_EMPLOYEES; - } else { - $user = new User($this->db); - $allusers = $user->get_full_tree(0, 'u.employee = 1'); - if (!empty($allusers) && is_array($allusers)) { - $array['nbemployees'] = count($allusers); - } else { - $array['nbemployees'] = 'N/A'; - } - } - return $array; - } + /** + * Get number employees + * + * @param array $moreParam More param (Object/user/etc) + * @return array + * @throws Exception + */ + public function getNbEmployees(array $moreParam = []): array + { + global $user; + + if (getDolGlobalInt('DIGIRISKDOLIBARR_NB_EMPLOYEES') > 0 && getDolGlobalInt('DIGIRISKDOLIBARR_MANUAL_INPUT_NB_EMPLOYEES')) { + $array['nbemployees'] = getDolGlobalInt('DIGIRISKDOLIBARR_NB_EMPLOYEES'); + } else { + $users = $user->get_full_tree(0, 'u.employee = 1' . ($moreParam['filter'] ?? '')); + if (!empty($users) && is_array($users)) { + $array['nbemployees'] = count($users); + } else { + $array['nbemployees'] = 0; + } + } + return $array; + } /** * Write information of trigger description diff --git a/class/firepermit.class.php b/class/firepermit.class.php index da31e6473..ed78e83e5 100644 --- a/class/firepermit.class.php +++ b/class/firepermit.class.php @@ -306,6 +306,12 @@ public function LibStatut($status, $mode = 0): string $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('ValidatePendingSignature'); $this->labelStatus[self::STATUS_LOCKED] = $langs->trans('Locked'); $this->labelStatus[self::STATUS_ARCHIVED] = $langs->trans('Archived'); + + $this->labelStatusShort[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('InProgress'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ValidatePendingSignature'); + $this->labelStatusShort[self::STATUS_LOCKED] = $langs->transnoentitiesnoconv('Locked'); + $this->labelStatusShort[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived'); } $statusType = 'status' . $status; diff --git a/class/preventionplan.class.php b/class/preventionplan.class.php index e300c48cf..f0c6d9d5d 100644 --- a/class/preventionplan.class.php +++ b/class/preventionplan.class.php @@ -307,6 +307,12 @@ public function LibStatut($status, $mode = 0): string $this->labelStatus[self::STATUS_VALIDATED] = $langs->trans('ValidatePendingSignature'); $this->labelStatus[self::STATUS_LOCKED] = $langs->trans('Locked'); $this->labelStatus[self::STATUS_ARCHIVED] = $langs->trans('Archived'); + + $this->labelStatusShort[self::STATUS_DELETED] = $langs->transnoentitiesnoconv('Deleted'); + $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); + $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled'); + $this->labelStatusShort[self::STATUS_LOCKED] = $langs->transnoentitiesnoconv('Locked'); + $this->labelStatusShort[self::STATUS_ARCHIVED] = $langs->transnoentitiesnoconv('Archived'); } $statusType = 'status' . $status; diff --git a/class/riskanalysis/risk.class.php b/class/riskanalysis/risk.class.php index 33b8d4b17..f054e7812 100644 --- a/class/riskanalysis/risk.class.php +++ b/class/riskanalysis/risk.class.php @@ -87,7 +87,7 @@ class Risk extends SaturneObject 'import_key' => ['type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => '1', 'position' => 70, 'notnull' => -1, 'visible' => 0], 'status' => ['type' => 'smallint', 'label' => 'Status', 'enabled' => '1', 'position' => 80, 'notnull' => 0, 'visible' => 0], 'category' => ['type' => 'varchar(255)', 'label' => 'RiskCategory', 'enabled' => '1', 'position' => 21, 'notnull' => 0, 'visible' => 1], - 'description' => ['type' => 'text', 'label' => 'Description', 'enabled' => '1', 'position' => 23, 'notnull' => 0, 'visible' => -1], + 'description' => ['type' => 'text', 'label' => 'Description', 'enabled' => '$conf->global->DIGIRISKDOLIBARR_RISK_DESCRIPTION', 'position' => 23, 'notnull' => 0, 'visible' => -1], 'type' => ['type' => 'varchar(255)', 'label' => 'Type', 'enabled' => '1', 'position' => 24, 'notnull' => 1, 'visible' => 0, 'default' => '(PROV)'], 'fk_user_creat' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => '1', 'position' => 110, 'notnull' => 1, 'visible' => 0, 'foreignkey' => 'user.rowid'], 'fk_user_modif' => ['type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => '1', 'position' => 120, 'notnull' => -1, 'visible' => 0], @@ -140,12 +140,12 @@ public function __construct(DoliDB $db) 'label' => $langs->transnoentities('RedRisk'), 'color' => '#e05353', 'start' => 51, - 'end' => 80 + 'end' => 79 ], 4 => [ 'label' => $langs->transnoentities('BlackRisk'), 'color' => '#2b2b2b', - 'start' => 81, + 'start' => 80, 'end' => 100 ] ]; @@ -192,7 +192,8 @@ public function fetchRisksOrderedByCotation($parent_id, $get_children_data = fal $objects = $object->getActiveDigiriskElements(); if ($get_shared_data) { - $risk->ismultientitymanaged = 0; + $activeDigiriskElements = $object->getActiveDigiriskElements($get_shared_data); + $risk->ismultientitymanaged = 0; $riskAssessment->ismultientitymanaged = 0; } $riskList = $risk->fetchAll('', '', 0, 0, ['customsql' => 'status = ' . self::STATUS_VALIDATED . $moreParams['filterRisk']]); @@ -305,11 +306,13 @@ public function fetchRisksOrderedByCotation($parent_id, $get_children_data = fal $digiriskElementOfEntity->fetchObjectLinked(null, '', $digiriskElementOfEntity->id, 'digiriskdolibarr_digiriskelement', 'AND', 1, 'sourcetype', 0); if (!empty($digiriskElementOfEntity->linkedObjectsIds['digiriskdolibarr_risk'])) { foreach ($digiriskElementOfEntity->linkedObjectsIds['digiriskdolibarr_risk'] as $sharedRiskId) { - $sharedRisk = $riskList[$sharedRiskId]; - if (is_object($sharedRisk)) { - $sharedRisk->appliedOn = $digiriskElementOfEntity->id; - $risks[] = $sharedRisk; - } + $sharedRisk = $riskList[$sharedRiskId]; + $sharedParentActive = array_search($sharedRisk->fk_element, array_column($activeDigiriskElements, 'id')); + if (is_object($sharedRisk) && $sharedParentActive > 0) { + $clonedRisk = clone $sharedRisk; + $clonedRisk->appliedOn = $digiriskElementOfEntity->id; + $risks[] = $clonedRisk; + } } } } @@ -320,10 +323,12 @@ public function fetchRisksOrderedByCotation($parent_id, $get_children_data = fal $parentElement->fetchObjectLinked(null, '', $parent_id, 'digiriskdolibarr_digiriskelement', 'AND', 1, 'sourcetype', 0); if (!empty($parentElement->linkedObjectsIds['digiriskdolibarr_risk'])) { foreach ($parentElement->linkedObjectsIds['digiriskdolibarr_risk'] as $sharedRiskId) { - $sharedRisk = $riskList[$sharedRiskId]; - if (is_object($sharedRisk)) { - $sharedRisk->appliedOn = $parent_id; - $risks[] = $sharedRisk; + $sharedRisk = $riskList[$sharedRiskId]; + $sharedParentActive = array_search($sharedRisk->fk_element, array_column($activeDigiriskElements, 'id')); + if (is_object($sharedRisk) && $sharedParentActive > 0) { + $clonedRisk = clone $sharedRisk; + $clonedRisk->appliedOn = $parent_id; + $risks[] = $clonedRisk; } } } @@ -490,6 +495,100 @@ public function getFirePermitDangerCategoryName($object) return -1; } + /** + * check if risk not exists for a digirisk element + * + * @param int $limit Limit + * @return array|int Int <0 if KO, array of pages if OK + * @throws Exception + */ + public function checkNotExistsDigiriskElementForRisk(int $limit = 0) + { + dol_syslog(__METHOD__, LOG_DEBUG); + + $digiriskElement = new DigiriskElement($this->db); + + $sql = 'SELECT '; + $sql .= $this->getFieldList('t'); + $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' WHERE !EXISTS'; + $sql .= ' ( SELECT '; + $sql .= $digiriskElement->getFieldList('d'); + $sql .= ' FROM ' . MAIN_DB_PREFIX . $digiriskElement->table_element . ' as d'; + $sql .= ' WHERE d.rowid = t.fk_element )'; + + $records = []; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new $this($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error ' . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + return -1; + } + } + + /** + * check if risk assessment not exists for a risk + * + * @param int $limit Limit + * @return array|int Int <0 if KO, array of pages if OK + * @throws Exception + */ + public function checkNotExistsRiskAssessmentForRisk(int $limit = 0) + { + dol_syslog(__METHOD__, LOG_DEBUG); + + $riskAssessment = new RiskAssessment($this->db); + + $sql = 'SELECT '; + $sql .= $this->getFieldList('t'); + $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' WHERE !EXISTS'; + $sql .= ' (SELECT '; + $sql .= $riskAssessment->getFieldList('ra'); + $sql .= ' FROM ' . MAIN_DB_PREFIX . $riskAssessment->table_element . ' as ra'; + $sql .= ' WHERE ra.fk_risk = t.rowid)'; + + $records = []; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new $this($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error ' . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + return -1; + } + } + /** * Get children tasks * @@ -534,7 +633,7 @@ public function getRelatedTasks($risk) */ public function getTasksWithFkRisk() { - $sql = "SELECT * FROM " . MAIN_DB_PREFIX . 'projet_task_extrafields' . ' WHERE fk_risk > 0'; + $sql = "SELECT * FROM " . MAIN_DB_PREFIX . 'projet_task_extrafields' . ' WHERE fk_risk > 0 ORDER BY fk_object ASC'; $tasksList = saturne_fetch_all_object_type('SaturneTask', '', '', 0, 0, [], 'AND', false, false); $resql = $this->db->query($sql); @@ -545,7 +644,7 @@ public function getTasksWithFkRisk() $records = array(); while ($i < $num) { $obj = $this->db->fetch_object($resql); - $records[$obj->fk_risk][$obj->rowid] = $tasksList[$obj->fk_object]; + $records[$obj->fk_risk][$obj->rowid] = $tasksList[$obj->fk_object] ?? null; $i++; } $this->db->free($resql); @@ -567,15 +666,51 @@ public function getTasksWithFkRisk() */ public function load_dashboard(): array { - $dangerCategories = $this->getDangerCategories(); + global $langs; + + $confName = dol_strtoupper($this->module) . '_DASHBOARD_CONFIG'; + $dashboardConfig = json_decode(getDolUserString($confName)); + $array = ['graphs' => [], 'lists' => [], 'disabledGraphs' => []]; + + $riskType = !empty($dashboardConfig->filters->riskType) ? $dashboardConfig->filters->riskType : 'risk'; - $getRisksByCotation = $this->getRisksByCotation(); - $getRisksByDangerCategoriesAndCriticality = $this->getRisksByDangerCategoriesAndCriticality($dangerCategories); - $getRisksByDangerCategories = $this->getRisksByDangerCategories($dangerCategories); - $getRiskListsByDangerCategories = $this->getRiskListsByDangerCategories($dangerCategories); + $digiriskElement = new DigiriskElement($this->db); - $array['graphs'] = [$getRisksByCotation, $getRisksByDangerCategoriesAndCriticality, $getRisksByDangerCategories]; - $array['lists'] = [$getRiskListsByDangerCategories]; + $filter = 'AND t.fk_element NOT IN ' . $digiriskElement->getTrashExclusionSqlFilter(); + + $dangerCategories = $this->getDangerCategories(); + $riskByDangerCategoriesAndRiskAssessments = $this->getRiskByDangerCategoriesAndRiskAssessments($dangerCategories, $filter, $riskType); + $moreParam['filter'] = $filter; + + $array['graphsFilters'] = [ + 'riskType' => [ + 'title' => $langs->transnoentities('DisplayRiskOfType'), + 'type' => 'selectarray', + 'filter' => 'riskType', + 'values' => ['risk' => $langs->transnoentities('Risk'), 'riskenvironmental' => $langs->transnoentities('Riskenvironmental')], + 'currentValue' => $riskType + ]]; + + if (empty($dashboardConfig->graphs->RisksRepartitionByDangerCategoriesAndCriticality->hide)) { + $array['graphs'][] = $this->getRisksByDangerCategoriesAndCriticality($dangerCategories, $riskByDangerCategoriesAndRiskAssessments); + } else { + $array['disabledGraphs']['RisksRepartitionByDangerCategoriesAndCriticality'] = $langs->transnoentities('RisksRepartitionByDangerCategoriesAndCriticality'); + } + if (empty($dashboardConfig->graphs->RisksRepartitionByDangerCategories->hide)) { + $array['graphs'][] = $this->getRisksByDangerCategories($dangerCategories, $riskByDangerCategoriesAndRiskAssessments); + } else { + $array['disabledGraphs']['RisksRepartitionByDangerCategories'] = $langs->transnoentities('RisksRepartitionByDangerCategories'); + } + if (empty($dashboardConfig->graphs->RisksRepartitionByCotation->hide)) { + $array['graphs'][] = $this->getRisksByCotation($moreParam); + } else { + $array['disabledGraphs']['RisksRepartitionByCotation'] = $langs->transnoentities('RisksRepartitionByCotation'); + } + if (empty($dashboardConfig->graphs->RiskListsByDangerCategories->hide)) { + $array['lists'][] = $this->getRiskListsByDangerCategories($dangerCategories, $riskByDangerCategoriesAndRiskAssessments, $filter, $riskType); + } else { + $array['disabledGraphs']['RiskListsByDangerCategories'] = $langs->transnoentities('RiskListsByDangerCategories'); + } return $array; } @@ -583,17 +718,20 @@ public function load_dashboard(): array /** * Get risks by cotation * + * @param array $moreParam More param (Object/user/etc) * @return array * @throws Exception */ - public function getRisksByCotation(): array + public function getRisksByCotation(array $moreParam = []): array { global $conf, $langs; - $riskAssessment = new RiskAssessment($this->db); + $riskAssessment = new RiskAssessment($this->db); + $digiriskElement = new DigiriskElement($this->db); // Graph Title parameters $array['title'] = $langs->transnoentities('RisksRepartition'); + $array['name'] = 'RisksRepartition'; $array['picto'] = $this->picto; // Graph parameters @@ -604,8 +742,11 @@ public function getRisksByCotation(): array $array['dataset'] = 1; $array['labels'] = $this->cotations; - $riskAssessmentList = $riskAssessment->fetchAll('', '', 0, 0, ['customsql' => 'status = 1']); - $array['data'] = $riskAssessment->getRiskAssessmentCategoriesNumber($riskAssessmentList); + $join = ' LEFT JOIN ' . MAIN_DB_PREFIX . $this->table_element . ' as r ON r.rowid = t.fk_risk'; + $join .= ' LEFT JOIN ' . MAIN_DB_PREFIX . $digiriskElement->table_element . ' as d ON d.rowid = r.fk_element'; + + $riskAssessments = saturne_fetch_all_object_type('RiskAssessment', '', '', 0, 0, ['customsql' => 't.status = ' . RiskAssessment::STATUS_VALIDATED . str_replace('t.fk_element NOT IN', 'r.fk_element NOT IN', $moreParam['filter'])], 'AND', false, $moreParam['multiEntityManagement'] ?? true, false, $join); + $array['data'] = $riskAssessment->getRiskAssessmentCategoriesNumber($riskAssessments); return $array; } @@ -613,18 +754,17 @@ public function getRisksByCotation(): array /** * Get risks by danger categories and criticality * - * @param array $dangerCategories Danger categories datas - * @param string $type Risk type (risk, riskenvironmental or ...) - * + * @param array $dangerCategories Danger categories datas + * @param array $riskByDangerCategoriesAndRiskAssessments Risk by danger categories and risk assessments * @return array - * @throws Exception */ - public function getRisksByDangerCategoriesAndCriticality(array $dangerCategories, string $type = 'risk'): array + public function getRisksByDangerCategoriesAndCriticality(array $dangerCategories, array $riskByDangerCategoriesAndRiskAssessments): array { - global $conf, $langs; + global $langs; // Graph Title parameters $array['title'] = $langs->transnoentities('RisksRepartitionByDangerCategoriesAndCriticality'); + $array['name'] = 'RisksRepartitionByDangerCategoriesAndCriticality'; $array['picto'] = $this->picto; // Graph parameters @@ -636,14 +776,10 @@ public function getRisksByDangerCategoriesAndCriticality(array $dangerCategories $array['moreCSS'] = 'grid-2'; $array['labels'] = $this->cotations; - $join = ' LEFT JOIN ' . MAIN_DB_PREFIX . $this->table_element . ' as r ON r.rowid = t.fk_risk'; foreach ($dangerCategories as $dangerCategory) { $array['data'][$dangerCategory['position']][0] = $dangerCategory['name']; - - $risks = $this->fetchAll('', '', 0, 0, ['customsql' => 't.status = ' . self::STATUS_VALIDATED . ' AND t.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND t.fk_element = ' . GETPOST('id') : '') . ' AND t.type = "' . $type . '" AND t.category = ' . $dangerCategory['position']]); for ($i = 1; $i <= 4; $i++) { - $riskAssessments = saturne_fetch_all_object_type('RiskAssessment', '', '', 0, 0, ['customsql' => 't.status = ' . RiskAssessment::STATUS_VALIDATED . ' AND r.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND r.fk_element = ' . GETPOST('id') : '') . ' AND r.type = "' . $type . '" AND r.category = ' . $dangerCategory['position'] . ' AND t.cotation >= ' . $this->cotations[$i]['start'] . ' AND t.cotation <= ' . $this->cotations[$i]['end']], 'AND', false, true, false, $join); - $array['data'][$dangerCategory['position']]['y_combined_' . $array['labels'][$i]['label']] = ((is_array($risks) && !empty($risks) && is_array($riskAssessments) && !empty($riskAssessments)) ? count($riskAssessments) / count($risks) : 0); + $array['data'][$dangerCategory['position']]['y_combined_' . $array['labels'][$i]['label']] = !empty($riskByDangerCategoriesAndRiskAssessments[$dangerCategory['name']]['risk']) ? $riskByDangerCategoriesAndRiskAssessments[$dangerCategory['name']]['riskAssessments'][$i] / $riskByDangerCategoriesAndRiskAssessments[$dangerCategory['name']]['risk'] : 0; } } @@ -653,18 +789,19 @@ public function getRisksByDangerCategoriesAndCriticality(array $dangerCategories /** * Get risks by danger categories * - * @param array $dangerCategories Danger categories datas - * @param string $type Risk type (risk, riskenvironmental or ...) - * + * @param array $dangerCategories Danger categories datas + * @param array $riskByDangerCategoriesAndRiskAssessments Risk by danger categories and risk assessments + * * @return array * @throws Exception */ - public function getRisksByDangerCategories(array $dangerCategories, string $type = 'risk'): array + public function getRisksByDangerCategories(array $dangerCategories, array $riskByDangerCategoriesAndRiskAssessments): array { - global $conf, $langs; + global $langs; // Graph Title parameters $array['title'] = $langs->transnoentities('RisksRepartitionByDangerCategories'); + $array['name'] = 'RisksRepartitionByDangerCategories'; $array['picto'] = $this->picto; // Graph parameters @@ -683,10 +820,8 @@ public function getRisksByDangerCategories(array $dangerCategories, string $type ]; foreach ($dangerCategories as $dangerCategory) { - $risks = $this->fetchAll('', '', 0, 0, ['customsql' => 't.status = ' . self::STATUS_VALIDATED . ' AND t.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND t.fk_element = ' . GETPOST('id') : '') . ' AND t.type = "' . $type . '" AND t.category = ' . $dangerCategory['position']]); - $array['data'][$dangerCategory['position']][] = $dangerCategory['name']; - $array['data'][$dangerCategory['position']][] = (is_array($risks) && !empty($risks) ? count($risks) : 0); + $array['data'][$dangerCategory['position']][] = $riskByDangerCategoriesAndRiskAssessments[$dangerCategory['name']]['risk']; } return $array; @@ -695,49 +830,50 @@ public function getRisksByDangerCategories(array $dangerCategories, string $type /** * Get list of risks by danger categories * - * @param array $dangerCategories Danger categories datas - * @param string $type Risk type (risk, riskenvironmental or ...) + * @param array $dangerCategories Danger categories datas + * @param array $riskByDangerCategoriesAndRiskAssessments Risk by danger categories and risk assessments + * @param string $filter SQL Filter + * @param string $type Risk type (risk, riskenvironmental or ...) * * @return array * @throws Exception */ - public function getRiskListsByDangerCategories(array $dangerCategories, string $type = 'risk') : array + public function getRiskListsByDangerCategories(array $dangerCategories, array $riskByDangerCategoriesAndRiskAssessments, string $filter = '', string $type = 'risk') : array { + //$riskByDangerCategoriesAndRiskAssessments global $conf, $langs; + $digiriskElement = new DigiriskElement($this->db); + // Graph Title parameters $array['title'] = $langs->transnoentities('RiskListsByDangerCategories'); + $array['name'] = 'RiskListsByDangerCategories'; $array['picto'] = $this->picto; // Graph parameters $array['width'] = '100%'; $array['type'] = 'list'; - $totalRisks = $this->fetchAll('', '', 0, 0, ['customsql' => 't.status = ' . self::STATUS_VALIDATED . ' AND t.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND t.fk_element = ' . GETPOST('id') : '') . ' AND t.type = "' . $type . '"']); + $totalRisks = saturne_fetch_all_object_type('Risk', '', '', 0, 0, ['customsql' => 't.status = ' . self::STATUS_VALIDATED . ' AND t.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND t.fk_element = ' . GETPOST('id') : '') . ' AND t.type = "' . $type . '"' . (!empty($filter) ? ' AND ' . $filter : '')], 'AND', false, true, false, ' LEFT JOIN ' . MAIN_DB_PREFIX . $digiriskElement->table_element . ' as d ON d.rowid = t.fk_element'); $array['labels']['Ref'] = $langs->transnoentities('DangerCategories'); $array['labels']['numberOfRisks'] = $langs->transnoentities('NumberOfRisks') . ' : ' . '' . (is_array($totalRisks) && !empty($totalRisks) ? count($totalRisks) : 0) . ''; $array['labels']['percentage'] = $langs->transnoentities('Percentage'); $arrayRiskLists = []; - $join = ' LEFT JOIN ' . MAIN_DB_PREFIX . $this->table_element . ' as r ON r.rowid = t.fk_risk'; if (is_array($totalRisks) && !empty($totalRisks)) { foreach ($dangerCategories as $dangerCategory) { $arrayRiskLists[$dangerCategory['position']]['Ref']['value'] = $dangerCategory['name']; - $risks = $this->fetchAll('', '', 0, 0, ['customsql' => 't.status = ' . self::STATUS_VALIDATED . ' AND t.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND t.fk_element = ' . GETPOST('id') : '') . ' AND t.type = "' . $type . '" AND t.category = ' . $dangerCategory['position']]); - $arrayRiskLists[$dangerCategory['position']]['numberOfRisks']['value'] = is_array($risks) && !empty($risks) ? count($risks) : 0; + $arrayRiskLists[$dangerCategory['position']]['numberOfRisks']['value'] = $riskByDangerCategoriesAndRiskAssessments[$dangerCategory['name']]['risk']; $arrayRiskLists[$dangerCategory['position']]['numberOfRisks']['morecss'] = 'risk-evaluation-cotation'; $arrayRiskLists[$dangerCategory['position']]['numberOfRisks']['moreAttr'] = 'style="line-height: 0; border-radius: 0; background-color: #A1467EAA; color: #FFF;"'; - $arrayRiskLists[$dangerCategory['position']]['percentage']['value'] = is_array($risks) && !empty($risks) ? price2num((count($risks) / count($totalRisks)) * 100, 2) . ' %' : 0; + $arrayRiskLists[$dangerCategory['position']]['percentage']['value'] = price2num(($riskByDangerCategoriesAndRiskAssessments[$dangerCategory['name']]['risk'] / count($totalRisks)) * 100, 2) . ' %'; for ($i = 1; $i <= 4; $i++) { $array['labels'][$i] = $this->cotations[$i]['label']; - - $riskAssessments = saturne_fetch_all_object_type('RiskAssessment', '', '', 0, 0, ['customsql' => 't.status = ' . RiskAssessment::STATUS_VALIDATED . ' AND r.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND r.fk_element = ' . GETPOST('id') : '') . ' AND r.type = "' . $type . '" AND r.category = ' . $dangerCategory['position'] . ' AND t.cotation >= ' . $this->cotations[$i]['start'] . ' AND t.cotation <= ' . $this->cotations[$i]['end']], 'AND', false, true, false, $join); - - $arrayRiskLists[$dangerCategory['position']][$i]['value'] = is_array($riskAssessments) && !empty($riskAssessments) ? count($riskAssessments) : 0; + $arrayRiskLists[$dangerCategory['position']][$i]['value'] = $riskByDangerCategoriesAndRiskAssessments[$dangerCategory['name']]['riskAssessments'][$i]; $arrayRiskLists[$dangerCategory['position']][$i]['morecss'] = 'risk-evaluation-cotation'; $arrayRiskLists[$dangerCategory['position']][$i]['moreAttr'] = 'data-scale = ' . $i . ' style="line-height: 0; border-radius: 0;"'; } @@ -749,6 +885,36 @@ public function getRiskListsByDangerCategories(array $dangerCategories, string $ return $array; } + /** + * Get risk by danger categories and risk assessments + * + * @param array $dangerCategories Danger categories datas + * @param string $filter SQL Filter + * @param string $type Risk type (risk, riskenvironmental or ...) + * + * @return array + * @throws Exception + */ + public function getRiskByDangerCategoriesAndRiskAssessments(array $dangerCategories, string $filter = '', string $type = 'risk') : array + { + global $conf; + + $array = []; + $digiriskElement = new DigiriskElement($this->db); + + foreach ($dangerCategories as $dangerCategory) { + $risks = saturne_fetch_all_object_type('Risk', '', '', 0, 0, ['customsql' => 't.status = ' . self::STATUS_VALIDATED . ' AND t.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND t.fk_element = ' . GETPOST('id') : '') . ' AND t.type = "' . $type . '" AND t.category = ' . $dangerCategory['position'] . $filter], 'AND', false, true, false, ' LEFT JOIN ' . MAIN_DB_PREFIX . $digiriskElement->table_element . ' as d ON d.rowid = t.fk_element'); + $array[$dangerCategory['name']]['risk'] = !empty($risks) && is_array($risks) ? count($risks) : 0; + for ($i = 1; $i <= 4; $i++) { + $join = ' LEFT JOIN ' . MAIN_DB_PREFIX . $this->table_element . ' as r ON r.rowid = t.fk_risk'; + $join .= ' LEFT JOIN ' . MAIN_DB_PREFIX . $digiriskElement->table_element . ' as d ON d.rowid = r.fk_element'; + $riskAssessments = saturne_fetch_all_object_type('RiskAssessment', '', '', 0, 0, ['customsql' => 't.status = ' . RiskAssessment::STATUS_VALIDATED . ' AND r.entity = ' . $conf->entity . (GETPOSTISSET('id') ? ' AND r.fk_element = ' . GETPOST('id') : '') . ' AND r.type = "' . $type . '" AND r.category = ' . $dangerCategory['position'] . ' AND t.cotation >= ' . $this->cotations[$i]['start'] . ' AND t.cotation <= ' . $this->cotations[$i]['end'] . str_replace('t.fk_element NOT IN', 'r.fk_element NOT IN', $filter)], 'AND', false, true, false, $join); + $array[$dangerCategory['name']]['riskAssessments'][$i] = !empty($riskAssessments) && is_array($riskAssessments) ? count($riskAssessments) : 0; + } + } + return $array; + } + /** * Write information of trigger description * diff --git a/class/riskanalysis/riskassessment.class.php b/class/riskanalysis/riskassessment.class.php index ba8a091bc..d05ce61c1 100644 --- a/class/riskanalysis/riskassessment.class.php +++ b/class/riskanalysis/riskassessment.class.php @@ -92,7 +92,7 @@ class RiskAssessment extends SaturneObject 'date_riskassessment' => array('type' => 'datetime', 'label' => 'RiskAssessmentDate', 'enabled' => '1', 'position' => 141, 'notnull' => -1, 'visible' => 0,), 'comment' => array('type' => 'text', 'label' => 'Comment', 'enabled' => '1', 'position' => 150, 'notnull' => 0, 'visible' => 0,), 'photo' => array('type' => 'varchar(255)', 'label' => 'Photo', 'enabled' => '1', 'position' => 160, 'notnull' => 0, 'visible' => 0,), - 'has_tasks' => array('type' => 'integer', 'label' => 'Tasks', 'enabled' => '1', 'position' => 170, 'notnull' => 0, 'visible' => -1,), + 'has_tasks' => array('type' => 'integer', 'label' => 'Tasks', 'enabled' => '$conf->global->DIGIRISKDOLIBARR_TASK_MANAGEMENT', 'position' => 170, 'notnull' => 0, 'visible' => -1,), 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => '1', 'position' => 180, 'notnull' => 1, 'visible' => 0, 'foreignkey' => 'user.rowid',), 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => '1', 'position' => 190, 'notnull' => -1, 'visible' => 0,), 'fk_risk' => array('type' => 'integer', 'label' => 'ParentRisk', 'enabled' => '1', 'position' => 200, 'notnull' => 1, 'visible' => 0,), @@ -192,6 +192,53 @@ public function updatePreviousRiskAssessmentStatus(User $user, int $riskID) } } + /** + * check if risk assessment not exists for a risk + * + * @param int $limit Limit + * @return array|int Int <0 if KO, array of pages if OK + * @throws Exception + */ + public function checkNotExistsRiskForRiskAssessment(int $limit = 0) + { + dol_syslog(__METHOD__, LOG_DEBUG); + + $risk = new Risk($this->db); + + $sql = 'SELECT '; + $sql .= $this->getFieldList('t'); + $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; + $sql .= ' WHERE !EXISTS'; + $sql .= ' ( SELECT '; + $sql .= $risk->getFieldList('r'); + $sql .= ' FROM ' . MAIN_DB_PREFIX . $risk->table_element . ' as r'; + $sql .= ' WHERE r.rowid = t.fk_risk )'; + + $records = []; + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new $this($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error ' . $this->db->lasterror(); + dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR); + return -1; + } + } + /** * Return scale level for risk assessment * diff --git a/class/ticketdashboard.class.php b/class/ticketdashboard.class.php index e16723195..5c250c6ad 100644 --- a/class/ticketdashboard.class.php +++ b/class/ticketdashboard.class.php @@ -40,6 +40,11 @@ class TicketDashboard extends DigiriskDolibarrDashboard */ public DoliDB $db; + /** + * @var string Module name + */ + public $module = 'digiriskdolibarr'; + /** * @var string SQL FROM */ @@ -70,7 +75,7 @@ public function __construct(DoliDB $db, ?string $moreJoin = '', ?string $moreWhe if (dol_strlen($moreJoin) > 0) { $this->join .= $moreJoin; } - $this->where = 't.fk_statut >= 0'; + $this->where = 't.fk_statut > 0'; $this->where .= ' AND t.entity IN (' . getEntity('ticket') . ')'; if (dol_strlen($moreWhere) > 0) { $this->where .= $moreWhere; @@ -267,19 +272,36 @@ public function getNbTicketByDigiriskElementAndTicketTags(int $dateStart, int $d */ public function load_dashboard(array $moreParams = []): array { - $getTicketsByMonth = $this->getTicketsByMonth(); + global $langs; + + $confName = dol_strtoupper($this->module) . '_DASHBOARD_CONFIG'; + $dashboardConfig = json_decode(getDolUserString($confName)); + $array = ['graphs' => [], 'lists' => [], 'disabledGraphs' => []]; $category = new Categorie($this->db); $category->fetch(getDolGlobalInt('DIGIRISKDOLIBARR_TICKET_MAIN_CATEGORY')); $mainCategories = $category->get_filles(); - $getTicketsByMainTagAndByDigiriskElement = $this->getTicketsByMainTagAndByDigiriskElement($mainCategories); - $getTicketsByMainSubTagAndByDigiriskElement = $this->getTicketsByMainSubTagAndByDigiriskElement($mainCategories); - - $getTicketsByYear = $this->getTicketsByYear(); - - $array['graphs'] = [$getTicketsByMonth, $getTicketsByMainTagAndByDigiriskElement, $getTicketsByMainSubTagAndByDigiriskElement]; - $array['lists'] = [$getTicketsByYear]; + if (empty($dashboardConfig->graphs->NumberOfTicketsByMonth->hide)) { + $array['graphs'][] = $this->getTicketsByMonth(); + } else { + $array['disabledGraphs']['NumberOfTicketsByMonth'] = $langs->transnoentities('NumberOfTicketsByMonth'); + } + if (empty($dashboardConfig->graphs->NumberOfTicketsByMainTagAndByDigiriskElement->hide)) { + $array['graphs'][] = $this->getTicketsByMainTagAndByDigiriskElement($mainCategories); + } else { + $array['disabledGraphs']['NumberOfTicketsByMainTagAndByDigiriskElement'] = $langs->transnoentities('NumberOfTicketsByMainTagAndByDigiriskElement'); + } + if (empty($dashboardConfig->graphs->NumberOfTicketsByMainSubTagAndByDigiriskElement->hide)) { + $array['graphs'][] = $this->getTicketsByMainSubTagAndByDigiriskElement($mainCategories); + } else { + $array['disabledGraphs']['NumberOfTicketsByMainSubTagAndByDigiriskElement'] = $langs->transnoentities('NumberOfTicketsByMainSubTagAndByDigiriskElement'); + } + if (empty($dashboardConfig->graphs->NumberOfTicketsByYear->hide)) { + $array['lists'][] = $this->getTicketsByYear(); + } else { + $array['disabledGraphs']['NumberOfTicketsByYear'] = $langs->transnoentities('NumberOfTicketsByYear'); + } return $array; } @@ -295,6 +317,7 @@ public function getTicketsByMonth(): array // Graph Title parameters $array['title'] = $langs->transnoentities('NumberOfTicketsByMonth'); + $array['name'] = 'NumberOfTicketsByMonth'; $array['picto'] = 'fontawesome_fa-ticket-alt_fas_#3bbfa8'; // Graph parameters @@ -352,6 +375,7 @@ public function getTicketsByMainTagAndByDigiriskElement($mainCategories): array // Graph Title parameters $array['title'] = $langs->transnoentities('NumberOfTicketsByMainTagAndByDigiriskElement'); + $array['name'] = 'NumberOfTicketsByMainTagAndByDigiriskElement'; $array['picto'] = 'fontawesome_fa-ticket-alt_fas_#3bbfa8'; // Graph parameters @@ -398,6 +422,7 @@ public function getTicketsByMainSubTagAndByDigiriskElement($mainCategories): arr // Graph Title parameters $array['title'] = $langs->transnoentities('NumberOfTicketsByMainSubTagAndByDigiriskElement'); + $array['name'] = 'NumberOfTicketsByMainSubTagAndByDigiriskElement'; $array['picto'] = 'fontawesome_fa-ticket-alt_fas_#3bbfa8'; // Graph parameters @@ -449,6 +474,7 @@ public function getTicketsByYear(): array // Graph Title parameters $array['title'] = $langs->transnoentities('NumberOfTicketsByYear'); + $array['name'] = 'NumberOfTicketsByYear'; $array['picto'] = 'fontawesome_fa-ticket-alt_fas_#3bbfa8'; // Graph parameters @@ -461,7 +487,7 @@ public function getTicketsByYear(): array foreach ($tickets as $key => $ticket) { $arrayTicketByYear[$key]['Ref']['value'] = $ticket['year']; $arrayTicketByYear[$key]['Tickets']['value'] = $ticket['nb']; - $arrayTicketByYear[$key]['Percentage']['value'] = price2num($ticket['avg'] ?: 0, 2) . ' %'; + $arrayTicketByYear[$key]['Percentage']['value'] = price2num($ticket['avg'] ?? 0, 2) . ' %'; } } diff --git a/class/ticketstatsdashboard.class.php b/class/ticketstatsdashboard.class.php new file mode 100644 index 000000000..bd5401729 --- /dev/null +++ b/class/ticketstatsdashboard.class.php @@ -0,0 +1,350 @@ + + * + * 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/ticketstatsdashboard.class.php + * \ingroup digiriskdolibarr + * \brief Class file for manage TicketDashboard + */ + +// load Dolibarr librairies +require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php'; + +/** + * Class to manage stats for tickets + */ +class TicketStatsDashboard extends DigiriskDolibarrDashboard +{ + /** + * @var DoliDB Database handler + */ + public DoliDB $db; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) + { + parent::__construct($db); + } + + /** + * Load dashboard info ticket + * + * @param array $moreParams Parameters for load dashboard info + * @return array + * @throws Exception + */ + public function load_dashboard(array $moreParams = []): array + { + $tickets = $this->getAllTickets(); + + $runningTickets = $this->getRunningTickets($tickets); + $ticketStats = $this->getTicketStats($tickets); + + $getTicketRepartitionPerUserAndMeanAnswerTime = $this->getTicketRepartitionPerUserAndMeanAnswerTime($tickets); + $getTopSocietyWithMostTickets = $this->getTopSocietyWithMostTickets($tickets); + + $array['widgets'] = array_merge($runningTickets, $ticketStats); + $array['graphs'] = [$getTicketRepartitionPerUserAndMeanAnswerTime, $getTopSocietyWithMostTickets]; + + return $array; + } + + /** + * Get all tickets from database for current entity order by datec DESC + * fetch all comments for each ticket if exists + * add them to ticket object as comms property (array of comments) + * + * @return array $tickets All tickets with comments if exists or empty array + * @throws Exception If an error occurs while fetching tickets + */ + public function getAllTickets(): array + { + try { + $actionComm = new ActionComm($this->db); + $tickets = saturne_fetch_all_object_type('Ticket', 'DESC', 't.datec'); + if (!empty($tickets) && is_array($tickets)) { + foreach ($tickets as $ticketID => $ticket) { + $ticket->comms = []; + $actionComms = $actionComm->getActions(0, $ticketID, 'ticket', 'AND a.code LIKE "TICKET_MSG%"', 'a.datec'); + if (!empty($actionComms) && is_array($actionComms)) { + $ticket->comms = $actionComms; + } elseif (is_string($actionComms)) { + dol_syslog(__METHOD__ . 'Error while fetching comments for ticket ID {$ticketID}: ' . $actionComms, LOG_ERR); + } + } + } + } catch (Exception $e) { + dol_syslog(__METHOD__ . 'Error while fetching tickets: ' . $e->getMessage(), LOG_ERR); + throw $e; + } + + return $tickets; + } + + /** + * Get running tickets + * + * @param array $tickets All tickets from database for current entity order by datec DESC with comments if exists or empty array + * @return array Widget of running tickets with the oldest ticket and oldest message ticket + */ + public function getRunningTickets(array $tickets): array + { + global $form, $langs; + + // Widget title parameters + $array['title'] = $langs->transnoentities('RunningTicket'); + $array['widgetName'] = 'RunningTicket'; + $array['picto'] = 'fas fa-ticket-alt'; + $array['pictoColor'] = '#0D8AFF'; + + // Widget labels parameters + $array['label'] = [ + $langs->transnoentities('NbOfOpenedTicket'), + $form->textwithpicto($langs->transnoentities('OldestTicket'), $langs->transnoentities('OldestTicketDescription')), + $form->textwithpicto($langs->transnoentities('OldestMessageTicket'), $langs->transnoentities('OldestMessageTicketDescription')) + ]; + + // Initialize variables + $openTickets = 0; + $oldestTicket = null; + $oldestMessageTicket = null; + $now = dol_now(); + + // Get number of open tickets, oldest ticket and oldest message ticket + if (!empty($tickets)) { + foreach ($tickets as $ticket) { + if (!in_array($ticket->fk_statut, [Ticket::STATUS_CANCELED, Ticket::STATUS_CLOSED])) { + $openTickets++; + + if (empty($oldestTicket) || $ticket->datec < $oldestTicket->datec) { + $oldestTicket = $ticket; + } + + $lastComm = !empty($ticket->comms) ? current($ticket->comms) : null; + if (!empty($lastComm) && (empty($oldestMessageTicket) || $lastComm->datec < $oldestMessageTicket->datec)) { + $oldestMessageTicket = $lastComm; + } + } + } + } + + // Widget content parameters + $array['content'] = [ + $openTickets, + !empty($oldestTicket) ? dol_print_date($oldestTicket->datec, 'day') : $langs->transnoentities('NoData'), + !empty($oldestMessageTicket) ? dol_print_date($oldestMessageTicket->datec, 'day') : $langs->transnoentities('NoData') + ]; + + $array['moreContent'] = [ + '', + !empty($oldestTicket) ? ' (' . convertSecondToTime(roundUpToNextMultiple($now - $oldestTicket->datec, 60)) . ')' . $oldestTicket->getNomUrl(2, '', 0, 'paddingleft') : '', + !empty($oldestMessageTicket) ? ' (' . convertSecondToTime(roundUpToNextMultiple($now - $oldestMessageTicket->datec, 60)) . ')' . $tickets[$oldestMessageTicket->fk_element]->getNomUrl(2, '', 0, 'paddingleft') : '' + ]; + + return ['runningTickets' => $array]; + } + + /** + * Get ticket stats + * + * @param array $tickets All tickets from database for current entity order by datec DESC with comments if exists or empty array + * @return array Widget of ticket stats with number of ticket per user, mean answer time and number of exchange per ticket + */ + function getTicketStats(array $tickets): array + { + global $langs; + + // Widget title parameters + $array['title'] = $langs->transnoentities('TicketStatistics'); + $array['widgetName'] = 'TicketStatistics'; + $array['picto'] = 'fas fa-chart-pie'; + $array['pictoColor'] = '#32E592'; + + // Widget labels parameters + $array['label'] = [ + $langs->transnoentities('MeanAnswerTime'), + $langs->transnoentities('NbTicketPerUser'), + $langs->transnoentities('NbExchangePerTicket') + ]; + + // Initialize variables + $timePerTicket = []; + $users = []; + $nbTicketAssigned = 0; + $nbExchanges = 0; + + if (!empty($tickets)) { + foreach ($tickets as $ticket) { + if (!empty($ticket->date_close)) { + $timePerTicket[] = $ticket->date_close - $ticket->datec; + } + if (!empty($ticket->fk_user_assign)) { + $nbTicketAssigned++; + if (!in_array($ticket->fk_user_assign, $users)) { + $users[] = $ticket->fk_user_assign; + } + } + $nbExchanges += count($ticket->comms); + } + } + + // Widget content parameters + $array['content'] = [ + count($timePerTicket) ? convertSecondToTime(array_sum($timePerTicket) / count($timePerTicket)) : $langs->transnoentities('NoData'), + count($users) ? intdiv($nbTicketAssigned, count($users)) : 0, + $tickets ? ceil($nbExchanges / count($tickets)) : 0 + ]; + + return ['ticketStats' => $array]; + } + + /** + * Get ticket repartition per user with number of ticket and mean answer time + * + * @param array $tickets All tickets from database for current entity order by datec DESC with comments if exists or empty array + * @return array Graph of ticket repartition per user with number of ticket and mean answer time + */ + function getTicketRepartitionPerUserAndMeanAnswerTime(array $tickets): array + { + global $langs; + + // Graph title parameters + $array['title'] = $langs->transnoentities('TicketRepartitionPerUserAndMeanAnswerTime'); + $array['picto'] = 'fontawesome_fa-ticket-alt_fas_#3bbfa8'; + + // Graph parameters + $array['width'] = '100%'; + $array['height'] = 300; + $array['type'] = 'bar'; + $array['showlegend'] = 1; + $array['dataset'] = 3; + $array['moreCSS'] = 'grid-2'; + + $array['labels'] = [ + ['label' => $langs->transnoentities('NbOfTickets')], + ['label' => $langs->transnoentities('MeanAnswerTime')] + ]; + + // Initialize technical objects + $userTmp = new User($this->db); + + // Initialize variables + $nbTicketPerUser = []; + + if (!empty($tickets)) { + foreach ($tickets as $ticket) { + if ($ticket->fk_user_assign == null) { + continue; + } + + $userTmp->fetch($ticket->fk_user_assign); + $userFullName = $userTmp->getFullName($langs); + if (!isset($nbTicketPerUser[$userFullName])) { + $nbTicketPerUser[$userFullName]['nbTicket'] = 0; + } + $nbTicketPerUser[$userFullName]['nbTicket']++; + if (!empty($ticket->date_close)) { + $nbTicketPerUser[$userFullName]['meanAnswerTime'][$ticket->id] = $ticket->date_close - $ticket->datec; + } + } + + if (!empty($nbTicketPerUser)) { + uasort($nbTicketPerUser, function($a, $b) { + return $b['nbTicket'] - $a['nbTicket']; + }); + + foreach ($nbTicketPerUser as $userName => $ticketData) { + $meanAnswerTimePerUser = 0; + if (isset($ticketData['meanAnswerTime'])) { + $meanAnswerTimePerUser = array_sum($ticketData['meanAnswerTime']) / count($ticketData['meanAnswerTime']); + $meanAnswerTimePerUser = round($meanAnswerTimePerUser / 86400); + } + $array['data'][] = [$userName, $ticketData['nbTicket'], $meanAnswerTimePerUser]; + } + } + } + + return $array; + } + + /** + * Get top society with most tickets + * + * @param array $tickets All tickets from database for current entity order by datec DESC with comments if exists or empty array + * @return array Graph of top society with most tickets + */ + function getTopSocietyWithMostTickets(array $tickets): array + { + global $langs; + + // Graph title parameters + $array['title'] = $langs->transnoentities('TopSocietyWithMostTickets', getDolGlobalInt('MAIN_SIZE_SHORTLIST_LIMIT', 5)); + $array['picto'] = 'fontawesome_fa-ticket-alt_fas_#3bbfa8'; + + // Graph parameters + $array['width'] = '100%'; + $array['height'] = 300; + $array['type'] = 'bar'; + $array['showlegend'] = 1; + $array['dataset'] = 2; + $array['moreCSS'] = 'grid-2'; + + $array['labels'] = [ + [ + 'label' => $langs->transnoentities('NbOfTickets'), + 'color' => '#A1467E' + ] + ]; + + // Initialize technical objects + $society = new Societe($this->db); + + // Initialize variables + $nbTicketPerSociety = []; + + if (!empty($tickets)) { + foreach ($tickets as $ticket) { + if ($ticket->fk_soc == null) { + continue; + } + + $society->fetch($ticket->fk_soc); + if (!isset($nbTicketPerSociety[$society->name])) { + $nbTicketPerSociety[$society->name]['nbTicket'] = 0; + } + $nbTicketPerSociety[$society->name]['nbTicket']++; + } + + if (!empty($nbTicketPerSociety)) { + uasort($nbTicketPerSociety, function($a, $b) { + return $b['nbTicket'] - $a['nbTicket']; + }); + + $nbTicketPerSociety = array_slice($nbTicketPerSociety, 0, getDolGlobalInt('MAIN_SIZE_SHORTLIST_LIMIT', 5), true); + foreach ($nbTicketPerSociety as $socName => $ticketData) { + $array['data'][] = [$socName, $ticketData['nbTicket']]; + } + } + } + + return $array; + } +} 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 0677b21fb..82de373d5 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/accidentinvestigationdocument/doc_accidentinvestigationdocument_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/accidentinvestigationdocument/doc_accidentinvestigationdocument_odt.modules.php @@ -215,17 +215,24 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $tmpArray['attendants_number'] = '0 '; } - $tmpArray['victim_lastname'] = dol_strtoupper($victim->lastname); - $tmpArray['victim_firstname'] = ucfirst($victim->firstname); $tmpArray['seniority_in_position'] = $object->seniority_in_position; - if ($victim->dateemployment > 0) { - $daysEmployee = dol_time_plus_duree($now, -$victim->dateemployment, 's'); - $daysEmployee = round($daysEmployee / 60 / 60 / 24); - $tmpArray['victim_date_employment'] = dol_print_date($victim->dateemployment, 'day', 'tzuser') . ' - ' . $daysEmployee . ' ' . ($daysEmployee <= 1 ? $outputLangs->trans('Day') : $outputLangs->trans('Days')); - } else { - $tmpArray['victim_date_employment'] = ''; - } + if ($victim->id > 0) { + $tmpArray['victim_lastname'] = dol_strtoupper($victim->lastname); + $tmpArray['victim_firstname'] = ucfirst($victim->firstname); + if ($victim->dateemployment > 0) { + $daysEmployee = dol_time_plus_duree($now, -$victim->dateemployment, 's'); + $daysEmployee = round($daysEmployee / 60 / 60 / 24); + $tmpArray['victim_date_employment'] = dol_print_date($victim->dateemployment, 'day', 'tzuser') . ' - ' . $daysEmployee . ' ' . ($daysEmployee <= 1 ? $outputLangs->trans('Day') : $outputLangs->trans('Days')); + } else { + $tmpArray['victim_date_employment'] = ''; + } + } else { + $tmpArray['victim_lastname'] = ''; + $tmpArray['victim_firstname'] = ''; + $tmpArray['victim_date_employment'] = ''; + } + $tmpArray['accident_date'] = dol_print_date($accident->accident_date, 'day'); $tmpArray['accident_hour'] = dol_print_date($accident->accident_date, 'hour'); $tmpArray['accident_day'] = dol_print_date($accident->accident_date, '%A'); diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/digiriskelementdocument/modules_digiriskelementdocument.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/digiriskelementdocument/modules_digiriskelementdocument.php index 5577f3650..f56fabef8 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/digiriskelementdocument/modules_digiriskelementdocument.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/digiriskelementdocument/modules_digiriskelementdocument.php @@ -32,8 +32,9 @@ require_once __DIR__ . '/../../../../../class/riskanalysis/risk.class.php'; require_once __DIR__ . '/../../../../../class/evaluator.class.php'; require_once __DIR__ . '/../../../../../class/accident.class.php'; +require_once __DIR__ . '/../../../../../class/digiriskresources.class.php'; -// Load saturne libraries +// Load Saturne libraries require_once __DIR__ . '/../../../../../../saturne/core/modules/saturne/modules_saturne.php'; /** @@ -306,6 +307,32 @@ public function write_file(SaturneDocuments $objectDocument, Translate $outputLa $tmpArray['photo'] = DOL_DOCUMENT_ROOT . $noPhoto; } + $resources = new DigiriskResources($this->db); + $userTmp = new User($this->db); + + // Get QRCode to public interface + if (isModEnabled('multicompany')) { + $qrCodePath = DOL_DATA_ROOT . '/digiriskdolibarr/multicompany/ticketqrcode/'; + } else { + $qrCodePath = $conf->digiriskdolibarr->multidir_output[$conf->entity ?: 1] . '/ticketqrcode/'; + } + $QRCodeList = dol_dir_list($qrCodePath); + if (is_array($QRCodeList) && !empty($QRCodeList)) { + $QRCode = array_shift($QRCodeList); + $QRCodeImagePath = $QRCode['fullname']; + } else { + $QRCodeImagePath = DOL_DOCUMENT_ROOT . '/public/theme/common/nophoto.png'; + } + + $allLinks = $resources->fetchDigiriskResources(); + $responsibleResources = $allLinks['Responsible']; + $userTmp->fetch($responsibleResources->id[0]); + + // @todo The keyword "signature" is needed because we want the image to be cropped to fit in the table + $tmpArray['helpUrl'] = DOL_MAIN_URL_ROOT . '/custom/digiriskdolibarr/public/ticket/create_ticket.php'; + $tmpArray['signatureQRCodeTicket'] = $QRCodeImagePath; + $tmpArray['securityResponsible'] = (!empty($userTmp) ? dol_strtoupper($userTmp->lastname) . ' ' . ucfirst($userTmp->firstname) : ''); + if (isset($moreParam['tmparray']) && is_array($moreParam['tmparray'])) { $moreParam['tmparray'] = array_merge($moreParam['tmparray'], $tmpArray); } else { 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 10a865cd2..559cd0a10 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/ticketdocument/doc_ticketdocument_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/ticketdocument/doc_ticketdocument_odt.modules.php @@ -108,7 +108,7 @@ public function fillTagsLines(Odf $odfHandler, Translate $outputLangs, array $mo $tmpArray['type'] = $outputLangs->transnoentities('Action' . $actionComm->type_code); $tmpArray['title'] = $actionComm->label; $tmpArray['event_content'] = dol_htmlentitiesbr_decode($actionComm->note); - $tmpArray['date'] = dol_print_date($actionComm->datec, 'dayreduceformat'); + $tmpArray['date'] = dol_print_date($actionComm->datec, 'dayhourreduceformat'); $this->setTmpArrayVars($tmpArray, $listLines, $outputLangs); } diff --git a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/workunitdocument/doc_workunitdocument_odt.modules.php b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/workunitdocument/doc_workunitdocument_odt.modules.php index 7b9adcc40..cb8da90f8 100644 --- a/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/workunitdocument/doc_workunitdocument_odt.modules.php +++ b/core/modules/digiriskdolibarr/digiriskdolibarrdocuments/workunitdocument/doc_workunitdocument_odt.modules.php @@ -28,7 +28,6 @@ // Load DigiriskDolibarr libraries require_once __DIR__ . '/../digiriskelementdocument/modules_digiriskelementdocument.php'; -require_once __DIR__ . '/../../../../../class/digiriskresources.class.php'; /** * Class to build documents using ODF templates generator @@ -65,52 +64,4 @@ public function info(Translate $langs): string { return parent::info($langs); } - - /** - * 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; - - $resources = new DigiriskResources($this->db); - $userTmp = new User($this->db); - - // Get QRCode to public interface - if (isModEnabled('multicompany')) { - $qrCodePath = DOL_DATA_ROOT . '/digiriskdolibarr/multicompany/ticketqrcode/'; - } else { - $qrCodePath = $conf->digiriskdolibarr->multidir_output[$conf->entity ?: 1] . '/ticketqrcode/'; - } - $QRCodeList = dol_dir_list($qrCodePath); - if (is_array($QRCodeList) && !empty($QRCodeList)) { - $QRCode = array_shift($QRCodeList); - $QRCodeImagePath = $QRCode['fullname']; - } else { - $QRCodeImagePath = DOL_DOCUMENT_ROOT . '/public/theme/common/nophoto.png'; - } - - $allLinks = $resources->fetchDigiriskResources(); - $responsibleResources = $allLinks['Responsible']; - $userTmp->fetch($responsibleResources->id[0]); - - // @todo The keyword "signature" is needed because we want the image to be cropped to fit in the table - $tmpArray['helpUrl'] = DOL_MAIN_URL_ROOT . '/custom/digiriskdolibarr/public/ticket/create_ticket.php'; - $tmpArray['signatureQRCodeTicket'] = $QRCodeImagePath; - $tmpArray['securityResponsible'] = (!empty($userTmp) ? dol_strtoupper($userTmp->lastname) . ' ' . ucfirst($userTmp->firstname) : ''); - - $moreParam['tmparray'] = $tmpArray; - - return parent::write_file($objectDocument, $outputLangs, $srcTemplatePath, $hideDetails, $hideDesc, $hideRef, $moreParam); - } } diff --git a/core/modules/modDigiriskDolibarr.class.php b/core/modules/modDigiriskDolibarr.class.php index ede0ae826..367154523 100644 --- a/core/modules/modDigiriskDolibarr.class.php +++ b/core/modules/modDigiriskDolibarr.class.php @@ -364,7 +364,7 @@ public function __construct($db) $this->errors[] = $langs->trans('activateModuleDependNotSatisfied', 'Digirisk', 'Saturne'); } - $langs->load("digiriskdolibarr@digiriskdolibarr"); + $langs->loadLangs(['digiriskdolibarr@digiriskdolibarr', 'categories']); // Id for module (must be unique). // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id). @@ -380,7 +380,7 @@ public function __construct($db) $this->descriptionlong = "Digirisk"; $this->editor_name = 'Evarisk'; $this->editor_url = 'https://evarisk.com'; - $this->version = '10.2.1'; + $this->version = '20.0.0'; $this->const_name = 'MAIN_MODULE_' . strtoupper($this->name); $this->picto = 'digiriskdolibarr_color@digiriskdolibarr'; @@ -478,7 +478,7 @@ public function __construct($db) $this->hidden = false; $this->depends = ['modSaturne', 'modECM', 'modProjet', 'modSociete', 'modTicket', 'modCategorie', 'modFckeditor', 'modApi', 'modExport', 'modImport']; - $this->requiredby = []; + $this->requiredby = ['modDigiBoard']; $this->conflictwith = []; $this->langfiles = ["digiriskdolibarr@digiriskdolibarr"]; $this->phpmin = [7, 4]; // Minimum version of PHP required by module @@ -755,7 +755,7 @@ public function __construct($db) $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_CHILD_CATEGORY_LABEL', 'chaine', $langs->trans('Rubriques'), '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_TICKET_PROJECT', 'integer', 0, '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_TICKET_SUCCESS_MESSAGE', 'chaine', $langs->trans('YouMustNotifyYourHierarchy'), '', 0, 'current'], $i++ => ['DIGIRISKDOLIBARR_SHOW_MULTI_ENTITY_SELECTOR_ON_TICKET_PUBLIC_INTERFACE', 'integer', 0, '', 0, 'current'], @@ -901,6 +901,7 @@ public function __construct($db) $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' => 'categories_ticket:+config:' . $pictoDigirisk .$langs->trans('WHSRegister') . ':digiriskdolibarr@digiriskdolibarr:1:/custom/digiriskdolibarr/view/ticket/category_config.php?id=__ID__&type=ticket']; // Dictionaries $this->dictionaries = [ @@ -1398,7 +1399,7 @@ public function __construct($db) 'prefix' => '', 'mainmenu' => 'digiriskdolibarr', 'leftmenu' => 'digiriskstandard', - 'url' => '/digiriskdolibarr/view/digiriskstandard/digiriskstandard_card.php', + 'url' => '/digiriskdolibarr/view/digiriskstandard/digiriskstandard_card.php?type=risk', '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', // 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. @@ -1459,7 +1460,7 @@ public function __construct($db) 'prefix' => '', 'mainmenu' => 'digiriskdolibarr', 'leftmenu' => 'digiriskstandard_riskenvironmental', - 'url' => '/digiriskdolibarr/view/digiriskstandard/digiriskstandard_card.php', + 'url' => '/digiriskdolibarr/view/digiriskstandard/digiriskstandard_card.php?type=riskenvironmental', 'langs' => 'digiriskdolibarr@digiriskdolibarr', 'position' => 100 + $r, 'enabled' => '$conf->digiriskdolibarr->enabled', @@ -1693,7 +1694,7 @@ public function __construct($db) 'prefix' => $pictoDigirisk, 'mainmenu' => 'ticket', 'leftmenu' => 'ticketstats', - 'url' => '/digiriskdolibarr/view/ticket/ticketstats.php', + 'url' => '/digiriskdolibarr/view/ticket/ticket_management_dashboard.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->ticket->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. @@ -1803,7 +1804,7 @@ public function __construct($db) $this->export_entities_array[$r] = []; $keyforclass = ucfirst($key); - $keyforclassfile = '/' . $this->rights_class . '/class/' . $objectMetaData['classPath'] . '/' . $key . '.class.php'; + $keyforclassfile = '/' . $this->rights_class . '/class/' . (isset($objectMetaData['classPath']) ? $objectMetaData['classPath'] . '/' : '') . $key . '.class.php'; $keyforelement = $key; $keyforalias = 't'; @@ -2106,6 +2107,28 @@ public function init($options = '') dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_THIRDPARTY_SET', 3, 'integer', 0, '', $conf->entity); } + if (getDolGlobalInt('DIGIRISKDOLIBARR_THIRDPARTY_SET') == 3) { + $poisonCenters = [ + 'ANGERS' => ['phone' => '02 41 48 21 21'], + 'BORDEAUX' => ['phone' => '05 56 96 40 80'], + 'LILLE' => ['phone' => '08 00 59 59 59'], + 'LYON' => ['phone' => '04 72 11 69 11'], + 'MARSEILLE' => ['phone' => '04 91 75 25 25'], + 'NANCY' => ['phone' => '03 83 22 50 50'], + 'PARIS' => ['phone' => '01 40 05 48 48'], + 'TOULOUSE' => ['phone' => '05 61 77 74 47'] + ]; + + foreach ($poisonCenters as $city => $poisonCenter) { + $societe->name = $langs->trans('PoisonControlCenter') . ' ' . $city . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; + $societe->client = 0; + $societe->phone = $poisonCenter['phone']; + $societe->url = ''; + $poisonControlCenterID = $societe->create($user); + } + + dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_THIRDPARTY_SET', 4, 'integer', 0, '', $conf->entity); + } if (getDolGlobalInt('DIGIRISKDOLIBARR_CONTACTS_SET') == 0) { require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; @@ -2136,118 +2159,105 @@ public function init($options = '') dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_CONTACTS_SET', 1, 'integer', 0, '', $conf->entity); } - if ( $conf->global->DIGIRISKDOLIBARR_THIRDPARTY_UPDATED == 0 ) { - require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php'; - require_once __DIR__ . '/../../class/digiriskresources.class.php'; - - $societe = new Societe($this->db); - $resources = new DigiriskResources($this->db); - $labour_inspectorID = $resources->fetchDigiriskResource('LabourInspectorSociety'); - $societe->fetch($labour_inspectorID); - $societe->name = $langs->trans('LabourInspectorName') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; - $societe->update(0, $user); - - $policeID = $resources->fetchDigiriskResource('Police'); - $societe->fetch($policeID); - $societe->name = $langs->trans('Police') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; - $societe->update(0, $user); - - $samuID = $resources->fetchDigiriskResource('SAMU'); - $societe->fetch($samuID); - $societe->name = $langs->trans('SAMU') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; - $societe->update(0, $user); - - $pompiersID = $resources->fetchDigiriskResource('Pompiers'); - $societe->fetch($pompiersID); - $societe->name = $langs->trans('Pompiers') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; - $societe->update(0, $user); - - $emergencyID = $resources->fetchDigiriskResource('AllEmergencies'); - $societe->fetch($emergencyID); - $societe->name = $langs->trans('AllEmergencies') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; - $societe->update(0, $user); - - $rights_defenderID = $resources->fetchDigiriskResource('RightsDefender'); - $societe->fetch($rights_defenderID); - $societe->name = $langs->transnoentities('RightsDefender') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; - $societe->update(0, $user); - - $poison_control_centerID = $resources->fetchDigiriskResource('PoisonControlCenter'); - $societe->fetch($poison_control_centerID); - $societe->name = $langs->trans('PoisonControlCenter') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; - $societe->update(0, $user); - - dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_THIRDPARTY_UPDATED', 1, 'integer', 0, '', $conf->entity); - } + if (getDolGlobalInt('DIGIRISKDOLIBARR_THIRDPARTY_UPDATED') == 0) { + $labourInspectorID = $resources->fetchDigiriskResource('LabourInspectorSociety'); + $societe->fetch($labourInspectorID); + $societe->name = $langs->trans('LabourInspectorName') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; + $societe->update(0, $user); + + $policeID = $resources->fetchDigiriskResource('Police'); + $societe->fetch($policeID); + $societe->name = $langs->trans('Police') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; + $societe->update(0, $user); + + $samuID = $resources->fetchDigiriskResource('SAMU'); + $societe->fetch($samuID); + $societe->name = $langs->trans('SAMU') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; + $societe->update(0, $user); + + $pompiersID = $resources->fetchDigiriskResource('Pompiers'); + $societe->fetch($pompiersID); + $societe->name = $langs->trans('Pompiers') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; + $societe->update(0, $user); + + $emergencyID = $resources->fetchDigiriskResource('AllEmergencies'); + $societe->fetch($emergencyID); + $societe->name = $langs->trans('AllEmergencies') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; + $societe->update(0, $user); + + $rightsDefenderID = $resources->fetchDigiriskResource('RightsDefender'); + $societe->fetch($rightsDefenderID); + $societe->name = $langs->transnoentities('RightsDefender') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; + $societe->update(0, $user); + + $poisonControlCenterID = $resources->fetchDigiriskResource('PoisonControlCenter'); + $societe->fetch($poisonControlCenterID); + $societe->name = $langs->trans('PoisonControlCenter') . ' - ' . $conf->global->MAIN_INFO_SOCIETE_NOM; + $societe->update(0, $user); + + dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_THIRDPARTY_UPDATED', 1, 'integer', 0, '', $conf->entity); + } + if (getDolGlobalInt('DIGIRISKDOLIBARR_THIRDPARTY_UPDATED') == 1) { + $rightsDefenderID = $resources->fetchDigiriskResource('RightsDefender'); + $societe->fetch($rightsDefenderID); + $societe->phone = '09 69 39 00 00'; + $societe->url = 'https://www.defenseurdesdroits.fr/'; + $societe->update(0, $user); + + dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_THIRDPARTY_UPDATED', 2, 'integer', 0, '', $conf->entity); + } - // Create extrafields during init - include_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; - require_once __DIR__ . '/../../lib/digiriskdolibarr_function.lib.php'; - - $extra_fields = new ExtraFields($this->db); - - $extra_fields->update('fk_risk', $langs->transnoentities("RiskLinked"), 'sellist', '', 'projet_task', 0, 0, 1010, 'a:1:{s:7:"options";a:1:{s:50:"digiriskdolibarr_risk:ref:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extra_fields->addExtraField('fk_risk', $langs->transnoentities("RiskLinked"), 'sellist', 1010, '', 'projet_task', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:50:"digiriskdolibarr_risk:ref:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extra_fields->update('fk_preventionplan', $langs->transnoentities("PreventionPlanLinked"), 'sellist', '', 'projet_task', 0, 0, 1020, 'a:1:{s:7:"options";a:1:{s:60:"digiriskdolibarr_preventionplan:ref:rowid::entity = $ENTITY$";N;}}', '', '', '', 1); - $extra_fields->addExtraField('fk_preventionplan', $langs->transnoentities("PreventionPlanLinked"), 'sellist', 1020, '', 'projet_task', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:60:"digiriskdolibarr_preventionplan:ref:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extra_fields->update('fk_firepermit', $langs->transnoentities("FirePermitLinked"), 'sellist', '', 'projet_task', 0, 0, 1030, 'a:1:{s:7:"options";a:1:{s:56:"digiriskdolibarr_firepermit:ref:rowid::entity = $ENTITY$";N;}}', '', '', '', 1); - $extra_fields->addExtraField('fk_firepermit', $langs->transnoentities("FirePermitLinked"), 'sellist', 1030, '', 'projet_task', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:56:"digiriskdolibarr_firepermit:ref:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extra_fields->update('fk_accident', $langs->transnoentities("AccidentLinked"), 'sellist', '', 'projet_task', 0, 0, 1040, 'a:1:{s:7:"options";a:1:{s:54:"digiriskdolibarr_accident:ref:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extra_fields->addExtraField('fk_accident', $langs->transnoentities("AccidentLinked"), 'sellist', 1040, '', 'projet_task', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:54:"digiriskdolibarr_accident:ref:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extra_fields->update('fk_accidentinvestigation', $langs->transnoentities("AccidentInvestigationLinked"), 'sellist', '', 'projet_task', 0, 0, 1050, 'a:1:{s:7:"options";a:1:{s:68:"digiriskdolibarr_accident_investigation:ref:rowid::entity = $ENTITY$";N;}}', '', '', 1); - $extra_fields->addExtraField('fk_accidentinvestigation', $langs->transnoentities("AccidentInvestigationLinked"), 'sellist', 1050, '', 'projet_task', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:68:"digiriskdolibarr_accident_investigation:ref:rowid::entity = $ENTITY$";N;}}', '', '', 1); - - if (!$conf->global->DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS_BACKWARD_COMPATIBILITY && (dolibarr_get_const($this->db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', 0) || dolibarr_get_const($this->db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', $conf->entity))) { - if ($conf->multicompany->enabled) { - $current_entity = $conf->entity; - $object = new ActionsMulticompany($this->db); - - $entities = $object->getEntitiesList(false, false, true, true); - foreach ($entities as $sub_entity => $entity_name) { - $conf->setEntityValues($this->db, $sub_entity); - - extrafield_soft_delete('digiriskdolibarr_ticket_firstname', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_lastname', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_phone', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_service', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_location', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_date', 'ticket', $extra_fields); - } - $conf->setEntityValues($this->db, $current_entity); - } else { - extrafield_soft_delete('digiriskdolibarr_ticket_firstname', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_lastname', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_phone', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_service', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_location', 'ticket', $extra_fields); - extrafield_soft_delete('digiriskdolibarr_ticket_date', 'ticket', $extra_fields); - } + // Create extrafields during init + require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; - $extra_fields->addExtraField('digiriskdolibarr_ticket_lastname', $langs->transnoentities("LastName"), 'varchar', 2000, 255, 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - $extra_fields->addExtraField('digiriskdolibarr_ticket_firstname', $langs->transnoentities("FirstName"), 'varchar', 2100, 255, 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - $extra_fields->addExtraField('digiriskdolibarr_ticket_phone', $langs->transnoentities("Phone"), 'phone', 2200, '', 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - $extra_fields->addExtraField('digiriskdolibarr_ticket_service', $langs->transnoentities("GP/UT"), 'sellist', 2300, '255', 'ticket', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:61:"digiriskdolibarr_digiriskelement:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 4, '','',0); - $extra_fields->addExtraField('digiriskdolibarr_ticket_location', $langs->transnoentities("Location"), 'varchar', 2400, 255, 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - $extra_fields->addExtraField('digiriskdolibarr_ticket_date', $langs->transnoentities("Date"), 'datetime', 2500, '', 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', 1, 'integer', 0, '', 0); - dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS_BACKWARD_COMPATIBILITY', 1, 'integer', 0, '', 0); - } + $extraFields = new ExtraFields($this->db); - //Used for data import from Digirisk Wordpress - $extra_fields->update('wp_digi_id', $langs->trans("WPDigiID"), 'int', 100, 'digiriskdolibarr_digiriskelement', 0, 0, 1020, '', '', '', 0); - $extra_fields->addExtraField('wp_digi_id', $langs->trans("WPDigiID"), 'int', 100, '', 'digiriskdolibarr_digiriskelement', 0, 0, '', '', '', '', 0); - $extra_fields->addExtraField('entity', $langs->trans("Entity"), 'int', 100, '', 'digiriskdolibarr_digiriskelement', 0, 0, '', '', '', '', 0); + $commonExtraFieldsValue = [ + 'alwayseditable' => 1, 'list' => 1, 'help' => '', 'entity' => 0, 'langfile' => 'digiriskdolibarr@digiriskdolibarr', 'enabled' => "isModEnabled('digiriskdolibarr') && isModEnabled('project')", 'moreparams' => ['css' => 'minwidth100 maxwidth300'] + ]; - $extra_fields->addExtraField('professional_qualification', $langs->trans("ProfessionalQualification"), 'varchar', 990, 255, 'user', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:0:"";N;}}', 1, '', 1, '', '', 0, 'digiriskdolibarr'); - $extra_fields->addExtraField('contract_type', $langs->trans("ContractType"), 'select', 1000, '', 'user', 0, 0, '', 'a:1:{s:7:"options";a:5:{i:1;s:3:"CDI";i:2;s:3:"CDD";i:3;s:18:"Apprentice/Student";i:4;s:7:"Interim";i:5;s:5:"Other";}}', 1, '', 1, '', '', 0, 'digiriskdolibarr'); + $extraFieldsArrays = [ + 'fk_risk' => ['Label' => 'Risk', 'type' => 'link', 'elementtype' => ['projet_task'], 'position' => $this->numero . 10, 'params' => ['Risk:digiriskdolibarr/class/riskanalysis/risk.class.php:1:(entity:IN:__SHARED_ENTITIES__)' => NULL], ], + 'fk_preventionplan' => ['Label' => 'PreventionPlan', 'type' => 'link', 'elementtype' => ['projet_task'], 'position' => $this->numero . 20, 'params' => ['PreventionPlan:digiriskdolibarr/class/preventionplan.class.php:1:(entity:IN:__SHARED_ENTITIES__)' => NULL], ], + 'fk_firepermit' => ['Label' => 'FirePermit', 'type' => 'link', 'elementtype' => ['projet_task'], 'position' => $this->numero . 30, 'params' => ['FirePermit:digiriskdolibarr/class/firepermit.class.php:1:(entity:IN:__SHARED_ENTITIES__)' => NULL], ], + 'fk_accident' => ['Label' => 'Accident', 'type' => 'link', 'elementtype' => ['projet_task'], 'position' => $this->numero . 40, 'params' => ['Accident:digiriskdolibarr/class/accident.class.php:1:(entity:IN:__SHARED_ENTITIES__)' => NULL], ], + 'fk_accidentinvestigation' => ['Label' => 'AccidentInvestigation', 'type' => 'link', 'elementtype' => ['projet_task'], 'position' => $this->numero . 50, 'params' => ['AccidentInvestigation:digiriskdolibarr/class/accidentinvestigation.class.php:1:(entity:IN:__SHARED_ENTITIES__)' => NULL]], - if ($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2 == 0) { - dolibarr_set_const($this->db, 'MAIN_EXTRAFIELDS_USE_SELECT2', 1, 'integer', 0, '', $conf->entity); - } + 'wp_digi_id' => ['Label' => 'WPDigiID', 'type' => 'int', 'length' => 100, 'elementtype' => ['digiriskdolibarr_digiriskelement'], 'position' => $this->numero . 10, 'list' => 0, 'enabled' => "isModEnabled('digiriskdolibarr')"], + 'entity' => ['Label' => 'Entity', 'type' => 'int', 'length' => 100, 'elementtype' => ['digiriskdolibarr_digiriskelement'], 'position' => $this->numero . 20, 'list' => 0, 'enabled' => "isModEnabled('digiriskdolibarr')"], - if ($conf->global->CATEGORIE_RECURSIV_ADD == 0) { - dolibarr_set_const($this->db, 'CATEGORIE_RECURSIV_ADD', 1, 'integer', 0, '', $conf->entity); - } + 'professional_qualification' => ['Label' => 'ProfessionalQualification', 'type' => 'varchar', 'length' => 255, 'elementtype' => ['user'], 'position' => $this->numero . 10, 'enabled' => "isModEnabled('digiriskdolibarr') && isModEnabled('user')"], + 'contract_type' => ['Label' => 'ContractType', 'type' => 'select', 'elementtype' => ['user'], 'position' => $this->numero . 20, 'params' => [1 => 'CDI', 2 => 'CDD', 3 => 'Apprentice/Student', 4 => 'Interim', 5 => 'Other'], 'enabled' => "isModEnabled('digiriskdolibarr') && isModEnabled('user')"] + ]; + + if (getDolGlobalInt('DIGIRISKDOLIBARR_EXTRAFIELDS_BACKWARD_COMPATIBILITY') == 0) { + if (isModEnabled('multicompany')) { + require_once __DIR__ . '/../../../multicompany/class/actions_multicompany.class.php'; + + $currentEntity = $conf->entity; + $actionsMulticompany = new ActionsMulticompany($this->db); + $entities = $actionsMulticompany->getEntitiesList(false, false, true, true); + foreach ($entities as $subEntity => $entity_name) { + $conf->setEntityValues($this->db, $subEntity); + foreach ($extraFieldsArrays as $key => $extraField) { + foreach ($extraField['elementtype'] as $extraFieldElementType) { + $extraFields->delete($key, $extraFieldElementType); + } + } + $conf->setEntityValues($this->db, $currentEntity); + } + } else { + foreach ($extraFieldsArrays as $key => $extraField) { + foreach ($extraField['elementtype'] as $extraFieldElementType) { + $extraFields->delete($key, $extraFieldElementType); + } + } + } + + dolibarr_set_const($this->db, 'DIGIRISKDOLIBARR_EXTRAFIELDS_BACKWARD_COMPATIBILITY', 1, 'integer', 0, '', $conf->entity); + } + + saturne_manage_extrafields($extraFieldsArrays, $commonExtraFieldsValue); //DigiriskElement favorite medias backward compatibility if ($conf->global->DIGIRISKDOLIBARR_DIGIRISKELEMENT_MEDIAS_BACKWARD_COMPATIBILITY == 0) { diff --git a/core/tpl/riskanalysis/risk/digiriskdolibarr_inheritedrisklist_view.tpl.php b/core/tpl/riskanalysis/risk/digiriskdolibarr_inheritedrisklist_view.tpl.php index a4dc6c16d..92527c277 100644 --- a/core/tpl/riskanalysis/risk/digiriskdolibarr_inheritedrisklist_view.tpl.php +++ b/core/tpl/riskanalysis/risk/digiriskdolibarr_inheritedrisklist_view.tpl.php @@ -328,26 +328,6 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); - $menuConf = 'MAIN_SELECTEDFIELDS_' . $varpage; - - if (dol_strlen($user->conf->$menuConf) < 1 || preg_match('/t./', $user->conf->$menuConf)) { - $user->conf->$menuConf = 'r.fk_element,r.ref,r.category,evaluation.cotation,'; - } - - if ( ! preg_match('/r.description/', $user->conf->$menuConf) && $conf->global->DIGIRISKDOLIBARR_RISK_DESCRIPTION) { - $user->conf->$menuConf = $user->conf->$menuConf . 'r.description,'; - } elseif ( ! $conf->global->DIGIRISKDOLIBARR_RISK_DESCRIPTION) { - $user->conf->$menuConf = preg_replace('/r.description,/', '', $user->conf->$menuConf); - $arrayfields['r.description']['enabled'] = 0; - } - - if ( ! preg_match('/evaluation.has_tasks/', $user->conf->$menuConf) && $conf->global->DIGIRISKDOLIBARR_TASK_MANAGEMENT) { - $user->conf->$menuConf .= $user->conf->$menuConf . 'evaluation.has_tasks,'; - } elseif ( ! $conf->global->DIGIRISKDOLIBARR_TASK_MANAGEMENT) { - $user->conf->$menuConf = preg_replace('/evaluation.has_tasks,/', '', $user->conf->$menuConf); - $arrayfields['evaluation.has_tasks']['enabled'] = 0; - } - $selectedfields = $form->multiSelectArrayWithCheckbox('inherited_risklist_selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); diff --git a/core/tpl/riskanalysis/risk/digiriskdolibarr_risk_actions.tpl.php b/core/tpl/riskanalysis/risk/digiriskdolibarr_risk_actions.tpl.php index 99d1e91df..fb75ee434 100644 --- a/core/tpl/riskanalysis/risk/digiriskdolibarr_risk_actions.tpl.php +++ b/core/tpl/riskanalysis/risk/digiriskdolibarr_risk_actions.tpl.php @@ -92,12 +92,8 @@ if ($result2 > 0) { $tasktitle = $data['task']; - $dateStart = $data['dateStart']; - $hourStart = $data['hourStart']; - $minStart = $data['minStart']; - $dateEnd = $data['dateEnd']; - $hourEnd = $data['hourEnd']; - $minEnd = $data['minEnd']; + $dateStart = dol_stringtotime($data['dateStart']); + $dateEnd = dol_stringtotime($data['dateEnd']); $budget = $data['budget']; if ( ! empty($tasktitle) && $tasktitle !== 'undefined') { $extrafields->fetch_name_optionals_label($task->table_element); @@ -107,16 +103,12 @@ $task->fk_project = $riskType == 'risk' ? $conf->global->DIGIRISKDOLIBARR_DU_PROJECT : $conf->global->DIGIRISKDOLIBARR_ENVIRONMENT_PROJECT; $task->date_c = dol_now(); if (!empty($dateStart)) { - $task->date_start = strtotime(preg_replace('/\//', '-', $dateStart)); - $task->date_start = dol_time_plus_duree($task->date_start, $hourStart, 'h'); - $task->date_start = dol_time_plus_duree($task->date_start, $minStart, 'i'); + $task->date_start = $dateStart; } else { $task->date_start = dol_now('tzuser'); } if (!empty($dateEnd)) { - $task->date_end = strtotime(preg_replace('/\//', '-', $dateEnd)); - $task->date_end = dol_time_plus_duree($task->date_end, $hourEnd, 'h'); - $task->date_end = dol_time_plus_duree($task->date_end, $minEnd, 'i'); + $task->date_end = $dateEnd; } $task->budget_amount = $budget; $task->array_options['options_fk_risk'] = $risk->id; @@ -355,18 +347,7 @@ } $entity = ($conf->entity > 1) ? '/' . $conf->entity : ''; - $result = $evaluation->update($user); - - if ($result > 0) { - // Update evaluation 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); - } else { - // Update evaluation KO - if ( ! empty($evaluation->errors)) setEventMessages(null, $evaluation->errors, 'errors'); - else setEventMessages($evaluation->error, null, 'errors'); - } + $evaluation->update($user); } if ( ! $error && $action == "deleteEvaluation" && $permissiontodelete) { @@ -400,12 +381,8 @@ $riskID = $data['riskToAssign']; $tasktitle = $data['tasktitle']; - $dateStart = $data['dateStart']; - $hourStart = $data['hourStart']; - $minStart = $data['minStart']; - $dateEnd = $data['dateEnd']; - $hourEnd = $data['hourEnd']; - $minEnd = $data['minEnd']; + $dateStart = dol_stringtotime($data['dateStart']); + $dateEnd = dol_stringtotime($data['dateEnd']); $budget = $data['budget']; $extrafields->fetch_name_optionals_label($task->table_element); @@ -415,16 +392,12 @@ $task->fk_project = $riskType == 'risk' ? $conf->global->DIGIRISKDOLIBARR_DU_PROJECT : $conf->global->DIGIRISKDOLIBARR_ENVIRONMENT_PROJECT; $task->datec = dol_now(); if (!empty($dateStart)) { - $task->date_start = strtotime(preg_replace('/\//', '-', $dateStart)); - $task->date_start = dol_time_plus_duree($task->date_start, $hourStart, 'h'); - $task->date_start = dol_time_plus_duree($task->date_start, $minStart, 'i'); + $task->date_start = $dateStart; } else { $task->date_start = dol_now('tzuser'); } if (!empty($dateEnd)) { - $task->date_end = strtotime(preg_replace('/\//', '-', $dateEnd)); - $task->date_end = dol_time_plus_duree($task->date_end, $hourEnd, 'h'); - $task->date_end = dol_time_plus_duree($task->date_end, $minEnd, 'i'); + $task->date_end = $dateEnd; } $task->budget_amount = $budget; $task->fk_task_parent = 0; @@ -451,12 +424,8 @@ $riskAssessmentTaskID = $data['riskAssessmentTaskID']; $tasktitle = $data['tasktitle']; - $dateStart = $data['dateStart']; - $hourStart = $data['hourStart']; - $minStart = $data['minStart']; - $dateEnd = $data['dateEnd']; - $hourEnd = $data['hourEnd']; - $minEnd = $data['minEnd']; + $dateStart = dol_stringtotime($data['dateStart']); + $dateEnd = dol_stringtotime($data['dateEnd']); $budget = $data['budget']; $taskProgress = $data['taskProgress']; @@ -465,18 +434,14 @@ $task->label = $tasktitle; if (!empty($dateStart)) { - $task->date_start = strtotime(preg_replace('/\//', '-', $dateStart)); - $task->date_start = dol_time_plus_duree($task->date_start, $hourStart, 'h'); - $task->date_start = dol_time_plus_duree($task->date_start, $minStart, 'i'); + $task->date_start = $dateStart; } else { $task->date_start = dol_now('tzuser'); } if (!empty($dateEnd)) { - $task->date_end = strtotime(preg_replace('/\//', '-', $dateEnd)); - $task->date_end = dol_time_plus_duree($task->date_end, $hourEnd, 'h'); - $task->date_end = dol_time_plus_duree($task->date_end, $minEnd, 'i'); + $task->date_end = $dateEnd; } - $task->budget_amount = is_int($budget) ? $budget : ($task->budget ?? 0); + $task->budget_amount = is_numeric($budget) ? $budget : ($task->budget ?? 0); if ($taskProgress == 1) { $task->progress = 100; diff --git a/core/tpl/riskanalysis/risk/digiriskdolibarr_risklist_view.tpl.php b/core/tpl/riskanalysis/risk/digiriskdolibarr_risklist_view.tpl.php index 11a22b516..da138fc58 100644 --- a/core/tpl/riskanalysis/risk/digiriskdolibarr_risklist_view.tpl.php +++ b/core/tpl/riskanalysis/risk/digiriskdolibarr_risklist_view.tpl.php @@ -459,9 +459,10 @@ $sql .= " FROM " . MAIN_DB_PREFIX . $evaluation->table_element . " as evaluation"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $risk->table_element . " as r on (evaluation.fk_risk = r.rowid)"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $digiriskelement->table_element . " as e on (r.fk_element = e.rowid)"; - if (is_array($extrafields->attributes[$evaluation->table_element]['label']) && count($extrafields->attributes[$evaluation->table_element]['label'])) $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $evaluation->table_element . "_extrafields as ef on (evaluation.rowid = ef.fk_object)"; + if (isset($extrafields->attributes[$evaluation->table_element]) && + is_array($extrafields->attributes[$evaluation->table_element]['label']) && count($extrafields->attributes[$evaluation->table_element]['label'])) $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $evaluation->table_element . "_extrafields as ef on (evaluation.rowid = ef.fk_object)"; if ($sortfield == 'evaluation.has_tasks') $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'projet_task_extrafields as taskextrafields ON (taskextrafields.fk_risk = r.rowid)'; - if (!empty($conf->categorie->enabled) && getDolGlobalInt('DIGIRISKDOLIBARR_CATEGORY_ON_RISK') > 0) $sql .= Categorie::getFilterJoinQuery('risk', "r.rowid"); + if (!empty($conf->categorie->enabled) && getDolGlobalInt('DIGIRISKDOLIBARR_CATEGORY_ON_RISK') > 0) $sql .= Categorie::getFilterJoinQuery('risk', "r.rowid"); if ($evaluation->ismultientitymanaged == 1) $sql .= " WHERE evaluation.entity IN (" . getEntity($evaluation->element) . ")"; else $sql .= " WHERE 1 = 1"; $sql .= " AND evaluation.status = 1"; @@ -593,441 +594,240 @@ } else { $newcardbutton = '
'; } ?> - - global->DIGIRISKDOLIBARR_TASK_MANAGEMENT == 0 && $conf->global->DIGIRISKDOLIBARR_RISK_DESCRIPTION == 0 && $conf->global->DIGIRISKDOLIBARR_MULTIPLE_RISKASSESSMENT_METHOD == 0 ) : ?> -
-
' . $form->editfieldkey('ResponsibleToNotify', 'Responsible_id', '', $object, 0) . ''; - print $form->selectarray('responsible_socid', $userlist, $usertmp->id, $langs->trans('SelectUser'), null, null, null, "40%", 0, 0, '', 'minwidth300', 1); + print img_picto('', 'user', 'class="pictofixedwidth"') . $form->selectarray('responsible_socid', $userlist, $usertmp->id, $langs->trans('SelectUser'), null, null, null, "40%", 0, 0, '', 'minwidth300', 1); print ' '; print '
'; + print '
'; + print img_picto('', 'object_phoning', 'class="pictofixedwidth"'); if ($usertmp->office_phone > 0) { print $usertmp->office_phone; } else { ?> diff --git a/admin/ticket/ticket.php b/admin/ticket/ticket.php index b848e8f2a..708947416 100644 --- a/admin/ticket/ticket.php +++ b/admin/ticket/ticket.php @@ -104,18 +104,22 @@ } if ($action == 'generateExtrafields') { - $ret1 = $extra_fields->addExtraField('digiriskdolibarr_ticket_lastname', $langs->transnoentities("LastName"), 'varchar', 2000, 255, 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - $ret2 = $extra_fields->addExtraField('digiriskdolibarr_ticket_firstname', $langs->transnoentities("FirstName"), 'varchar', 2100, 255, 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - $ret3 = $extra_fields->addExtraField('digiriskdolibarr_ticket_phone', $langs->transnoentities("Phone"), 'phone', 2200, '', 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - $ret4 = $extra_fields->addExtraField('digiriskdolibarr_ticket_service', $langs->transnoentities("Service"), 'sellist', 2300, '255', 'ticket', 0, 0, '', 'a:1:{s:7:"options";a:1:{s:61:"digiriskdolibarr_digiriskelement:ref:rowid::entity = $ENTITY$";N;}}', 1, '', 4, '','',0); - $ret5 = $extra_fields->addExtraField('digiriskdolibarr_ticket_location', $langs->transnoentities("Location"), 'varchar', 2400, 255, 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - $ret6 = $extra_fields->addExtraField('digiriskdolibarr_ticket_date', $langs->transnoentities("Date"), 'datetime', 2500, '', 'ticket', 0, 0, '', '', 1, '', 1, '', '', 0); - if ($ret1 > 0 && $ret2 > 0 && $ret3 > 0 && $ret4 > 0 && $ret5 > 0 && $ret6 > 0) { - setEventMessages($langs->transnoentities('ExtrafieldsCreated'), array()); - } else { - setEventMessages($extra_fields->error, array(), 'errors'); - } - dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', 1, 'integer', 0, '', 0); + $commonExtraFieldsValue = [ + 'alwayseditable' => 1, 'list' => 1, 'help' => '', 'entity' => 0, 'langfile' => 'digiriskdolibarr@digiriskdolibarr', 'enabled' => "isModEnabled('digiriskdolibarr') && isModEnabled('ticket')", 'moreparams' => ['css' => 'minwidth100 maxwidth300'] + ]; + + $extraFieldsArrays = [ + 'digiriskdolibarr_ticket_lastname' => ['Label' => 'LastName', 'type' => 'varchar', 'length' => 255, 'elementtype' => ['ticket'], 'position' => 43630210, ], + 'digiriskdolibarr_ticket_firstname' => ['Label' => 'FirstName', 'type' => 'varchar', 'length' => 255, 'elementtype' => ['ticket'], 'position' => 43630220, ], + 'digiriskdolibarr_ticket_phone' => ['Label' => 'Phone', 'type' => 'varchar', 'length' => 255, 'elementtype' => ['ticket'], 'position' => 43630230, ], + 'digiriskdolibarr_ticket_service' => ['Label' => 'GP/UT', 'type' => 'link', 'elementtype' => ['ticket'], 'position' => 43630240, 'params' => ['DigiriskElement:digiriskdolibarr/class/digiriskelement.class.php:1' => NULL], 'list' => 4], + 'digiriskdolibarr_ticket_location' => ['Label' => 'Location', 'type' => 'varchar', 'length' => 255, 'elementtype' => ['ticket'], 'position' => 43630250, ], + 'digiriskdolibarr_ticket_date' => ['Label' => 'DeclarationDate', 'type' => 'datetime', 'elementtype' => ['ticket'], 'position' => 43630260, ] + ]; + + saturne_manage_extrafields($extraFieldsArrays, $commonExtraFieldsValue); + setEventMessages($langs->transnoentities('ExtrafieldsCreated'), []); + dolibarr_set_const($db, 'DIGIRISKDOLIBARR_TICKET_EXTRAFIELDS', 1, 'integer', 0, '', 0); } if ($action == 'generateCategories') { @@ -370,6 +374,28 @@ print '
'; + print $langs->transnoentities('PublicInterfaceUseSignatoryDescription'); + print ''; + print ajax_constantonoff('DIGIRISKDOLIBARR_TICKET_PUBLIC_INTERFACE_USE_SIGNATORY'); + print ''; + print $form->textwithpicto('', $langs->transnoentities('TicketPublicInterfaceUseSignatoryDescription')); + print '
'; + print $langs->transnoentities('TicketPublicInterfaceShowCategoryDescription'); + print ''; + print ajax_constantonoff('DIGIRISKDOLIBARR_TICKET_PUBLIC_INTERFACE_SHOW_CATEGORY_DESCRIPTION'); + print ''; + print $form->textwithpicto('', $langs->transnoentities('TicketPublicInterfaceShowCategoryDescriptionHelp')); + print '
' . $langs->transnoentities("ShowSelectorOnTicketPublicInterface") . '
' . $langs->transnoentities("TicketDigiriskElementVisible") . '
' . $langs->transnoentities("TicketDigiriskelementVisible") . ''; print ajax_constantonoff('DIGIRISKDOLIBARR_TICKET_DIGIRISKELEMENT_VISIBLE'); print ''; - print $form->textwithpicto('', $langs->transnoentities("TicketDigiriskElementVisibleHelp")); + print $form->textwithpicto('', $langs->transnoentities("TicketDigiriskelementVisibleHelp")); print '
' . $langs->transnoentities("TicketFirstNameVisible") . '
' . $langs->transnoentities("TicketFirstnameVisible") . ''; print ajax_constantonoff('DIGIRISKDOLIBARR_TICKET_FIRSTNAME_VISIBLE'); print ''; - print $form->textwithpicto('', $langs->transnoentities("TicketFirstNameVisibleHelp")); + print $form->textwithpicto('', $langs->transnoentities("TicketFirstnameVisibleHelp")); print '
' . $langs->transnoentities("TicketLastNameVisible") . '
' . $langs->transnoentities("TicketLastnameVisible") . ''; print ajax_constantonoff('DIGIRISKDOLIBARR_TICKET_LASTNAME_VISIBLE'); print ''; - print $form->textwithpicto('', $langs->transnoentities("TicketLastNameVisibleHelp")); + print $form->textwithpicto('', $langs->transnoentities("TicketLastnameVisibleHelp")); print '
' . $picto . $langs->trans('Signature') . ''; + $out .= '
'; + $out .= ' '; + $out .= ''; + $out .= '
- - - - - -
- - - - + + +
+
+ +
+ +
+
-
- 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) : ?> +
+
+ trans('Task'); ?> + trans('Label'); ?> +
+
+ trans('DateStart'); ?> + '; ?> +
+
+ trans('Deadline'); ?> + '; ?> +
+
+ trans('Budget'); ?> + +
+ + + + + + + trans('DigiriskElement' . ucfirst($riskType) . 'sList'); print '
'; -print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $risk->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $risk->picto, 0, $newcardbutton ?? '', '', $limit, 0, 0, 1); $corruptedRisks = saturne_fetch_all_object_type('Risk', '', '', 0, 0, ['customsql' => 't.category NOT BETWEEN 0 AND ' . count($dangerCategories) . ' AND t.type = "' . $riskType . '"']); @@ -1066,26 +866,6 @@ class="risk-evaluation-cotation cotation">
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; -$menuConf = 'MAIN_SELECTEDFIELDS_' . $varpage; - -if (dol_strlen($user->conf->$menuConf) < 1 || preg_match('/t./', $user->conf->$menuConf)) { - $user->conf->$menuConf = ($contextpage == 'risklist' ? 'r.fk_element,' : '') . 'r.ref,r.category,evaluation.cotation,'; -} - -if ( ! preg_match('/r.description/', $user->conf->$menuConf) && $conf->global->DIGIRISKDOLIBARR_RISK_DESCRIPTION) { - $user->conf->$menuConf = $user->conf->$menuConf . 'r.description,'; -} elseif ( ! $conf->global->DIGIRISKDOLIBARR_RISK_DESCRIPTION) { - $user->conf->$menuConf = preg_replace('/r.description,/', '', $user->conf->$menuConf); - $arrayfields['r.description']['enabled'] = 0; -} - -if ( ! preg_match('/evaluation.has_tasks/', $user->conf->$menuConf) && $conf->global->DIGIRISKDOLIBARR_TASK_MANAGEMENT) { - $user->conf->$menuConf .= $user->conf->$menuConf . 'evaluation.has_tasks,'; -} elseif ( ! $conf->global->DIGIRISKDOLIBARR_TASK_MANAGEMENT) { - $user->conf->$menuConf = preg_replace('/evaluation.has_tasks,/', '', $user->conf->$menuConf); - $arrayfields['evaluation.has_tasks']['enabled'] = 0; -} - $selectedfields = $form->multiSelectArrayWithCheckbox('risklist_selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); @@ -1102,15 +882,15 @@ class="risk-evaluation-cotation cotation"> if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '') . 'center'; if ( ! empty($arrayfields['r.' . $key]['checked'])) { print ''; - if (is_array($val['arrayofkeyval'])) print $form->selectarray('search_' . $key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth75'); + if (isset($val['arrayofkeyval']) && 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) { print $risk->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } elseif ($key == 'fk_element') { - print $digiriskelement->selectDigiriskElementList($search['fk_element'], 'search_fk_element', ['customsql' => 'rowid NOT IN (' . implode(',', $deletedElements) . ')'], 1, 0, [], 0, 0, 'minwidth100 maxwidth300', 0, false, 1); + print $digiriskelement->selectDigiriskElementList($search['fk_element'] ?? '', 'search_fk_element', ['customsql' => 'rowid NOT IN (' . implode(',', $deletedElements) . ')'], 1, 0, [], 0, 0, 'minwidth100 maxwidth300', 0, false, 1); } elseif ($key == 'category') { ?> - '; + '; print ''; } } @@ -1195,7 +975,7 @@ class="risk-evaluation-cotation cotation"> // contenu $i = 0; -$totalarray = array(); +$totalarray = array('nbfield' => 0); while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); diff --git a/core/tpl/riskanalysis/risk/digiriskdolibarr_sharedrisklist_view.tpl.php b/core/tpl/riskanalysis/risk/digiriskdolibarr_sharedrisklist_view.tpl.php index e7925f20f..db5b01e3b 100644 --- a/core/tpl/riskanalysis/risk/digiriskdolibarr_sharedrisklist_view.tpl.php +++ b/core/tpl/riskanalysis/risk/digiriskdolibarr_sharedrisklist_view.tpl.php @@ -120,6 +120,7 @@ } $sql .= " AND el.sourcetype = 'digiriskdolibarr_risk'"; $sql .= ' AND r.type = "' . $riskType . '"'; + $sql .= ' AND e.rowid IN (' . implode(',', array_keys($alldigiriskelement)) . ')'; foreach ($search as $key => $val) { if ($key == 'status' && $search[$key] == -1) continue; @@ -211,7 +212,8 @@ $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $risk->table_element . " as r on (evaluation.fk_risk = r.rowid)"; $sql .= " INNER JOIN " . MAIN_DB_PREFIX . 'element_element' . " as el on (r.rowid = el.fk_source)"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $digiriskelement->table_element . " as e on (r.fk_element = e.rowid)"; - if (is_array($extrafields->attributes[$evaluation->table_element]['label']) && count($extrafields->attributes[$evaluation->table_element]['label'])) $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $evaluation->table_element . "_extrafields as ef on (evaluation.rowid = ef.fk_object)"; + if (isset($extrafields->attributes[$evaluation->table_element]) && + is_array($extrafields->attributes[$evaluation->table_element]['label']) && count($extrafields->attributes[$evaluation->table_element]['label'])) $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $evaluation->table_element . "_extrafields as ef on (evaluation.rowid = ef.fk_object)"; //if ($evaluation->ismultientitymanaged == 1) $sql .= " WHERE evaluation.entity IN (" . getEntity($evaluation->element) . ")"; else $sql .= " WHERE 1 = 1"; $sql .= " AND evaluation.status = 1"; @@ -234,6 +236,7 @@ } $sql .= " AND el.sourcetype = 'digiriskdolibarr_risk'"; $sql .= ' AND r.type = "' . $riskType . '"'; + $sql .= ' AND e.rowid IN (' . implode(',', array_keys($alldigiriskelement)) . ')'; foreach ($search as $key => $val) { if ($key == 'status' && $search[$key] == -1) continue; @@ -368,26 +371,6 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); -$menuConf = 'MAIN_SELECTEDFIELDS_' . $varpage; - -if (dol_strlen($user->conf->$menuConf) < 1 || preg_match('/t./', $user->conf->$menuConf)) { - $user->conf->$menuConf = 'r.entity,r.fk_element,r.applied_on,r.ref,r.category,evaluation.cotation,'; -} - -if ( ! preg_match('/r.description/', $user->conf->$menuConf) && $conf->global->DIGIRISKDOLIBARR_RISK_DESCRIPTION) { - $user->conf->$menuConf = $user->conf->$menuConf . 'r.description,'; -} elseif ( ! $conf->global->DIGIRISKDOLIBARR_RISK_DESCRIPTION) { - $user->conf->$menuConf = preg_replace('/r.description,/', '', $user->conf->$menuConf); - $arrayfields['r.description']['enabled'] = 0; -} - -if ( ! preg_match('/evaluation.has_tasks/', $user->conf->$menuConf) && $conf->global->DIGIRISKDOLIBARR_TASK_MANAGEMENT) { - $user->conf->$menuConf .= $user->conf->$menuConf . 'evaluation.has_tasks,'; -} elseif ( ! $conf->global->DIGIRISKDOLIBARR_TASK_MANAGEMENT) { - $user->conf->$menuConf = preg_replace('/evaluation.has_tasks,/', '', $user->conf->$menuConf); - $arrayfields['evaluation.has_tasks']['enabled'] = 0; -} - $selectedfields = $form->multiSelectArrayWithCheckbox('shared_risklist_selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); @@ -408,19 +391,19 @@ if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '') . 'center'; if ( ! empty($arrayfields['r.' . $key]['checked'])) { print ''; - 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 (isset($val['arrayofkeyval']) && 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) { print $risk->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); } elseif ($key == 'entity') { - print select_entity_list($search['entity'], 'search_entity', 'e.rowid NOT IN (' . $conf->entity . ')'); + print select_entity_list($search['entity'] ?? '', 'search_entity', 'e.rowid NOT IN (' . $conf->entity . ')'); } elseif ($key == 'fk_element') { - print $digiriskelement->selectDigiriskElementList($search['fk_element'], 'search_fk_element_sharedrisk', ['customsql' => 'entity NOT IN (' . $conf->entity . ') AND rowid NOT IN (' . implode(',', $deletedElements) . ')'], 1, 0, array(), 0, 0, 'minwidth100 maxwidth300', 0, false, 1, $contextpage, false); + print $digiriskelement->selectDigiriskElementList($search['fk_element'] ?? '', 'search_fk_element_sharedrisk', ['customsql' => 'entity NOT IN (' . $conf->entity . ') AND rowid NOT IN (' . implode(',', $deletedElements) . ')'], 1, 0, array(), 0, 0, 'minwidth100 maxwidth300', 0, false, 1, $contextpage, false); } elseif ($key == 'applied_on') { // print $digiriskelement->select_digiriskelement_list($search['search_applied_on_sharedrisk'], 'search_applied_on_sharedrisk', '', 1, 0, array(), 0, 0, 'minwidth100', 0, false, 1, $contextpage); } elseif ($key == 'category') { ?> -
-
-
-
-
- trans('NoRiskAssessment'); ?> -
-
- - - - -
- -
- - -
-
-
method = $lastRiskAssessment->method ?: "standard" ; ?> @@ -335,10 +313,10 @@ class="risk-evaluation-cotation cotation">
-
@@ -379,7 +357,7 @@ class="risk-evaluation-cotation cotation">
- + - + @@ -121,18 +109,6 @@
0 ? $langs->trans('NoTaskLinked') : $langs->trans('NoTaskShared'); ?> - - - - -
- -
- -
@@ -148,18 +124,6 @@
trans('NoTaskLinked'); ?> - - - - -
- -
- -
@@ -194,11 +158,11 @@
trans('DateStart'); ?> - selectDate(dol_now('tzuser'), 'RiskassessmentTaskDateStart' . $risk->id, 1, 1, 0, '', 1, 1); ?> + id . '" name="RiskassessmentTaskDateStart' . $risk->id . '">'; ?>
trans('Deadline'); ?> - selectDate(-1,'RiskassessmentTaskDateEnd'. $risk->id, 1, 1, 0, '', 1, 1); ?> + id . '" name="RiskassessmentTaskDateEnd' . $risk->id . '">'; ?>
trans('Budget'); ?> @@ -323,9 +287,19 @@ - 0) : ?> - - id]; ?> + 0) : + foreach ($related_tasks as $related_task) : + if ($conf->global->DIGIRISKDOLIBARR_SHOW_TASK_CALCULATED_PROGRESS) { + $tmparray = $related_task->getSummaryOfTimeSpent(); + if ($tmparray['total_duration'] > 0 && !empty($related_task->planned_workload)) { + $task_progress = round($tmparray['total_duration'] / $related_task->planned_workload * 100, 2); + } else { + $task_progress = 0; + } + } else { + $task_progress = $related_task->progress; + } + $allTimeSpentArray = $timeSpentSortedByTasks[$related_task->id] ?? []; ?>