ArchiveRestitutionRequest.php 16.3 KB
Newer Older
Cyril Vazquez's avatar
Cyril Vazquez 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
<?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 bundle\medona\Controller;

/**
 * Trait for archive restitution
 *
 * @author Prosper DE LAURE <prosper.delaure@maarch.org>
 */
class ArchiveRestitutionRequest extends abstractMessage
{
    /**
     * Get received archive resititution message
     *
     * @return array Array of medona/message object
     */
    public function listReception()
    {
        $queryParts = array();
        $registrationNumber = $this->getCurrentRegistrationNumber();

        $queryParts[] = "type='ArchiveRestitutionRequest'";
        $queryParts[] = "recipientOrgRegNumber=$registrationNumber";
        $queryParts[] = "active=true";
        $queryParts[] = "status != 'processed' AND status != 'error' AND status != 'rejected'";

Alexandre Morin's avatar
Alexandre Morin committed
46
47
48
49
50
51
52
53
54
        $maxResults = \laabs::configuration('presentation.maarchRM')['maxResults'];
        return $this->sdoFactory->find(
            'medona/message',
            implode(' and ', $queryParts),
            null,
            false,
            false,
            $maxResults
        );
Cyril Vazquez's avatar
Cyril Vazquez committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
    }

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

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

Alexandre Morin's avatar
Alexandre Morin committed
72
73
74
75
76
77
78
79
80
        $maxResults = \laabs::configuration('presentation.maarchRM')['maxResults'];
        return $this->sdoFactory->find(
            'medona/message',
            implode(' and ', $queryParts),
            null,
            false,
            false,
            $maxResults
        );
Cyril Vazquez's avatar
Cyril Vazquez committed
81
82
83
84
85
86
87
88
89
90
91
92
    }

    /**
     * Get sending archive resitution message
     * @param string $sender
     * @param string $recipient
     * @param string $fromDate
     * @param string $toDate
     * @param string $reference
     *
     * @return array Array of medona/message object
     */
Alexandre Morin's avatar
Alexandre Morin committed
93
94
95
96
97
98
99
    public function listSending(
        $sender = false,
        $recipient = false,
        $fromDate = false,
        $toDate = false,
        $reference = false
    ) {
Cyril Vazquez's avatar
Cyril Vazquez committed
100
101
102
103
104
105
        $registrationNumber = $this->getCurrentRegistrationNumber();

        $queryParts[] = "type='ArchiveRestitutionRequest'";
        $queryParts[] = "senderOrgRegNumber=$registrationNumber";
        $queryParts[] = "active=true";

Alexandre Morin's avatar
Alexandre Morin committed
106
107
108
109
110
111
112
113
114
        $maxResults = \laabs::configuration('presentation.maarchRM')['maxResults'];
        return $this->sdoFactory->find(
            'medona/message',
            '('.implode(') and (', $queryParts).')',
            null,
            false,
            false,
            $maxResults
        );
Cyril Vazquez's avatar
Cyril Vazquez committed
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
151
    }

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

        $res = array();
        $queryParts = array();

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

        $res['received'] = $this->sdoFactory->count('medona/message', implode(' and ', $queryParts));

        $queryParts["registrationNumber"] = "senderOrgRegNumber=$registrationNumber";
        $res['sent'] = $this->sdoFactory->count('medona/message', implode(' and ', $queryParts));

        return $res;
    }

    /**
     * Send a new a new restitution request
     * @param string $reference    The message identifier
     * @param array  $archives     An array of archives
     * @param string $comment      The request comment
     * @param string $senderOrg    The requesting org
     * @param string $recipientOrg The requesting org
     * @param string $userName     The requester user name
     *
     * @return The reply message generated
     */
Alexandre Morin's avatar
Alexandre Morin committed
152
153
154
155
156
157
158
159
    public function send(
        $reference,
        $archives,
        $comment = false,
        $senderOrg = false,
        $recipientOrg = false,
        $userName = false
    ) {
Cyril Vazquez's avatar
Cyril Vazquez committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
334
335
336
337
338
339
340
341
342
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
        if (!is_array($archives)) {
            $archives = array($archives);
        }

        $message = \laabs::newInstance('medona/message');
        $message->messageId = \laabs::newId();

        $message->schema = "medona";
        if (\laabs::hasBundle('seda')) {
            $message->schema = "seda";
        }

        $message->type = "ArchiveRestitutionRequest";
        $message->date = \laabs::newDatetime(null, "UTC");
        $message->receptionDate = $message->date;
        $message->reference = $reference;
        $message->status = "sent";

        $message->comment[] = $comment;

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

        try {
            $message->unitIdentifier = array();
            foreach ($archives as $archive) {
                $unitIdentifier = \laabs::newInstance("medona/unitIdentifier");
                $unitIdentifier->messageId = $message->messageId;
                $unitIdentifier->objectClass = "recordsManagement/archive";
                $unitIdentifier->objectId = (string) $archive->archiveId;

                $message->unitIdentifier[] = $unitIdentifier;
            }

            if ($message->schema != 'medona') {
                $archiveRestitutionRequestController = \laabs::newController($message->schema.'/ArchiveRestitutionRequest');
                $archiveRestitutionRequestController->send($message);
            } else {
                $archiveRestitutionRequest = $this->sendMessage($message);
                $message->object = $archiveRestitutionRequest;

                $archiveRestitutionRequest->requester = $this->sendOrganization($message->senderOrg);
                if ($userName) {
                    $archiveRestitutionRequest->requester->userName = $userName;
                }
                
                $archiveRestitutionRequest->archivalAgency = $this->sendOrganization($message->recipientOrg);

                $this->generate($message);
                $this->save($message);
            }

            $operationResult = true;

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

            throw $e;
        }

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

        return $message;
    }

    /**
     * Send a new a new restitution request
     * @param string         $reference      The message reference
     * @param medona/message $requestMessage The request message
     *
     * @return The reply message generated
     */
    public function sendFromRequestMessage($reference, $requestMessage)
    {
        $this->readOrgs($requestMessage);

        $message = \laabs::newInstance('medona/message');
        $message->messageId = \laabs::newId();

        $message->schema = $requestMessage->schema;
        $message->type = "ArchiveRestitutionRequest";
        $message->date = \laabs::newDatetime(null, "UTC");
        $message->reference = $reference;
        $message->status = "sent";

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

        try {
            if ($message->schema != 'medona') {
                $archiveRestitutionRequestController = \laabs::newController($message->schema.'/ArchiveRestitutionRequest');
                $archiveRestitutionRequestController->send($message);
            } else {
                $archiveRestitutionRequest = $this->sendMessage($message);
                $message->object = $archiveRestitutionRequest;

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

                $this->generate($message);
                $this->save($message);
            }

            $message->unitIdentifier = $this->sdoFactory->readChildren('medona/unitIdentifier', $requestMessage);
            foreach ($message->unitIdentifier as $unitIdentifier) {
                $unitIdentifier->messageId = $message->messageId;
            }
            $operationResult = true;

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

            throw $e;
        }

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

    /**
     * Accept archive restitution request message
     * @param string $messageId The message identifier
     *
     * @return medona/message The medon reply message
     */
    public function accept($messageId)
    {
        $this->changeStatus($messageId, "accepted");

        $message = $this->sdoFactory->read('medona/message', array('messageId' => $messageId));
        $message->unitIdentifier = $this->sdoFactory->readChildren('medona/unitIdentifier', $message);

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

        $archiveRestitutionRequestReplyController = \laabs::newController('medona/ArchiveRestitutionRequestReply');
        $replyMessage = $archiveRestitutionRequestReplyController->send($message, "000");

        return $replyMessage;
    }

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

        $message = $this->sdoFactory->read('medona/message', array('messageId' => $messageId));
        $message->unitIdentifier = $this->sdoFactory->readChildren('medona/unitIdentifier', $message);

        foreach ((array) $message->unitIdentifier as $unitIdentifier) {
            $this->archiveController->setStatus((string) $unitIdentifier->objectId, "preserved");
        }


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

        $archiveRestitutionRequestReplyController = \laabs::newController('medona/ArchiveRestitutionRequestReply');
        $replyMessage = $archiveRestitutionRequestReplyController->send($messageId, "400", $comment);

        return $replyMessage;
    }

    /**
     * Process the messages
     *
     * @return medona/message $message
     */
    public function processBatch()
    {
        $results = array();

369
        $messageIds = $this->sdoFactory->index(
Alexandre Morin's avatar
Alexandre Morin committed
370
            "medona/message",
371
            ["messageId"],
Alexandre Morin's avatar
Alexandre Morin committed
372
373
374
            "status='accepted' AND type='ArchiveRestitutionRequest' AND active=true"
        );

375
376
377
378
379
380
381
382
        foreach ($messageIds as $messageId) {
            // Avoid parallel processing
            $message = $this->sdoFactory->read('medona/message', (string) $messageId);
            if (!$message->status != 'accepted') {
                continue;
            }
            $this->changeStatus($message->messageId, "processing");

Cyril Vazquez's avatar
Cyril Vazquez committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
            try {
                $results[(string) $message->messageId] = $this->process((string)$message->messageId);
            } catch (\Exception $e) {
                $results[(string) $message->messageId] = $e;
            }
        }

        return $results;
    }

    /**
     * Validate message against schema and rules
     * @param medona/message $message
     *
     * @return the result of process
     */
    public function process($message)
    {
        if (is_scalar($message)) {
            $messageId = $message;
            $message = $this->read($messageId);
        }

        $this->changeStatus($message->messageId, "processing");

        $archives = array();

        foreach ((array) $message->unitIdentifier as $unitIdentifier) {
            $archive = $this->archiveController->restitute($unitIdentifier->objectId);

            if ($archive == null) {
                continue;
            }

            $archives[] = $archive;
        }

        $logMessage = ["message" => "%s archives are restituted", "variables"=> count($archives)];
        \laabs::notify(\bundle\audit\AUDIT_ENTRY_OUTPUT, $logMessage);

        try {
            $archiveRestitutionController = \laabs::newController('medona/ArchiveRestitution');
            $archiveRestitutionController->send($message, $archives);

            $operationResult = true;
        } catch (\Exception $e) {
            $message->status = "error";
            $operationResult = false;
431
            $this->update($message);
Cyril Vazquez's avatar
Cyril Vazquez committed
432
433
434
435
436
437
438
439
440
441
442
            throw $e;
        }

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

443
        $this->changeStatus($message->messageId, "processed");
Cyril Vazquez's avatar
Cyril Vazquez committed
444
445
446
447
448
449
450
451
452
453
454
455
456

        return true;
    }

    /**
     * Destruct all restitued archives of restitution message
     *
     * @return the result of process
     */
    public function destructAll()
    {
        $results = array();

Alexandre Morin's avatar
Alexandre Morin committed
457
458
459
460
461
        $restitutionIds = $this->sdoFactory->index(
            'medona/message',
            array('messageId'),
            'type = "ArchiveRestitution" AND status = "validated"'
        );
Cyril Vazquez's avatar
Cyril Vazquez committed
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480

        foreach ($restitutionIds as $restitutionId) {
            $this->changeStatus($restitutionId, "processing");
            $results[(string) $restitutionId] = $this->destruct($restitutionId);
            $this->changeStatus($restitutionId, "processed");
        }

        return $results;
    }

    /**
     * Destruction of restitued archive of message
     * @param string $messageId The restitution message identifier
     *
     * @return array array of archive
     */
    public function destruct($messageId)
    {
        $restitution = $this->sdoFactory->read('medona/message', array("messageId" => $messageId));
Alexandre Morin's avatar
Alexandre Morin committed
481
482
483
484
        $restitutionRequest = $this->sdoFactory->find(
            'medona/message',
            "type='ArchiveRestitutionRequest' AND senderOrgRegNumber='".$restitution->recipientOrgRegNumber."' AND replyReference='".$restitution->relatedReference."'"
        )[0];
Cyril Vazquez's avatar
Cyril Vazquez committed
485

Alexandre Morin's avatar
Alexandre Morin committed
486
487
488
489
        $restitutionRequest->unitIdentifier = $this->sdoFactory->readChildren(
            'medona/unitIdentifier',
            $restitutionRequest
        );
Cyril Vazquez's avatar
Cyril Vazquez committed
490
491
492
493
494
495
496
497
498
499
500
501

        $removedArchiveIds = [];
        foreach ($restitutionRequest->unitIdentifier as $unitIdentifier) {
            $archive = $this->archiveController->destruct($unitIdentifier->objectId);
            if (count($archive["success"]) > 0) {
                $removedArchiveIds[] = (string)$archive["success"][0]->archiveId;
            }
        }

        return $removedArchiveIds;
    }
}