From ec324f7b3de45c32f10d2999fc68229418b4c46d Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Wed, 18 Mar 2020 18:39:12 +0100
Subject: [PATCH] FEAT #12214 TIME 1:30 export department from senders

---
 apps/maarch_entreprise/department_list.php    | 104 ------
 apps/maarch_entreprise/export.php             |   4 +-
 apps/maarch_entreprise/getDepartment.php      |  33 --
 .../indexing_searching/search_adv.php         |   4 +-
 apps/maarch_entreprise/xml/export.xml         | 117 -------
 core/class/ExportControler.php                | 317 +-----------------
 modules/life_cycle/batch/extract_data.php     |   2 +-
 modules/life_cycle/batch/extract_data_2.php   |   2 +-
 .../life_cycle/batch/load_extract_data.php    |   4 -
 .../life_cycle/batch/load_extract_data_2.php  |   4 -
 .../controllers/DepartmentController.php      |   2 +-
 .../resource/controllers/ExportController.php |  81 ++++-
 12 files changed, 75 insertions(+), 599 deletions(-)
 delete mode 100755 apps/maarch_entreprise/department_list.php
 delete mode 100755 apps/maarch_entreprise/getDepartment.php
 delete mode 100755 apps/maarch_entreprise/xml/export.xml

diff --git a/apps/maarch_entreprise/department_list.php b/apps/maarch_entreprise/department_list.php
deleted file mode 100755
index bddc6a1de9f..00000000000
--- a/apps/maarch_entreprise/department_list.php
+++ /dev/null
@@ -1,104 +0,0 @@
-<?php
-
-$depts = array();
-$depts["01"] = "Ain";
-$depts["02"] = "Aisne";
-$depts["03"] = "Allier";
-$depts["04"] = "Alpes de Haute Provence";
-$depts["05"] = "Hautes Alpes";
-$depts["06"] = "Alpes Maritimes";
-$depts["07"] = "Ardèche";
-$depts["08"] = "Ardennes";
-$depts["09"] = "Ariège";
-$depts["10"] = "Aube";
-$depts["11"] = "Aude";
-$depts["12"] = "Aveyron";
-$depts["13"] = "Bouches du Rhône";
-$depts["14"] = "Calvados";
-$depts["15"] = "Cantal";
-$depts["16"] = "Charente";
-$depts["17"] = "Charente Maritime";
-$depts["18"] = "Cher";
-$depts["19"] = "Corrèze";
-$depts["2A"] = "Corse du Sud";
-$depts["2B"] = "Haute Corse";
-$depts["21"] = "Côte d'Or";
-$depts["22"] = "Côtes d'Armor";
-$depts["23"] = "Creuse";
-$depts["24"] = "Dordogne";
-$depts["25"] = "Doubs";
-$depts["26"] = "Drôme";
-$depts["27"] = "Eure";
-$depts["28"] = "Eure et Loir";
-$depts["29"] = "Finistère";
-$depts["30"] = "Gard";
-$depts["31"] = "Haute Garonne";
-$depts["32"] = "Gers";
-$depts["33"] = "Gironde";
-$depts["34"] = "Hérault";
-$depts["35"] = "Ille et Vilaine";
-$depts["36"] = "Indre";
-$depts["37"] = "Indre et Loire";
-$depts["38"] = "Isère";
-$depts["39"] = "Jura";
-$depts["40"] = "Landes";
-$depts["41"] = "Loir et Cher";
-$depts["42"] = "Loire";
-$depts["43"] = "Haute Loire";
-$depts["44"] = "Loire Atlantique";
-$depts["45"] = "Loiret";
-$depts["46"] = "Lot";
-$depts["47"] = "Lot et Garonne";
-$depts["48"] = "Lozère";
-$depts["49"] = "Maine et Loire";
-$depts["50"] = "Manche";
-$depts["51"] = "Marne";
-$depts["52"] = "Haute Marne";
-$depts["53"] = "Mayenne";
-$depts["54"] = "Meurthe et Moselle";
-$depts["55"] = "Meuse";
-$depts["56"] = "Morbihan";
-$depts["57"] = "Moselle";
-$depts["58"] = "Nièvre";
-$depts["59"] = "Nord";
-$depts["60"] = "Oise";
-$depts["61"] = "Orne";
-$depts["62"] = "Pas de Calais";
-$depts["63"] = "Puy de Dôme";
-$depts["64"] = "Pyrénées Atlantiques";
-$depts["65"] = "Hautes Pyrénées";
-$depts["66"] = "Pyrénées Orientales";
-$depts["67"] = "Bas Rhin";
-$depts["68"] = "Haut Rhin";
-$depts["69"] = "Rhône";
-$depts["70"] = "Haute Saône";
-$depts["71"] = "Saône et Loire";
-$depts["72"] = "Sarthe";
-$depts["73"] = "Savoie";
-$depts["74"] = "Haute Savoie";
-$depts["75"] = "Paris";
-$depts["76"] = "Seine Maritime";
-$depts["77"] = "Seine et Marne";
-$depts["78"] = "Yvelines";
-$depts["79"] = "Deux Sèvres";
-$depts["80"] = "Somme";
-$depts["81"] = "Tarn";
-$depts["82"] = "Tarn et Garonne";
-$depts["83"] = "Var";
-$depts["84"] = "Vaucluse";
-$depts["85"] = "Vendée";
-$depts["86"] = "Vienne";
-$depts["87"] = "Haute Vienne";
-$depts["88"] = "Vosges";
-$depts["89"] = "Yonne";
-$depts["90"] = "Territoire de Belfort";
-$depts["91"] = "Essonne";
-$depts["92"] = "Hauts de Seine";
-$depts["93"] = "Seine St Denis";
-$depts["94"] = "Val de Marne";
-$depts["95"] = "Val d'Oise";
-$depts["971"] = "Guadeloupe";
-$depts["972"] = "Martinique";
-$depts["973"] = "Guyane";
-$depts["974"] = "La Réunion";
-$depts["976"] = "Mayotte";
\ No newline at end of file
diff --git a/apps/maarch_entreprise/export.php b/apps/maarch_entreprise/export.php
index 56d3bf331e6..c48749c5c25 100755
--- a/apps/maarch_entreprise/export.php
+++ b/apps/maarch_entreprise/export.php
@@ -1,17 +1,15 @@
 <?php
-if($_REQUEST['origin'] != 'graph'){
+if ($_REQUEST['origin'] != 'graph') {
     require_once('core/class/ExportControler.php');
     $export = new ExportControler();
 }
 if (!empty($_SESSION['error'])) {
-    
     ?>
     <script language="javascript" >
         window.opener.location.reload();
         window.close();
     </script>
     <?php
-    
 } else {
     header('Pragma: public');
     header('Expires: 0');
diff --git a/apps/maarch_entreprise/getDepartment.php b/apps/maarch_entreprise/getDepartment.php
deleted file mode 100755
index 2437868a42e..00000000000
--- a/apps/maarch_entreprise/getDepartment.php
+++ /dev/null
@@ -1,33 +0,0 @@
-<?php
-
-require_once("core".DIRECTORY_SEPARATOR."class".DIRECTORY_SEPARATOR."class_request.php");
-require_once("apps".DIRECTORY_SEPARATOR."maarch_entreprise".DIRECTORY_SEPARATOR."department_list.php");
-
-$address_id = $_REQUEST['address_id'];
-
-if (is_numeric($address_id)) {
-	$db = new Database();
-
-	$stmt = $db->query("SELECT address_postal_code FROM contact_addresses WHERE id = ? AND (address_country ILIKE 'FRANCE' OR address_country = '' OR address_country IS NULL)", array($address_id));
-
-	$res = $stmt->fetchObject();
-
-	$department_id = substr($res->address_postal_code, 0, 2);
-
-	if ((int) $department_id >= 97 || $department_id == '20') {
-		$department_id = substr($res->address_postal_code, 0, 3);
-		if ((int)$department_id < 202) {
-			$department_id = "2A";
-		} else if ((int)$department_id >= 202 && (int)$department_id < 970) {
-			$department_id = "2B";
-		}
-	}
-	if ($depts[$department_id] <> "") {
-		$statusNB = 0;
-	} else {
-		$statusNB = 1;
-	}
-}
-
-echo '{ status: '.$statusNB.', departement_name: "'.$department_id.' - '.$depts[$department_id].'", departement_id: "'.$department_id.'"}';
-exit;
\ No newline at end of file
diff --git a/apps/maarch_entreprise/indexing_searching/search_adv.php b/apps/maarch_entreprise/indexing_searching/search_adv.php
index acdfef9c984..df05534df13 100755
--- a/apps/maarch_entreprise/indexing_searching/search_adv.php
+++ b/apps/maarch_entreprise/indexing_searching/search_adv.php
@@ -276,10 +276,8 @@ $arr_tmp2 = array('label' => _PROJECT, 'type' => 'input_text', 'param' => array(
 $param['folder'] = $arr_tmp2;
 
 // Department number
-include("apps/maarch_entreprise/department_list.php");
-
 $arr_tmp = array();
-foreach ($depts as $key => $value) {
+foreach (\Resource\controllers\DepartmentController::FRENCH_DEPARTMENTS as $key => $value) {
     array_push($arr_tmp, array('VALUE' => $key, 'LABEL' => $key . " - " . $value));
 }
 
diff --git a/apps/maarch_entreprise/xml/export.xml b/apps/maarch_entreprise/xml/export.xml
deleted file mode 100755
index d1b67bddd80..00000000000
--- a/apps/maarch_entreprise/xml/export.xml
+++ /dev/null
@@ -1,117 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ROOT>
-    <!-- 
-        options 
-    -->
-    <CSVOPTIONS>
-        <DELIMITER>;</DELIMITER> <!-- 1 charcater, default for MSExcel ';' && default other ',' -->
-        <ENCLOSURE>"</ENCLOSURE> <!-- 1 charcater, default for all '"' -->
-        <IS_UTF8>FALSE</IS_UTF8>
-    </CSVOPTIONS>
-    <!--
-        letterbox_coll
-    -->
-    <letterbox_coll>
-        <FIELD>
-            <LIBELLE>Num GED</LIBELLE>
-            <DATABASE_FIELD>res_view_letterbox.res_id</DATABASE_FIELD>
-        </FIELD>
-        <FIELD>
-            <LIBELLE>Date d'arrivée</LIBELLE>
-            <DATABASE_FIELD>doc_date</DATABASE_FIELD>
-        </FIELD>
-<!--        <FIELD>-->
-<!--            <LIBELLE>Prénom de l'expéditeur</LIBELLE>-->
-<!--            <DATABASE_FIELD>contact_firstname</DATABASE_FIELD>-->
-<!--        </FIELD>-->
-<!--        <FIELD>-->
-<!--            <LIBELLE>Nom de l'expéditeur</LIBELLE>-->
-<!--            <DATABASE_FIELD>contact_lastname</DATABASE_FIELD>-->
-<!--        </FIELD>-->
-<!--        <FIELD>-->
-<!--            <LIBELLE>Société de l'expéditeur</LIBELLE>-->
-<!--            <DATABASE_FIELD>contact_society</DATABASE_FIELD>-->
-<!--        </FIELD>-->
-        <FIELD>
-            <LIBELLE>Service destinataire</LIBELLE>
-            <DATABASE_FIELD>destination</DATABASE_FIELD>
-        </FIELD>        
-		<FIELD>
-            <LIBELLE>Destinataire</LIBELLE>
-            <DATABASE_FIELD>dest_user</DATABASE_FIELD>
-        </FIELD>
-        <FIELD>
-            <LIBELLE>Objet</LIBELLE>
-            <DATABASE_FIELD>subject</DATABASE_FIELD>
-        </FIELD>
-        <FIELD>
-            <LIBELLE>Type de courrier</LIBELLE>
-            <DATABASE_FIELD>type_label</DATABASE_FIELD>
-        </FIELD>
-        <FUNCTIONS>
-            <FUNCTION>
-                <LIBELLE>Statut</LIBELLE>
-                <CALL>get_status</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Priorité</LIBELLE>
-                <CALL>get_priority</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Services en copie</LIBELLE>
-                <CALL>retrieve_copies</CALL>
-            </FUNCTION>
-<!--            <FUNCTION>-->
-<!--                <LIBELLE>Page détail</LIBELLE>-->
-<!--                <CALL>makeLink_detail</CALL>-->
-<!--            </FUNCTION>-->
-
-<!--             <FUNCTION>
-                <LIBELLE>Thème</LIBELLE>
-                <CALL>get_parent_folder</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Catégorie</LIBELLE>
-                <CALL>get_category_label</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Service versant</LIBELLE>
-                <CALL>get_entity_initiator_short_label</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Service destinataire</LIBELLE>
-                <CALL>get_entity_dest_short_label</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Type de contact</LIBELLE>
-                <CALL>get_contact_type</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Civilité du contact</LIBELLE>
-                <CALL>get_contact_civility</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Fonction du contact</LIBELLE>
-                <CALL>get_contact_function</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Mots clés</LIBELLE>
-                <CALL>get_tags</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Signataire</LIBELLE>
-                <CALL>get_signatory_name</CALL>
-            </FUNCTION>
-            <FUNCTION>
-                <LIBELLE>Date de signature</LIBELLE>
-                <CALL>get_signatory_date</CALL>
-            </FUNCTION> -->
-        </FUNCTIONS>
-        <EMPTYS>
-            <EMPTY>
-                <LIBELLE>Commentaire</LIBELLE>
-                <COLNAME>comments</COLNAME> <!-- no spaces in the COLNAME -->
-            </EMPTY>
-        </EMPTYS>
-    </letterbox_coll>
-</ROOT>
diff --git a/core/class/ExportControler.php b/core/class/ExportControler.php
index ce8525ff79c..6513b20c2c1 100755
--- a/core/class/ExportControler.php
+++ b/core/class/ExportControler.php
@@ -13,60 +13,17 @@
 require_once 'core/class/class_functions.php';
 require_once 'core/class/class_history.php';
 
-class ExportControler extends ExportFunctions
+class ExportControler
 {
-    public $collection = false;
-    public $configuration = false;
-    public $delimiter = false;
-    public $enclosure = false;
-
-    public $object_export = false;
     public $array_export = [];
     public $pos = 0;
 
     public function __construct()
     {
-        $this->collection = $_SESSION['collection_id_choice'];
-        $this->load_configuration();
         $this->retrieve_datas();
         $_SESSION['export']['filename'] = $this->make_csv();
     }
 
-    // Private
-    private function load_configuration()
-    {
-        // Retrieve id to create paths (app & custom)
-        $id_app = $_SESSION['config']['app_id'];
-        $id_custom = false;
-        if (!empty($_SESSION['custom_override_id'])) {
-            $id_custom = $_SESSION['custom_override_id'];
-        }
-        $collection = $this->collection;
-
-        // Retrieve name for export configuration file
-        $fileName = 'export.xml';
-
-        // Make paths to xml dir
-        $pathToDir_app = 'apps/'.$id_app.'/xml/';
-        $pathToDir_custom = 'custom/'.$id_custom.'/'.$pathToDir_app;
-
-        $pathToFile_app = $pathToDir_app.$fileName;
-        $pathToFile_custom = $pathToDir_custom.$fileName;
-
-        // Load the configuration file
-        if ($id_custom && file_exists($pathToFile_custom)) {
-            $configuration = simplexml_load_file($pathToFile_custom);
-        } else {
-            $configuration = simplexml_load_file($pathToFile_app);
-        }
-
-        // Store interesting part of the configuration
-        $this->configuration = $configuration->{$collection};
-        $this->delimiter = end($configuration->CSVOPTIONS->DELIMITER);
-        $this->enclosure = end($configuration->CSVOPTIONS->ENCLOSURE);
-        $this->isUtf8 = end($configuration->CSVOPTIONS->IS_UTF8);
-    }
-
     private function retrieve_datas()
     {
         // Retrieve the query
@@ -95,53 +52,10 @@ class ExportControler extends ExportFunctions
 
         // Create template for the new query
         $query_template = 'SELECT ';
-        $query_template .= '##DATABASE_FIELDS## ';
+        $query_template .= 'res_id ';
         $query_template .= $endLastQuery;
 
-        // Retrieve ##DATABASE_FIELDS##
-        $fields = $this->configuration->FIELD;
-        $i_max = count($fields);
-        $database_fields = false;
-        for ($i = 0; $i < $i_max; ++$i) {
-            $field = $fields[$i];
-            $database_fields .= $field->DATABASE_FIELD;
-            if ($i != ($i_max - 1)) {
-                $database_fields .= ', ';
-            }
-        }
-
-        // Return query
-        return str_replace(
-                '##DATABASE_FIELDS##',
-                $database_fields,
-                $query_template
-            );
-    }
-
-    private function encode()
-    {
-        foreach ($this->object_export as $line_name => $line_value) {
-            foreach ($line_value as $column_name => $column_value) {
-                if ($this->retrieve_encoding($column_value) === false) {
-                    $column_value = utf8_encode($column_value);
-                }
-                if ($this->isUtf8 != 'TRUE') {
-                    $column_value = utf8_decode($column_value);
-                }
-                $column_value = $this->unprotect_string($column_value);
-                $this->object_export->{$line_name}->{$column_name} = $column_value;
-            }
-        }
-    }
-
-    private function retrieve_encoding($string)
-    {
-        return mb_detect_encoding($string, 'UTF-8', true);
-    }
-
-    private function unprotect_string($string)
-    {
-        return str_replace("\'", "'", $string);
+        return $query_template;
     }
 
     private function make_csv()
@@ -209,8 +123,6 @@ class ExportControler extends ExportFunctions
                     $select[] = 'res_view_letterbox.typist';
                 } elseif ($value['value'] == 'getAssignee') {
                     $select[] = 'res_view_letterbox.dest_user';
-                } elseif ($value['value'] == 'getDepartment') {
-                    $select[] = 'res_view_letterbox.department_number_id';
                 }
             } else {
                 $select[] = "res_view_letterbox.{$value['value']}";
@@ -247,226 +159,3 @@ class ExportControler extends ExportFunctions
         return $csvName;
     }
 }
-
-class ExportFunctions
-{
-    /* -------------------------------------------------------------------------
-    - Functions
-    -
-    - All the functions must have only one argument
-    - This argument is the name of the column for the header of the export
-    ------------------------------------------------------------------------- */
-    public function retrieve_copies($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $collection = $this->collection;
-
-        $query = 'SELECT item_id, ue.entity_id FROM listinstance l LEFT JOIN users_entities ue on l.item_id = ue.user_id WHERE l.res_id = ? AND l.item_mode = ?';
-        $stmt = $db->query($query, array($res_id, 'cc'));
-
-        $arr_copy = [];
-        while ($result = $stmt->fetchObject()) {
-            if (!empty($result->entity_id)) {
-                // USER COPY
-                $arr_copy[] = "{$result->item_id} : {$result->entity_id}";
-            } else {
-                // ENTITY COPY
-                $arr_copy[] = "{$result->item_id}";
-            }
-        }
-
-        $copyList = implode(' # ', $arr_copy);
-
-        $this->object_export->{$this->pos}->retrieve_copies = $copyList;
-    }
-
-    public function makeLink_detail($libelle, $res_id)
-    {
-        $link_template = $_SESSION['config']['businessappurl']."index.php?page=details&dir=indexing_searching&id={$res_id}";
-        $this->object_export->{$this->pos}->makeLink_detail = $link_template;
-    }
-
-    public function get_priority($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT priority FROM res_letterbox WHERE res_id = ?';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $label_priority = $_SESSION['mail_priorities'][$result->priority];
-
-        $this->object_export->{$this->pos}->get_priority = $label_priority;
-    }
-
-    public function get_status($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT label_status FROM res_letterbox r LEFT JOIN status s on r.status = s.id WHERE r.res_id = ?';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $this->object_export->{$this->pos}->get_status = $result->label_status;
-    }
-
-    function get_department($libelle)
-    {
-
-        $query_status = "SELECT department_number_id FROM res_view_letterbox WHERE res_id = ##res_id## ";
-
-        $db = new Database();
-
-        $i=0;
-        foreach($this->object_export as $line_name => $line_value) {
-            if ($i == 0) {
-                $line_value->get_department = $libelle;
-                $i++;
-                continue;
-            }
-
-            $res_id = $line_value->res_id;
-            $query = str_replace('##res_id##', '?', $query_status);
-            $stmt = $db->query($query, array($res_id));
-
-            $result = $stmt->fetchObject();
-
-            $deptName = "";
-
-            require_once("apps".DIRECTORY_SEPARATOR."maarch_entreprise".DIRECTORY_SEPARATOR."department_list.php");
-            if ($result->department_number_id <> '') {
-                $deptName = $result->department_number_id . ' - ' . $depts[$result->department_number_id];
-            }
-
-            $line_value->get_department = $deptName;
-        }
-    }
-
-    public function get_tags($libelle, $res_id)
-    {
-        $db = new Database();
-        $collection = $this->collection;
-
-        $query = 'SELECT t.tag_label FROM tags t LEFT JOIN resources_tags tr ON t.tag_id = tr.tag_id WHERE t.coll_id = ? AND tr.res_id = ?';
-        $stmt = $db->query($query, array($collection, $res_id));
-
-        $arr_tags = [];
-        while ($result = $stmt->fetchObject()) {
-            $arr_tags[] = $result->tag_label;
-        }
-
-        $this->object_export->{$this->pos}->get_tags = implode(' ## ', $arr_tags);
-    }
-
-    public function get_contact_type($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT ct.label from contacts_v2 cont LEFT JOIN res_letterbox rlb ON (rlb.exp_contact_id = cont.contact_id OR rlb.dest_contact_id = cont.contact_id) LEFT JOIN contact_types ct ON ct.id = cont.contact_type WHERE rlb.res_id = ?';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $this->object_export->{$this->pos}->get_contact_type = $result->label;
-    }
-
-    public function get_contact_civility($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT cont.title from contacts_v2 cont LEFT JOIN res_letterbox rlb ON (rlb.exp_contact_id = cont.contact_id OR rlb.dest_contact_id = cont.contact_id) WHERE rlb.res_id = ?';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $this->object_export->{$this->pos}->get_contact_civility = $_SESSION['mail_titles'][$result->title];
-    }
-
-    public function get_contact_function($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT c.function FROM res_letterbox r LEFT JOIN contacts_v2 c ON c.contact_id = r.dest_contact_id WHERE r.res_id = ?';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $this->object_export->{$this->pos}->get_contact_function = $result->function;
-    }
-
-    public function get_entity_initiator_short_label($libelle)
-    {
-        require_once 'modules/entities/class/class_manage_entities.php';
-        $db = new Database();
-        $entities = new entity();
-
-        $query = 'SELECT initiator FROM res_letterbox r WHERE r.res_id = ?';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $this->object_export->{$this->pos}->get_entity_initiator_short_label = $entities->getentityshortlabel($result->initiator);
-    }
-
-    public function get_entity_dest_short_label($libelle, $res_id)
-    {
-        require_once 'modules/entities/class/class_manage_entities.php';
-        $db = new Database();
-        $entities = new entity();
-
-        $query = 'SELECT destination FROM res_letterbox r WHERE r.res_id = ?';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $this->object_export->{$this->pos}->get_entity_dest_short_label = $entities->getentityshortlabel($result->destination);
-    }
-
-    public function get_signatory_name($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT DISTINCT u.lastname, u.firstname FROM res_attachments r LEFT JOIN users u ON u.user_id = r.typist WHERE r.attachment_type = ? AND r.status = ? AND r.res_id_master = ?';
-        $stmt = $db->query($query, array('signed_response', 'TRA', $res_id));
-
-        $arr_signatory = [];
-        while ($result = $stmt->fetchObject()) {
-            $arr_signatory[] = strtoupper($result->lastname).' '.ucfirst($result->firstname);
-        }
-
-        $this->object_export->{$this->pos}->get_signatory_name = implode(', ', $arr_signatory);
-    }
-
-    public function get_signatory_date($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT creation_date FROM res_attachments r WHERE r.attachment_type = ? and r.status = ? and r.res_id_master = ?';
-        $stmt = $db->query($query, array('signed_response', 'TRA', $res_id));
-
-        $arr_signatoryDate = [];
-        while ($result = $stmt->fetchObject()) {
-            $arr_signatoryDate[] = functions::format_date_db($result->creation_date);
-        }
-
-        $this->object_export->{$this->pos}->get_signatory_date = implode(', ', $arr_signatoryDate);
-    }
-
-    public function get_parent_folder($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT folder_name FROM folders WHERE folders_system_id in ( SELECT f.parent_id FROM res_letterbox r LEFT JOIN folders f ON r.folders_system_id = f.folders_system_id WHERE r.res_id = ?)';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $this->object_export->{$this->pos}->get_parent_folder = $result->folder_name;
-    }
-
-    public function get_category_label($libelle, $res_id)
-    {
-        $db = new Database();
-
-        $query = 'SELECT category_id FROM res_letterbox WHERE res_id = ?';
-        $stmt = $db->query($query, array($res_id));
-        $result = $stmt->fetchObject();
-
-        $this->object_export->{$this->pos}->get_category_label = $_SESSION['coll_categories']['letterbox_coll'][$result->category_id];
-    }
-}
diff --git a/modules/life_cycle/batch/extract_data.php b/modules/life_cycle/batch/extract_data.php
index 544cb4d16a1..0c497768166 100755
--- a/modules/life_cycle/batch/extract_data.php
+++ b/modules/life_cycle/batch/extract_data.php
@@ -200,7 +200,7 @@ try {
         #### Department Full Name ####
         $department_name = "";
         if($selectedFile->department_number_id <> ""){
-            $department_name = $selectedFile->department_number_id . " - " .$depts[$selectedFile->department_number_id];
+            $department_name = $selectedFile->department_number_id . " - " .\Resource\controllers\DepartmentController::FRENCH_DEPARTMENTS[$selectedFile->department_number_id];
         }
 
         #### Info contacts ####
diff --git a/modules/life_cycle/batch/extract_data_2.php b/modules/life_cycle/batch/extract_data_2.php
index fb9058a8d9a..4b0657ca0d8 100755
--- a/modules/life_cycle/batch/extract_data_2.php
+++ b/modules/life_cycle/batch/extract_data_2.php
@@ -193,7 +193,7 @@ try {
         #### Department Full Name ####
         $department_name = "";
         if($selectedFile->department_number_id <> ""){
-            $department_name = $selectedFile->department_number_id . " - " .$depts[$selectedFile->department_number_id];
+            $department_name = $selectedFile->department_number_id . " - " .\Resource\controllers\DepartmentController::FRENCH_DEPARTMENTS[$selectedFile->department_number_id];
         }
 
         #### Info contacts ####
diff --git a/modules/life_cycle/batch/load_extract_data.php b/modules/life_cycle/batch/load_extract_data.php
index 68ab89c56ee..d71b3a7ba89 100755
--- a/modules/life_cycle/batch/load_extract_data.php
+++ b/modules/life_cycle/batch/load_extract_data.php
@@ -271,10 +271,6 @@ try {
         $xml_entreprise = simplexml_load_file($GLOBALS['MaarchDirectory'] . 'apps' . DIRECTORY_SEPARATOR . 'maarch_entreprise' . DIRECTORY_SEPARATOR . 'xml' . DIRECTORY_SEPARATOR . 'entreprise.xml');
     }
 
-    if (file_exists($GLOBALS['MaarchDirectory'] . 'custom' . DIRECTORY_SEPARATOR . $GLOBALS['CustomId'] . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . 'maarch_entreprise' . DIRECTORY_SEPARATOR . 'department_list.php')) {
-        include($GLOBALS['MaarchDirectory'] . 'custom' . DIRECTORY_SEPARATOR . $GLOBALS['CustomId'] . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . 'maarch_entreprise' . DIRECTORY_SEPARATOR . 'department_list.php');
-    }
-
 } catch (IncludeFileError $e) {
     $GLOBALS['logger']->write(
         'Problem with the php include path:' 
diff --git a/modules/life_cycle/batch/load_extract_data_2.php b/modules/life_cycle/batch/load_extract_data_2.php
index 75d8c331050..6e2091cb924 100755
--- a/modules/life_cycle/batch/load_extract_data_2.php
+++ b/modules/life_cycle/batch/load_extract_data_2.php
@@ -280,10 +280,6 @@ try {
         $xml_entreprise = simplexml_load_file($GLOBALS['MaarchDirectory'] . 'apps' . DIRECTORY_SEPARATOR . 'maarch_entreprise' . DIRECTORY_SEPARATOR . 'xml' . DIRECTORY_SEPARATOR . 'entreprise.xml');
     }
 
-    if (file_exists($GLOBALS['MaarchDirectory'] . 'custom' . DIRECTORY_SEPARATOR . $GLOBALS['CustomId'] . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . 'maarch_entreprise' . DIRECTORY_SEPARATOR . 'department_list.php')) {
-        include($GLOBALS['MaarchDirectory'] . 'custom' . DIRECTORY_SEPARATOR . $GLOBALS['CustomId'] . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . 'maarch_entreprise' . DIRECTORY_SEPARATOR . 'department_list.php');
-    }
-
 } catch (IncludeFileError $e) {
     $GLOBALS['logger']->write(
         'Problem with the php include path:' 
diff --git a/src/app/resource/controllers/DepartmentController.php b/src/app/resource/controllers/DepartmentController.php
index b1f67f1fa57..e09c0d020a9 100644
--- a/src/app/resource/controllers/DepartmentController.php
+++ b/src/app/resource/controllers/DepartmentController.php
@@ -126,7 +126,7 @@ class DepartmentController
     public static function getById(array $aArgs)
     {
         ValidatorModel::notEmpty($aArgs, ['id']);
-        ValidatorModel::intVal($aArgs, ['id']);
+        ValidatorModel::stringType($aArgs, ['id']);
 
         if (empty(self::FRENCH_DEPARTMENTS[$aArgs['id']])) {
             return '';
diff --git a/src/app/resource/controllers/ExportController.php b/src/app/resource/controllers/ExportController.php
index 311dd609c68..b986617d2be 100644
--- a/src/app/resource/controllers/ExportController.php
+++ b/src/app/resource/controllers/ExportController.php
@@ -22,6 +22,7 @@ use Entity\models\EntityModel;
 use Entity\models\ListInstanceModel;
 use Folder\controllers\FolderController;
 use Folder\models\FolderModel;
+use Resource\controllers\DepartmentController;
 use Resource\models\ExportTemplateModel;
 use Resource\models\ResModel;
 use Resource\models\ResourceListModel;
@@ -30,10 +31,11 @@ use setasign\Fpdi\Tcpdf\Fpdi;
 use Slim\Http\Request;
 use Slim\Http\Response;
 use SrcCore\controllers\PreparedClauseController;
+use SrcCore\models\DatabaseModel;
 use SrcCore\models\TextFormatModel;
 use SrcCore\models\ValidatorModel;
-use Tag\models\TagModel;
 use Tag\models\ResourceTagModel;
+use Tag\models\TagModel;
 use User\models\UserModel;
 
 require_once 'core/class/Url.php';
@@ -162,8 +164,6 @@ class ExportController
                     $select[] = 'res_view_letterbox.typist';
                 } elseif ($value['value'] == 'getAssignee') {
                     $select[] = 'res_view_letterbox.dest_user';
-                } elseif ($value['value'] == 'getDepartment') {
-                    $select[] = 'res_view_letterbox.department_number_id';
                 }
             } else {
                 $select[] = "res_view_letterbox.{$value['value']}";
@@ -270,11 +270,8 @@ class ExportController
                         $signatureDates = ExportController::getSignatureDates(['chunkedResIds' => $aArgs['chunkedResIds']]);
                         $csvContent[] = empty($signatureDates[$resource['res_id']]) ? '' : $signatureDates[$resource['res_id']];
                     } elseif ($value['value'] == 'getDepartment') {
-                        if (!empty($resource['department_number_id'])) {
-                            $csvContent[] = $resource['department_number_id'] . ' - ' . DepartmentController::getById(['id' => $resource['department_number_id']]);
-                        } else {
-                            $csvContent[] = '';
-                        }
+                        $department   = ExportController::getDepartment(['chunkedResIds' => $aArgs['chunkedResIds']]);
+                        $csvContent[] = empty($department[$resource['res_id']]) ? '' : $department[$resource['res_id']];
                     } elseif (strpos($value['value'], 'custom_', 0) !== false) {
                         $csvContent[] = ExportController::getCustomFieldValue(['custom' => $value['value'], 'resId' => $resource['res_id']]);
                     }
@@ -380,13 +377,10 @@ class ExportController
                         $content[] = empty($signatories[$resource['res_id']]) ? '' : $signatories[$resource['res_id']];
                     } elseif ($value['value'] == 'getSignatureDates') {
                         $signatureDates = ExportController::getSignatureDates(['chunkedResIds' => $aArgs['chunkedResIds']]);
-                        $csvContent[] = empty($signatureDates[$resource['res_id']]) ? '' : $signatureDates[$resource['res_id']];
+                        $content[] = empty($signatureDates[$resource['res_id']]) ? '' : $signatureDates[$resource['res_id']];
                     } elseif ($value['value'] == 'getDepartment') {
-                        if (!empty($resource['department_number_id'])) {
-                            $content[] = $resource['department_number_id'] . ' - ' . DepartmentController::getById(['id' => $resource['department_number_id']]);
-                        } else {
-                            $content[] = '';
-                        }
+                        $department = ExportController::getDepartment(['chunkedResIds' => $aArgs['chunkedResIds']]);
+                        $content[]  = empty($department[$resource['res_id']]) ? '' : $department[$resource['res_id']];
                     } elseif (strpos($value['value'], 'custom_', 0) !== false) {
                         $content[] = ExportController::getCustomFieldValue(['custom' => $value['value'], 'resId' => $resource['res_id']]);
                     }
@@ -462,6 +456,65 @@ class ExportController
         return $aCopies;
     }
 
+    private static function getDepartment(array $args)
+    {
+        ValidatorModel::notEmpty($args, ['chunkedResIds']);
+        ValidatorModel::arrayType($args, ['chunkedResIds']);
+
+        static $aDepartment = [];
+        if (!empty($aDepartment)) {
+            return $aDepartment;
+        }
+
+        foreach ($args['chunkedResIds'] as $resIds) {
+            $contactsMatch = DatabaseModel::select([
+                'select'    => ['res_id', 'address_postcode'],
+                'table'     => ['resource_contacts', 'contacts'],
+                'left_join' => ['resource_contacts.item_id = contacts.id'],
+                'where'     => ["res_id in (?)", "type = 'contact'","mode = 'sender'", "(address_country ILIKE 'FRANCE' OR address_country = '' OR address_country IS NULL)"],
+                'data'      => [$resIds]
+            ]);
+
+            $resId = '';
+            $departmentName = '';
+            if (!empty($contactsMatch)) {
+                foreach ($contactsMatch as $key => $contact) {
+                    if (empty($contact['address_postcode'])) {
+                        continue;
+                    }
+                    if ($key != 0 && $resId == $contact['res_id']) {
+                        $departmentName .= "\n";
+                    } elseif ($key != 0 && $resId != $contact['res_id']) {
+                        $aDepartment[$resId] = $departmentName;
+                        $departmentName = '';
+                    } else {
+                        $departmentName = '';
+                    }
+                    $departmentId = substr($contact['address_postcode'], 0, 2);
+
+                    if ((int) $departmentId >= 97 || $departmentId == '20') {
+                        $departmentId = substr($contact['address_postcode'], 0, 3);
+                        if ((int)$departmentId < 202) {
+                            $departmentId = "2A";
+                        } elseif ((int)$departmentId >= 202 && (int)$departmentId < 970) {
+                            $departmentId = "2B";
+                        }
+                    }
+                    $departmentName .= $departmentId . ' - ' . DepartmentController::getById(['id' => $departmentId]);
+                    $resId = $contact['res_id'];
+                }
+                if (!empty($resId)) {
+                    $aDepartment[$resId] = $departmentName;
+                }
+            }
+        }
+
+        if (empty($aDepartment)) {
+            $aDepartment = ['empty'];
+        }
+        return $aDepartment;
+    }
+
     private static function getTags(array $args)
     {
         ValidatorModel::notEmpty($args, ['chunkedResIds']);
-- 
GitLab