Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added digital post test command #84

Merged
merged 2 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
13 changes: 11 additions & 2 deletions 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
Drupal](https://github.com/itk-dev/beskedfordeler-drupalon) to get get
The digital post module depends on [Beskedfordeler for
Drupal](https://github.com/itk-dev/beskedfordeler-drupal) 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,152 @@
<?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\Component\Console\Style\SymfonyStyle;
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 {
$io = new SymfonyStyle($this->input(), $this->output());

if ($options['dump-digital-post-settings']) {
$this->dumpDigitalPostSettings($io);
}

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

$io->section('Digital post');
$io->definitionList(
['Type' => $type],
['Subject' => $subject],
['Message' => $message]
);

foreach ($recipients as $recipient) {
try {
$io->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
);

$io->success(sprintf('Digital post sent to %s', $recipient));
}
catch (\Throwable $throwable) {
$io->error(sprintf('Error sending digital post to %s:', $recipient));
$io->writeln($throwable->getMessage());

if ($throwable instanceof ClientExceptionInterface) {
$response = $throwable->getResponse();
$io->section('Response');
$io->writeln(
Yaml::encode([
'headers' => $response->getHeaders(FALSE),
'content' => $response->getContent(FALSE),
]),
);
}
}
}
}

/**
* Dump digital post settings.
*/
private function dumpDigitalPostSettings(SymfonyStyle $io): void {
$io->section('Digital post settings');
$io->writeln([
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
Loading