From 8c3e2e3be7316cb2463937d788abae892e351a88 Mon Sep 17 00:00:00 2001
From: Damien <damien.burel@maarch.org>
Date: Wed, 16 Oct 2019 16:00:34 +0200
Subject: [PATCH] FIX #12070 TIME 1:25 Refactoring res columns + typist

---
 .../show_technicalInfo_tab.php                | 58 +-----------
 core/class/class_resource.php                 | 31 +------
 migration/19.12/1912.sql                      | 46 +++++++--
 sql/structure.sql                             | 34 +++----
 .../docserver/models/ResDocserverModel.php    | 21 -----
 .../models/ResDocserverModelAbstract.php      | 93 -------------------
 .../resource/controllers/ResController.php    | 12 ++-
 .../resource/controllers/StoreController.php  | 67 +++++--------
 8 files changed, 83 insertions(+), 279 deletions(-)
 delete mode 100755 src/app/docserver/models/ResDocserverModel.php
 delete mode 100755 src/app/docserver/models/ResDocserverModelAbstract.php

diff --git a/apps/maarch_entreprise/show_technicalInfo_tab.php b/apps/maarch_entreprise/show_technicalInfo_tab.php
index dea90bdc63c..59ec30a1545 100755
--- a/apps/maarch_entreprise/show_technicalInfo_tab.php
+++ b/apps/maarch_entreprise/show_technicalInfo_tab.php
@@ -82,18 +82,6 @@ $db = new Database();
     $creationDate = functions::format_date_db($res->creation_date, false);
     $fingerprint = $res->fingerprint;
     $workBatch = $res->work_batch;
-    $isMultiDs = $res->is_multi_docservers;
-    if ($isMultiDs == 'Y') {
-        $adr = array();
-        $resource = new resource();
-        $whereClause = ' and 1=1';
-        $adr = $resource->getResourceAdr(
-            $table,
-            $_SESSION['doc_id'],
-            $whereClause,
-            $adrTable
-        );
-    }
     ?>
         <h2>
             <span class="date">
@@ -157,49 +145,6 @@ $db = new Database();
         <br/>
         <?php
         $docserversControler = new docservers_controler();
-        if ($isMultiDs == 'Y') {
-            for ($cptAdr = 0; $cptAdr < count($adr[0]); ++$cptAdr) {
-                $docserver = $docserversControler->get(
-                    $adr[0][$cptAdr]['docserver_id']
-                );
-                echo '<h4>'.functions::xssafe($adr[0][$cptAdr]['docserver_id'])
-                    .' ('.functions::xssafe($docserver->device_label).')</h4>'; ?>
-                <table cellpadding="2" cellspacing="2" border="0" class="block forms details" width="100%">
-                    <tr>
-                        <th align="left" class="picto">
-                            &nbsp;
-                        </th>
-                        <td align="left" width="200px"><?php echo _PATH_TEMPLATE; ?> :</td>
-                        <td><input type="text" class="readonly" readonly="readonly" value="<?php echo str_replace('#', '/', functions::xssafe($adr[0][$cptAdr]['path'])); ?>"/></td>
-                        <th align="left" class="picto">
-                            &nbsp;
-                        </th>
-                        <td align="left" width="200px"><?php echo _FILE; ?> :</td>
-                        <td><input type="text" class="readonly" readonly="readonly" value="<?php functions::xecho($adr[0][$cptAdr]['filename']); ?>" /></td>
-                    </tr>
-                    <tr>
-                        <th align="left" class="picto">
-                            &nbsp;
-                        </th>
-                        <td align="left" width="200px"><?php echo _FORMAT; ?> :</td>
-                        <td><input type="text" class="readonly" readonly="readonly" value="<?php functions::xecho($adr[0][$cptAdr]['format']); ?>"/></td>
-                        <th align="left" class="picto">
-                            &nbsp;
-                        </th>
-                        <td align="left" width="200px"><?php echo _FINGERPRINT; ?> :</td>
-                        <td><input type="text" class="readonly" readonly="readonly" value="<?php functions::xecho($adr[0][$cptAdr]['fingerprint']); ?>" /></td>
-                    </tr>
-                    <tr>
-                        <th align="left" class="picto">
-                            &nbsp;
-                        </th>
-                        <td align="left" width="200px"><?php echo _ADR_PRIORITY; ?> :</td>
-                        <td><input type="text" class="readonly" readonly="readonly" value="<?php functions::xecho($adr[0][$cptAdr]['adr_priority']); ?>" /></td>
-                    </tr>
-                </table>
-                <?php
-            }
-        } else {
             $docserver = $docserversControler->get($docserverId);
             echo '<h4>'.functions::xssafe($docserverId)
                     .' ('.functions::xssafe($docserver->device_label).')</h4>'; ?>
@@ -218,6 +163,5 @@ $db = new Database();
                 </tr>
             </table>
             <?php
-        }
         ?>
-        <br>
\ No newline at end of file
+        <br>
diff --git a/core/class/class_resource.php b/core/class/class_resource.php
index 006fcc2ae4f..14a2134380d 100755
--- a/core/class/class_resource.php
+++ b/core/class/class_resource.php
@@ -313,40 +313,13 @@
         }
         $docserverAdr = array();
         $db = new Database();
-        $query = "select res_id, docserver_id, path, filename, format, fingerprint, is_multi_docservers from " . $view
+        $query = "select res_id, docserver_id, path, filename, format, fingerprint from " . $view
             . " where res_id = ? ". $whereClause;
         $stmt = $db->query($query, array($resId));
         if ($stmt->rowCount() > 0) {
             $line = $stmt->fetchObject();
             $format = $line->format;
-            if ($line->is_multi_docservers == "Y") {
-                if (
-                    $adrTable == 'adr_letterbox' ||
-                    $adrTable == 'adr_attachments' ||
-                    $adrTable == 'adr_attachments_version'
-
-                ) {
-                    if ($adrTable == 'adr_x') {
-                        $adrTable = 'adr_letterbox';
-                    }
-                    $query = "select res_id, docserver_id, path, filename, fingerprint, adr_priority from "
-                        . $adrTable . " where res_id = ? order by adr_priority";
-                    $stmt = $db->query($query, array($resId));
-                    if ($stmt->rowCount() > 0) {
-                        while ($line = $stmt->fetchObject()) {
-                            array_push($docserverAdr, array("docserver_id" => $line->docserver_id, "path" => $line->path, "filename" => $line->filename, "format" => $format, "fingerprint" => $line->fingerprint, "adr_priority" => $line->adr_priority));
-                        }
-                    } else {
-                        $control = array("status" => "ko", "error" => _RESOURCE_NOT_FOUND);
-                        return $control;
-                    }
-                } else {
-                    $control = array("status" => "ko", "error" => _PB_WITH_ARGUMENTS . ' adrTable');
-                    return $control;
-                }
-            } else {
-                array_push($docserverAdr, array("docserver_id" => $line->docserver_id, "path" => $line->path, "filename" => $line->filename, "format" => $format, "fingerprint" => $line->fingerprint, "adr_priority" => ""));
-            }
+            array_push($docserverAdr, array("docserver_id" => $line->docserver_id, "path" => $line->path, "filename" => $line->filename, "format" => $format, "fingerprint" => $line->fingerprint, "adr_priority" => ""));
             $control = array("status" => "ok", $docserverAdr, "error" => "");
             return $control;
         } else {
diff --git a/migration/19.12/1912.sql b/migration/19.12/1912.sql
index cf3ed1410a1..730117b0181 100644
--- a/migration/19.12/1912.sql
+++ b/migration/19.12/1912.sql
@@ -139,6 +139,18 @@ CREATE TABLE custom_fields
 )
 WITH (OIDS=FALSE);
 
+DROP TABLE IF EXISTS resources_custom_fields;
+CREATE TABLE resources_custom_fields
+(
+    id serial NOT NULL,
+    res_id INTEGER NOT NULL,
+    custom_field_id INTEGER NOT NULL,
+    value jsonb NOT NULL,
+    CONSTRAINT resources_custom_fields_pkey PRIMARY KEY (id),
+    CONSTRAINT resources_custom_fields_unique_key UNIQUE (res_id, custom_field_id)
+)
+WITH (OIDS=FALSE);
+
 
 /* INDEXING MODELS */
 DROP TABLE IF EXISTS indexing_models;
@@ -226,6 +238,19 @@ DO $$ BEGIN
 END$$;
 
 
+/* RES_LETTERBOX */
+DO $$ BEGIN
+    IF (SELECT count(column_name) from information_schema.columns where table_name = 'res_letterbox' and column_name = 'typist' and data_type != 'integer') THEN
+        ALTER TABLE res_letterbox ADD COLUMN typist_tmp integer;
+        UPDATE res_letterbox set typist_tmp = (select id FROM users where users.user_id = res_letterbox.typist);
+        UPDATE res_letterbox set typist_tmp = 0 WHERE typist_tmp IS NULL;
+        ALTER TABLE res_letterbox ALTER COLUMN typist_tmp set not null;
+        ALTER TABLE res_letterbox DROP COLUMN IF EXISTS typist;
+        ALTER TABLE res_letterbox RENAME COLUMN typist_tmp TO typist;
+    END IF;
+END$$;
+
+
 /* MLB COLL EXT */
 DO $$ BEGIN
     IF (SELECT count(attname) FROM pg_attribute WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'mlb_coll_ext') AND attname = 'category_id') THEN
@@ -388,13 +413,21 @@ ALTER TABLE priorities DROP COLUMN IF EXISTS working_days;
 DROP TABLE IF EXISTS thesaurus;
 DROP TABLE IF EXISTS thesaurus_res;
 DROP SEQUENCE IF EXISTS thesaurus_id_seq;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS title;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS description;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS author;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS identifier;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS source;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS relation;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS offset_doc;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS is_multi_docservers;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS tablename;
+ALTER TABLE res_letterbox DROP COLUMN IF EXISTS validation_date;
 
 
 /* RE CREATE VIEWS */
 CREATE OR REPLACE VIEW res_view_letterbox AS
-SELECT r.tablename,
-       r.is_multi_docservers,
-       r.res_id,
+SELECT r.res_id,
        r.type_id,
        r.policy_id,
        r.cycle_id,
@@ -409,12 +442,10 @@ SELECT r.tablename,
        r.typist,
        r.creation_date,
        r.modification_date,
-       r.relation,
        r.docserver_id,
        r.path,
        r.filename,
        r.fingerprint,
-       r.offset_doc,
        r.filesize,
        r.scan_date,
        r.scan_user,
@@ -425,9 +456,6 @@ SELECT r.tablename,
        r.status,
        r.work_batch,
        r.doc_date,
-       r.description,
-       r.source,
-       r.author,
        r.reference_number,
        r.external_reference,
        r.external_id,
@@ -492,8 +520,6 @@ SELECT r.tablename,
        r.flag_alarm2,
        r.is_multicontacts,
        r.subject,
-       r.identifier,
-       r.title,
        r.priority,
        r.locker_user_id,
        r.locker_time,
diff --git a/sql/structure.sql b/sql/structure.sql
index ef6e6d7d6aa..823f61b5997 100755
--- a/sql/structure.sql
+++ b/sql/structure.sql
@@ -1104,23 +1104,16 @@ CREATE SEQUENCE res_id_mlb_seq
 CREATE TABLE res_letterbox
 (
   res_id bigint NOT NULL DEFAULT nextval('res_id_mlb_seq'::regclass),
-  title character varying(255) DEFAULT NULL::character varying,
   subject text,
-  description text,
   type_id bigint NOT NULL,
   format character varying(50) NOT NULL,
-  typist character varying(128) NOT NULL,
+  typist INTEGER NOT NULL,
   creation_date timestamp without time zone NOT NULL,
   modification_date timestamp without time zone DEFAULT NOW(),
-  author character varying(255) DEFAULT NULL::character varying,
-  identifier character varying(255) DEFAULT NULL::character varying,
-  source character varying(255) DEFAULT NULL::character varying,
-  relation bigint,
   doc_date timestamp without time zone,
   docserver_id character varying(32) NOT NULL,
   path character varying(255) DEFAULT NULL::character varying,
   filename character varying(255) DEFAULT NULL::character varying,
-  offset_doc character varying(255) DEFAULT NULL::character varying,
   fingerprint character varying(255) DEFAULT NULL::character varying,
   filesize bigint,
   scan_date timestamp without time zone,
@@ -1131,13 +1124,11 @@ CREATE TABLE res_letterbox
   scan_postmark character varying(50) DEFAULT NULL::character varying,
   status character varying(10) NOT NULL,
   destination character varying(50) DEFAULT NULL::character varying,
-  validation_date timestamp without time zone,
   work_batch bigint,
   origin character varying(50) DEFAULT NULL::character varying,
   priority character varying(16),
   policy_id character varying(32) DEFAULT NULL::character varying,
   cycle_id character varying(32) DEFAULT NULL::character varying,
-  is_multi_docservers character(1) NOT NULL DEFAULT 'N'::bpchar,
   custom_t1 text,
   custom_n1 bigint,
   custom_f1 numeric,
@@ -1174,7 +1165,6 @@ CREATE TABLE res_letterbox
   custom_t14 character varying(255) DEFAULT NULL::character varying,
   custom_t15 character varying(255) DEFAULT NULL::character varying,
   reference_number character varying(255) DEFAULT NULL::character varying,
-  tablename character varying(32) DEFAULT 'res_letterbox'::character varying,
   initiator character varying(50) DEFAULT NULL::character varying,
   dest_user character varying(128) DEFAULT NULL::character varying,
   locker_user_id INTEGER DEFAULT NULL,
@@ -1365,9 +1355,7 @@ WITH (OIDS=FALSE);
 --VIEWS
 -- view for letterbox
 CREATE OR REPLACE VIEW res_view_letterbox AS
-SELECT r.tablename,
-       r.is_multi_docservers,
-       r.res_id,
+SELECT r.res_id,
        r.type_id,
        r.policy_id,
        r.cycle_id,
@@ -1382,12 +1370,10 @@ SELECT r.tablename,
        r.typist,
        r.creation_date,
        r.modification_date,
-       r.relation,
        r.docserver_id,
        r.path,
        r.filename,
        r.fingerprint,
-       r.offset_doc,
        r.filesize,
        r.scan_date,
        r.scan_user,
@@ -1398,9 +1384,6 @@ SELECT r.tablename,
        r.status,
        r.work_batch,
        r.doc_date,
-       r.description,
-       r.source,
-       r.author,
        r.reference_number,
        r.external_reference,
        r.external_id,
@@ -1465,8 +1448,6 @@ SELECT r.tablename,
        r.flag_alarm2,
        r.is_multicontacts,
        r.subject,
-       r.identifier,
-       r.title,
        r.priority,
        r.locker_user_id,
        r.locker_time,
@@ -1842,6 +1823,17 @@ CREATE TABLE custom_fields
 )
 WITH (OIDS=FALSE);
 
+CREATE TABLE resources_custom_fields
+(
+    id serial NOT NULL,
+    res_id INTEGER NOT NULL,
+    custom_field_id INTEGER NOT NULL,
+    value jsonb NOT NULL,
+    CONSTRAINT resources_custom_fields_pkey PRIMARY KEY (id),
+    CONSTRAINT resources_custom_fields_unique_key UNIQUE (res_id, custom_field_id)
+)
+WITH (OIDS=FALSE);
+
 CREATE TABLE indexing_models
 (
     id SERIAL NOT NULL,
diff --git a/src/app/docserver/models/ResDocserverModel.php b/src/app/docserver/models/ResDocserverModel.php
deleted file mode 100755
index 61af1753928..00000000000
--- a/src/app/docserver/models/ResDocserverModel.php
+++ /dev/null
@@ -1,21 +0,0 @@
-<?php
-
-/**
-* Copyright Maarch since 2008 under licence GPLv3.
-* See LICENCE.txt file at the root folder for more details.
-* This file is part of Maarch software.
-*
-*/
-
-/**
-* @brief Res and docserver association Model
-* @author dev@maarch.org
-* @ingroup core
-*/
-
-namespace Docserver\models;
-
-class ResDocserverModel extends ResDocserverModelAbstract
-{
-    // Do your stuff in this class
-}
diff --git a/src/app/docserver/models/ResDocserverModelAbstract.php b/src/app/docserver/models/ResDocserverModelAbstract.php
deleted file mode 100755
index b8d6de3e189..00000000000
--- a/src/app/docserver/models/ResDocserverModelAbstract.php
+++ /dev/null
@@ -1,93 +0,0 @@
-<?php
-
-/**
-* Copyright Maarch since 2008 under licence GPLv3.
-* See LICENCE.txt file at the root folder for more details.
-* This file is part of Maarch software.
-*
-*/
-
-/**
-* @brief Res Docserver association Model
-* @author dev@maarch.org
-* @ingroup core
-*/
-
-namespace Docserver\models;
-
-use SrcCore\models\DatabaseModel;
-use SrcCore\models\ValidatorModel;
-
-class ResDocserverModelAbstract
-{
-
-    /**
-     * Retrieve the path of source file to process
-     * @param string $resTable resource table
-     * @param string $adrTable adr table
-     * @param bigint $resId Id of the resource to process
-     * @param string $adrType type of the address
-     * $resTable, $adrTable, $resId, $adrType = 'DOC'
-     * @return string
-     */
-    public static function getSourceResourcePath(array $aArgs = [])
-    {
-        ValidatorModel::notEmpty($aArgs, ['resTable']);
-        ValidatorModel::notEmpty($aArgs, ['adrTable']);
-        ValidatorModel::notEmpty($aArgs, ['resId']);
-        
-        if (!isset($aArgs['adrType'])) {
-            $aArgs['adrType'] = 'DOC';
-        }
-
-        if ($aArgs['adrType'] == 'DOC') {
-            $table = $aArgs['resTable'];
-            $where = ['res_id=?'];
-            $data  = [$aArgs['resId']];
-        } else {
-            $table = $aArgs['adrTable'];
-            $where = ['res_id = ?', 'adr_type = ?'];
-            $data  = [$aArgs['resId'], $aArgs['adrType']];
-        }
-
-        $aReturn = DatabaseModel::select([
-            'select'    => [$table.'.path', $table.'.filename', $table.'.offset_doc', 'docservers.path_template'],
-            'table'     => [$table, 'docservers'],
-            'where'     => $where,
-            'data'      => $data,
-            'left_join' => [$table.'.docserver_id = docservers.docserver_id']
-        ]);
-
-        if (empty($aReturn)) {
-            return false;
-        }
-
-        $resPath            = '';
-        $resFilename        = '';
-        if (isset($aReturn[0]['path'])) {
-            $resPath = $aReturn[0]['path'];
-        }
-        if (isset($aReturn[0]['filename'])) {
-            $resFilename = $aReturn[0]['filename'];
-        }
-        if (isset($aReturn[0]['offset_doc'])
-            && $aReturn[0]['offset_doc'] <> ''
-            && $aReturn[0]['offset_doc'] <> ' '
-        ) {
-            $sourceFilePath = $aReturn[0]['path']
-                . $aReturn[0]['filename']
-                . DIRECTORY_SEPARATOR . $aReturn[0]['offset_doc'];
-        } else {
-            $sourceFilePath = $resPath . $resFilename;
-        }
-        $resPathTemplate = '';
-        if (isset($aReturn[0]['path_template'])) {
-            $resPathTemplate = $aReturn[0]['path_template'];
-        }
-
-        $sourceFilePath = $resPathTemplate . $sourceFilePath;
-        $sourceFilePath = str_replace('#', DIRECTORY_SEPARATOR, $sourceFilePath);
-
-        return $sourceFilePath;
-    }
-}
diff --git a/src/app/resource/controllers/ResController.php b/src/app/resource/controllers/ResController.php
index c9a8536d41b..0d40df05c44 100755
--- a/src/app/resource/controllers/ResController.php
+++ b/src/app/resource/controllers/ResController.php
@@ -726,8 +726,16 @@ class ResController
         $resources = ResModel::getOnView(['select' => $select, 'where' => $where, 'orderBy' => $data['orderBy'], 'limit' => $data['limit']]);
         if (!empty($resources) && $data['withFile'] === true) {
             foreach ($resources as $key => $res) {
-                $path = ResDocserverModel::getSourceResourcePath(['resId' => $res['res_id'], 'resTable' => 'res_letterbox', 'adrTable' => 'null']);
-                $file = file_get_contents($path);
+                $document = ResModel::getById(['resId' => $res['res_id'], 'select' => ['path', 'filename', 'docserver_id']]);
+                $docserver = DocserverModel::getByDocserverId(['docserverId' => $document['docserver_id'], 'select' => ['path_template', 'docserver_type_id']]);
+                if (empty($docserver['path_template']) || !file_exists($docserver['path_template'])) {
+                    continue;
+                }
+                $pathToDocument = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $document['path']) . $document['filename'];
+                if (!file_exists($pathToDocument)) {
+                    continue;
+                }
+                $file = file_get_contents($pathToDocument);
                 $base64Content = base64_encode($file);
                 $resources[$key]['fileBase64Content'] = $base64Content;
             }
diff --git a/src/app/resource/controllers/StoreController.php b/src/app/resource/controllers/StoreController.php
index ba30ec8b0fd..8879b1d65d4 100755
--- a/src/app/resource/controllers/StoreController.php
+++ b/src/app/resource/controllers/StoreController.php
@@ -15,15 +15,11 @@
 
 namespace Resource\controllers;
 
-use Slim\Http\Request;
-use Slim\Http\Response;
 use Attachment\models\AttachmentModel;
-use Contact\models\ContactModel;
 use Docserver\controllers\DocserverController;
 use Resource\models\ChronoModel;
 use SrcCore\models\DatabaseModel;
 use SrcCore\models\ValidatorModel;
-use Respect\Validation\Validator;
 use Resource\models\ResModel;
 use SrcCore\models\CoreConfigModel;
 
@@ -32,7 +28,8 @@ class StoreController
     public static function storeResource(array $aArgs)
     {
         ValidatorModel::notEmpty($aArgs, ['encodedFile', 'format', 'status', 'type_id', 'category_id']);
-        ValidatorModel::stringType($aArgs, ['format', 'status']);
+        ValidatorModel::stringType($aArgs, ['format', 'status', 'category_id']);
+        ValidatorModel::intVal($aArgs, ['type_id']);
 
         try {
             foreach ($aArgs as $column => $value) {
@@ -149,58 +146,36 @@ class StoreController
         return hash_file(strtolower($aArgs['mode']), $aArgs['filePath']);
     }
 
-    public static function prepareStorage(array $aArgs)
+    public static function prepareStorage(array $args)
     {
-        ValidatorModel::notEmpty($aArgs, ['docserver_id', 'filename', 'format', 'filesize', 'path', 'fingerprint', 'status', 'res_id']);
-        ValidatorModel::stringType($aArgs, ['docserver_id', 'filename', 'format', 'path', 'fingerprint', 'status']);
-        ValidatorModel::intVal($aArgs, ['filesize', 'res_id']);
+        ValidatorModel::notEmpty($args, ['docserver_id', 'filename', 'format', 'filesize', 'path', 'fingerprint', 'status', 'res_id']);
+        ValidatorModel::stringType($args, ['docserver_id', 'filename', 'format', 'path', 'fingerprint', 'status']);
+        ValidatorModel::intVal($args, ['filesize', 'res_id']);
 
-        if (empty($aArgs['typist'])) {
-            $aArgs['typist'] = 'auto';
-        }
-
-        unset($aArgs['alt_identifier']);
-        if (!empty($aArgs['chrono'])) {
-            $aArgs['alt_identifier'] = ChronoModel::getChrono(['id' => $aArgs['category_id'], 'entityId' => $aArgs['destination'], 'typeId' => $aArgs['type_id'], 'resId' => $aArgs['res_id']]);
-        }
-        unset($aArgs['chrono']);
+        $args['typist'] = $GLOBALS['id'];
 
-        if (empty($aArgs['process_limit_date'])) {
-            $processLimitDate = ResModel::getStoredProcessLimitDate(['typeId' => $aArgs['type_id'], 'admissionDate' => $aArgs['admission_date']]);
-            $aArgs['process_limit_date'] = $processLimitDate;
+        unset($args['alt_identifier']);
+        if (!empty($args['chrono'])) {
+            $args['alt_identifier'] = ChronoModel::getChrono(['id' => $args['category_id'], 'entityId' => $args['destination'], 'typeId' => $args['type_id'], 'resId' => $args['res_id']]);
         }
+        unset($args['chrono']);
 
-        if (!empty($aArgs['exp_contact_id']) && !is_numeric($aArgs['exp_contact_id'])) {
-            $mail = explode('<', str_replace('>', '', $aArgs['exp_contact_id']));
-            $contact = ContactModel::getByEmail(['email' => $mail[count($mail) - 1], 'select' => ['contacts_v2.contact_id']]);
-            if (!empty($contact['contact_id'])) {
-                $aArgs['exp_contact_id'] = $contact['contact_id'];
-            } else {
-                $aArgs['exp_contact_id'] = 0;
-            }
-        }
-
-        if (!empty($aArgs['address_id']) && !is_numeric($aArgs['address_id'])) {
-            $mail = explode('<', str_replace('>', '', $aArgs['address_id']));
-            $contact = ContactModel::getByEmail(['email' => $mail[count($mail) - 1], 'select' => ['contact_addresses.id']]);
-            if (!empty($contact['id'])) {
-                $aArgs['address_id'] = $contact['id'];
-            } else {
-                $aArgs['address_id'] = 0;
-            }
+        if (empty($args['process_limit_date'])) {
+            $processLimitDate = ResModel::getStoredProcessLimitDate(['typeId' => $args['type_id'], 'admissionDate' => $args['admission_date']]);
+            $args['process_limit_date'] = $processLimitDate;
         }
 
-        unset($aArgs['external_id']);
-        if (!empty($aArgs['externalId'])) {
-            if (is_array($aArgs['externalId'])) {
-                $aArgs['external_id'] = json_encode($aArgs['externalId']);
+        unset($args['external_id']);
+        if (!empty($args['externalId'])) {
+            if (is_array($args['externalId'])) {
+                $args['external_id'] = json_encode($args['externalId']);
             }
-            unset($aArgs['externalId']);
+            unset($args['externalId']);
         }
 
-        $aArgs['creation_date'] = 'CURRENT_TIMESTAMP';
+        $args['creation_date'] = 'CURRENT_TIMESTAMP';
 
-        return $aArgs;
+        return $args;
     }
 
     public static function prepareAttachmentStorage(array $aArgs)
-- 
GitLab