Skip to content

Commit

Permalink
Added digital post test command
Browse files Browse the repository at this point in the history
  • Loading branch information
rimi-itk committed Feb 1, 2024
1 parent bb6b90b commit 0186484
Show file tree
Hide file tree
Showing 5 changed files with 176 additions and 7 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ before starting to add changes. Use example [placed in the end of the page](#exa
## [Unreleased]

- CprFetchData adding ajax error fix
- [#84](https://github.com/OS2Forms/os2forms/pull/84)
Added digital post test command.

## [3.14.0]

Expand Down
11 changes: 10 additions & 1 deletion modules/os2forms_digital_post/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,20 @@ graphical overview of jobs in the queue.

## Beskedfordeler

Thie digital post module depends on [Beskedfordeler for
The digital post module depends on [Beskedfordeler for
Drupal](https://github.com/itk-dev/beskedfordeler-drupalon) to get get
information on how or why not a digital post has been delivered (cf.
[BeskedfordelerEventSubscriber](src/EventSubscriber/BeskedfordelerEventSubscriber.php)).

See the [documentation for Beskedfordeler for
Drupal](https://github.com/itk-dev/beskedfordeler-drupal#beskedfordeler) for
details on how to set up the Beskedfordeler module.

## Testing digital post

This module contains a simple Drush command for sending digital post to a list
of recipients:

``` shell
drush os2forms-digital-post:test:send --help
```
9 changes: 9 additions & 0 deletions modules/os2forms_digital_post/drush.services.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
services:
Drupal\os2forms_digital_post\Drush\Commands\DigitalPostTestCommands:
arguments:
- '@Drupal\os2forms_digital_post\Helper\DigitalPostHelper'
- '@token'
- '@plugin.manager.entity_print.print_engine'
- '@Drupal\os2forms_digital_post\Helper\Settings'
tags:
- { name: drush.command }
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
<?php

namespace Drupal\os2forms_digital_post\Drush\Commands;

use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Utility\Token;
use Drupal\entity_print\Plugin\EntityPrintPluginManagerInterface;
use Drupal\os2forms_digital_post\Helper\DigitalPostHelper;
use Drupal\os2forms_digital_post\Helper\Settings;
use Drupal\os2forms_digital_post\Model\Document;
use Drush\Commands\DrushCommands;
use ItkDev\Serviceplatformen\Service\SF1601\SF1601;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;

/**
* Test commands for digital post.
*/
class DigitalPostTestCommands extends DrushCommands {

/**
* Constructor.
*/
public function __construct(
private readonly DigitalPostHelper $digitalPostHelper,
private readonly Token $token,
private readonly EntityPrintPluginManagerInterface $entityPrintPluginManager,
private readonly Settings $digitalPostSettings
) {
}

/**
* Send digital post.
*
* @param array $recipients
* The recipients (CPR or CVR).
* @param array $options
* The options.
*
* @option string subject
* The subject. Can contain HTML.
* @option string message
* The message to send. Can contain HTML.
* @option string digital-post-type
* The digital post type to use.
* @option bool dump-digital-post-settings
* Dump digital post settings.
*
* @phpstan-param array<string> $recipients
* @phpstan-param array<string, mixed> $options
*
* @command os2forms-digital-post:test:send
* @usage os2forms-digital-post:test:send --help
*/
public function send(array $recipients, array $options = [
'subject' => 'os2forms_digital_post',
'message' => 'This is a test message from os2forms_digital_post sent on [current-date:html_datetime].',
'digital-post-type' => SF1601::TYPE_AUTOMATISK_VALG,
'dump-digital-post-settings' => FALSE,
]): void {
if ($options['dump-digital-post-settings']) {
$this->dumpDigitalPostSettings();
}

$subject = $this->token->replace($options['subject']);
$message = $this->token->replace($options['message']);
$senderLabel = $this->token->replace('os2forms_digital_post');
$messageLabel = $this->token->replace('os2forms_digital_post [current-date:html_datetime]');

$html = sprintf('<h1>%s</h1>%s', $subject, $message);

/** @var \Drupal\entity_print\Plugin\EntityPrint\PrintEngine\PdfEngineBase $printer */
$printer = $this->entityPrintPluginManager->createInstance('dompdf');
$printer->addPage($html);
$content = $printer->getBlob();

$document = new Document(
$content,
Document::MIME_TYPE_PDF,
'os2forms_digital_post.pdf'
);

$type = $options['digital-post-type'];
if (!in_array($type, SF1601::TYPES, TRUE)) {
$quote = static fn ($value) => var_export($value, TRUE);
throw new InvalidArgumentException(sprintf('Invalid type: %s. Must be one of %s.', $quote($type), implode(', ', array_map($quote, SF1601::TYPES))));
}

$this->output()->writeln(sprintf('Type: %s', $type));

foreach ($recipients as $recipient) {
try {
$this->output()->writeln(sprintf('Recipient: %s', $recipient));
$recipientLookupResult = $this->digitalPostHelper->lookupRecipient($recipient);
$actions = [];

$meMoMessage = $this->digitalPostHelper->getMeMoHelper()->buildMessage($recipientLookupResult, $senderLabel,
$messageLabel, $document, $actions);
$forsendelse = $this->digitalPostHelper->getForsendelseHelper()->buildForsendelse($recipientLookupResult,
$messageLabel, $document);

$this->digitalPostHelper->sendDigitalPost(
$type,
$meMoMessage,
$forsendelse
);

$this->output()->writeln(sprintf('Digital post sent to %s', $recipient));
}
catch (\Throwable $throwable) {
$this->output()->writeln([
sprintf('Error sending digital post to %s:', $recipient),
$throwable->getMessage(),
]);
if ($throwable instanceof ClientExceptionInterface) {
$response = $throwable->getResponse();
$this->output()->writeln([
'',
'Response',
Yaml::encode([
'headers' => $response->getHeaders(FALSE),
'content' => $response->getContent(FALSE),
]),
]);
}
}
}
}

/**
* Dump digital post settings.
*/
private function dumpDigitalPostSettings(): void {
$this->writeln([
'Digital post settings',
Yaml::encode([
'testMode' => $this->digitalPostSettings->getTestMode(),
'sender' => $this->digitalPostSettings->getSender(),
'certificate' => $this->digitalPostSettings->getCertificate(),
'processing' => $this->digitalPostSettings->getProcessing(),
]),
'',
]);
}

}
15 changes: 9 additions & 6 deletions modules/os2forms_digital_post/src/Helper/DigitalPostHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,15 @@ public function __construct(
* The MeMo message.
* @param \Oio\Fjernprint\ForsendelseI|null $forsendelse
* The forsendelse if any.
* @param \Drupal\webform\WebformSubmissionInterface $submission
* The submission.
* @param null|\Drupal\webform\WebformSubmissionInterface $submission
* A submission used for hooking up with Beskedfordeler.
*
* @return array
* [The response, The kombi post message].
*
* @phpstan-return array<int, mixed>
*/
public function sendDigitalPost(string $type, Message $message, ?ForsendelseI $forsendelse, WebformSubmissionInterface $submission): array {
public function sendDigitalPost(string $type, Message $message, ?ForsendelseI $forsendelse, WebformSubmissionInterface $submission = NULL): array {
$senderSettings = $this->settings->getSender();
$options = [
'test_mode' => (bool) $this->settings->getTestMode(),
Expand All @@ -66,7 +66,10 @@ public function sendDigitalPost(string $type, Message $message, ?ForsendelseI $f
$transactionId = Serializer::createUuid();
$response = $service->kombiPostAfsend($transactionId, $type, $message, $forsendelse);

$this->beskedfordelerHelper->createMessage($submission->id(), $message, (string) $response->getContent());
$content = (string) $response->getContent();
if (NULL !== $submission) {
$this->beskedfordelerHelper->createMessage($submission->id(), $message, $content);
}

return [$response, $service->getLastKombiMeMoMessage()];
}
Expand All @@ -92,7 +95,7 @@ public function lookupCpr(string $cpr): CprLookupResult {
}
$lookupResult = $instance->lookup($cpr);
if (!$lookupResult->isSuccessful()) {
throw new RuntimeException('Cannot lookup CPR');
throw new RuntimeException('Cannot look up CPR');
}

return $lookupResult;
Expand All @@ -108,7 +111,7 @@ public function lookupCvr(string $cvr): CompanyLookupResult {
}
$lookupResult = $instance->lookup($cvr);
if (!$lookupResult->isSuccessful()) {
throw new RuntimeException('Cannot lookup CVR');
throw new RuntimeException('Cannot look up CVR');
}

return $lookupResult;
Expand Down

0 comments on commit 0186484

Please sign in to comment.