From 5d31dbdc02f9556d8e03fd4311fbc4c889ab54be Mon Sep 17 00:00:00 2001 From: Grzegorz Date: Tue, 1 Dec 2026 08:56:31 +0100 Subject: [PATCH] feat(invoices): make combined proforma receipt optional --- app/Hooks/proforma.php | 47 ++++++- .../Controllers/Admin/SettingController.php | 2 +- app/Listeners/SendNotificationListener.php | 50 ++++++- app/Mail/InvoicePaidMail.php | 46 +++++- lang/de/admin.php | 2 + lang/de/email.php | 7 + lang/en/admin.php | 2 + lang/en/email.php | 7 + lang/pl/admin.php | 2 + lang/pl/email.php | 7 + lang/tr/admin.php | 2 + lang/tr/email.php | 7 + lang/zh/admin.php | 2 + lang/zh/email.php | 7 + .../views/admin/settings/general.blade.php | 5 + .../views/emails/proforma-paid.blade.php | 22 +++ tests/Feature/GeneralSettingsScopeTest.php | 1 + tests/Feature/ProformaPaymentEmailTest.php | 133 ++++++++++++++++++ 18 files changed, 335 insertions(+), 16 deletions(-) create mode 100644 resources/views/emails/proforma-paid.blade.php create mode 100644 tests/Feature/ProformaPaymentEmailTest.php diff --git a/app/Hooks/proforma.php b/app/Hooks/proforma.php index cc5811559..a77138dfc 100644 --- a/app/Hooks/proforma.php +++ b/app/Hooks/proforma.php @@ -1,15 +1,38 @@ client?->billingEmail(); + + if (! $email) { + return; + } + + try { + Mail::to($email)->queue(new InvoicePaidMail($proforma, $transactionId, $vat)); + } catch (Throwable $e) { + Log::error('Proforma: could not queue paid email for #'.$proforma->id.': '.$e->getMessage()); + } +}; /** * A paid proforma is not a tax document: issue the corresponding VAT invoice, * then re-fire InvoicePaid for it so the KSeF hook (and any other module) * sees the VAT invoice. + * + * The normal paid mail and the separate VAT-created mail are suppressed for + * this flow. One message tells the customer the proforma is paid and carries + * the VAT invoice. A top-up has no VAT invoice and keeps the ordinary paid + * message; a supply whose VAT invoice could not be issued still gets that + * ordinary confirmation rather than silence. */ -add_hook('InvoicePaid', function (array $params): void { +add_hook('InvoicePaid', function (array $params) use ($sendProformaPaidMail): void { $invoice = $params['invoice'] ?? null; if (! $invoice instanceof Invoice) { @@ -20,13 +43,31 @@ return; } + $hasSupply = ! $invoice->items()->where('type', 'AddFunds')->exists(); + $combined = Setting::get('ProformaCombinedPaidEmail', '0') === '1'; + $transactionId = $params['transactionId'] ?? null; + try { $vat = app(ProformaService::class)->issueVatInvoice($invoice); if ($vat) { - run_hook('InvoicePaid', ['invoice' => $vat, 'transactionId' => $params['transactionId'] ?? null]); + run_hook('InvoicePaid', ['invoice' => $vat, 'transactionId' => $transactionId]); + + if ($combined && $vat->wasRecentlyCreated) { + $sendProformaPaidMail($invoice, $vat, $transactionId); + } + + return; } - } catch (\Throwable $e) { + + if ($combined && $hasSupply) { + $sendProformaPaidMail($invoice, null, $transactionId); + } + } catch (Throwable $e) { Log::error('Proforma: could not issue VAT invoice for #'.$invoice->id.': '.$e->getMessage()); + + if ($combined && $hasSupply) { + $sendProformaPaidMail($invoice, null, $transactionId); + } } }); diff --git a/app/Http/Controllers/Admin/SettingController.php b/app/Http/Controllers/Admin/SettingController.php index acd56b56c..e504ebee5 100644 --- a/app/Http/Controllers/Admin/SettingController.php +++ b/app/Http/Controllers/Admin/SettingController.php @@ -102,7 +102,7 @@ protected function paymentMethods(): array 'MaxMindAccountId', 'MaxMindEnabled', 'MaxMindLicenseKey', 'TwilioAccountSid', 'TwilioAuthToken', 'TwilioVerifyEnabled', 'TwilioVerifyServiceSid', 'WhatsappVerifyEnabled', 'WhatsappBusinessNumber', 'WhatsappAppSecret', 'WhatsappWebhookVerifyToken', - 'ProformaEnabled', 'ProformaNumberFormat', 'HidePaidProformas', + 'ProformaEnabled', 'ProformaNumberFormat', 'HidePaidProformas', 'ProformaCombinedPaidEmail', 'LateFeeAmount', 'LateFeeMinDays', 'LateFeeType', 'MailEnabled', 'MailType', 'MaintenanceMode', 'PhoneNumber', 'SMTPHost', 'SMTPPassword', 'SMTPPort', 'SMTPSecurity', 'SMTPUsername', diff --git a/app/Listeners/SendNotificationListener.php b/app/Listeners/SendNotificationListener.php index 048bcb4c5..14f981c75 100644 --- a/app/Listeners/SendNotificationListener.php +++ b/app/Listeners/SendNotificationListener.php @@ -21,6 +21,7 @@ use App\Mail\TicketOpenedMail; use App\Mail\TicketReplyMail; use App\Models\Admin; +use App\Models\Invoice; use App\Models\Setting; use App\Models\Ticket; use App\Services\AddonManager; @@ -77,7 +78,7 @@ public function handleInvoiceCreated(InvoiceCreated $event): void $ksefActive = app(AddonManager::class)->isActive('ksef'); $isVat = ($event->invoice->type ?? 'vat') === 'vat'; - if (! ($isVat && $ksefActive)) { + if (! ($isVat && $ksefActive) && ! ($this->combinedProformaEmailEnabled() && $this->isVatFromProforma($event->invoice))) { try { $email = $event->invoice->client?->billingEmail(); if ($email) { @@ -98,13 +99,15 @@ public function handleInvoiceCreated(InvoiceCreated $event): void public function handleInvoicePaid(InvoicePaid $event): void { - try { - $email = $event->invoice->client?->billingEmail(); - if ($email) { - Mail::to($email)->queue(new InvoicePaidMail($event->invoice, $event->transactionId)); + if (! $this->paidEmailComesFromProformaFlow($event->invoice)) { + try { + $email = $event->invoice->client?->billingEmail(); + if ($email) { + Mail::to($email)->queue(new InvoicePaidMail($event->invoice, $event->transactionId)); + } + } catch (\Throwable $e) { + Log::error('SendNotification: InvoicePaid email failed', ['error' => $e->getMessage()]); } - } catch (\Throwable $e) { - Log::error('SendNotification: InvoicePaid email failed', ['error' => $e->getMessage()]); } $this->dispatchNotification('invoice.paid', [ @@ -116,6 +119,39 @@ public function handleInvoicePaid(InvoicePaid $event): void ]); } + /** + * A VAT invoice issued from a proforma gets the combined proforma-paid + * email from the proforma hook instead of a separate invoice-created mail. + */ + private function isVatFromProforma(Invoice $invoice): bool + { + return ($invoice->type ?? 'vat') === 'vat' && $invoice->source_invoice_id !== null; + } + + private function combinedProformaEmailEnabled(): bool + { + return Setting::get('ProformaCombinedPaidEmail', '0') === '1'; + } + + /** + * The paid email for a normal proforma is sent by the proforma hook with + * the VAT invoice attached when the combined option is on. A top-up has no + * VAT invoice, so it keeps the ordinary paid email. The VAT invoice itself + * is covered by the combined message as well. + */ + private function paidEmailComesFromProformaFlow(Invoice $invoice): bool + { + if (! $this->combinedProformaEmailEnabled()) { + return false; + } + + if ($invoice->isProforma()) { + return ! $invoice->items()->where('type', 'AddFunds')->exists(); + } + + return $this->isVatFromProforma($invoice); + } + public function handleTicketOpened(TicketOpened $event): void { try { diff --git a/app/Mail/InvoicePaidMail.php b/app/Mail/InvoicePaidMail.php index 12011c016..b64861b3c 100644 --- a/app/Mail/InvoicePaidMail.php +++ b/app/Mail/InvoicePaidMail.php @@ -2,24 +2,26 @@ namespace App\Mail; -use App\Models\Invoice; use App\Mail\Concerns\LocalizesToRecipient; -use App\Models\Setting; +use App\Models\Invoice; +use App\Services\InvoicePdfService; use Illuminate\Bus\Queueable; +use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; +use Illuminate\Mail\Mailables\Attachment; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; use Illuminate\Queue\SerializesModels; -use Illuminate\Contracts\Queue\ShouldQueue; class InvoicePaidMail extends Mailable implements ShouldQueue { - use Queueable, SerializesModels; use LocalizesToRecipient; + use Queueable, SerializesModels; public function __construct( public Invoice $invoice, - public ?string $transactionId = null + public ?string $transactionId = null, + public ?Invoice $vatInvoice = null ) { $this->localizeTo($this->invoice); } @@ -28,11 +30,30 @@ public function envelope(): Envelope { $num = $this->invoice->invoice_num ?? $this->invoice->id; + if ($this->vatInvoice) { + return new Envelope(subject: __('email.invoice.proforma_paid_subject', [ + 'proforma' => $num, + 'invoice' => $this->vatInvoice->invoice_num ?? $this->vatInvoice->id, + ])); + } + return new Envelope(subject: __('email.invoice.paid_subject', ['number' => $num])); } public function content(): Content { + if ($this->vatInvoice) { + return new Content( + view: 'emails.proforma-paid', + with: [ + 'invoice' => $this->invoice, + 'vatInvoice' => $this->vatInvoice, + 'transactionId' => $this->transactionId, + 'companyName' => company_name(), + ], + ); + } + return new Content( view: 'emails.invoice-paid', with: [ @@ -42,4 +63,19 @@ public function content(): Content ], ); } + + public function attachments(): array + { + if (! $this->vatInvoice) { + return []; + } + + $pdf = app(InvoicePdfService::class)->generate($this->vatInvoice); + $num = str_replace(['/', '\\'], '-', (string) ($this->vatInvoice->invoice_num ?? $this->vatInvoice->id)); + + return [ + Attachment::fromData(fn () => $pdf->output(), "vat-invoice-{$num}.pdf") + ->withMime('application/pdf'), + ]; + } } diff --git a/lang/de/admin.php b/lang/de/admin.php index ce2bc829a..04aeef0ce 100644 --- a/lang/de/admin.php +++ b/lang/de/admin.php @@ -2972,6 +2972,8 @@ 'proforma_number_format' => 'Proforma-Nummerierungsschema', 'proforma_number_last' => 'Letzte Proforma', 'hide_paid_proformas' => 'Bezahlte Proformas ausblenden', + 'proforma_combined_paid_email' => 'Eine gemeinsame E-Mail nach Zahlung einer Proforma senden', + 'proforma_combined_paid_email_hint' => 'Standardmäßig aus: Der Kunde erhält die Proforma-Zahlungsbestätigung und die Umsatzsteuerrechnung getrennt. Wenn aktiviert, bestätigt eine E-Mail die Proforma-Zahlung und enthält die Umsatzsteuerrechnung als Anhang. Aufladungen ohne Umsatzsteuerrechnung behalten die normale Zahlungsbestätigung.', 'invoice_number_last' => 'Letzte Rechnung', 'invoice_number_preview' => 'Vorschau', 'invoice_number_reset_year' => 'Nummerierung jedes Jahr zurücksetzen', diff --git a/lang/de/email.php b/lang/de/email.php index 40671ebff..3eccea05d 100644 --- a/lang/de/email.php +++ b/lang/de/email.php @@ -117,6 +117,7 @@ 'overdue_subject' => 'Rechnung überfällig – Nr. :number', 'paid_body' => 'Vielen Dank! Wir haben Ihre Zahlung erhalten.', 'paid_subject' => 'Zahlungseingang bestätigt – Rechnung Nr. :number', + 'proforma_paid_subject' => 'Proforma #:proforma bezahlt – Umsatzsteuerrechnung #:invoice', 'reminder_body' => 'Wir möchten Sie daran erinnern, dass Ihre Rechnung bald fällig wird.', 'reminder_subject' => 'Zahlungserinnerung – Rechnung Nr. :number', ], @@ -145,6 +146,12 @@ 'received' => 'Wir haben Ihre Zahlung erhalten. Vielen Dank!', 'transaction_id' => 'Transaktions-ID', ], + 'proforma_paid' => [ + 'received' => 'Wir haben Ihre Zahlung für Proforma #:proforma erhalten.', + 'vat_ready' => 'Ihre Umsatzsteuerrechnung #:invoice wurde ausgestellt und ist dieser Nachricht beigefügt.', + 'proforma_number' => 'Proformanummer', + 'vat_invoice_number' => 'Umsatzsteuerrechnungsnummer', + ], 'order' => [ 'confirmation_body' => 'Vielen Dank für Ihre Bestellung! Wir bearbeiten sie bereits.', 'confirmation_subject' => 'Bestellbestätigung – Nr. :number', diff --git a/lang/en/admin.php b/lang/en/admin.php index 1041185e8..7cf4ade67 100644 --- a/lang/en/admin.php +++ b/lang/en/admin.php @@ -2972,6 +2972,8 @@ 'proforma_number_format' => 'Proforma numbering scheme', 'proforma_number_last' => 'Last proforma', 'hide_paid_proformas' => 'Hide paid proformas', + 'proforma_combined_paid_email' => 'Send one combined email after a proforma is paid', + 'proforma_combined_paid_email_hint' => 'Off by default: the customer receives the proforma-paid email and the VAT invoice email separately. When on, one email confirms the proforma payment and attaches the VAT invoice. Top-ups without a VAT invoice keep the normal paid email.', 'invoice_number_last' => 'Last invoice', 'invoice_number_preview' => 'Preview', 'invoice_number_reset_year' => 'Reset numbering each year', diff --git a/lang/en/email.php b/lang/en/email.php index bded16b26..b6670c0f9 100644 --- a/lang/en/email.php +++ b/lang/en/email.php @@ -118,6 +118,7 @@ 'overdue_subject' => 'Invoice Overdue - #:number', 'paid_body' => 'Thank you! Your payment has been received.', 'paid_subject' => 'Invoice Payment Confirmation - #:number', + 'proforma_paid_subject' => 'Proforma #:proforma paid - VAT invoice #:invoice', 'reminder_body' => 'This is a friendly reminder that your invoice is due soon.', 'reminder_subject' => 'Payment Reminder - Invoice #:number', ], @@ -146,6 +147,12 @@ 'received' => 'We have received your payment. Thank you!', 'transaction_id' => 'Transaction ID', ], + 'proforma_paid' => [ + 'received' => 'We have received your payment for proforma #:proforma.', + 'vat_ready' => 'Your VAT invoice #:invoice has been issued and is attached to this message.', + 'proforma_number' => 'Proforma number', + 'vat_invoice_number' => 'VAT invoice number', + ], 'order' => [ 'confirmation_body' => 'Thank you for your order! We are processing it now.', 'confirmation_subject' => 'Order Confirmation - #:number', diff --git a/lang/pl/admin.php b/lang/pl/admin.php index b249a888b..5201c70ca 100644 --- a/lang/pl/admin.php +++ b/lang/pl/admin.php @@ -2972,6 +2972,8 @@ 'proforma_number_format' => 'Schemat numeracji proform', 'proforma_number_last' => 'Ostatnia proforma', 'hide_paid_proformas' => 'Nie pokazuj opłaconych proform', + 'proforma_combined_paid_email' => 'Wysyłaj jeden wspólny e-mail po opłaceniu proformy', + 'proforma_combined_paid_email_hint' => 'Domyślnie wysyłane są dwa e-maile. Po włączeniu jeden e-mail zawiera potwierdzenie i fakturę VAT w załączniku.', 'invoice_number_last' => 'Ostatnia faktura', 'invoice_number_preview' => 'Podgląd', 'invoice_number_reset_year' => 'Resetuj numerację co roku', diff --git a/lang/pl/email.php b/lang/pl/email.php index 47bed5771..b71a47a8f 100644 --- a/lang/pl/email.php +++ b/lang/pl/email.php @@ -118,6 +118,7 @@ 'overdue_subject' => 'Przeterminowana faktura – #:number', 'paid_body' => 'Dziękujemy! Twoja płatność została odebrana.', 'paid_subject' => 'Potwierdzenie płatności faktury – #:number', + 'proforma_paid_subject' => 'Proforma #:proforma opłacona – faktura VAT #:invoice', 'reminder_body' => 'To przyjazne przypomnienie, że Twoja faktura wkrótce będzie wymagać zapłaty.', 'reminder_subject' => 'Przypomnienie o płatności – faktura #:number', ], @@ -146,6 +147,12 @@ 'received' => 'Otrzymaliśmy Twoją płatność. Dziękujemy!', 'transaction_id' => 'Identyfikator transakcji', ], + 'proforma_paid' => [ + 'received' => 'Otrzymaliśmy płatność za proformę #:proforma.', + 'vat_ready' => 'Faktura VAT #:invoice została wystawiona i jest załączona do tej wiadomości.', + 'proforma_number' => 'Numer proformy', + 'vat_invoice_number' => 'Numer faktury VAT', + ], 'order' => [ 'confirmation_body' => 'Dziękujemy za Twoje zamówienie! Właśnie je przetwarzamy.', 'confirmation_subject' => 'Potwierdzenie zamówienia – #:number', diff --git a/lang/tr/admin.php b/lang/tr/admin.php index bd098adca..a13fa221d 100644 --- a/lang/tr/admin.php +++ b/lang/tr/admin.php @@ -3662,6 +3662,8 @@ 'products.zero_tax' => '0%', 'products.unit' => 'Birim', 'settings.hide_paid_proformas' => 'Ödenmiş proformaları gizle', + 'settings.proforma_combined_paid_email' => 'Proforma ödendikten sonra tek bir birleşik e-posta gönder', + 'settings.proforma_combined_paid_email_hint' => 'Varsayılan olarak kapalı: müşteri proforma ödeme e-postasını ve KDV faturası e-postasını ayrı ayrı alır. Açıkken tek bir e-posta proforma ödemesini onaylar ve KDV faturasını ekler. KDV faturası olmayan bakiyeler normal ödeme e-postasını almaya devam eder.', 'clients.provision_now' => 'Hesabı sunucuda şimdi oluştur', 'clients.provision_now_hint' => 'İşaretlenirse seçili sunucu modülü Create komutunu çalıştırıp gerçek bir hesap açar. Yalnızca mevcut bir hizmeti kaydetmek (göç) için işaretlemeyin.', 'clients.service_provisioned' => 'Hizmet eklendi ve sunucuda oluşturuldu.', diff --git a/lang/tr/email.php b/lang/tr/email.php index cd5e3dec7..ce8e5946f 100644 --- a/lang/tr/email.php +++ b/lang/tr/email.php @@ -117,6 +117,7 @@ 'overdue_subject' => 'Fatura Vadesi Geçti - #:number', 'paid_body' => 'Teşekkürler! Ödemeniz alındı.', 'paid_subject' => 'Fatura Ödemesi Alındı - #:number', + 'proforma_paid_subject' => 'Proforma #:proforma ödendi – KDV faturası #:invoice', 'reminder_body' => 'Faturanızın ödeme tarihinin yaklaştığını hatırlatmak isteriz.', 'reminder_subject' => 'Ödeme Hatırlatması - Fatura #:number', ], @@ -145,6 +146,12 @@ 'received' => 'Ödemenizi aldık. Teşekkür ederiz!', 'transaction_id' => 'İşlem No', ], + 'proforma_paid' => [ + 'received' => 'Proforma #:proforma için ödemenizi aldık.', + 'vat_ready' => 'KDV faturanız #:invoice düzenlendi ve bu mesaja eklendi.', + 'proforma_number' => 'Proforma numarası', + 'vat_invoice_number' => 'KDV fatura numarası', + ], 'order' => [ 'confirmation_body' => 'Siparişiniz için teşekkürler! Şu anda işleme alıyoruz.', 'confirmation_subject' => 'Sipariş Onayı - #:number', diff --git a/lang/zh/admin.php b/lang/zh/admin.php index 5e674b7de..7aaa90615 100644 --- a/lang/zh/admin.php +++ b/lang/zh/admin.php @@ -2972,6 +2972,8 @@ 'proforma_number_format' => '形式发票编号方案', 'proforma_number_last' => '最后一张形式发票', 'hide_paid_proformas' => '隐藏已付形式发票', + 'proforma_combined_paid_email' => '形式发票付款后发送一封合并邮件', + 'proforma_combined_paid_email_hint' => '默认关闭:客户会分别收到形式发票付款邮件和增值税发票邮件。开启后,一封邮件确认形式发票付款并附上增值税发票。没有增值税发票的充值仍使用普通付款邮件。', 'invoice_number_last' => '最后一张账单', 'invoice_number_preview' => '预览', 'invoice_number_reset_year' => '每年重置编号', diff --git a/lang/zh/email.php b/lang/zh/email.php index 96e229b02..2ff67e754 100644 --- a/lang/zh/email.php +++ b/lang/zh/email.php @@ -117,6 +117,7 @@ 'overdue_subject' => '发票逾期 - #:number', 'paid_body' => '感谢您!我们已收到付款。', 'paid_subject' => '发票付款确认 - #:number', + 'proforma_paid_subject' => '形式发票 #:proforma 已付款 - 增值税发票 #:invoice', 'reminder_body' => '温馨提醒:您的发票即将到期。', 'reminder_subject' => '付款提醒 - 发票 #:number', ], @@ -145,6 +146,12 @@ 'received' => '我们已收到您的付款,谢谢!', 'transaction_id' => '交易编号', ], + 'proforma_paid' => [ + 'received' => '我们已收到形式发票 #:proforma 的付款。', + 'vat_ready' => '您的增值税发票 #:invoice 已开具,并附在此邮件中。', + 'proforma_number' => '形式发票编号', + 'vat_invoice_number' => '增值税发票编号', + ], 'order' => [ 'confirmation_body' => '感谢您的订购!我们正在处理您的订单。', 'confirmation_subject' => '订单确认 - #:number', diff --git a/resources/views/admin/settings/general.blade.php b/resources/views/admin/settings/general.blade.php index c30363466..231b3cf28 100644 --- a/resources/views/admin/settings/general.blade.php +++ b/resources/views/admin/settings/general.blade.php @@ -667,6 +667,11 @@ {{ __('admin.settings.hide_paid_proformas') }} + +
{{ __('admin.settings.proforma_combined_paid_email_hint') }}
diff --git a/resources/views/emails/proforma-paid.blade.php b/resources/views/emails/proforma-paid.blade.php new file mode 100644 index 000000000..3cc532383 --- /dev/null +++ b/resources/views/emails/proforma-paid.blade.php @@ -0,0 +1,22 @@ + + + +

{{ $companyName }}

+ +

{{ __('email.common.greeting', ['name' => $invoice->client?->first_name ?? __('email.common.customer')]) }}

+ +

{{ __('email.proforma_paid.received', ['proforma' => $invoice->invoice_num ?? $invoice->id]) }}

+

{{ __('email.proforma_paid.vat_ready', ['invoice' => $vatInvoice->invoice_num ?? $vatInvoice->id]) }}

+ + + + + + + +
{{ __('email.proforma_paid.proforma_number') }}{{ $invoice->invoice_num ?? $invoice->id }}
{{ __('email.proforma_paid.vat_invoice_number') }}{{ $vatInvoice->invoice_num ?? $vatInvoice->id }}
{{ __('email.invoice_paid.amount_paid') }}{{ dual_money_fmt($invoice->total, $invoice) }}
{{ __('email.invoice_paid.transaction_id') }}{{ $transactionId ?? 'N/A' }}
{{ __('email.invoice_paid.payment_date') }}{{ $invoice->date_paid?->format(date_fmt()) ?? now()->format(date_fmt()) }}
+ +@include('emails.partials.action', ['url' => route('client.invoices.show', $vatInvoice->id), 'label' => __('email.common.view_invoice')]) + +

{{ $companyName }}

+ diff --git a/tests/Feature/GeneralSettingsScopeTest.php b/tests/Feature/GeneralSettingsScopeTest.php index e5c032617..657d8cb96 100644 --- a/tests/Feature/GeneralSettingsScopeTest.php +++ b/tests/Feature/GeneralSettingsScopeTest.php @@ -41,6 +41,7 @@ function switchScopeAdmin(): Admin 'TwilioVerifyEnabled', 'ProformaEnabled', 'HidePaidProformas', + 'ProformaCombinedPaidEmail', ]; test('saving the openai key on the languages screen leaves every switch alone', function () { diff --git a/tests/Feature/ProformaPaymentEmailTest.php b/tests/Feature/ProformaPaymentEmailTest.php new file mode 100644 index 000000000..bd3be91da --- /dev/null +++ b/tests/Feature/ProformaPaymentEmailTest.php @@ -0,0 +1,133 @@ +create([ + 'client_id' => $client->id, + 'invoice_num' => 'PRO-EMAIL-'.uniqid(), + 'type' => 'proforma', + 'status' => 'unpaid', + 'subtotal' => $amount, + 'total' => $amount, + 'tax' => 0, + 'due_date' => now()->addDay(), + ]); + + InvoiceItem::create([ + 'invoice_id' => $invoice->id, + 'client_id' => $client->id, + 'type' => $type, + 'rel_id' => 0, + 'description' => $type, + 'amount' => $amount, + 'taxed' => false, + ]); + + return $invoice; +} + +function proformaPaidMailClient(): Client +{ + return Client::factory()->create(['email' => 'proforma-mail@example.test']); +} + +beforeEach(function () { + require app_path('Hooks/proforma.php'); + Setting::set('ProformaCombinedPaidEmail', '1'); + Mail::fake(); +}); + +it('sends one email when a proforma is paid and the VAT invoice is issued', function () { + $client = proformaPaidMailClient(); + $proforma = proformaPaidMailInvoice($client); + + app(PaymentService::class)->applyPayment($proforma->fresh(), 'banktransfer', 'TX-PRO-MAIL-1', 10.0); + + $vat = Invoice::where('source_invoice_id', $proforma->id)->firstOrFail(); + + Mail::assertQueuedCount(1); + Mail::assertQueued(InvoicePaidMail::class, function (InvoicePaidMail $mail) use ($client, $proforma, $vat) { + return $mail->invoice->is($proforma) + && $mail->vatInvoice?->is($vat) + && $mail->hasTo($client->billingEmail()); + }); + Mail::assertNotQueued(InvoiceCreatedMail::class); + + expect($vat->type)->toBe('vat') + ->and(trim((string) $vat->notes))->toContain($proforma->invoice_num); +}); + +it('puts both documents and the VAT invoice attachment in the combined email', function () { + $client = proformaPaidMailClient(); + $proforma = proformaPaidMailInvoice($client); + $vat = Invoice::factory()->create([ + 'client_id' => $client->id, + 'invoice_num' => 'VAT-EMAIL-1', + 'type' => 'vat', + 'status' => 'paid', + 'source_invoice_id' => $proforma->id, + 'subtotal' => 10, + 'total' => 10, + 'date_paid' => now(), + ]); + + $mail = new InvoicePaidMail($proforma, 'TX-PRO-MAIL-4', $vat); + + expect($mail->envelope()->subject) + ->toContain($proforma->invoice_num) + ->toContain($vat->invoice_num) + ->and($mail->render()) + ->toContain(__('email.proforma_paid.received', ['proforma' => $proforma->invoice_num], $client->language)) + ->toContain(__('email.proforma_paid.vat_ready', ['invoice' => $vat->invoice_num], $client->language)) + ->and($mail->attachments())->toHaveCount(1); +}); + +it('keeps two separate emails by default', function () { + Setting::set('ProformaCombinedPaidEmail', '0'); + $client = proformaPaidMailClient(); + $proforma = proformaPaidMailInvoice($client); + + app(PaymentService::class)->applyPayment($proforma->fresh(), 'banktransfer', 'TX-PRO-MAIL-5', 10.0); + + $vat = Invoice::where('source_invoice_id', $proforma->id)->firstOrFail(); + + Mail::assertQueuedCount(2); + Mail::assertQueued(InvoicePaidMail::class, function (InvoicePaidMail $mail) use ($proforma) { + return $mail->invoice->is($proforma) && $mail->vatInvoice === null; + }); + Mail::assertQueued(InvoiceCreatedMail::class, function (InvoiceCreatedMail $mail) use ($vat) { + return $mail->invoice->is($vat); + }); +}); +it('does not send the combined email again when the paid event repeats', function () { + $client = proformaPaidMailClient(); + $proforma = proformaPaidMailInvoice($client); + + app(PaymentService::class)->applyPayment($proforma->fresh(), 'banktransfer', 'TX-PRO-MAIL-2', 10.0); + event(new InvoicePaid($proforma->fresh(), 'TX-PRO-MAIL-2')); + + Mail::assertQueuedCount(1); +}); + +it('keeps the ordinary paid email for a top-up proforma with no VAT invoice', function () { + $client = proformaPaidMailClient(); + $proforma = proformaPaidMailInvoice($client, 'AddFunds', 100); + + app(PaymentService::class)->applyPayment($proforma->fresh(), 'banktransfer', 'TX-PRO-MAIL-3', 100.0); + + Mail::assertQueuedCount(1); + Mail::assertQueued(InvoicePaidMail::class, function (InvoicePaidMail $mail) use ($proforma) { + return $mail->invoice->is($proforma) && $mail->vatInvoice === null; + }); + expect(Invoice::where('source_invoice_id', $proforma->id)->exists())->toBeFalse(); +});