ArchiveRestitution.php 15.3 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
170
171
172
173
174
175
176
177
178
179
180
181
            $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

        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);

182
183
184
185
186
187
188
189
190
191
192
193
194
            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
195
196
197
198
199
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
            $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)
    {
229
230
231
232
233
234
        $senderOrg = \laabs::getToken('ORGANIZATION');
        if (!$senderOrg) {
            throw \laabs::newException('medona/invalidMessageException', "No current organization choosen");
        }

        $senderOrgRegNumber = $senderOrg->registrationNumber;
235
236
237
238
239
240
        $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
241

242
243
        $archivesByOriginator = [];
        $archivesIdsByOriginator = [];
Prosper De Laure's avatar
Prosper De Laure committed
244

245
        foreach ($archiveIds as $archiveId) {
Prosper De Laure's avatar
Prosper De Laure committed
246
247
248
249
250
251
            $archive = $this->archiveController->retrieve($archiveId);
            if (!isset($archivesByOriginator[$archive->originatorOrgRegNumber])) {
                $archivesByOriginator[$archive->originatorOrgRegNumber] = [];
            }

            $archivesByOriginator[$archive->originatorOrgRegNumber][] = $archive;
252
            $archivesIdsByOriginator[$archive->originatorOrgRegNumber][] = $archive->archiveId;
Prosper De Laure's avatar
Prosper De Laure committed
253
254
        }

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

258
        if (!$identifier) {
259
            $identifier = "archiveRestitutionRequest_".date("Y-m-d-H-i-s");
260
        }
Prosper De Laure's avatar
Prosper De Laure committed
261

262
263
264
        $reference = $identifier;
        foreach ($archivesIdsByOriginator as $originatorOrgRegNumber => $archiveIds) {
            
265
266
267
            $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
268

269
            $archivesForRestitution = [];
Prosper De Laure's avatar
Prosper De Laure committed
270

271
272
273
            foreach ($archivesByOriginator[$originatorOrgRegNumber] as $archive) {
                if (in_array($archive->archiveId, $candidates["success"])) {
                    $archivesForRestitution[] = $archive;
Prosper De Laure's avatar
Prosper De Laure committed
274
275
                }
            }
276

Alexis Ragot's avatar
Alexis Ragot committed
277
278
279
280
            if (empty($archivesForRestitution)) {
                continue;
            }

281
282
            $i = 1;
            $unique = array(
283
                'type' => 'ArchiveRestitutionRequest',
284
285
286
287
288
289
290
291
                'senderOrgRegNumber' => $senderOrgRegNumber,
                'reference' => $reference,
            );

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

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

295
            $archiveRestitutionRequestController->send($reference, $archivesForRestitution, $comment, $senderOrgRegNumber, $recipientOrgRegNumber, $userName);
Prosper De Laure's avatar
Prosper De Laure committed
296
297
        }

298
        return $result;
Prosper De Laure's avatar
Prosper De Laure committed
299
300
301
302
303
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
    }

    /**
     * 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));
334
335
336
337
338
339
340
341
342
        $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
343
344
345
346
347
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
        $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)
    {
398
        $this->changeStatus($messageId, "validating");
Prosper De Laure's avatar
Prosper De Laure committed
399
400
401
402
403
        $message = $this->sdoFactory->read('medona/message', array("messageId" => $messageId));
        $message->active = false;

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

404
        
405
        $this->changeStatus($messageId, "validated");
Prosper De Laure's avatar
Prosper De Laure committed
406

Alexis Ragot's avatar
Alexis Ragot committed
407
        $uri = $this->messageDirectory.DIRECTORY_SEPARATOR.(string) $message->messageId;
Prosper De Laure's avatar
Prosper De Laure committed
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
        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
        );
    }
}