mirror of
https://github.com/FOSSBilling/FOSSBilling.git
synced 2026-12-01 12:48:08 +09:00
Attach PDF invoices to invoice emails (#3913)
* Attach PDF invoices to invoice emails (#1724) Adds generic file-attachment support to the email pipeline (Mail, QueuedEmail, Email\Service) and wires it into invoice notifications via a new "Attach PDF Copy to Invoice Emails" setting, so clients who pay by bank transfer can view the invoice without logging in. Also carries the same attachment into the sent-email activity log so a later "resend" (client or admin) reattaches the PDF instead of dropping it. * Address PR review: avoid blob hydration in email history list, fix checkbox uncheck - ActivityClientEmailRepository::getSearchQueryBuilder() now selects a partial entity that excludes attachment_content, so the paginated admin/client email history list no longer hydrates every PDF into memory just to render has_attachment. Verified against a real Doctrine EntityManager that the DQL parses, the generated SQL excludes the blob column, and toApiArray() still works correctly on the partial entity. - mod_invoice_settings.html.twig: add the hidden-input-before-checkbox pattern already used elsewhere in this codebase (e.g. mod_client_new_form.html.twig), so unchecking "Attach PDF Copy to Invoice Emails" actually persists as disabled instead of being silently dropped from the form submission.
This commit is contained in:
1 parent
feb6794a80
commit
d144dfdc07
16 files changed
+731
-38
No files matched your search
@@ -304,7 +304,7 @@ LOCK TABLES `setting` WRITE;
|
||||
|
||||
INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`)
|
||||
VALUES
|
||||
(1,'last_patch','85',0,NULL,NULL,NOW(),NOW()),
|
||||
(1,'last_patch','87',0,NULL,NULL,NOW(),NOW()),
|
||||
(2,'company_name','Company Name',0,NULL,NULL,NOW(),NOW()),
|
||||
(3,'company_email','support@yourcompany.com',0,NULL,NULL,NOW(),NOW()),
|
||||
(4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,NOW(),NOW()),
|
||||
|
||||
@@ -45,6 +45,9 @@ CREATE TABLE `activity_client_email` (
|
||||
`subject` varchar(255) DEFAULT NULL,
|
||||
`content_html` text,
|
||||
`content_text` text,
|
||||
`attachment_name` varchar(255) DEFAULT NULL,
|
||||
`attachment_content` longblob DEFAULT NULL,
|
||||
`attachment_mime` varchar(100) DEFAULT NULL,
|
||||
`created_at` datetime DEFAULT NULL,
|
||||
`updated_at` datetime DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
@@ -706,6 +709,9 @@ CREATE TABLE `email_queue` (
|
||||
`priority` int(11) DEFAULT NULL,
|
||||
`tries` int(11) NOT NULL,
|
||||
`status` varchar(20) NOT NULL,
|
||||
`attachment_name` varchar(255) DEFAULT NULL,
|
||||
`attachment_content` longblob DEFAULT NULL,
|
||||
`attachment_mime` varchar(100) DEFAULT NULL,
|
||||
`created_at` datetime NOT NULL,
|
||||
`updated_at` datetime NOT NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
|
||||
@@ -100,6 +100,18 @@ class Mail
|
||||
$this->email->addReplyTo($replyToAddresses);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach a file to the email message.
|
||||
*
|
||||
* @param string $content the raw contents of the file to attach
|
||||
* @param string $name the file name shown to the recipient (e.g. 'invoice.pdf')
|
||||
* @param string $contentType the MIME type of the attachment (e.g. 'application/pdf')
|
||||
*/
|
||||
public function attach(string $content, string $name, string $contentType): void
|
||||
{
|
||||
$this->email->attach($content, $name, $contentType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the priority of the email message. Can be an integer between 1 and 5, with 1 being the highest priority.
|
||||
* It's recommended to use Symfony's pre-defined constants instead of a specific integer, but either should work. (Example: Email::PRIORITY_HIGH).
|
||||
|
||||
@@ -494,6 +494,8 @@ class UpdatePatcher implements InjectionAwareInterface
|
||||
83 => 'patch83',
|
||||
84 => 'patch84',
|
||||
85 => 'patch85',
|
||||
86 => 'patch86',
|
||||
87 => 'patch87',
|
||||
];
|
||||
ksort($patches, SORT_NATURAL);
|
||||
|
||||
@@ -2291,6 +2293,41 @@ class UpdatePatcher implements InjectionAwareInterface
|
||||
}
|
||||
}
|
||||
|
||||
private function patch86(): void
|
||||
{
|
||||
// Allows queued emails (e.g. invoice notifications) to carry a file attachment such as a PDF copy.
|
||||
// @see https://github.com/FOSSBilling/FOSSBilling/issues/1724
|
||||
if (!$this->tableHasColumn('email_queue', 'attachment_name')) {
|
||||
$this->executeSql('ALTER TABLE `email_queue` ADD COLUMN `attachment_name` varchar(255) DEFAULT NULL');
|
||||
}
|
||||
|
||||
if (!$this->tableHasColumn('email_queue', 'attachment_content')) {
|
||||
$this->executeSql('ALTER TABLE `email_queue` ADD COLUMN `attachment_content` longblob DEFAULT NULL');
|
||||
}
|
||||
|
||||
if (!$this->tableHasColumn('email_queue', 'attachment_mime')) {
|
||||
$this->executeSql('ALTER TABLE `email_queue` ADD COLUMN `attachment_mime` varchar(100) DEFAULT NULL');
|
||||
}
|
||||
}
|
||||
|
||||
private function patch87(): void
|
||||
{
|
||||
// Carries the same attachment (e.g. a PDF invoice) into the sent-email activity log, so
|
||||
// resending a logged email (client or admin "resend") can reattach it.
|
||||
// @see https://github.com/FOSSBilling/FOSSBilling/issues/1724
|
||||
if (!$this->tableHasColumn('activity_client_email', 'attachment_name')) {
|
||||
$this->executeSql('ALTER TABLE `activity_client_email` ADD COLUMN `attachment_name` varchar(255) DEFAULT NULL');
|
||||
}
|
||||
|
||||
if (!$this->tableHasColumn('activity_client_email', 'attachment_content')) {
|
||||
$this->executeSql('ALTER TABLE `activity_client_email` ADD COLUMN `attachment_content` longblob DEFAULT NULL');
|
||||
}
|
||||
|
||||
if (!$this->tableHasColumn('activity_client_email', 'attachment_mime')) {
|
||||
$this->executeSql('ALTER TABLE `activity_client_email` ADD COLUMN `attachment_mime` varchar(100) DEFAULT NULL');
|
||||
}
|
||||
}
|
||||
|
||||
private function generateDownloadableStoredFilename(): string
|
||||
{
|
||||
do {
|
||||
|
||||
@@ -13,6 +13,7 @@ declare(strict_types=1);
|
||||
namespace Box\Mod\Activity;
|
||||
|
||||
use Doctrine\DBAL\Connection;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use FOSSBilling\InjectionAwareInterface;
|
||||
|
||||
class Service implements InjectionAwareInterface
|
||||
@@ -209,7 +210,7 @@ class Service implements InjectionAwareInterface
|
||||
return [$sql, $params];
|
||||
}
|
||||
|
||||
public function logEmail($subject, $clientId = null, $sender = null, $recipients = null, $content_html = null, $content_text = null): bool
|
||||
public function logEmail($subject, $clientId = null, $sender = null, $recipients = null, $content_html = null, $content_text = null, ?array $attachment = null): bool
|
||||
{
|
||||
$this->getDbal()->insert('activity_client_email', [
|
||||
'client_id' => $clientId,
|
||||
@@ -218,7 +219,12 @@ class Service implements InjectionAwareInterface
|
||||
'subject' => $subject,
|
||||
'content_html' => $content_html,
|
||||
'content_text' => $content_text,
|
||||
'attachment_name' => $attachment['name'] ?? null,
|
||||
'attachment_content' => $attachment['content'] ?? null,
|
||||
'attachment_mime' => $attachment['mime'] ?? ($attachment !== null ? 'application/octet-stream' : null),
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
], [
|
||||
'attachment_content' => Types::BLOB,
|
||||
]);
|
||||
|
||||
return true;
|
||||
|
||||
@@ -68,7 +68,10 @@ test('log email', function (): void {
|
||||
&& $values['subject'] === $data['subject']
|
||||
&& $values['content_html'] === $data['content_html']
|
||||
&& $values['content_text'] === $data['content_text']
|
||||
&& isset($values['created_at'])))
|
||||
&& $values['attachment_name'] === null
|
||||
&& $values['attachment_content'] === null
|
||||
&& $values['attachment_mime'] === null
|
||||
&& isset($values['created_at'])), Mockery::any())
|
||||
->andReturn(1);
|
||||
|
||||
$di['dbal'] = $dbalMock;
|
||||
@@ -78,6 +81,38 @@ test('log email', function (): void {
|
||||
expect($result)->toBeTrue();
|
||||
});
|
||||
|
||||
test('log email stores the given attachment', function (): void {
|
||||
$service = new Box\Mod\Activity\Service();
|
||||
$data = [
|
||||
'client_id' => 1,
|
||||
'sender' => 'sender',
|
||||
'recipients' => 'recipients',
|
||||
'subject' => 'subject',
|
||||
'content_html' => 'html',
|
||||
'content_text' => 'text',
|
||||
];
|
||||
$attachment = [
|
||||
'content' => '%PDF-1.4 fake invoice contents',
|
||||
'name' => 'Invoice-BB0001.pdf',
|
||||
'mime' => 'application/pdf',
|
||||
];
|
||||
|
||||
$di = container();
|
||||
$dbalMock = Mockery::mock(Doctrine\DBAL\Connection::class);
|
||||
$dbalMock->shouldReceive('insert')
|
||||
->once()
|
||||
->with('activity_client_email', Mockery::on(static fn (array $values) => $values['attachment_name'] === $attachment['name']
|
||||
&& $values['attachment_content'] === $attachment['content']
|
||||
&& $values['attachment_mime'] === $attachment['mime']), Mockery::on(static fn (array $types) => ($types['attachment_content'] ?? null) === Doctrine\DBAL\Types\Types::BLOB))
|
||||
->andReturn(1);
|
||||
|
||||
$di['dbal'] = $dbalMock;
|
||||
$service->setDi($di);
|
||||
|
||||
$result = $service->logEmail($data['subject'], $data['client_id'], $data['sender'], $data['recipients'], $data['content_html'], $data['content_text'], $attachment);
|
||||
expect($result)->toBeTrue();
|
||||
});
|
||||
|
||||
test('to api array', function (): void {
|
||||
$service = new Box\Mod\Activity\Service();
|
||||
$clientHistoryModel = new Model_ActivityClientHistory();
|
||||
|
||||
@@ -55,6 +55,15 @@ class ActivityClientEmail implements ApiArrayInterface, TimestampInterface
|
||||
#[ORM\Column(name: 'content_text', type: Types::TEXT, nullable: true)]
|
||||
private ?string $contentText = null;
|
||||
|
||||
#[ORM\Column(name: 'attachment_name', type: Types::STRING, length: 255, nullable: true)]
|
||||
private ?string $attachmentName = null;
|
||||
|
||||
#[ORM\Column(name: 'attachment_content', type: Types::BLOB, nullable: true)]
|
||||
private mixed $attachmentContent = null;
|
||||
|
||||
#[ORM\Column(name: 'attachment_mime', type: Types::STRING, length: 100, nullable: true)]
|
||||
private ?string $attachmentMime = null;
|
||||
|
||||
public function toApiArray(): array
|
||||
{
|
||||
return [
|
||||
@@ -65,6 +74,7 @@ class ActivityClientEmail implements ApiArrayInterface, TimestampInterface
|
||||
'subject' => $this->subject,
|
||||
'content_html' => Tools::sanitizeContent($this->contentHtml ?? ''),
|
||||
'content_text' => $this->contentText,
|
||||
'has_attachment' => $this->attachmentName !== null,
|
||||
'created_at' => $this->getCreatedAt()?->format('Y-m-d H:i:s'),
|
||||
'updated_at' => $this->getUpdatedAt()?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
@@ -146,4 +156,44 @@ class ActivityClientEmail implements ApiArrayInterface, TimestampInterface
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAttachmentName(): ?string
|
||||
{
|
||||
return $this->attachmentName;
|
||||
}
|
||||
|
||||
public function setAttachmentName(?string $attachmentName): self
|
||||
{
|
||||
$this->attachmentName = $attachmentName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAttachmentContent(): ?string
|
||||
{
|
||||
if (is_resource($this->attachmentContent)) {
|
||||
return stream_get_contents($this->attachmentContent) ?: null;
|
||||
}
|
||||
|
||||
return $this->attachmentContent;
|
||||
}
|
||||
|
||||
public function setAttachmentContent(?string $attachmentContent): self
|
||||
{
|
||||
$this->attachmentContent = $attachmentContent;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAttachmentMime(): ?string
|
||||
{
|
||||
return $this->attachmentMime;
|
||||
}
|
||||
|
||||
public function setAttachmentMime(?string $attachmentMime): self
|
||||
{
|
||||
$this->attachmentMime = $attachmentMime;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,15 @@ class QueuedEmail implements ApiArrayInterface, TimestampInterface
|
||||
#[ORM\Column(type: Types::STRING, length: 20, options: ['default' => self::STATUS_PENDING])]
|
||||
private string $status = self::STATUS_PENDING;
|
||||
|
||||
#[ORM\Column(name: 'attachment_name', type: Types::STRING, length: 255, nullable: true)]
|
||||
private ?string $attachmentName = null;
|
||||
|
||||
#[ORM\Column(name: 'attachment_content', type: Types::BLOB, nullable: true)]
|
||||
private mixed $attachmentContent = null;
|
||||
|
||||
#[ORM\Column(name: 'attachment_mime', type: Types::STRING, length: 100, nullable: true)]
|
||||
private ?string $attachmentMime = null;
|
||||
|
||||
public function toApiArray(): array
|
||||
{
|
||||
return [
|
||||
@@ -81,6 +90,7 @@ class QueuedEmail implements ApiArrayInterface, TimestampInterface
|
||||
'to_name' => $this->toName,
|
||||
'status' => $this->status,
|
||||
'tries' => $this->tries,
|
||||
'has_attachment' => $this->attachmentName !== null,
|
||||
'created_at' => $this->getCreatedAt()?->format('Y-m-d H:i:s'),
|
||||
'updated_at' => $this->getUpdatedAt()?->format('Y-m-d H:i:s'),
|
||||
];
|
||||
@@ -222,4 +232,44 @@ class QueuedEmail implements ApiArrayInterface, TimestampInterface
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAttachmentName(): ?string
|
||||
{
|
||||
return $this->attachmentName;
|
||||
}
|
||||
|
||||
public function setAttachmentName(?string $attachmentName): self
|
||||
{
|
||||
$this->attachmentName = $attachmentName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAttachmentContent(): ?string
|
||||
{
|
||||
if (is_resource($this->attachmentContent)) {
|
||||
return stream_get_contents($this->attachmentContent) ?: null;
|
||||
}
|
||||
|
||||
return $this->attachmentContent;
|
||||
}
|
||||
|
||||
public function setAttachmentContent(?string $attachmentContent): self
|
||||
{
|
||||
$this->attachmentContent = $attachmentContent;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAttachmentMime(): ?string
|
||||
{
|
||||
return $this->attachmentMime;
|
||||
}
|
||||
|
||||
public function setAttachmentMime(?string $attachmentMime): self
|
||||
{
|
||||
$this->attachmentMime = $attachmentMime;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,11 @@ class ActivityClientEmailRepository extends EntityRepository
|
||||
*/
|
||||
public function getSearchQueryBuilder(array $data = []): QueryBuilder
|
||||
{
|
||||
// Excludes the attachment_content blob: list responses only need has_attachment
|
||||
// (derived from attachmentName), and hydrating every PDF for a page of results
|
||||
// would pull megabytes into memory just to render a list.
|
||||
$qb = $this->createQueryBuilder('e')
|
||||
->select('partial e.{id, clientId, sender, recipients, subject, contentHtml, contentText, attachmentName, attachmentMime, createdAt, updatedAt}')
|
||||
->orderBy('e.id', 'DESC');
|
||||
|
||||
if (!empty($data['id'])) {
|
||||
|
||||
@@ -148,10 +148,11 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
}
|
||||
$vars = $data;
|
||||
unset($vars['to'], $vars['to_client'], $vars['to_staff'], $vars['to_name'], $vars['from'], $vars['from_name'], $vars['to_admin']);
|
||||
unset($vars['default_description'], $vars['default_subject'], $vars['default_template'], $vars['code'], $vars['send_now'], $vars['throw_exceptions']);
|
||||
unset($vars['default_description'], $vars['default_subject'], $vars['default_template'], $vars['code'], $vars['send_now'], $vars['throw_exceptions'], $vars['attachment']);
|
||||
|
||||
$send_now = $data['send_now'] ?? false;
|
||||
$throw_exceptions = $data['throw_exceptions'] ?? false;
|
||||
$attachment = $data['attachment'] ?? null;
|
||||
|
||||
$template = $this->getOrCreateTemplateByCode($data['code'], $data);
|
||||
|
||||
@@ -230,20 +231,20 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
|
||||
$to = $staff['email'];
|
||||
$to_name = $staff['name'];
|
||||
$sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, null, $staff['id'], $send_now, $throw_exceptions);
|
||||
$sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, null, $staff['id'], $send_now, $throw_exceptions, $attachment);
|
||||
}
|
||||
} elseif (isset($oneStaff)) {
|
||||
$to = $oneStaff['email'];
|
||||
$to_name = $oneStaff['name'];
|
||||
$sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, $oneStaff['id'], null, $send_now, $throw_exceptions);
|
||||
$sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, $oneStaff['id'], null, $send_now, $throw_exceptions, $attachment);
|
||||
} elseif (isset($customer)) {
|
||||
$to = $customer['email'];
|
||||
$to_name = $customer['first_name'] . ' ' . $customer['last_name'];
|
||||
$sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, $customer['id'], null, $send_now, $throw_exceptions);
|
||||
$sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, $customer['id'], null, $send_now, $throw_exceptions, $attachment);
|
||||
} else {
|
||||
$to = $data['to'];
|
||||
$to_name = $data['to_name'] ?? null;
|
||||
$sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, null, null, $send_now, $throw_exceptions);
|
||||
$sent = $this->sendMail($to, $from, $subject, $content, $to_name, $from_name, null, null, $send_now, $throw_exceptions, $attachment);
|
||||
}
|
||||
|
||||
return $sent;
|
||||
@@ -259,10 +260,13 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
];
|
||||
}
|
||||
|
||||
public function sendMail($to, $from, $subject, $content, $to_name = null, $from_name = null, $client_id = null, $admin_id = null, bool $send_now = false, bool $throw_exceptions = false): bool
|
||||
/**
|
||||
* @param array{content: string, name: string, mime?: string}|null $attachment a file to attach to the email, e.g. a generated invoice PDF
|
||||
*/
|
||||
public function sendMail($to, $from, $subject, $content, $to_name = null, $from_name = null, $client_id = null, $admin_id = null, bool $send_now = false, bool $throw_exceptions = false, ?array $attachment = null): bool
|
||||
{
|
||||
// Add the email to the queue
|
||||
$email = $this->_queue($to, $from, $subject, $content, $to_name, $from_name, $client_id, $admin_id);
|
||||
$email = $this->_queue($to, $from, $subject, $content, $to_name, $from_name, $client_id, $admin_id, $attachment);
|
||||
if ($send_now) {
|
||||
$this->_sendFromQueue($email, $throw_exceptions);
|
||||
}
|
||||
@@ -479,7 +483,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
return [$template->getSubject() ?? '', $template->getContent() ?? ''];
|
||||
}
|
||||
|
||||
private function _queue($to, $from, $subject, $content, $to_name = null, $from_name = null, $client_id = null, $admin_id = null): QueuedEmail
|
||||
private function _queue($to, $from, $subject, $content, $to_name = null, $from_name = null, $client_id = null, $admin_id = null, ?array $attachment = null): QueuedEmail
|
||||
{
|
||||
$em = $this->di['em'];
|
||||
|
||||
@@ -496,6 +500,12 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
$queue->setPriority(1);
|
||||
$queue->setTries(0);
|
||||
|
||||
if ($attachment !== null && isset($attachment['content'], $attachment['name'])) {
|
||||
$queue->setAttachmentName((string) $attachment['name']);
|
||||
$queue->setAttachmentContent((string) $attachment['content']);
|
||||
$queue->setAttachmentMime((string) ($attachment['mime'] ?? 'application/octet-stream'));
|
||||
}
|
||||
|
||||
try {
|
||||
$em->persist($queue);
|
||||
$em->flush();
|
||||
@@ -569,13 +579,30 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
$systemService = $this->di['mod_service']('system');
|
||||
$from_name = $systemService->getParamValue('company_name');
|
||||
|
||||
$this->sendMail($email->getRecipients(), $email->getSender(), $email->getSubject(), $email->getContentHtml(), $customer['first_name'] . ' ' . $customer['last_name'], $from_name, $email->getClientId());
|
||||
$this->sendMail($email->getRecipients(), $email->getSender(), $email->getSubject(), $email->getContentHtml(), $customer['first_name'] . ' ' . $customer['last_name'], $from_name, $email->getClientId(), null, false, false, $this->loggedAttachmentToArray($email));
|
||||
|
||||
$this->di['logger']->info('Resent email #%s', $email->getId());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{content: string, name: string, mime: string}|null
|
||||
*/
|
||||
private function loggedAttachmentToArray(ActivityClientEmail $email): ?array
|
||||
{
|
||||
$content = $email->getAttachmentContent();
|
||||
if ($content === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'content' => $content,
|
||||
'name' => $email->getAttachmentName() ?? 'attachment',
|
||||
'mime' => $email->getAttachmentMime() ?? 'application/octet-stream',
|
||||
];
|
||||
}
|
||||
|
||||
public function queueGetSearchQuery($data): array
|
||||
{
|
||||
$query = 'SELECT * FROM email_queue';
|
||||
@@ -1013,6 +1040,23 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{content: string, name: string, mime: string}|null
|
||||
*/
|
||||
private function queuedAttachmentToArray(QueuedEmail $queue): ?array
|
||||
{
|
||||
$content = $queue->getAttachmentContent();
|
||||
if ($content === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'content' => $content,
|
||||
'name' => $queue->getAttachmentName() ?? 'attachment',
|
||||
'mime' => $queue->getAttachmentMime() ?? 'application/octet-stream',
|
||||
];
|
||||
}
|
||||
|
||||
private function _sendFromQueue(QueuedEmail $queue, bool $throw_exceptions = false): bool
|
||||
{
|
||||
$extensionService = $this->di['mod_service']('extension');
|
||||
@@ -1038,8 +1082,15 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
'name' => $queue->getToName(),
|
||||
];
|
||||
|
||||
$attachment = $this->queuedAttachmentToArray($queue);
|
||||
|
||||
try {
|
||||
$mail = new \FOSSBilling\Mail($sender, $recipient, $queue->getSubject(), $queue->getContent(), $transport, $settings['custom_dsn'] ?? null);
|
||||
|
||||
if ($attachment !== null) {
|
||||
$mail->attach($attachment['content'], $attachment['name'], $attachment['mime']);
|
||||
}
|
||||
|
||||
if (!empty($settings['reply_to'])) {
|
||||
if (filter_var($settings['reply_to'], FILTER_VALIDATE_EMAIL)) {
|
||||
$mail->addReplyTo($settings['reply_to']);
|
||||
@@ -1059,7 +1110,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
// It sent without causing an exception (error), so we are safe to log it now
|
||||
if ($log) {
|
||||
$activityService = $this->di['mod_service']('activity');
|
||||
$activityService->logEmail($queue->getSubject(), $queue->getClientId(), $queue->getSender(), $queue->getRecipient(), $queue->getContent());
|
||||
$activityService->logEmail($queue->getSubject(), $queue->getClientId(), $queue->getSender(), $queue->getRecipient(), $queue->getContent(), null, $attachment);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -1085,7 +1136,7 @@ class Service implements \FOSSBilling\InjectionAwareInterface
|
||||
// The email failed to send after the max number of tries. This might be because of a server error, so let's be sure to log it which gives the client the ability to resend it.
|
||||
if ($log) {
|
||||
$activityService = $this->di['mod_service']('activity');
|
||||
$activityService->logEmail($queue->getSubject(), $queue->getClientId(), $queue->getSender(), $queue->getRecipient(), $queue->getContent());
|
||||
$activityService->logEmail($queue->getSubject(), $queue->getClientId(), $queue->getSender(), $queue->getRecipient(), $queue->getContent(), null, $attachment);
|
||||
}
|
||||
$this->di['em']->remove($queue);
|
||||
$this->di['em']->flush();
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Box\Mod\Email\Repository\ActivityClientEmailRepository;
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
|
||||
test('get search query builder excludes the attachment blob from the select', function (): void {
|
||||
$selectCalls = [];
|
||||
|
||||
$queryBuilder = Mockery::mock(QueryBuilder::class);
|
||||
$queryBuilder->shouldReceive('select')->once()->andReturnUsing(function (string $select) use (&$selectCalls, $queryBuilder) {
|
||||
$selectCalls[] = $select;
|
||||
|
||||
return $queryBuilder;
|
||||
});
|
||||
$queryBuilder->shouldReceive('orderBy')->with('e.id', 'DESC')->once()->andReturn($queryBuilder);
|
||||
|
||||
$repository = Mockery::mock(ActivityClientEmailRepository::class)->makePartial();
|
||||
$repository->shouldReceive('createQueryBuilder')->with('e')->once()->andReturn($queryBuilder);
|
||||
|
||||
$result = $repository->getSearchQueryBuilder([]);
|
||||
|
||||
expect($result)->toBe($queryBuilder);
|
||||
expect($selectCalls)->toHaveCount(1);
|
||||
expect($selectCalls[0])->toContain('attachmentName');
|
||||
expect($selectCalls[0])->toContain('attachmentMime');
|
||||
expect($selectCalls[0])->not->toContain('attachmentContent');
|
||||
});
|
||||
@@ -158,6 +158,7 @@ test('ActivityClientEmail toApiArray returns sanitized API array', function ():
|
||||
'subject' => $subject,
|
||||
'content_html' => FOSSBilling\Tools::sanitizeContent($content_html),
|
||||
'content_text' => $content_text,
|
||||
'has_attachment' => false,
|
||||
'created_at' => $created->format('Y-m-d H:i:s'),
|
||||
'updated_at' => $updated->format('Y-m-d H:i:s'),
|
||||
];
|
||||
@@ -323,6 +324,98 @@ test('sendTemplate sends email when template exists', function (): void {
|
||||
expect($result)->toBeTrue();
|
||||
});
|
||||
|
||||
test('sendTemplate forwards the attachment to the queue and strips it from the stored vars', function (): void {
|
||||
$data = [
|
||||
'code' => 'mod_email_test',
|
||||
'to' => 'example@example.com',
|
||||
'default_subject' => 'SUBJECT',
|
||||
'default_template' => 'TEMPLATE',
|
||||
'default_description' => 'DESCRIPTION',
|
||||
'attachment' => [
|
||||
'content' => '%PDF-1.4 fake invoice contents',
|
||||
'name' => 'Invoice-BB0001.pdf',
|
||||
'mime' => 'application/pdf',
|
||||
],
|
||||
];
|
||||
$service = new Box\Mod\Email\Service();
|
||||
|
||||
$di = container();
|
||||
|
||||
$emailTemplate = emailTemplate(data: ['enabled' => true]);
|
||||
|
||||
$templateRepo = Mockery::mock(Box\Mod\Email\Repository\EmailTemplateRepository::class);
|
||||
$templateRepo->shouldReceive('findOneByActionCode')->andReturn($emailTemplate);
|
||||
|
||||
/** @var Box\Mod\Email\Entity\QueuedEmail|null $persistedQueue */
|
||||
$persistedQueue = null;
|
||||
$em = emailBuildEm(null, $templateRepo);
|
||||
$em->shouldReceive('persist')
|
||||
->atLeast()->once()
|
||||
->with(Mockery::on(function ($entity) use (&$persistedQueue): bool {
|
||||
if ($entity instanceof Box\Mod\Email\Entity\QueuedEmail) {
|
||||
$persistedQueue = $entity;
|
||||
}
|
||||
|
||||
return true;
|
||||
}));
|
||||
$em->shouldReceive('flush')->atLeast()->once();
|
||||
|
||||
$systemService = Mockery::mock(Box\Mod\System\Service::class);
|
||||
$systemService->shouldReceive('getParamValue')
|
||||
->atLeast()->once()
|
||||
->andReturn('value');
|
||||
$systemService->shouldReceive('renderEmailTplString')
|
||||
->atLeast()->once()
|
||||
->andReturn('rendered content');
|
||||
|
||||
$di['api_admin'] = function () use ($di) {
|
||||
$api = new FOSSBilling\Api\Proxy(new Model_Admin());
|
||||
$api->setDi($di);
|
||||
|
||||
return $api;
|
||||
};
|
||||
$validatorMock = Mockery::mock(FOSSBilling\Validate::class);
|
||||
$validatorMock->shouldReceive('checkRequiredParamsForArray')->byDefault();
|
||||
$di['validator'] = $validatorMock;
|
||||
|
||||
$encryptedVars = null;
|
||||
$cryptMock = Mockery::mock('\Box_Crypt');
|
||||
$cryptMock->shouldReceive('encrypt')
|
||||
->atLeast()->once()
|
||||
->with(Mockery::on(function ($json) use (&$encryptedVars): bool {
|
||||
$encryptedVars = $json;
|
||||
|
||||
return true;
|
||||
}), Mockery::any())
|
||||
->andReturn('encrypted');
|
||||
|
||||
$modMock = Mockery::mock(FOSSBilling\Module::class)->makePartial();
|
||||
$modMock->shouldReceive('getConfig')
|
||||
->atLeast()->once()
|
||||
->andReturn([
|
||||
'from_name' => 'Test',
|
||||
'from_email' => 'test@test.com',
|
||||
]);
|
||||
|
||||
$di['em'] = $em;
|
||||
$di['crypt'] = $cryptMock;
|
||||
$di['twig'] = Mockery::mock(Twig\Environment::class);
|
||||
$di['mod'] = $di->protect(fn () => $modMock);
|
||||
$di['mod_service'] = $di->protect(moduleService(['system' => $systemService]));
|
||||
$di['tools'] = new FOSSBilling\Tools();
|
||||
|
||||
$service->setDi($di);
|
||||
|
||||
$result = $service->sendTemplate($data);
|
||||
|
||||
expect($result)->toBeTrue();
|
||||
expect($persistedQueue)->not->toBeNull();
|
||||
expect($persistedQueue->getAttachmentName())->toBe('Invoice-BB0001.pdf');
|
||||
expect($persistedQueue->getAttachmentContent())->toBe('%PDF-1.4 fake invoice contents');
|
||||
expect($persistedQueue->getAttachmentMime())->toBe('application/pdf');
|
||||
expect($encryptedVars)->not->toContain('fake invoice contents');
|
||||
});
|
||||
|
||||
dataset('sendTemplateExistsStaffProvider', fn (): array => [
|
||||
[
|
||||
[
|
||||
@@ -1007,6 +1100,42 @@ test('sendMail queues email for sending', function (): void {
|
||||
expect($result)->toBeTrue();
|
||||
});
|
||||
|
||||
test('sendMail queues the given attachment onto the queued email', function (): void {
|
||||
$em = emailBuildEm();
|
||||
/** @var Box\Mod\Email\Entity\QueuedEmail|null $persistedQueue */
|
||||
$persistedQueue = null;
|
||||
$em->shouldReceive('persist')
|
||||
->atLeast()->once()
|
||||
->with(Mockery::on(function ($queue) use (&$persistedQueue): bool {
|
||||
if ($queue instanceof Box\Mod\Email\Entity\QueuedEmail) {
|
||||
$persistedQueue = $queue;
|
||||
}
|
||||
|
||||
return true;
|
||||
}));
|
||||
$em->shouldReceive('flush')->atLeast()->once();
|
||||
|
||||
$di = container();
|
||||
$di['em'] = $em;
|
||||
|
||||
$service = new Box\Mod\Email\Service();
|
||||
$service->setDi($di);
|
||||
|
||||
$attachment = [
|
||||
'content' => '%PDF-1.4 fake invoice contents',
|
||||
'name' => 'Invoice-BB0001.pdf',
|
||||
'mime' => 'application/pdf',
|
||||
];
|
||||
|
||||
$result = $service->sendMail('receiver@example.com', 'sender@example.com', 'Invoice created', 'content', null, null, null, null, false, false, $attachment);
|
||||
|
||||
expect($result)->toBeTrue();
|
||||
expect($persistedQueue)->not->toBeNull();
|
||||
expect($persistedQueue->getAttachmentName())->toBe('Invoice-BB0001.pdf');
|
||||
expect($persistedQueue->getAttachmentContent())->toBe('%PDF-1.4 fake invoice contents');
|
||||
expect($persistedQueue->getAttachmentMime())->toBe('application/pdf');
|
||||
});
|
||||
|
||||
test('getBrokenTemplateCount returns count from repository', function (): void {
|
||||
$service = new Box\Mod\Email\Service();
|
||||
$di = container();
|
||||
@@ -1268,3 +1397,57 @@ test('EmailTemplate toApiArray includes has_error and last_error in deep mode',
|
||||
expect($result['has_error'])->toBeTrue();
|
||||
expect($result['last_error'])->toBe('Some syntax error');
|
||||
});
|
||||
|
||||
test('queuedAttachmentToArray returns null when the queue has no attachment', function (): void {
|
||||
$service = new Box\Mod\Email\Service();
|
||||
$queue = new Box\Mod\Email\Entity\QueuedEmail();
|
||||
|
||||
$ref = new ReflectionMethod($service, 'queuedAttachmentToArray');
|
||||
$result = $ref->invoke($service, $queue);
|
||||
|
||||
expect($result)->toBeNull();
|
||||
});
|
||||
|
||||
test('queuedAttachmentToArray converts a queued attachment into a mail-ready array', function (): void {
|
||||
$service = new Box\Mod\Email\Service();
|
||||
$queue = new Box\Mod\Email\Entity\QueuedEmail();
|
||||
$queue->setAttachmentName('Invoice-BB0001.pdf');
|
||||
$queue->setAttachmentContent('%PDF-1.4 fake invoice contents');
|
||||
$queue->setAttachmentMime('application/pdf');
|
||||
|
||||
$ref = new ReflectionMethod($service, 'queuedAttachmentToArray');
|
||||
$result = $ref->invoke($service, $queue);
|
||||
|
||||
expect($result)->toBe([
|
||||
'content' => '%PDF-1.4 fake invoice contents',
|
||||
'name' => 'Invoice-BB0001.pdf',
|
||||
'mime' => 'application/pdf',
|
||||
]);
|
||||
});
|
||||
|
||||
test('loggedAttachmentToArray returns null when the logged email has no attachment', function (): void {
|
||||
$service = new Box\Mod\Email\Service();
|
||||
$email = new Box\Mod\Email\Entity\ActivityClientEmail();
|
||||
|
||||
$ref = new ReflectionMethod($service, 'loggedAttachmentToArray');
|
||||
$result = $ref->invoke($service, $email);
|
||||
|
||||
expect($result)->toBeNull();
|
||||
});
|
||||
|
||||
test('loggedAttachmentToArray converts a logged attachment into a mail-ready array', function (): void {
|
||||
$service = new Box\Mod\Email\Service();
|
||||
$email = new Box\Mod\Email\Entity\ActivityClientEmail();
|
||||
$email->setAttachmentName('Invoice-BB0001.pdf');
|
||||
$email->setAttachmentContent('%PDF-1.4 fake invoice contents');
|
||||
$email->setAttachmentMime('application/pdf');
|
||||
|
||||
$ref = new ReflectionMethod($service, 'loggedAttachmentToArray');
|
||||
$result = $ref->invoke($service, $email);
|
||||
|
||||
expect($result)->toBe([
|
||||
'content' => '%PDF-1.4 fake invoice contents',
|
||||
'name' => 'Invoice-BB0001.pdf',
|
||||
'mime' => 'application/pdf',
|
||||
]);
|
||||
});
|
||||
@@ -397,6 +397,10 @@ class Service implements InjectionAwareInterface
|
||||
$email['to_client'] = $invoiceModel->client_id;
|
||||
$email['code'] = 'mod_invoice_paid';
|
||||
$email['invoice'] = $invoice;
|
||||
$attachment = $service->getInvoicePdfAttachment($invoiceModel);
|
||||
if ($attachment !== null) {
|
||||
$email['attachment'] = $attachment;
|
||||
}
|
||||
$emailService = $di['mod_service']('email');
|
||||
$emailService->sendTemplate($email);
|
||||
}
|
||||
@@ -420,6 +424,10 @@ class Service implements InjectionAwareInterface
|
||||
$email['to_client'] = $invoiceModel->client_id;
|
||||
$email['code'] = 'mod_invoice_created';
|
||||
$email['invoice'] = $invoice;
|
||||
$attachment = $service->getInvoicePdfAttachment($invoiceModel);
|
||||
if ($attachment !== null) {
|
||||
$email['attachment'] = $attachment;
|
||||
}
|
||||
$emailService = $di['mod_service']('email');
|
||||
$emailService->sendTemplate($email);
|
||||
} catch (\Exception $exc) {
|
||||
@@ -433,8 +441,11 @@ class Service implements InjectionAwareInterface
|
||||
{
|
||||
$params = $event->getParameters();
|
||||
$di = $event->getDi();
|
||||
$service = $di['mod_service']('invoice');
|
||||
|
||||
try {
|
||||
$invoiceModel = $di['db']->load('Invoice', $params['id'] ?? 0);
|
||||
|
||||
if (($params['total'] ?? 0) > 0
|
||||
&& ($params['status'] ?? null) !== \Model_Invoice::STATUS_PAID
|
||||
&& isset($params['client']['id'])
|
||||
@@ -443,15 +454,19 @@ class Service implements InjectionAwareInterface
|
||||
$email['to_client'] = $params['client']['id'];
|
||||
$email['code'] = 'mod_invoice_created';
|
||||
$email['invoice'] = $params;
|
||||
if ($invoiceModel instanceof \Model_Invoice) {
|
||||
$attachment = $service->getInvoicePdfAttachment($invoiceModel);
|
||||
if ($attachment !== null) {
|
||||
$email['attachment'] = $attachment;
|
||||
}
|
||||
}
|
||||
$emailService = $di['mod_service']('email');
|
||||
$emailService->sendTemplate($email);
|
||||
}
|
||||
|
||||
// Sending the created-email extends the hash lifetime so the
|
||||
// recipient has a fresh window to act on the link.
|
||||
$invoiceModel = $di['db']->load('Invoice', $params['id'] ?? 0);
|
||||
if ($invoiceModel instanceof \Model_Invoice) {
|
||||
$service = $di['mod_service']('invoice');
|
||||
$service->extendInvoiceHashLifetime($invoiceModel);
|
||||
}
|
||||
} catch (\Exception $exc) {
|
||||
@@ -478,6 +493,10 @@ class Service implements InjectionAwareInterface
|
||||
$email['to_client'] = $invoiceModel->client_id;
|
||||
$email['code'] = 'mod_invoice_payment_reminder';
|
||||
$email['invoice'] = $invoice;
|
||||
$attachment = $service->getInvoicePdfAttachment($invoiceModel);
|
||||
if ($attachment !== null) {
|
||||
$email['attachment'] = $attachment;
|
||||
}
|
||||
$emailService = $di['mod_service']('email');
|
||||
$emailService->sendTemplate($email);
|
||||
|
||||
@@ -521,6 +540,10 @@ class Service implements InjectionAwareInterface
|
||||
$email['code'] = 'mod_invoice_due_after';
|
||||
$email['days_passed'] = $params['days_passed'];
|
||||
$email['invoice'] = $invoice;
|
||||
$attachment = $service->getInvoicePdfAttachment($invoiceModel);
|
||||
if ($attachment !== null) {
|
||||
$email['attachment'] = $attachment;
|
||||
}
|
||||
|
||||
$emailService = $di['mod_service']('email');
|
||||
$emailService->sendTemplate($email);
|
||||
@@ -1545,29 +1568,64 @@ class Service implements InjectionAwareInterface
|
||||
}
|
||||
|
||||
public function generatePDF($hash, $identity): Response
|
||||
{
|
||||
$invoiceModel = $this->di['db']->findOne('Invoice', 'hash = :hash', [':hash' => $hash]);
|
||||
|
||||
if (!$invoiceModel instanceof \Model_Invoice) {
|
||||
throw new InformationException('Invoice not found');
|
||||
}
|
||||
|
||||
$this->checkInvoiceAuth($invoiceModel, InvoiceOperation::READ);
|
||||
|
||||
$invoice = $this->toApiArray($invoiceModel, false, $identity);
|
||||
$content = $this->renderInvoicePdfContent($invoiceModel, $invoice);
|
||||
|
||||
return $this->createPdfResponse($content, $invoice['serie_nr']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the PDF invoice as an email attachment, provided the admin has opted into it via
|
||||
* the "Attach PDF invoice to invoice emails" setting. Returns null if the setting is off
|
||||
* or the PDF could not be generated, so callers can skip attaching without failing the send.
|
||||
*
|
||||
* @return array{content: string, name: string, mime: string}|null
|
||||
*/
|
||||
public function getInvoicePdfAttachment(\Model_Invoice $invoiceModel): ?array
|
||||
{
|
||||
$systemService = $this->di['mod_service']('system');
|
||||
if (!$systemService->getParamValue('invoice_email_attach_pdf')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$invoice = $this->toApiArray($invoiceModel, false);
|
||||
$content = $this->renderInvoicePdfContent($invoiceModel, $invoice);
|
||||
|
||||
return [
|
||||
'content' => $content,
|
||||
'name' => $this->sanitizePdfFileName((string) $invoice['serie_nr']) . '.pdf',
|
||||
'mime' => 'application/pdf',
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
$this->di['logger']->setChannel('email')->error('Failed to generate PDF invoice attachment: ' . $e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected function renderInvoicePdfContent(\Model_Invoice $invoiceModel, array $invoice): string
|
||||
{
|
||||
$systemService = $this->di['mod_service']('system');
|
||||
$c = $systemService->getCompany();
|
||||
$document_format = $systemService->getParamValue('invoice_document_format', 'Letter');
|
||||
|
||||
$invoice = $this->di['db']->findOne('Invoice', 'hash = :hash', [':hash' => $hash]);
|
||||
|
||||
if (!$invoice instanceof \Model_Invoice) {
|
||||
throw new InformationException('Invoice not found');
|
||||
}
|
||||
|
||||
$this->checkInvoiceAuth($invoice, InvoiceOperation::READ);
|
||||
|
||||
if (isset($invoice->currency)) {
|
||||
$currencyCode = $invoice->currency;
|
||||
if (isset($invoiceModel->currency)) {
|
||||
$currencyCode = $invoiceModel->currency;
|
||||
} else {
|
||||
$client = $this->di['db']->getExistingModelById('Client', $invoice->client_id, 'Client not found');
|
||||
$client = $this->di['db']->getExistingModelById('Client', $invoiceModel->client_id, 'Client not found');
|
||||
$currencyCode = $client->currency;
|
||||
}
|
||||
|
||||
$invoice = $this->toApiArray($invoice, false, $identity);
|
||||
$company = $this->di['mod_service']('System')->getCompany();
|
||||
|
||||
$CSS = $this->getPdfCss();
|
||||
|
||||
$pdf = $this->createPdfGenerator();
|
||||
@@ -1579,8 +1637,8 @@ class Service implements InjectionAwareInterface
|
||||
$buyerLines = 0;
|
||||
$logoSource = '';
|
||||
|
||||
if (!empty($company['logo_url'])) {
|
||||
[$logoSource, $remote] = $this->getPdfLogoSource($company['logo_url']);
|
||||
if (!empty($c['logo_url'])) {
|
||||
[$logoSource, $remote] = $this->getPdfLogoSource($c['logo_url']);
|
||||
$options->set('isRemoteEnabled', $remote);
|
||||
}
|
||||
|
||||
@@ -1606,7 +1664,7 @@ class Service implements InjectionAwareInterface
|
||||
$pdf->loadHtml($html);
|
||||
$pdf->render();
|
||||
|
||||
return $this->createPdfResponse($pdf->output(), $invoice['serie_nr']);
|
||||
return $pdf->output();
|
||||
}
|
||||
|
||||
public function addNote(\Model_Invoice $model, $note): bool
|
||||
@@ -1918,11 +1976,7 @@ class Service implements InjectionAwareInterface
|
||||
$safeFileName = 'invoice';
|
||||
}
|
||||
|
||||
$fallbackFileName = preg_replace('/[^A-Za-z0-9._-]/', '-', $safeFileName);
|
||||
$fallbackFileName = trim((string) $fallbackFileName, '.-');
|
||||
if ($fallbackFileName === '') {
|
||||
$fallbackFileName = 'invoice';
|
||||
}
|
||||
$fallbackFileName = $this->sanitizePdfFileName($fileName);
|
||||
|
||||
$disposition = $response->headers->makeDisposition(
|
||||
HeaderUtils::DISPOSITION_INLINE,
|
||||
@@ -1936,6 +1990,18 @@ class Service implements InjectionAwareInterface
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce a file name to a plain ASCII form safe for both HTTP fallback
|
||||
* Content-Disposition names and MIME attachment part headers.
|
||||
*/
|
||||
private function sanitizePdfFileName(string $fileName): string
|
||||
{
|
||||
$fallbackFileName = preg_replace('/[^A-Za-z0-9._-]/', '-', trim($fileName));
|
||||
$fallbackFileName = trim((string) $fallbackFileName, '.-');
|
||||
|
||||
return $fallbackFileName !== '' ? $fallbackFileName : 'invoice';
|
||||
}
|
||||
|
||||
protected function getPdfCss(): string
|
||||
{
|
||||
$basePath = Path::join(__DIR__, 'templates', 'pdf');
|
||||
|
||||
@@ -122,6 +122,15 @@
|
||||
<input class="form-control" type="number" min="0" id="invoice_hash_lifetime_days" name="invoice_hash_lifetime_days" value="{{ params.invoice_hash_lifetime_days|default('90') }}">
|
||||
<small class="form-hint">{{ 'Number of days an invoice hash link remains valid after issue. Set to 0 to never expire. The lifetime is automatically extended when the invoice email is re-sent.'|trans }}</small>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<input type="hidden" name="invoice_email_attach_pdf" value="0">
|
||||
<label class="form-check form-switch form-switch-2">
|
||||
<input class="form-check-input" type="checkbox" name="invoice_email_attach_pdf" value="1" {% if params.invoice_email_attach_pdf|default('') == '1' %}checked{% endif %}>
|
||||
<span class="form-check-label">{{ 'Attach PDF Copy to Invoice Emails'|trans }}</span>
|
||||
</label>
|
||||
<small class="form-hint">{{ 'Attaches a PDF copy of the invoice to the created, paid, reminder, and overdue emails, so clients who pay by bank transfer can view it without logging in.'|trans }}</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -454,6 +454,9 @@ test('handles after admin invoice payment received event', function (): void {
|
||||
$serviceMock->shouldReceive('toApiArray')
|
||||
->atLeast()->once()
|
||||
->andReturn($arr);
|
||||
$serviceMock->shouldReceive('getInvoicePdfAttachment')
|
||||
->atLeast()->once()
|
||||
->andReturn(null);
|
||||
|
||||
$eventMock = Mockery::mock('\Box_Event');
|
||||
$eventMock->shouldReceive('getParameters')
|
||||
@@ -503,6 +506,9 @@ test('handles after admin invoice reminder sent event', function (): void {
|
||||
$serviceMock->shouldReceive('toApiArray')
|
||||
->atLeast()->once()
|
||||
->andReturn($arr);
|
||||
$serviceMock->shouldReceive('getInvoicePdfAttachment')
|
||||
->atLeast()->once()
|
||||
->andReturn(null);
|
||||
|
||||
$eventMock = Mockery::mock('\Box_Event');
|
||||
$eventMock->shouldReceive('getParameters')
|
||||
@@ -588,6 +594,9 @@ test('handles event after invoice is due', function (): void {
|
||||
$serviceMock->shouldReceive('toApiArray')
|
||||
->atLeast()->once()
|
||||
->andReturn($arr);
|
||||
$serviceMock->shouldReceive('getInvoicePdfAttachment')
|
||||
->atLeast()->once()
|
||||
->andReturn(null);
|
||||
|
||||
$eventMock = Mockery::mock('\Box_Event');
|
||||
$params = ['days_passed' => 5, 'id' => 1];
|
||||
@@ -2481,3 +2490,94 @@ test('markAsPaid transitions a deposit invoice to paid status', function (): voi
|
||||
expect($depositInvoice->status)->toBe(Model_Invoice::STATUS_PAID);
|
||||
expect($depositInvoice->paid_at)->not->toBeNull();
|
||||
});
|
||||
|
||||
test('getInvoicePdfAttachment returns null when the setting is disabled', function (): void {
|
||||
$service = new Service();
|
||||
|
||||
$systemService = Mockery::mock(SystemService::class);
|
||||
$systemService->shouldReceive('getParamValue')
|
||||
->with('invoice_email_attach_pdf')
|
||||
->atLeast()->once()
|
||||
->andReturn(false);
|
||||
|
||||
$di = container();
|
||||
$di['mod_service'] = $di->protect(fn ($name) => match ($name) {
|
||||
'system' => $systemService,
|
||||
default => throw new RuntimeException("Unexpected service: {$name}"),
|
||||
});
|
||||
$service->setDi($di);
|
||||
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
expect($service->getInvoicePdfAttachment($invoiceModel))->toBeNull();
|
||||
});
|
||||
|
||||
test('getInvoicePdfAttachment builds a sanitized PDF attachment when enabled', function (): void {
|
||||
$serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
|
||||
$systemService = Mockery::mock(SystemService::class);
|
||||
$systemService->shouldReceive('getParamValue')
|
||||
->with('invoice_email_attach_pdf')
|
||||
->atLeast()->once()
|
||||
->andReturn(true);
|
||||
|
||||
$di = container();
|
||||
$di['mod_service'] = $di->protect(fn ($name) => match ($name) {
|
||||
'system' => $systemService,
|
||||
default => throw new RuntimeException("Unexpected service: {$name}"),
|
||||
});
|
||||
$serviceMock->setDi($di);
|
||||
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
$serviceMock->shouldReceive('toApiArray')
|
||||
->once()
|
||||
->with($invoiceModel, false)
|
||||
->andReturn(['serie_nr' => 'BB/2026/00042']);
|
||||
$serviceMock->shouldReceive('renderInvoicePdfContent')
|
||||
->once()
|
||||
->with($invoiceModel, ['serie_nr' => 'BB/2026/00042'])
|
||||
->andReturn('%PDF-1.4 fake invoice contents');
|
||||
|
||||
$result = $serviceMock->getInvoicePdfAttachment($invoiceModel);
|
||||
|
||||
expect($result)->toBe([
|
||||
'content' => '%PDF-1.4 fake invoice contents',
|
||||
'name' => 'BB-2026-00042.pdf',
|
||||
'mime' => 'application/pdf',
|
||||
]);
|
||||
});
|
||||
|
||||
test('getInvoicePdfAttachment returns null and logs when PDF generation fails', function (): void {
|
||||
$serviceMock = Mockery::mock(Service::class)->makePartial()->shouldAllowMockingProtectedMethods();
|
||||
|
||||
$systemService = Mockery::mock(SystemService::class);
|
||||
$systemService->shouldReceive('getParamValue')
|
||||
->with('invoice_email_attach_pdf')
|
||||
->atLeast()->once()
|
||||
->andReturn(true);
|
||||
|
||||
$di = container();
|
||||
$di['mod_service'] = $di->protect(fn ($name) => match ($name) {
|
||||
'system' => $systemService,
|
||||
default => throw new RuntimeException("Unexpected service: {$name}"),
|
||||
});
|
||||
$logger = new Tests\Helpers\TestLogger();
|
||||
$di['logger'] = $logger;
|
||||
$serviceMock->setDi($di);
|
||||
|
||||
$invoiceModel = new Model_Invoice();
|
||||
$invoiceModel->loadBean(new Tests\Helpers\DummyBean());
|
||||
|
||||
$serviceMock->shouldReceive('toApiArray')
|
||||
->once()
|
||||
->andThrow(new Exception('boom'));
|
||||
|
||||
$result = $serviceMock->getInvoicePdfAttachment($invoiceModel);
|
||||
|
||||
expect($result)->toBeNull();
|
||||
$errors = array_filter($logger->calls, fn ($c): bool => $c['method'] === 'error');
|
||||
expect($errors)->not->toBeEmpty();
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Copyright 2022-2026 FOSSBilling
|
||||
* SPDX-License-Identifier: Apache-2.0.
|
||||
*
|
||||
* @copyright FOSSBilling (https://www.fossbilling.org)
|
||||
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use FOSSBilling\Mail;
|
||||
|
||||
function mailGetUnderlyingEmail(Mail $mail): Symfony\Component\Mime\Email
|
||||
{
|
||||
$ref = new ReflectionProperty($mail, 'email');
|
||||
|
||||
return $ref->getValue($mail);
|
||||
}
|
||||
|
||||
test('attach adds a file attachment to the underlying email message', function (): void {
|
||||
$mail = new Mail(
|
||||
['email' => 'sender@example.com', 'name' => 'Sender'],
|
||||
['email' => 'receiver@example.com', 'name' => 'Receiver'],
|
||||
'Invoice created',
|
||||
'<p>Body</p>',
|
||||
'sendmail'
|
||||
);
|
||||
|
||||
$mail->attach('%PDF-1.4 fake invoice contents', 'Invoice-BB0001.pdf', 'application/pdf');
|
||||
|
||||
$attachments = mailGetUnderlyingEmail($mail)->getAttachments();
|
||||
expect($attachments)->toHaveCount(1);
|
||||
|
||||
$attachment = $attachments[0];
|
||||
expect($attachment->getFilename())->toBe('Invoice-BB0001.pdf');
|
||||
expect($attachment->getMediaType() . '/' . $attachment->getMediaSubtype())->toBe('application/pdf');
|
||||
expect($attachment->getBody())->toBe('%PDF-1.4 fake invoice contents');
|
||||
});
|
||||
|
||||
test('attach can be called multiple times to add several attachments', function (): void {
|
||||
$mail = new Mail(
|
||||
['email' => 'sender@example.com'],
|
||||
['email' => 'receiver@example.com'],
|
||||
'Subject',
|
||||
'<p>Body</p>',
|
||||
'sendmail'
|
||||
);
|
||||
|
||||
$mail->attach('content-a', 'a.txt', 'text/plain');
|
||||
$mail->attach('content-b', 'b.txt', 'text/plain');
|
||||
|
||||
expect(mailGetUnderlyingEmail($mail)->getAttachments())->toHaveCount(2);
|
||||
});
|
||||
Reference in new issue
Block a user