ArchiveRestitution.php 15.5 KB
Newer Older
Prosper De Laure's avatar
Prosper De Laure committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

/* 
 * Copyright (C) 2015 Maarch
 *
 * This file is part of bundle medona
 *
 * Bundle medona is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Bundle medona is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with bundle medona.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace ext\thirdPartyArchiving\bundle\medona\Controller;

/**
 * Trait for archive restitution
 *
 * @author Prosper DE LAURE <prosper.delaure@maarch.org>
 */
class ArchiveRestitution extends abstractMessage
{

    /**
     * Get validation restitution message
     *
     * @return array Array of medona/message object
     */
    public function validationList()
    {
        $registrationNumber = $this->getCurrentRegistrationNumber();

        $queryParts = [];
        $queryParts[] = "type='ArchiveRestitution'";
        $queryParts[] = "recipientOrgRegNumber=$registrationNumber";
        $queryParts[] = "status=['sent', 'received']";
        $queryParts[] = "active=true";

        return $this->sdoFactory->find('medona/message', implode(' and ', $queryParts), null, false, false, 300);
    }

    /**
     * Get process restitution message
     *
     * @return array Array of medona/message object
     */
    public function processList()
    {
        $registrationNumber = $this->getCurrentRegistrationNumber();

        $queryParts = [];
        $queryParts[] = "type='ArchiveRestitution'";
        $queryParts[] = "senderOrgRegNumber=$registrationNumber";
        $queryParts[] = "status='acknowledge'";
        $queryParts[] = "active=true";

        return $this->sdoFactory->find('medona/message', implode(' and ', $queryParts), null, false, false, 300);
    }

    /**
     * Get transfer history
Alexandre Morin's avatar
Alexandre Morin committed
70
71
72
73
74
75
76
77
78
     *
     * @param string $reference         Reference
     * @param string $archiver          Archiver
     * @param string $originator        Originator
     * @param string $depositor         Depositor
     * @param string $archivalAgreement Archival agreement
     * @param date   $fromDate          From date
     * @param date   $toDate            To date
     * @param string $status            Status
Prosper De Laure's avatar
Prosper De Laure committed
79
80
81
     *
     * @return array Array of medona/message object
     */
Alexandre Morin's avatar
Alexandre Morin committed
82
    public function history($reference = null, $archiver = null, $originator = null, $depositor = null, $archivalAgreement = null, $fromDate = null, $toDate = null, $status = null)
Prosper De Laure's avatar
Prosper De Laure committed
83
    {
Alexandre Morin's avatar
Alexandre Morin committed
84
        return $this->search("ArchiveRestitution", $reference, $archiver, $originator, $depositor, $archivalAgreement, $fromDate, $toDate, $status);
Prosper De Laure's avatar
Prosper De Laure committed
85
86
87
88
89
90
91
92
93
94
95
96
    }

    /**
     * Export archive restitution
     * @param string $messageId The message identifier
     *
     * @return the result of process
     */
    public function export($messageId)
    {
        $message = $this->sdoFactory->read('medona/message', $messageId);

97
        $exportResult = \laabs::newController("medona/message")->export($messageId);
Prosper De Laure's avatar
Prosper De Laure committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150

        $this->lifeCycleJournalController->logEvent(
            'medona/reception',
            'medona/message',
            $message->messageId,
            $message,
            true
        );

        $this->changeStatus($messageId, "received");

        return $exportResult;
    }

    /**
     * Count archive restitution message
     *
     * @return array Number of received
     */
    public function count()
    {
        $registrationNumber = $this->getCurrentRegistrationNumber();

        $queryParts = [];
        $queryParts["type"] = "type='ArchiveRestitution'";
        $queryParts["registrationNumber"] = "recipientOrgRegNumber=$registrationNumber";
        $queryParts["active"] = "active=true";

        return $this->sdoFactory->count('medona/message', implode(' and ', $queryParts));
    }

    /**
     * Send a new restitution request reply
     * @param string $requestMessage The request message identifier
     * @param object $archives       The archives to deliver
     * @param string $replyCode      The reply code
     *
     * @return The reply message generated
     */
    public function send($requestMessage, $archives, $replyCode = "000")
    {
        if (is_scalar($requestMessage)) {
            $messageId = $requestMessage;
            $requestMessage = $this->sdoFactory->read('medona/message', $messageId);

            //$this->load($message);
        }

        $replyMessage = $this->sdoFactory->find('medona/message', "type='".$requestMessage->type."Reply' AND recipientOrgRegNumber='".$requestMessage->senderOrgRegNumber."' AND senderOrgRegNumber='".$requestMessage->recipientOrgRegNumber."' AND requestReference='".$requestMessage->reference."'");
        if (count($replyMessage) > 0) {
            $replyMessage = $replyMessage[0];
        } else {
            $this->sendError('104', "The reply message was not found.");
151
            $exception = \laabs::newException('medona/invalidMessageException', "Invalid message", 400);
Prosper De Laure's avatar
Prosper De Laure committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
            $exception->errors = $this->errors;
        }

        $message = \laabs::newInstance('medona/message');
        $message->messageId = \laabs::newId();
        $message->type = "ArchiveRestitution";
        $message->schema = $requestMessage->schema;
        $message->status = "sent";
        $message->date = \laabs::newDatetime(null, "UTC");
        $message->receptionDate = $message->date;

        $message->reference = 'ArchiveRestitution_'.\laabs::newId();
        $message->relatedReference = $replyMessage->reference;

        $message->senderOrgRegNumber = $replyMessage->senderOrgRegNumber;
        $message->recipientOrgRegNumber = $replyMessage->recipientOrgRegNumber;
        $this->readOrgs($message); // read org names, addresses, communications, contacts

170
171
172
173
174
        $message->unitIdentifier = $requestMessage->unitIdentifier;
        foreach ($message->unitIdentifier as $unitIdentifier) {
            $unitIdentifier->messageId = $message->messageId;
        }

Prosper De Laure's avatar
Prosper De Laure committed
175
176
177
178
179
180
181
182
183
184
185
186
        if ($replyMessage->replyCode == "000" || $replyMessage->replyCode == "001") {
            foreach ($archives as $archive) {
                $archive->lifeCycleEvent = $this->lifeCycleJournalController->getObjectEvents($archive->archiveId, 'recordsManagement/archive');
            }

            $message->archive = $archives;
            $message->dataObjectCount = count($archives);
        }

        try {
            mkdir($this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId, 0777, true);

187
188
189
190
191
192
193
194
195
196
197
198
199
            if ($message->schema != 'medona') {
                $archiveRestitutionController = \laabs::newController($message->schema.'/ArchiveRestitution');
                $archiveRestitutionController->send($message);
            } else {
                $archiveRestitution = $this->sendMessage($message);
                $message->object = $archiveRestitution;

                $archiveRestitution->requester = $this->sendOrganization($message->senderOrg);
                $archiveRestitution->archivalAgency = $this->sendOrganization($message->recipientOrg);

                $this->generate($message);
                $this->save($message);
            }
Prosper De Laure's avatar
Prosper De Laure committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
            $operationResult = true;

        } catch (\Exception $e) {
            $message->status = "invalid";
            $operationResult = false;

            $this->create($message);

            throw $e;
        }

        $event = $this->lifeCycleJournalController->logEvent(
            'medona/sending',
            'medona/message',
            $message->messageId,
            $message,
            $operationResult
        );

        $this->create($message);

        return $message;
    }

    /**
     * Flag for restitution
     * @param array  $archiveIds Array of archive identifier
     * @param string $identifier The medona message reference
     * @param string $comment    The message comment
     *
     * @return array The result of the operation
     */
    public function setForRestitution($archiveIds, $identifier = null, $comment = null)
    {
234
235
236
237
238
239
        $senderOrg = \laabs::getToken('ORGANIZATION');
        if (!$senderOrg) {
            throw \laabs::newException('medona/invalidMessageException', "No current organization choosen");
        }

        $senderOrgRegNumber = $senderOrg->registrationNumber;
240
241
242
243
244
245
        $user = \laabs::getToken('AUTH');
        $userName = false;
        if($user) {
            $user = \laabs::callService('auth/userAccount/read_userAccountId_', $user->accountId);
            $userName = $user->accountName;
        }
Prosper De Laure's avatar
Prosper De Laure committed
246

247
248
        $archivesByOriginator = [];
        $archivesIdsByOriginator = [];
Prosper De Laure's avatar
Prosper De Laure committed
249

250
        foreach ($archiveIds as $archiveId) {
Prosper De Laure's avatar
Prosper De Laure committed
251
252
253
254
255
256
            $archive = $this->archiveController->retrieve($archiveId);
            if (!isset($archivesByOriginator[$archive->originatorOrgRegNumber])) {
                $archivesByOriginator[$archive->originatorOrgRegNumber] = [];
            }

            $archivesByOriginator[$archive->originatorOrgRegNumber][] = $archive;
257
            $archivesIdsByOriginator[$archive->originatorOrgRegNumber][] = $archive->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
258
259
        }

260
261
        $result = array('success' => array(), 'error' => array());
        $archiveRestitutionRequestController = \laabs::newController("medona/ArchiveRestitutionRequest");
Prosper De Laure's avatar
Prosper De Laure committed
262

263
        if (!$identifier) {
264
            $identifier = "archiveRestitutionRequest_".date("Y-m-d-H-i-s");
265
        }
Prosper De Laure's avatar
Prosper De Laure committed
266

267
268
269
        $reference = $identifier;
        foreach ($archivesIdsByOriginator as $originatorOrgRegNumber => $archiveIds) {
            
270
271
272
            $candidates = $this->archiveController->setForRestitution($archiveIds);
            $result["success"] = array_merge($result["success"], $candidates["success"]);
            $result["error"] = array_merge($result["error"], $candidates["error"]);
Prosper De Laure's avatar
Prosper De Laure committed
273

274
            $archivesForRestitution = [];
Prosper De Laure's avatar
Prosper De Laure committed
275

276
277
278
            foreach ($archivesByOriginator[$originatorOrgRegNumber] as $archive) {
                if (in_array($archive->archiveId, $candidates["success"])) {
                    $archivesForRestitution[] = $archive;
Prosper De Laure's avatar
Prosper De Laure committed
279
280
                }
            }
281

Alexis Ragot's avatar
Alexis Ragot committed
282
283
284
285
            if (empty($archivesForRestitution)) {
                continue;
            }

286
287
            $i = 1;
            $unique = array(
288
                'type' => 'ArchiveRestitutionRequest',
289
290
291
292
293
294
295
296
                'senderOrgRegNumber' => $senderOrgRegNumber,
                'reference' => $reference,
            );

            while ($this->sdoFactory->exists("medona/message", $unique)) {
                $i++;
                $unique['reference'] = $reference = $identifier.'_'.$i;
            }
297
298
299

            $recipientOrgRegNumber = $archivesForRestitution[0]->archiverOrgRegNumber;

300
            $archiveRestitutionRequestController->send($reference, $archivesForRestitution, $comment, $senderOrgRegNumber, $recipientOrgRegNumber, $userName);
Prosper De Laure's avatar
Prosper De Laure committed
301
302
        }

303
        return $result;
Prosper De Laure's avatar
Prosper De Laure committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    }

    /**
     * Validate archive restitution message
     * @param string $messageId The message identifier
     */
    public function validate($messageId)
    {
        $this->changeStatus($messageId, "accepted");

        $message = $this->sdoFactory->read('medona/message', array('messageId' => $messageId));
        $eventInfo = array();
        $eventInfo['type'] = "ArchiveRestitution";
        $eventInfo['senderOrgRegNumber'] = $message->senderOrgRegNumber;
        $eventInfo['recipientOrgRegNumber'] = $message->recipientOrgRegNumber;
        $eventInfo['reference'] = $message->reference;

        $this->lifeCycleJournalController->logEvent(
            'medona/acceptance',
            'medona/message',
            $message->messageId,
            $eventInfo,
            true
        );
    }

    /**
     * Validate archive restitution message
     * @param string $messageId The message identifier
     */
    public function acknowledge($messageId)
    {
        $this->changeStatus($messageId, "acknowledge");

        $message = $this->sdoFactory->read('medona/message', array('messageId' => $messageId));
339
340
341
342
343
344
345
346
347
        $requestMessage = $this->sdoFactory->find('medona/message', "type='ArchiveRestitutionRequest' AND senderOrgRegNumber='".$message->recipientOrgRegNumber."' AND replyReference='".$message->relatedReference."'")[0];

        $requestMessage->unitIdentifier = $this->sdoFactory->readChildren('medona/unitIdentifier', $requestMessage);

        foreach ($requestMessage->unitIdentifier as $unitIdentifier) {
            $this->archiveController->setStatus($unitIdentifier->objectId, 'restituted');
        }


Prosper De Laure's avatar
Prosper De Laure committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
        $eventInfo = array();
        $eventInfo['type'] = "ArchiveRestitution";
        $eventInfo['senderOrgRegNumber'] = $message->senderOrgRegNumber;
        $eventInfo['recipientOrgRegNumber'] = $message->recipientOrgRegNumber;
        $eventInfo['reference'] = $message->reference;

        $this->lifeCycleJournalController->logEvent(
            'medona/acknowledgement',
            'medona/message',
            $message->messageId,
            $eventInfo,
            true
        );
    }

    /**
     * Reject the archive restitution
     * @param string $messageId The message identifier
     * @param string $comment   The comment
     *
     * @return object The reply message
     */
    public function reject($messageId, $comment)
    {
        $this->changeStatus($messageId, "rejected");

        $message = $this->sdoFactory->read('medona/message', $messageId);
        $requestMessage = $this->sdoFactory->find('medona/message', "type='ArchiveRestitutionRequest' AND senderOrgRegNumber='".$message->recipientOrgRegNumber."' AND replyReference='".$message->relatedReference."'")[0];
        $requestMessage->unitIdentifier = $this->sdoFactory->readChildren('medona/unitIdentifier', $requestMessage);

        foreach ($requestMessage->unitIdentifier as $unitIdentifier) {
            $this->archiveController->setStatus((string) $unitIdentifier->objectId, "preserved");
        }
//
        $eventInfo = array();
        $eventInfo['type'] = "ArchiveRestitution";
        $eventInfo['senderOrgRegNumber'] = $message->senderOrgRegNumber;
        $eventInfo['recipientOrgRegNumber'] = $message->recipientOrgRegNumber;
        $eventInfo['reference'] = $message->reference;

        $this->lifeCycleJournalController->logEvent(
            'medona/rejection',
            'medona/message',
            $message->messageId,
            $eventInfo,
            true
        );
    }

    /**
     * Validate archive restitution message
     * @param string $messageId The message identifier
     */
    public function process($messageId)
    {
403
        $this->changeStatus($messageId, "validating");
Prosper De Laure's avatar
Prosper De Laure committed
404
405
406
407
408
        $message = $this->sdoFactory->read('medona/message', array("messageId" => $messageId));
        $message->active = false;

        $this->sdoFactory->update($message, "medona/message");

409
        
410
        $this->changeStatus($messageId, "validated");
Prosper De Laure's avatar
Prosper De Laure committed
411

Alexis Ragot's avatar
Alexis Ragot committed
412
        $uri = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;
Prosper De Laure's avatar
Prosper De Laure committed
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
        if (is_dir($uri)) {
            \laabs\rmdir($uri, true);
        }

        $eventInfo = array();
        $eventInfo['type'] = "ArchiveRestitution";
        $eventInfo['senderOrgRegNumber'] = $message->senderOrgRegNumber;
        $eventInfo['recipientOrgRegNumber'] = $message->recipientOrgRegNumber;
        $eventInfo['reference'] = $message->reference;

        $this->lifeCycleJournalController->logEvent(
            'medona/processing',
            'medona/message',
            $message->messageId,
            $eventInfo,
            true
        );
    }
}