From dcd619915e4505ad9a5e738845f98c2050767268 Mon Sep 17 00:00:00 2001
From: lvessiller <lvessiller@open-dsi.fr>
Date: Wed, 11 Aug 2021 08:47:38 +0200
Subject: [PATCH] NEW amelioration tache planifiee indexation

---
 lib/BackgroundJob/IndexationProcess.php |   9 +-
 lib/Db/DematpayslipProcess.php          | 176 +++++++++++++++---------
 2 files changed, 113 insertions(+), 72 deletions(-)

diff --git a/lib/BackgroundJob/IndexationProcess.php b/lib/BackgroundJob/IndexationProcess.php
index 8e84985..13a6c0b 100644
--- a/lib/BackgroundJob/IndexationProcess.php
+++ b/lib/BackgroundJob/IndexationProcess.php
@@ -18,7 +18,6 @@ use DateTime;
 use DateTimeZone;
 use Exception;
 
-use OCA\Dematpayslip\Db\DematpayslipArchive;
 use OCA\Dematpayslip\Db\DematpayslipArchiveMapper;
 use OCA\Dematpayslip\Db\DematpayslipProcessMapper;
 use OCA\Dematpayslip\Db\DematpayslipProcessSkipMapper;
@@ -222,8 +221,8 @@ class IndexationProcess extends TimedJob {
         $this->_timeZone = new DateTimeZone($timeZoneName);
 
         // run once by interval
-        $taskDefaultInterval = 60;
-        //$taskDefaultInterval = 3600; // 1h
+        //$taskDefaultInterval = 60;
+        $taskDefaultInterval = 3600; // 1h
         $taskInterval = intval($this->_config->getAppValue($this->_appName,$this->_appName . '_indexation_cron_interval', $taskDefaultInterval));
         //print __METHOD__ . ' : time_zone_name=' . $timeZoneName . ', cron_interval=' . $taskInterval . "\n";
         $this->setInterval($taskInterval);
@@ -278,12 +277,8 @@ class IndexationProcess extends TimedJob {
                 if (!empty($processList)) {
                     $process = current($processList);
                     if ($process->getPhase() == DematpayslipProcess::PHASE_ID_INDEXATION) {
-                        $this->_log('Indexation process : Load');
                         $process->load($this->_appName, $this->_config, $this->_dbConnection, $this->_l10n, $this->_rootFolder, $this->_shareManager, $this->_userManager, $userId, $this->_dematpayslipProcessMapper, $this->_dematpayslipProcessSkipMapper, $this->_dematpayslipUserMapper, $this->_timeZone);
-
-                        $this->_log('Indexation process : Indexation Begin');
                         $result = $process->indexation($processMsgList);
-                        $this->_log('Indexation process : Indexation End');
 
                         if ($result < 0) {
                             $this->_log('Indexation process : Error : ', self::LOG_ERROR);
diff --git a/lib/Db/DematpayslipProcess.php b/lib/Db/DematpayslipProcess.php
index e091379..d26c586 100644
--- a/lib/Db/DematpayslipProcess.php
+++ b/lib/Db/DematpayslipProcess.php
@@ -159,7 +159,6 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
     private $_exportDirFullPath;
     private $_tmpDirUserPath;
     private $_tmpDirFullPath;
-    private $_userDirFullPath;
 
     /**
      * @var string payslip no index dir
@@ -529,18 +528,16 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
             $this->_msgList['error'][] = $this->_l10n->t('L\'utilisateur "' . $this->_userId . '" n\'existe pas.');
         }
 
-        // mounter le dossier de l'utilisateur
-        if (count($this->_msgList['error'])<=0) {
+        // create application user directory
+        if (!$this->hasError()) {
             $userHomeAppFilesFullPath = $user->getHome() . DIRECTORY_SEPARATOR . 'files';
             $this->_checkDirFullPath  = $userHomeAppFilesFullPath . DIRECTORY_SEPARATOR . $this->_checkDirUserPath;
             $this->_reportDirFullPath = $userHomeAppFilesFullPath . DIRECTORY_SEPARATOR . $this->_reportDirUserPath;
             $this->_uploadDirFullPath = $userHomeAppFilesFullPath . DIRECTORY_SEPARATOR . $this->_uploadDirUserPath;
             $this->_exportDirFullPath = $userHomeAppFilesFullPath . DIRECTORY_SEPARATOR . $this->_exportDirUserPath;
             $this->_tmpDirFullPath    = $userHomeAppFilesFullPath . DIRECTORY_SEPARATOR . $this->_tmpDirUserPath;
-            $this->_userDirFullPath   = $userHomeAppFilesFullPath;
 
             // mount user directory
-            //Filesystem::initMountPoints($this->_userId);
             $userFolder = $this->_rootFolder->getUserFolder($this->_userId);
 
             // create payslip directory
@@ -574,7 +571,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                 }
             }
 
-            if (count($this->_msgList['error'])<=0) {
+            if (!$this->hasError()) {
                 // check directory
                 try {
                     $userFolder->get($this->_checkDirUserPath);
@@ -712,7 +709,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
             $this->_msgList['error'][] = $this->_l10n->t('Une opération "' . self::_getPhaseName($this->getPhase()) . '" a déjà été démarrée par l\'utilisateur "' . $this->getUserId() . '".');
         } else if ($this->getHasError()>0) {
             if ($this->getMustTerminate()==1) {
-                // last process terminate with errors and we have to determine action to unlock it
+                // last process terminate with errors, we have to determine action to unlock it
                 $this->_msgList['error'][] = $this->_l10n->t('L\'opération "' . self::_getPhaseName($this->getPhase()) . '" s\'est terminée avec les erreurs suivantes') . ' : ';
                 $this->_msgList['error'][] = $this->getErrorMsg();
             }
@@ -897,7 +894,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
 
         $configList['payslip_dir']  = $config->getAppValue($appName, 'payslip_dir', 'Bulletins');       // Bulletins
         $configList['user_id']      = $config->getAppValue($appName, 'user_id', 'demat');               // demat
-        $configList['app_data_dir'] = $config->getAppValue($appName, 'app_data_dir', 'dematpayslip');   // dematpayslip directory of user demat (upload, check, report, etc)
+        $configList['app_data_dir'] = $config->getAppValue($appName, 'app_data_dir', 'dematpayslip');   // dematpayslip directory of user demat (upload, check, report, ...)
         if (empty($configList['payslip_dir']) || empty($configList['user_id'])) {
             $msgList['error'][] = $l10n->t('Veuillez vérifier la configuration de cette application.');
         }
@@ -964,7 +961,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
         $this->_initDematUser();
 
         $this->_processCheck();
-        if (count($this->_msgList['error'])<=0) {
+        if (!$this->hasError()) {
             $dateTimeNow = new DateTime('now', $this->_timeZone);
 
             $this->setProcessing(1);
@@ -1101,7 +1098,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
             $this->_msgList['error'][] = $this->_l10n->t('Opération impossible : phase en cours "' . self::_getPhaseName($this->getPhase()) . '".');
         }
 
-        if (count($this->_msgList['error']) <= 0) {
+        if (!$this->hasError()) {
             $this->_processFailOnFirstError = false;
             $dateTimeNow = new DateTime('now', $this->_timeZone);
 
@@ -1128,8 +1125,18 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
             $uploadFileCSVName = $this->getCsvOrigin();
 
             // log file
-            $logFilePath = $this->_checkDirUserPath . DIRECTORY_SEPARATOR . $this->getPhase() . '_log';
-            $this->_logFile = Filesystem::fopen($logFilePath, 'w+');
+            $userFolder = $this->_rootFolder->getUserFolder($this->_userId);
+            $logFileName = $this->getPhase() . '_log';
+            $logFilePath = $this->_checkDirUserPath . DIRECTORY_SEPARATOR . $logFileName;
+            $logFileFullPath = $this->_checkDirFullPath . DIRECTORY_SEPARATOR . $this->getPhase() . '_log';
+            try {
+                //$userFolder->newFile($logFilePath);
+                $this->_logFile = fopen($logFileFullPath, 'w+');
+            } catch (Exception $e) {
+                $errorMsg = $this->_l10n->t('Impossible d\'ouvrir le fichier de log "' . $logFilePath . '".');
+                $this->_msgList['error'][] = $errorMsg;
+            }
+
             $this->_logCsvCols(array('date', 'heure', 'niveau', 'message', 'siret', 'matricule', 'nom_prenom', 'zip_city', 'date_debut', 'date_fin', 'email'));
             $this->_logCsvLine('## ' .$this->_l10n->t('Début du processus de vérification.') . ' ##', self::LOG_DEBUG);
 
@@ -1196,14 +1203,14 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                             $agentUser->setEmail($csvLine[5]);
                             $agentUser->setZipCity($csvLine[10]);
 
-                            // verifier l'existance de l'email et autres champs (regex)
+                            // check email field and others fields (regex)
                             $this->_logCsvLine($this->_l10n->t('Ligne CSV'), self::LOG_DEBUG, $agentUser, $startDate, $endDate);
                             if (empty($agentUser->getEmail())) {
                                 $warningMsg = $this->_l10n->t('Le fichier CSV "' . $uploadFileCSVName . '" contient un champ email vide [ligne=' . ($csvLineNum + 1) . '].');
                                 $this->_logCsvLine($warningMsg, self::LOG_WARNING, $agentUser, $startDate, $endDate);
                                 $this->_processWarningMsg($warningMsg);
 
-                                // sauter cette ligne dans la suite du process de verification et d'indexation
+                                // skip this line in check and indexation process
                                 //$dematpayslipProcessSkipLineArr = $this->_dematpayslipProcessSkipMapper->findAllByIdProcessAndIdLine($this->getId(), $csvLineNum);
                                 //if (empty($dematpayslipProcessSkipLineArr)) {
                                 //    $dematpayslipProcessSkip = new DematpayslipProcessSkip();
@@ -1297,22 +1304,22 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
 
                     $checkLastLineNum = -1;
 
-                    // pour chaque page du PDF
+                    // for each PDF page
                     $this->_logCsvLine($this->_l10n->t('Lecture des pages du fichier PDF.'), self::LOG_DEBUG);
                     $pdfPageList = array();
                     foreach ($pdfPages as $pdfPageNum => $pdfPage) {
                         $this->_logCsvLine('-- ' . $this->_l10n->t('Page PDF en cours : ' .  ($pdfPageNum + 1) . ' --'), self::LOG_DEBUG);
 
-                        // recuperer les champs textes dans le PDF et enlever les espaces
+                        // get text fields in PDF and remove blanks
                         $this->_logCsvLine($this->_l10n->t('Récupération des champs textes du fichier PDF.'), self::LOG_DEBUG);
                         $pdfPageTextList = array();
                         $pdfPageTextArr = $pdfPage->getTextArray();
                         foreach ($pdfPageTextArr as $pdfPageTextKey => $pdfPageText) {
-                            // formater les champs textes du PDF (enlever les espaces)
+                            // format text fields (remove blanks)
                             $pdfPageTextList[] = trim($pdfPageText);
                         }
 
-                        // pour chaque ligne du CSV restant a traiter
+                        // for each CSV line remaining to do
                         $this->_logCsvLine($this->_l10n->t('Lecture des lignes fichier CSV.'), self::LOG_DEBUG);
                         $csvTodoLineNum = 0;
                         $csvTodoLine = array();
@@ -1322,7 +1329,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                         foreach ($csvTodoLineList as $csvTodoLineNum => $csvTodoLine) {
                             $this->_logCsvLine('-- ' . $this->_l10n->t('Début de ligne CSV : ' .  ($csvTodoLineNum + 1)) . ' --', self::LOG_DEBUG);
 
-                            // recuperer les valeurs de controle
+                            // get check values
                             $checkCurrentValues = array(
                                 'siret'     => $csvTodoLine['siret'],
                                 'matricule' => $csvTodoLine['matricule'],
@@ -1332,9 +1339,9 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
 
                             $pdfPageValues = array();
 
-                            // pour chaque champ CSV a controler
+                            // for each value to check
                             foreach ($checkCurrentValues as $checkField => $checkCurrentValue) {
-                                // verifier d'abord aux emplacements previsibles du PDF
+                                // check first in forecast positions in PDF
                                 if ($checkField == 'siret') {
                                     // siret
                                     if (isset($this->_payslipPDFSearchFieldList[$checkField]) && !empty($this->_payslipPDFSearchFieldList[$checkField])) {
@@ -1361,10 +1368,10 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                                 }
 
                                 if (!isset($pdfPageValues[$checkField])) {
-                                    // si on a pas trouve aux emplacement previsibles du PDF
-                                    // pour chaque champ texte de la page du PDF
+                                    // not fount in forecast position in PDF
+                                    // for each field text in PDF page
                                     foreach ($pdfPageTextList as $pdfPageTextKey => $pdfPageText) {
-                                        // formater les champs textes du PDF (enlever les espaces)
+                                        // format text fields in PDF (remove blanks)
                                         $pdfPageTextValue = trim($pdfPageText);
 
                                         if ($checkField == 'siret') {
@@ -1386,7 +1393,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                                 }
                             }
 
-                            // verifie si on a trouve un agent correspondant a la ligne du fichier CSV en cours
+                            // check if we found a user agent that match CSV line in progress
                             $agentFound = false;
                             if (!empty($pdfPageValues)) {
                                 foreach ($checkCurrentValues as $checkField => $checkCurrentValue) {
@@ -1411,7 +1418,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                             $this->_processErrorMsg(-1, $errorMsg);
                             break;
                         } else {
-                            // si on a bien trouve l'agent correspondant a la page du PDF
+                            // if agent user found and match with PDF page
                             $siret = $csvTodoLine['siret'];
                             $matricule = $csvTodoLine['matricule'];
                             $period = $csvTodoLine['start_date'] . '_' . $csvTodoLine['end_date'];
@@ -1433,31 +1440,31 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                                 $pdfPageList[$agentKey] = array('page_num_list' => array($pdfPageNum + 1), 'period' => $period);
 
                                 if ($checkLastLineNum >= 0) {
-                                    // mettre ligne CSV dans fichier CSV qui va servir pour l'indexation (y ajouter les numeros de pages du fichier PDF)
+                                    // keep and put this line CSV in CSV check file for indexation step (add pages numbers of PDF file)
                                     $checkAgentKey = $csvTodoLineList[$checkLastLineNum]['siret'] . '-' . $csvTodoLineList[$checkLastLineNum]['matricule'];
                                     $csvTodoLineList[$checkLastLineNum]['pdf_pages'] = implode('-', $pdfPageList[$checkAgentKey]['page_num_list']);
                                     fputcsv($csvCheckFile, $csvTodoLineList[$checkLastLineNum], $this->_csvDelimiter, $this->_csvEnclosure);
-                                    unset($csvTodoLineList[$checkLastLineNum]); // enlever ligne de l'ancien agent
+                                    unset($csvTodoLineList[$checkLastLineNum]); // remove last agent user line
                                 }
 
-                                // sauvegarder le numero de la ligne CSV lie a l'ancien agent
+                                // keep line number linked to last agent
                                 $checkLastLineNum = $csvTodoLineNum;
 
-                                // mettre les nouvelles valeurs dans les anciennes valeurs a verifier
+                                // put new values in old values to check
                                 $checkLastValues = $checkCurrentValues;
                             } else {
                                 $this->_logCsvLine($this->_l10n->t('Ajout de la page ' . ($pdfPageNum + 1) .' du PDF des bulletins de paie de l\'agent.'), self::LOG_DEBUG);
                                 $pdfPageList[$agentKey]['page_num_list'][] = $pdfPageNum + 1;
                             }
 
-                            // cas de la derniere page du PDF
+                            // case of last PDF page
                             if ($pdfPageNum == $pdfPageNb - 1) {
                                 if ($checkLastLineNum >= 0) {
-                                    // mettre ligne CSV dans fichier CSV qui va servir pour l'indexation (y ajouter les numeros de pages du fichier PDF)
+                                    // keep and put this line CSV in CSV check file for indexation step (add pages numbers of PDF file)
                                     $checkAgentKey = $csvTodoLineList[$checkLastLineNum]['siret'] . '-' . $csvTodoLineList[$checkLastLineNum]['matricule'];
                                     $csvTodoLineList[$checkLastLineNum]['pdf_pages'] = implode('-', $pdfPageList[$checkAgentKey]['page_num_list']);
                                     fputcsv($csvCheckFile, $csvTodoLineList[$checkLastLineNum], $this->_csvDelimiter, $this->_csvEnclosure);
-                                    unset($csvTodoLineList[$checkLastLineNum]); // enlever ligne de l'ancien agent
+                                    unset($csvTodoLineList[$checkLastLineNum]); // remove last agent user line
                                 }
                             }
                         }
@@ -1467,7 +1474,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                     fclose($csvCheckFile);
 
                     if ($this->_processFailOnFirstError===false || $this->getHasError()<=0) {
-                        // Si on n'a pas traite toutes les lignes du CSV
+                        // if not all CSV lines was done
                         if (count($csvTodoLineList) > 0) {
                             $errorMsgLines = array();
                             $errorMsgLines[] = $this->_l10n->t('Des lignes du fichier CSV "' . $uploadFileCSVName . '" n\'ont pas été traitées') . ' : ';
@@ -1481,12 +1488,12 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                     $this->_logCsvLine('## ' .$this->_l10n->t('Fin de l\'association des pages du PDF aux différents agents.') . ' ##', self::LOG_DEBUG);
                 }
 
-                // Phase - decoupage des pages du fichier PDF
+                // Step - cut PDF pages
                 if ($this->getHasError()>0)   $this->_processFailOnFirstError = true;
                 if ($this->_processFailOnFirstError===false || $this->getHasError()<=0) {
                     $this->_logCsvLine('## ' . $this->_l10n->t('Début de découpage des pages du fichier PDF.') . ' ##', self::LOG_DEBUG);
 
-                    // ouvrir le fichier CSV du dossier "check"
+                    // open CSV file of check directory
                     $this->_logCsvLine($this->_l10n->t('Ouverture des lignes du fichier CSV contenant les pages des bulletins de paie à découper.'), self::LOG_DEBUG);
                     $csvCheckFilePath = $this->_checkDirFullPath . DIRECTORY_SEPARATOR . $csvCheckFileName;
                     $csvCheckFile = fopen($csvCheckFilePath, 'r');
@@ -1497,7 +1504,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                     }
 
                     if ($this->_processFailOnFirstError===false || $this->getHasError()<=0) {
-                        // pour chaque ligne CSV
+                        // for each CSV line
                         $this->_logCsvLine($this->_l10n->t('Lecture des lignes fichier CSV.'), self::LOG_DEBUG);
                         $csvCheckLineNum = 0;
                         while ($csvCheckLine = fgetcsv($csvCheckFile, $this->_csvLength, $this->_csvDelimiter, $this->_csvEnclosure)) {
@@ -1523,7 +1530,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                             $pdfPageNumList = explode('-', $csvCheckLine[12]);
                             $this->_logCsvLine($this->_l10n->t('Découpage des pages du PDF pour le bulletin de paie de l\'agent [matricule=' . $csvCheckMatricule . '].'), self::LOG_DEBUG);
 
-                            // ajout des pages
+                            // add pages
                             $this->_logCsvLine($this->_l10n->t('Ajout des pages PDF au bulletin de paie.'), self::LOG_DEBUG);
                             $pdfPayslip = new \setasign\Fpdi\Fpdi();
                             foreach ($pdfPageNumList as $pdfPageNum) {
@@ -1534,7 +1541,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                                 $pdfPayslip->useTemplate($tplPayslipId);
                             }
 
-                            /// mettre la fiche de paie dans le dossier "check"
+                            // put payslip in check directory
                             $this->_logCsvLine($this->_l10n->t('Créer le PDF du bulletin de paie.'), self::LOG_DEBUG);
                             $pdfPayslip->Output('F', $this->_checkDirFullPath . DIRECTORY_SEPARATOR . ($csvCheckLineNum + 1) . '_' . $csvCheckMatricule . '.pdf');
 
@@ -1561,7 +1568,6 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
             fclose($this->_logFile);
             // rename (log file)
             try {
-                $userFolder = $this->_rootFolder->getUserFolder($this->_userId);
                 $logFileNode = $userFolder->get($logFilePath);
                 $logFileNode->move($logFileNode->getPath() . '.csv');
             } catch (Exception $e) {
@@ -1767,7 +1773,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                                 $userFindByEmailId = $userFindByEmail->getUID();
 
                                 if ($this->getHasError() <= 0) {
-                                    // directory "SIRET-MATRICULE"
+                                    // "SIRET-MATRICULE" directory
                                     $siretMatriculeDirName = $agentUser->getSiret() . '-' . $agentUser->getMatricule();
                                     $payslipsMatriculeDirPath = $payslipsDirPath . DIRECTORY_SEPARATOR . $siretMatriculeDirName;
 
@@ -2132,6 +2138,9 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                                             } else {
                                                 $processMsgList['success'][] = $dematpayslipArchive;
                                                 $dematpayslipArchive->setStatus(DematpayslipArchive::STATUS_INDEXED);
+                                                $dematpayslipArchive->setStatusTime($phaseStartTime);
+                                                $dematpayslipArchive->setDematIdProcess(0);
+                                                $dematpayslipArchive->setFilePagesNum('');
                                                 // next operation for this file if asked
                                                 if ($operationAskArchive) {
                                                     $dematpayslipArchive->setOperationProgress(DematpayslipArchive::OPERATION_ARCHIVE);
@@ -2352,6 +2361,9 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                                         } else {
                                             $processMsgList['success'][] = $dematpayslipArchive;
                                             $dematpayslipArchive->setStatus(DematpayslipArchive::STATUS_INDEXED);
+                                            $dematpayslipArchive->setStatusTime($phaseStartTime);
+                                            $dematpayslipArchive->setDematIdProcess(0);
+                                            $dematpayslipArchive->setFilePagesNum('');
                                             // next operation for this file if asked
                                             if ($operationAskArchive) {
                                                 $dematpayslipArchive->setOperationProgress(DematpayslipArchive::OPERATION_ARCHIVE);
@@ -2384,8 +2396,22 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                                     if (!empty($skipArchiveList)) {
                                         foreach ($skipArchiveList as $skipArchive) {
                                             $processMsgList['success'][] = $skipArchive;
+                                            // remove file
+                                            try {
+                                                $skipArchiveNode = $this->_rootFolder->get($skipArchive->getFilePath());
+                                                $skipArchiveNode->delete();
+                                            } catch (Exception $e) {
+                                                $errorMsg = $this->_l10n->t('Impossible de supprimer "' . $skipArchive->getFilePath() . '".');
+                                                $this->_logCsvLine($errorMsg, self::LOG_ERROR);
+                                                $this->_processErrorMsg(-1, $errorMsg, $phaseStep, $csvCheckLineNum);
+                                            }
+
+                                            $skipArchive->setIdFile($payslipSkipPDFPathNode->getId());
                                             $skipArchive->setFilePath($payslipSkipPDFPathNode->getPath());
                                             $skipArchive->setStatus(DematpayslipArchive::STATUS_INDEXED);
+                                            $skipArchive->setStatusTime($phaseStartTime);
+                                            $skipArchive->setDematIdProcess(0);
+                                            $skipArchive->setFilePagesNum('');
                                             $skipArchive->setOperationProgress(DematpayslipArchive::OPERATION_FINISHED); // no next operation
                                             $skipArchive->setError(0);
                                             $dematpayslipArchiveMapper->update($skipArchive);
@@ -2552,20 +2578,25 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
     public function agentCsv() {
         $this->_initDematFolders();
 
-        if (count($this->_msgList['error']) <= 0) {
+        if (!$this->hasError()) {
             $dematpayslipUserList = $this->_dematpayslipUserMapper->findAll(array(array('disabled', 'desc'), array('siret'), array('matricule')));
 
             if (!empty($dematpayslipUserList)) {
                 $dateTimeNow = new DateTime('now', $this->_timeZone);
-                $csvFilePath = $this->_exportDirUserPath . DIRECTORY_SEPARATOR . $dateTimeNow->format('Y-m-d_H-i-s') . '_agent';
-                $csvFile = Filesystem::fopen($csvFilePath, 'w+');
-
-                if (!$csvFile) {
-                    $errorMsg = $this->_l10n->t('Ouverture du fichier CSV.');
+                $userFolder = $this->_rootFolder->getUserFolder($this->_userId);
+                $csvFileName = $dateTimeNow->format('Y-m-d_H-i-s') . '_agent';
+                $csvFilePath = $this->_exportDirUserPath . DIRECTORY_SEPARATOR . $csvFileName;
+                $csvFileFullPath = $this->_exportDirFullPath . DIRECTORY_SEPARATOR . $csvFileName;
+                $csvFile = null;
+                try {
+                    $userFolder->newFile($csvFilePath);
+                    $csvFile = fopen($csvFileFullPath, 'w+');
+                } catch (Exception $e) {
+                    $errorMsg = $this->_l10n->t('Impossible d\'ouvrir le fichier CSV "' . $csvFilePath . '".');
                     $this->_msgList['error'][] = $errorMsg;
                 }
 
-                if (count($this->_msgList['error']) <= 0) {
+                if (!$this->hasError()) {
                     $csvDelimiter = $this->_csvDelimiter;
                     $csvEnclosure = $this->_csvEnclosure;
 
@@ -2582,7 +2613,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                         $this->_msgList['error'][] = $errorMsg;
                     }
 
-                    if (count($this->_msgList['error']) <= 0) {
+                    if (!$this->hasError()) {
                         foreach ($dematpayslipUserList as $dematpayslipUser) {
                             $agent = $this->_userManager->get($dematpayslipUser->getUserId());
 
@@ -2609,10 +2640,15 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                         $this->_msgList['error'][] = $errorMsg;
                     }
 
-                    if (count($this->_msgList['error']) <= 0) {
-                        // rename (sync files)
-                        $renamed = Filesystem::rename($csvFilePath, $csvFilePath . '.csv');
-                        $this->_msgList['success'][] = $this->_l10n->t('La liste des agents a bien été exporté au format CSV.');
+                    if (!$this->hasError()) {
+                        // rename csv file
+                        try {
+                            $csvFileNode = $userFolder->get($csvFilePath);
+                            $csvFileNode->move($userFolder->getPath() . DIRECTORY_SEPARATOR . $csvFilePath . '.csv');
+                            $this->_msgList['success'][] = $this->_l10n->t('La liste des agents a bien été exporté au format CSV.');
+                        } catch (Exception $e) {
+                            $this->_msgList['error'][] = $this->_l10n->t('Impossible de déplacer le fichier CSV "' . $csvFilePath . '" .');
+                        }
                     }
                 }
             }
@@ -2698,7 +2734,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                         }
                     }
 
-                    if (count($this->_msgList['error']) > 0) break;
+                    if ($this->hasError()) break;
                 }
             }
         }
@@ -2725,15 +2761,20 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
 
         if (!empty($dematpayslipArchiveList)) {
             $dateTimeNow = new DateTime('now', $this->_timeZone);
-            $csvFilePath = $this->_exportDirUserPath . DIRECTORY_SEPARATOR . $dateTimeNow->format('Y-m-d_H-i-s') . '_archive';
-            $csvFile = Filesystem::fopen($csvFilePath, 'w+');
-
-            if (!$csvFile) {
-                $errorMsg = $this->_l10n->t('Ouverture du fichier CSV.');
+            $userFolder = $this->_rootFolder->getUserFolder($this->_userId);
+            $csvFileName = $dateTimeNow->format('Y-m-d_H-i-s') . '_archive';
+            $csvFilePath = $this->_exportDirUserPath . DIRECTORY_SEPARATOR . $csvFileName;
+            $csvFileFullPath = $this->_exportDirFullPath . DIRECTORY_SEPARATOR . $csvFileName;
+            $csvFile = null;
+            try {
+                $userFolder->newFile($csvFilePath);
+                $csvFile = fopen($csvFileFullPath, 'w+');
+            } catch (Exception $e) {
+                $errorMsg = $this->_l10n->t('Impossible d\'ouvrir le fichier CSV "' . $csvFilePath . '".');
                 $this->_msgList['error'][] = $errorMsg;
             }
 
-            if (count($this->_msgList['error']) <= 0) {
+            if (!$this->hasError()) {
                 $csvDelimiter = $this->_csvDelimiter;
                 $csvEnclosure = $this->_csvEnclosure;
 
@@ -2755,7 +2796,7 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                     $this->_msgList['error'][] = $errorMsg;
                 }
 
-                if (count($this->_msgList['error']) <= 0) {
+                if (!$this->hasError()) {
                     foreach ($dematpayslipArchiveList as $dematpayslipArchive) {
                         $csvFields = array();
                         $csvFields[] = $dematpayslipArchive->getFilePath();
@@ -2784,10 +2825,15 @@ class DematpayslipProcess extends Entity implements JsonSerializable {
                     $this->_msgList['error'][] = $errorMsg;
                 }
 
-                if (count($this->_msgList['error']) <= 0) {
-                    // rename (sync files)
-                    $renamed = Filesystem::rename($csvFilePath, $csvFilePath . '.csv');
-                    $this->_msgList['success'][] = $this->_l10n->t('La liste des archives a bien été exporté au format CSV.');
+                if (!$this->hasError()) {
+                    // rename csv file
+                    try {
+                        $csvFileNode = $userFolder->get($csvFilePath);
+                        $csvFileNode->move($userFolder->getPath() . DIRECTORY_SEPARATOR . $csvFilePath . '.csv');
+                        $this->_msgList['success'][] = $this->_l10n->t('La liste des archives a bien été exporté au format CSV.');
+                    } catch (Exception $e) {
+                        $this->_msgList['error'][] = $this->_l10n->t('Impossible de déplacer le fichier CSV "' . $csvFilePath . '" .');
+                    }
                 }
             }
         }
-- 
GitLab