From d160854b79a7dbae88a46c2554a41a6f82a643f4 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Thu, 26 Nov 2026 16:00:15 +0200 Subject: [PATCH] Email quick sale receipts and send them again from the sales list Co-Authored-By: Claude Sonnet 5.5 --- .../Application/Contracts/ReceiptMailer.php | 15 ++++ .../Application/DTOs/QuickSaleSummary.php | 19 +++++ .../Sales/Application/DTOs/SaleData.php | 4 +- .../Sales/Application/DTOs/SaleResult.php | 6 +- .../Application/UseCases/CreditQuickSale.php | 16 +++- .../UseCases/ResendQuickSaleReceipt.php | 41 ++++++++++ .../Application/UseCases/SellQuickSale.php | 21 ++++- .../Domain/Contracts/QuickSaleRepository.php | 11 +++ .../Sales/Domain/Entities/QuickSale.php | 16 +++- .../Persistence/Eloquent/QuickSaleModel.php | 10 ++- .../Repositories/EloquentQuickSaleQueries.php | 3 + .../EloquentQuickSaleRepository.php | 22 +++++ .../Providers/SalesServiceProvider.php | 3 + .../Receipts/QueuedReceiptMailer.php | 17 ++++ .../Receipts/QuickSaleReceiptMail.php | 55 +++++++++++++ .../Infrastructure/Receipts/ReceiptPdf.php | 32 ++++++++ .../Receipts/SendQuickSaleReceipt.php | 47 +++++++++++ .../Http/Controllers/ShowReceipt.php | 13 +-- .../Presentation/Livewire/⚡index.blade.php | 80 ++++++++++++++++++- .../Presentation/Livewire/⚡sell.blade.php | 53 ++++++++++-- .../Presentation/Views/receipt-mail.blade.php | 23 ++++++ ...add_receipt_email_to_quick_sales_table.php | 28 +++++++ docs/maarittely.md | 2 +- lang/en/sales.php | 20 +++++ lang/fi/sales.php | 20 +++++ tests/Fakes/FakeReceiptMailer.php | 16 ++++ tests/Fakes/InMemoryQuickSaleRepository.php | 22 +++++ .../Feature/Modules/Sales/QuickSalesTest.php | 72 +++++++++++++++++ tests/Unit/Modules/Sales/QuickSaleTest.php | 26 +++++- 29 files changed, 679 insertions(+), 34 deletions(-) create mode 100644 app/Modules/Sales/Application/Contracts/ReceiptMailer.php create mode 100644 app/Modules/Sales/Application/UseCases/ResendQuickSaleReceipt.php create mode 100644 app/Modules/Sales/Infrastructure/Receipts/QueuedReceiptMailer.php create mode 100644 app/Modules/Sales/Infrastructure/Receipts/QuickSaleReceiptMail.php create mode 100644 app/Modules/Sales/Infrastructure/Receipts/ReceiptPdf.php create mode 100644 app/Modules/Sales/Infrastructure/Receipts/SendQuickSaleReceipt.php create mode 100644 app/Modules/Sales/Presentation/Views/receipt-mail.blade.php create mode 100644 database/migrations/2026_11_26_135516_add_receipt_email_to_quick_sales_table.php create mode 100644 tests/Fakes/FakeReceiptMailer.php diff --git a/app/Modules/Sales/Application/Contracts/ReceiptMailer.php b/app/Modules/Sales/Application/Contracts/ReceiptMailer.php new file mode 100644 index 0000000..5e00fa3 --- /dev/null +++ b/app/Modules/Sales/Application/Contracts/ReceiptMailer.php @@ -0,0 +1,15 @@ +receiptEmail === null => null, + $this->receiptFailed => 'failed', + $this->receiptSentAt !== null => 'sent', + default => 'pending', + }; + } + public function isCredit(): bool { return $this->creditsSaleId !== null; diff --git a/app/Modules/Sales/Application/DTOs/SaleData.php b/app/Modules/Sales/Application/DTOs/SaleData.php index 671d0e0..4f6a43f 100644 --- a/app/Modules/Sales/Application/DTOs/SaleData.php +++ b/app/Modules/Sales/Application/DTOs/SaleData.php @@ -6,7 +6,8 @@ namespace App\Modules\Sales\Application\DTOs; /** * Input for a quick sale: quantities by product id (zero or empty ones are - * left out by the caller), the payment method key and an optional customer. + * left out by the caller), the payment method key, an optional customer + * and an optional address the receipt is emailed to. */ final readonly class SaleData { @@ -17,5 +18,6 @@ final readonly class SaleData public array $quantities, public string $paymentMethod, public ?int $customerId = null, + public ?string $receiptEmail = null, ) {} } diff --git a/app/Modules/Sales/Application/DTOs/SaleResult.php b/app/Modules/Sales/Application/DTOs/SaleResult.php index d0113f4..a6cc097 100644 --- a/app/Modules/Sales/Application/DTOs/SaleResult.php +++ b/app/Modules/Sales/Application/DTOs/SaleResult.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace App\Modules\Sales\Application\DTOs; /** - * A recorded quick sale: its id and total with VAT, and the hours booked - * on the seller or left unbooked (in quarters of an hour). + * A recorded quick sale: its id and total with VAT, the hours booked on + * the seller or left unbooked (in quarters of an hour), and the address + * the receipt is being emailed to, if one was given. */ final readonly class SaleResult { @@ -15,5 +16,6 @@ final readonly class SaleResult public int $totalCents, public int $bookedQuarters, public int $unbookedQuarters, + public ?string $receiptEmail = null, ) {} } diff --git a/app/Modules/Sales/Application/UseCases/CreditQuickSale.php b/app/Modules/Sales/Application/UseCases/CreditQuickSale.php index 5fa3f17..245a8e1 100644 --- a/app/Modules/Sales/Application/UseCases/CreditQuickSale.php +++ b/app/Modules/Sales/Application/UseCases/CreditQuickSale.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Modules\Sales\Application\UseCases; +use App\Modules\Sales\Application\Contracts\ReceiptMailer; use App\Modules\Sales\Domain\Contracts\CashDayRepository; use App\Modules\Sales\Domain\Contracts\QuickSaleRepository; use App\Modules\Sales\Domain\Entities\QuickSale; @@ -18,13 +19,16 @@ use App\Modules\Users\Application\Contracts\Clock; * Credits a quick sale (hyvitys): records the sale's lines negated on * today's cash day, so a sale of a closed day can be credited too. Hours * stay as they are: the work was done, and a wrong amount is corrected in - * the weekly view. Who may credit is checked by the caller. + * the weekly view. When the original's receipt went to an email address, + * the credit's receipt is emailed there too. Who may credit is checked by + * the caller. */ final class CreditQuickSale { public function __construct( private QuickSaleRepository $sales, private CashDayRepository $cashDays, + private ReceiptMailer $mailer, private TransactionManager $transactions, private Clock $clock, ) {} @@ -41,7 +45,7 @@ final class CreditQuickSale { $today = $this->clock->today(); - return $this->transactions->run(function () use ($saleId, $actorUserId, $today): int { + $credit = $this->transactions->run(function () use ($saleId, $actorUserId, $today): QuickSale { $original = $this->sales->findById($saleId) ?? throw new QuickSaleNotFound($saleId); $this->cashDays->lockForDay($today)->ensureOpen(); @@ -51,7 +55,13 @@ final class CreditQuickSale $credit = QuickSale::creditFor($original, $actorUserId, $this->clock->now(), $today); - return (int) $this->sales->add($credit)->id(); + return $this->sales->add($credit); }); + + if ($credit->receiptEmail() !== null) { + $this->mailer->send((int) $credit->id()); + } + + return (int) $credit->id(); } } diff --git a/app/Modules/Sales/Application/UseCases/ResendQuickSaleReceipt.php b/app/Modules/Sales/Application/UseCases/ResendQuickSaleReceipt.php new file mode 100644 index 0000000..eb66840 --- /dev/null +++ b/app/Modules/Sales/Application/UseCases/ResendQuickSaleReceipt.php @@ -0,0 +1,41 @@ +transactions->run(function () use ($saleId, $address): void { + $this->sales->findById($saleId) ?? throw new QuickSaleNotFound($saleId); + $this->sales->changeReceiptEmail($saleId, $address); + }); + + $this->mailer->send($saleId); + } +} diff --git a/app/Modules/Sales/Application/UseCases/SellQuickSale.php b/app/Modules/Sales/Application/UseCases/SellQuickSale.php index 2744d6d..fe80719 100644 --- a/app/Modules/Sales/Application/UseCases/SellQuickSale.php +++ b/app/Modules/Sales/Application/UseCases/SellQuickSale.php @@ -7,6 +7,7 @@ namespace App\Modules\Sales\Application\UseCases; use App\Modules\Customers\Application\Contracts\CustomerQueries; use App\Modules\Sales\Application\Contracts\QuickSaleHours; use App\Modules\Sales\Application\Contracts\QuickSaleProducts; +use App\Modules\Sales\Application\Contracts\ReceiptMailer; use App\Modules\Sales\Application\DTOs\SaleData; use App\Modules\Sales\Application\DTOs\SaleResult; use App\Modules\Sales\Domain\Contracts\CashDayRepository; @@ -20,13 +21,16 @@ use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound; use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty; use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine; use App\Modules\Shared\Application\Contracts\TransactionManager; +use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress; +use App\Modules\Shared\Domain\ValueObjects\EmailAddress; use App\Modules\Users\Application\Contracts\Clock; /** * Records a quick sale on today's cash day with the products' current * prices, and books the products' durations as the seller's hours. The * customer has paid, so the sale is kept even when the hours cannot be - * booked; the result tells how many were left out. + * booked; the result tells how many were left out. When an address is + * given, the PDF receipt is emailed to it after the sale is stored. */ final class SellQuickSale { @@ -35,6 +39,7 @@ final class SellQuickSale private CashDayRepository $cashDays, private QuickSaleProducts $products, private QuickSaleHours $hours, + private ReceiptMailer $mailer, private CustomerQueries $customers, private TransactionManager $transactions, private Clock $clock, @@ -46,6 +51,7 @@ final class SellQuickSale * @throws QuickSaleEmpty * @throws QuickSaleCustomerNotFound * @throws CashDayClosed + * @throws InvalidEmailAddress */ public function execute(int $sellerId, SaleData $data): SaleResult { @@ -70,10 +76,11 @@ final class SellQuickSale throw new QuickSaleCustomerNotFound($data->customerId); } + $receiptEmail = $data->receiptEmail === null || trim($data->receiptEmail) === '' ? null : new EmailAddress($data->receiptEmail); $today = $this->clock->today(); - $sale = QuickSale::sell($sellerId, $data->customerId, PaymentMethod::from($data->paymentMethod), $lines, $this->clock->now(), $today); + $sale = QuickSale::sell($sellerId, $data->customerId, PaymentMethod::from($data->paymentMethod), $lines, $this->clock->now(), $today, $receiptEmail); - return $this->transactions->run(function () use ($sale, $sellerId, $today, $quartersByWorkType): SaleResult { + $result = $this->transactions->run(function () use ($sale, $sellerId, $today, $quartersByWorkType): SaleResult { $this->cashDays->lockForDay($today)->ensureOpen(); $saleId = (int) $this->sales->add($sale)->id(); @@ -88,7 +95,13 @@ final class SellQuickSale } } - return new SaleResult($saleId, $sale->totalCents(), $booked, $unbooked); + return new SaleResult($saleId, $sale->totalCents(), $booked, $unbooked, $sale->receiptEmail()?->value); }); + + if ($result->receiptEmail !== null) { + $this->mailer->send($result->saleId); + } + + return $result; } } diff --git a/app/Modules/Sales/Domain/Contracts/QuickSaleRepository.php b/app/Modules/Sales/Domain/Contracts/QuickSaleRepository.php index bf425c2..f037423 100644 --- a/app/Modules/Sales/Domain/Contracts/QuickSaleRepository.php +++ b/app/Modules/Sales/Domain/Contracts/QuickSaleRepository.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Modules\Sales\Domain\Contracts; use App\Modules\Sales\Domain\Entities\QuickSale; +use App\Modules\Shared\Domain\ValueObjects\EmailAddress; use DateTimeImmutable; interface QuickSaleRepository @@ -24,4 +25,14 @@ interface QuickSaleRepository * @return list */ public function forDay(DateTimeImmutable $day): array; + + /** + * Sets the address the receipt is emailed to and clears the earlier + * sending result, before the receipt is sent again. + */ + public function changeReceiptEmail(int $saleId, EmailAddress $email): void; + + public function markReceiptSent(int $saleId, DateTimeImmutable $at): void; + + public function markReceiptFailed(int $saleId, DateTimeImmutable $at): void; } diff --git a/app/Modules/Sales/Domain/Entities/QuickSale.php b/app/Modules/Sales/Domain/Entities/QuickSale.php index 5539bb3..e407a70 100644 --- a/app/Modules/Sales/Domain/Entities/QuickSale.php +++ b/app/Modules/Sales/Domain/Entities/QuickSale.php @@ -8,6 +8,7 @@ use App\Modules\Sales\Domain\Enums\PaymentMethod; use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited; use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty; use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine; +use App\Modules\Shared\Domain\ValueObjects\EmailAddress; use DateTimeImmutable; /** @@ -30,6 +31,7 @@ final class QuickSale private DateTimeImmutable $soldOn, private array $lines, private ?int $creditsSaleId, + private ?EmailAddress $receiptEmail = null, ) { if ($lines === []) { throw new QuickSaleEmpty; @@ -42,9 +44,9 @@ final class QuickSale * * @throws QuickSaleEmpty */ - public static function sell(int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, array $lines, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn): self + public static function sell(int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, array $lines, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, ?EmailAddress $receiptEmail = null): self { - return new self(null, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, null); + return new self(null, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, null, $receiptEmail); } /** @@ -65,15 +67,16 @@ final class QuickSale $soldOn, array_map(fn (QuickSaleLine $line): QuickSaleLine => $line->negated(), $original->lines), $original->id, + $original->receiptEmail, ); } /** * @param list $lines */ - public static function reconstitute(int $id, int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, array $lines, ?int $creditsSaleId): self + public static function reconstitute(int $id, int $sellerId, ?int $customerId, PaymentMethod $paymentMethod, DateTimeImmutable $soldAt, DateTimeImmutable $soldOn, array $lines, ?int $creditsSaleId, ?EmailAddress $receiptEmail = null): self { - return new self($id, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, $creditsSaleId); + return new self($id, $sellerId, $customerId, $paymentMethod, $soldAt, $soldOn, $lines, $creditsSaleId, $receiptEmail); } public function totalCents(): int @@ -128,4 +131,9 @@ final class QuickSale { return $this->creditsSaleId; } + + public function receiptEmail(): ?EmailAddress + { + return $this->receiptEmail; + } } diff --git a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php index db57e85..6bbc07e 100644 --- a/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php +++ b/app/Modules/Sales/Infrastructure/Persistence/Eloquent/QuickSaleModel.php @@ -5,6 +5,7 @@ namespace App\Modules\Sales\Infrastructure\Persistence\Eloquent; use App\Modules\Sales\Domain\Enums\PaymentMethod; use Database\Factories\QuickSaleFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; +use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Attributes\Table; use Illuminate\Database\Eloquent\Attributes\UseFactory; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -24,9 +25,13 @@ use Illuminate\Support\Carbon; * @property string $sold_on Y-m-d * @property int $total_cents * @property int|null $credits_quick_sale_id + * @property string|null $receipt_email + * @property Carbon|null $receipt_sent_at + * @property Carbon|null $receipt_send_failed_at */ #[Table('quick_sales')] -#[Fillable(['user_id', 'customer_id', 'payment_method', 'sold_at', 'sold_on', 'total_cents', 'credits_quick_sale_id'])] +#[Fillable(['user_id', 'customer_id', 'payment_method', 'sold_at', 'sold_on', 'total_cents', 'credits_quick_sale_id', 'receipt_email'])] +#[Hidden(['receipt_email'])] #[UseFactory(QuickSaleFactory::class)] class QuickSaleModel extends Model { @@ -61,6 +66,9 @@ class QuickSaleModel extends Model 'sold_at' => 'datetime', 'total_cents' => 'integer', 'credits_quick_sale_id' => 'integer', + 'receipt_email' => 'encrypted', + 'receipt_sent_at' => 'datetime', + 'receipt_send_failed_at' => 'datetime', ]; } } diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleQueries.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleQueries.php index 81804d4..4e45a0b 100644 --- a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleQueries.php +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleQueries.php @@ -106,6 +106,9 @@ class EloquentQuickSaleQueries implements QuickSaleQueries ))->values()->all(), creditsSaleId: $model->credits_quick_sale_id, creditedBySaleId: $model->credit?->id, + receiptEmail: $model->receipt_email, + receiptSentAt: $this->localTime($model->receipt_sent_at), + receiptFailed: $model->receipt_send_failed_at !== null, ))->values()->all(); } diff --git a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php index 75d66fa..572198d 100644 --- a/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php +++ b/app/Modules/Sales/Infrastructure/Persistence/Repositories/EloquentQuickSaleRepository.php @@ -7,6 +7,7 @@ use App\Modules\Sales\Domain\Entities\QuickSale; use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine; use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleLineModel; use App\Modules\Sales\Infrastructure\Persistence\Eloquent\QuickSaleModel; +use App\Modules\Shared\Domain\ValueObjects\EmailAddress; use DateTimeImmutable; class EloquentQuickSaleRepository implements QuickSaleRepository @@ -28,6 +29,7 @@ class EloquentQuickSaleRepository implements QuickSaleRepository 'sold_on' => $sale->soldOn()->format('Y-m-d'), 'total_cents' => $sale->totalCents(), 'credits_quick_sale_id' => $sale->creditsSaleId(), + 'receipt_email' => $sale->receiptEmail()?->value, ]); foreach ($sale->lines() as $index => $line) { @@ -62,6 +64,25 @@ class EloquentQuickSaleRepository implements QuickSaleRepository ->all(); } + public function changeReceiptEmail(int $saleId, EmailAddress $email): void + { + QuickSaleModel::query()->whereKey($saleId)->firstOrFail()->forceFill([ + 'receipt_email' => $email->value, + 'receipt_sent_at' => null, + 'receipt_send_failed_at' => null, + ])->save(); + } + + public function markReceiptSent(int $saleId, DateTimeImmutable $at): void + { + QuickSaleModel::query()->whereKey($saleId)->update(['receipt_sent_at' => $at->format('Y-m-d H:i:s'), 'receipt_send_failed_at' => null]); + } + + public function markReceiptFailed(int $saleId, DateTimeImmutable $at): void + { + QuickSaleModel::query()->whereKey($saleId)->update(['receipt_send_failed_at' => $at->format('Y-m-d H:i:s')]); + } + private function toEntity(QuickSaleModel $model): QuickSale { return QuickSale::reconstitute( @@ -79,6 +100,7 @@ class EloquentQuickSaleRepository implements QuickSaleRepository $line->vat_basis_points, ))->values()->all(), $model->credits_quick_sale_id, + $model->receipt_email === null ? null : new EmailAddress($model->receipt_email), ); } } diff --git a/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php b/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php index 193e250..fc6bab2 100644 --- a/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php +++ b/app/Modules/Sales/Infrastructure/Providers/SalesServiceProvider.php @@ -8,6 +8,7 @@ use App\Modules\Sales\Application\Contracts\QuickSaleHours; use App\Modules\Sales\Application\Contracts\QuickSaleProducts; use App\Modules\Sales\Application\Contracts\QuickSaleQueries; use App\Modules\Sales\Application\Contracts\QuickSaleReportQueries; +use App\Modules\Sales\Application\Contracts\ReceiptMailer; use App\Modules\Sales\Domain\Contracts\CashDayRepository; use App\Modules\Sales\Domain\Contracts\QuickSaleRepository; use App\Modules\Sales\Infrastructure\CustomerReferencesFromSales; @@ -17,6 +18,7 @@ use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleQ use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleReportQueries; use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleRepository; use App\Modules\Sales\Infrastructure\ProductsFromPriceList; +use App\Modules\Sales\Infrastructure\Receipts\QueuedReceiptMailer; use App\Modules\Users\Domain\Enums\Role; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; @@ -39,6 +41,7 @@ class SalesServiceProvider extends ServiceProvider QuickSaleReportQueries::class => EloquentQuickSaleReportQueries::class, QuickSaleProducts::class => ProductsFromPriceList::class, QuickSaleHours::class => HoursForQuickSales::class, + ReceiptMailer::class => QueuedReceiptMailer::class, ]; public function register(): void diff --git a/app/Modules/Sales/Infrastructure/Receipts/QueuedReceiptMailer.php b/app/Modules/Sales/Infrastructure/Receipts/QueuedReceiptMailer.php new file mode 100644 index 0000000..a561bc7 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Receipts/QueuedReceiptMailer.php @@ -0,0 +1,17 @@ +afterCommit(); + } +} diff --git a/app/Modules/Sales/Infrastructure/Receipts/QuickSaleReceiptMail.php b/app/Modules/Sales/Infrastructure/Receipts/QuickSaleReceiptMail.php new file mode 100644 index 0000000..943962e --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Receipts/QuickSaleReceiptMail.php @@ -0,0 +1,55 @@ +locale('fi'); + } + + public function envelope(): Envelope + { + $company = app(CompanyDetailsStore::class)->get(); + + return new Envelope( + subject: __($this->sale->isCredit() ? 'sales.receipt_mail.credit_subject' : 'sales.receipt_mail.subject', [ + 'number' => $this->sale->id, + 'company' => $company->name ?? config('app.name'), + ]), + ); + } + + public function content(): Content + { + return new Content( + view: 'sales-views::receipt-mail', + with: ['sale' => $this->sale, 'company' => app(CompanyDetailsStore::class)->get()], + ); + } + + /** + * @return list + */ + public function attachments(): array + { + $pdf = app(ReceiptPdf::class); + + return [ + Attachment::fromData(fn (): string => $pdf->render($this->sale)->output(), $pdf->fileName($this->sale)) + ->withMime('application/pdf'), + ]; + } +} diff --git a/app/Modules/Sales/Infrastructure/Receipts/ReceiptPdf.php b/app/Modules/Sales/Infrastructure/Receipts/ReceiptPdf.php new file mode 100644 index 0000000..bcc9d7e --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Receipts/ReceiptPdf.php @@ -0,0 +1,32 @@ + $sale, + 'company' => $this->company->get(), + ]) + ->setPaper('a5') + ->setOption('isFontSubsettingEnabled', true); + } + + public function fileName(QuickSaleSummary $sale): string + { + return __('sales.receipt.file', ['number' => $sale->id]); + } +} diff --git a/app/Modules/Sales/Infrastructure/Receipts/SendQuickSaleReceipt.php b/app/Modules/Sales/Infrastructure/Receipts/SendQuickSaleReceipt.php new file mode 100644 index 0000000..aaa7833 --- /dev/null +++ b/app/Modules/Sales/Infrastructure/Receipts/SendQuickSaleReceipt.php @@ -0,0 +1,47 @@ + */ + public array $backoff = [10, 60]; + + public function __construct(public int $saleId) {} + + public function handle(QuickSaleRepository $sales, QuickSaleQueries $queries, Clock $clock): void + { + $email = $sales->findById($this->saleId)?->receiptEmail(); + $summary = $queries->findSale($this->saleId); + + if ($email === null || $summary === null) { + return; + } + + Mail::to($email->value)->send(new QuickSaleReceiptMail($summary)); + + $sales->markReceiptSent($this->saleId, $clock->now()); + } + + public function failed(?Throwable $exception): void + { + app(QuickSaleRepository::class)->markReceiptFailed($this->saleId, app(Clock::class)->now()); + } +} diff --git a/app/Modules/Sales/Presentation/Http/Controllers/ShowReceipt.php b/app/Modules/Sales/Presentation/Http/Controllers/ShowReceipt.php index fb4cfa0..c0296bb 100644 --- a/app/Modules/Sales/Presentation/Http/Controllers/ShowReceipt.php +++ b/app/Modules/Sales/Presentation/Http/Controllers/ShowReceipt.php @@ -3,8 +3,7 @@ namespace App\Modules\Sales\Presentation\Http\Controllers; use App\Modules\Sales\Application\Contracts\QuickSaleQueries; -use App\Modules\Shared\Application\UseCases\CompanyDetailsStore; -use Barryvdh\DomPDF\Facade\Pdf; +use App\Modules\Sales\Infrastructure\Receipts\ReceiptPdf; use Illuminate\Support\Facades\Gate; use Symfony\Component\HttpFoundation\Response; @@ -15,17 +14,11 @@ use Symfony\Component\HttpFoundation\Response; */ class ShowReceipt { - public function __invoke(int $sale, QuickSaleQueries $sales, CompanyDetailsStore $company): Response + public function __invoke(int $sale, QuickSaleQueries $sales, ReceiptPdf $pdf): Response { $summary = $sales->findSale($sale) ?? abort(404); Gate::authorize('sales.view-sale', $summary->sellerId); - return Pdf::loadView('sales-views::receipt', [ - 'sale' => $summary, - 'company' => $company->get(), - ]) - ->setPaper('a5') - ->setOption('isFontSubsettingEnabled', true) - ->stream(__('sales.receipt.file', ['number' => $summary->id])); + return $pdf->render($summary)->stream($pdf->fileName($summary)); } } diff --git a/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php b/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php index 285a474..8e9a55d 100644 --- a/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php +++ b/app/Modules/Sales/Presentation/Livewire/⚡index.blade.php @@ -6,6 +6,7 @@ use App\Modules\Sales\Application\DTOs\QuickSaleSummary; use App\Modules\Sales\Application\UseCases\CloseCashDay; use App\Modules\Sales\Application\UseCases\CreditQuickSale; use App\Modules\Sales\Application\UseCases\ReopenCashDay; +use App\Modules\Sales\Application\UseCases\ResendQuickSaleReceipt; use App\Modules\Sales\Domain\Exceptions\CashDayClosed; use App\Modules\Sales\Domain\Exceptions\CashDayInFuture; use App\Modules\Sales\Domain\Exceptions\CashDayNotClosed; @@ -13,6 +14,7 @@ use App\Modules\Sales\Domain\Exceptions\CreditCannotBeCredited; use App\Modules\Sales\Domain\Exceptions\QuickSaleAlreadyCredited; use App\Modules\Sales\Domain\Exceptions\QuickSaleNotFound; use App\Modules\Sales\Presentation\Livewire\Concerns\FormatsSales; +use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress; use App\Modules\Users\Application\Contracts\Clock; use App\Modules\Users\Application\Contracts\UserAccountQueries; use App\Modules\Users\Application\DTOs\UserOption; @@ -27,7 +29,8 @@ use Livewire\Component; * A day's quick sales and its cash day (kassapäivä). Sellers see their own * sales, management everyone's. Anyone selling may close the day, which * forms its balance; management may reopen it. Sales are credited, never - * deleted. + * deleted. An emailed receipt's state is shown on its row, and a receipt + * can be emailed again, to a corrected address if need be. */ new class extends Component { @@ -52,6 +55,11 @@ new class extends Component #[Locked] public string $statusMessage = ''; + #[Locked] + public ?int $resendSaleId = null; + + public string $resendEmail = ''; + public function mount(Clock $clock): void { $this->authorize('sales.use'); @@ -155,6 +163,42 @@ new class extends Component $this->js("document.getElementById('credit-dialog').close(); document.getElementById('sales-status').focus()"); } + public function confirmResend(int $saleId): void + { + $sale = app(QuickSaleQueries::class)->findSale($saleId) ?? abort(404); + $this->authorize('sales.view-sale', $sale->sellerId); + + $this->resendSaleId = $saleId; + $this->resendEmail = $sale->receiptEmail ?? ''; + $this->resetErrorBag('resendEmail'); + $this->js("document.getElementById('resend-dialog').showModal()"); + } + + public function resend(ResendQuickSaleReceipt $resendQuickSaleReceipt): void + { + $sale = app(QuickSaleQueries::class)->findSale((int) $this->resendSaleId) ?? abort(404); + $this->authorize('sales.view-sale', $sale->sellerId); + + $this->validate( + ['resendEmail' => ['required', 'string', 'email', 'max:255']], + attributes: ['resendEmail' => __('sales.sell.receipt_email')], + ); + + try { + $resendQuickSaleReceipt->execute($sale->id, $this->resendEmail); + } catch (InvalidEmailAddress) { + $this->addError('resendEmail', __('sales.errors.receipt_email')); + + return; + } + + $this->statusMessage = __('sales.receipt_mail.resent', ['number' => $sale->id, 'email' => mb_strtolower(trim($this->resendEmail))]); + $this->resendSaleId = null; + $this->resendEmail = ''; + unset($this->sales); + $this->js("document.getElementById('resend-dialog').close(); document.getElementById('sales-status').focus()"); + } + public function confirmClose(): void { $this->authorize('sales.close-day'); @@ -425,6 +469,29 @@ new class extends Component