Email quick sale receipts and send them again from the sales list

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-26 16:00:15 +02:00
co-authored by Claude Sonnet 5.5
parent 3faa4cfbc6
commit d160854b79
29 changed files with 679 additions and 34 deletions
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\Contracts;
/**
* Emails a quick sale's PDF receipt to the address stored on the sale, in
* the background: the sale is kept whatever happens, and the outcome is
* recorded on the sale for the sales list.
*/
interface ReceiptMailer
{
public function send(int $saleId): void;
}
@@ -11,6 +11,8 @@ use App\Modules\Sales\Domain\ValueObjects\VatTotal;
* A quick sale as listed: amounts with VAT, negative on a credit.
* $soldAt is "Y-m-d H:i" in the company's time zone. $creditsSaleId is set
* on a credit, $creditedBySaleId on a sale that has been credited.
* $receiptEmail is the address the receipt was emailed to; it is shown
* only on the sales list, never in reports.
*/
final readonly class QuickSaleSummary
{
@@ -28,8 +30,25 @@ final readonly class QuickSaleSummary
public array $lines,
public ?int $creditsSaleId,
public ?int $creditedBySaleId,
public ?string $receiptEmail = null,
public ?string $receiptSentAt = null,
public bool $receiptFailed = false,
) {}
/**
* The emailed receipt's state: null without an address, otherwise
* 'sent', 'failed' or 'pending' (still in the queue).
*/
public function receiptStatus(): ?string
{
return match (true) {
$this->receiptEmail === null => null,
$this->receiptFailed => 'failed',
$this->receiptSentAt !== null => 'sent',
default => 'pending',
};
}
public function isCredit(): bool
{
return $this->creditsSaleId !== null;
@@ -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,
) {}
}
@@ -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,
) {}
}
@@ -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();
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Application\UseCases;
use App\Modules\Sales\Application\Contracts\ReceiptMailer;
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
use App\Modules\Sales\Domain\Exceptions\QuickSaleNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Shared\Domain\ValueObjects\EmailAddress;
/**
* Emails a sale's receipt again, to the stored address or a corrected one,
* which replaces it on the sale. Who may do this is checked by the caller.
*/
final class ResendQuickSaleReceipt
{
public function __construct(
private QuickSaleRepository $sales,
private ReceiptMailer $mailer,
private TransactionManager $transactions,
) {}
/**
* @throws QuickSaleNotFound
* @throws InvalidEmailAddress
*/
public function execute(int $saleId, string $email): void
{
$address = new EmailAddress($email);
$this->transactions->run(function () use ($saleId, $address): void {
$this->sales->findById($saleId) ?? throw new QuickSaleNotFound($saleId);
$this->sales->changeReceiptEmail($saleId, $address);
});
$this->mailer->send($saleId);
}
}
@@ -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;
}
}
@@ -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<QuickSale>
*/
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;
}
@@ -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<QuickSaleLine> $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;
}
}
@@ -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',
];
}
}
@@ -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();
}
@@ -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),
);
}
}
@@ -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
@@ -0,0 +1,17 @@
<?php
namespace App\Modules\Sales\Infrastructure\Receipts;
use App\Modules\Sales\Application\Contracts\ReceiptMailer;
/**
* Sends receipts through the queue, after the surrounding transaction (if
* any) has committed.
*/
class QueuedReceiptMailer implements ReceiptMailer
{
public function send(int $saleId): void
{
SendQuickSaleReceipt::dispatch($saleId)->afterCommit();
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Modules\Sales\Infrastructure\Receipts;
use App\Modules\Sales\Application\DTOs\QuickSaleSummary;
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
/**
* The email with a quick sale's PDF receipt attached. Always in Finnish,
* like the receipt itself.
*/
class QuickSaleReceiptMail extends Mailable
{
public function __construct(public QuickSaleSummary $sale)
{
$this->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<Attachment>
*/
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'),
];
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Modules\Sales\Infrastructure\Receipts;
use App\Modules\Sales\Application\DTOs\QuickSaleSummary;
use App\Modules\Shared\Application\UseCases\CompanyDetailsStore;
use Barryvdh\DomPDF\Facade\Pdf;
use Barryvdh\DomPDF\PDF as DomPdf;
/**
* Renders a quick sale's A5 PDF receipt, both for the browser and as an
* email attachment.
*/
class ReceiptPdf
{
public function __construct(private CompanyDetailsStore $company) {}
public function render(QuickSaleSummary $sale): DomPdf
{
return Pdf::loadView('sales-views::receipt', [
'sale' => $sale,
'company' => $this->company->get(),
])
->setPaper('a5')
->setOption('isFontSubsettingEnabled', true);
}
public function fileName(QuickSaleSummary $sale): string
{
return __('sales.receipt.file', ['number' => $sale->id]);
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Modules\Sales\Infrastructure\Receipts;
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Sends a quick sale's receipt to the address stored on the sale and
* records the outcome. Retried a few times; when it finally fails, the
* sales list shows it so the seller can send it again.
*/
class SendQuickSaleReceipt implements ShouldQueue
{
use Queueable;
public int $tries = 3;
/** @var list<int> */
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());
}
}
@@ -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));
}
}
@@ -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
<x-icon name="document-text" class="size-4" aria-hidden="true" />
{{ __('sales.receipt_link') }}
</a>
@if ($sale->receiptStatus() !== null)
<span class="mr-2 inline-flex items-center gap-1 text-xs">
@if ($sale->receiptStatus() === 'failed')
<x-icon name="exclamation-triangle" class="size-4 text-red-700 dark:text-red-400" aria-hidden="true" />
@elseif ($sale->receiptStatus() === 'sent')
<x-icon name="envelope" class="size-4" aria-hidden="true" />
@else
<x-icon name="clock" class="size-4" aria-hidden="true" />
@endif
{{ __('sales.receipt_mail.status_'.$sale->receiptStatus()) }}
</span>
@endif
@can('sales.view-sale', $sale->sellerId)
<x-button
wire:click="confirmResend({{ $sale->id }})"
subtle
color="black"
sm
icon="envelope"
:text="__('sales.receipt_mail.send')"
:aria-label="__('sales.receipt_mail.send_named', ['number' => $sale->id])"
/>
@endcan
@if ($sale->canBeCredited())
@can('sales.credit', $sale->sellerId)
<x-button
@@ -454,6 +521,17 @@ new class extends Component
</x-slot:actions>
</x-confirm-dialog>
<x-confirm-dialog id="resend-dialog" :title="__('sales.receipt_mail.send_title')">
@if ($resendSaleId !== null)
<p class="mb-3">{{ __('sales.receipt_mail.send_text', ['number' => $resendSaleId]) }}</p>
@endif
<x-input id="resend-email" wire:model="resendEmail" type="email" inputmode="email" autocomplete="off" :label="__('sales.sell.receipt_email')" />
<x-slot:actions>
<x-button wire:click="resend" icon="envelope" :text="__('sales.receipt_mail.send_confirm')" />
</x-slot:actions>
</x-confirm-dialog>
<x-confirm-dialog id="close-dialog" :title="__('sales.cash_day.close_title')">
<p>{{ __('sales.cash_day.close_text') }}</p>
<p class="mt-2 font-medium">
@@ -14,6 +14,7 @@ use App\Modules\Sales\Domain\Exceptions\QuickSaleCustomerNotFound;
use App\Modules\Sales\Domain\Exceptions\QuickSaleEmpty;
use App\Modules\Sales\Domain\ValueObjects\QuickSaleLine;
use App\Modules\Sales\Presentation\Livewire\Concerns\FormatsSales;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
@@ -22,8 +23,8 @@ use Livewire\Component;
/**
* A quick sale at the counter (pikamyynti), made for phones: each press of
* a product button adds one to the sale's list, where quantities can be
* lowered, raised or removed; then the payment method and an optional
* customer. After saving, the form empties for the next customer and the
* lowered, raised or removed; then the payment method, an optional
* customer and an optional address the PDF receipt is emailed to. After saving, the form empties for the next customer and the
* result is announced with a link to the PDF receipt. Prices are consumer
* prices with VAT, which everyone may see.
*/
@@ -44,6 +45,8 @@ new class extends Component
public string $customerSearch = '';
public string $receiptEmail = '';
#[Locked]
public ?int $customerId = null;
@@ -204,6 +207,11 @@ new class extends Component
$this->customerId = $customer->id;
$this->customerName = $customer->name;
$this->customerSearch = '';
if (trim($this->receiptEmail) === '') {
$this->receiptEmail = $this->customerEmail($customer->id) ?? '';
}
$this->js("document.getElementById('change-customer')?.focus()");
}
}
@@ -222,10 +230,13 @@ new class extends Component
$this->hoursMessage = '';
$this->savedSaleId = null;
$this->validate(['paymentMethod' => ['required', Rule::enum(PaymentMethod::class)]]);
$this->validate([
'paymentMethod' => ['required', Rule::enum(PaymentMethod::class)],
'receiptEmail' => ['nullable', 'string', 'email', 'max:255'],
], attributes: ['receiptEmail' => __('sales.sell.receipt_email')]);
try {
$result = $sellQuickSale->execute((int) auth()->id(), new SaleData($this->quantities, $this->paymentMethod, $this->customerId));
$result = $sellQuickSale->execute((int) auth()->id(), new SaleData($this->quantities, $this->paymentMethod, $this->customerId, trim($this->receiptEmail) === '' ? null : $this->receiptEmail));
} catch (QuickSaleEmpty) {
$this->addError('quantities', __('sales.errors.empty'));
@@ -248,6 +259,10 @@ new class extends Component
} catch (CashDayClosed) {
$this->addError('sale', __('sales.errors.day_closed'));
return;
} catch (InvalidEmailAddress) {
$this->addError('receiptEmail', __('sales.errors.receipt_email'));
return;
}
@@ -258,12 +273,16 @@ new class extends Component
'method' => __('sales.payment_methods.'.$this->paymentMethod),
]);
if ($result->receiptEmail !== null) {
$this->savedMessage .= ' '.__('sales.sell.receipt_queued', ['email' => $result->receiptEmail]);
}
$this->hoursMessage = trim(
($result->bookedQuarters > 0 ? __('sales.sell.hours_booked', ['hours' => $this->hours($result->bookedQuarters)]) : '')
.' '.($result->unbookedQuarters > 0 ? __('sales.sell.hours_not_booked', ['hours' => $this->hours($result->unbookedQuarters)]) : ''),
);
$this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage');
$this->reset('quantities', 'paymentMethod', 'customerSearch', 'customerId', 'customerName', 'cartMessage', 'receiptEmail');
$this->forgetLines();
$this->js("document.getElementById('sale-saved')?.focus()");
@@ -295,6 +314,21 @@ new class extends Component
$this->js("const field = document.getElementById('quantity-{$productId}'); if (field) { field.value = '{$quantity}'; }");
}
/**
* The first email address among the customer's contacts, to prefill
* the receipt address.
*/
private function customerEmail(int $customerId): ?string
{
foreach (app(CustomerQueries::class)->contactsOf($customerId) as $contact) {
if ($contact->email !== null && $contact->email !== '') {
return $contact->email;
}
}
return null;
}
private function forgetLines(): void
{
unset($this->lines, $this->totalCents);
@@ -482,6 +516,15 @@ new class extends Component
@endif
</div>
<x-input
wire:model="receiptEmail"
type="email"
inputmode="email"
autocomplete="off"
:label="__('sales.sell.receipt_email')"
:hint="__('sales.sell.receipt_email_hint')"
/>
<x-button submit lg class="w-full" :text="__('sales.sell.save')" />
</form>
@endif
@@ -0,0 +1,23 @@
{{--
Body of the email that carries a quick sale's PDF receipt. Always in
Finnish, like the receipt.
--}}
<!DOCTYPE html>
<html lang="fi">
<head>
<meta charset="utf-8">
<title>{{ $sale->isCredit() ? __('sales.receipt.credit_title') : __('sales.receipt.title') }} {{ $sale->id }}</title>
</head>
<body style="font-family: Arial, sans-serif; font-size: 15px; color: #111;">
<p>{{ __('sales.receipt_mail.greeting') }}</p>
<p>{{ __($sale->isCredit() ? 'sales.receipt_mail.credit_body' : 'sales.receipt_mail.body', ['number' => $sale->id, 'date' => \Carbon\CarbonImmutable::parse($sale->soldAt)->format('j.n.Y')]) }}</p>
<p>{{ __('sales.receipt.thanks') }}</p>
@if ($company !== null)
<p>
{{ $company->name }}
@if ($company->phone !== null)<br>{{ $company->phone }}@endif
@if ($company->email !== null)<br>{{ $company->email }}@endif
</p>
@endif
</body>
</html>