Apply percentage coupons in the cart summary
C# · ASP.NET Core · beginner · modification
Adds percentage coupons to the cart summary, so the checkout page can show the discount before payment. `CartEndpoints.cs` reads an optional `coupon` query parameter, looks it up with the existing `ICouponStore`, answers 422 for a code that is not active, and returns the new `DiscountCents` next to the subtotal and total. The discount maths lives in a small `CartPricing.DiscountCents` helper, rounded down to the whole cent, with unit tests in `CartPricingTests.cs`.
ASP.NET Core 10 on .NET 10, C# 14 with nullable reference types enabled, minimal APIs, xUnit for tests. `Program.cs` (unchanged) registers the cookie authentication scheme, `ICartStore` and `ICouponStore` and calls `app.MapCartEndpoints()`; `user.GetUserId()` (unchanged) returns the signed-in user's id. `ICartStore.GetForUserAsync` (existing, unchanged) returns the user's cart, an empty one if they have none: at most 100 lines, each with a `long` `UnitPriceCents` from 0 to 1,000,000 and an `int` `Quantity` from 1 to 99. `ICouponStore.FindActiveAsync` (existing, unchanged) matches the code case-insensitively and returns `null` for a code that is unknown, expired or used up; a returned `Coupon.PercentOff` is an `int` from 1 to 100 (a database check constraint). The checkout page reads `discountCents` and ships separately. Tests go in the existing `Shop.Api.Tests` xUnit project (template global usings, including `Xunit`).
Requirements
- `GET /api/cart/summary` (existing) accepts an optional `coupon` query parameter. When it names an active percentage coupon, the response's new `discountCents` is `percentOff` percent of `subtotalCents`, rounded down to the whole cent, and `totalCents` is `subtotalCents - discountCents`. For example a 10% coupon on a subtotal of 8,498 cents gives a discount of 849 and a total of 7,649.
- Without a coupon (parameter missing, empty or only spaces), `discountCents` is `0` and `totalCents` equals `subtotalCents`, as before.
- A coupon code that is not active (unknown, expired or used up) answers 422 with `{"error": "coupon_invalid"}`; surrounding spaces in the code are ignored.
- Unchanged: the endpoint requires a signed-in user (401 otherwise) and `subtotalCents` is the sum of each line's unit price times its quantity.
Files touched
- src/Shop.Api/Cart/CartEndpoints.cs
- src/Shop.Api/Cart/CartPricing.cs
- tests/Shop.Api.Tests/CartPricingTests.cs