Receipt email right after checkout

C# · ASP.NET Core · intermediate · modification

Customers get their receipt as soon as they check out, instead of from the hourly receipt job. `ReceiptService` (new, `Receipts/ReceiptService.cs`) sends the receipt for a freshly placed order through the existing `IEmailSender` and `ReceiptEmail.Build`, then records `ReceiptSentAt`; a failed send is logged as a warning and left to the hourly job. `CheckoutController` starts the receipt for the order it has just placed, passing `CancellationToken.None` so that a shopper closing the page does not cancel it, and answers 201 as before. `Program.cs` registers the service as scoped. `CheckoutReceiptTests.cs` (new) adds endpoint tests on the existing `ShopApiFactory`.

ASP.NET Core 10 Web API on .NET 10 (C# 14, nullable reference types enabled, implicit usings), controllers with `[ApiController]`, EF Core 10 with Npgsql. `ShopDbContext` is registered with `AddDbContext` (default scoped lifetime, no pooling). Existing and unchanged: `OrderPlacement` (scoped) turns the caller's cart into an order in one transaction and clears the cart, then returns the saved, tracked `Order` with its `Lines` and `CustomerEmail`, or `null` when the cart is empty, so a repeated checkout answers 409. `Order.ReceiptSentAt` is a `DateTimeOffset?` (`timestamptz`). `IEmailSender` is a typed `HttpClient` for the email provider's HTTP API, with a 5-second timeout. Its `SendAsync` returns once the provider has accepted the message, which usually takes 100 to 800 ms. It throws `EmailSendException` for every failure (rejected, unreachable, timed out), and `OperationCanceledException` only when its token is cancelled. `ReceiptEmail.Build(Order)` builds the receipt message. `ReceiptJob` is a hosted service that runs every hour: for each order placed more than an hour ago whose `ReceiptSentAt` is `null`, it sends the receipt and sets `ReceiptSentAt`. Until this PR it was the only sender. `TimeProvider.System` is registered as a singleton. `AddShopAuth` sets up the cookie sign-in and `User.GetCustomerId()`. `UseExceptionHandler` with `AddProblemDetails` answers any unhandled exception in a request with a generic 500 problem body and logs it, so a database error answers 500, as everywhere in the API. A receipt is sent at least once: a second copy after such a database error is accepted. Tests use xUnit and the existing `ShopApiFactory` (`WebApplicationFactory<Program>` over an in-memory SQLite database). It replaces the provider with `FakeEmailSender`, which answers at once, records each message in `Sent`, and throws `EmailSendException` on the next send after `FailNext()`. `SeedCartAsync(customerId, items...)` fills a cart, `CreateClientFor(customerId)` signs requests in as that customer, and `GetOrderAsync(id)` reads an order back from the database.

Requirements

Files touched

Review this PR

C# practice